title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
Codeigniter displaying total added likes from mysql table
|
<p>I am using MVC in codeigniter and I have a MySql table that has pages made by users <strong>page_id</strong> and topics <strong>topic_number</strong> as shown in the image below (Table page). pages can have multiple <strong>topic numbers</strong>.</p>
<p>I also have another table called <strong>table page likes</strong> (shown in the image below also). This table also has <strong>page_id</strong> and <strong>topic_number</strong> but it has two more fields, which are, <strong>like</strong> and <strong>user_who_liked_topic_number</strong>.</p>
<p><a href="https://i.stack.imgur.com/z4eEk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z4eEk.png" alt="enter image description here"></a></p>
<p>My problem is that, I would like to display all the topic numbers that have or dont have likes. But if I only fetch topic numbers from the <strong>Table_page_likes</strong>, I will not get topic_numbers that dont have any likes recorded. which is why I am using both tables.</p>
<p>The first table is fetched from the database where all the Topic_number is printed out. Then each Topic_number is searched in the <strong>table_pages_like</strong> to find if it has any like records and display it next to the Page_id and topic_number.</p>
<p>This is my code so far, but I am not sure how to do the second step, which is to fetch each page_id with any number of likes from the table <strong>table_page_likes</strong> </p>
<p><strong>controller_page.php</strong></p>
<pre><code> function viewdata() {
$data['pages'] = $this->model_page->get_pages();
$this->load->view('view_page', $data);
}
function get_like($post_id, $topic_number) {
$data['liked_pages'] = $this->model_page->get_likes_model($post_id, topic_number);
$this->load->view('view_page', $data);
}
</code></pre>
<p><strong>model_page.php</strong></p>
<pre><code> function get_pages() {
$query = $this->db->get_where('table_pages');
return $query->result_array();
}
function get_likes($page_id, $topic_number) {
$query = $this->db->get_where('table_pages_likes', array('page_id' => $page_id , 'topic_number' => $topic_number));
}
</code></pre>
<p><strong>view_page.php</strong></p>
<pre><code> <?php foreach($pages as $value): ?>
<tr>
<td><?php echo $value['page_id']; ?></td>
<td><?php echo $value['topic_number']; ?></td>
<?php foreach($liked_pages as $value): ?>
<td><?php echo $value['page_id']; ?></td>
<td><?php echo $value['topic_number']; ?></td>
<td><?php echo $value['like']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</code></pre>
<p>Thanks in advance</p>
| 3 | 1,200 |
Video camera crashes after latest(4.4.2) Samsung/OS update
|
<p>I am using custom camera in my application this works fine in jelly bean. Now after this Samsung Galaxy Tab OS update the custom camera is broken. I got this report from one of my friend i didn't saw that tablet. And i got crash report form <code>Carshylytics</code>. </p>
<p>My log report:</p>
<pre><code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.x.y/com.x.y.tools.EnregistrementVideoStackActivity}: java.lang.RuntimeException: Unable to initialize media recorder
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2053)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
at android.app.ActivityThread.access$700(ActivityThread.java:146)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4949)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.RuntimeException: Unable to initialize media recorder
at android.media.MediaRecorder.native_setup(MediaRecorder.java)
at android.media.MediaRecorder.<init>(MediaRecorder.java:121)
at com.x.y.tools.EnregistrementVideoStackActivity.<init>(EnregistrementVideoStackActivity.java:38)
at java.lang.Class.newInstanceImpl(Class.java)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2044)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
at android.app.ActivityThread.access$700(ActivityThread.java:146)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4949)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
at dalvik.system.NativeStart.main(NativeStart.java)
</code></pre>
<p>And this error line is </p>
<pre><code>public MediaRecorder mrec = new MediaRecorder();
</code></pre>
<p>Why it is happen have any idea? How can i solve this issue. I hope the camera code is not needed. But anyone want to see the code i can post here.</p>
<p><strong>EDIT:</strong></p>
<p>My EnregistrementVideoStackActivity class:</p>
<pre><code> public class EnregistrementVideoStackActivity extends Activity implements
SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
private Button stopRecording = null;
File video;
private Camera mCamera;
private String output_path;
boolean isActivityRestarting = false;
Chronometer myChronometer;
Boolean recording = false;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (recording == false) {
finish();
} else {
stopRecording();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onRestart() {
super.onRestart();
isActivityRestarting = true;
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (isActivityRestarting) {
return;
}
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
/*getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);*/
setContentView(R.layout.camera_surface);
Intent intent = getIntent();
output_path = intent.getStringExtra("path");
startRecording = (Button) findViewById(R.id.buttonstart);
stopRecording = (Button) findViewById(R.id.buttonstop);
try {
// This case can actually happen if the user opens and closes the
// camera too frequently.
// The problem is that we cannot really prevent this from happening
// as the user can easily
// get into a chain of activites and tries to escape using the back
// button.
// The most sensible solution would be to quit the entire EPostcard
// flow once the picture is sent.
mCamera = Camera.open();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Please restart device, camera error", Toast.LENGTH_LONG)
.show();
finish();
return;
}
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
myChronometer = (Chronometer) findViewById(R.id.chronometer1);
startRecording.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
startRecording();
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.start();
startRecording.setClickable(false);
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
mrec.release();
}
}
});
stopRecording.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
stopRecording();
myChronometer.stop();
Intent intent = getIntent();
intent.putExtra("gallery", "viewed");
setResult(RESULT_OK, intent);
} catch (Exception e) {
e.getMessage();
}
}
});
myChronometer
.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
public void onChronometerTick(Chronometer chronometer) {
long myElapsedMillis = SystemClock.elapsedRealtime()
- myChronometer.getBase();
if (myElapsedMillis >= 120000) {
Toast.makeText(getApplicationContext(),
"Maximum Video limit reached",
Toast.LENGTH_LONG).show();
stopRecording();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
try {
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.e(null, "Problem Start" + message);
mrec.release();
}
break;
case 1: // GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException {
recording = true;
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mrec.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
int width = 320;
int height = 240;
try {
// Check what resolutions are supported by your camera
List<Size> sizes = params.getSupportedPictureSizes();
for (Size size : sizes) {
Log.e("TAG", "Available resolution: " + size.width + " "
+ size.height);
width = size.width;
height = size.height;
}
} catch (Exception e) {
e.printStackTrace();
}
mrec.setVideoFrameRate(30);
mrec.setVideoSize(width, height);
mrec.setVideoEncodingBitRate(1700000);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile(output_path);
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
try {
Log.e("stop recording", "Stop recording");
recording = false;
mrec.stop();
mrec.release();
mCamera.release();
// go out
Toast.makeText(getApplicationContext(),
"New Video Observation Saved", Toast.LENGTH_LONG).show();
} catch (Exception npe) {
npe.printStackTrace();
}
Intent intent = getIntent();
setResult(RESULT_OK, intent);
finish();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
//
}
Parameters params;
public void surfaceCreated(SurfaceHolder holder) {
if (!isActivityRestarting) {
if (mCamera != null) {
params = mCamera.getParameters();
mCamera.setParameters(params);
} else {
Toast.makeText(getApplicationContext(),
"Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera.setPreviewCallback(null);
mCamera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if (recording == false) {
finish();
} else {
stopRecording();
}
}
}
</code></pre>
| 3 | 5,291 |
check if route is valid react router
|
<p>I am using react router v5 and would like to check my routes to make sure they are valid as my 404 page is not triggering when an invalid link is shown presumably because the route still matches even though there is no item to display on the route as it's invalid. e.g <code>example.com/cat1/product1</code> being valid and <code>example.com/cat1/produc1</code> being invalid.</p>
<p>The same for the categories <code>example.com/cat1</code> being valid and <code>example.com/ca1</code> being invalid.</p>
<p>Currently it just shows no content for the invalid link instead of my <code>NotFound</code> component.</p>
<p>How can I check each link to see if it is valid and if not display my <code>NotFound</code> component?</p>
<pre><code> <Switch>
<Route exact path="/">
<Home categories={categories} products={products} />
</Route>
<Route exact path="/product-categories">
<Products categories={categories} />
</Route>
<Route exact path="/delivery">
<Delivery categories={categories} />
</Route>
<Route exact path="/terms">
<Terms categories={categories} />
</Route>
<Route exact path="/privacy">
<Privacy categories={categories} />
</Route>
<Route exact path="/returns">
<Returns categories={categories} />
</Route>
<Route exact path="/about">
<About categories={categories} />
</Route>
<Route path="/sitemap.xml" onEnter={reload}/>
<Route path="/robots.txt" onEnter={reload}/>
<Route exact path="/:catSlug">
<ProductsList categories={categories} products={products} userCountry={userCountry}/>
</Route>
<Route exact path="/:catSlug/:productSlug">
<Product alertIsVisble={() => dispatch(allActions.showAlert())} categories={categories} products={products} userCountry={userCountry} />
</Route>
<Route>
<NotFound categories={categories} />
</Route>
</Switch>
</code></pre>
| 3 | 1,172 |
How to close Flume with kafka as Source
|
<p>I'm upgrading Flume1.7 to 1.9.I have 5 Kafka sources and 7 aws-s3's sinks in FLume's conf.
Firstly I need stop Flume 1.7.So I execute the command
'kill <code>ps -ef |grep flume |grep bidinfo | awk '{print $2}'</code>' to stop the bidinfo task,but this process still exists.22 hours later ,this process always alive until now. What else can I do without this command 'kill -9 xxxx'.Welcome to suggest!!!</p>
<p>This server has been running for 60 days with Flume 1.7,kafka ,I've tried to execute the command 'kill -3 xxxx',However, only two sources and two sinks have been stopped and the others have been running.
I read the source code of flume-kafkaSource and observed flume's log.
It is possible that two methods(Consumer. wakeup ();Consumer. close ();) are not completed.</p>
<pre><code>#flume-conf
ag.sources = src_1 src_2 src_3 src_4 src_5
ag.channels = ch
ag.sinks = sk_1 sk_2 sk_3 sk_4 sk_5 sk_6 sk_7
#source:kafka
ag.sources.src_1.type = org.apache.flume.source.kafka.KafkaSource
ag.sources.src_1.kafka.bootstrap.servers = xxxx
ag.sources.src_1.kafka.consumer.group.id = flume.xxxxx
ag.sources.src_1.kafka.consumer.retry.backoff.ms = 10000
ag.sources.src_1.batchSize = 5000
ag.sources.src_1.batchDurationMillis = 2000
ag.sources.src_1.kafka.topics = xxxx
ag.sources.src_1.interceptors = i1
ag.sources.src_1.interceptors.i1.type = xxxx.interceptor
ag.sources.src_1.channels = ch
#sink:aws S3
ag.sinks.sk_1.type = hdfs
ag.sinks.sk_1.hdfs.path = s3a://xxxxxxx
ag.sinks.sk_1.hdfs.filePrefix = %{minute}
ag.sinks.sk_1.hdfs.fileSuffix = .xxx.1.lzo
ag.sinks.sk_1.hdfs.rollSize = 0
ag.sinks.sk_1.hdfs.rollCount = 0
ag.sinks.sk_1.hdfs.rollInterval = 0
ag.sinks.sk_1.hdfs.idleTimeout = 180
ag.sinks.sk_1.hdfs.callTimeout = 600000
ag.sinks.sk_1.hdfs.closeTries = 5
ag.sinks.sk_1.hdfs.retryInterval = 60
ag.sinks.sk_1.hdfs.batchSize = 3000
ag.sinks.sk_1.hdfs.codeC = lzop
ag.sinks.sk_1.hdfs.fileType = CompressedStream
ag.sinks.sk_1.hdfs.writeFormat = Text
ag.sinks.sk_1.channel = ch
#channels
ag.channels.ch.type = memory
ag.channels.ch.capacity = 2000000
ag.channels.ch.transactionCapacity = 100000
</code></pre>
<h1>Error Message</h1>
<pre><code>09 Sep 2019 11:14:18,010 ERROR [PollableSourceRunner-KafkaSource-src_2] (org.apache.flume.source.kafka.KafkaSource.doProcess:314) - KafkaSource EXCEPTION, {}
org.apache.flume.ChannelException: java.lang.InterruptedException
at org.apache.flume.channel.BasicTransactionSemantics.commit(BasicTransactionSemantics.java:154)
at org.apache.flume.channel.ChannelProcessor.processEventBatch(ChannelProcessor.java:194)
at org.apache.flume.source.kafka.KafkaSource.doProcess(KafkaSource.java:295)
at org.apache.flume.source.AbstractPollableSource.process(AbstractPollableSource.java:60)
at org.apache.flume.source.PollableSourceRunner$PollingRunner.run(PollableSourceRunner.java:133)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1326)
at java.util.concurrent.Semaphore.tryAcquire(Semaphore.java:582)
at org.apache.flume.channel.MemoryChannel$MemoryTransaction.doCommit(MemoryChannel.java:119)
at org.apache.flume.channel.BasicTransactionSemantics.commit(BasicTransactionSemantics.java:151)
... 5 more
#this place I think is the main problem
09 Sep 2019 11:14:18,011 INFO [PollableSourceRunner-KafkaSource-src_2] (org.apache.flume.source.PollableSourceRunner$PollingRunner.run:143) - Source runner interrupted. Exiting
09 Sep 2019 11:14:18,011 INFO [agent-shutdown-hook] (org.apache.kafka.clients.consumer.internals.AbstractCoordinator$2.onFailure:571) - LeaveGroup request failed with error
org.apache.kafka.clients.consumer.internals.SendFailedException
#-------------
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:149) - Component type: SOURCE, name: src_2 stopped
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:155) - Shutdown Metric for type: SOURCE, name: src_2. source.start.time == 1567911973591
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:161) - Shutdown Metric for type: SOURCE, name: src_2. source.stop.time == 1567998858018
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. source.kafka.commit.time == 2470886
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. source.kafka.empty.count == 0
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. source.kafka.event.get.time == 78823378
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.append-batch.accepted == 0
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.append-batch.received == 0
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.append.accepted == 0
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.append.received == 0
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.events.accepted == 767319160
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.events.received == 767366357
09 Sep 2019 11:14:18,018 INFO [agent-shutdown-hook] (org.apache.flume.instrumentation.MonitoredCounterGroup.stop:177) - Shutdown Metric for type: SOURCE, name: src_2. src.open-connection.count == 0
</code></pre>
| 3 | 2,408 |
How to group ID in while loop (for php json_encode)
|
<p>I have a problem for several days to create a Json array with MySQL data</p>
<p>Here are my MySQL data:</p>
<pre><code>zi zn vn pioo pio ve station es eo
1 Zone 1 Value 01 1 199 0 1 1 0
1 Zone 1 Value 02 54 637 0 3 0 0
1 Zone 1 Value 03 55 637 1 3 0 0
2 Zone 2 Value 01 1 199 0 1 1 0
2 Zone 2 Value 03 55 637 1 3 0 0
2 Zone 2 Value 04 56 642 0 3 0 0
3 Zone 3 Value 01 1 199 0 1 1 0
3 Zone 3 Value 05 57 647 1 3 0 0
4 Zone 4 Value 05 57 647 1 3 0 0
5 Zone Test Value 02 54 637 0 3 0 0
5 Zone Test Value 03 55 637 1 3 0 0
</code></pre>
<p>Here is my PHP code:</p>
<p>My query is $query and my SQL connexion is $con</p>
<pre><code>$result = array();
$json_response = array();
$response = array();
if($stmt = $con->prepare($query)){
$stmt->execute();
$stmt->bind_result($zoneId,$zoneName,$vanneName,$piooId,$pioId,$vanne_etat,$station,$etat_station,$etat_ordre);
while($stmt->fetch()){
$json_response = [
'zi' => $zoneId,
'zn' => $zoneName,
$vanneName => [],
];
$json_response[$vanneName][] = [
'pioo' => $piooId,
'pio' => $pioId,
've' => $vanne_etat,
'es' => $etat_station,
'eo' => $etat_ordre,
];
$data = [];
foreach ($json_response as $element) {
$data[] = $element;
}
$result[]=$json_response;
}
$stmt->close();
$online = mysqli_fetch_array(mysqli_query($con, "SELECT CASE WHEN TIMESTAMP > DATE_SUB(NOW(), INTERVAL 5 MINUTE) THEN 1 ELSE 0 END AS online FROM relevés_instantanés ORDER BY ID DESC LIMIT 1")) ['online'];
$response["online"] = $online;
$response["success"] = 1;
$response["data"] = $result;
}else{
//Errors
$response["success"] = 0;
$response["message"] = mysqli_error($con);
}
mysqli_close($con);
echo json_encode($response);
</code></pre>
<p>Output Json like that : </p>
<pre><code>{
"online":"1",
"success":1,
"data":[
{
"zi":1,
"zn":"Zone 1",
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
},
{
"zi":1,
"zn":"Zone 1",
"Value 02":[
{
"pioo":54,
"pio":637,
"ve":0,
"es":0,
"eo":0
}
]
},
{
"zi":1,
"zn":"Zone 1",
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":2,
"zn":"Zone 2",
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
},
{
"zi":2,
"zn":"Zone 2",
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":2,
"zn":"Zone 2",
"Value 04":[
{
"pioo":56,
"pio":642,
"ve":0,
"es":0,
"eo":0
}
]
},
{
"zi":3,
"zn":"Zone 3",
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
},
{
"zi":3,
"zn":"Zone 3",
"Value 05":[
{
"pioo":57,
"pio":647,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":4,
"zn":"Zone 4",
"Value 05":[
{
"pioo":57,
"pio":642,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":5,
"zn":"Zone Test",
"Value 02":[
{
"pioo":54,
"pio":637,
"ve":0,
"es":0,
"eo":0
}
]
},
{
"zi":5,
"zn":"Zone Test",
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
}
]
}
</code></pre>
<p>But I expect an ouput like that : (I am not sure of the syntax, but it is for you to understand my wish.)</p>
<pre><code>{
"online":"1",
"success":1,
"data":[
{
"zi":1,
"zn":"Zone 1"{
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
"Value 02":[
{
"pioo":54,
"pio":637,
"ve":0,
"es":0,
"eo":0
}
]
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":2,
"zn":"Zone 2"{
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
"Value 04":[
{
"pioo":56,
"pio":642,
"ve":0,
"es":0,
"eo":0
}
]
},
{
"zi":3,
"zn":"Zone 3"{
"Value 01":[
{
"pioo":1,
"pio":199,
"ve":0,
"es":1,
"eo":0
}
]
"Value 05":[
{
"pioo":57,
"pio":647,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":4,
"zn":"Zone 4"{
"Value 05":[
{
"pioo":57,
"pio":642,
"ve":1,
"es":0,
"eo":0
}
]
},
{
"zi":5,
"zn":"Zone Test"{
"Value 02":[
{
"pioo":54,
"pio":637,
"ve":0,
"es":0,
"eo":0
}
]
"Value 03":[
{
"pioo":55,
"pio":637,
"ve":1,
"es":0,
"eo":0
}
]
}
]
}
</code></pre>
<p>I can not isolate each id of Zones to correctly build my JSON ....</p>
<p>Is it possible to use each ID once in the while loop?</p>
<p>any help appreciated</p>
<p>Sorry for my bad english .. :S</p>
<p>Joel</p>
| 3 | 5,928 |
Webview JavaScript loads inconsistantly
|
<p>I'm working on an app that takes a webpage and injects JavaScript to format the website for mobile. The code works fine on both my Nexus 5 and Nexus 7. However on my Moto G and LG G2 it does not inject consistently. Sometimes the pages load correctly with the JavaScript changing the look of the website. Other times the page is loaded without any changes being made. I have been looking for over a week for the cause of this but have found nothing. The code I am using is below.</p>
<p>This is a sample fragment.</p>
<pre><code>public class Summary extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@SuppressLint("SetJavaScriptEnabled")
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View myFragmentView = inflater.inflate(R.layout.summary, container, false);
final ProgressDialog pd = ProgressDialog.show(getActivity(), "FRC Manual", "Loading");
final WebView webView = (WebView) myFragmentView.findViewById(R.id.webview1);
String url = "http://google.com";
Functions.webViewSettings(webView);
Functions.zoom(webView);
Functions.cache(webView, getActivity());
webView.setWebViewClient(new MyWebViewClient() {
boolean loadingFinished = true;
boolean redirect = false;
@Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(urlNewString);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap facicon) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
@Override
public void onPageFinished(WebView view, String url)
{
if(!redirect) {
loadingFinished = true;
Functions.javascript(webView, url);
Functions.javascript(webView, url);
Functions.javascript(webView, url);
pd.dismiss();
}
if(loadingFinished && !redirect) {
Functions.javascript(webView, url);
Functions.javascript(webView, url);
Functions.javascript(webView, url);
pd.dismiss();
}
else {
redirect = false;
Functions.javascript(webView, url);
Functions.javascript(webView, url);
Functions.javascript(webView, url);
pd.dismiss();
}
super.onPageFinished(webView, url);
}
});
webView.loadUrl(url);
return myFragmentView;
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
</code></pre>
<p>This is the class that handles all the webview settings</p>
<pre><code> public class Functions {
public static void javascript(WebView view, String url) {
view.loadUrl("javascript:var con = document.getElementById('header_container'); "
+ "con.style.display = 'none'; javascript:var con = document.getElementById('footer'); "
+ "con.style.display = 'none'; javascript:var con = document.getElementsByClassName('ChapterTools RightPos')[0].style.visibility='hidden';"
+ "javascript:var con = document.getElementsByClassName('showhide_button1')[0].style.visibility='hidden';"
+ "javascript:var con = document.getElementsByClassName('colmid')[0].style.right='100%'; "
+ "javascript:var con = document.getElementsByClassName('colleft')[0].style.right='initial'; "
+ "javascript:var con = document.getElementsByClassName('col1')[0].style.width='98%'; "
+ "javascript:var con = document.getElementsByClassName('col1')[0].style.top='-50px'; "
+ "javascript:var con = document.getElementsByClassName('colmask threecol')[0].style.right='2%'; "
+ "javascript:var con = document.getElementsByClassName('colmask threecol')[0].style.width=''; "
+ "javascript:var img = document.getElementsByTagName('img'); for (var i = 0; i < img.length; ++i) {img[i].style.maxWidth='100%';} "
+ "javascript:var img = document.getElementsByTagName('img'); for (var i = 0; i < img.length; ++i) {img[i].style.height='';} "
+ "javascript:var img = document.getElementsByTagName('table'); for (var i = 0; i < img.length; ++i) {img[i].style.width='';} ");
}
public static void zoom(WebView view) {
if (MainActivity.getEnableZoom()==true)view.getSettings().setBuiltInZoomControls(true);
else view.getSettings().setBuiltInZoomControls(false);
}
public static void cache(WebView view, Activity test) {
if (!isNetworkAvailable(test))view.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ONLY );
else {
if(MainActivity.getUpdateCache()==true)view.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
else {
if(MainActivity.getEnableCache()==true)view.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ONLY );
else view.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
}
}
}
@SuppressWarnings("deprecation")
@SuppressLint({ "SetJavaScriptEnabled", "SdCardPath" })
public static void webViewSettings(WebView view) {
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.setVerticalScrollBarEnabled(false);
view.setHorizontalScrollBarEnabled(false);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setRenderPriority(RenderPriority.HIGH);
view.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
view.getSettings().setAppCachePath("/data/data/de.app/cache");
view.getSettings().setAllowFileAccess( true );
view.getSettings().setAppCacheEnabled( false );
}
public static boolean isNetworkAvailable(Activity test) {
ConnectivityManager connectivityManager = (ConnectivityManager) test.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
</code></pre>
| 3 | 3,126 |
Select from 3 tables (one to many, many to one relationship)
|
<p>I have 3 tables:
Recipes (1 --- * ) Ingridients ( *---1) Products. I need to obtain Recipes that contains products in a given list or products that are not in list but have a specific flag set. I have a flag in product table (bool). So where clause looks like:</p>
<pre><code>WHERE Product.Caption IN ('A', 'B', 'C') OR (Product.Caption NOT IN ('A', 'B', 'C') AND Product.Flag=TRUE)
</code></pre>
<p>Important is: I do not need recipes that contain products in list and also contain other products (not in list and flag is false).</p>
<p>Bellow is an example database dump for MSSQL:</p>
<pre><code>USE [master]
IF EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = N'movedb') ALTER DATABASE [movedb] SET SINGLE_USER With ROLLBACK IMMEDIATE
IF EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = N'movedb') DROP DATABASE [movedb]
IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = N'movedb') CREATE DATABASE [movedb]
USE [movedb]
--
-- Table structure for table 'Ingridients'
--
IF object_id(N'Ingridients', 'U') IS NOT NULL DROP TABLE [Ingridients]
CREATE TABLE [Ingridients] (
[Id] INT NOT NULL IDENTITY,
[Quantity] INT DEFAULT 0,
[IdProduct] INT DEFAULT 0,
[IdRecipe] INT DEFAULT 0,
PRIMARY KEY ([Id])
)
SET IDENTITY_INSERT [Ingridients] ON
GO
--
-- Dumping data for table 'Ingridients'
--
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (1, 0, 1, 2)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (2, 0, 3, 2)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (3, 0, 4, 2)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (4, 0, 6, 2)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (5, 0, 2, 3)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (6, 0, 4, 3)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (7, 0, 8, 3)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (8, 0, 1, 4)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (9, 0, 6, 4)
INSERT INTO [Ingridients] ([Id], [Quantity], [IdProduct], [IdRecipe]) VALUES (10, 0, 5, 4)
-- 10 records
SET IDENTITY_INSERT [Ingridients] OFF
GO
--
-- Table structure for table 'Products'
--
IF object_id(N'Products', 'U') IS NOT NULL DROP TABLE [Products]
CREATE TABLE [Products] (
[Id] INT NOT NULL IDENTITY,
[Caption] NVARCHAR(255),
[EasyToFind] BIT DEFAULT 0,
PRIMARY KEY ([Id])
)
SET IDENTITY_INSERT [Products] ON
GO
--
-- Dumping data for table 'Products'
--
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (1, N'ProductA', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (2, N'ProductB', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (3, N'ProductC', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (4, N'ProductD', -1)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (5, N'ProductE', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (6, N'ProductF', -1)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (7, N'ProductG', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (8, N'ProductH', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (9, N'ProductI', 0)
INSERT INTO [Products] ([Id], [Caption], [EasyToFind]) VALUES (10, N'ProductJ', 0)
-- 10 records
SET IDENTITY_INSERT [Products] OFF
GO
--
-- Table structure for table 'Recipes'
--
IF object_id(N'Recipes', 'U') IS NOT NULL DROP TABLE [Recipes]
CREATE TABLE [Recipes] (
[Id] INT NOT NULL IDENTITY,
[Caption] NVARCHAR(255),
PRIMARY KEY ([Id])
)
SET IDENTITY_INSERT [Recipes] ON
GO
--
-- Dumping data for table 'Recipes'
--
INSERT INTO [Recipes] ([Id], [Caption]) VALUES (2, N'RecipeA')
INSERT INTO [Recipes] ([Id], [Caption]) VALUES (3, N'RecipeB')
INSERT INTO [Recipes] ([Id], [Caption]) VALUES (4, N'RecipeC')
-- 3 records
SET IDENTITY_INSERT [Recipes] OFF
GO
</code></pre>
<p>Example:
If I search for ProductA and ProductE it should give me only RecipeC</p>
<p>Right now I have something like this for MySQL ( it is not final. I can only operate with Ids, I neet somehow to change it to work only with product captions and adapt for MSSQL)</p>
<pre><code>SELECT
*
FROM
recipes AS r
INNER JOIN
ingridients i ON i.IdRecipe = r.Id
WHERE
i.IdProduct IN (1 , 5, 6)
GROUP BY r.Id
HAVING COUNT(*) = (SELECT
COUNT(*)
FROM
ingridients AS ing
WHERE
ing.IdRecipe = r.Id);
</code></pre>
| 3 | 1,748 |
Entity framework core throwing error while inserting rows in partitioned table
|
<p>I have tried using entity framework core for my project.</p>
<p>I'm using latest PostgreSQL. And my requirement is to insert bulk data in database, which has a main table and its partitioned tables (horizontal partition).</p>
<p>Partitioned table are inherited from the main table and gets created in advance automatically using database triggers.</p>
<p>PostgreSQL has one more trigger like when the data for insertion arrives it decides in which partition table it has to insert using pre-decided column value.</p>
<p>(lets say there is column of timestamp and it decides according to date).</p>
<p><a href="https://i.stack.imgur.com/jKFiM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jKFiM.png" alt="Architecture like this" /></a></p>
<p>The issue is when I try to insert data using EF Core methods</p>
<blockquote>
<p>(like adding model and then context.SaveChanges())</p>
</blockquote>
<p>PostgreSQL throws an error of unknown exception from PgSql.</p>
<pre><code>{"The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions."}
Data: {System.Collections.ListDictionaryInternal}
Entries: Count = 1
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions."
Source: "Npgsql.EntityFrameworkCore.PostgreSQL"
StackTrace: " at Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal.NpgsqlModificationCommandBatch.Consume(RelationalDataReader reader)\r\n at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)\r\n at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)\r\n at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple`2 t)\r\n at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3
</code></pre>
<p>operation, Func`3 verifySucceeded)\r\n at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)\r\n at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)\r\n at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()\r\n at Efcore_testapp.Controllers.HomeController.Index() in C:\Users\parthraj.panchal\source\repos\Efcore testapp\Efcore testapp\Controllers\HomeController.cs:line 52"
TargetSite: {Void Consume(Microsoft.EntityFrameworkCore.Storage.RelationalDataReader)}</p>
<blockquote>
<p>My observation is that :-</p>
</blockquote>
<blockquote>
<p>EF core has sent data to pgsql to insert in table T and is expecting confirmation from table T but as pgsql has inserted the data in partitioned table T2 it it sending confirmation from that T2 table .
And thats where the conflict happens between pgsql and EF core.</p>
</blockquote>
<blockquote>
<p>My test :</p>
</blockquote>
<blockquote>
<p>As I once tested a scenario where I just disabled the triggers that were deciding where to insert data and all the flow working fine.</p>
</blockquote>
<p>Anyone has any idea about this ?</p>
| 3 | 1,190 |
Can't install PagedJS due to a Puppeteer issue
|
<p>When I try to <a href="https://www.pagedjs.org/documentation/02-getting-started-with-paged-js/#command-line-version" rel="nofollow noreferrer">install PagedJS</a> with the recommended <code>npm install -g pagedjs-cli pagedjs</code> I get:</p>
<pre><code>npm WARN deprecated @babel/polyfill@7.12.1: This package has been deprecated in favor of separate inclusion of a polyfill and regenerator-runtime (when neded). See the @babel/polyfill docs (https://babeljs.io/docs/en/babel-polyfill) for more information.
npm WARN deprecated core-js@2.6.12: core-js@<3.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 enginewhims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.
npm ERR! code 1
npm ERR! path /root/.nvm/versions/node/v14.17.5/lib/node_modules/pagedjs-cli/node_modules/puppeteer
npm ERR! command failed
npm ERR! command sh -c node install.js
npm ERR! internal/modules/cjs/loader.js:905
npm ERR! throw err;
npm ERR! ^
npm ERR!
npm ERR! Error: Cannot find module '/root/.nvm/versions/node/v14.17.5/lib/node_modules/pagedjs-cli/node_modules/puppeteer/install.js'
npm ERR! at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
npm ERR! at Function.Module._load (internal/modules/cjs/loader.js:746:27)
npm ERR! at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
npm ERR! at internal/main/run_main_module.js:17:47 {
npm ERR! code: 'MODULE_NOT_FOUND',
npm ERR! requireStack: []
npm ERR! }
</code></pre>
<p>If I run <code>npm install -g puppeteer</code> I get the exact same error (minus the warnings).</p>
<p>I tried a local install with <code>npm install pagedjs-cli pagedjs</code> and everything went fine (when I run <code>npm ls</code> I get:</p>
<pre><code>├── pagedjs-cli@0.1.6
├── pagedjs@0.2.0
└── puppeteer@10.4.0
</code></pre>
<p>which seems to indicate that the relevant packages were successfully installed locally). But when I try to run PagedJS with <code>npx pagedjs-cli example.html -o result.pdf</code> I get:</p>
<pre><code>Loading: example.htmlError: Failed to launch the browser process!
/home/sophivorus/node_modules/puppeteer/.local-chromium/linux-901912/chrome-linux/chrome: error while loading shared libraries: libatk-bridge-2.0.so.0: cannot open shared object file: No such file or directory
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (/home/sophivorus/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:197:20)
at Interface.<anonymous> (/home/sophivorus/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:187:68)
at Interface.emit (events.js:412:35)
at Interface.close (readline.js:530:8)
at Socket.onend (readline.js:254:10)
at Socket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
</code></pre>
<p>I then tried installing the missing library with <code>yum install libatk-bridge-2.0.so.0</code> and everything went fine (when I run <code>ldconfig -p | grep libatk-bridge-2.0.so.0</code> I get:</p>
<pre><code>libatk-bridge-2.0.so.0 (libc6) => /lib/libatk-bridge-2.0.so.0
</code></pre>
<p>which seems to indicate that the library was successfully installed). However when I retry <code>npx pagedjs-cli example.html -o result.pdf</code> I get the exact same error. If I avoid <code>npx</code> with <code>/home/sophivorus/node_modules/.bin/pagedjs-cli example.html -o result.pdf</code> I get the same error.</p>
<p>I'm on CentOS 7 and running the latest node and npm:</p>
<pre><code>node -v
v17.0.1
npm -v
8.1.0
</code></pre>
<p>I also tried with the latest LTS version. Thanks for any help!</p>
| 3 | 1,462 |
How to filter a table by a second table attribute on SQL
|
<p>I have a table named <code>lines</code>, that has registered every transaction made in every <code>account</code> with it's <code>datetime</code>. Along with the amount of the transaction the table has the <code>balance</code> for that account at that given time. The line registers the date with the hour (<code>datetime</code>) when the transaction was made and registers the datetime when the line was created (<code>created_at</code>).</p>
<p>So the lines table looks like this:</p>
<pre><code>id | account_id | amount | balance | datetime | created_at
1 | ac1 | 5 | 13 | 2020-03-24 08:57:31.195993 | 2020-03-24 08:57:31.195993
2 | ac1 | 3 | 10 | 2020-03-24 08:57:31.195993 | 2020-03-24 08:57:30.195993
3 | ac1 | 5 | 5 | 2020-03-24 06:54:31.195993 | 2020-03-24 06:57:31.195993
4 | ac2 | 6 | 11 | 2020-03-23 08:57:31.195993 | 2020-03-23 08:57:31.195993
4 | ac2 | 0 | 5 | 2020-03-23 07:57:31.195993 | 2020-03-23 07:57:31.195993
5 | ac3 | 6 | 13 | 2020-03-24 08:57:31.195993 | 2020-03-24 08:57:31.195993
</code></pre>
<p>I would like to get the balance of the last transaction of each day for every account.
It's important to mention that sometimes there are two <code>lines</code> that have the same <code>datetime</code> for an <code>account</code>, in that case I want the line with higher <code>created_at</code> datetime.
So I would like my output to be:</p>
<pre><code>id | account_id | amount | balance | date | datetime
1 | ac1 | 5 | 13 | 2020-03-24 | 2020-03-24 08:57:31.195993
4 | ac2 | 6 | 11 | 2020-03-23 | 2020-03-23 08:57:31.195993
5 | ac3 | 6 | 13 | 2020-03-24 | 2020-03-24 08:57:31.195993
</code></pre>
<p>I've managed to do this with lots of <code>INNER JOINS</code> but the query is just too slow.</p>
<pre><code>SELECT DATE(lines.datetime) as date, lines.account_id as account, lines.balance as balance
FROM lines
INNER JOIN (
SELECT DATE(a.datetime) date, a.account_id, MAX(a.created_at) created_at
FROM lines a
INNER JOIN (
SELECT b.account_id, DATE(b.datetime) date, MAX(b.datetime) datetime
FROM lines b
GROUP BY b.account_id, DATE(b.date)
) b ON a.account_id = b.account_id AND a.datetime = b.datetime
GROUP BY DATE(a.datetime), a.account_id
) c ON lines.account_id = c.account_id AND DATE(lines.datetime) = c.date AND lines.created_at = c.created_at
</code></pre>
<p>I know there must be a better way, just couldn't find it by myself :(</p>
| 3 | 1,060 |
How to produce a armv5 binary by zig builed-exec
|
<h2>Host</h2>
<p>Here is a running binary in target system</p>
<pre><code>readelf -h asterisk
</code></pre>
<pre><code>ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: ARM
Version: 0x1
Entry point address: 0x1ee30
Start of program headers: 52 (bytes into file)
Start of section headers: 3431360 (bytes into file)
Flags: 0x4000002, Version4 EABI, <unknown>
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 8
Size of section headers: 40 (bytes)
Number of section headers: 27
Section header string table index: 26
</code></pre>
<p>The target system cpu info</p>
<pre><code>Processor : ARMv6-compatible processor rev 5 (v6l)
BogoMIPS : 648.80
Features : swp half thumb fastmult edsp java
CPU implementer : 0x41
CPU architecture: 6TEJ
CPU variant : 0x1
CPU part : 0xb36
CPU revision : 5
Hardware : Comcerto 1000 (EVM)
Revision : 0000
Serial : 0000000000000000
</code></pre>
<p>The dmesg info</p>
<pre class="lang-sh prettyprint-override"><code>dmesg | head
</code></pre>
<pre><code>Initializing cgroup subsys cpuset
Initializing cgroup subsys cpu
Linux version 2.6.33.5 (root@Jason.openvox) (gcc version 4.1.2) #5 Mon Jan 29 20:07:16 CST 2018
CPU: ARMv6-compatible processor [4117b365] revision 5 (ARMv6TEJ), cr=00c5387d
CPU: VIPT aliasing data cache, VIPT aliasing instruction cache
Machine: Comcerto 1000 (EVM)
Memory policy: ECC disabled, Data cache writeback
On node 0 totalpages: 30720
free_area_init_node: node 0, pgdat c0399e54, node_mem_map c03c2000
DMA zone: 240 pages used for memmap
</code></pre>
<h2>zig build-exec</h2>
<p>Tried build with</p>
<pre class="lang-sh prettyprint-override"><code># running ./hello Aborted
zig build-exe -target arm-linux-none -mcpu=arm1136j_s hello.zig
# Aborted
zig build-exe -target arm-linux-eabi -mcpu=arm1136j_s hello.zig
# Illegal instruction
zig build-exe -target arm-linux-eabi hello.zig
</code></pre>
<p>tried v4 & v5 mcpu, but build failed</p>
<ul>
<li>arm710t</li>
<li>arm1020e</li>
<li>arm1020t</li>
<li>arm1022e</li>
</ul>
<pre><code>ld.lld: warning: lld uses blx instruction, no object with architecture supporting feature detected
ld.lld: error: undefined symbol: __sync_val_compare_and_swap_4
>>> referenced by heap.zig:352 (/usr/lib/zig/std/heap.zig:352)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.heap.PageAllocator.alloc)
>>> referenced by Mutex.zig:101 (/usr/lib/zig/std/Thread/Mutex.zig:101)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.Thread.Mutex.AtomicMutex.lockSlow)
>>> referenced by StaticResetEvent.zig:149 (/usr/lib/zig/std/Thread/StaticResetEvent.zig:149)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.Thread.StaticResetEvent.AtomicEvent.timedWait)
>>> referenced 2 more times
ld.lld: error: undefined symbol: __sync_fetch_and_add_1
>>> referenced by debug.zig:284 (/usr/lib/zig/std/debug.zig:284)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.debug.panicImpl)
ld.lld: error: undefined symbol: __sync_fetch_and_sub_1
>>> referenced by debug.zig:305 (/usr/lib/zig/std/debug.zig:305)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.debug.panicImpl)
ld.lld: error: undefined symbol: __sync_lock_test_and_set_4
>>> referenced by Mutex.zig:81 (/usr/lib/zig/std/Thread/Mutex.zig:81)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.Thread.Mutex.AtomicMutex.lock)
>>> referenced by Mutex.zig:88 (/usr/lib/zig/std/Thread/Mutex.zig:88)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.Thread.Mutex.AtomicMutex.unlock)
>>> referenced by Mutex.zig:123 (/usr/lib/zig/std/Thread/Mutex.zig:123)
>>> zig-cache/o/750724e51d9b1b9d610b91ec3f30a585/hello.o:(std.Thread.Mutex.AtomicMutex.lockSlow)
error: LLDReportedFailure
</code></pre>
<hr />
<p>But go cross build can running in target</p>
<pre class="lang-sh prettyprint-override"><code># produce EABI5 & armv5
GOOS=linux GOARM=5 GOARCH=arm CGO_ENABLED=0 go build hello.go
</code></pre>
<p>So I guess the problem is zig produce EABI5 or armv6, but <strong>none</strong> of armv5 mcpu can pass the build, how can I produce a EABI4 or armv5 binary by using zig ?</p>
<p><strong>Related PR</strong></p>
<ul>
<li><a href="https://github.com/ziglang/zig/pull/10756" rel="nofollow noreferrer">https://github.com/ziglang/zig/pull/10756</a></li>
</ul>
| 3 | 2,379 |
How to store data in ImageView in android dynamically?
|
<p>Subject of interest : Android</p>
<p>After hours of searching I couldn't find or understand how to create ImageView dynamically to store associative data and perform an action depending on the image view clicked.</p>
<p>Let me elaborate ,
I am creating a grid of ImageViews using GridLayout (as gridview examples are too complex for me). I am able to create the grid but still struggling with alignment issues.
So now I have this Grid of ImageViews, but from what I learned, the Id's of these ImageViews are converted to integers at run time. But I need these IDs as I use them to fetch data from server depending on their uniqueness. Is there a way to store other data than the Ids in ImageView Tags?. I come from a web development background where I could use JavaScript easily to create elements with dynamic Ids to refer later and use in queries. So please guide me.</p>
<p><strong>UPDATE:</strong>
I tried using the SetId method, and that is when I got this doubt. Because SetId only lets me set IntegerIDs. What if I needed alphanumeric ID to be used later for querying purposes?.</p>
<p><strong>Exam_Screen.Java</strong></p>
<pre><code>public class Exam_Screen extends AppCompatActivity {
GridLayout gridLayout;
public int[] QArray;
private int[] GetQuestionsFromServer() {
return new int[50];
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam__screen);
QArray = GetQuestionsFromServer();
AddQuestionsToScrollArea(QArray);
}
public void AddQuestionsToScrollArea(int[] QArray)
{
gridLayout = findViewById(R.id.gridlayout);
gridLayout.removeAllViews();
int total = QArray.length;
int column = 4 ;
int row = total / column;
gridLayout.setColumnCount(column);
gridLayout.setRowCount(row + 1);
//gridLayout
for (int i = 0, c = 0, r = 0; i < total; i++, c++) {
if (c == column) {
c = 0;
r++;
}
ImageView oImageView = new ImageView(this);
oImageView.setScaleX(0.3f);
oImageView.setScaleY(0.3f);
oImageView.setId(i); // I want to set the Ids I get from Server, and use them later
oImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
oImageView.setAdjustViewBounds(true);
oImageView.setImageResource(R.drawable.new_candidate_image);
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.width = 30;
lp.height = 30;
lp.topMargin = 5;
lp.bottomMargin = 5;
lp.leftMargin = 5;
lp.rightMargin = 5;
oImageView.setLayoutParams(lp);
GridLayout.Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
GridLayout.Spec colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
if (r == 0 && c == 0) {
Log.e("", "spec");
Log.d("Column", "value: " + column);
Log.d("rows", "value: " + row);
colspan = GridLayout.spec(GridLayout.UNDEFINED, 1);
rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
}
GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
rowSpan, colspan);
gridLayout.addView(oImageView, gridParam);
}
}
}
</code></pre>
<p><strong>Relevant Exam Screen Activity XML</strong></p>
<pre><code><ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border">
<GridLayout
android:id="@+id/gridlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ScrollView>
</code></pre>
| 3 | 1,482 |
How to delete checked items with one delete button
|
<p>I want to make a delete button that deletes the checked items. Means one master button to delete all the checked items. I made a master checkbox that checks all the values. Now I want to make a master button that would delete the checked values. Here is my code. I am new in laravel please help me. Sorry for my bad english. </p>
<pre><code>@extends('footer')
@extends('header')
@section('body')
<!DOCTYPE html>
<html>
<head>
<title>Retrieve data|Std view</title>
<link rel="stylesheet" type="text/css" href="{{ asset('public/css/style.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('public/css/bootstrap.css') }}">
<script type="text/javascript" src="{{ asset('public/js/jQuery.js') }}"></script>
</head>
<body>
@if(session()->has('success'))
<div class="alert alert-success">
<h3> {{ session()->get('success') }} </h3>
</div>
@endif
<div class="container">
<form action="" method="">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<h2 style="color: green">This Is View Form</h2>
<a href = "insert" class="btn btn-primary">Add New</a>
//HERE IS MY MASTER DELETE BUTTON.
<button type="submit" class="btn btn-danger" >Delete</button><br><br>
<table border="1" id="customers">
<tr>
<th>
//Here is my checkbox inside the loop.
<input type="checkbox" id="master" onchange="checkall(this);"> All
</th>
<th>Name</th>
<th>Email</th>
<th>Update</th>
<th>Delete</th>
</tr>
@foreach($data as $value)
<tr>
<td>
<input type="checkbox" class="sub_chk_{{ $value->id }}" value="{{ $value->id }}">
</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td><a href="edit/{{$value->id}}" class="btn btn-primary" >Edit</a></td>
//THIS DELETE BUTTON FOR SINGLE DELETE FUNCTION
<td><a href="delete/{{$value->id}}" onclick='ConfirmDelete()' class="btn btn-danger" >Delete</a></td>
</tr>
@endforeach
</table>
</form><br>
{{ $data->links() }}
</div>
</body>
</html>
@endsection
<script>
function checkall(obj) {
var selectedIds = [];
if(obj.checked){
$('input:checkbox').not(obj).prop('checked', 'checked');
$("input:checkbox").each(function(){
var $this = $(this);
if($this.is(":checked")){
selectedIds.push($this.attr("value"));
console.log(selectedIds);
}
})
}
else{
$('input:checkbox').prop('checked',false);
}
}
function ConfirmDelete()
{
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
event.preventDefault();
return false;
}
</script>
</code></pre>
| 3 | 1,559 |
Oracle SQL Partitions and Rank
|
<p>I want to be able to group data by effective dates for the most current project for employees, including department, and manager they work for. Here is a sample of the data. </p>
<p><strong>PROJ_TBL</strong></p>
<pre><code>+-------------+----------+----------------+
| EMPLOYEE_ID | EFF_DATE | EMPL_PROJECT |
+-------------+----------+----------------+
| P1441 | 05/21/11 | IMC |
| P1441 | 09/12/12 | BEEB |
| P1441 | 09/23/12 | PRUD_FIN_SALES |
+-------------+----------+----------------+
</code></pre>
<p><strong>EMPLOYEE_TBL</strong></p>
<pre><code>+-------------+--------------+---------+----------+
| EMPLOYEE_ID | PROJECT_MBR | DEPT_NM | EFF_DATE |
+-------------+--------------+---------+----------+
| P1441 | BEN DEENEY | ACCNT | 02/09/08 |
| P1566 | LAURA FIELDS | ACCNT | 05/03/10 |
| P2155 | PAUL DAVEY | ACCNT | 10/03/10 |
| P1441 | BEN DEENEY | SALES | 07/19/12 |
+-------------+--------------+---------+----------+
</code></pre>
<p><strong>EMP_DPT_TBL</strong></p>
<pre><code>+-------------+---------------+---------+----------+
| EMPLOYEE_ID | MANAGER | DEPT_NM | EFF_DATE |
+-------------+---------------+---------+----------+
| P1441 | BOB PAISLEY | ACCNT | 02/09/08 |
| P1441 | LINDA HARDY | SALES | 07/19/12 |
+-------------+---------------+---------+----------+
</code></pre>
<p>I'm not very familiar with the use of partitions. I want to be able to use it to combine the information to get the current data for <code>EMPLOYEE_ID</code> <code>P1441</code>. The desired output is :</p>
<pre><code>+-------------+---------+--------------+----------------+
| EMPLOYEE_ID | DEPT_NM | MANAGER | PROJECT |
+-------------+---------+--------------+----------------+
| P1441 | SALES | LINDA HARDY | PRUD_FIN_SALES |
+-------------+---------+--------------+----------------+
</code></pre>
<p>I am able to get the correct current records for the individual tables but combining the results to generate what I want is problematic. Here are the queries...</p>
<pre><code>-- Current Project
SELECT EMPL_PROJECT,
EMPLOYEE_ID,
EFF_DT
FROM ( SELECT EMPL_PROJECT,
EMPLOYEE_ID,
EFF_DT,
RANK() OVER ( PARTITION BY EMPLOYEE_ID
ORDER BY EFF_DT DESC) AS rk1
FROM PROJ_TBL ) t
WHERE rk1 = 1
-- Current Department
SELECT DEPT_NM,
EMPLOYEE_ID,
EFF_DT
FROM ( SELECT DEPT_NM,
EMPLOYEE_ID,
EFF_DT,
RANK() OVER ( PARTITION BY EMPLOYEE_ID
ORDER BY EFF_DT DESC ) AS rk2
FROM EMPLOYEE_TBL ) t
WHERE rk2 = 1
-- Current Manager
SELECT MANAGER,
EMPLOYEE_ID,
EFF_DT
FROM ( SELECT MANAGER,
EMPLOYEE_ID,
EFF_DT,
RANK() OVER ( PARTITION BY EMPLOYEE_ID
ORDER BY EFF_DT DESC ) AS rk3
FROM EMP_DPT_TBL ) t
WHERE rk3 = 1
</code></pre>
<p>How can I combine these into one query using the <code>EMPLOYEE_ID</code> to generate the report? </p>
| 3 | 1,406 |
XML Skip 'wrong' event type
|
<p>I have a certain BLOATED XML file that i use to generate a Gallery with some few information about the Picture. Besides of the Actual needed NEW there are plenty of entries with OLD, adding more pictures, but creating also duplicate entries.</p>
<pre><code><result>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>OLD</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/SPECIFICNAME/?w=</url>
<name>SPECIFICNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>NEW</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/ANOTHERNAME/?w=</url>
<name>ANOTHERNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
<event>
<date>2015-04-14T22:19:02+02:00</date>
<type>NEW</type>
<value1>AAA</value1>
<id>changingIDwhatever</id>
<profile>
<url>/domainpart/SPECIFICNAME/?w=</url>
<name>SPECIFICNAME</name>
<value2>BBB</value2>
<value3>CCC</value3>
<value4>DDD</value4>
<image>
<url>http://domain.tld/path/to/the/image/320.jpg?1234-ab1cd2e345fg6789</url>
<width>320</width>
</image>
</profile>
</event>
</result>
</code></pre>
<p>I do generate everything in a pretty neat layout in a very basic way. As i have really NO knowledge at all about php, i usually base on skriptpieces i find that are kind of put together in a way that the outcome mostly is the way i need it.</p>
<pre><code><?php
//###################Config Start#########################
$memberid = "123456";
$maxAnzahl = 50;
$zaehler = 0;
$baseURL = "http://www.domain.tld";
//###################Config End#########################
$feed = simplexml_load_file('http://key:keypass@www.domain.tld/news/xml');
$events = $feed->events;
foreach ($events->event as $event) {
echo "<div class='4u'>";
echo "<article class='box style2'>";
if ($event->type == "newMember") {
echo "<a href='".$baseURL.$event->profile->url.$memberid."' class='image featured' target='_blank'><img src='" . $event->profile->image->url . "' alt='' /> </a>";
} else {
echo "<a href='".$baseURL.$event->profile->url.$memberid."' class='image featured' target='_blank'><img src='" . $event->image->url . "' alt='' /> </a>";
}
echo "<h3><a href='".$baseURL.$event->profile->url.$memberid."'>" . $event->profile->name . "</a></h3>";
echo "</article>";
echo "</div>";
$zaehler = $zaehler + 1;
if ($zaehler == $maxAnzahl) {
break;
}
}
?>
</code></pre>
<p>Would be someone able to tell me how i could specify now in that skript how to SKIP all OLD ?</p>
<p>Kind Regards
Caylean</p>
| 3 | 1,741 |
BOSH MySql Deployment timeout error
|
<p>I am trying to install the MySql deployment using bosh deployment manifest by configuring VIP network. I could execute the bosh mysql deployment without any error but in the final stage of deployment i am getting the timeout error(Error 450002: Timed out pinging to 0f66d2df-e923-42c2-81e4-0e1e1a0c39d3 after 600 seconds) while "Started creating bound missing vms > common/0". I have used the below manifest without HAProxy load balancing,</p>
<hr>
<p>name: cf-mysql
director_uuid: fgfg54253-fgkdsgf-4977dfafsdfg</p>
<p>releases:
- {name: cf-mysql, version: latest}</p>
<p>compilation:
workers: 1
network: cf1
reuse_compilation_vms: true
cloud_properties:
instance_type: m1.medium
availability_zone: us-west-2a</p>
<p>update:
canaries: 1
canary_watch_time: 30000-180000
update_watch_time: 30000-180000
max_in_flight: 4 </p>
<p>networks:
- name: cf1
type: manual
subnets:
- range: 10.0.0.0/24
gateway: 10.0.0.1
static:
- 10.0.0.16 - 10.0.0.17
reserved:
- 10.0.0.2 - 10.0.0.15
dns: [10.0.0.2]
cloud_properties:
subnet: subnet-4545d5r4
security_groups:
- Bosh</p>
<ul>
<li>name: elastic
type: vip
cloud_properties: {}</li>
<li>name: default
type: dynamic
cloud_properties:<br>
security_groups:
<ul>
<li>default</li>
</ul></li>
</ul>
<p>resource_pools:
- name: common
network: default
size: 1
stemcell:
name: bosh-aws-xen-ubuntu
version: 2427
cloud_properties:
instance_type: m1.medium
availability_zone: us-west-2a
key_name: MYKeyPair</p>
<p>jobs:
- name: mysql
release: cf-mysql
template: mysql
instances: 1
resource_pool: common
networks:
- name: default
default: [dns, gateway]
- name: elastic
static_ips:
- 52.54.25.44
persistent_disk: 10240</p>
<pre><code>properties:
admin_username: root
admin_password: root
port: 3306
max_connections: 1500
cluster_ips: 52.54.25.44
</code></pre>
<p>cloud:
plugin: aws
properties:
aws:
access_key_id: fslkjghfljsghLJH
secret_access_key: pqE/fskglkljfsklghkh
region: us-west-2
default_key_name: MYKeyPair
default_security_groups: ["default"]
ec2_private_key: ~/my-micro-deployment/MYKeyPair.pem</p>
<p>Error log:</p>
<p>DEBUG -- DirectorJobRunner: SENT: hm.director.alert {"id":"f1205784-c8d5-457a-ac00-7036585f7987","severity":3,"title":"director - error during update deployment","summary":"Error during update deployment for 'cf-mysql' against Director '6a9032ae-197e-47e9-830b-3e4ca0c44f64': #","created_at":1432044197}
E, [2015-05-19 14:03:17 #4025] [task:20] ERROR -- DirectorJobRunner: Timed out pinging to 0f66d2df-e923-42c2-81e4-0e1e1a0c39d3 after 600 seconds.</p>
<p>TIA..,</p>
| 3 | 1,247 |
python imagededupe can you reconstruct an original image from its embeddings?
|
<p>I am using <a href="https://github.com/idealo/imagededup" rel="nofollow noreferrer">imagededupe</a> in Python to produce image embeddings I place in a folder and I want to take those embeddings and convert them back to the original .jpg image.</p>
<p>I encode each image by using the <code>CNN</code> method (<em>convolutional neural network trained on <code>ImageNet</code></em>) method that package.</p>
<p>The resulting encodings are <code>numpy.ndarray</code> type, like so:</p>
<pre><code>{'IMG-7817.jpg': array([0. , 0.8666797 , 0.6738928 , ..., 0.19499177, 0.19915162,
0.11766607], dtype=float32)}
</code></pre>
<p>To persist them in memory, I have used <code>numpy.ndarray.tolist()</code> to convert the <code>ndarray</code> values into a list of <code>floats</code>. Then it saves it as a new document into MongoDB.</p>
<p>Here is an example of one document, showing the floats:</p>
<pre><code>{'_id': ObjectId('62de157cd66e524858266e56'),
'filename': 'image_0.jpg',
'createdAt': datetime.datetime(2022, 7, 24, 21, 0, 58, 297000),
'encoding': [0.34322163462638855,
0.509546160697937,
0.5979495048522949,
0.0,
0.9418766498565674,
0.062201134860515594,
0.0,
0.0,
0.3629385828971863,
0.8452704548835754,
1.0556049346923828,
0.15479359030723572,
0.05965745821595192,
0.6355874538421631,
0.0075227259658277035,
0.0,
0.7630028128623962,
0.25163599848747253,
0.38510754704475403,
0.05900629609823227,
1.259505033493042,
0.2511945962905884,
0.34552499651908875,
0.0,
0.20837950706481934,
0.0,
0.46649169921875,
0.04043807461857796,
0.04735632985830307,
2.764833450317383,
0.28932467103004456,
0.022755710408091545,
1.7064937353134155,
0.020368073135614395,
0.08486563712358475,
0.08789866417646408,
0.018082227557897568,
0.8046256899833679,
0.2572726905345917,
1.7080179452896118,
0.13402247428894043,
0.0,
0.6671139597892761,
0.6578285694122314,
0.8306216597557068,
0.33851000666618347,
0.8741984367370605,
1.769014596939087,
0.684082567691803,
0.5945196747779846,
0.0,
0.4923103153705597,
0.0,
0.0,
0.0,
0.43480363488197327,
0.0,
2.0243093967437744,
3.1641061305999756,
0.04148351401090622,
0.2754305601119995,
0.24396584928035736,
0.0,
0.02952236868441105,
1.3269319534301758,
0.400570809841156,
0.1814577877521515,
1.0266987085342407,
0.0,
0.48076146841049194,
0.31500837206840515,
0.24837727844715118,
0.0,
0.23274537920951843,
0.10061652213335037,
0.5313457250595093,
0.22604097425937653,
0.11777201294898987,
0.6426587700843811,
0.30787965655326843,
0.00855748075991869,
0.011529005132615566,
1.1762546300888062,
0.02678094431757927,
1.6777329444885254,
0.6672563552856445,
0.23667019605636597,
0.49905094504356384,
0.9757379293441772,
0.07683343440294266,
1.5291916131973267,
0.0,
0.3130893409252167,
0.6051976084709167,
0.017192933708429337,
0.43943557143211365,
0.2320941686630249,
0.3049321174621582,
1.4164737462997437,
3.0678188800811768,
0.027480242773890495,
0.0016468112589791417,
0.0,
0.07514918595552444,
0.43065083026885986,
3.375669479370117,
1.547513723373413,
0.4367760121822357,
0.004104389809072018,
0.19813460111618042,
0.0,
1.5236296653747559,
2.4143331050872803,
0.0,
0.4325718879699707,
0.3500346839427948,
0.7155059576034546,
0.0,
2.191272258758545,
0.021950488910079002,
0.6380945444107056,
0.07029495388269424,
0.9965856075286865,
0.7871404886245728,
0.020270364359021187,
0.21629869937896729,
0.22851204872131348,
0.6256837844848633,
0.6793181896209717,
0.0,
0.7013466358184814,
0.2701347768306732,
0.4660792052745819,
0.0,
0.99172443151474,
0.05413336679339409,
0.9221435785293579,
0.0,
0.9360405802726746,
0.0,
0.030728023499250412,
0.022367192432284355,
0.019651522859930992,
0.4800198972225189,
0.11290711909532547,
0.0,
0.8062187433242798,
0.0,
0.7398870587348938,
0.6118819713592529,
0.17569033801555634,
0.6082322597503662,
0.025949034839868546,
1.804274559020996,
0.4318274259567261,
0.0,
0.33641141653060913,
1.38775634765625,
0.0,
1.2272226810455322,
0.15384995937347412,
1.5630751848220825,
1.190468192100525,
0.5651965737342834,
1.4905359745025635,
0.08070334792137146,
0.099326491355896,
1.6428868770599365,
1.8835887908935547,
1.900753378868103,
0.0058065494522452354,
0.7904874682426453,
0.7456177473068237,
1.5191725492477417,
0.0,
1.411240577697754,
0.0,
0.2351973056793213,
0.47451984882354736,
0.6398224830627441,
0.06026613339781761,
0.06863820552825928,
0.33046841621398926,
1.8896198272705078,
0.021269584074616432,
2.3213772773742676,
0.19969674944877625,
0.22938404977321625,
0.138387069106102,
0.0,
0.2955643832683563,
0.7730927467346191,
1.2605562210083008,
1.813166618347168,
0.5475223064422607,
0.07392473518848419,
0.05272753909230232,
1.260231375694275,
0.0,
1.3669939041137695,
0.13212966918945312,
0.0,
1.810328722000122,
0.0,
0.968720555305481,
0.5265544056892395,
0.0,
0.0,
0.3666769862174988,
0.6280245780944824,
0.24455592036247253,
0.05917458236217499,
0.1274377703666687,
0.24018031358718872,
0.04338640719652176,
0.6593717336654663,
0.4561670124530792,
0.6908249258995056,
0.0,
0.025656165555119514,
1.4662184715270996,
0.4808516204357147,
0.48574984073638916,
0.0,
0.5596708059310913,
0.0,
0.07661600410938263,
0.8362483382225037,
0.019625132903456688,
1.4666523933410645,
0.0,
0.5307647585868835,
0.2795000374317169,
0.14065083861351013,
0.06074102967977524,
0.5063194036483765,
0.3797137141227722,
0.37272703647613525,
0.22654202580451965,
1.655469298362732,
0.0,
0.11777283996343613,
1.388221263885498,
0.327331006526947,
0.14950616657733917,
2.0307371616363525,
0.40243691205978394,
1.0219730138778687,
1.53922438621521,
1.2161401510238647,
0.7625423073768616,
0.1292436718940735,
0.9063143134117126,
0.9079506397247314,
0.37720248103141785,
1.4248236417770386,
1.437509298324585,
0.6693912148475647,
0.0,
0.0,
0.0027586750220507383,
0.9666323065757751,
0.0,
0.46942809224128723,
1.44985032081604,
0.34272393584251404,
2.2227885723114014,
0.0,
1.488860011100769,
0.2924092411994934,
1.0731092691421509,
1.4170044660568237,
0.10373884439468384,
0.12016452103853226,
0.02246188558638096,
0.9552142024040222,
0.05175960808992386,
0.9273093342781067,
0.4393492639064789,
0.3075776696205139,
0.2306509166955948,
0.0,
0.615312933921814,
0.16303738951683044,
0.0,
0.2877673804759979,
1.501681923866272,
0.4097016751766205,
2.9622018337249756,
0.5579401254653931,
0.142703577876091,
0.5920137166976929,
1.303241491317749,
0.00606588926166296,
0.4949913024902344,
0.19190119206905365,
0.733661413192749,
0.6974300742149353,
0.0,
0.8278228044509888,
0.5845810770988464,
0.026461739093065262,
0.4288907051086426,
0.21419385075569153,
2.954052686691284,
0.3760499656200409,
0.004199077375233173,
3.8070878982543945,
0.715491771697998,
0.4648321568965912,
0.0,
0.0,
0.19548028707504272,
0.48019057512283325,
1.1979873180389404,
0.07732359319925308,
0.19149938225746155,
0.1502079963684082,
2.0691733360290527,
2.4982733726501465,
1.337972640991211,
1.100319504737854,
2.6857542991638184,
0.29503199458122253,
0.23128174245357513,
0.0,
0.5455896854400635,
0.4850095510482788,
0.10392599552869797,
0.2443435788154602,
0.7817987203598022,
0.0,
2.063075065612793,
0.4417440593242645,
0.2553230822086334,
0.3762524724006653,
0.05001183599233627,
0.04212421923875809,
1.286272644996643,
0.9305449724197388,
0.02449200674891472,
1.2230279445648193,
0.0,
0.29419076442718506,
0.008204713463783264,
0.7008044123649597,
0.16965098679065704,
0.11801895499229431,
0.8991751670837402,
0.4699343144893646,
0.0,
0.8951627612113953,
1.3787250518798828,
0.0,
0.08008038997650146,
1.3252822160720825,
0.32005879282951355,
0.0,
0.4818739593029022,
0.4019497334957123,
0.7889391779899597,
0.0,
0.18576571345329285,
0.0,
1.3088619709014893,
2.7723488807678223,
0.00022756097314413637,
0.4293895363807678,
0.5022754073143005,
0.044507503509521484,
1.5894511938095093,
0.062480755150318146,
0.0,
1.1833703517913818,
1.6038163900375366,
1.7601900100708008,
0.11935224384069443,
0.0,
3.55781888961792,
0.9694040417671204,
0.38496172428131104,
0.09860406816005707,
1.0045870542526245,
3.0407869815826416,
1.3872655630111694,
0.5597723722457886,
0.4029926359653473,
1.82244873046875,
1.4435524940490723,
0.0,
0.268917053937912,
1.1448471546173096,
1.3053370714187622,
0.6695809364318848,
0.22877833247184753,
0.8759015202522278,
0.009998252615332603,
0.22522638738155365,
0.0,
2.089116096496582,
0.10225784778594971,
0.0835852101445198,
0.04399365931749344,
0.357903391122818,
0.00423638429492712,
2.197624444961548,
1.4854577779769897,
0.785973310470581,
0.0,
1.33061945438385,
0.05213224142789841,
0.0,
1.4183796644210815,
0.07906366884708405,
0.27266740798950195,
0.0919405072927475,
0.32426464557647705,
1.0865753889083862,
0.0,
0.17555345594882965,
0.8236625790596008,
0.5672846436500549,
0.0,
0.035536810755729675,
0.7000375986099243,
1.5232492685317993,
0.3168185353279114,
0.0,
0.29834094643592834,
0.20520535111427307,
0.4351038336753845,
0.13560494780540466,
0.48883458971977234,
0.02037435956299305,
1.1522188186645508,
0.9122401475906372,
0.0,
1.30799400806427,
0.22012335062026978,
0.0,
0.0,
0.24422557651996613,
0.0,
0.4273641109466553,
0.5228200554847717,
0.5666704773902893,
0.3363366425037384,
0.6759360432624817,
2.0034751892089844,
0.17202824354171753,
0.2595841884613037,
0.015393995679914951,
0.04131931811571121,
0.18808656930923462,
0.0669889822602272,
0.9347860217094421,
1.5079140663146973,
2.3521738052368164,
0.45415419340133667,
0.7850313186645508,
0.010190464556217194,
0.6210658550262451,
0.3110385835170746,
0.08557576686143875,
0.2882275879383087,
0.018340876325964928,
0.08235052973031998,
0.11521648615598679,
2.253997564315796,
1.2350491285324097,
0.08332804590463638,
0.1232355460524559,
2.3126087188720703,
1.156542181968689,
0.6510205864906311,
0.0,
0.12935137748718262,
0.0308428592979908,
0.3024436831474304,
0.0,
0.3228701055049896,
1.1835720539093018,
1.2879806756973267,
0.0,
0.0,
1.0283877849578857,
0.9930158257484436,
0.46817547082901,
1.4385830163955688,
1.4435007572174072,
0.3171677887439728,
0.6235666871070862,
0.5815529823303223,
0.5360093116760254,
0.9516975283622742,
0.1696314960718155,
0.09518808126449585,
0.030107799917459488,
0.31380897760391235,
0.0,
0.42714065313339233,
0.5804895162582397,
0.9608817100524902,
0.1775510311126709,
0.010171392001211643,
0.5893941521644592,
1.5398626327514648,
0.39006567001342773,
0.32146579027175903,
2.948575019836426,
0.06686578691005707,
1.531951904296875,
0.0,
0.17576193809509277,
0.2349756807088852,
0.9275945425033569,
0.3193134367465973,
3.367725372314453,
0.8526585102081299,
0.0,
0.422979474067688,
1.0967295169830322,
1.4886173009872437,
0.08168420940637589,
1.9246219396591187,
0.6297357082366943,
0.6322764158248901,
0.0,
2.65885329246521,
1.6137109994888306,
0.791668176651001,
0.18871046602725983,
1.6689802408218384,
0.219522163271904,
1.7474461793899536,
0.10053602606058121,
0.6737263798713684,
0.8441563248634338,
0.3114991784095764,
0.7566099166870117,
0.2245187759399414,
0.2011154741048813,
0.8214294910430908,
0.0,
1.9816653728485107,
0.7716283798217773,
1.6154274940490723,
0.22172033786773682,
0.0,
0.058957479894161224,
1.076833963394165,
0.26426446437835693,
1.0176373720169067,
0.3910500705242157,
2.1494927406311035,
0.664349377155304,
0.7940111756324768,
0.4397018253803253,
0.7703667283058167,
0.0,
0.018988996744155884,
0.5460900664329529,
1.7279266119003296,
0.754666805267334,
0.08635308593511581,
0.5351725816726685,
0.015438989736139774,
0.5810871720314026,
0.4795708954334259,
0.09397150576114655,
1.8130183219909668,
1.0192855596542358,
0.7982662916183472,
0.6442264914512634,
1.0579023361206055,
0.9965284466743469,
0.33102571964263916,
0.0,
0.12347199022769928,
0.0012085589114576578,
0.0,
0.012317202985286713,
0.7999298572540283,
0.23033346235752106,
0.10711371153593063,
0.055289968848228455,
0.10045799612998962,
0.2694406807422638,
1.6767593622207642,
0.08160638809204102,
0.055825188755989075,
0.35727065801620483,
0.14833365380764008,
0.03880086913704872,
0.05746801570057869,
0.023325448855757713,
0.3614659309387207,
1.1203327178955078,
0.23827773332595825,
0.1701105833053589,
0.005051849409937859,
0.014566520228981972,
0.0,
0.17170780897140503,
0.0,
0.3361126184463501,
0.7800708413124084,
1.4469071626663208,
0.9698413014411926,
0.47699087858200073,
0.0,
0.6676139235496521,
2.3889882564544678,
0.16141292452812195,
0.549674928188324,
1.446986198425293,
2.9572486877441406,
1.2994608879089355,
0.9938348531723022,
0.012836528941988945,
0.5091323852539062,
0.3293815851211548,
0.2696889638900757,
0.023653989657759666,
0.9666279554367065,
0.0,
0.09485077112913132,
0.21621057391166687,
0.05144309997558594,
0.7748975157737732,
0.16373832523822784,
0.32590582966804504,
3.2590131759643555,
0.18453021347522736,
0.32559701800346375,
0.01810051128268242,
1.3126763105392456,
0.9643300771713257,
0.7701171636581421,
0.012872778810560703,
3.2080838680267334,
1.3774534463882446,
0.6093534827232361,
0.4270886778831482,
1.536228060722351,
1.0596519708633423,
0.7293568849563599,
0.040961820632219315,
0.8098430037498474,
0.03354305401444435,
0.3781156837940216,
0.07808584719896317,
1.5445245504379272,
0.2643190026283264,
0.03979670628905296,
0.1401960253715515,
0.0,
2.858400821685791,
1.5187857151031494,
0.916731059551239,
0.4406169056892395,
2.0909416675567627,
0.041937537491321564,
0.26336491107940674,
0.6905952095985413,
0.5504804849624634,
0.7093060612678528,
0.0,
1.5680856704711914,
0.6002225875854492,
0.6944994926452637,
0.09715773910284042,
0.37384095788002014,
0.09308439493179321,
0.11243189871311188,
0.0,
0.0014087663730606437,
0.6081674695014954,
1.0300709009170532,
0.0,
1.6597859859466553,
0.0,
0.06655865907669067,
0.0,
0.0,
0.776603102684021,
0.706895112991333,
0.06840622425079346,
0.01103916671127081,
0.20892217755317688,
0.06662453711032867,
2.3237693309783936,
0.0,
1.001037836074829,
0.7960761189460754,
0.011129717342555523,
0.04408513754606247,
0.9169716835021973,
0.18723581731319427,
0.0,
0.13618384301662445,
0.1143331304192543,
0.08429567515850067,
0.5295025706291199,
0.24401012063026428,
0.4518049657344818,
1.6427943706512451,
2.9292097091674805,
0.2356298565864563,
1.886139988899231,
0.8494397401809692,
1.0584583282470703,
0.10908976197242737,
1.6228749752044678,
0.03479631990194321,
0.3667331635951996,
0.29944977164268494,
0.0,
0.5278289318084717,
1.8577454090118408,
0.7919538617134094,
0.3287472724914551,
1.0173267126083374,
0.21281661093235016,
2.5687320232391357,
0.0,
0.22931823134422302,
0.08953932672739029,
1.8022074699401855,
0.031096210703253746,
0.0,
0.3735235929489136,
0.9747275710105896,
1.4670822620391846,
0.0014497002121061087,
0.1918376237154007,
0.017492996528744698,
0.14093568921089172,
2.4359452724456787,
1.0266388654708862,
0.06744030863046646,
0.5923642516136169,
0.05829468369483948,
0.7882423996925354,
0.006824888754636049,
0.0,
0.12467359006404877,
0.0,
0.6454435586929321,
0.7348983287811279,
0.21230670809745789,
0.751591682434082,
0.10542069375514984,
2.747696876525879,
0.025314131751656532,
1.5147247314453125,
0.4253242611885071,
0.026335788890719414,
0.2820242941379547,
0.0,
1.629762887954712,
0.0,
1.0258194208145142,
0.01697576977312565,
0.0026492439210414886,
0.5882153511047363,
0.15281014144420624,
0.15450280904769897,
0.7614965438842773,
1.5575156211853027,
0.44215384125709534,
0.031301699578762054,
0.0,
0.41315919160842896,
0.0,
0.9163169860839844,
0.0,
0.6567441821098328,
2.000319480895996,
0.6224666833877563,
1.1936211585998535,
0.37969183921813965,
0.6791279315948486,
0.7023849487304688,
0.5725939273834229,
0.33029961585998535,
0.29946884512901306,
0.08158722519874573,
1.1009563207626343,
0.1951158344745636,
0.17529775202274323,
0.0,
0.24547788500785828,
0.4813558757305145,
0.10754260420799255,
1.0999802350997925,
0.09632908552885056,
1.257835030555725,
3.48246169090271,
1.4914885759353638,
1.3317164182662964,
0.0,
0.26352792978286743,
0.1344657689332962,
1.5231508016586304,
0.10092543810606003,
0.11918514966964722,
2.744619846343994,
0.0,
1.9301466941833496,
0.23720590770244598,
1.2849202156066895,
0.0021527463104575872,
0.22261980175971985,
0.0,
1.2995405197143555,
1.5964542627334595,
0.3902784585952759,
0.0,
0.39399170875549316,
1.5980095863342285,
0.5178284049034119,
1.002244472503662,
0.0,
1.0685653686523438,
0.3623090386390686,
0.24759413301944733,
2.319288969039917,
0.06726662069559097,
0.4107389748096466,
0.25172483921051025,
0.09692853689193726,
0.36315271258354187,
0.19497661292552948,
0.19528783857822418,
0.9833536744117737,
0.0,
0.3592410981655121,
0.3673408031463623,
0.9627466797828674,
0.026713738217949867,
0.6547496318817139,
0.04448238015174866,
0.008870258927345276,
0.6792797446250916,
0.0,
0.024829436093568802,
1.5601677894592285,
0.18391843140125275,
0.16963115334510803,
0.49852055311203003,
0.29731711745262146,
1.5001922845840454,
0.5966616868972778,
0.5658796429634094,
0.9493252635002136,
0.0,
0.0,
0.4046423137187958,
1.4287112951278687,
0.0,
0.15436147153377533,
0.3651731312274933,
0.0,
0.00114287412725389,
0.4599761962890625,
0.13904592394828796,
0.049609310925006866,
0.04458696022629738,
0.006772597320377827,
0.050582993775606155,
0.0,
0.0,
1.1677778959274292,
0.3135088384151459,
0.1667020320892334,
1.4050168991088867,
0.08352083712816238,
1.5827399492263794,
1.193649172782898,
0.030835293233394623,
0.0,
0.0015767943114042282,
0.7566667795181274,
0.26073670387268066,
1.8150725364685059,
0.0028364635072648525,
0.7325196266174316,
0.21360227465629578,
0.27992552518844604,
0.9042648673057556,
2.0153775215148926,
0.26339706778526306,
0.0,
0.6202089190483093,
0.10526447743177414,
2.882450580596924,
0.3095151484012604,
0.0,
0.637947142124176,
0.5944535136222839,
0.0,
0.0,
2.7035391330718994,
0.7932912111282349,
0.40263426303863525,
1.382933497428894,
0.5418493151664734,
0.08483023196458817,
0.7244842052459717,
0.20402145385742188,
0.27017006278038025,
1.0310587882995605,
0.0,
0.26290374994277954,
0.44489234685897827,
0.0,
0.10985265672206879,
4.00398588180542,
0.0,
1.889216661453247,
0.9396313428878784,
0.5248347520828247,
2.334782361984253,
0.6514081358909607,
0.021495413035154343,
0.30265650153160095,
0.0,
0.11324827373027802,
0.0,
0.0,
0.07938762754201889,
0.00594561081379652,
0.2369159758090973,
0.3200414478778839,
0.7243974804878235,
0.07896162569522858,
0.19521552324295044,
0.017373599112033844,
0.0,
0.7747635245323181,
0.0,
3.0585978031158447,
0.2982688248157501,
0.006080341059714556,
0.11861772835254669,
0.0,
0.0,
0.4043075144290924,
0.0,
0.2331291139125824,
0.05324462428689003,
0.3905235528945923,
0.49934008717536926,
0.0,
0.0,
0.2706427276134491,
0.0,
0.0,
0.02849772945046425,
0.5065882802009583,
1.5505584478378296,
1.4176472425460815,
0.830781102180481,
0.6771125197410583,
0.1085791289806366,
0.43909430503845215,
0.13297335803508759,
1.5684330463409424,
2.108699321746826,
0.11001390963792801,
0.4872213900089264,
0.32524189352989197,
0.0737423524260521,
0.14409983158111572,
0.9547043442726135,
1.1935787200927734,
0.16664843261241913,
0.282832533121109,
0.28268536925315857,
0.19144511222839355,
0.11462447047233582,
0.5705850720405579,
0.434655100107193,
0.03162039443850517,
0.8690363168716431,
0.049061935395002365,
2.015324592590332,
0.01103197317570448,
0.9478869438171387,
0.0,
0.7611132264137268,
1.5938303470611572,
0.41670796275138855,
0.5746119618415833,
0.6635866165161133,
1.0752760171890259,
0.06721699237823486,
0.05494782701134682,
0.396668016910553,
...],
'updatedAt': datetime.datetime(2022, 7, 25, 0, 33, 50, 36000)}
</code></pre>
<p>And so, I want to take those saved embeddings from MongoDB and convert them back to the original <code>.jpg</code> image.</p>
<p><strong>Can this be done?</strong></p>
<p>I have tried unsuccessfully the following before asking:</p>
<ol>
<li>Took the embeddings list, passed it to np.array (converting it into ndarray), then tried to use Image.fromarray to generate the image. Got a <code>ValueError: not enough image data</code></li>
</ol>
<p>code:</p>
<pre><code>na = np.array( embeddings_doc['embeddings'] )
image = Image.fromarray(na.astype('uint8'), 'RGB')
image
</code></pre>
<ol start="2">
<li>Tried to use PIL Image to render an image but it ended up displaying an image with a single line (the embeddings no doubt but a single line is not what I am after)</li>
</ol>
<p>Before trying keras, perhaps someone can advise a better way to regenerate the original image from encodings?</p>
<p>I'm not saving the image shape. Should I? Is that going to be needed or can that be <em>figured out</em> by python somehow?</p>
| 3 | 11,979 |
Reloading ChartJs Image
|
<p>I have a chart and before creating a new chart in the same canvas, I call the <code>myccc.destroy();</code> and it works well. </p>
<p>However, if I create a image of chart and after that If I create a new chart, image persist. Obviously, I need to remove image of chart as well as chart itself before redrawing the chart. </p>
<p>I tried this;</p>
<pre><code>$("#dialog_chart_img").remove();
$(".dialog_chart_img_div").append('<img id="dialog_chart_img" style="width: 655px; height: 580px; margin-top: 40px;" />');
if (myccc != undefined || myccc != null) {
myccc.destroy();
}
var ctx = document.getElementById('dialog_chart');
var myccc = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: array_zaman,
datasets: [{
label: "Yumurta",
data: array_adet,
}]
},
options: {
maintainAspectRatio: true,
responsive: true,
// maintainAspectRatio: true,
legend: {
display: false
},
animation: {
duration: 1,
onComplete: function(animation) {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize = 16, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily = "charter");
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y);
});
});
document.querySelector('#dialog_chart').remove();
document.querySelector('#dialog_chart_img').setAttribute('src', this.toBase64Image());
}
}
}
});
</code></pre>
<p>Html:</p>
<pre><code><div class="dialog_chart_img_div">
<img id="dialog_chart_img" style="width: 655px; height: 580px; margin-top: 40px;" /> <br> <br>
<canvas id="dialog_chart" style="visibility:hidden;"></canvas>
</div>
</code></pre>
<p>How can I reload the image after creating a new chart?</p>
| 3 | 1,214 |
Why is this happening?
|
<p>I am trying to create a remote-desktop monitor application using java where a server can see the screenshot of the client and also can monitor the number of processes running on the client. Here is the screenshot of the user interface</p>
<p><img src="https://i.stack.imgur.com/rPNw5.png" alt="enter image description here"></p>
<p>But now I have a bug which I can't fix. I have debugged it several times but I couldn't find a way to track the bug. Here are the problems which I am facing right now:=</p>
<p>1) When I press the "GET PROCESS LIST" button nothing happens. The process list is fetched to the textarea when the capture button is pressed i.e First I have to press the "GET PROCESS LIST" then I have to press the capture button for the list of processes to show up. </p>
<p>2) When I press the capture button it only captures the screenshot of the client once. After that when I press the capture button it doesn't do anything. Same is with the Get Process Button. They only get executed once. </p>
<p>I have tried debugging both the client and the server but failed to track the bug.</p>
<p>Here is my code for client and server. The code for server is big but I have to provide the whole code as because I don't know where the problem actually lies. </p>
<p>This is the client </p>
<pre><code>public class ScreenClient {
private static BufferedImage screen;
public static void main(String[] args) {
try {
Socket server = new Socket("localhost", 5494);
while (true) {
BufferedReader bf = new BufferedReader(new InputStreamReader(server.getInputStream()));
String s;
s = bf.readLine();
System.out.println(s);
if (s.contains("execute")) {
ImageThread im=new ImageThread();
im.start();
}
if (s.contains("getProcessList")) {
ProcessThread pt=new ProcessThread();
pt.start();
}
}
} catch (Exception e) {
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
public static class ImageThread extends Thread {
@Override
public void run() {
try {
Socket server = new Socket("localhost", 9999);//connect to server at port 9999 for screenshots
Robot robot = new Robot();
Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
screen = robot.createScreenCapture(size);
int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];
screen.getRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
OutputStream baseOut = server.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baseOut);
out.writeObject(size);
//for (int x = 0; x < rgbData.length; x++) {
out.writeObject(rgbData);
// }
out.flush();
server.close();
//added new
} catch (Exception e) {
e.printStackTrace();
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
}
public static class ProcessThread extends Thread {
@Override
public void run() {
System.out.println("\n\n********");
StringBuilder builder = new StringBuilder("");
Socket server;
PrintWriter ps;
String query = "tasklist";
try {
server = new Socket("localhost", 9898);//connect to server at port 9898 for process list
Runtime runtime = Runtime.getRuntime();
InputStream input = runtime.exec(query).getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
while ((line = commandResult.readLine()) != null) {
builder.append(line + "\n");
}
//byte[] responseClient=s.getBytes();
System.out.println("Obj ::" + server);
ps = new PrintWriter(server.getOutputStream());
ps.write(builder.toString());
System.out.println(builder.toString());
ps.flush();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>Here is the Server's code:=</p>
<pre><code>public class ScreenServer extends JFrame implements ActionListener {
String uname;
BufferedReader br;
static JTextArea taMessages, taUserList, taProcessList;
JTextField tfInput;
static Socket client, client1,client2;//
JButton btnCapture, btnExit, btnGetUsers, btnGetProcess;
static HashMap<String, Socket> users = new HashMap<>();
static ArrayList<Socket> usersSockets = new ArrayList();
PrintWriter os;
PrintWriter os2;
public static void main(String[] args) throws Exception {
ScreenServer screenServer = new ScreenServer();
screenServer.buildInterface();
ServerSocket server = new ServerSocket(5494);
ServerSocket s1 = new ServerSocket(9898);
ServerSocket s2=new ServerSocket(9999);
while (true) {
ScreenServer.client = server.accept();
users.put(client.getInetAddress().getHostName(), client);
usersSockets.add(client); //not needed
InetAddress inet1 = client.getInetAddress();
broadcast(inet1.getHostName(), " Has connected!");
client1=s2.accept();//accept connection on port 9999
ScreenshotThread st = new ScreenshotThread(client1);
st.start();
client2=s1.accept();//accept connection on port 9898
ProcessListClient clientProcessList = new ProcessListClient(client2);
clientProcessList.start();
}
}
public void buildInterface() {
btnCapture = new JButton("Capture Screen");
btnExit = new JButton("Exit");
btnGetUsers = new JButton("Get Users");
btnGetProcess = new JButton("Get Process List");
//chat area
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
taProcessList = new JTextArea();
taProcessList.setRows(10);
taProcessList.setColumns(50);
taProcessList.setEditable(false);
//online users list
taUserList = new JTextArea();
taUserList.setRows(10);
taUserList.setColumns(10);
taUserList.setEditable(false);
//top panel (chat area and online users list
JScrollPane chatPanel = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane onlineUsersPanel = new JScrollPane(taUserList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane processPanel = new JScrollPane(taProcessList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JPanel tp = new JPanel(new FlowLayout());
tp.add(chatPanel);
tp.add(onlineUsersPanel);
tp.add(processPanel);
add(tp, "Center");
//user input field
tfInput = new JTextField(50);
//buttom panel (input field, send and exit)
JPanel bp = new JPanel(new FlowLayout());
bp.add(tfInput);
bp.add(btnCapture);
bp.add(btnExit);
bp.add(btnGetUsers);
bp.add(btnGetProcess);
add(bp, "South");
btnCapture.addActionListener(this);
tfInput.addActionListener(this);//allow user to press Enter key in order to send message
btnExit.addActionListener(this);
btnGetUsers.addActionListener(this);
btnGetProcess.addActionListener(this);
setSize(500, 300);
setVisible(true);
pack();
}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == btnExit) {
System.exit(0);
} else if (tfInput.getText().contains("!getusers")) {
taUserList.setText(" ");
this.getUsersOnline();
} else if (evt.getSource() == btnCapture) {
MessagesThread mt = new MessagesThread(client);
mt.start();
}
if (evt.getSource() == btnGetUsers) {
taUserList.setText("");
System.out.println("ERROR--> No Client Connection Found");
}
if (evt.getSource() == btnGetProcess) {
GetProcessThread gt = new GetProcessThread(client);
gt.start();
}
}
private void getUsersOnline() {
Iterator it = users.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
putUserOnline((String) pairs.getKey());
}
}
public static void broadcast(String user, String message) {
putMessage(user, message);
}
public static void putMessage(String uname, String msg) {
taMessages.append(uname + ": " + msg + "\n");
}
public static void putUserOnline(String name) {
taUserList.setText(name + ": " + "\n");
}
public class MessagesThread extends Thread {
Socket client;
public MessagesThread(Socket client) {
this.client = client;
}
@Override
public void run() {
String ClientName = tfInput.getText();
try {
String response = "execute";
Socket clientValue = users.get(ClientName);
os = new PrintWriter(clientValue.getOutputStream(), true);
os.println(response);
} catch (IOException ex) {
Logger.getLogger(ScreenServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//here
public class GetProcessThread extends Thread {
Socket client;
public GetProcessThread(Socket client) {
this.client = client;
}
@Override
public void run() {
String ClientName = tfInput.getText();
try {
String response = "getProcessList";
Socket clientValue = users.get(ClientName);
os2 = new PrintWriter(clientValue.getOutputStream(), true);
os2.println(response);
} catch (IOException ex) {
Logger.getLogger(ScreenServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//here
static class ScreenshotThread extends Thread {
BufferedImage screen;
Socket client;
public ScreenshotThread(Socket client) {
this.client=client;
}
@Override
public void run() {
try {
Robot robot = new Robot();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
Rectangle size = (Rectangle) in.readObject();
int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];
/* for (int x = 0; x < rgbData.length; x++) {
rgbData[x] = in.readInt();
}*/
rgbData=(int[])in.readObject();
screen = new BufferedImage((int) size.getWidth(), (int) size.getHeight(), BufferedImage.TYPE_INT_ARGB);
screen.setRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
InetAddress clientAddress = client.getInetAddress();
String clientName = clientAddress.getHostName();
String t = (new Date()).toString();
ImageIO.write(screen, "png", new File(clientName + ".png"));
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
static class ProcessListClient extends Thread {
Socket client;
BufferedReader is;
public ProcessListClient(Socket s1) {
this.client=s1;
}
@Override
public void run() {
StringBuilder stringBuilder = new StringBuilder("");
try {
this.is = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = "";
while ((line = is.readLine()) != null) {
stringBuilder.append(line + "\n");
}
System.out.println(stringBuilder);
taProcessList.setText(stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>I think I have stated all the issues and provided relevant code.I would really appreciate any help. :)</p>
| 3 | 6,144 |
ipython notebook freeze on start
|
<p>my ipython notebook functionality stop working.
If I do</p>
<p>ipython notebook</p>
<p>the console just hangs forever with no debug output.
I have already tried reinstalling ipython but no success.
Also, if I start normal ipython everything seems fine.</p>
<p>Does anybody have a clue how to solve this? I suspect some lock file is still there but how can I find out what is exactly going wrong? </p>
<p>also if I force interrupt I get the following stack trace</p>
<pre><code>^C^CTraceback (most recent call last):
File "/home/lfiaschi/anaconda/bin/ipython", line 9, in <module>
load_entry_point('ipython==1.2.1', 'console_scripts', 'ipython')()
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/__init__.py", line 118, in start_ipython
return launch_new_instance(argv=argv, **kwargs)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 544, in launch_instance
app.initialize(argv)
File "<string>", line 2, in initialize
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/terminal/ipapp.py", line 312, in initialize
super(TerminalIPythonApp, self).initialize(argv)
File "<string>", line 2, in initialize
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/core/application.py", line 373, in initialize
self.parse_command_line(argv)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/terminal/ipapp.py", line 307, in parse_command_line
return super(TerminalIPythonApp, self).parse_command_line(argv)
File "<string>", line 2, in parse_command_line
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 474, in parse_command_line
return self.initialize_subcommand(subc, subargv)
File "<string>", line 2, in initialize_subcommand
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 89, in catch_config_error
return method(app, *args, **kwargs)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/config/application.py", line 405, in initialize_subcommand
subapp = import_item(subapp)
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/utils/importstring.py", line 42, in import_item
module = __import__(package, fromlist=[obj])
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/html/notebookapp.py", line 64, in <module>
from .services.kernels.kernelmanager import MappingKernelManager
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/html/services/kernels/kernelmanager.py", line 21, in <module>
from IPython.kernel.multikernelmanager import MultiKernelManager
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/kernel/__init__.py", line 6, in <module>
from .connect import *
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/kernel/connect.py", line 39, in <module>
from IPython.utils.localinterfaces import LOCALHOST
File "/home/lfiaschi/anaconda/lib/python2.7/site-packages/IPython/utils/localinterfaces.py", line 43, in <module>
PUBLIC_IPS = socket.gethostbyname_ex(socket.gethostname() + '.local')[2]
KeyboardInterrupt
</code></pre>
| 3 | 1,351 |
SQL Display results only if the row exists in another table
|
<p>Is there a way to display results only if that particular value exists, if there are multiple entries of it in another table?</p>
<p>For example, I am trying to display teacher name only if the type is Math. If there are no entries of Math, the column Teacher should display none.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>UserName U</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Me</td>
<td>row@1.com</td>
</tr>
<tr>
<td>Wiz</td>
<td>bow@1.com</td>
</tr>
</tbody>
</table>
</div><div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Classes C</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>Me</td>
</tr>
<tr>
<td>Second</td>
<td>Me</td>
</tr>
<tr>
<td>Third</td>
<td>Me</td>
</tr>
<tr>
<td>Third</td>
<td>Wiz</td>
</tr>
</tbody>
</table>
</div><div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Classes</th>
<th>Teacher T</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>A</td>
<td>Math</td>
</tr>
<tr>
<td>Second</td>
<td>B</td>
<td>Math</td>
</tr>
<tr>
<td>Third</td>
<td>C</td>
<td>NULL</td>
</tr>
</tbody>
</table>
</div>
<p>Final result as Math Classes exist for Me</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>UserName</th>
<th>Email</th>
<th>Teacher</th>
</tr>
</thead>
<tbody>
<tr>
<td>Me</td>
<td>row@1.com</td>
<td>A</td>
</tr>
<tr>
<td>Me</td>
<td>row@1.com</td>
<td>B</td>
</tr>
</tbody>
</table>
</div>
<p>Final result as Math Classes exist for Wiz with no math classes</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>UserName</th>
<th>Email</th>
<th>Teacher</th>
</tr>
</thead>
<tbody>
<tr>
<td>Wiz</td>
<td>bow@1.com</td>
<td>None</td>
</tr>
</tbody>
</table>
</div>
<p>The issue I'm running into is that my query is displaying either no entries even though user has no math but has other classes, or it's displaying Math and None at the same time.</p>
<p>My current query is as follows:</p>
<pre><code>from User u
join classes c on c.username=u.username
join teachers t on t.classes=c.classes and type ='Math' <---- If I left join, I get 2 entries, if I join, I get 0 entries for non-math folks
where username ='Me'
</code></pre>
<p>So the 3 scenarios I want the query to cover:</p>
<ol>
<li><p>If user does not exist in the user table (no entry)</p>
</li>
<li><p>If user exists but doesn't have any math (show user None entry)</p>
</li>
<li><p>If user exists and has math (regardless of any other type) display classes - final situation up there</p>
</li>
</ol>
<p>Do I do some kind of select count in the case statement? This query is part of a bigger execution query.</p>
<p>This was SQL Server Management Studio</p>
| 3 | 1,157 |
Auth0: `state` does not match on FireFox
|
<p>I have developed a web app using React, using Auth0 for authentication process. I have encountered a problem - every time I successfully login into the web app, when I refresh the page, it would throw the error:</p>
<blockquote>
<p>'state' does not match</p>
</blockquote>
<p>Here is my <code>Auth.js</code>:</p>
<pre><code>class Auth {
constructor() {
this.link = 'https://mywebapp.com'
this.auth0 = new auth0.WebAuth({
domain: <MY_DOMAIN>',
audience: <AUDIENCE_LINK>,
clientID: <CLIENT_ID>,
redirectUri: `${this.link}/callback`,
responseType: 'token id_token',
scope: 'openid email profile'
});
this.getProfile = this.getProfile.bind(this);
this.handleAuthentication = this.handleAuthentication.bind(this);
this.isAuthenticated = this.isAuthenticated.bind(this);
this.signIn = this.signIn.bind(this);
this.signOut = this.signOut.bind(this);
}
getProfile() {
return this.profile;
}
getIdToken() {
return this.idToken;
}
isAuthenticated() {
return new Date().getTime() < this.expiresAt;
}
signIn() {
this.auth0.authorize({}, (err, authResult) => {
if (err) this.localLogout();
else {
this.localLogin(authResult);
this.accessToken = authResult.accessToken;
}
});
}
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (err) {
alert(err.errorDescription)
this.signOut()
return reject(err);
}
if (!authResult || !authResult.idToken) {
return reject(err);
}
this.setSession(authResult);
resolve();
});
})
}
setSession(authResult) {
this.idToken = authResult.idToken;
this.profile = authResult.idTokenPayload;
this.expiresAt = authResult.idTokenPayload.exp * 1000;
}
signOut() {
// clear id token, profile, and expiration
this.auth0.logout({
returnTo: `${this.link}`,
clientID: <CLIENT_ID>,
});
}
silentAuth() {
return new Promise((resolve, reject) => {
this.auth0.checkSession({}, (err, authResult) => {
if (err) return reject(err);
this.setSession(authResult);
resolve();
});
});
}
}
</code></pre>
<p>Here is my React router setup:</p>
<pre><code>const SecureRoute = (props) => {
const {component: Component, path, checkingSession } = props;
return (
<Route path={path} render={() => {
if (checkingSession) return <div>Loading...</div>
if (!auth0Client.isAuthenticated()) {
auth0Client.signIn();
return <div></div>;
}
return <Component />
}} />
)
}
class AppStack extends Component {
constructor(props) {
super(props);
this.state = {
checkingSession: true
}
}
async componentDidMount() {
if (this.props.location.pathname === '/callback') {
this.setState({checkingSession:false})
return;
}
try {
await auth0Client.silentAuth();
this.forceUpdate();
} catch (err) {
if (err.error !== 'login_required') console.log(err.error);
}
this.setState({checkingSession:false})
}
render() {
return (
<div className="site-wrap">
<AppHeader />
<div className="main">
<Switch>
<Route exact path="/" render={() => <Redirect to="/dashboard"/>} />
<SecureRoute exact path="/dashboard" component={Dashboard} checkingSession={this.state.checkingSession}/>
<SecureRoute exact path="/project" component={Project} checkingSession={this.state.checkingSession}/>
<SecureRoute exact path="/project/:page" component={Project} checkingSession={this.state.checkingSession}/>
<SecureRoute exact path="/profile" component={Profile} checkingSession={this.state.checkingSession}/>
<SecureRoute exact path="/profile/:page" component={Profile} checkingSession={this.state.checkingSession}/>
<Route exact path="/signout" component={Signout}/>
<Route exact path='/callback' component={Callback}/>
<Route component={NoMatch} />
</Switch>
</div>
</div>
)
}
}
</code></pre>
<p>Here is the screening of the problem:
<a href="https://www.loom.com/share/0c25158cf6b54db288a7c94987f8bb9a" rel="nofollow noreferrer">https://www.loom.com/share/0c25158cf6b54db288a7c94987f8bb9a</a></p>
<p>Any reason why I am getting this error when I refresh the page ?</p>
<p>Thanks for any advice !</p>
| 3 | 2,266 |
Get facebook friends list of logged user
|
<p>I want to get the Facebook friends for the user who has already logged in via the Facebook widget that it is integrated with my app.</p>
<p>I created an activity that retrieves the friends list, however it doesn't work for me. (I also have the Facebook ID of the logged in user in the <code>String id</code> variable).</p>
<pre><code>public class FreindsActivity extends Activity {
Facebook mFacebook;
String name,password,email,id,phone,emailOwner;
AsyncFacebookRunner mAsyncRunner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
Intent intent = getIntent();
name = intent.getExtras().getString("name");
password = intent.getExtras().getString("password");
email = intent.getExtras().getString("email");
id = intent.getExtras().getString("id");
phone = intent.getExtras().getString("phone");
emailOwner=intent.getExtras().getString("emailOwner");
mFacebook=new Facebook(id);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mAsyncRunner.request("me/friends", new FriendsRequestListener());
//Bundle params = new Bundle();
// params.putString("fields", "name,id");
}
public class FriendsRequestListener implements com.facebook.android.AsyncFacebookRunner.RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response)
{
try
{
// process the response here: executed in background thread
JSONObject json = Util.parseJson(response);
JSONArray friendsData = json.getJSONArray("data");
String ids[]=new String[friendsData.length()] , names[] = new String[friendsData.length()];
for(int i = 0; i < friendsData .length(); i++){
ids[i] = friendsData .getJSONObject(i).getString("id");
names[i] = friendsData .getJSONObject(i).getString("name");
}
}
catch (JSONException e)
{
}
}
@Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try
{
JSONObject json = Util.parseJson(response);
JSONArray friendsData = json.getJSONArray("data");
String ids[]=new String[friendsData.length()] , names[] = new String[friendsData.length()];
for(int i = 0; i < friendsData .length(); i++){
ids[i] = friendsData .getJSONObject(i).getString("id");
names[i] = friendsData .getJSONObject(i).getString("name");
}
}
catch (JSONException e){
}
}
@Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
@Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
}
</code></pre>
<p>LogCat:</p>
<pre><code>03-13 17:24:33.396: E/AndroidRuntime(846): FATAL EXCEPTION: Thread-107
03-13 17:24:33.396: E/AndroidRuntime(846): com.facebook.android.FacebookError: An active access token must be used to query information about the current user.
03-13 17:24:33.396: E/AndroidRuntime(846): at com.facebook.android.Util.parseJson(Util.java:272)
03-13 17:24:33.396: E/AndroidRuntime(846): at com.example.salebook.FreindsActivity$FriendsRequestListener.onComplete(FreindsActivity.java:87)
03-13 17:24:33.396: E/AndroidRuntime(846): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:276)
</code></pre>
<p>thanks</p>
| 3 | 1,823 |
HTTP status code 419 when accessing Laravel api by browser
|
<p>I can't access my laravel api post routes at localhost by browser (script / console / dev-tools). I'm always getting HTTP 419 (Page Expired) status error. Interestingly I can access the api with success via postman.</p>
<p>The routes are outside of everey "auth:sanctum" group, so that this should not be the cause of failure. Because of this I also think that sessions and session config could not be the cause, could they?</p>
<pre><code>// routes/api.php
Route::post('/test', function() {
return "Hello World @ POST";
}); // => HTTP 419
Route::get('/test', function() {
return "Hello World @ GET";
}); // => HTTP 200
</code></pre>
<p>I excluded the path from xsrf-checks, to exclude this error cause:</p>
<pre><code>// VerifyCsrfToken.php
protected $except = [
'api/test',
];
</code></pre>
<p>The script I run in firefox console:</p>
<pre><code>await fetch("http://localhost:8000/api/test", {
"method": "POST"
});
</code></pre>
<p>The HTTP request firefox sends to localhost:</p>
<pre><code>POST /api/test HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0
Accept: */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://127.0.0.1:8000/
Origin: http://127.0.0.1:8000
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
Content-Length: 0
</code></pre>
<p>What can I do to get my api running in the browser?</p>
<p><strong>EDIT#1</strong></p>
<p>app/http/kernel.php</p>
<pre><code><?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
</code></pre>
| 3 | 1,752 |
Cannot bundle update & install in a redmine migration
|
<p>I migrated to Debian 9 a Redmine application v 2.5.0. After copying all files, it is impossible to bundle update or install.</p>
<p>I have installed <code>default-libmysqlclient-dev</code> and then <code>gem install mysql</code>
but without success.</p>
<p>Bundle update give this output:</p>
<pre><code>Your Gemfile lists the gem activerecord-jdbcmysql-adapter (>= 0) more than once.
You should probably keep only one of them.
While it's not a problem now, it could cause errors if you change the version of one of them later.
Fetching gem metadata from https://rubygems.org/..............
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies...
Using rake 12.3.2 (was 10.1.1)
Using concurrent-ruby 1.1.5
Using multi_json 1.13.1 (was 1.9.2)
Using builder 3.0.0
Using erubis 2.7.0
Using journey 1.0.4
Using rack 1.4.7 (was 1.4.5)
Using hike 1.2.3
Using tilt 1.4.1
Using mime-types 1.25.1
Using polyglot 0.3.5 (was 0.3.4)
Using arel 3.0.3
Using tzinfo 0.3.55 (was 0.3.39)
Using bundler 1.13.6
Using mini_portile2 2.4.0
Using ffi 1.10.0
Using coderay 1.1.2 (was 1.1.0)
Using json 1.8.6 (was 1.8.1)
Using thor 0.20.3 (was 0.18.1)
Using metaclass 0.0.4
Installing mysql 2.8.1 with native extensions
Using mysql2 0.3.21 (was 0.3.15)
Using net-ldap 0.3.1
Installing pg 1.1.4 (was 0.17.1) with native extensions
Using ruby-openid 2.3.0
Using redcarpet 2.3.0
Using rmagick 3.0.0 (was 2.13.2)
Using rubyzip 1.2.2
Using shoulda-context 1.0.2
Installing sqlite3 1.4.0 (was 1.3.9) with native extensions
Using yard 0.9.18 (was 0.8.7.3)
Using i18n 0.9.5 (was 0.6.9)
Using rack-cache 1.9.0 (was 1.2)
Using rack-test 0.6.3 (was 0.6.2)
Using rack-ssl 1.3.4 (was 1.3.3)
Using sprockets 2.2.3 (was 2.2.2)
Using treetop 1.4.15
Using nokogiri 1.10.2
Using childprocess 0.9.0
Using rdoc 3.12.2
Using mocha 1.8.0 (was 1.0.0)
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory: /var/lib/gems/2.3.0/gems/mysql-2.8.1/ext/mysql_api
/usr/bin/ruby2.3 -r ./siteconf20190326-30772-4a7i24.rb extconf.rb
checking for mysql_ssl_set()... yes
checking for rb_str_set_len()... yes
checking for rb_thread_start_timer()... no
checking for mysql.h... yes
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details. You may
need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
--with-mysql-config
--without-mysql-config
extconf.rb:67:in `<main>': uninitialized constant Config (NameError)
Did you mean? RbConfig
CONFIG
To see why this extension failed to compile, please check the mkmf.log which can be found here:
/var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/mysql-2.8.1/mkmf.log
extconf failed, exit code 1
Gem files will remain installed in /var/lib/gems/2.3.0/gems/mysql-2.8.1 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/mysql- 2.8.1/gem_make.out
An error occurred while installing mysql (2.8.1), and Bundler cannot continue.
Make sure that `gem install mysql -v '2.8.1'` succeeds before bundling.
</code></pre>
<p>When I try to install bundle, I have the same error as bellow: </p>
<pre><code>An error occurred while installing json (1.8.1), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.
</code></pre>
| 3 | 1,489 |
In JQuery check if window.open streamed file contents to a new window sucessfully
|
<p>When a user clicks on a document icon, I am opening/streaming the document in a new window using window.open. The call returns windowObjectReference which gives me access to the child window. However if the child window failed to open a document such as a pdf in a pdf viewer because it was not installed on the local machine, how can I determine that the document failed to open in a suitable viewer such as PDF Viewer or Word etc. The code below shows the javascript function I am using.</p>
<pre><code>function LoadDocument(id) {
$.ajax({
cache: false,
type: "GET",
url: 'Dashboard/GetDocument',
contentType: 'application/json',
data: { "id": id },
success: function (data, textStatus, jqXHR) {
doc = data;
if (data !== undefined) {
if (doc.Result == true) {
var windowObjectReference = window.open("data:" + doc.ContentType + ";base64, " + doc.Document, '', 'height=650,width=840,resizable,scrollbars=yes,status=1');
if (windowObjectReference === undefined) {
var a = document.createElement("a");
a.href = "data:application/octet-stream;charset=utf-8;base64," + doc.Document;
a.download = doc.Filename;
document.body.appendChild(a);
a.click();
}
}
else {
alert('Unable to obtain the document from the database.');
}
}
else
{
alert('Unable to load the document.');
}
},
error: function (xhr) {
alert("Error occurred while loading the avatar image. "
+ xhr.responseText);
}
});
}
</code></pre>
<p>The windowObjectReference returns an object instance even when a document fails to load in a new window. Is there some other way to check if the window.open method failed?</p>
| 3 | 1,049 |
Can not correct to display data from ms sql tables in datagridview
|
<p>No idea how to fix that.
So i have an imported table (screenshot) <strong>Patient</strong> (# 1) and <strong>Diagnoz</strong> (Diagnosis) (# 2) from the MS SQL Server. The first table contains a complete list of patient data and a foreign key for the id_diagnoz in which the Stage and Name_diagnoz is indicated.
Table (# 3) is a ready-made option for outputting data without unnecessary columns, but this is not a problem.<code>"select Pacient.id_patient, Pacient.Name, Pacient.Surname, Pacient.Middle_name, Pacient.Age, Pacient.Legal_address_Clinic, Diagnoz.Name_diagnoz, Diagnoz.Stage FROM Pacient JOIN Diagnoz ON Diagnoz.id_diagnoz = Pacient.id_diagnoz";</code> That's work well.</p>
<hr>
<p><em>The problem is</em> that when filling in the data from the textboxes and comboboxes, I need to first generate an id_diagnoz from the table (# 2) and with it add the other info to the patient table (# 1). However, I could not manage to do this for several hours, because even the error did not lead. Therefore, I decided to separately add the id_diagnoz to the empty table (# 4) to make sure that my query is working.
Please, help me with this id_diagnoz and other data put into the patient table.</p>
<pre><code> private void button5_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R551818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + comboBox2.Text + "' and Stage = '" + comboBox3.Text + "'" +
"INSERT INTO Pacient (Name, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age)" +
" VALUES (@Name, @Surname, @Middle, @Passport, @AddresClinic, @Age) ", conn);
comm.SelectCommand.Parameters.AddWithValue("@Name", textBox3.Text);
comm.SelectCommand.Parameters.AddWithValue("@Surname", textBox4.Text);
comm.SelectCommand.Parameters.AddWithValue("@Middle", textBox5.Text);
comm.SelectCommand.Parameters.AddWithValue("@Passport", maskedTextBox1.Text);
comm.SelectCommand.Parameters.AddWithValue("@AddresClinic", comboBox1.Text);
comm.SelectCommand.Parameters.AddWithValue("@Age", textBox7.Text);
DataSet ds = new DataSet();
comm.Fill(ds);
//da.Fill(ds, "Pacient");
dataGridView2.DataSource = ds.Tables[0];
conn.Close();
conn.Open();
}}
</code></pre>
<p><a href="https://i.stack.imgur.com/FTc9J.png" rel="nofollow noreferrer">Screenshot for understanding</a></p>
| 3 | 1,085 |
Is it possible to access a field value in one collection from another collection in firestore?
|
<p>Is it possible to access/pass field value(in this case gamerroomname) of Allusers collection from/to another collection(in this case gamerooms)?</p>
<p>so that I can do below:</p>
<pre><code>ref.collection("GameRooms").document(gameroomname).addSnapshotListener(){
}
</code></pre>
<p>Screenshot of Allusers:
<a href="https://i.stack.imgur.com/uy5sM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uy5sM.png" alt="enter image description here"></a></p>
<p>Screenshot of Gamerooms:</p>
<p><a href="https://i.stack.imgur.com/kZ6gY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kZ6gY.png" alt="enter image description here"></a></p>
<p>After trying,the below code works.But is this the correct way to do this or is there any way better:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> mFirestore.collection("AllUsers").document(SplitString(currentUser.email!!)).get().addOnSuccessListener(OnSuccessListener<DocumentSnapshot> { documentSnapshot ->
var gameRoomName: String = ""
if (documentSnapshot.exists()) {
gameRoomName = documentSnapshot.getString("gameroomname")!!
}
mFirestore.collection("GameRooms").document(gameRoomName).collection("Words called").addSnapshotListener(EventListener<QuerySnapshot>(){ queryDocumentSnapshot, e->
selectedWordsList.clear()
if (!queryDocumentSnapshot!!.isEmpty) {
val gameRoomList = queryDocumentSnapshot.documents
for (doc: DocumentSnapshot in gameRoomList) {
var addWord: String = ""
if (doc.get("addword") != null) {
addWord = doc.get("addword").toString()
}
val selectedGameRoomList: SelectedWordsObject = SelectedWordsObject(addWord, false)
selectedWordsList.add(selectedGameRoomList)
mSelectedWordsAdapter.notifyDataSetChanged()
}
mSelectedWordsAdapter.notifyItemChanged(0)
}
else {
Toast.makeText(this@Screen, "Document does not exist", Toast.LENGTH_LONG).show()
}
})
}).addOnFailureListener(OnFailureListener { e->
val error=e.message
Toast.makeText(this@Screen,"Error:"+error, Toast.LENGTH_LONG).show()
})</code></pre>
</div>
</div>
</p>
| 3 | 1,190 |
nr. bound variables, missmatch number tokens
|
<p>Hi I have been scanning the answers on this subject but they seem to be individual at most, so here goes. My code is from a free repository and it works when I remove the addition I have maid.</p>
<p>I added "uname" because I wanted the users to be greeted by their name and not their username. It may be stupied but I like it this way. But I am missing something. My code is here:</p>
<pre><code> <?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['username']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// This if statement checks to determine whether the edit form has been submitted
// If it has, then the account updating code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Make sure the user entered a valid E-Mail address
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// If the user is changing their E-Mail address, we need to make sure that
// the new value does not conflict with a value that is already in the system.
// If the user is not changing their E-Mail address this check is not needed.
if($_POST['email'] != $_SESSION['username']['email'])
{
// Define our SQL query
$query = "
SELECT
*
FROM admin_users
WHERE
email = :email
";
// Define our query parameter values
$query_params = array(
':email' => $_POST['email'],
':uname' => $_POST['uname']
);
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Retrieve results (if any)
$row = $stmt->fetch();
if($row)
{
die("This E-Mail address is already in use");
}
}
// If the user entered a new password, we need to hash it and generate a fresh salt
// for good measure.
if(!empty($_POST['password']))
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
}
else
{
// If the user did not enter a new password we will not update their old one.
$password = null;
$salt = null;
}
// Initial query parameter values
$query_params = array(
':email' => $_POST['email'],
':uname' => $_POST['uname'],
':user_id' => $_SESSION['username']['id'],
);
// If the user is changing their password, then we need parameter values
// for the new password hash and salt too.
if($password !== null)
{
$query_params[':password'] = $password;
$query_params[':salt'] = $salt;
}
// Note how this is only first half of the necessary update query. We will dynamically
// construct the rest of it depending on whether or not the user is changing
// their password.
$query = "
UPDATE admin_users
SET
uname = :uname
email = :email
username = :username
";
// If the user is changing their password, then we extend the SQL query
// to include the password and salt columns and parameter tokens too.
if($password !== null)
{
$query .= "
, password = :password
, salt = :salt
";
}
// Finally we finish the update query by specifying that we only wish
// to update the one record with for the current user.
$query .= "
WHERE
id = :user_id
";
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Now that the user's E-Mail address has changed, the data stored in the $_SESSION
// array is stale; we need to update it so that it is accurate.
$_SESSION['username']['email'] = $_POST['email'];
// This redirects the user back to the members-only page after they register
header("Location: private.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to private.php");
}
?>
<?php include("header.php"); ?>
<?php include("menu.php"); ?>
<div id="header_wrapper">
<h1>Edit Account</h1>
<form action="edit_account.php" method="post">
Username:<br />
<b><?php echo htmlentities($_SESSION['username']['username'], ENT_QUOTES, 'UTF-8'); ?></b>
<br /><br />
Navn:<br />
<input type="text" name="uname" value="<?php echo htmlentities($_SESSION['username']['uname'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
Brugernavn:<br />
<input type="text" name="username" value="<?php echo htmlentities($_SESSION['username']['username'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
E-Mail Address:<br />
<input type="text" name="email" value="<?php echo htmlentities($_SESSION['username']['email'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" /><br />
<i>(leave blank if you do not want to change your password)</i>
<br /><br />
<input type="submit" value="Update Account" />
</form>
</div>
<?php include("footer.php"); ?>
</code></pre>
<p>The error</p>
<blockquote>
<p>Error: "Failed to run query: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"</p>
</blockquote>
| 3 | 3,479 |
Combine items from different rows in database and display them in one row on listview
|
<p>I have items in a database. The columns are ID, Region, and Report. I display all these in an asp listview. I need combine each of these items and display them in one row for each id. So for example if ID = testuser Regions = 1, 2 Reports = A, B</p>
<p>Right now the list displays something like this:</p>
<p>testuser | 1 | A</p>
<p>testuser | 1 | B</p>
<p>testuser | 2 | A</p>
<p>testuser | 2 | B</p>
<p>I want it to be:</p>
<p>testuser | 1,2 | A,B</p>
<p>Here is the front end: </p>
<pre><code><ItemTemplate>
<tr class="tableRow">
<td class="value">
<asp:Label runat="server" ID="lblCWSID" Text='<%# Eval("CwsId") %>'></asp:Label>
</td>
<td class="value">
<asp:Label ID="lblRegion" runat="server" Text='<%# Eval("Regions") %>'></asp:Label>
</td>
<td class="value" style="width: 70px">
<asp:Label ID="lblReport" runat="server" Text='<%# Eval("Reports") %>'></asp:Label>
</td>
<td class="value" style="width: 50px">
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/App_Themes/Default/Images/edit-icon.png"
OnCommand="btnEdit_User" CommandArgument='<%# Eval("CWSID") %>' Height="20px"
Width="20px" />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/App_Themes/Default/Images/remove-icon.png"
OnCommand="btnDelete_User" CommandArgument='<%# Eval("CWSID") %>' Height="20px"
Width="20px" />
</td>
</tr>
</ItemTemplate>
</code></pre>
<p>Here is the backend:</p>
<pre><code> /// <summary>
/// Add a user to the list and then rebind
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lbSaveUser_Click(object sender, CommandEventArgs e)
{
List<string> selectedRegions = RegionsCheckBox.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
List<string> selectedReports = ReportsCheckBox.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
try
{
if (String.IsNullOrWhiteSpace(txtCWSID.Text))
{
this.lblError.Text = "Please enter a valid CWS ID";
return;
}
if (Common.GetUserCwsId() == txtCWSID.Text.Trim())
{
this.lblError.Text = "It would not be a good idea to block yourself from the site";
return;
}
ReportPermissionsFactory.DeleteReportPermissionUser(txtCWSID.Text, Common.GetConnectionString());
foreach (string Region in selectedRegions)
{
foreach (string Report in selectedReports)
{
ReportPermissionsFactory.InsUpdReportPermissions(txtCWSID.Text.Trim(),Region, Report, Common.GetConnectionString());
}
}
txtCWSID.Text = String.Empty;
BindList();
}
catch (Exception ex)
{
Logger.HandleException(Common.GetUserCwsId(), Projects.GlobalSizingTool, "ReportPermissionsUsers", "lbAddUser_Click", ex, Common.GetConnectionString());
this.lblError.Text = "There was an error completing your request. Please try again.";
}
}
</code></pre>
<p>Here is how the data gets loaded:</p>
<pre><code>internal static List<ReportPermissions> LoadData(string connectionString, bool refresh = false)
{
string cacheItem = "ReportPermissionsFactory";
ObjectCache cache = MemoryCache.Default;
if (refresh)
{
cache.Remove(cacheItem);
}
List<ReportPermissions> l = cache[cacheItem] as List<ReportPermissions>;
if (l == null || l.Count == 0)
{
l = new List<ReportPermissions>();
Database db = DatabaseFactory.CreateDatabase(connectionString);
DbCommand wrapper = db.GetStoredProcCommand("usp_GetReportPermissionsUsers");
IDataReader reader = db.ExecuteReader(wrapper);
using (wrapper)
{
using (reader)
{
while (reader.Read())
{
ReportPermissions obj = new ReportPermissions();
obj.CwsId= SizingDBLayer.Utilities.GetDBFieldString(reader["CwsId"]);
obj.Regions = SizingDBLayer.Utilities.GetDBFieldString(reader["RegionCode"]);
obj.Reports = SizingDBLayer.Utilities.GetDBFieldString(reader["Reports"]);
l.Add(obj);
}
}
}
cache.Add(cacheItem, l, new DateTimeOffset(DateTime.Now.AddMinutes(5)));
}
return l;
}
</code></pre>
| 3 | 2,608 |
BackgroundMediaPlayer not playing music files outside Music Folder
|
<p>I am having this strange issue. I am trying to create a music player app for <code>Windows Phone 8.1</code>. I need the music player to play the music in background, even if the application is in background/closed state. So I am using the <a href="https://msdn.microsoft.com/en-us/windows.media.playback.backgroundmediaplayer" rel="nofollow noreferrer"><strong>BackgroundMediaPlayer</strong></a> class for playing the music. Following is the code for the same:</p>
<pre><code>private void SendMessageToBackground(string Path, string Name, bool IsRadio)
{
if (!string.IsNullOrEmpty(Path))
{
var message = new ValueSet();
message.Add(Constants.TrackURI, Path);
message.Add(Constants.TrackName, Name);
message.Add(Constants.IsRadio, IsRadio);
BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
BackgroundMediaPlayer.Current.MediaFailed += Current_MediaFailed;
BackgroundMediaPlayer.SendMessageToBackground(message);
}
}
</code></pre>
<p>The code works all fine, the music is playing smoothly. But now I am facing an issue. I am fetching the music files in the application by looping through all folders. Hence it displays all music files, wherever they are in the folder hierarchy. But when I am trying to play a file outside the <code>Music</code> folder created by the windows phone(refer screenshot), the background music player simply doesn't play the file.</p>
<p><a href="https://i.stack.imgur.com/kAP2k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kAP2k.jpg" alt="Music File Issue"></a></p>
<p>As seen in the code I am listening to events from the <code>BackgroundMediaPlayer</code> and its <code>MediaPlayer</code> to check for any possible failure reasons, but both these events are not getting triggered in case of a failed playback. But the <code>BackgroundMediaPlayer</code>'s <code>MessageReceivedFromBackground</code> event is getting triggered correctly in case of successful playbacks(from Music folder). I checked the file path being passed, and it was all correct, and I tried playing these music files using the inbuilt Music app of the phone, and that too played successfully. What can be the possible problem here? How can I solve it?</p>
<p><strong>EDIT</strong></p>
<p>I debugged further and figured out that it is actually an permission issue. The path passed from the above code, I was using in another function, to pass the <code>Uri</code>/<code>StorageFile</code> to the <code>BackgroundMediaPlayer.Current</code>. Code:</p>
<pre><code>public async void StartTrackAt(string TrackURI, string Name)
{
try
{
BackgroundMediaPlayer.Current.SetUriSource(new Uri(TrackURI)); // This works fine in debug mode. Throws Exception in release mode
/* Tried this also, but this doesn't even work in debug mode
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(TrackURI);
mediaPlayer.SetFileSource(s);
*/
}
catch (Exception ex)
{
//Control comes here when trying to play files outside Music folder.
}
}
</code></pre>
<p>I have set the required capabilities in the app's manifest file. But I got the following <code>Exception</code> when I tried to run this application:</p>
<pre><code>{System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at BackgroundMusicPlayer.MyPlayListManager.<StartTrackAt>d__0.MoveNext()}
[System.UnauthorizedAccessException]: {System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at BackgroundMusicPlayer.MyPlayListManager.<StartTrackAt>d__0.MoveNext()}
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
HResult: -2147024891
InnerException: null
Message: "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
Source: "mscorlib"
StackTrace: " at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at BackgroundMusicPlayer.MyPlayListManager.<StartTrackAt>d__0.MoveNext()"
</code></pre>
<p>Strangely enough, when passing the <code>Uri</code> directly without fetching the <code>StorageFile</code>, it works well in debug mode.</p>
<p>Here are the capabilities I have set for the application:</p>
<p><a href="https://i.stack.imgur.com/SbGWs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SbGWs.png" alt="App Capabilities"></a></p>
| 3 | 1,630 |
How to implement a bespoke recaptcha in rails?
|
<p>Though using existing gems to add a recaptcha to every single form is a pretty simple affair, I can't work out how to create recaptcha as described by the diagram below.</p>
<pre><code> |
user submits question form <-------
| |
V |
============================= |
| Are the attributes valid? | ----> NO
=============================
|
YES
|
V
===============================================================
| Has user submitted more than 4 forms in the last 5 minutes? | --NO---|
=============================================================== |
| |
YES |
| |
redirect them to recaptcha form |
| |
V V
============================ ************************************
| Captcha form incorrect? | -- NO ----------> * save the form as a record *
============================ * and redirect user to see it *
| ^ ************************************
YES |
| NO
V |
==================================================
| Have they been redirected to the captcha form |
| more than 5 times in the last minute? |
==================================================
|
YES
|
V
*******************
* TEMPORARY BLOCK *
*******************
</code></pre>
<p>I just can't do figure out how to do it. Where is the submitted data saved, for example, while the user fills out the captcha form? In the session? In the cache? In a cookie? Any pointers on how this could be achieved?</p>
<p>I am thinking some sort of function in the application controller, triggered by a <code>before_action</code> all hook. Every time this action is called (i.e whenever a user requests a link of my app) the action is time-stamped in an array of time stamps. When this array is filled with say 10 time stamps, we work out the average, and it's under x amount we block them. This would stop crawlers as well as spammers. </p>
<p><code>However, I still want to let google, yahoo! and bing in!</code> And why not the internet way back machine? <strong><em>I don't want to compromise my app.</em></strong> There's lots of little nuances I need to know before I jump into this.</p>
<p>Here's the behavior I want to implement in a nutshell:</p>
<p>*<em>If the user is sending x number of requests in y number of seconds, redirect them to a recaptcha page. If they pass the recaptcha, let them continue as normal. *</em></p>
<p>I'm open to both visual and logic (question based) recaptchas, just want a solution other than adding a recaptcha to every single form...</p>
<p>Also, I don't like using Gems as they feel like blackboxes to me. Much prefer doing it myself. However, I do like versitile gems like state machine and carrierwave, so if there's an open ended-recaptcha gem I'm open to that.</p>
| 3 | 1,351 |
Object acceleration not behaving as expected
|
<p>I have two objects in a 2D space. I expect <code>object1</code> to begin orbiting <code>object2</code>. I derived my methods from the equation</p>
<blockquote>
<p>f = G * (m1 * m2 / r*r)</p>
</blockquote>
<p>and</p>
<blockquote>
<p>dx1 += x1 - x2 * f</p>
</blockquote>
<p>etc. However, I am struggling because the object is only moving in the pos pos direction. Here is the class for each object:</p>
<h3>Mass.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.Point;
public class Mass {
public static float G = 0.1f;
public Point center;
public float mass, radius, dx = 0, dy = 0;
public boolean locked = false;
public Mass(Point center, float[] vect, float mass) {
this.center = center;
this.dx = vect[0];
this.dy = vect[1];
this.mass = mass;
this.radius = mass;
}
public void moveVector(float[] vector) {
if(!this.locked) {
this.dx += vector[0];
this.dy += vector[1];
}
}
public void lock() {
this.locked = true;
}
public static float distance(Mass obj1, Mass obj2) {
float dX = obj1.center.x - obj2.center.x;
float dY = obj1.center.y - obj2.center.y;
double ans = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
return (float) ans;
}
public static float force(Mass obj1, Mass obj2) {
double ans = ((obj1.mass * obj2.mass) / Math.pow(distance(obj1, obj2), 2)) * G;
return (float) ans;
}
public static float[] vector(Mass obj1, Mass obj2) {
// total change between the two objects
float force = force(obj1, obj2);
float totalX = Math.abs(obj1.center.x - obj2.center.x);
float totalY = Math.abs(obj1.center.y - obj2.center.y);
float x = totalX * force;
float y = totalY * force;
float[] vector = {x, y};
return vector;
}
}
</code></pre>
<p>This is the main class.</p>
<h3>Sim.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sim extends JPanel {
private static final long serialVersionUID = -2669101810074157675L;
public static final int PREF_W = 800, PREF_H = 600;
private Mass object1, object2;
private Sim() {
this.setFocusable(true);
this.setBackground(Color.WHITE);
float[] vect1 = {0, -1}, vect2 = {0, 0};
object1 = new Mass(new Point(PREF_W / 2 - 100, PREF_H / 2 - 100), vect1, 10);
object2 = new Mass(new Point(PREF_W / 2 + 100, PREF_H / 2 + 100), vect2, 30);
gameTimer.start();
}
private Timer gameTimer = new Timer(1000/30, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
object1.moveVector(Mass.vector(object1, object2));
object1.center.x += object1.dx;
object1.center.y += object1.dy;
System.out.println("[" + object1.dx + "," + object1.dy + "]");
}
});
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.fillOval(
(int) object1.center.x - (int) object1.radius,
(int) object1.center.y - (int) object1.radius,
(int) object1.radius,
(int) object1.radius
);
g2.fillOval(
(int) object2.center.x - (int) object2.radius,
(int) object2.center.y - (int) object2.radius,
(int) object2.radius,
(int) object2.radius
);
g2.drawLine(object1.center.x, object1.center.y, object2.center.x, object2.center.y);
repaint();
}
/* METHODS FOR CREATING JFRAME AND JPANEL */
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Gravity Simulation");
JPanel gamePanel = new Sim();
frame.getContentPane().add(gamePanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
</code></pre>
<p>I have it printing out the DX and DY of <code>object1</code> (the unlocked object) at all times. It seems to get flung super fast, as expected, but it never slows down. Instead, the dx is just increasing slower and slower. I'm not very mathy, but it seems to be logistic. I wonder why this is happening.</p>
<p>So far I have tried rewriting my formula and using a different equation. I have also attempted using different datatypes, and making some things negative. Nothing works, though.</p>
<p>TLDR, the problem:
Objects are not changing DX / DY as expected.</p>
<p>Thank you in advance! Sorry if this was posted somewhere else, I could not find any duplicates.</p>
| 3 | 2,366 |
transfer learning of Inception v3 returns the same predictions
|
<p>I have tried to customize inception to classify. I used the cat, dog, human and other to classify cat, dog, human ( collection of family photos) and other (mostly natural scenes) I have about 2000 dog, 1000 cat, 7000 human and 3000 images split 80:20 among the train and validate. The essence of model is as below. When I train the training accuracy is close to 97% and validation accuracy is ~90%.</p>
<pre><code> import os
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.applications.inception_v3 import InceptionV3
local_weights_file = 'C:/users/sethr/education/Healthcare/imagedetect/modelimageadvance /inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(input_shape = (150, 150,3), include_top = False, weights = `enter code here`local_weights_file)
for layer in pre_trained_model.layers:
layer.trainable = False
# pre_trained_model.summary()
last_layer = pre_trained_model.get_layer('mixed7')
#print('last layer output shape: ', last_layer.output_shape)
last_output = last_layer.output
# Flatten the output layer to 1 dimension
x = tf.keras.layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = tf.keras.layers.Dense(512, activation='relu')(x)
x = tf.keras.layers.Dense(256, activation='relu')(x)
# Add a dropout rate of 0.2
x = tf.keras.layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = tf.keras.layers.Dense(4, activation='softmax')(x)
model = Model(pre_trained_model.input, x)
model.compile(optimizer = RMSprop(lr=0.0001), loss = 'categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(train_generator,validation_data = validation_generator,steps_per_epoch = 20,epochs = 20,validation_steps = 25,verbose = 2)
model.save("dcho.rp5")
___________________
import numpy as np
import cv2
import glob
from keras.preprocessing import image
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
labels= ["cat","dog","human","other"]
path='C:/Users/sethr/education/Healthcare/imagedetect/images/*.jpg'
for fim in glob.glob(path):
# predicting images
img=image.load_img(fim, target_size=(150, 150))
x=image.img_to_array(img)
x=np.expand_dims(x, axis=0)
images = np.vstack([x])
plt.figure()
plt.imshow(img)
plt.show()
classes = model.predict(images,batch_size=10)
________________________________________________________
_______________________________________________________
# All images will be rescaled by 1./255.
train_datagen = ImageDataGenerator( rescale = 1.0/255. )
test_datagen = ImageDataGenerator( rescale = 1.0/255. )
# --------------------
# Flow training images in batches of 20 using train_datagen generator
# --------------------
train_generator = train_datagen.flow_from_directory(train_dir,
batch_size=20,
shuffle='True',
class_mode='categorical',
target_size=(150, 150))
# --------------------
# Flow validation images in batches of 20 using test_datagen generator
# --------------------
validation_generator = test_datagen.flow_from_directory(validation_dir,
target_size = (150, 150),
batch_size=20,
class_mode='categorical',
shuffle='True',
)
_______________________________________________________________
</code></pre>
<p>The problem is it is returning always human as prediction.. I played around with Adam, Adjusted learning rate but still the prediction remains the same. Any insight.</p>
| 3 | 1,877 |
Volley: Kotlin Class call from JavaCode
|
<p>I'd like to make simple Volley POST Requests due Java and Kotlin. I'm using both languages in my App so I tried do to my best to use both languages.
I came over <a href="https://medium.com/@nishinraj/simplifying-volley-requests-kotlin-development-1bb87c3fb6f8" rel="nofollow noreferrer">this</a> tutorial with the following VolleyClass in Kotlin:</p>
<p>class WolfRequest(val url: String,
val result: (JSONObject) -> Unit,
val error: (String) -> Unit) {</p>
<pre><code>fun POST(vararg params: Pair<String, Any>) {
// HashMap to pass arguments to Volley
val hashMap = HashMap<String, String>()
params.forEach {
// Convert all Any type to String and add to HashMap
hashMap[it.first] = it.second.toString()
}
// Make the Http Request
makeRequest(Request.Method.POST, hashMap)
}
private fun makeRequest(method: Int, params: HashMap<String, String>) {
// Creating a StringRequest
val req = object : StringRequest(method, url, { res ->
// Creating JSON object from the response string
// and passing it to result: (JSONObject) -> Unit function
result(JSONObject(res.toString().trim()))
}, { volleyError ->
// Getting error message and passing it
// to val error: (String) -> Unit function
error(volleyError.message!!)
}) {
// Overriding getParams() to pass our parameters
override fun getParams(): MutableMap<String, String> {
return params
}
}
// Adding request to the queue
volley.add(req)
}
// For using Volley RequestQueue as a singleton
// call WolfRequest.init(applicationContext) in
// app's Application class
companion object {
var context: Context? = null
val volley: RequestQueue by lazy {
Volley.newRequestQueue(context
?: throw NullPointerException(" Initialize WolfRequest in application class"))
}
fun init(context: Context) {
this.context = context
}
}
</code></pre>
<p>}</p>
<p>I'm trying to access this Code from a Java.Class to make a POST Reuqest:</p>
<pre><code> WolfRequest.Companion.init(getApplicationContext());
HashMap <String, String> params = new HashMap <> ();
params.put("id", "123");
new WolfRequest(config.PING_EVENTS,*new WolfRequest()*
{
public void response(JSONObject response) {
Log.e("Ping","PING");
}
public void error(String error) {
Log.e("Ping",error);
}
}).POST(params);
</code></pre>
<p>It gives me an error here (<em>new WolfRequest()</em>) saying: Cannot inherit from final "...wolfrequest.kt"</p>
<p>I really don't get the error, what's the problem here?</p>
<p>Thank you</p>
| 3 | 1,084 |
OpenCV 4.1 with CUDA in python uses wrong OpenCV version
|
<p>I'm trying to install opencv 4.1 to use in python WITH Cuda support. I tried following <a href="https://gist.github.com/raulqf/f42c718a658cddc16f9df07ecc627be7" rel="nofollow noreferrer">this guide</a> and had preinstalled CUDA 10 (because I needed it with keras and this works already), but when checking opencv in python using following code</p>
<pre><code>import cv2 as cv
print(cv.__version__)
print(cv.getBuildInformation())
</code></pre>
<p>But it returns the wrong open cv version AND unavailable cuda libraries:</p>
<pre><code>3.2.0
General configuration for OpenCV 3.2.0 =====================================
Version control: unknown
Extra modules:
Location (extra): /build/opencv-L2vuMj/opencv-3.2.0+dfsg/contrib/modules
Version control (extra): unknown
Platform:
Timestamp: 2018-09-20T09:28:13Z
Host: Linux 4.4.0-135-generic x86_64
CMake: 3.10.2
CMake generator: Unix Makefiles
CMake build tool: /usr/bin/make
Configuration: Release
C/C++:
Built as dynamic libs?: YES
C++ Compiler: /usr/bin/c++ (ver 7.3.0)
C++ flags (Release): -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG
C++ flags (Debug): -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
C Compiler: /usr/bin/cc
C flags (Release): -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG
C flags (Debug): -g -O2 -fdebug-prefix-map=/build/opencv-L2vuMj/opencv-3.2.0+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -Wno-comment -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -msse -msse2 -mno-avx -mno-sse3 -mno-ssse3 -mno-sse4.1 -mno-sse4.2 -ffunction-sections -fvisibility=hidden -g -O0 -DDEBUG -D_DEBUG
Linker flags (Release): -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now
Linker flags (Debug): -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now
ccache: NO
Precompiled headers: NO
Extra dependencies: /usr/lib/x86_64-linux-gnu/libwebp.so gdcmMSFF /usr/lib/x86_64-linux-gnu/libImath.so /usr/lib/x86_64-linux-gnu/libIlmImf.so /usr/lib/x86_64-linux-gnu/libIex.so /usr/lib/x86_64-linux-gnu/libHalf.so /usr/lib/x86_64-linux-gnu/libIlmThread.so /usr/lib/libgdal.so gtk-3 gdk-3 pangocairo-1.0 pango-1.0 atk-1.0 cairo-gobject cairo gdk_pixbuf-2.0 gio-2.0 gobject-2.0 glib-2.0 gthread-2.0 dc1394 avcodec avformat avutil swscale avresample gphoto2 gphoto2_port /usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5.so /usr/lib/x86_64-linux-gnu/libpthread.so /usr/lib/x86_64-linux-gnu/libsz.so /usr/lib/x86_64-linux-gnu/libdl.so /usr/lib/x86_64-linux-gnu/libm.so vtkRenderingOpenGL vtkImagingHybrid vtkIOImage vtkCommonDataModel vtkCommonMath vtkCommonCore vtksys vtkCommonMisc vtkCommonSystem vtkCommonTransforms vtkCommonExecutionModel vtkDICOMParser vtkIOCore /usr/lib/x86_64-linux-gnu/libz.so vtkmetaio /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/x86_64-linux-gnu/libpng.so /usr/lib/x86_64-linux-gnu/libtiff.so vtkImagingCore vtkRenderingCore vtkCommonColor vtkFiltersExtraction vtkFiltersCore vtkFiltersGeneral vtkCommonComputationalGeometry vtkFiltersStatistics vtkImagingFourier vtkalglib vtkFiltersGeometry vtkFiltersSources vtkInteractionStyle vtkRenderingLOD vtkFiltersModeling vtkIOPLY vtkIOGeometry vtkFiltersTexture vtkRenderingFreeType /usr/lib/x86_64-linux-gnu/libfreetype.so vtkftgl vtkIOExport vtkRenderingAnnotation vtkImagingColor vtkRenderingContext2D vtkRenderingGL2PS vtkRenderingContextOpenGL /usr/lib/x86_64-linux-gnu/libgl2ps.so vtkRenderingLabel tesseract lept dl m pthread rt tbb
3rdparty dependencies:
OpenCV modules:
To be built: core flann hdf imgproc ml photo reg surface_matching video viz freetype fuzzy imgcodecs shape videoio highgui objdetect plot superres ts xobjdetect xphoto bgsegm bioinspired dpm face features2d line_descriptor saliency text calib3d ccalib datasets rgbd stereo stitching videostab ximgproc aruco optflow phase_unwrapping structured_light java python2 python3
Disabled: world contrib_world
Disabled by dependency: tracking
Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cnn_3dobj cvv dnn matlab sfm
GUI:
QT: NO
GTK+ 3.x: YES (ver 3.22.30)
GThread : YES (ver 2.56.2)
GtkGlExt: NO
OpenGL support: NO
VTK support: YES (ver 6.3.0)
Media I/O:
ZLib: /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.11)
JPEG: /usr/lib/x86_64-linux-gnu/libjpeg.so (ver )
WEBP: /usr/lib/x86_64-linux-gnu/libwebp.so (ver encoder: 0x020e)
PNG: /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.6.34)
TIFF: /usr/lib/x86_64-linux-gnu/libtiff.so (ver 42 - 4.0.9)
JPEG 2000: NO
OpenEXR: /usr/lib/x86_64-linux-gnu/libImath.so /usr/lib/x86_64-linux-gnu/libIlmImf.so /usr/lib/x86_64-linux-gnu/libIex.so /usr/lib/x86_64-linux-gnu/libHalf.so /usr/lib/x86_64-linux-gnu/libIlmThread.so (ver 2.2.0)
GDAL: /usr/lib/libgdal.so
GDCM: YES (ver 2.8.4)
Video I/O:
DC1394 1.x: NO
DC1394 2.x: YES (ver 2.2.5)
FFMPEG: YES
avcodec: YES (ver 57.107.100)
avformat: YES (ver 57.83.100)
avutil: YES (ver 55.78.100)
swscale: YES (ver 4.8.100)
avresample: YES (ver 3.7.0)
GStreamer: NO
OpenNI: NO
OpenNI PrimeSensor Modules: NO
OpenNI2: NO
PvAPI: NO
GigEVisionSDK: NO
Aravis SDK: NO
UniCap: NO
UniCap ucil: NO
V4L/V4L2: NO/YES
XIMEA: NO
Xine: NO
gPhoto2: YES
Parallel framework: TBB (ver 2017.0 interface 9107)
Other third-party libraries:
Use IPP: NO
Use IPP Async: NO
Use VA: NO
Use Intel VA-API/OpenCL: NO
Use Lapack: NO
Use Eigen: YES (ver 3.3.4)
Use Cuda: NO
Use OpenCL: YES
Use OpenVX: NO
Use custom HAL: NO
OpenCL: <Dynamic loading of OpenCL library>
Include path: /usr/include/CL
Use AMDFFT: NO
Use AMDBLAS: NO
Python 2:
Interpreter: /usr/bin/python2.7 (ver 2.7.15)
Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.15rc1)
numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.13.3)
packages path: lib/python2.7/dist-packages
Python 3:
Interpreter: /usr/bin/python3 (ver 3.6.5)
Libraries: /usr/lib/x86_64-linux-gnu/libpython3.6m.so (ver 3.6.5)
numpy: /usr/lib/python3/dist-packages/numpy/core/include (ver 1.13.3)
packages path: lib/python3.6/dist-packages
Python (for build): /usr/bin/python2.7
Java:
ant: /usr/bin/ant (ver 1.10.3)
JNI: /usr/lib/jvm/default-java/include /usr/lib/jvm/default-java/include/linux /usr/lib/jvm/default-java/include
Java wrappers: YES
Java tests: NO
Matlab: Matlab not found or implicitly disabled
Documentation:
Doxygen: /usr/bin/doxygen (ver 1.8.13)
Tests and samples:
Tests: NO
Performance tests: YES
C/C++ Examples: YES
Install path: /usr
cvconfig.h is in: /build/opencv-L2vuMj/opencv-3.2.0+dfsg/obj-x86_64-linux-gnu
-----------------------------------------------------------------
</code></pre>
<p>Altough in cmake-gui when generating the cmake, cuda WAS enabled and opencv was effectively version 4.1.</p>
<p>Any ideas? Thanks in advance!</p>
<p>PS. I didn't use pip to install opencv, but I built it from source</p>
| 3 | 5,644 |
error in the statement (Build.VERSION_CODES.JELLY_BEAN)
|
<p>this is the utility java class to check which version of android is being used....but there is an error in the statement @interface TargetApi(Build.VERSION_CODES.JELLY_BEAN)...what may be the possible reasons and how can I remove it??</p>
<pre><code>package com.example.ishan.complainbox;
/**
* Created by ishan on 11/04/2017.
*/
import android.os.Build;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.DialogInterface;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
@interface TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED)
{
if
(ActivityCompat.shouldShowRequestPermissionRationale((MainActivity) context,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
AlertDialog.Builder alertBuilder = new
AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is
necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity)
context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((MainActivity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else
{
return true;
}
}
}
</code></pre>
| 3 | 1,055 |
Emacs Orgmode table $> References does not work
|
<p><strong>GNU Emacs 24.4.1 org-mode</strong></p>
<p>Here is an org-mode table</p>
<pre><code>#+TBLNAME: revenue
| / | < | | < | | < | | | | | | | | | | | |
| Product | Year_SUM | Month_SUM | Platform | Platform_SUM | adwo | AdMob | adChina | adSage | appfigures | appdriver | coco | Domob | Dianru | Limei | guohead | youmi |
| | | | | | | | | | | | | | | | | |
|---------+----------+-----------+----------+------------------+------+-------+---------+--------+------------+-----------+------+-------+--------+-------+---------+-------|
| Jan | | | iOS | #ERROR | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| | | | Android | =vsum($6..$>);NE | | 1 | | 1 | | 1 | | 1 | | 1 | | 1 |
|---------+----------+-----------+----------+------------------+------+-------+---------+--------+------------+-----------+------+-------+--------+-------+---------+-------|
| | | | | | | | | | | | | | | | | |
#+TBLFM: $5=vsum($6..$>);NE
</code></pre>
<p>As you see ,the formula <code>$5=vsum($6..$>);NE</code> can't be calculated! Here is debug info: </p>
<pre><code>Substitution history of formula
Orig: vsum($6..$>)
$xyz-> vsum($6..$>)
@r$c-> vsum($6..$>)
$1-> vsum((0)..$>)
--------^
Error: Expected `)'
</code></pre>
<p>But if I replace the formula with <code>$5=vsum($6..$17)</code> and then it works ,I can't figure out where is the problem? </p>
<p>I need some help ,appreciate it!</p>
| 3 | 1,192 |
Why is my websocket-client stopping all of my subsequent code, and what can I do about it?
|
<p>I am setting up a python program to pull cryptocurrency data from binance, but the websocket that I am using pauses all code after it executes.</p>
<pre><code>import websockets
import websocket, json
import asyncio
def establishDefaultConnection():
#websocket.enableTrace(True)
def on_open(message):
ws.send(loginStr)
print("The default connection was opened")
def pipeData(ws, message):
print(message)
def on_error(ws, message):
print(message)
def on_close(message):
print("She gone")
# Declare some variables
socket = "wss://stream.binance.us:9443/stream?streams="
loginStr = '{"method": "SUBSCRIBE","params": ["btcusd@kline_1m","btcusd@kline_3m"],"id": 1}'
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=pipeData, on_error=on_error, on_close=on_close)
ws.run_forever()
establishDefaultConnection())
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Code was executed later>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
</code></pre>
<p>The print command will never run, nor will anything after the command "ws.run_forever()". In this web-sockets <a href="https://websocket-client.readthedocs.io/en/latest/app.html#websocket._app.WebSocketApp.run_forever" rel="nofollow noreferrer">documentation</a>, that command in stated to be a loop, but I can't tell what its looping on.</p>
<p>I have tried setting up an asynchronous operation, but that hasn't worked out yet - though that could be my fault, since I am still learning how to use asyncio</p>
<p>Any help here would be much appreciated - I will be online for the next 2 hours to immediately answer questions or talk about this issue.</p>
<p>EDIT: I want to note that this websocket does indeed work - it streams in data just fine, but no other code runs. Also, any comments about my methodology would also be appreciated - again, I'm new to python and network/asynchronous coding.</p>
| 3 | 1,053 |
Subtracting arrays more efficiently
|
<p>I have a few questions. Got this array:</p>
<pre><code>$array_1 = array(
"1" => "4",
"2" => "8",
"3" => "12",
"4" => "16",
"5" => "20",
"6" => "24",
"7" => "28",
"8" => "32",
"9" => "36",
"10" => "40",
"11" => "44",
"12" => "48",
"13" => "52",
"14" => "56",
"15" => "60",
"16" => "64",
"17" => "68",
"18" => "72",
"19" => "76",
"20" => "80",
"21" => "84",
"22" => "88",
"23" => "92",
"24" => "96",
"25" => "100",
"26" => "104",
"27" => "108",
"28" => "112",
"29" => "116",
"20" => "120",
"31" => "124",
"32" => "128",
"33" => "132",
"34" => "136",
"35" => "140",
"36" => "144",
"37" => "148",
"38" => "152",
"39" => "156",
"40" => "160",
"41" => "164",
"42" => "168",
"43" => "172",
"44" => "176",
"45" => "180",
"46" => "184",
"47" => "188",
"48" => "192",
"49" => "196",
"50" => "200"
);
</code></pre>
<p>I would like to subtract <code>$array_1</code> by 1,2,3,4 into multiple arrays. So far I have done it by having other arrays:</p>
<pre><code>$array_2 = array(
"1" => "1",
"2" => "1",
...
"49" => "1",
"50" => "1"
);
$array_3 = array(
"1" => "2",
"2" => "2",
...
"49" => "2",
"50" => "2"
);
// All the way to values of 4
</code></pre>
<p>Then with this I would do an <code>array_diff</code> to get the lowered value.</p>
<p>I was wondering firstly is there a better way (more efficient) to have the array subtract rather than repeat the 1,2,3,4 50 times each.</p>
<p>Secondly, is there a more efficient way to have <code>$array_1</code> have the values of multiple of 4 up to 200?</p>
<p>Thirdly, do I need an array to subtract from <code>$array_1</code> to lower the value? Is there a better way to this like: <code>$array_1 - 1</code></p>
<p><strong>INTENDED OUTPUT</strong></p>
<pre><code>// $array_1 - $array_2 (value of 1)
$minus_one = array(
"1" => "3",
"2" => "7",
"3" => "11",
...
);
// $array_1 - $array_3 (value of 2)
$minus_two = array(
"1" => "2",
"2" => "6",
"3" => "10",
...
);
// $array_1 - $array_4 (value of 3)
$minus_one = array(
"1" => "1",
"2" => "4",
"3" => "8",
...
);
</code></pre>
| 3 | 1,368 |
Performance issues updating multiple UI elements every second
|
<p><strong>EDIT</strong>: I've posted my solution below, (basically, ListViews are very slow for some reason), and will try to update it further if I can clarify why exactly a ListView is so awful in this situation.</p>
<p><strong>Objective:</strong></p>
<p>Get 7 ListView objects showing 7 independently set clocks/timers which update/tick every second. These clocks are just Strings with a calculated elapsed time shown (SystemClock.ElapsedRealTime() - stored ElapsedRealTime() of when the object was instantiated.)</p>
<p><strong>The problem:</strong></p>
<p>Basically, 8 minutes into these 7 clocks ticking away - my program is essentially useless.. the information presented is inaccurate, the UI is pretty much unresponsive, etc. Here are some results of testing against the benchmark of a physical stopwatch:</p>
<ul>
<li>At 04:00, clocks are slipping 1 second, and updating every 4 seconds.</li>
<li>At 06:00, clocks are slipping 3 seconds, and updating every 5 seconds.</li>
<li>At 08:00, clocks are slipping 6-7 seconds, and updating every 6 seconds.</li>
<li>At 16:00, clocks are slipping 7 seconds, and updating every 10 seconds.</li>
</ul>
<p><strong>What I have so far:</strong></p>
<p>I have a custom class, ActivityTimer, with a stored long representing the SystemClock.ElapsedRealTime() of when each ActivityTimer was first instantiated. By clicking on a Button 7 times, I instantiate 7 of these, each of which are added to an ArrayList</p>
<p>I have a compound view, ActivityTimerControl, which is passed an ActivityTimer upon instantiation, and then presents data elements of my ActivityTimer in UI elements (such as the ticking clock.) My ArrayAdapter handles this instantiation and works fine. As per <a href="http://developer.android.com/resources/articles/timed-ui-updates.html" rel="nofollow">this fine tutorial</a> I have a _Handler in this ActivityControl, which upon construction of the ActvityControl posts this: </p>
<pre><code>private Runnable _timerUpdateTask = new Runnable()
{
public void run()
{
final long start = _ActivityTimer.getStartTime();
long millis = SystemClock.elapsedRealtime() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10)
{
_tglActivityPauseButton.setTextOn(""+minutes+":0"+seconds);
}
else
{
_tglActivityPauseButton.setTextOn("" + minutes + ":" + seconds);
}
_tglActivityPauseButton.setChecked(true);
_timerUpdateHandler.postDelayed(this, 1000);
}
};
</code></pre>
<p>Other than what I've described my project really doesn't do anything yet, as I've been stuck on this fundamental issue so far. So I haven't posted any other code because I just don't think its relevant beyond the summaries I've given above - but if anyone feels some other part of the project is relevant just let me know and I'll post the detailed code for it. I'm presenting my final String into the SetTextOn() of a ToggleButton, but testing has shown that this isn't a significant factor - it doesn't matter whether I'm setting the Text of a normal TextView, or what, no matter what I've tried my results are always roughly the same, with noticable lag on each clock and eventually the UI becoming unresponsive completely. </p>
<p>My understanding is that a Handler is supposed to be the most efficient way of updating a UI element on a consistent and frequent basis, replacing java.util.Timer, but despite this my code starts out slow and just gets worst the longer I let it run.</p>
<p>Even upon increasing the postDelay to 5000ms, the same problems still occured and the app still force closed after 49 minutes. Since I would have thought this test would have extended the time til force-close by 5, if not fixing it altogether (at the detriment to the functionality I want), I'm suspecting that something isn't recycling right with the handler or some other component.</p>
<p><strong>My Questions:</strong></p>
<ul>
<li>I suspect my problem is in having 7 objects (ActivityControls), each of which has <em>its own</em> Handler constantly cycling the update of the corresponding time that's displayed. Does anyone have experience to say if this would be the case? </li>
<li>Is there a way I can have a <em>single</em> Handler that calls upon each ActivityControl in my ListView to update its time? </li>
<li>Does posting a message to the Handler leave some memory trace that doesn't dispose automatically, or might benefit from being forced to dispose?</li>
<li>Does anyone else have other ideas about the most efficient way of running constant UI updates on multiple objects?</li>
</ul>
| 3 | 1,356 |
Passing data from Adapter to Item's ViewModel in Android
|
<p>I have a view pager with an adapter that has a number of items fetched from the cloud. I add the pages to the adapter through the fragment.
I am trying to pass a variable to the Item's view model every time a new page is instantiated from the adapter so as to notify one of the views that depend on this view model. I have tried a few workarounds but nothing has been successful so far. Would anyone please advice how I may pass this data.</p>
<p>Below is my adapter</p>
<pre><code>public class HelpPagerAdapter extends PagerAdapter {
private final List<HelpPage> mHelpPages;
private int currentPage = 0;
public HelpPagerAdapter(Context context) {
mPages = new ArrayList<>();
}
@Override
public int getCount() {
return mHelpPages.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
HelpPage helpPage = mHelpPages.get(position);
currentPage = position;
LayoutInflater inflater = (LayoutInflater) container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewDataBinding binding = DataBindingUtil.inflate(inflater, helpPage.getLayout(), container, false);
binding.setVariable(helpPage.getViewModelBindingId(), helpPage.getViewModel());
container.addView(binding.getRoot());
return binding.getRoot();
}
public void addPage(@LayoutRes int layout, Object viewModel, int viewModelBindingId) {
mHelpPages.add(new HelpPage(layout, viewModel, viewModelBindingId));
}
private class HelpPage {
private final @LayoutRes int mLayout;
private final Object mViewModel;
private final int mViewModelBindingId;
HelpPage(@LayoutRes int layout, Object viewModel, int viewModelBindingId) {
mLayout = layout;
mViewModel = viewModel;
mViewModelBindingId = viewModelBindingId;
}
@LayoutRes int getLayout() {
return mLayout;
}
Object getViewModel() {
return mViewModel;
}
int getViewModelBindingId() {
return mViewModelBindingId;
}
}
}
</code></pre>
<p>Part of my fragment code</p>
<pre><code> @Override
public void onAttach(Context context) {
super.onAttach(context);
Bundle bundle = getArguments();
if (bundle == null || (!bundle.containsKey(ARG_STEPS) && !bundle.containsKey(ARG_VIEWS))) {
throw new IllegalStateException("HelpFragment cannot be initialised without views");
}
HelpPagerAdapter adapter = new HelpPagerAdapter(getContext());
if (bundle.containsKey(ARG_STEPS)) {
List<Step> steps = Parcels.unwrap(bundle.getParcelable(ARG_STEPS));
adapter = addHelpPages(steps, adapter);
}
mHelpViewModel = new HelpViewModel(adapter);
}
private HelpPagerAdapter addHelpPages(List<Step> steps, HelpPagerAdapter adapter) {
for (Step step : steps) {
adapter.addPage(R.layout.layout_help, new HelpItemViewModel(step), BR.viewModel);
}
return adapter;
}
</code></pre>
<p>Part of my ViewModel</p>
<pre><code>public class HelpItemViewModel {
private final String mText;
private final String mVideoId;
private final String mImageUrl;
public HelpItemViewModel(Step step) {
mText = step.getText();
mHelpId = step.getHelpId();
mImageUrl = step.getImage();
}
}
</code></pre>
| 3 | 1,200 |
Connection problem when changing password
|
<p>I have a software which displays some tables from our SQL database. Now I want to add a tool, where I can change the password for my "testdummy" user.</p>
<p>I tried to open a connection again but it didn't help. If you need some additional code or informations, just write a comment.</p>
<p>Notice that I'm new to programming. I'm a apprentice and currently learning programming and administer databases. I know this is not the safest solution, but it's just a little task from my instructor. This software will not be released for customers.</p>
<p>Like I mentioned before, I tried to open a connection again before I want to change the password.</p>
<pre><code> public void Change()
{
SqlConnection con = new SqlConnection();
string connectionString = GetConnectionString();
if (NewPassword.Password == NewPasswordAgain.Password && OldPassword.Password == GlobalData.Password)
{
try
{
//dbMan.TryConnect(connectionString);
//con.Open();
SqlConnection.ChangePassword($"Data Source={GlobalData.ServerName};Initial Catalog={GlobalData.DBName};UID={GlobalData.Username};PWD={OldPassword}", $"{NewPassword}");
}
catch (SqlException ex)
{
MessageBox.Show("Unable to change password. Try again!" + ex);
}
}
else
{
// If new Password doesn't match.
MessageBox.Show("Passwords doesn't match!");
}
}
</code></pre>
<p>I'm getting a SQL exception when I am trying to change the password.</p>
<pre><code>(System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'csharptest'.
</code></pre>
<p>I get this at:</p>
<pre><code>SqlConnection.ChangePassword($"Data Source={GlobalData.ServerName};Initial Catalog={GlobalData.DBName};UID={GlobalData.Username};PWD={OldPassword}", $"{NewPassword}");
</code></pre>
<p>At this point of the programm, there should be a connection to the database, because I can handle some tables and manipulate the data sets.</p>
<p>But when I uncomment this:</p>
<pre><code>//dbMan.TryConnect(connectionString);
//con.Open();
</code></pre>
<p>It goes into the catch brackets there:</p>
<pre><code>public bool TryConnect(string connectionString)
{
conn = new SqlConnection();
conn.ConnectionString = connectionString;
try
{
conn.Open();
return true;
}
catch (Exception)
{
MessageBox.Show("Couldn't connect");
return false;
}
}
</code></pre>
<p>and returns following exception:</p>
<pre><code>System.InvalidOperationException: 'Die ConnectionString-Eigenschaft wurde nicht initialisiert.'
</code></pre>
<p>In english it should be something like: "the connectionstring property has not been initialized"</p>
<p>Edit:
In the logs I'm getting this:</p>
<pre><code>Login failed for user 'csharptest'. Reason: Password did not match that for the login provided.
</code></pre>
<p>Edit:
Instead of:</p>
<pre><code>SqlConnection.ChangePassword($"Data Source={GlobalData.ServerName};Initial Catalog={GlobalData.DBName};UID={GlobalData.Username};PWD={OldPassword}", $"{NewPassword}");
</code></pre>
<p>I did this:</p>
<pre><code>string updatePassword = "USE CSHARPTEST ALTER LOGIN [" + GlobalData.Username + "] WITH PASSWORD = '" + NewPassword + "'";
con.Open();
cmd.ExecuteNonQuery();
</code></pre>
<p>And now I think the only problem is the permission on the server.</p>
| 3 | 1,451 |
Angular 2 application with refreshing data in real time
|
<p>I am using angular4.</p>
<p>I am trying to Real time update using observable.</p>
<p>Here is my code</p>
<p>First i import <code>observable</code></p>
<pre><code> import { Observable } from 'rxjs/Rx';
import { AnonymousSubscription } from "rxjs/Subscription";
import { ApiServiceProvider } from '../../providers/api-service/api-service';
constructor(public apiService:ApiServiceProvider){}
ngOnInit(){
this.getAllNeighbours();
}
getAllNeighbours(){
//Get Apartment User
this.addNeighbours=[];
this.postsSubscription=this.apiService.getApartmentUser(this.currentUserApartId).subscribe(users=>{
var apartmentUsers=users.json();
this.subscribeToData();
//Get Apartments flats
this.apiService.getApartmentFlats(this.currentUserApartId).subscribe(flats=>{
var apartmentFlats=flats.json();
for(var i in apartmentFlats){
if(apartmentFlats[i].USER_ID.toString() != this.currentUserId.toString()){
var filterUser=apartmentUsers.filter(u=>u.id.toString() === apartmentFlats[i].USER_ID.toString());
console.log(filterUser);
if(filterUser.length != 0)
this.addNeighbours.push({
username:filterUser[0].FIRST_NAME + filterUser[0].LAST_NAME,
flatno:apartmentFlats[i].FLAT_NO,
userid:apartmentFlats[i].USER_ID
})
}
if(apartmentFlats[i].TENANT_ID.toString() != this.currentUserId.toString()){
var filterUser=apartmentUsers.filter(u=>u.id.toString() === apartmentFlats[i].TENANT_ID.toString());
if(filterUser.length != 0)
this.addNeighbours.push({
username:filterUser[0].FIRST_NAME + filterUser[0].LAST_NAME,
flatno:apartmentFlats[i].FLAT_NO,
userid:apartmentFlats[i].USER_ID
})
}
}
this.loading=false;
})
});
}
subscribeToData(){
this.timerSubscription = Observable.timer(5000).subscribe(()=>{
this.getAllNeighbours();
})
}
public ngOnDestroy(): void {
if (this.postsSubscription) {
this.postsSubscription.unsubscribe();
}
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
}
</code></pre>
<p>First I get Flats list after I get users list.then i combined data and filter and these values are pushed into <code>addNeighbours</code> array.</p>
<p>I am using <code>this.subscribeToData();</code>.Its used for every time called <code>getAllNeighbours()</code> and update to UI.</p>
<p>Everything is worked fine.My UI is every 5 seconds Update.But at the same time My UI is every 5 seconds like blinking.How can i fix this issue.</p>
<p>Kindly advice me,</p>
<p>Thanks.</p>
| 3 | 1,416 |
Data posting server gets error in swift 3?
|
<p>Here i got a token number from api like as shown here <code>"210"</code> and it is saving using userdefaults but when i tried to retrieve data from the userdefaults then it is returning <code>"\"210\""</code> like this why it is adding slashes and quotes can anyone help me how to resolve this ?</p>
<p>here is the code for posting key</p>
<pre><code>request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.CustomerToken!)", forHTTPHeaderField: "Authorization")
print(self.CustomerToken!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(responseString!)
self.customerCartIdNumber = responseString!
self.customerCartIdNumber = responseString!
UserDefaults.standard.set(self.customerCartIdNumber, forKey: "CustomerLoginNumber")
print(self.customerCartIdNumber!)
print(responseString!)
</code></pre>
<p>here is the code for getting key </p>
<pre><code> let customerId = UserDefaults.standard.string(forKey: "CustomerLoginNumber")
self.customerCartId = customerId!
print(customerId!)
</code></pre>
<p>here is the code for posting</p>
<pre><code>func customerAddToCartItemsDownloadJsonWithURl(cartApi: String){
let url = URL(string: cartApi)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
let cartNumber = customerCartId?.replacingOccurrences(of: "\\", with: "")
let parameters : [String: Any] = ["cartItem":
[
"quote_id": "\(customerCartId!)",
"sku": "\(itemCode!)",
"qty":"1"
]
]
print(customerCartId)
print(parameters)
print(cartNumber)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
}
</code></pre>
| 3 | 1,549 |
Auto select based on number value
|
<p>I am attempting to create a donations form but i am failing at the custom enter amount field.</p>
<p>I have predefined select option which the user can select 5, 7 and 14 but a custom field.</p>
<p><strong>What i want to achieve:</strong></p>
<p>If someone enters <strong>more than 14</strong> in the custom field, it should accept it, if they enter in an amount which is already in the predefined list, it should select the button, if they enter in an amount which is not in that list, it should just prompt an alert.</p>
<p><strong>HTML</strong></p>
<pre><code><form class="donate" novalidate="" autocomplete="on" method="POST">
<div>
<input type="radio" name="amount" id="amount_3" value="3" tabindex="10"/>
<label for="amount_3">£3</label>
</div>
<div>
<input type="radio" name="amount" id="amount_5" value="5" tabindex="10"/>
<label for="amount_5">£5</label>
</div>
<div>
<input type="radio" name="amount" id="amount_10" value="10" tabindex="50"/>
<label for="amount_10">£10</label>
</div>
<div>
<label for="amount_other">Enter Other Amount</label>
<input type="tel" name="amount_other" id="amount_other" placeholder="Enter Other Amount" tabindex="18"/>
</div>
<div>
<input type="checkbox" name="amount_reoccuring" id="amount_reoccuring"/>
<label for="amount_reoccuring"><span></span> Make this a reoccuring donation.</label>
</div>
</form>
</code></pre>
<p><strong>Jquery</strong></p>
<pre><code>$('form').submit(function (e) {
e.preventDefault();
});
$('.amount label').on('click', function () {
var dollarAmount = parseInt($(this).text().replace('£', ''), 10);
var impactAmount = parseInt(dollarAmount / 10, 10);
$('.impact-amount').text('£' + dollarAmount);
$('#amount_other').val('');
});
$('#amount_other').keyup(function () {
var dollarAmount = $(this).val();
var impactAmount = parseInt(dollarAmount / 10, 10);
$('.impact-amount').text('£' + dollarAmount);
$('.amount input[type=radio]').prop('checked', false);
});
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.amount label').on('click', function () {
var dollarAmount = parseInt($(this).text().replace('£', ''), 10);
var impactAmount = parseInt(dollarAmount / 10, 10);
$('.impact-amount').text('£' + dollarAmount);
$('#amount_other').val('');
});
$('#amount_other').keyup(function () {
var dollarAmount = $(this).val();
var impactAmount = parseInt(dollarAmount / 10, 10);
$('.impact-amount').text('£' + dollarAmount);
$('.amount input[type=radio]').prop('checked', false);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="donate" novalidate="" autocomplete="on" method="POST">
<div class="amount">
<input type="radio" name="amount" id="amount_5" value="5" tabindex="10"/>
<label for="amount_5">£5</label>
</div>
<div class="amount">
<input type="radio" name="amount" id="amount_7" value="7" tabindex="10"/>
<label for="amount_7">£7</label>
</div>
<div class="amount">
<input type="radio" name="amount" id="amount_14" value="14" tabindex="50"/>
<label for="amount_14">£14</label>
</div>
<div class="amount">
<label for="amount_other">Enter Other Amount</label>
<input type="tel" name="amount_other" id="amount_other" placeholder="Enter Other Amount" tabindex="18"/>
</div>
<div class="amount">
<input type="checkbox" name="amount_reoccuring" id="amount_reoccuring"/>
<label for="amount_reoccuring"><span></span> Make this a reoccuring donation.</label>
</div>
</form></code></pre>
</div>
</div>
</p>
| 3 | 1,721 |
spark-shell command giving ERROR Shell:397 - Failed to locate the winutils binary in the hadoop binary path java.io.IOException:
|
<p>Could not locate executable null\bin\winutils.exe in the Hadoop binaries. </p>
<p>I have added winutils.exe and all .dll's into C:\Hadoop\bin folder, HADOOP_HOME set to C:\Hadoop and PATH to C:\Hadoop\bin </p>
<p>Trying to run C:\Spark\spark-2.4.0-bin-hadoop2.7\bin>spark-shell command</p>
<p>2019-01-29 12:06:03 ERROR Shell:397 - Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. </p>
<pre><code> at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:379)
at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:394)
at org.apache.hadoop.util.Shell.<clinit>(Shell.java:387)
at org.apache.hadoop.util.StringUtils.<clinit>(StringUtils.java:80)
at org.apache.hadoop.security.SecurityUtil.getAuthenticationMethod(SecurityUtil.java:611)
at org.apache.hadoop.security.UserGroupInformation.initialize(UserGroupInformation.java:273)
at org.apache.hadoop.security.UserGroupInformation.ensureInitialized(UserGroupInformation.java:261)
at org.apache.hadoop.security.UserGroupInformation.loginUserFromSubject(UserGroupInformation.java:791)
at org.apache.hadoop.security.UserGroupInformation.getLoginUser(UserGroupInformation.java:761)
at org.apache.hadoop.security.UserGroupInformation.getCurrentUser(UserGroupInformation.java:634)
at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2422)
at org.apache.spark.util.Utils$$anonfun$getCurrentUserName$1.apply(Utils.scala:2422)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.util.Utils$.getCurrentUserName(Utils.scala:2422)
at org.apache.spark.SecurityManager.<init>(SecurityManager.scala:79)
at org.apache.spark.deploy.SparkSubmit.secMgr$lzycompute$1(SparkSubmit.scala:359)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$secMgr$1(SparkSubmit.scala:359)
at org.apache.spark.deploy.SparkSubmit$$anonfun$prepareSubmitEnvironment$7.apply(SparkSubmit.scala:367)
at org.apache.spark.deploy.SparkSubmit$$anonfun$prepareSubmitEnvironment$7.apply(SparkSubmit.scala:367)
at scala.Option.map(Option.scala:146)
at org.apache.spark.deploy.SparkSubmit.prepareSubmitEnvironment(SparkSubmit.scala:366)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:143)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:86)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:924)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:933)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)parkSubmit.main(SparkSubmit.scala)`
</code></pre>
| 3 | 1,094 |
Unknown attribute error for parent id, only happening in test
|
<p>I have TopicList (parent) and Topic (child) models</p>
<pre><code>class TopicList < ApplicationRecord
has_many :topics
validates :name, presence: true , uniqueness: { case_sensitive: false }
end
class Topic < ApplicationRecord
belongs_to :topic_list
validates :topic_list_id, presence: true
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
</code></pre>
<p>The schema.rb includes:</p>
<pre><code>ActiveRecord::Schema.define(version: 20161116031922) do
create_table "topic_lists", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["name"], name: "index_topic_lists_on_name", unique: true
end
create_table "topics", force: :cascade do |t|
t.string "name"
t.string "source"
t.integer "position"
t.integer "topic_list_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["name"], name: "index_topics_on_name", unique: true
t.index ["position"], name: "index_topics_on_position"
t.index ["topic_list_id"], name: "index_topics_on_topic_list_id"
end
</code></pre>
<p>My topic_test.rb starts by creating a new TopicList and building a Topic under it:</p>
<pre><code>require 'test_helper'
class TopicTest < ActiveSupport::TestCase
def setup
@topic_list = TopicList.new(name: "Vocab")
@topic_list.save
@topic = @topic_list.topics.build(name: "Topic 1")
end
test "should be valid" do
assert @topic.valid?
end
end
</code></pre>
<p>Whenever I run this test, I get the error:</p>
<pre><code>ActiveModel::UnknownAttributeError: unknown attribute 'topic_list_id' for Topic.
</code></pre>
<p>But when I try the same sequence in my rails console, it works just fine.</p>
<pre><code>Loading development environment (Rails 5.0.0.1)
>> list = TopicList.new(name: "List 1")
=> #<TopicList id: nil, name: "List 1", created_at: nil, updated_at: nil>
>> list.save
(0.1ms) begin transaction
TopicList Exists (0.3ms) SELECT 1 AS one FROM "topic_lists" WHERE LOWER("topic_lists"."name") = LOWER(?) LIMIT ? [["name", "List 1"], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "topic_lists" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "List 1"], ["created_at", 2016-11-16 21:23:33 UTC], ["updated_at", 2016-11-16 21:23:33 UTC]]
(11.3ms) commit transaction
=> true
>> topic = list.topics.build(name: "Topic #1")
=> #<Topic id: nil, name: "Topic #1", source: nil, position: nil, topic_list_id: 3, created_at: nil, updated_at: nil>
>> topic.valid?
Topic Exists (0.2ms) SELECT 1 AS one FROM "topics" WHERE LOWER("topics"."name") = LOWER(?) LIMIT ? [["name", "Topic #1"], ["LIMIT", 1]]
=> true
>>
</code></pre>
<p>Every similar question I've found here deals with incorrect CamelCase, snake_case, or plural/single names. I think I've done all that correctly here. What am I missing?</p>
| 3 | 1,146 |
How to change a SQL query based on PHP array?
|
<p>I have a PHP file that references a SQL query, validates the contact data returned to meet certain standards, and then generates an XML file with all of the contact data. Part of the query allows me to select which countries I want to pull the data from (ex.by adding WHERE tbl_vsed_unvalidated.c ='US' to the end for United States). What I have been doing is simply editing the SQL query to select the appropriate countries before running the PHP script.</p>
<p>What I am now working on is a way to select any countries you want via an HTML form, store those results in a PHP array via the POST method, and then altar the SQL "WHERE" statement on the fly to return the selected countries. I found a way to achieve this using a $where variable and the implode() method to add all countries in the array. The only issue I am having is the fact that I am referencing the SQL query by using "file_get_contents(SqlQuery.sql)". It seems like this is the only way to reference the query because it is very large and must contain multiple "s and 's.</p>
<p>Is there any way to wrap a SQL query in quotes within PHP if it already contains both quotes and apostrophes? Here is how I want it to look:</p>
<pre><code>$query = " SELECT tbl_vsed_unvalidated.keyuid "UNIQUE ID",tbl_vsed_unvalidated.sn "LAST NAME",
tbl_vsed_unvalidated.gskpreferredname "FIRST NAME",
tbl_vsed_unvalidated.initials "MIDDLE INITIAL",
tbl_vsed_unvalidated.co "COUNTRY",-- tbl_vsed_unvalidated.preferredlanguage "PREFERRED LANGUAGE",
tbl_vsed_unvalidated.c "CODE",
'Business Level 1' AS "CUSTOM LABEL 1",
tbl_vsed_unvalidated.gskglobalbusinesscategory "CUSTOM VALUE 1",
'Business Level 2' AS "CUSTOM LABEL 2", tbl_vsed_unvalidated.o "CUSTOM VALUE 2",
'Business Level 3' AS "CUSTOM LABEL 3",tbl_vsed_unvalidated.ou "CUSTOM VALUE 3",
'Department' AS "CUSTOM LABEL 4",tbl_vsed_unvalidated.gskdepartmentname "CUSTOM VALUE 4",
'Site' AS "CUSTOM LABEL 5",tbl_vsed_unvalidated.l "CUSTOM VALUE 5",
'Employee ID' AS "CUSTOM LABEL 6",tbl_vsed_unvalidated.employeenumber "CUSTOM VALUE 6",
'Resource Type' AS "CUSTOM LABEL 7",tbl_vsed_unvalidated.gskresourcetype "CUSTOM VALUE 7",
'Cost Center' AS "CUSTOM LABEL 8",tbl_vsed_unvalidated.departmentnumber "CUSTOM VALUE 8",
'Office' AS "PHONE LABEL 1",
null as "PHONE 1 COUNTRY CODE",
REPLACE(REPLACE(REPLACE(REPLACE(tbl_vsed_unvalidated.telephonenumber,'#',null),'-',null),' ',null),'+',null)
AS "PHONE 1",
NULL as "PHONE EXTENSION 1",
'2' AS "CASCADE 1",
'Mobile' AS "PHONE 2 LABEL",
null as "PHONE 2 COUNTRY CODE",
REPLACE(REPLACE(REPLACE(REPLACE(tbl_vsed_unvalidated.mobile,'#',null),'-',null),' ',null),'+',null)
AS "PHONE 2",
NULL as "PHONE EXTENSION 2",
'1' AS "CASCADE 2",
'Work' AS "EMAIL LABEL 1", tbl_vsed_unvalidated.mail AS "EMAIL 1",
DECODE (null,tbl_vsed_unvalidated.mobile,tbl_vsed_unvalidated.mobile,
REPLACE(REPLACE(REPLACE(REPLACE(tbl_vsed_unvalidated.mobile,'#',null),'-',null),'
',null),'+',null)||'@sms.sendwordnow.com') AS "SMS 1"
FROM useradmin.VSED_UNVALIDATED_VW tbl_vsed_unvalidated
WHERE ((((tbl_vsed_unvalidated.gskresourcetype <> 'Functional')
OR tbl_vsed_unvalidated.gskresourcetype is null)
AND (tbl_vsed_unvalidated.c ='US'))
";
</code></pre>
<p>instead of this:</p>
<pre><code> $query=file_get_contents(SQLQuery.sql);
</code></pre>
<p>This way I will be able to reference the PHP array within the SQL Query's WHERE statement. I should also mention that I am using an Oracle Database so I am using oci rather than mysql.</p>
| 3 | 1,642 |
How is it possible to make this app working with mobile browsers?
|
<p>I am working on an app for drawing using HTML 5 Canvas the problem that it's working well on computer browser like this picture
<a href="http://s28.postimg.org/z0ytnva98/problem.jpg" rel="nofollow">http://s28.postimg.org/z0ytnva98/problem.jpg</a></p>
<p>I want to make it working on mobile browser (never mind working on both, mobile browser is what I want).
the problem in my code concerning the Java Script events.
I change it to</p>
<pre><code>canvas.addEventListener('touchstart' , engage);
canvas.addEventListener('touchmove', putpoint);
canvas.addEventListener('touchend' , disengage);
</code></pre>
<p>but didn't work i also tried</p>
<pre><code>canvas.addEventListener('touchstart' , engage);
canvas.addEventListener('touchmove', putpoint);
canvas.addEventListener('touchleave' , disengage);
</code></pre>
<p>also didn't work.
when I leave it to as it was like this </p>
<pre><code>canvas.addEventListener('mousedown' , engage);
canvas.addEventListener('mousemove', putpoint);
canvas.addEventListener('mouseup' , disengage);
</code></pre>
<p>it make just a point like this picture
<a href="http://s14.postimg.org/tadk87jpt/Screenshot_2015_02_15_20_16_32.png" rel="nofollow">http://s14.postimg.org/tadk87jpt/Screenshot_2015_02_15_20_16_32.png</a></p>
<p>here is my code </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drawing app</title>
<body style="overflow: hidden">
<canvas id="canvas" style="width:100% ; height:100%">
Your browser does not support canvas element.
</canvas>
<script>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
radius = 20,
dragging = false;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context.lineWidth = radius*2;
var putpoint = function(e){
if(dragging){
context.lineTo(e.clientX, e.clientY);
context.stroke();
context.beginPath();
context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2);
context.fill();
context.beginPath();
context.moveTo(e.clientX, e.clientY);
}
};
var engage = function(e){
dragging = true;
putpoint(e);
};
var disengage = function(){
dragging = false;
context.beginPath();
};
canvas.addEventListener('mousedown' , engage);
canvas.addEventListener('mousemove', putpoint);
canvas.addEventListener('mouseup' , disengage);
</script>
</code></pre>
<p>
</p>
| 3 | 1,092 |
PHP Mail form does not send
|
<p>I copied the message form and PHP mail from a website. But it doesn't seem to work. It does not send anything or make any reaction. I tried to find the error, but I am not familiar with PHP. I tried editing the $emailFrom =... to $_POST['email']; but that doesn't work either..</p>
<p>HTML:</p>
<pre><code><div id="form-main">
<div id="form-div">
<form class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Naam"/>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" placeholder="E-mail" />
</p>
<p class="text">
<textarea name="text" class="validate[required,length[6,300]] feedback-input" placeholder="Bericht"></textarea>
</p>
<div class="submit">
<input type="submit" value="Verstuur" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
</code></pre>
<p>PHP:</p>
<pre><code> <?php
include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="lisa-ederveen@hotmail.com"; //"yourmail@yoursite.com";
//from email adress
$emailFrom =$_POST['email']; //"contact@yoursite.com";
//email subject
$emailSubject = "Mail from Porta";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
?>
</code></pre>
| 3 | 1,261 |
Can very long I/O processes be handled by threads
|
<p>I'm starting here a new topic that will be linked with <a href="https://stackoverflow.com/questions/47250025/qthreadpool-how-to-interrupt-how-to-use-wisely-the-waitfordone-method">this question</a>.</p>
<p>I invite you to just read on the background in order to get the global idea.</p>
<p>So I’ve a download function which relies on a python 3.2 API (developed by a private company). The process can take up to 400 seconds per file.</p>
<p>Obviously, I don't have only one file to download, so I've been trying for days to put every download process in a thread pool. Each thread in the pool should be completely autonomous from the GUI Main Thread. When one of them has finished, it should just send a signal to the GUI.</p>
<p>I did several tests but whatever the technique used, but </p>
<ol>
<li>the GUI is freezing;</li>
<li>the result is only given at the end of the processing of all threads and not – as wanted – one by one.</li>
</ol>
<p>I think that the download method given by the API is a blocking function that can't be threaded.</p>
<p>So my question is simple: how to know if a I/O method can be handled through a thread.</p>
<hr>
<p>November 24,2017 Update</p>
<p>You will find below a first draft (with the tandem multiprocessing.pool / map_async) that partially meets my expectations. As you will see, I unfortunately had to insert a "Busy Waiting Loop" in order to get on the QPlainTextEdit some information on what was going on.</p>
<p>The results of the tasks are given only at the end of the global processing (behaviour map_async). That's not exactly what I'm looking for. I would like to insert a little more real time and see for each completed task its message immediately on the console.</p>
<pre><code>import time
import multiprocessing
import private.library as bathy
from PyQt4 import QtCore, QtGui
import os
import sys
user = 'user'
password = 'password'
server = 'server'
basename = 'basename'
workers = multiprocessing.cpu_count()
node = bathy.NodeManager(user, password, server)
database = node.get_database(basename)
ids = (10547, 3071, 13845, 13846, 13851, 13844, 5639, 4612, 4613, 954,
961, 962, 4619, 4620, 4622, 4623, 4624, 4627, 4628, 4631,
4632, 4634, 4635, 4638, 4639, 4640, 4641, 4642, 10722, 1300,
1301, 1303, 1310, 1319, 1316, 1318, 1321, 1322, 1323, 1324,
1325, 1347, 1348, 1013, 1015, 1320, 8285, 8286, 8287, 10329,
9239, 9039, 5006, 5009, 5011, 5012, 5013, 5014, 5015, 5025,
5026, 4998, 5040, 5041, 5042, 5043, 11811, 2463, 2464, 5045,
5046, 5047, 5048, 5049, 5053, 5060, 5064, 5065, 5068, 5069,
5071, 5072, 5075, 5076, 5077, 5079, 5080, 5081, 5082, 5083,
5084, 5085, 5086, 5087, 5088, 5090, 5091, 5092, 5093)
# ---------------------------------------------------------------------------------
def download(surface_id, index):
global node
global database
t = time.time()
message = 'Surface #%d - Process started\n' % index
surface = database.get_surface(surface_id)
metadata = surface.get_metadata()
file_path = os.path.join("C:\\Users\\philippe\\Test_Download",
metadata["OBJNAM"] + ".surf")
try:
surface.download_bathymetry(file_path)
except RuntimeError as error:
message += "Error : " + str(error).split('\n')[0] + '\n'
finally:
message += ('Process ended : %.2f s\n' % (time.time() - t))
return message
# ---------------------------------------------------------------------------------
def pass_args(args):
# Method to pass multiple arguments to download (multiprocessing.Pool)
return download(*args)
# ---------------------------------------------------------------------------------
class Console(QtGui.QDialog):
def __init__(self):
super(self.__class__, self).__init__()
self.resize(600, 300)
self.setMinimumSize(QtCore.QSize(600, 300))
self.setWindowTitle("Console")
self.setModal(True)
self.verticalLayout = QtGui.QVBoxLayout(self)
# Text edit
# -------------------------------------------------------------------------
self.text_edit = QtGui.QPlainTextEdit(self)
self.text_edit.setReadOnly(True)
self.text_edit_cursor = QtGui.QTextCursor(self.text_edit.document())
self.verticalLayout.addWidget(self.text_edit)
# Ok / Close
# -------------------------------------------------------------------------
self.button_box = QtGui.QDialogButtonBox(self)
self.button_box.setStandardButtons(QtGui.QDialogButtonBox.Close |
QtGui.QDialogButtonBox.Ok)
self.button_box.setObjectName("button_box")
self.verticalLayout.addWidget(self.button_box)
# Connect definition
# -------------------------------------------------------------------------
self.connect(self.button_box.button(QtGui.QDialogButtonBox.Close),
QtCore.SIGNAL('clicked()'),
self.button_cancel_clicked)
self.connect(self.button_box.button(QtGui.QDialogButtonBox.Ok),
QtCore.SIGNAL('clicked()'),
self.button_ok_clicked)
# Post initialization
# -------------------------------------------------------------------------
self.pool = multiprocessing.Pool(processes=workers)
# Connect functions
# -----------------------------------------------------------------------------
def button_cancel_clicked(self):
self.close()
def button_ok_clicked(self):
jobs_args = [(surface_id, index) for index, surface_id in enumerate(ids)]
async = pool.map_async(pass_args, jobs_args)
pool.close()
# Busy waiting loop
while True:
# pool.map_async has a _number_left attribute, and a ready() method
if async.ready():
self.write_stream("All tasks completed\n")
pool.join()
for line in async.get():
self.write_stream(line)
break
remaining = async._number_left
self.write_stream("Waiting for %d task(s) to complete...\n" % remaining)
time.sleep(0.5)
# Other functions
# -----------------------------------------------------------------------------
def write_stream(self, text):
self.text_edit.insertPlainText(text)
cursor = self.text_edit.textCursor()
self.text_edit.setTextCursor(cursor)
app.processEvents()
# ---------------------------------------------------------------------------------
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Console()
window.show()
app.exec_()
</code></pre>
<p><strong>Questions</strong></p>
<ol>
<li>At first glance does the above code for you present conceptual errors?</li>
<li>Do I have to use the apply_async method in this specific case to get something more interactive?</li>
<li>Could you guide me on how to use a callback function to post a custom event to update the console (methodology suggested by @ekhumoro)?</li>
</ol>
<hr>
<p>November 25,2017 Update</p>
<p>I had a try with apply_async:</p>
<pre><code>def button_ok_clicked(self):
# Pool.apply_async - the call returns immediately instead of
# waiting for the result
for index, surface_id in enumerate(ids):
async = pool.apply_async(download,
args=(surface_id, index),
callback=self.write_stream)
pool.close()
</code></pre>
<p>with a callback:</p>
<pre><code>def write_stream(self, text):
# This is called whenever pool.apply_async(i) returns a result
self.text_edit.insertPlainText(text)
cursor = self.text_edit.textCursor()
self.text_edit.setTextCursor(cursor)
# Update the text edit
app.processEvents()
</code></pre>
<p>Unfortunately, by doing this way the application crashes. I think I'll have to put a lock mechanism to prevent all the tasks from writing in the text edit at the same time.</p>
| 3 | 3,030 |
CoreCLR, 'Type' does not contain a definition for 'GetTypeFromProgID'
|
<p>I'm trying to upgrade a web application from dnx451 to a dotnetcoreapp1.0.</p>
<p>This application needs to use an old library (at least I think it's a library). This snippet used to work with DNX, but it doesn't now that I've upgraded. </p>
<pre><code>//COMPILE ERROR: 'Type' does not contain a definition for 'GetTypeFromProgID'
var comType = Type.GetTypeFromProgID("ABCCrypto2.Crypto");
var abc = Activator.CreateInstance(comType);
var license = _config["AbcCrypto:License"];
var password = _config["AbcCrypto:Password"];
comType.InvokeMember("License", System.Reflection.BindingFlags.SetProperty, null, abc, new object[] { license });
comType.InvokeMember("Password", System.Reflection.BindingFlags.SetProperty, null, abc, new object[] { password });
var hashed = comType.InvokeMember("Encrypt", System.Reflection.BindingFlags.InvokeMethod, null, abc, new object[] { data });
</code></pre>
<p>Any ideas or workarounds? Thanks!</p>
<p><strong>EDIT:</strong></p>
<p>The code above is in <em>a class library separate from the ASP.NET Core Web Application that references it</em>. Here is the project.json for the class library:</p>
<pre><code>"buildOptions": {
"emitEntryPoint": false
},
"dependencies": {
"MyApp.Data": "1.0.0-*",
"System.Net.Mail": "1.0.0-rtm-00002",
"System.Runtime": "4.1.0"
},
"frameworks": {
"netcoreapp1.0": { }
}
</code></pre>
<p>And here is the project.json for the ASP.NET Core Web Application:</p>
<pre><code>"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"dependencies": {
"MyApp.Services": "1.0.0-*",
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
"Microsoft.AspNetCore.Authorization": "1.0.0",
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Hosting": "1.0.0",
"Microsoft.AspNetCore.Hosting.Abstractions": "1.0.0",
"Microsoft.AspNetCore.Http.Extensions": "1.0.0",
"Microsoft.AspNetCore.Localization": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Routing": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.AspNetCore.Session": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Caching.SqlServer": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
}
}
},
"runtimes": {
"win10-x86": {}
}
</code></pre>
| 3 | 1,139 |
Error at rendering circles - Google Maps Javascript
|
<p>I'm developing a web app which has a map and where the user can set circles wherever he wants. Then he can see every circle he has set. </p>
<p>But when I load the circles that the user has, this happens:
<a href="https://i.stack.imgur.com/w7VkO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w7VkO.png" alt="Oops!"></a></p>
<p>The user that I´m using to test has 5 circles, the ones that appear complete. The rest is junk that just appears there and I´m not sure why. </p>
<p>This is my code (I´m using RoR): </p>
<p>Javascript: </p>
<pre><code>function initMap() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: "<%= asset_path('marker.png') %>"
});
map.setCenter(pos);
}, function(e) {
console.log(e);
});
}
}
function loadUserTargets() {
$.getJSON('/circles/list', function(circlesList) {
if(circlesList.length > 0) {
jQuery.each(circlesList, function(index, circle){
var circleCenter = new google.maps.LatLng(circle.latitude, circle.longitude);
drawCircleAt(circleCenter, circle.radius);
});
}
});
}
function drawCircleAt(location, radius) {
return new google.maps.Circle({
strokeWeight: 0,
fillColor: '#efc537',
fillOpacity: 0.7,
map: map,
center: location,
radius: radius
});
}
</code></pre>
<p>When I call getJSON('/circles/list', ...) I get the following in return:</p>
<pre><code>[{"id":4,"latitude":-34.9001517737747,"longitude":-56.1877727508545,"radius":456},
{"id":5,"latitude":-34.8983567053717,"longitude":-56.1922359466553,"radius":367},
{"id":6,"latitude":-34.9032138587385,"longitude":-56.1949396133423,"radius":100},
{"id":7,"latitude":-34.9053255749513,"longitude":-56.2041234970093,"radius":200},
{"id":8,"latitude":-34.9103230869756,"longitude":-56.18408203125,"radius":500}]
</code></pre>
<p>Does anybody know what´s going on?</p>
<p>Thanks!</p>
<p><strong>UPDATE</strong></p>
<p>This bug was handled in the isssue <a href="https://issuetracker.google.com/issues/38211242" rel="nofollow noreferrer">https://issuetracker.google.com/issues/38211242</a>.
It was fixed in August 2017.</p>
| 3 | 1,059 |
Issue with accessing JSON Covid Data
|
<p><strong>Background on my application</strong> </p>
<p>I am using react and node js. I connected node.js to react.js using axios. </p>
<p><strong>Issue</strong></p>
<p>I'm trying to access the cases (5226) in Afganistan, but I can't seem to get the right variable for it. </p>
<pre><code>const cases = covidData[0].cases
</code></pre>
<p>Whenever, i try to run the app using nodemon (to run my server) and npm start (to run my react app) I get the following error on my terminal</p>
<p>Error from node terminal</p>
<pre><code>[nodemon] starting `node ./server.js`
listening at port 5000
200
undefined:1
[{"updated":1589436777722,"country":"Afghanistan","countryInfo":{"_id":4,"iso2":"AF","iso3":"AFG","lat":33,"long":65,"flag":"https://disease.sh/assets/img/flags/af.png"},"cases":5226,"todayCases":0,"deaths":132,"todayDeaths":0,"recovered":648,"active":4446,"critical":7,"casesPerOneMillion":134,"deathsPerOneMillion":3,"tests":18724,"testsPerOneMillion":481,"continent":"Asia"},{"updated":1589436777821,"country":"Albania","countryInfo":{"_id":8,"iso2":"AL","iso3":"ALB","lat":41,"long":20,"flag":"https://disease.sh/assets/img/flags/al.png"},"cases":880,"todayCases":0,"deaths":31,"todayDeaths":0,"recovered"
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (/Users/alfietorres/github/covid19/server.js:13:30)
at IncomingMessage.emit (events.js:198:13)
at IncomingMessage.Readable.read (_stream_readable.js:504:10)
at flow (_stream_readable.js:973:34)
at resume_ (_stream_readable.js:954:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
[nodemon] app crashed - waiting for file changes before starting...
</code></pre>
<p>JSON from website</p>
<pre><code>[
{
"updated": 1589433177684,
"country": "Afghanistan",
"countryInfo": {
"_id": 4,
"iso2": "AF",
"iso3": "AFG",
"lat": 33,
"long": 65,
"flag": "https://disease.sh/assets/img/flags/af.png"
},
"cases": 5226,
"todayCases": 0,
"deaths": 132,
"todayDeaths": 0,
"recovered": 648,
"active": 4446,
"critical": 7,
"casesPerOneMillion": 134,
"deathsPerOneMillion": 3,
"tests": 18724,
"testsPerOneMillion": 481,
"continent": "Asia"
},
{
.
.
.
etc
</code></pre>
<p>Node.js code </p>
<pre><code>const express = require("express");
const app = express();
const https = require("https");
const url = "https://disease.sh/v2/countries/";
app.get("/getData",function(req,res){
https.get(url, function(response){
console.log(response.statusCode)
response.on("data",function(data){
const covidData=JSON.parse(data)
// const cases = covidData.cases
res.send({covidData});
})
}, function(err){ console.log(err)})
}
)
app.listen(5000,function(){
console.log("listening at port 5000")
})
</code></pre>
| 3 | 1,089 |
werkzeug module not matching hashed password
|
<p>Im currently following along w a video trying to build this login system for a site, but each time I call the werkzeug function to check the hash of the password against the one used to sign up, it returns invalid password. What am I doing wrong to make the hashes end up different even though I'm entering the same password as I did to sign up?</p>
<pre><code>from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from flask_login import login_user, login_required, logout_user, current_user
auth = Blueprint('auth', __name__)
@auth.route('/sign-up', methods=['GET', 'POST'])
def sign_up():
if request.method == 'POST':
email = request.form.get('email')
first_name = request.form.get('firstName')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
user = User.query.filter_by(email=email).first()
if user:
flash('Email already exists.', category='error')
elif len(email) < 4:
flash('Email must be greater than 3 characters.', category='error')
elif len(first_name) < 2:
flash('First name must be greater than 1 character.', category='error')
elif password1 != password2:
flash('Passwords don\'t match.', category='error')
elif len(password1) < 7:
flash('Password must be at least 7 characters.', category='error')
else:
new_user = User(email=email, first_name=first_name, password=generate_password_hash(password1, method='sha256',))
db.session.add(new_user)
db.session.commit()
flash('Account created!', category='success')
return redirect(url_for('views.home'))
return render_template("sign_up.html")
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user:
if check_password_hash(user.password, password):
flash('Logged in successfully!', category='success')
login_user(user, remember=True)
return redirect(url_for('views.home'))
else:
flash('Incorrect password, try again.', category='error')
else:
flash('Email does not exist.', category='error')
return render_template("login.html", user=current_user)
@auth.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('auth.login'))
</code></pre>
| 3 | 1,075 |
Local Storage Problem > ME I cant seem to make this work
|
<p>Problem: Local Storage is not storing data. </p>
<p>I am working on a daily scheduler app for my bootcamp. I am trying to use local storage to keep data on the app. However when I refresh, the data disappears. I included the code I am using that i am working with. Let me know if you can show me where I am going wrong. </p>
<p>Thanks so much!</p>
<p>Cheers</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Background Color Set Function
// define row is time in 24 hour time format
const rows = document.getElementsByClassName("row");
let currentHour = parseInt(moment().format('H'));
// lets make sure we are getting expected output
console.log(currentHour);
Array.from(rows).forEach(row => {
let
rowIdString = row.id,
rowHour;
if (rowIdString) {
rowHour = parseInt(rowIdString);
}
if (rowHour) {
// Compares row id to current hour and sets color accordingly
if (currentHour === rowHour) {
setColor(row, "red");
} else if ((currentHour < rowHour)) {
setColor(row, "green");
} else {
setColor(row, "lightgrey");
}
}
});
function setColor(element, color) {
element.style.backgroundColor = color;
}
var input = document.getElementById('textArea6').value;
localStorage.setItem('text6', input);
document.getElementById('textArea6').value = localStorage.getItem('text6');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: 'Open Sans', sans-serif;
font-size: 16px;
line-height: 1;
}
textarea {
background: transparent;
border: none;
resize: none;
color: #000000;
border-left: 1px solid black;
padding: 10px;
}
.jumbotron {
text-align: center;
background-color: transparent;
color: black;
border-radius: 0;
border-bottom: 10px solid black;
}
.description {
white-space: pre-wrap;
}
.time-block {
text-align: center;
border-radius: 15px;
}
.row {
white-space: pre-wrap;
height: 80px;
border-top: 1px solid white;
;
}
.hour {
background-color: #ffffff;
color: #000000;
border-top: 1px dashed #000000;
}
.past {
background-color: #d3d3d3;
color: white;
}
.present {
background-color: #ff6961;
color: white;
}
.future {
background-color: #77dd77;
color: white;
}
.saveBtn {
border-left: 1px solid black;
border-top-right-radius: 15px;
border-bottom-right-radius: 15px;
background-color: #06AED5;
color: white;
}
.saveBtn i:hover {
font-size: 20px;
transition: all .3s ease-in-out;
}
.red {
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-8"></code></pre>
</div>
</div>
</p>
| 3 | 1,094 |
Symfony 3.4 - Can we collect code coverage for functional testing?
|
<p>I am using symfony 3.4 for some of our projects. According to the docs, we should write functional tests for ours controllers. However, it seems that we cannot collect code coverage for functional test because symfony will run main code in another PHP processs. </p>
<ul>
<li>In phpunit process: <code>var_dump(xdebug_code_coverage_started()) => true</code></li>
<li>In controller code: <code>var_dump(xdebug_code_coverage_started()) =>
false</code>.</li>
</ul>
<p>UPDATE: It seems that the problem only occurs when I put tests in separate folder to <code>src</code> folder. It works when I put tests in the same bundle folder (<code>src/MyBubndle/Tests</code>) </p>
<p><strong>PHP Unit config</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.0/phpunit.xsd"
backupGlobals="false"
colors="true"
processIsolation = "false"
bootstrap="vendor/autoload.php"
>
<php>
<ini name="error_reporting" value="-1" />
<server name="KERNEL_DIR" value="app/" />
<env name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/>
<!--<env name="KERNEL_CLASS" value="App\Kernel" />-->
<env name="APP_ENV" value="test"/>
<env name="APP_DEBUG" value="1"/>
<env name="SYMFONY_ENV" value="test"/>
<env name="MYSQL_SERVER" value="127.0.0.1"/>
<env name="MYSQL_DATABASE" value="db"/>
<env name="MYSQL_USER" value="root"/>
<env name="MYSQL_PASSWORD" value="root"/>
<env name="MYSQL_PORT" value="3306"/>
<env name="JWT_PUBLIC_KEY_PATH" value="jwt/public.pem"/>
<env name="SYMFONY_PHPUNIT_VERSION" value="6.5.5"/>
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory suffix="Test.php" >.</directory>
<exclude>vendor</exclude>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">.</directory>
<exclude>
<directory>src/*Bundle/Resources</directory>
<directory>src/*/*Bundle/Resources</directory>
<directory>src/*/Bundle/*Bundle/Resources</directory>
<directory>app</directory>
<directory>bin</directory>
<directory>docker</directory>
<directory>jwt</directory>
<directory>var</directory>
<directory>vendor</directory>
<directory>web</directory>
<directory>tests</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="./var/logs/codeCoverage" charset="UTF-8"
yui="true" highlight="true"
lowUpperBound="50" highLowerBound="80"/>
<log type="coverage-text" target="php://stdout" showOnlySummary = "true" showUncoveredFiles="false"/>
<log type="testdox-html" target="./var/logs/testdox.html" />
<log type="junit" target="./var/logs/testreport.xml" logIncompleteSkipped="false"/>
<log type="coverage-clover" target="./var/logs/coverage.xml"/>
</logging>
<!--<listeners>-->
<!--<listener class="Symfony\Bridge\PhpUnit\CoverageListener" />-->
<!--</listeners>-->
</phpunit>
</code></pre>
<p>Also tried:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.0/phpunit.xsd"
backupGlobals="false"
colors="true"
processIsolation = "false"
bootstrap="vendor/autoload.php"
>
<php>
<ini name="error_reporting" value="-1" />
<server name="KERNEL_DIR" value="app/" />
<env name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/>
<!--<env name="KERNEL_CLASS" value="App\Kernel" />-->
<env name="APP_ENV" value="test"/>
<env name="APP_DEBUG" value="1"/>
<env name="SYMFONY_ENV" value="test"/>
<env name="MYSQL_SERVER" value="127.0.0.1"/>
<env name="MYSQL_DATABASE" value="db"/>
<env name="MYSQL_USER" value="root"/>
<env name="MYSQL_PASSWORD" value="root"/>
<env name="MYSQL_PORT" value="3306"/>
<env name="JWT_PUBLIC_KEY_PATH" value="jwt/public.pem"/>
<env name="SYMFONY_PHPUNIT_VERSION" value="6.5.5"/>
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory suffix="Test.php" >./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">./src</directory>
<exclude>
<directory>src/*Bundle/Resources</directory>
<directory>src/*/*Bundle/Resources</directory>
<directory>src/*/Bundle/*Bundle/Resources</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="./var/logs/codeCoverage" charset="UTF-8"
yui="true" highlight="true"
lowUpperBound="50" highLowerBound="80"/>
<log type="coverage-text" target="php://stdout" showOnlySummary = "true" showUncoveredFiles="false"/>
<log type="testdox-html" target="./var/logs/testdox.html" />
<log type="junit" target="./var/logs/testreport.xml" logIncompleteSkipped="false"/>
<log type="coverage-clover" target="./var/logs/coverage.xml"/>
</logging>
<!--<listeners>-->
<!--<listener class="Symfony\Bridge\PhpUnit\CoverageListener" />-->
<!--</listeners>-->
</phpunit>
</code></pre>
<p>Is there any workaround for this without using other testing framework?</p>
<p>All helps are highly appreciated!</p>
| 3 | 3,318 |
Async callback nodejs
|
<p>I try to use async NodeJs library to execute a render with express after collecting informations of a API but the async.parallel callback execute itself before collecting all data that I need</p>
<p>This is the code : </p>
<pre><code> LolApi.getMatchHistory(app_dtb.summoner.id, "euw", function(err, history) {
if (!err) {
async.parallel([
function(callback) {
LolApi.getMatch(history.matches[nbMatch].matchId, function(err, match) {
if (!err) {
var teamIn;
function getParticipantNb() {
for (var i = 0; i < match.participantIdentities.length; i++) {
if (app_dtb.summoner.id == match.participantIdentities[i].player.summonerId) {
if (i <= 5) teamIn = 100
else teamIn = 200
return i + 1
}
}
return false;
}
var participantNb = getParticipantNb()
if (match.teams[0].winner == true && teamIn == 100) {
app_dtb.lastGame.won = "Win";
} else {
app_dtb.lastGame.won = "Loose";
}
console.log(app_dtb.lastGame.won)
} else {
console.log(err)
}
});
setTimeout(function() {
callback(null, "one");
}, 200);
},
function(callback) {
options = {
champData: 'allytips,blurb',
version: '4.4.3',
locale: 'en_US'
}
LolApi.Static.getChampionById(history.matches[nbMatch].champion, options, function(err, champ) {
if (!err) {
console.log(champ.name);
app_dtb.lastGame.champName = champ.name
} else {
console.log(err)
}
});
setTimeout(function() {
callback(null, "two");
}, 100);
}
], function(err, results) {
console.log(results)
res.render("index");
});
} else {
console.log(err);
}
})
</code></pre>
<p>Any idea or other way to have the same result ? </p>
<p>Thanks a lot</p>
| 3 | 2,097 |
When ThreadB Monitor.Pulse(_locker) which thread will get _locker first?
|
<p>I read this article <a href="https://www.codeproject.com/Articles/28785/Thread-synchronization-Wait-and-Pulse-demystified#_articleTop" rel="nofollow noreferrer">https://www.codeproject.com/Articles/28785/Thread-synchronization-Wait-and-Pulse-demystified#_articleTop</a></p>
<p>There is a quote:</p>
<blockquote>
<p>Recommended pattern</p>
<p>These queues can lead to unexpected behaviour. When a Pulse occurs, the head of the waiting queue is released and is added to the ready queue. However, if there are other threads in the ready queue, they will acquire the lock before the thread that was released. This is a problem, because the thread that acquires the lock can alter the state that the pulsed thread relies on.</p>
<p>The solution is to use a while condition inside the lock statement:</p>
<pre><code>readonly object key = new object();
bool block = true;
// thread A
lock ( key )
{
while ( block )
Monitor.Wait( key );
block = true;
}
// thread B
lock ( key )
{
block = false;
Monitor.Pulse( key );
}
</code></pre>
</blockquote>
<p>The author says ThreadC will get _locker first, but in my demo in which I run three threads I find it is not true. ThreadC gets _locker last.</p>
<p>Here is my code :</p>
<pre><code>class Program
{
private static readonly object _locker = new object();
public static void ThreadA()
{
new Thread(() =>
{
lock (_locker)
{
Console.WriteLine("Thread A acquire lock then wait threadId {0}", Thread.CurrentThread.ManagedThreadId);
Monitor.Wait(_locker);
Thread.Sleep(1000);
Console.WriteLine("Thread A Continue .. threadId {0}", Thread.CurrentThread.ManagedThreadId);
}
}).Start();
}
public static void ThreadB()
{
new Thread(() =>
{
lock (_locker)
{
Console.WriteLine("Thread B acquire lock...then pulse threadId {0}",Thread.CurrentThread.ManagedThreadId);
Monitor.Pulse(_locker);
Thread.Sleep(1000);
Console.WriteLine("Thread B sleep...then realse the locker threadId {0}", Thread.CurrentThread.ManagedThreadId);
}
}).Start();
}
public static void ThreadC()
{
new Thread(ThreadA).Start();
}
static void Main(string[] args)
{
ThreadA();
Thread.Sleep(10); // ensure threadA get _locker firstly
ThreadB();
ThreadC();
}
}
</code></pre>
| 3 | 1,065 |
android: handler
|
<p>I am developing a kind of memory game app, where initially the 6 buttons will show some figures. Then when the below MyCount5sec and handler operates, after 5 sec of waiting period for user to remember, the handler will invoke txtClearRun whereby all the texts on every buttons to be erased.</p>
<p>Then after the 5 sec waiting period, it comes the testing period. The user has to select the button in sequence, ie. the latter button value must need to be greater than the earlier button value.</p>
<p>If the user is sucessful (ie. pressed all 6 number buttons), the app should wait 1.5 sec according to postDelay? Yet it appears that there are no delays.</p>
<p>If the user is wrong, ie. pressed button with value smaller than the previous one, the user fails and the app should also wait 1.5sec, with the button highlighted in red. However, it seems that there are no such 1.5sec delay too. No highlighting in red neither.</p>
<h2>Question</h2>
<ol>
<li>Why there appears no delays? TWO handlers cannot be invoked at the same time?</li>
<li>how could that be further modified?</li>
</ol>
<p>Thanks a lot!!</p>
<pre><code> private void setQup()
{
.....
MyCount5sec counter5sec = new MyCount5sec(6000,1000);
counter5sec.start();
handler.postDelayed(txtClearRun, 6000);
pressed = 0;
temp = 0;
final int txtClearRun1time = 1500; // set here!
button_space1.setText("reset press "+pressed);
Button11.setOnClickListener(new OnClickListener() {@Override
public void onClick(View v) {vibrate(); int i=0; Button11.setEnabled(false);
if (i == B0) {puttobutton(B0,0);} if (i == B1) {puttobutton(B1,1);} if (i == B2) {puttobutton(B2,2);}
if (i == B3) {puttobutton(B3,3);} if (i == B4) {puttobutton(B4,4);} if (i == B5) {puttobutton(B5,5);}
pressed = pressed + 1;
int buttonvalue = Integer.parseInt(Button11.getText().toString());
if (pressed >5)
{
TotalScores=TotalScores+20;
handler1.postDelayed(txtClearRun1, txtClearRun1time);
loadNextQup();
}
if (buttonvalue < temp)
{
Button11.setBackgroundResource(R.drawable.red_btn);
TotalScores=TotalScores-10;
handler1.postDelayed(txtClearRun1, txtClearRun1time);
loadNextQup();
}
temp = buttonvalue;
}});
......same for other buttons..
}
Runnable txtClearRun = new Runnable()
{
public void run() {blankbutton();} //remove text on buttons
};
Runnable txtClearRun1 = new Runnable()
{
public void run() {} // solely for wish to delay operations
};
private void loadNextQup()
{
if (TerminateOrNot ==0)
{
handler.removeCallbacks(txtClearRun);
handler1.removeCallbacks(txtClearRun1);
setQup();
}
....
}
</code></pre>
| 3 | 1,537 |
Modifying array for pygame to blit
|
<p>I have a medium sized array of tiles represented as numbers that pygame blits to the surface each tick. My array looks like this:</p>
<pre><code>chipset = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2], #Start Render
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]]
#2132 pixels.
</code></pre>
<p>After that, I have a FOR loop that should replace all 0's on chipset[19] with little scenery grass pieces. </p>
<pre><code>for element in chipset[19]:
element = 4
</code></pre>
<p>But it seems, this doesn't work, as the scenery doesn't show up on screen. I've tried manually placing them into the list, and it does indeed work, but this loop doesn't seem to.</p>
<p>Anyone have any ideas?</p>
| 3 | 3,328 |
How do I detect loss of connection from a web socket in my Swift App
|
<p>I am trying to detect loss of connection to my web socket in Swift. I have very little understanding of web sockets but I have tried googling for information but with little success. Here is my custom class providing a web socket service;</p>
<pre><code>//
// Services.swift
// BetVictorTask
//
// Created by Stephen Learmonth on 28/02/2022.
//
import UIKit
protocol NetworkServicesDelegateProtocol: AnyObject {
func sendStockInfo(stocksInfo: [String: StockInfo])
}
class NetworkServices: NSObject, URLSessionWebSocketDelegate {
static let sharedInstance = NetworkServices()
var webSocketTask: URLSessionWebSocketTask?
var stocksInfo: [String: StockInfo] = [:]
var socketResults: [String: [StockInfo]] = [:]
weak var delegate: NetworkServicesDelegateProtocol?
func fetchStockInfo(symbols: [String], delegate: CompanyPriceListVC) {
self.delegate = delegate
let urlSession = URLSession(configuration: .default)
webSocketTask = urlSession.webSocketTask(with: FINNHUB_SOCKET_STOCK_INFO_URL!)
webSocketTask!.resume()
for symbol in symbols {
let string = FINNHUB_SOCKET_MESSAGE_STRING + symbol + "\"}"
let message = URLSessionWebSocketTask.Message.string(string)
webSocketTask!.send(message) { error in
if let error = error {
print("Error sending message: \(error)")
}
self.receiveMessage()
}
}
}
private func receiveMessage() {
self.webSocketTask!.receive { result in
switch result {
case .failure(let error):
print("Error receiving message: \(error)")
case .success(.string(let jsonData)):
guard let stockData = jsonData.data(using: .utf8) else { return }
self.socketResults = [:]
self.stocksInfo = [:]
let decoder = JSONDecoder()
do {
let socketData = try decoder.decode(SocketData.self, from: stockData)
guard let stockInfoData = socketData.data else { return }
for stockInfo in stockInfoData {
let symbol = stockInfo.symbol
if self.socketResults[symbol] == nil {
self.socketResults[symbol] = [StockInfo]()
}
self.socketResults[symbol]?.append(stockInfo)
}
for (symbol, stocks) in self.socketResults {
for item in stocks {
if self.stocksInfo[symbol] == nil {
self.stocksInfo[symbol] = item
} else if item.timestamp > self.stocksInfo[symbol]!.timestamp {
self.stocksInfo[symbol] = item
}
}
}
self.delegate?.sendStockInfo(stocksInfo: self.stocksInfo)
self.receiveMessage()
} catch {
print("Error converting JSON: \(error)")
}
default:
print("default")
}
}
}
func closeWebSocketConnection() {
webSocketTask?.cancel(with: .goingAway, reason: nil)
}
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
print("Got here")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let error = error as? URLError else { return }
print("got here")
}
func fetchCompanyInfo(symbol: String, completion: @escaping (CompanyInfo?, UIImage?)->()) {
let urlString = FINNHUB_HTTP_COMPANY_INFO_URL_STRING + symbol + "&token=" + FINNHUB_API_TOKEN
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error fetching company info: \(error)")
}
guard let data = data else { return }
let decoder = JSONDecoder()
do {
let companyInfo = try decoder.decode(CompanyInfo.self, from: data)
guard let logoURL = URL(string: companyInfo.logo) else { return }
let task = URLSession.shared.dataTask(with: logoURL) { data, response, error in
if let error = error {
print("Error fetching logo image: \(error)")
}
guard let data = data else { return }
guard let logoImage = UIImage(data: data) else { return }
completion(companyInfo, logoImage)
}
task.resume()
} catch {
print("Error decoding JSON: \(error)")
completion(nil, nil)
}
}
task.resume()
}
}
</code></pre>
<p>I have tried implementing;</p>
<pre><code> func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
print("Got here")
}
</code></pre>
<p>and then run the app and turn off WiFi to simulate loss of connection but the urlSession method never gets called.</p>
<p>How can I simulate loss of web socket connection while running my app and detect this disconnection. Also I need to think of a way to reconnect the web socket</p>
| 3 | 3,245 |
Refresh Text in Notification (Remote View) Using Broadcast Receiver
|
<p>I have looked all around and can not find a way to overwrite an existing Remote View TextView using a Broadcast Receiver.</p>
<p>I'm trying to get the Remote View inside my MainActivity and update it with a new value to be displayed inside the notification when I press the button on the notification. I tried to recreate the notification manager and the remote view inside "Button_listener_plus", hoping it would override the existing one, but of course it doesn't and make the app crash... I also tried to make the remote view public to see if I could reuse it in "Button_listener_plus" but again could get it to work. The former method I described is shown in the code below.</p>
<p>Here is a snippet of the code I'm having trouble with:</p>
<pre><code>import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//Notification stuff
private NotificationCompat.Builder builder;
public NotificationManager notificationManager;
private int notification_id;
private int notification_id2;
private int notification_id3;
private RemoteViews remoteViews;
private Context context;
//debug tags
private String TAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//If permission is needed, ask
/*
boolean canDo = Settings.System.canWrite(this);
if (false == canDo)
{
Intent grantIntent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
startActivity(grantIntent);
}
*/
context = this;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
remoteViews = new RemoteViews(getPackageName(),R.layout.custom_notif);
//remoteViews.setImageViewResource(R.id.notif_icon,R.mipmap.ic_launcher);
remoteViews.setTextViewText(R.id.text_display_bright,"LVL");
findViewById(R.id.button_start_n).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//plus
notification_id = (int) System.currentTimeMillis();
Intent button_intent = new Intent("button_clicked_plus");
button_intent.putExtra("id",notification_id);
PendingIntent button_intent_plus = PendingIntent.getBroadcast(context,notification_id,
button_intent,0);
remoteViews.setOnClickPendingIntent(R.id.button_max_10,button_intent_plus);
//minus
notification_id2 = (int) System.currentTimeMillis() + 2;
Intent button_intent_minus = new Intent("button_clicked_minus");
button_intent_minus.putExtra("id2",notification_id2);
PendingIntent button_pending_event_minus = PendingIntent.getBroadcast(context,notification_id2,
button_intent_minus,0);
remoteViews.setOnClickPendingIntent(R.id.button_min_10,button_pending_event_minus);
//Notif Check
notification_id3 = (int) System.currentTimeMillis() + 3;
Intent button_intent_check = new Intent("button_clicked_check");
button_intent_check.putExtra("id3",notification_id3);
PendingIntent button_pending_event_check = PendingIntent.getBroadcast(context,notification_id3,
button_intent_check,0);
remoteViews.setOnClickPendingIntent(R.id.button_notif_check,button_pending_event_check);
Intent notification_intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,notification_intent,0);
//build notification & insert remote view (custom layout)
builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_stat_name)
//.setAutoCancel(true)
//.setCustomBigContentView(remoteViews)
.setCustomContentView(remoteViews)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MIN)
;
notificationManager.notify(notification_id,builder.build());
}
});
}
}
</code></pre>
<p>And the Broadcast Receiver:</p>
<pre><code>import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v7.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Button_listener_plus extends BroadcastReceiver {
private int plus_id;
//
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private RemoteViews remoteViews;
private Context context;
//
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "button_clicked!", Toast.LENGTH_SHORT).show();
int curBrightnessValue = 0;
try {
curBrightnessValue = Settings.System.getInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
//int rounded = ((curBrightnessValue + 9) / 10 ) * 10;
//int result = Math.min(255, rounded + 10);
int result = Math.min(250, curBrightnessValue + 25);
android.provider.Settings.System.putInt(context.getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, result);
//Toast.makeText(MainActivity.this,"" + result,Toast.LENGTH_SHORT).show();
int percent_scale = (result/25)*10;
Toast toasty = Toast.makeText(context, "" + percent_scale, Toast.LENGTH_SHORT);
toasty.show();
//...not working... crashes
notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.custom_notif);
remoteViews.setTextViewText(R.id.text_display_bright,""+result);
notificationManager.notify(intent.getExtras().getInt("id"),builder.build());
//delete
}
}
</code></pre>
<p>I looked at the following to try to figure things out:</p>
<p><a href="https://stackoverflow.com/questions/22869928/android-broadcastreceiver-onreceive-update-textview-in-mainactivity">Android BroadcastReceiver onReceive Update TextView in MainActivity</a></p>
<p><a href="https://stackoverflow.com/questions/38967787/update-textview-in-broadcast-receivers">Update TextView in Broadcast Receivers</a></p>
| 3 | 2,900 |
PayPalConnectionException in PayPalHttpConnection.php line 174:
|
<p>Hey I'm working on Laravel 5.3 and I'm trying to implement the PayPal Api, and I found a tutorial online, so I followed every step but then I got an error and I don't know how to solve it.</p>
<p>This is the code where I get the error:</p>
<pre><code>try{
$payment->create($this->_apiContext);
} catch (\PayPal\Exception\PayPalConnectionException $ex){
if(\Config::get('app.debug')){
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
echo $err_data;/*
echo $ex->getCode();
echo $ex->getData();*/
exit;
} else {
die('Ups! Algo salio mal');
}
}
</code></pre>
<p>And this is the error: </p>
<p>PayPalConnectionException in PayPalHttpConnection.php line 174:
Got Http response code 400 when accessing <a href="https://api.sandbox.paypal.com/v1/payments/payment/PAY-3SH87897C2313620PLCHWOOY/execute" rel="nofollow noreferrer">https://api.sandbox.paypal.com/v1/payments/payment/PAY-3SH87897C2313620PLCHWOOY/execute</a>.</p>
<p>Any idea?</p>
<p>Code:</p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Foundation\Validation\ValidatesRequests;
use App\Http\Requests;
use App\Deal;
use App\Status;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;
use Paypal;
use Session;
class PaypalController extends Controller
{
private $_apiContext;
public function __construct()
{
$paypal_conf = \Config::get('paypal');
$this->_apiContext = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_apiContext->setConfig($paypal_conf['settings']);
/*$this->_apiContext = Paypal::ApiContext(
config('services.paypal.client_id'),
config('services.paypal.secret'));
$this->_apiContext->setConfig(array(
'mode' =>'sandbox',
'service.EndPoint' => 'https://api.sandbox.paypal.com',
'http.ConnectionTimeOut' => 30,
'log.LogEnabled' => true,
'log.FileName' => storage_path('logs/paypal.log'),
'log.LogLevel' => 'FINE',
));*/
}
public function payPremium()
{
return view('payPremium');
}
public function getCheckout(Request $request)
{
$payer = Paypal::Payer();
$payer->setPaymentMethod('paypal');
$amount = Paypal::Amount();
$amount->setCurrency('USD');
$amount->setTotal($request->input('pay'));
$transaction = Paypal::Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('Compra de Plan '.$request->input('type').' Precio por mensualidad '.$request->input('pay'). 'Descripción del plan: '.$request->input('description'));
$redirectUrls = Paypal::RedirectUrls();
$redirectUrls->setReturnUrl(route('getDone'));
$redirectUrls->setCancelUrl(route('getCancel'));
$payment = Paypal::Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setRedirectUrls($redirectUrls);
$payment->setTransactions(array($transaction));
try{
$payment->create($this->_apiContext);
} catch (\PayPal\Exception\PayPalConnectionException $ex){
if(\Config::get('app.debug')){
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
echo $err_data;
echo $ex->getMessage();
echo $ex->getCode();
echo $ex->getData();
exit(1);
} else {
die('Ups! Algo salio mal');
}
}
foreach ($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url'){
$redirectUrls = $link->getHref();
break;
}
}
Session::put('paypal_payment_id', $payment->getId());
if(isset($redirectUrls)){
return \Redirect::away($redirectUrls);
}
return \Redirect::route('payPremium')->with('message', 'Ups! Error desconocido.');
/*$response = $payment->create($this->_apiContext);*/
/*$redirectUrl = $response->links[1]->href;*/
/*$paymentExecution = Paypal::PaymentExecution();
$id = $request->get('paymentId');
$token = $request->get('token');
$payer_id = $request->get('PayerID');
$payment = Paypal::getById($id, $this->_apiContext);
$paymentExecution->setPayerId($payer_id);
$executePayment = $payment->execute($paymentExecution, $this->_apiContext);
if ($executePayment->getState() == 'approved') {
dd($executePayment);
dd($amount);
$transactions = new Transaction;
$transactions->payer = $payer_id;
$transactions->paymentID = $id;
$transactions->amount = array_get($amount, 'setTotal');
$transactions->description = array_get($transaction, 'setDescription');
$transactions->statuses_id = 10;
$transactions->save();
}
else
{
dd('Error en su pago');
$transactions = new Transaction;
$transactions->payer = $payer_id;
$transactions->paymentID = $id;
$transactions->amount = $amount;
$transactions->description = $description;
$transactions->statuses_id = 11;
$transactions->save();
}*/
/*return redirect()->to( $redirectUrl );*/
}
public function getDone(Request $request)
{
$payment_id = \Session::get('paypal_payment_id');
\Session::forget('paypal_payment_id');
$payerId = $request->get('paymentId');
$token = $request->get('PayerID');
if(empty($payerId) || empty($token)){
return \Redirect::route('payPremium')->with('message', 'Hubo un problema al intentar pagar con Paypal');
}
$payment = Payment::get($payment_id, $this->_apiContext);
$execution = new PaymentExecution();
$execution->setPayerId($request->get('paymentId'));
$result = $payment->execute($execution, $this->_apiContext);
if ($result->getState() == 'approved') {
return \Redirect::route('payPremium')->with('message', 'Compra realizada de forma correcta');
} else {
return \Redirect::route('payPremium')->with('message', 'La compra fue cancelada');
}
// $paymentExecution = Paypal::PaymentExecution();
// $id = $request->get('paymentId');
// $token = $request->get('token');
// $payer_id = $request->get('PayerID');
// $payment = Paypal::getById($id, $this->_apiContext);
// $paymentExecution->setPayerId($payer_id);
// $executePayment = $payment->execute($paymentExecution, $this->_apiContext);
// if ($executePayment->getState() == 'approved') {
// /*dd($executePayment);*/
// dd($amount);
// $transactions = new Transaction;
// $transactions->payer = $payer_id;
// $transactions->paymentID = $id;
// $transactions->amount = $price;
// $transactions->description = $description;
// $transactions->statuses_id = 10;
// $transactions->save();
// }
// else
// {
// dd('Error en su pago');
// $transactions = new Transaction;
// $transactions->payer = $payer_id;
// $transactions->paymentID = $id;
// $transactions->amount = $amount;
// $transactions->description = $description;
// $transactions->statuses_id = 11;
// $transactions->save();
// }
}
public function getCancel()
{
return redirect()->route('payPremium');
}
</code></pre>
<p>}</p>
| 3 | 3,459 |
You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition, but it will be removed soon
|
<p>I am uploading data to database using WWW.
I have two data classes for data object.</p>
<pre><code>[Serializable]
public class pushdatawrapper{
public string email;
public pushdata[] shotsArray=new pushdata[1];
}
[Serializable]
public class pushdata{
public string timehappened;
public string clubtype;
public pushdata(string timestamp_,string clubtype_)
{
timehappened = timestamp_;
clubtype = clubtype_;
}
}
</code></pre>
<p>Loading Json array of data object to database, I tried two approaches.
The first one was ok, but the second one is always failed at calling <code>StartCoroutine</code> function.</p>
<p><code>First approach</code></p>
<pre><code>public class BLEBridge : MonoBehaviour {
void Start () {
pushdata_ pdata = new pushdata_("123123123123.0","15","123.0","123.0", "123.0", "123.0","123.0", "123.0","123.0","123.0","123.0","123.0", "First");
pushdatawrapper_ pw = new pushdatawrapper_ ();
pw.email = "test@gmail.com";
pw.shotsArray[0] = pdata;
StartCoroutine (PushData_ (pw));
}
private IEnumerator PushData_(pushdatawrapper_ pdata){
WWW www;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
string dataToJason = JsonUtility.ToJson(pdata);
Debug.Log ("dataToJason " + dataToJason);
// convert json string to byte
var formData = System.Text.Encoding.UTF8.GetBytes(dataToJason);
www = new WWW("http://rmotion.rapsodo.com/api/push/new", formData, postHeader);
StartCoroutine(WaitForRequest(www));
return www;
}
IEnumerator WaitForRequest(WWW data)
{
yield return data; // Wait until the download is done
if (data.error != null)
{
Debug.Log("There was an error sending request: " + data.text);
}
else
{
Debug.Log("WWW Request: " + data.text);
}
}
}
</code></pre>
<p>This first method is always ok.
But in actual implementation, I need to upload data from a static function. Those <code>private IEnumerator PushData_(pushdatawrapper_ pdata) and IEnumerator WaitForRequest(WWW data)</code> can't be static.</p>
<p>So what I did was
I made a separate class as</p>
<pre><code>public class UploadData: MonoBehaviour{
public void uploadindividualshot(pushdatawrapper pw){
StartCoroutine (PushData (pw));
}
private IEnumerator PushData(pushdatawrapper pdata){
WWW www;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
string dataToJason = JsonUtility.ToJson(pdata);
Debug.Log ("dataToJason " + dataToJason);
// convert json string to byte
var formData = System.Text.Encoding.UTF8.GetBytes(dataToJason);
Debug.Log ("before www ");
www = new WWW("http://rmotion.rapsodo.com/api/push/new", formData, postHeader);
Debug.Log ("after new ");
StartCoroutine(WaitForRequest(www));
Debug.Log ("after WaitForRequest ");
return www;
}
IEnumerator WaitForRequest(WWW data)
{
Debug.Log ("start pushing ");
yield return data; // Wait until the download is done
if (data.error != null)
{
Debug.Log("There was an error sending request: " + data.text);
}
else
{
Debug.Log("WWW Request: " + data.text);
}
}
}
</code></pre>
<p>Then call the instance of the class from static method as</p>
<pre><code>public class BLEBridge : MonoBehaviour {
void Start(){}
public unsafe static void GetGolfREsult()
{
pushdata pdata = new pushdata("123123123123.0","15","123.0","123.0", "123.0", "123.0","123.0", "123.0","123.0","123.0","123.0","123.0", "First");
pushdatawrapper pw = new pushdatawrapper();
pw.email = Login.loginName;
pw.shotsArray[0] = pdata;
UploadData up = new UploadData ();
up.uploadindividualshot (pw);
}
}
</code></pre>
<p>I always have error as</p>
<pre><code>after new
UploadData:PushData(pushdatawrapper)
BLEBridge:GetGolfREsult()
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
libc++abi.dylib: terminating with uncaught exception of type Il2CppExceptionWrapper
2018-04-29 17:25:25.565292+0800 RMotion[270:7241] You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition, but it will be removed soon. Please consider updating to https.
</code></pre>
<p>The program has error at <code>StartCoroutine(WaitForRequest(www));</code></p>
<p>What is wrong with second approach?</p>
| 3 | 1,949 |
I can't take QObject information from an object created as a subclass of QObject using reflection
|
<p>I have to create an instance of an object (subclass of <code>QObject</code>) using reflection. </p>
<p>Let's suppose this object is <code>MyQObject</code> and have declared the following properties using the <code>Q_PROPERTY</code> macro: <code>MyQObject1* p1</code>, <code>MyQObject2* p2</code>, <code>MyQObject3* p3</code>, ...</p>
<p>Let's say I have this function to do that:</p>
<pre><code> QObject* Manager::createInstanceOf(const QMetaObject* c, QList<const char*> paramsNames, QList<QObject*> oparams) {
QObject* instance = (QObject*) c->newInstance();
for(int i = 0; i < paramsNames.length(); i++) {
QVariant variant = QVariant::fromValue(oparams[i]);
instance->setProperty(paramsNames[i], variant);
}
return instance;
}
</code></pre>
<p>where:</p>
<p><code>c</code> is the <code>QMetaObject*</code> associated with <code>MyQObject</code>.</p>
<p><code>paramsNames</code> is a <code>QList<const char*></code> containing the names of the properties declared in the object's class definition through the <code>Q_PROPERTY</code> macro. In this example, <code>QList</code> contains: <code>"MyQObject1"</code>, <code>"MyQObject2"</code>, <code>"MyQObject3"</code>, ...</p>
<p><code>oparams</code> is a <code>QList<QObject*></code> containing the properties of the object already instantiated. None of them is a <code>QObject</code> per se, but a subclass of <code>QObject</code>, and might not be all the same. In this example, a <code>QList</code> containing a instance for <code>MyQObject1</code>, <code>MyQObject2</code>, <code>MyQObject3</code>...</p>
<p>My problem is that although the instance of <code>MyQObject</code> is created and the types were registered using <code>Q_DECLARE_METATYPE</code> macro and <code>qRegisterMetaType</code>, I can't access to any of the properties' methods associated with <code>QObject</code> without getting segfault. In few words, I can't do:</p>
<pre><code>myQObjectInstance->property("p1").value<MyQObject1*>()->metaObject();
</code></pre>
<p>but I can access without problem other methods of the properties that are not from <code>QObject</code>. For example:</p>
<pre><code>myQObjectInstance->property("p1").value<MyQObject1*>()->toString();
</code></pre>
<p>I realized that if I cast the property before doing the <code>setProperty</code>, my problem can be solved partially: </p>
<pre><code>QVariant::fromValue((MyQObject1*) oparams[0]);
</code></pre>
<p>It seems to be that if the property is not set as the specific subclass of <code>QObject</code> as it was created, but casted as its superclass (when inserted in <code>oparams</code> <code>QList</code> they are automatically casted), is what causes the problem.</p>
<p>Due to the different types of the properties (<code>MyQObject1</code>, <code>MyQObject2</code>, <code>MyQObject3</code>,...) I can't cast one by one because I don't know this information at compile time. </p>
<p>So, any ideas?</p>
<p>I will really appreciate your help. Thanks.</p>
| 3 | 1,084 |
start navigating to position which is stored in database
|
<p>I have an application where I am getting the latitude and longitude coordinates.</p>
<p>I want , when to press a button to start navigating to that position .</p>
<p>Now , I am storing latitude and longitude in database.</p>
<p>So , I want to extract the location first.When I press the button to navigate I open an alertdialog and in 'YES' I do:</p>
<pre><code>public void navigation(final View v){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Do you want to navigate to the saved position?")
.setCancelable(false)
.setPositiveButton("Navigate",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// Action for 'Yes' Button
String query = "SELECT latitude,longitude FROM MEMORIES ";
Cursor c1 = sqlHandler.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
String mylatitude=c1.getString(c1.getColumnIndex("latitude"));
String mylongitude=c1.getString(c1.getColumnIndex("longitude"));
Double lat=Double.parseDouble(mylatitude);
Double lon=Double.parseDouble(mylongitude);
} while (c1.moveToNext());
}
}
c1.close();
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" +
gps.getLocation().getLatitude() + "," +
gps.getLocation().getLongitude() + "&daddr=" + mylatitude + "," + mylongitude ));
startActivity(intent);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Navigation");
alert.show();
}
</code></pre>
<p>I have the location stored (lat and lon) and i want to start navigating to that position.
How can I do that?</p>
<p>Thanks!</p>
<p>---------------------UPDATE-------------------------------------</p>
<p>If I do sth like:</p>
<pre><code> String mylat="";
String mylon="";
@Override
protected void onCreate(Bundle savedInstanceState) {
...
...
public void navigation(final View v){
....
String mylatitude=c1.getString(c1.getColumnIndex("latitude"));
String mylongitude=c1.getString(c1.getColumnIndex("longitude"));
mylat=mylatitude;//stored coordinates from database
mylon=mylongitude;
String f="45.08" //current location (start points)
String s="23.3";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" +
f + "," +
s + "&daddr=" + mylat + "," + mylon ));
startActivity(intent);
</code></pre>
<p>The intent starts and I am in the map application where the start points are the "f" and "s" I defined above but the destination points are 0.0 , 0.0 ;</p>
<p>So , I have 2 problems:</p>
<p>1) How to put to destination points my stored locations (mylatitude ,mylongitude (which I copy to mylat,mylon)</p>
<p>2) How to get current location (initial points) because my gps class doesn't work on that.</p>
| 3 | 1,820 |
Restructuring Dataframe
|
<p>I have a dataframe that currently looks as follows and has 262800 rows and 3 columns. My dataframe is currently as follows:</p>
<pre><code> Currency Maturity value
0 GBP 0.08333333 4.709456
1 GBP 0.08333333 4.713099
2 GBP 0.08333333 4.707237
3 GBP 0.08333333 4.705043
4 GBP 0.08333333 4.697150
5 GBP 0.08333333 4.710647
6 GBP 0.08333333 4.701150
7 GBP 0.08333333 4.694639
8 GBP 0.08333333 4.686111
9 GBP 0.08333333 4.714750
......
262770 GBP 25 2.432869
</code></pre>
<p>I want the dataframe to be of the form below. I've taken some steps towards this, which included using <code>melt</code> in the code below, but for some reason that got rid of my <code>Date</code> Column and resulted in the dataframe above. I am unsure how to get the Date Column back and obtain the Dataframe below:</p>
<pre><code> Maturity Date Currency Yield_pct
0 0.08333333 2005-01-04 GBP 4.709456
1 0.08333333 2005-01-05 GBP 4.713099
2 0.08333333 2005-01-06 GBP 4.707237
....
9 25 2005-01-04 GBP 2.432869
</code></pre>
<p>My code is as follows:</p>
<pre><code>from pandas.io.excel import read_excel
import pandas as pd
import numpy as np
url = 'http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/uknom05_mdaily.xls'
# check the sheet number, spot: 9/9, short end 7/9
spot_curve = read_excel(url, sheetname=8)
short_end_spot_curve = read_excel(url, sheetname=6)
# do some cleaning, keep NaN for now, as forward fill NaN is not recommended for yield curve
spot_curve.columns = spot_curve.loc['years:']
spot_curve.columns.name = 'Maturity'
valid_index = spot_curve.index[4:]
spot_curve = spot_curve.loc[valid_index]
# remove all maturities within 5 years as those are duplicated in short-end file
col_mask = spot_curve.columns.values > 5
spot_curve = spot_curve.iloc[:, col_mask]
short_end_spot_curve.columns = short_end_spot_curve.loc['years:']
short_end_spot_curve.columns.name = 'Maturity'
valid_index = short_end_spot_curve.index[4:]
short_end_spot_curve = short_end_spot_curve.loc[valid_index]
# merge these two, time index are identical
# ==============================================
combined_data = pd.concat([short_end_spot_curve, spot_curve], axis=1, join='outer')
# sort the maturity from short end to long end
combined_data.sort_index(axis=1, inplace=True)
def filter_func(group):
return group.isnull().sum(axis=1) <= 50
combined_data = combined_data.groupby(level=0).filter(filter_func)
idx = 0
values = ['GBP'] * len(combined_data.index)
combined_data.insert(idx, 'Currency', values)
#print combined_data.columns.values
#I had to do the melt
combined_data = pd.melt(combined_data,id_vars=['Currency'])#Arbitrarily melted on 'Currency' as for some reason when I do print combined_data.columns.values I see that 'Currency' corresponds to 0.08333333, etc.
print combined_data
</code></pre>
| 3 | 1,301 |
ChartJS 'Line chartjs' does not show output in NodeRED?
|
<p>My requirement is to output 2 y-axis chart with real-time data readings in NodeRED. I have installed <code>ChartJS</code> package in NodeRED and now according to the documentation of the package there should be <code>PATH, Title, X-Axis, Y-Axis, Payload</code>. But I couldn't find the <code>Payload</code> tab anywhere in the <code>Line Chartjs</code> node?</p>
<p><a href="https://i.stack.imgur.com/n5aEJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n5aEJ.png" alt="enter image description here" /></a></p>
<p>Ref : <a href="https://www.npmjs.com/package/node-red-contrib-chartjs" rel="nofollow noreferrer">https://www.npmjs.com/package/node-red-contrib-chartjs</a></p>
<p><a href="https://i.stack.imgur.com/KoleG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KoleG.png" alt="enter image description here" /></a></p>
<p>So I assumed that I have to add the code which belonged to <code>Payload</code> inside a function node before the <code>Line Chartjs node</code>.</p>
<p>What I have tried : (my function node)</p>
<pre><code>var left = {payload : msg.payload.readResults[0].v };
var right = {payload : msg.payload.readResults[1].v };
//return [[left,right]];
const labels = [1,2,3,4,5,6,7,8,9,10];
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: left,
borderColor: '#ff0000',
backgroundColor: '#ff0000',
yAxisID: 'leftCamber',
},
{
label: 'Dataset 2',
data: right,
borderColor: '#0000ff',
backgroundColor: '#0000ff',
yAxisID: 'rightCamber',
}
]
};
const config = {
type: 'line',
data: data,
options: {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
stacked: false,
plugins: {
title: {
display: true,
text: 'Chart.js Line Chart - Multi Axis'
}
},
scales: {
leftCamber: {
type: 'linear',
display: true,
position: 'left',
},
rightCamber: {
type: 'linear',
display: true,
position: 'right',
// grid line settings
grid: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
},
}
},
};
const actions = [
{
name: 'CamberGraph',
handler(chart) {
chart.data.datasets.forEach(dataset => {
dataset.data = chart.data.labels.length
});
chart.update();
}
},
];
</code></pre>
<p>Here I have tried to get the 2 HTTP outputs I've named as <code>left</code> and <code>right</code> as my datasets(2 y-axis) vs hardcoded x-axis(1 through 10) which will be <code>Footage</code> later on.</p>
<p>PS : I have returned the <code>left</code> and <code>right</code> using return statement and it's outputting the values as I expected.</p>
<p>Currently I do not get any output in my debug window as well as in my <code>ChartJS Line Chart</code> when I inject the node. Using what I've tried so far can anybody show where I've done wrong or add/remove anything to make the graph work?</p>
<p>Thank you!</p>
| 3 | 1,256 |
Delete Row from html table on icon click using flask, python, and sqlite
|
<p>I'm at a total loss on how to do this. I'm building a webpage and I need to be able to delete a record from my SQLite database once the user clicks the delete icon on the front end. Can someone please help me figure out how to do this? I have no experience using PHP so any reference to that just won't be helpful. As you can see from the entries page a user will be able to see all entries entered already; each entry_id is unique. If a user clicks delete, then I want the row deleted from the entries page, and also deleted from the DB. If a user clicks the edit button that's another beast, and I'd like to be able to show on click, the populated form in edit mode, and once a user makes changes and click save, then have those changes updated in the DB as well.</p>
<p>Here's my html code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends "layout.html" %}
{% block title %}
index
{% endblock %}
{% block main %}
{% if msg %}
<div class="alert alert-danger" role="alert"> {{ msg }}
</div>
{% endif %}
<div>
<form method="POST" action="/entries">
<table class="table table-hover table-sm table-bordered">
<thead class="thead-light">
<tr>
<th class="col-auto"> ID </th>
<!--<th class="col-auto" style="display:none;"> entryid</th>-->
<th class="col-auto"> Edit </th>
<th class="col-auto"> Delete </th>
<th class="col-auto">View</th>
<th class="col-auto">Date</th>
<th class="left">Title</th>
<th class="left">Notes</th>
</tr>
</thead>
<tbody >
{% for row in entrylist %}
<tr>
<td id="{{row.entry_id}}"></td>
<!--<td style="display:none;" id="{{row.entry_id}}"> {{row.entry_id}}-->
<td> <a title="Add" data-toggle="tooltip" class="btn" id="{{row.entry_id}}"><i class="bi bi-pencil-fill"> </i></a></td>
<td> <a class="btn" data-toggle="tooltip" title="delete" id="{{row.entry_id}}"><i class="bi bi-trash" style="color:red;"></i></a></td>
<td> <a class="btn" data-toggle="tooltip" title = "view" id="{{row.entry_id}}"><i class="bi bi-journals"></i></a></td>
<td id="{{row.entry_id}}"> {{row.entry_dt}}</td>
<td class="ellipsistd" id="{{row.entry_id}}"> {{row.title }} </td>
<td class="ellipsis" id ="{{row.entry_id}}">{{row.notes }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</div>
{% endblock %}</code></pre>
</div>
</div>
</p>
<p>Here's my flask code:</p>
<pre><code>@app.route("/entries", methods=['GET'])
@login_required
def entries():
if request.method == "GET":
entrylist = db.execute ("SELECT * FROM entries WHERE id = ? AND entry_dt <> '' ORDER BY entry_id", session["user_id"])
# print(entrylist)
return render_template ("entries.html", entrylist = entrylist)
</code></pre>
| 3 | 1,718 |
Shared Preferences in music player
|
<p>I created a Music stream app that fetch the data from the firebase but i have a one issue in my app when i play a song and go back and come again then seek bar does not shows the current duration . So i think i should use Shared Preferences but i don't known how to use can any one suggest me the code for my music player </p>
<pre><code> public class ViewUploadsActivity extends AppCompatActivity implements
MediaPlayer.OnBufferingUpdateListener,View.OnTouchListener
,MediaPlayer.OnCompletionListener{
//the listview
ListView listView;
private SeekBar seekBarProgress;
private int mediaFileLengthInMilliseconds;
private final Handler handler = new Handler();
CustomArrayAdapter adapter;
//database reference to get uploads data
DatabaseReference mDatabaseReference;
//list to store uploads data
List<Upload> uploadList = new ArrayList<>();
private TextView mSelectedTrackTitle,selected_track_ar;
private ImageView mSelectedTrackImage;
private MediaPlayer mMediaPlayer =new MediaPlayer();
private ImageView mPlayerControl;
Toolbar toolbar2;
TextView length;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_upload);
listView = (ListView) findViewById(R.id.listView);
//status = (TextView) findViewById(R.id.status);
seekBarProgress = (SeekBar)findViewById(R.id.length);
listView.setStackFromBottom(true);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
togglePlayPause();
}
});
mMediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mPlayerControl.setImageResource(R.drawable.ic_play);
}
});
mSelectedTrackTitle = (TextView)findViewById(R.id.selected_track_title);
mSelectedTrackImage =
(ImageView)findViewById(R.id.selected_track_image);
mSelectedTrackTitle.setSelected(true);
mPlayerControl = (ImageView)findViewById(R.id.player_control);
selected_track_ar=(TextView)findViewById(R.id.selected_track_ar);
mPlayerControl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
togglePlayPause();
}
});
get();
//getting the database reference
mDatabaseReference = FirebaseDatabase.getInstance().getReference
(Constants.DATABASE_PATH_UPLOADS);
//retrieving upload data from firebase database
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
uploadList.add(upload);
}
adapter = new CustomArrayAdapter(getApplicationContext(),
(ArrayList<Upload>) uploadList);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Intent svc=new Intent(this, MySongServices.class);
startService(svc);
}
private void togglePlayPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mPlayerControl.setImageResource(R.drawable.ic_play);
} else if(!mMediaPlayer.isPlaying()){
mMediaPlayer.start();
mPlayerControl.setImageResource(R.drawable.ic_pause);
mediaFileLengthInMilliseconds = mMediaPlayer.getDuration();
primarySeekBarProgressUpdater();
}
}
public void get()
{
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int
i, long l) {
//getting the upload
Upload upload = uploadList.get(i);
mSelectedTrackTitle.setText(upload.getName());
selected_track_ar.setText(upload.getAr());
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
seekBarProgress.setProgress(0);
}
try {
mMediaPlayer.setDataSource(upload.getUrl());
mMediaPlayer.prepare();
show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void primarySeekBarProgressUpdater() {
try {
seekBarProgress.setProgress((int) (((float)
mMediaPlayer.getCurrentPosition()
/ mediaFileLengthInMilliseconds) * 100));
if (mMediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.length){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer
to
seekBar primary progress position*/
if(mMediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds
/ 100) * sb.getProgress();
mMediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
}
</code></pre>
| 3 | 2,610 |
Finding closest input text after select dropdown was chosen
|
<p>So what I'm trying to do is change value of the input with id championSpell[] whenever something from dropdown select name="change[]" id="change[] is chosen. Inputs are generated dynamically. Test variable in function val() is responsible for that change and is the one I have problems with.</p>
<pre><code><script src="LeagueNotes/js/jquery.min.js"></script>
<script src="LeagueNotes/js/champions_list.js"></script>
<script src="LeagueNotes/js/jquery.validate.min.js"></script>
<style>
* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }
input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
</style>
<h2>
<a href="#" id="addChampion">Add Another Champion</a>
</h2>
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="champion[]" size="20" list="champions" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
<a href="#" id="addGeneral">Add General Change</a><a></a>
<a href="#" id="addSpell"> Add Spell</a><a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
<script>
for(var key in champions){
if(champions.hasOwnProperty(key)){
$('#champions').append('<option value="' + key + '">');
}
}
var config = {
fillAll: true
};
document.forms["second_form"].oninput = function(e) {
var champion = this["champion[]"];
//Force into array
if (champion[0] === undefined)
champion = [this["champion[]"]];
var reached = {
valid: 0,
unique: 0
};
var inputs = [].map.call(champion, function(n) {
return n.value
}).filter(function(n) {
return n.length
});
var valid = [].every.call(champion, function(n, i) {
n.setCustomValidity("");
if (config.fillAll) return (reached.valid = i, champions.hasOwnProperty(n.value));
else return n.value ? (
reached.valid = i,
champions.hasOwnProperty(n.value) > -1
) : true;
});
var unique = inputs.slice(0).sort().every(function(n, i, a) {
reached.unique = inputs.lastIndexOf(n);
return n != a[i - 1];
});
//Check for valid champions
if (!valid) {
champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
}
//Check for duplicates
if (!unique) {
champion[reached.unique].setCustomValidity("This champion has already been entered.")
}
this.checkValidity();
};
function change(x, dblchamp){
if(dblchamp===true){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="Q2"){x=2;}
if(x==="W"){x=3;}
if(x==="W2"){x=4;}
if(x==="E"){x=5;}
if(x==="E2"){x=6;}
if(x==="R"){x=7;}
if(x==="R2"){x=8;}
}else if(dblchamp===false){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
}
console.log(x);
return x;
}
function val(elm) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
//var championName = $("#change").closest('input').val();
//var championName =$("#champion\\[\\]").val();
var championName = $(elm).closest("label").find("input").val();
//document.getElementById("champion[]").value;
console.log(championName);
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
var d = $(elm).val();
var spellname = document.getElementById("championSpell[]");
var z = champions[""+championName+""][change(d, existsInArray)];
test = $(elm).nextAll("input").first().val('test');
test.value=champions[""+championName+""][change(d, existsInArray)];
}
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents label').size() + 1;
var j =0;
$('body').on('click', '#addChampion', function() {
$('<p><a href="#" id="remScnt">Remove</a><br><label for="p_scnts"><input type="text" id="champion[]" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion\'s name" /><datalist id="champions"></datalist><a href="#" id="addGeneral">Add General Change</a><a href="#" id="addSpell"> Add Spell</a><a></a></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('body').on('click', '#remScnt', function() {
if( i >2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('body').on('click', '#addGeneral',function() {
$(
'<p><label for="var"><textarea type="text" id="champion[]" size="20" name="GeneralChange[]" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> <a href="#" id="remVar">Remove Change</a></p>').appendTo($(this).next());
j++;
return false;
});
$('body').on('click', '#remVar',function() {
$(this).parent('p').remove();
return false;
});
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> <a href="#" id="addGeneral">Add Change</a> <a href="#" id="remVar">Remove Spell</a></p>').appendTo($(this).next());
return false;
});
});
</script>
</code></pre>
| 3 | 4,379 |
Context initialization failed(Caused by No qualifying bean of type)
|
<p>I tried to run my first web application using Spring MVC and Hibernate, but I have some problem.</p>
<p>GenericDao:</p>
<pre><code>@Repository
public abstract class GenericDao<T> implements GeneralDao<T> {
private Class<T> className;
protected GenericDao(Class<T> className) {
this.className = className;
}
@PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@Override
public void add(T object) {
try {
getEntityManager().persist(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_ADD_ENTITY_FAIL, e);
}
}
@Override
public void update(T object) {
try {
getEntityManager().merge(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_UPDATE_ENTITY_FAIL, e);
}
}
@Override
public void remove(T object) {
try {
getEntityManager().remove(object);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_REMOVE_ENTITY_FAIL, e);
}
}
@Override
public T getById(int id) {
try {
return getEntityManager().find(this.className, id);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_BY_ID_ENTITY_FAIL, e);
}
}
public abstract List<T> getAll() throws DaoException;
}
</code></pre>
<p>GenericService:</p>
<pre><code>@Service("genericService")
public abstract class GenericService<T> implements GeneralService<T> {
public abstract GenericDao<T> getGenericDao();
@Transactional
@Override
public void add(T object) throws ServiceException {
try {
getGenericDao().add(object);
} catch (DaoException e) {
throw new ServiceException(e.getMessage());
}
}
@Transactional
@Override
public void update(T object) throws ServiceException {
try {
getGenericDao().update(object);
} catch (DaoException e) {
throw new ServiceException(e.getMessage());
}
}
@Transactional
@Override
public void remove(T object) throws ServiceException {
try {
getGenericDao().remove(object);
} catch (DaoException e) {
throw new ServiceException(e.getMessage());
}
}
@Transactional(readOnly = true)
@Override
public T getById(int id) throws ServiceException {
try {
return getGenericDao().getById(id);
} catch (DaoException e) {
throw new ServiceException(e.getMessage());
}
}
@Transactional(readOnly = true)
@Override
public List<T> getAll() throws ServiceException {
try {
return getGenericDao().getAll();
} catch (DaoException e) {
throw new ServiceException(e.getMessage());
}
}
}
</code></pre>
<p>UserDao.java</p>
<pre><code>@Repository
public class UserDao extends GenericDao<User> {
private final static String USER_LOGIN = "login";
private final static String USER_PASSWORD = "password";
@Autowired
private UserDao() {
super(User.class);
}
@Override
public List<User> getAll() {
List<User> userList;
try {
userList = getEntityManager().createQuery(Statement.GET_ALL_USERS).getResultList();
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_ALL_ENTITY_FAIL, e);
}
return userList;
}
@Transactional
public List<User> getByLoginAndPassword(String userLogin, String userPassword) {
CriteriaQuery<User> criteriaQuery;
try {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<User> userRoot = criteriaQuery.from(User.class);
criteriaQuery.select(userRoot);
criteriaQuery.where(
criteriaBuilder.equal(userRoot.get(USER_LOGIN), userLogin),
criteriaBuilder.equal(userRoot.get(USER_PASSWORD), userPassword)
);
} catch (HibernateException e) {
throw new DaoException(ErrorMessage.MESSAGE_GET_ENTITY_BY_LOGIN_AND_PASSWORD_FAIL, e);
}
return getEntityManager().createQuery(criteriaQuery).getResultList();
}
}
</code></pre>
<p>UserService.java</p>
<pre><code>@Service("userService")
@Transactional
public class UserService extends GenericService<User> {
private static Logger logger = Logger.getLogger(UserService.class);
@Autowired
private UserDao userDao;
@Override
public GenericDao<User> getGenericDao() {
return userDao;
}
public String checkUser(String userLogin, String userPassword) throws ServiceException {
String namePage = "errorAuthorization";
List<User> userList;
try {
userList = userDao.getByLoginAndPassword(userLogin, userPassword);
} catch (DaoException e) {
logger.debug(e);
throw new ServiceException(e.getMessage());
}
if(userList.size() != 0) {
return UserRoleChecker.defineUserPage(userList.get(0));
}
return namePage;
}
public void addUser(String userLogin, String userPassword, String userMail) throws ServiceException{
Role role = new Role(0, RoleType.USER);
User user = new User(0, userLogin, userPassword, userMail, role);
add(user);
}
}
</code></pre>
<p>root-context.xml:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="by.netcracker.artemyev" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/airline?useSSL=false" />
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="10"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="by.netcracker.artemyev" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="database" value="MYSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="debug">true</prop>
<prop key="connection.isolation">2</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
</beans>
</code></pre>
<p>Logs:</p>
<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userDao'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDao' is expected to be of type 'by.netcracker.artemyev.dao.UserDao' but was actually of type 'com.sun.proxy.$Proxy31'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4744)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5206)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDao' is expected to be of type 'by.netcracker.artemyev.dao.UserDao' but was actually of type 'com.sun.proxy.$Proxy31'
at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1503)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1482)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 60 more
</code></pre>
<p>Questions:
Please explain me why I have this problem?
How to fix this error?</p>
| 3 | 6,693 |
How to do a t-test for dependent variable by groups
|
<p>i want to show, if there is there a significant change in VO2max between the two groups (Experimentalgruppe and Kontrollgruppe).
Therefor i have to make zwo t-tests (betwenn t0/t1 and t1/t2) for dependet variables with the following data:</p>
<pre><code># A tibble: 18 x 4
group `t0 VO2 max` `t1 VO2 max` `t2 VO2 max`
<chr> <dbl> <dbl> <dbl>
1 Experimentalgruppe 47.6 47.9 48.7
2 Kontrollgruppe 47.6 46.5 43.0
3 Experimentalgruppe 47.6 48.7 48.7
4 Kontrollgruppe 46.8 47.6 46.2
5 Kontrollgruppe 44.6 46.2 47.9
6 Experimentalgruppe 41.3 42.1 42.4
7 Kontrollgruppe 38 40.7 38.6
8 Experimentalgruppe 43.5 44.6 42.7
9 Experimentalgruppe 41.9 43.2 43.8
10 Kontrollgruppe 45.1 47.9 49.2
11 Experimentalgruppe 44.1 44.3 44.9
12 Kontrollgruppe 28.5 30.9 30.3
13 Kontrollgruppe 38.6 41.6 42.1
14 Kontrollgruppe 44.6 45.4 47.6
15 Kontrollgruppe 40.4 43.0 42.4
16 Experimentalgruppe 32.6 33.3 33.3
17 Experimentalgruppe 40.4 38.6 43.0
18 Kontrollgruppe 44.3 40.1 42.7
</code></pre>
<p>the dput is here:</p>
<pre><code>> dput(data)
structure(list(group = c("Experimentalgruppe", "Kontrollgruppe",
"Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe",
"Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
"Kontrollgruppe", "Experimentalgruppe", "Kontrollgruppe", "Kontrollgruppe",
"Kontrollgruppe", "Kontrollgruppe", "Experimentalgruppe", "Experimentalgruppe",
"Kontrollgruppe"), `t0 VO2 max` = c(47.6, 47.6, 47.6, 46.7818181818182,
44.6, 41.3, 38, 43.5090909090909, 41.8727272727273, 45.1454545454545,
44.0545454545455, 28.475, 38.6, 44.6, 40.4, 32.6, 40.4, 44.3272727272727
), `t1 VO2 max` = c(47.8727272727273, 46.5090909090909, 48.6909090909091,
47.6, 46.2363636363636, 42.1454545454545, 40.7, 44.6, 43.2363636363636,
47.8727272727273, 44.3272727272727, 30.9333333333333, 41.6, 45.4181818181818,
42.9636363636364, 33.2666666666667, 38.6, 40.1), `t2 VO2 max` = c(48.6909090909091,
42.9636363636364, 48.6909090909091, 46.2363636363636, 47.8727272727273,
42.4181818181818, 38.6, 42.6909090909091, 43.7818181818182, 49.2363636363636,
44.8727272727273, 30.2666666666667, 42.1454545454545, 47.6, 42.4181818181818,
33.2666666666667, 42.9636363636364, 42.6909090909091)), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
</code></pre>
<p>As i am pretty new to R, i cant figure out, how to do this.</p>
<pre><code>t.test(Vo2Max.Auswertung$`t1 VO2 max`, Vo2Max.Auswertung$`t2 VO2 max`, paired = TRUE, alternative = "less")
</code></pre>
<p>This is a working t-test but its not divided into the two groups. Where is my mistake?</p>
| 3 | 1,850 |
Siamese network with third component error
|
<p>I was able to create a siamese network similar to :</p>
<p><a href="https://github.com/aspamers/siamese/" rel="nofollow noreferrer">https://github.com/aspamers/siamese/</a></p>
<p>The problem happens if I try to add a third model as an input to the head of my network.
I will get the following error :</p>
<pre><code>ValueError: Shape must be rank 2 but is rank 3 for '{{node head/concatenate/concat}} = ConcatV2[N=3, T=DT_FLOAT, Tidx=DT_INT32](simple/Identity, simple_1/Identity, different/Identity, head/concatenate/concat/axis)' with input shapes: [?,?], [?,?], [?,?,1], [].
</code></pre>
<p>Here is the code below, one thing I am not comfortable with is the line processed_a = base_model1(input_a) and what it does even after checking the Keras model doc. I understand that if I don't do it I cannot have the desired shape and provide the necessary inputs to the final network.</p>
<p>Note that if I replace the code with what is comment and just use a pure siamese network it will work ok.
Any idea what needs to be changed to resolve the above error and what base_model1(input_a) does.</p>
<pre><code>import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.python.keras.layers import *
def getModel1(input_shape):
model_input = Input(shape=input_shape)
layer = layers.Dense(32, activation='relu')(model_input)
layer = layers.Flatten()(layer)
return tf.keras.Model(inputs=model_input, outputs= layer, name="simple")
def getModel3(input_shape):
model_input = Input(shape=input_shape)
layer = layers.Dense(1, activation='relu')(model_input)
return tf.keras.Model(inputs=model_input, outputs=layer, name="different")
def outputModel(models):
inputs = []
for model in models:
inputs.append(Input(shape=model.output_shape))
layer = layers.Concatenate()(inputs)
layer = layers.Dense(1)(layer)
return tf.keras.Model(inputs=inputs, outputs=layer, name="head")
dataset = []
inputs1 = []
for i in range(0, 128):
dataset.append([0.0, 1.0, 2.0])
train_dataset1 = np.asarray(dataset)
base_model1 = getModel1(train_dataset1.shape)
dataset3 = [0.0, 1.0, 2.0]
train_dataset3 = np.asarray(dataset3)
base_model3 = getModel3(train_dataset3.shape)
input_a = Input(shape=base_model1.input_shape)
input_b = Input(shape=base_model1.input_shape)
input_c = Input(shape=base_model3.input_shape)
oModel = outputModel([base_model1, base_model1, base_model3])
#oModel = outputModel([base_model1, base_model1])
processed_a = base_model1(input_a)
processed_b = base_model1(input_b)
processed_c = base_model3(input_c)
head = oModel([processed_a, processed_b, processed_c])
model = tf.keras.Model(inputs=[input_a, input_b, input_c], outputs=head, name="model")
#head = oModel([processed_a, processed_b])
#model = tf.keras.Model(inputs=[input_a, input_b], outputs=head, name="model")
optimizer = tf.keras.optimizers.RMSprop(0.001)
model.compile(loss='mse',
optimizer=optimizer,
metrics=['mae', 'mse'])
model.predict([np.asarray([train_dataset1]), np.asarray([train_dataset1]), np.asarray([train_dataset3])])
#model.predict([np.asarray([train_dataset1]), np.asarray([train_dataset1])])
model.fit([np.asarray([train_dataset1]), np.asarray([train_dataset1]), np.asarray([train_dataset3])], np.asarray([1.0]), epochs=1000, validation_split=0, verbose=0, callbacks=[])
#model.fit([np.asarray([train_dataset1]), np.asarray([train_dataset1])], np.asarray([1.0]), epochs=1000, validation_split=0, verbose=0, callbacks=[])
</code></pre>
| 3 | 1,376 |
pytesseract.image_to_string(im) not able to access the input file
|
<p>Trying to read text from an image using pytesseract. Using the following two commands. Image.open does return the image properly, but the next command fails with windows error of file not found.</p>
<p>First of all I don't understand, why it is trying to read the image from the disk, as it is already read by previous statement and image im is already in the memory.
Then I have included the directory where pytesseract.exe is, in the path of environment variables, as suggested by some one. Still the same issue persists.</p>
<p>I am using anaconda distribution of python 3.5 on windows 10. Running the code from Jupyter Notebook, not python command line. </p>
<p>Installed pytesseract using pip, and corresponding import statement in jupyter notebook get executed without any error.</p>
<p>appreciate any help in resolving this issue.</p>
<pre><code>im = Image.open('test_image1.png')
text = pytesseract.image_to_string(im)
</code></pre>
<blockquote>
<p>FileNotFoundError Traceback (most recent call
last) in ()
1 im = Image.open('test_image1.png')
----> 2 text = pytesseract.image_to_string(im)</p>
<p>C:\Anaconda3\envs\keras35\lib\site-packages\pytesseract\pytesseract.py
in image_to_string(image, lang, config, nice, boxes, output_type)
191 return run_and_get_output(image, 'txt', lang, config, nice, True)
192
--> 193 return run_and_get_output(image, 'txt', lang, config, nice)
194
195 </p>
<p>C:\Anaconda3\envs\keras35\lib\site-packages\pytesseract\pytesseract.py
in run_and_get_output(image, extension, lang, config, nice,
return_bytes)
138 }
139
--> 140 run_tesseract(**kwargs)
141 filename = kwargs['output_filename_base'] + os.extsep + extension
142 with open(filename, 'rb') as output_file:</p>
<p>C:\Anaconda3\envs\keras35\lib\site-packages\pytesseract\pytesseract.py
in run_tesseract(input_filename, output_filename_base, extension,
lang, config, nice)
109 command.append(extension)
110
--> 111 proc = subprocess.Popen(command, stderr=subprocess.PIPE)
112 status_code, error_string = proc.wait(), proc.stderr.read()
113 proc.stderr.close()</p>
<p>C:\Anaconda3\envs\keras35\lib\subprocess.py in <strong>init</strong>(self, args,
bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds,
shell, cwd, env, universal_newlines, startupinfo, creationflags,
restore_signals, start_new_session, pass_fds)
674 c2pread, c2pwrite,
675 errread, errwrite,
--> 676 restore_signals, start_new_session)
677 except:
678 # Cleanup if the child failed starting.</p>
<p>C:\Anaconda3\envs\keras35\lib\subprocess.py in _execute_child(self,
args, executable, preexec_fn, close_fds, pass_fds, cwd, env,
startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread,
c2pwrite, errread, errwrite, unused_restore_signals,
unused_start_new_session)
955 env,
956 cwd,
--> 957 startupinfo)
958 finally:
959 # Child is launched. Close the parent's copy of those pipe</p>
<p>FileNotFoundError: [WinError 2] The system cannot find the file
specified</p>
</blockquote>
| 3 | 1,565 |
activiti execution.setvariable not working in task listener
|
<p>Good day.</p>
<p>I created a variable instance 'TaskAssignee' which will be utilize across task and flow.
TaskAssignee will store the task assignee name and show it in the next user task (via form).
I used the execution.setVariable inside the task listener but it didn't work.
How am i able to do it?</p>
<p>Here is the code :</p>
<pre><code><process id="GetAssigneePerTask2" name="Get Assignee Per Task" isExecutable="true">
<documentation>undefined</documentation>
<extensionElements>
<activiti:executionListener event="start" expression="${execution.setVariable(&quot;TaskAssignee&quot;, &quot;MyData&quot;)}"/>
<modeler:executionvariables xmlns:modeler="http://activiti.com/modeler" modeler:variableName="TaskAssignee" modeler:variableType="string"/>
</extensionElements>
<startEvent id="startEvent1"/>
<userTask id="sid-F533EC22-E107-49D2-ABDE-AE3BA402E8A4" name="Show Task User" activiti:assignee="$INITIATOR" activiti:formKey="2661">
<extensionElements>
<modeler:allow-send-email>true</modeler:allow-send-email>
<modeler:form-reference-id>2661</modeler:form-reference-id>
<modeler:form-reference-name>Show Data form</modeler:form-reference-name>
<modeler:initiator-can-complete>true</modeler:initiator-can-complete>
</extensionElements>
</userTask>
<sequenceFlow id="sid-F6A4A4AA-3075-4FA2-BE69-5109B340E3A8" sourceRef="sid-CB8D41DC-E2C6-4D60-A247-62630B0EF758" targetRef="sid-F533EC22-E107-49D2-ABDE-AE3BA402E8A4"/>
<endEvent id="sid-C23D6404-68B8-4C5C-8469-562C63E363AA"/>
<sequenceFlow id="sid-70DA56B6-5156-4CF1-8B36-DE0CB28096C5" sourceRef="sid-F533EC22-E107-49D2-ABDE-AE3BA402E8A4" targetRef="sid-C23D6404-68B8-4C5C-8469-562C63E363AA"/>
<userTask id="sid-CB8D41DC-E2C6-4D60-A247-62630B0EF758" name="Get User of this task" activiti:assignee="$INITIATOR">
<extensionElements>
<activiti:taskListener event="complete" class="org.activiti.engine.impl.bpmn.listener.ScriptTaskListener">
<activiti:field name="script">
<activiti:string><![CDATA[var dataValue = task.assignee;
execution.setVariable("TaskAssignee", dataValue);]]></activiti:string>
</activiti:field>
<activiti:field name="language">
<activiti:string><![CDATA[javascript]]></activiti:string>
</activiti:field>
</activiti:taskListener>
<modeler:allow-send-email>true</modeler:allow-send-email>
<modeler:initiator-can-complete>true</modeler:initiator-can-complete>
</extensionElements>
</userTask>
<sequenceFlow id="sid-9B8DB7EE-D9CD-4FA8-96C8-ED62ECED5404" sourceRef="startEvent1" targetRef="sid-CB8D41DC-E2C6-4D60-A247-62630B0EF758"/>
</process>
</code></pre>
<p>BTW i'm using activiti 5.19.</p>
| 3 | 1,410 |
Spring boot JPA Hibernate return nested Json Object : Reddit style comment system
|
<pre><code>@Entity
public class Comment {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
private Comment parentComment;
@OneToMany(mappedBy="parentComment", cascade = CascadeType.ALL)
private List<Comment> childrenComments = new ArrayList<>();
}
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
</code></pre>
<p>Here is how I am saving replies for a specific comment.</p>
<pre><code>Comment parent = new Comment();
parent.setContent(" 1 comment");
parent = commentRepository.save(parent);
Comment reply1 = new Comment();
reply1.setContent("reply 1 to comment 1");
reply1.setParentComment(parent);
Comment reply2 = new Comment();
reply1.setContent("reply 2 to comment 1");
reply1.setParentComment(parent);
parent = commentRepository.save(parent);
</code></pre>
<p>When I do commentrepository.findAll()</p>
<p>I would like to return the following json data. </p>
<pre><code>{
"id": 1,
"content": "1 comment",
"replies" :[
{
"id": 2,
"content": "reply 1 to comment 1"
},
{
"id": 3,
"content": "reply 2 to comment 1"
}
]
}
</code></pre>
<p>My goal is to build a reddit style comment system. Where each comment has an array of comments(replies). When I query for all comments, using spring data jpa, I only want the root comments and their nested replies.</p>
<p>In the above case, don't want something like this:</p>
<pre><code>{
{
"id": 1,
"content": "1 comment",
"replies" :[
{
"id": 2,
"content": "reply 1 to comment 1"
},
{
"id": 3,
"content": "reply 2 to comment 1"
}
]
}
{
"id": 2,
"content": "reply 1 to comment 1"
}
{
"id": 2,
"content": "reply 1 to comment 1"
}
}
</code></pre>
<p>I have spent several days on this without success. I have tried using @jsonIgnore and other jackson annotations without success. Any suggestions or recommendations?
Thank you in adavance. you are appreciated!</p>
| 3 | 1,149 |
Jquery Validate changing page before php script runs
|
<p>I am new to PHP MYSQL JQUERY and I have a Jquery Mobile Form that i want to submit the form data to mySql then change to #pageTwo of the mobile page. This seems like it should be easy to do but i cant seem to figure it out.</p>
<pre><code><body>
<div data-role="page" id="pageone">
<?php include 'connectDB.php' ?>
<div data-role="header">
<h1>Order Request Form</h1>
</div>
<div data-role="main" class="ui-content">
<div class="ui-field-contain">
<form method="post" id="ACform" name="ACform">
<div>
<label for="onSiteName" class="ui-hidden-accessible">On Site Contact:</label>
<input type="text" name="onSiteName" id="onSiteName" data-clear-btn="true" placeholder="On Site Contact name..." required>
</div>
<div>
<label for="onSiteNumber" class="ui-hidden-accessible">On Site Contact Number:</label>
<input type="tel" name="onSiteNumber" id="onSiteNumber" data-clear-btn="true" placeholder="On Site Contact number..." required>
</div>
<div>
<label for="adminContactName" class="ui-hidden-accessible">Administrator Contact:</label>
<select name="adminContactDropDown" id="adminContactDropDown" required>
<option value="">Admin Contact</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="Other">Other</option>
</select>
</div>
<div>
<input type="text" name="adminContactName" id="adminContactName" data-clear-btn="true" placeholder="Administrator Contact name..." required>
<label for="adminContactNumber" class="ui-hidden-accessible">Administrator Contact Number:</label>
<input type="tel" name="adminContactNumber" id="adminContactNumber" data-clear-btn="true" placeholder="Administrator Contact number..." required>
</div>
<script>
$('#ACform').validate({
messages: {
onSiteName: {required: "Please enter the on-site contact name"},
onSiteNumber: {required: "Please enter the on-site contacts number"},
adminContactDropDown: {required: "Please select an admin contact"},
adminContactName: {required: "Please enter an admin contact name"},
adminContactNumber: {required: "Please enter an admin contact number"},
},
errorPlacement: function (error, element) {
error.insertAfter($(element).parent());
},
submitHandler: function (form) {
form.submit();
':mobile-pagecontainer'.pagecontainer('change', '#pagetwo', {
reload: false
});
return false;
}
});
</script>
<?php include 'submit.php' ?>
<div>
<input type="reset" name="reset" value="Reset" id="clear">
<input type="submit" name="submit" value="Submit"><br/>
</div>
</form>
</div>
</div>
<div data-role="footer">
<h1><img src="logo.png" align="middle" width="160" height="26"/></h1>
</div>
</div>
<!--Page two-->
<div data-role="page" data-dialog="true" id="pagetwo">
<div data-role="header">
<h1>A/C Order Request Sent!</h1>
</div>
<div data-role="main" class="ui-content">
<?php echo $output; ?>
<p>Thank you for submitting your order request. Your request will be reviewed by one of our sales representatives and you will be contacted shortly.</p>
<div align="right"><a href="#pageone" class="ui-btn ui-btn-inline ui-shadow ui-corner-all ui-icon-arrow-r ui-btn-icon-right">Place another order</a></div>
</div>
<div data-role="footer">
<h1><img src="logo.png" align="middle" width="160" height="26"/></h1>
</div>
</div>
</body>
</html>
</code></pre>
<p>submit.php</p>
<pre><code> <?php $jobName = $delDate = $delTimeFrom = $useDate = $startTime = $puDate = $puTimeFrom = $address = $address2 = $zip = $city = $state = $delArea = $onSiteName = $onSiteNumber = $adminContactName = $adminContactNumber = $ACtotal = '';
if ($_POST) {
$onSiteName = test_input($_POST["onSiteName"]);
$onSiteNumber = test_input($_POST["onSiteNumber"]);
$adminContactName = test_input($_POST["adminContactName"]);
$adminContactNumber = test_input($_POST["adminContactNumber"]);
$sql = "INSERT INTO tbl_orders (onSiteName , onSiteNumber , adminContactName , adminContactNumber)
VALUES ('$onSiteName' , '$onSiteNumber' , '$adminContactName' , '$adminContactNumber')";}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
$output = '';
if ($conn->query($sql) === TRUE) {
$output .= "New record created successfully";
} else {
$output .= "Error: " . $sql . "<br>" . $conn->error;
}
?>
</code></pre>
<p>I have tried to remove the submitHandler, it submits the form properly but it doesnt change the page and disrupts all the other javascript on the page (not shown) when it reloads. But when i have the submitHandler in, the page changes but the form doesn't submit.</p>
<h1>edit</h1>
<p>Based on Michaels suggestion, i tried the below code which gave me an "error loading page" error:</p>
<pre><code>submitHandler: function (form) {
$(':mobile-pagecontainer').pagecontainer('change', '#pagetwo', {
reload: false
});
return false;
}
form.submit();
});
</code></pre>
<p>I also tried:</p>
<pre><code>submitHandler: function (form) {
$(':mobile-pagecontainer').pagecontainer('change', '#pagetwo', {
reload: false
});
return false;
form.submit();
}
});
</code></pre>
<p>which took me to pageTwo but did not submit the form</p>
| 3 | 2,504 |
Could not install erdpy - no module named 'ledgercomm'
|
<p>When I try to install <code>erdpy</code>, it fails with the following message:</p>
<blockquote>
<p>ModuleNotFoundError: No module named 'ledgercomm'<br />
CRITICAL:installer:Could not install erdpy.</p>
</blockquote>
<p>I follow the steps from <a href="https://docs.elrond.com/sdk-and-tools/erdpy/installing-erdpy/" rel="nofollow noreferrer">here</a>.</p>
<p>Running:</p>
<pre><code>$ wget -O erdpy-up.py https://raw.githubusercontent.com/ElrondNetwork/elrond-sdk-erdpy/master/erdpy-up.py
</code></pre>
<p>outputs:</p>
<pre><code>--2021-09-25 11:04:20-- https://raw.githubusercontent.com/ElrondNetwork/elrond-sdk-erdpy/master/erdpy-up.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.111.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8902 (8.7K) [text/plain]
Saving to: ‘erdpy-up.py’
erdpy-up.py 100%[=============================================================>] 8.69K --.-KB/s in 0.003s
2021-09-25 11:04:20 (2.82 MB/s) - ‘erdpy-up.py’ saved [8902/8902]
</code></pre>
<p>Then, running:</p>
<pre><code>$ python3 erdpy-up.py
</code></pre>
<p>outputs:</p>
<pre><code>INFO:installer:Checking user.
INFO:installer:Checking Python version.
INFO:installer:Python version: sys.version_info(major=3, minor=6, micro=9, releaselevel='final', serial=0)
INFO:installer:Checking operating system.
INFO:installer:Operating system: linux
INFO:installer:Removed previous installation (virtual environment).
INFO:installer:Packages found: <module 'ensurepip' from '/usr/lib/python3.6/ensurepip/__init__.py'>, <module 'venv' from '/usr/lib/python3.6/venv/__init__.py'>.
INFO:installer:Creating virtual environment in: /home/user/elrondsdk/erdpy-venv.
INFO:installer:Virtual environment has been created in: /home/user/elrondsdk/erdpy-venv.
INFO:installer:Installing erdpy in virtual environment...
Collecting pip
Using cached https://files.pythonhosted.org/packages/ca/31/b88ef447d595963c01060998cb329251648acf4a067721b0452c45527eb8/pip-21.2.4-py3-none-any.whl
Installing collected packages: pip
Found existing installation: pip 9.0.1
Uninstalling pip-9.0.1:
Successfully uninstalled pip-9.0.1
Successfully installed pip-21.2.4
Collecting erdpy
Downloading erdpy-1.0.17-py3-none-any.whl (142 kB)
|################################| 142 kB 1.6 MB/s
Downloading erdpy-1.0.16-py3-none-any.whl (142 kB)
|################################| 142 kB 5.1 MB/s
Collecting bottle
Downloading bottle-0.12.19-py3-none-any.whl (89 kB)
|################################| 89 kB 4.5 MB/s
Collecting pycryptodomex
Downloading pycryptodomex-3.10.4-cp35-abi3-manylinux2010_x86_64.whl (1.9 MB)
|################################| 1.9 MB 5.4 MB/s
Collecting pynacl
Downloading PyNaCl-1.4.0-cp35-abi3-manylinux1_x86_64.whl (961 kB)
|################################| 961 kB 4.7 MB/s
Collecting requests
Downloading requests-2.26.0-py2.py3-none-any.whl (62 kB)
|################################| 62 kB 6.8 MB/s
Collecting prettytable
Downloading prettytable-2.2.0-py3-none-any.whl (23 kB)
Collecting toml>=0.10.2
Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting cryptography>=3.2
Downloading cryptography-3.4.8-cp36-abi3-manylinux_2_24_x86_64.whl (3.0 MB)
|################################| 3.0 MB 5.5 MB/s
Collecting cffi>=1.12
Downloading cffi-1.14.6-cp36-cp36m-manylinux1_x86_64.whl (401 kB)
|################################| 401 kB 6.1 MB/s
Collecting pycparser
Downloading pycparser-2.20-py2.py3-none-any.whl (112 kB)
|################################| 112 kB 6.9 MB/s
Collecting importlib-metadata
Downloading importlib_metadata-4.8.1-py3-none-any.whl (17 kB)
Collecting wcwidth
Downloading wcwidth-0.2.5-py2.py3-none-any.whl (30 kB)
Collecting zipp>=0.5
Downloading zipp-3.5.0-py3-none-any.whl (5.7 kB)
Collecting typing-extensions>=3.6.4
Downloading typing_extensions-3.10.0.2-py3-none-any.whl (26 kB)
Collecting six
Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting idna<4,>=2.5
Downloading idna-3.2-py3-none-any.whl (59 kB)
|################################| 59 kB 8.6 MB/s
Collecting certifi>=2017.4.17
Downloading certifi-2021.5.30-py2.py3-none-any.whl (145 kB)
|################################| 145 kB 6.5 MB/s
Collecting charset-normalizer~=2.0.0
Downloading charset_normalizer-2.0.6-py3-none-any.whl (37 kB)
Collecting urllib3<1.27,>=1.21.1
Downloading urllib3-1.26.7-py2.py3-none-any.whl (138 kB)
|################################| 138 kB 5.6 MB/s
Installing collected packages: zipp, typing-extensions, pycparser, wcwidth, urllib3, six, importlib-metadata, idna, charset-normalizer, cffi, certifi, toml, requests, pynacl, pycryptodomex, prettytable, cryptography, bottle, erdpy
Successfully installed bottle-0.12.19 certifi-2021.5.30 cffi-1.14.6 charset-normalizer-2.0.6 cryptography-3.4.8 erdpy-1.0.16 idna-3.2 importlib-metadata-4.8.1 prettytable-2.2.0 pycparser-2.20 pycryptodomex-3.10.4 pynacl-1.4.0 requests-2.26.0 six-1.16.0 toml-0.10.2 typing-extensions-3.10.0.2 urllib3-1.26.7 wcwidth-0.2.5 zipp-3.5.0
Traceback (most recent call last):
File "/home/user/elrondsdk/erdpy-venv/bin/erdpy", line 5, in <module>
from erdpy.cli import main
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/cli.py", line 7, in <module>
import erdpy.cli_accounts
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/cli_accounts.py", line 4, in <module>
from erdpy import cli_shared, utils
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/cli_shared.py", line 8, in <module>
from erdpy import config, errors, scope, utils
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/scope.py", line 6, in <module>
from erdpy.testnet.config import TestnetConfiguration
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/testnet/__init__.py", line 2, in <module>
from erdpy.testnet.setup import clean, configure, install_dependencies
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/testnet/setup.py", line 8, in <module>
from erdpy.testnet import (genesis_json, genesis_smart_contracts_json,
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/testnet/genesis_json.py", line 6, in <module>
from erdpy.testnet.genesis import (get_delegation_address,
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/testnet/genesis.py", line 2, in <module>
from erdpy.contracts import SmartContract
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/contracts.py", line 10, in <module>
from erdpy.transactions import Transaction
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/transactions.py", line 11, in <module>
from erdpy.ledger.ledger_app_handler import SIGN_USING_HASH_VERSION
File "/home/user/elrondsdk/erdpy-venv/lib/python3.6/site-packages/erdpy/ledger/ledger_app_handler.py", line 1, in <module>
from ledgercomm import Transport
ModuleNotFoundError: No module named 'ledgercomm'
CRITICAL:installer:Could not install erdpy.
</code></pre>
<p><strong>Details:</strong></p>
<pre><code>$ python3 --version
Python 3.6.9
</code></pre>
<p>How can I fix this?</p>
| 3 | 3,209 |
Android app crashes on onClickListener
|
<p>I have this app which is a simple lottery system but whenever I try pressing one of the buttons the app freezes then crashes and I don't know why. The program doesn't give me errors so it's really confusing. I saw some things about it being a problem with the layout but I can't figure out what it is. I will answer the page Layout in a comment under the question. Thanks in advance.</p>
<p>Here's the page script:</p>
<pre><code>package com.example.myapplication;
import android.graphics.Color;
import android.icu.text.NumberFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.*;
import java.math.*;
import org.w3c.dom.Text;
import javax.xml.transform.Result;
public class Lottery extends AppCompatActivity {
Button Check, Random;
EditText User1;
TextView Balance2, ResultText;
int Balance1 = 500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lottery);
Check = (Button)findViewById(R.id.CheckNumbers);
Random = (Button)findViewById(R.id.RandomNumber);
User1 = findViewById(R.id.PickNumber);
Balance2 = (TextView)findViewById(R.id.Balance);
ResultText = (TextView)findViewById(R.id.Result);
ResultText.setVisibility(View.GONE);
Balance2.setText("Balance: $500");
Check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int User=Integer.parseInt(String.valueOf(User1));
if(User1.toString().trim().equals("")){
ResultText.setBackgroundColor(Color.RED);
ResultText.setText("Please Enter a Number");
ResultText.setVisibility(View.VISIBLE);
}
else if(User > 100 || User < 1){
ResultText.setBackgroundColor(Color.RED);
ResultText.setText("Please Enter a Number between 1 and 100");
ResultText.setVisibility(View.VISIBLE);
}
else {
int answer = (int)((Math.random()*100)+1);
int placeholder = answer % 10;
int AnswerTens = (answer - placeholder)/10;
int AnswerOnes = placeholder;
placeholder = User %10;
int UserTens = (User- placeholder)/10;
int UserOnes = placeholder;
if(User == answer){
ResultText.setBackgroundColor(Color.GREEN);
ResultText.setText("Correct!!! The Number was "+User+" $1000 has been added to your account");
ResultText.setVisibility(View.VISIBLE);
Balance1 += 1000;
Balance2.setText("Balance: $ "+ Balance1);
}
else if((UserTens == AnswerOnes)&&(UserOnes == AnswerTens)){
ResultText.setBackgroundColor(Color.GREEN);
ResultText.setText(" Somewhat Correct! The digit were correct but in the wrong order The answer was "+answer+" $500 has been added to your account");
ResultText.setVisibility(View.VISIBLE);
Balance1 += 500;
Balance2.setText("Balance: $ "+ Balance1);
}
else if((UserTens == AnswerTens)|| (UserTens == AnswerOnes)||(UserOnes == AnswerOnes)||(UserOnes==AnswerTens)){
ResultText.setBackgroundColor(Color.GREEN);
ResultText.setText("Kinda Correct! One digit was correct The answer was "+answer+" $100 has been added to your account");
ResultText.setVisibility(View.VISIBLE);
Balance1 += 100;
Balance2.setText("Balance: $ "+ Balance1);
}
else{
ResultText.setBackgroundColor(Color.RED);
ResultText.setText("Incorrect the Number was "+answer);
ResultText.setVisibility(View.VISIBLE);
}
}
}
});
Random.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int answer = (int)((Math.random()*100)+1);
User1.setText(answer);
}
});
}
}
</code></pre>
| 3 | 2,233 |
Associative Array where a class TypeInfo is key in D?
|
<p>I'd like to be able to create an multidim associative array where one dimension is a class. Like this:</p>
<pre><code>class Node{
Node[?classType?][string] inputs;
}
</code></pre>
<p>so that I later can do</p>
<pre><code>Node[] getInputsOfType(?? aClass){
if(aClass in this.inputs)
return this.inputs[aClass];
else
return null;
}
// meanwhile in another file...
Node[] effects = someAudioNode.getInputsOfType(AudioEffect);
</code></pre>
<p>I'm just lost. Any ideas?<br>
Regarding the last part: Can a class be used as a parameter all by itself like that? (<code>AudioEffect</code> in this example is a class.)</p>
<p>BR</p>
<p><strong>[update/resolution]</strong></p>
<p>Thanks for the answer(s)! </p>
<p>I thought it'd be nice to post the result. Ok, I looked up <code>.classinfo</code> in the source code and found that it returns an instance of TypeInfo_Class, and that there's a <code>.name</code>-property, a <code>string</code>. So this is what I came up with: </p>
<pre><code>#!/usr/bin/env dmd -run
import std.stdio;
class A{
int id;
static int newId;
A[string][string] list;
this(){ id = newId++; }
void add(A a, string name){
writefln("Adding: [%s][%s]", a.classinfo.name, name);
list[a.classinfo.name][name] = a;
}
T[string] getAllOf(T)(){
return cast(T[string]) list[T.classinfo.name];
}
}
class B : A{ }
void main(){
auto a = new A();
a.add(new A(), "test");
a.add(new B(), "bclass");
a.add(new B(), "bclass2");
auto myAList = a.getAllOf!(A);
foreach(key, item; myAList)
writefln("k: %s, i: %s id: %s",
key, item.toString(), item.id);
auto myBList = a.getAllOf!(B);
foreach(key, item; myBList)
writefln("k: %s, i: %s id: %s",
key, item.toString(), item.id);
}
</code></pre>
<p>It outputs:</p>
<pre><code>Adding: [classtype.A][test]
Adding: [classtype.B][bclass]
Adding: [classtype.B][bclass2]
Trying to get [classtype.A]
k: test, i: classtype.A id: 1
Trying to get [classtype.B]
k: bclass2, i: classtype.B id: 3
k: bclass, i: classtype.B id: 2
</code></pre>
<p>So yeah, I suppose it works. Yey! Anyone has ideas for improvement?</p>
<p>Are there any pitfalls here? </p>
<ul>
<li>Can <code>classinfo.name</code> suddenly behave unexpedictly?</li>
<li>Is there a »proper» way of getting the class name?</li>
</ul>
<p>Also, is this the fastest way of doing it? I mean, all class names seems to start with <code>classtype.</code>. Oh well, that's perhaps another SO-thread. Thanks again!</p>
<p>BR</p>
| 3 | 1,093 |
How to check who won in rock, paper, scissors- user vs computer- Python Tkinter
|
<p>I'm working on a rock, paper scissors game- user vs computer in Python tkinter. I'm struggling in the check function- the if statements in that function always evaluate to false for some reason (I checked by adding an else statement and printing something, and the program ended up going to the else statement every time). Can someone help me construct better if statements that check who won?
My code:</p>
<pre><code>from tkinter import *
from random import randint
from tkinter import messagebox
window = Tk()
window.title("Rock, Paper, Scissors")
window.geometry("800x600+220+10")
window.configure(bg="#fbfcbc")
title = Label(window, text="Rock Paper Scissors:\nUser vs. Computer", font=("Arial Rounded MT Bold", 30), fg="#f59c97",
bg="#fbfcbc")
title.place(x=200, y=10)
count = 0
computer_choice = None
chosen = []
images_list = [
PhotoImage(file="images/rock.png"),
PhotoImage(file="images/paper.png"),
PhotoImage(file="images/scissors.png")
]
def user_choice():
global count
user_choice_button.configure(text="", image=images_list[count])
user_choice_button.place(x=120, y=320)
count += 1
if count == 3:
count = 0
def start():
global computer_choice
try:
while chosen[-1] == computer_choice:
computer_choice = images_list[randint(0, 2)]
chosen.append(computer_choice)
except IndexError:
computer_choice = images_list[randint(0, 2)]
chosen.append(computer_choice)
computer_choice_label.configure(image=computer_choice, text="")
check()
def check():
if user_choice_button["image"] == images_list[0] and computer_choice_label["image"] == images_list[1]:
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == images_list[1] and computer_choice_label["image"] == images_list[0]:
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == images_list[0] and computer_choice_label["image"] == images_list[2]:
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == images_list[2] and computer_choice_label["image"] == images_list[0]:
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == images_list[1] and computer_choice_label["image"] == images_list[2]:
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == images_list[2] and computer_choice_label["image"] == images_list[1]:
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == computer_choice_label["image"]:
messagebox.showinfo("Rock, Paper, Scissors", "The game ended in a draw!")
def reset():
user_choice_button.configure(text="Click to\nchoose", font=("Arial Rounded MT Bold", 40))
user_choice_button.place(x=50, y=300)
computer_choice_label.configure(text="The computer's\nchoice will be\ndisplayed here",
font=("Arial Rounded MT Bold", 30))
computer_choice_label.place(x=450, y=310)
user_choice_button = Button(window, text="Click to\nchoose", font=("Arial Rounded MT Bold", 40), bg="#b6f5f8",
fg="#f59c97", command=user_choice)
user_choice_button.place(x=50, y=300)
computer_choice_label = Label(window, text="The computer's\nchoice will be\ndisplayed here",
font=("Arial Rounded MT Bold", 30), bg="#fbfcbc", fg="#f59c97")
computer_choice_label.place(x=450, y=310)
start_button = Button(window, text="START", font=("Arial Rounded MT Bold", 30), bg="lime", command=start)
start_button.place(x=300, y=200)
window.mainloop()
</code></pre>
<p>A big thanks to jasonharper for solving the problem! Updated code:</p>
<pre><code>from tkinter import *
from random import randint
from tkinter import messagebox
window = Tk()
window.title("Rock, Paper, Scissors")
window.geometry("800x600+220+10")
window.configure(bg="#fbfcbc")
title = Label(window, text="Rock Paper Scissors:\nUser vs. Computer", font=("Arial Rounded MT Bold", 30), fg="#f59c97",
bg="#fbfcbc")
title.place(x=200, y=10)
count = 0
computer_choice = None
chosen = []
images_list = [
PhotoImage(file="images/rock.png"),
PhotoImage(file="images/paper.png"),
PhotoImage(file="images/scissors.png")
]
def user_choice():
global count
user_choice_button.configure(text="", image=images_list[count])
user_choice_button.place(x=120, y=320)
count += 1
if count == 3:
count = 0
def start():
global computer_choice
try:
while chosen[-1] == computer_choice:
computer_choice = images_list[randint(0, 2)]
chosen.append(computer_choice)
except IndexError:
computer_choice = images_list[randint(0, 2)]
chosen.append(computer_choice)
computer_choice_label.configure(image=computer_choice, text="")
check()
def check():
if user_choice_button["image"] == str(images_list[0]) and computer_choice_label["image"] == str(images_list[1]):
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == str(images_list[1]) and computer_choice_label["image"] == str(images_list[0]):
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == str(images_list[0]) and computer_choice_label["image"] == str(images_list[2]):
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == str(images_list[2]) and computer_choice_label["image"] == str(images_list[0]):
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == str(images_list[1]) and computer_choice_label["image"] == str(images_list[2]):
messagebox.showinfo("Rock, Paper, Scissors", "The computer won!")
elif user_choice_button["image"] == str(images_list[2]) and computer_choice_label["image"] == str(images_list[1]):
messagebox.showinfo("Rock, Paper, Scissors", "You won!")
elif user_choice_button["image"] == computer_choice_label["image"]:
messagebox.showinfo("Rock, Paper, Scissors", "The game ended in a draw!")
def reset():
user_choice_button.configure(text="Click to\nchoose", font=("Arial Rounded MT Bold", 40))
user_choice_button.place(x=50, y=300)
computer_choice_label.configure(text="The computer's\nchoice will be\ndisplayed here",
font=("Arial Rounded MT Bold", 30))
computer_choice_label.place(x=450, y=310)
user_choice_button = Button(window, text="Click to\nchoose", font=("Arial Rounded MT Bold", 40), bg="#b6f5f8",
fg="#f59c97", command=user_choice)
user_choice_button.place(x=50, y=300)
computer_choice_label = Label(window, text="The computer's\nchoice will be\ndisplayed here",
font=("Arial Rounded MT Bold", 30), bg="#fbfcbc", fg="#f59c97")
computer_choice_label.place(x=450, y=310)
start_button = Button(window, text="START", font=("Arial Rounded MT Bold", 30), bg="lime", command=start)
start_button.place(x=300, y=200)
window.mainloop()
</code></pre>
| 3 | 3,644 |
Datatables Multi Filter Same Column
|
<p>I need to be able to apply multiple filters to a single column using datatables.</p>
<p>I've been looking at an example they have provided <a href="https://www.datatables.net/release-datatables/examples/api/multi_filter_select.html" rel="nofollow noreferrer">here</a> but my requirements are slightly different.</p>
<p>The first column in my table will contain location information, each cell will contain a <code>building name</code> and <code>floor</code>. I want to have two dropdowns that allow users to filter on both of these.</p>
<p>So e.g. '<em>Show me Building 1 and Second Floor</em>'. </p>
<p>I can get the first dropdown to filter on building, but the second doesn't filter on floor. My current code is below, here's a <a href="https://codepen.io/qubjohnny/pen/jOPrymJ?editors=1010" rel="nofollow noreferrer">codepen</a>.</p>
<p>Note I have simplified this table and limited it to 6 records, my live table will contain hundreds of records.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
var table = $("#example").DataTable();
$("#dropdown1").on("change", function() {
table
.columns(0)
.search(this.value)
.draw();
});
$("#dropdown2").on("change", function() {
table
.columns(0)
.search(this.value)
.draw();
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet"/>
<select id="dropdown1">
<option value="">Building</option>
<option value="Building 1">Building 1</option>
<option value="Building 2">Building 2</option>
</select>
<select id="dropdown2">
<option value="">Floor</option>
<option value="First Floor">First Floor</option>
<option value="Second Floor">Second Floor</option>
<option value="Third Floor">Third Floor</option>
</select>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Building 1<br><span class="floor">First Floor</span></td>
<td>Available</td>
</tr>
<tr>
<td>Building 1<br><span class="floor">Second Floor</span></td>
<td>Available</td>
</tr>
<tr>
<td>Building 1<br><span class="floor">Third Floor</span></td>
<td>Available</td>
</tr>
<tr>
<td>Building 2<br><span class="floor">First Floor</span></td>
<td>Unavailable</td>
</tr>
<tr>
<td>Building 2<br><span class="floor">Second Floor</span></td>
<td>Available</td>
</tr>
<tr>
<td>Building 2<br><span class="floor">Third Floor</span></td>
<td>Unavailable</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
| 3 | 1,617 |
jQuery - Show entered text from input field as heading for Dynamically added block
|
<p>jQuery with Bootstrap Modal...</p>
<p>I am creating info boxes dynamically and allowing users to type box heading through input textbox and clearing the input after adding it...</p>
<p>First time, it is working as expected.. where as If I try to create one more box, previously created boxes headers also changing... :(</p>
<p>How can I create a box with unique textfield every time?</p>
<blockquote>
<p><strong><a href="https://jsfiddle.net/ReddyPrasad/3yz9te79/" rel="nofollow">Online Demo</a></strong></p>
</blockquote>
<p><strong>HTML</strong></p>
<pre><code><div class="container wrapper">
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal">
<i class="glyphicon glyphicon-plus"></i> Add More
</button>
<div class="box-holder clearfix">
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title">
</div>
<div class="form-group">
<label for="options">Options:</label>
<select id="mySelectOptions">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="addBox" data-dismiss="modal">Add Box</button>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(document).ready(function () {
$('#addBox').click(function () {
$( ".wrapper .box-holder" ).append( '<div class="new-box"><div><label class="box-title">Title: <span></span></label></div><div><label class="box-values">Values: <span></span></label></div></div>' );
var newTitle = $(".modal-body .form-group #title").val();
$(".new-box .box-title span").text(newTitle);
$(".modal-body .form-group #title").val('');
});
});
</code></pre>
| 3 | 1,338 |
How to improve peformance of extracting data code in Python and numpy
|
<p>I'm trying to implement missing point in DIC (Digital Image Correlation) results, which are missing due to destruction of material (photo). </p>
<p><img src="https://i.stack.imgur.com/IcSBe.png" alt="enter image description here"></p>
<p>I would like to put points (without values) for this area where it is missing. (native points from source data)</p>
<p><img src="https://i.stack.imgur.com/sJWv2.png" alt="enter image description here"></p>
<p>This code is part of my thesis and I would like to find those points which are missing due to destruction of material during tensile test. Data comming from DIC (Digital image correlation) method which measure strain on surface of specimen. When specimen suffer local failure DIC software cannot find pixel cluster and finaly missing points in this region. I have over 30 specimens, each 50 frames. Total computation time for this data is about week. Code shown bellow in version 1 - nothing to change on my computer is runing something about 4 minutes. Code in version 2 is shorten that: statement MARK1 from begin to end is commented, and Version 2 comment lines are uncommented, but still takes 3 minutes 45 seconds.</p>
<p>Input data:
<a href="https://github.com/MarekSawicki/data/blob/master/022_0_29-03-2018_e11_45.csv" rel="nofollow noreferrer">https://github.com/MarekSawicki/data/blob/master/022_0_29-03-2018_e11_45.csv</a></p>
<pre><code>import numpy as np
import os
# changing of folder
os.chdir("D:/Marek/doktorat/Badania_obrobione/test")
# load data from file
data = np.genfromtxt('022_0_29-03-2018_e11_45.csv', delimiter=',',dtype='float64')
# separation of coordintates (points) and values (both floats64)
# data in format: list of points (X,Y) and list of values
points = data[1:,1:3]
values = data[1:,4]
#shifting coordinates to zero (points coordinates might be negative or offset from 0) (-x0)
points[:,0] -= min(points[:,0])
points[:,1] -= min(points[:,1])
#scale factor K_scale
k_scale=2
points[:,0:2] *= k_scale
# vector reshape
values= np.reshape(values, [len(data)-1,1])
# sort the points to keep order in X direction
# points X are assumed as points[:,0]
# points Y are assumed as points[:,1]
array1 = np.ascontiguousarray(points)
a_view = array1.view(dtype=[('', array1.dtype)]*array1.shape[-1])
a_view.sort(axis=0)
points_sorted = array1
# Start of processing points
# a and b are respectively X and Y limits
a = np.int32(np.ceil(np.max(points[:,0])))+1
b = np.int32(np.ceil(np.max(points[:,1])))+1
# length 1 unit array cluster
array2=np.empty((0,2))
for m in range(0,3):
for n in range(0,3):
array2=np.append(array2,[[m*.5,n*.5]],axis=0)
# initialization of variables
k=0 # searching limits
bool_array_del=np.zeros((9,1), dtype=bool) # determine which line should be deleted - bool type
# array4 is a container of values which meets criteria
array4=np.empty((0,2))
# array7 is output container
array7=np.empty((0,2))
# main loop of concerned code:
for i in range(0,a): # X wise loop, a is a X limit
for i2 in range(0,b): # Y wise loop, a is a Y limit
array3 = np.copy(array2) # creating a cluster in range (i:i+1,i2:i2+1, step=0.5)
array3[:,0]+=i
array3[:,1]+=i2
# value container (each loop it should be cleaned)
array4=np.empty((0,2))
# container which determine data to delete (each loop it should be cleaned)
bool_array_del = np.empty((0,1),dtype=bool)
k=0 # set zero searching limits
# loop for searching points which meet conditions.
# I think it is the biggest time waster
#To make it shorter I deal with sorted points which allows me
#to browse part of array insted of whole array
#(that is why I used k parameter and if-break condition )
for i3 in range(k,points_sorted.shape[0]):
valx = points_sorted[i3,0]
valy = points_sorted[i3,1]
if valx>i-1:
k=i3
if valx>i+1.5:
break
#this condition check does considered point has X and coordinates is range : i-0.5:i+1.5
# If yes then append this coordinate to empty container (array4)
if np.abs(valx-(i+.5))<=1:
if np.abs(valy-(i2+.5))<=1:
array4=np.append(array4,[[valx,valy]],axis=0)
# (version 2) break
# Then postprocessing of selected points container - array4. To determine - do all point out of array4 should are close enough to be deleted?
if array4.shape[0]!=0:
# (version 2) pass
# begin(MARK1)
# round the values from array4 to neares .5 value
array5 = np.round(array4*2)/2
# if value from array5 are out of bound for proper cluster values then shift it to the closest correct value
for i4 in range(0,array5.shape[0]):
if array5[i4,0]>i+1:
array5[i4,0]= i+1
elif array5[i4,0]<i:
array5[i4,0]=i
if array5[i4,1]>i2+1:
array5[i4,1]=i2+1
elif array5[i4,1]<i2:
array5[i4,1]=i2
# substract i,i2 vector and double from value of array5 to get indices which should be deleted
array5[:,0]-=i
array5[:,1]-=i2
array5*=2
# create empty container with bool values - True - delete this value, False - keep
array_bool1=np.zeros((3,3), dtype=bool)
for i5 in range(0,array5.shape[0]):
# below condition doesn't work - it is too rough
#array_bool1[int(array5[i5,0]),int(array5[i5,1])]=True
# this approach works with correct results but I guess it is second the biggest time waster.
try:
array_bool1[int(array5[i5,0]),int(array5[i5,1])]=True
array_bool1[int(array5[i5,0]+1),int(array5[i5,1]-1)]=True
array_bool1[int(array5[i5,0]+1),int(array5[i5,1])+1]=True
array_bool1[int(array5[i5,0]+1),int(array5[i5,1])]=True
array_bool1[int(array5[i5,0]-1),int(array5[i5,1]+1)]=True
array_bool1[int(array5[i5,0]-1),int(array5[i5,1]-1)]=True
array_bool1[int(array5[i5,0]-1),int(array5[i5,1])]=True
array_bool1[int(array5[i5,0]),int(array5[i5,1]+1)]=True
array_bool1[int(array5[i5,0]),int(array5[i5,1]-1)]=True
except:
pass
# convert bool array to list
for i6 in range(0,array_bool1.shape[0]):
for i7 in range(0,array_bool1.shape[1]):
bool_array_del=np.append(bool_array_del, [[array_bool1[i6,i7]]],axis=0)
# get indices where bool list (unfotunatelly called bool_array_del) is true
result= np.argwhere(bool_array_del)
array6=np.delete(array3,result[:,0],axis=0)
# append it to output container
array7=np.append(array7,array6,axis=0)
# if nothing is found in loop for searching points which meet conditions append full cluster to output array
# end(MARK1)
else:
array7=np.append(array7,array3,axis=0)
</code></pre>
<p>This code gives me satisfactionary results for version 1 (Fig 3) and acceptable results for version 2.(Fig 4)</p>
<p><a href="https://i.stack.imgur.com/O3fjS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O3fjS.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/HxzjQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HxzjQ.png" alt="enter image description here"></a></p>
<p>I am new in python and numpy. Could you tell me what I can do better to speed up my code? I thought about switch to panda</p>
| 3 | 3,187 |
How do I keep the string value the same when the indicator buffer no longer gives a value?
|
<p>I've coded a basic Expert Advisor to trigger a trade when the parameters are true. However, in this case the code will never meet all the requirements because the string value gives no value when the indicator buffer doesn't give a value.</p>
<p>What I need help with is to make the string value for <code>saisignal</code> stay the same when triggered by the indicator buffer, after the bar has passed the arrow indicator, so that when the other signals are eventually indicating a trade, it can trigger a trade.</p>
<pre><code>double closeAllTradesThisPair()
{
for (int i=OrdersTotal();i>=0;i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
if(OrderSymbol()==Symbol())
{
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,clrNONE);
}
}
}
void OnTick()
{
double saiup = iCustom( Symbol(), PERIOD_H1, "super-arrow-indicator", 0, 0 );
double saidn = iCustom( Symbol(), PERIOD_H1, "super-arrow-indicator", 1, 0 );
double osma1 = iOsMA( Symbol(), PERIOD_H1, 12, 26, 9, PRICE_OPEN, 1 );
double osma0 = iOsMA( Symbol(), PERIOD_H1, 12, 26, 9, PRICE_OPEN, 0 );
double stup = iCustom( Symbol(), PERIOD_H1, "super-trend", 0, 0 );
double stdn = iCustom( Symbol(), PERIOD_H1, "super-trend", 1, 0 );
double sar = iSAR( Symbol(), PERIOD_H1, 0.02, 0.2, 0 );
double ma = iMA( Symbol(), PERIOD_H1, 20, 0, MODE_SMA, PRICE_CLOSE, 0 );
string saisignal = "";
string osmasignal = "";
string stsignal = "";
string sarsignal = "";
string masignal = "";
if(saiup < 1000)
{
saisignal = "123";
}
if(saidn < 1000)
{
saisignal = "321";
}
if(osma1 < osma0)
{
osmasignal = "123";
}
if(osma1 > osma0)
{
osmasignal = "321";
}
if(stup < 1000)
{
stsignal = "123";
}
if(stdn < 1000)
{
stsignal = "321";
}
if(sar < Bid)
{
sarsignal = "123";
}
if(sar > Bid)
{
sarsignal = "321";
}
if(ma < Bid)
{
masignal = "123";
}
if(ma > Bid)
{
masignal = "321";
}
for(int b=OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
{
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY)
{
if(OrderStopLoss() < Ask - (150*_Point))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask-(150*_Point),OrderTakeProfit(),0,CLR_NONE);
}
}
if(OrderType()==OP_SELL)
{
if(OrderStopLoss() > Bid + (150*_Point))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid+(150*_Point),OrderTakeProfit(),0,CLR_NONE);
}
}
}
}
}
if(saisignal == "123")
{
if(osmasignal == "123")
{
if(stsignal == "123")
{
if(sarsignal == "123")
{
if(masignal == "123")
{
double buyticket = OrderSend(Symbol(),OP_BUY,0.01,Ask,3,Ask-150*_Point,0,NULL,0,0,CLR_NONE);
}
}
}
}
}
if(saisignal == "321")
{
if(osmasignal == "321")
{
if(stsignal == "321")
{
if(sarsignal == "321")
{
if(masignal == "321")
{
double sellticket = OrderSend(Symbol(),OP_SELL,0.01,Ask,3,Bid+150*_Point,0,NULL,0,0,CLR_NONE);
}
}
}
}
}
Comment(" sai: ",saisignal," osma: ",osmasignal," st: ",stsignal," sar: ",sarsignal," ma: ",masignal);
}
</code></pre>
| 3 | 2,168 |
Uncaught ReferenceError: AI is not defined at Object.play.AIPlay
|
<p>I have developed an AI HTML5 game.
It could run well locally.
But after deployed to github page, some js problems occurs.</p>
<p>AI.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var AI = AI||{};
AI.historyTable = {}; //��ʷ��
//�˹����ܳ�ʼ��
AI.init = function(pace){
var bill = AI.historyBill || com.gambit; //���ֿ�
if (bill.length){
var len=pace.length;
var arr=[];
//����������
for (var i=0;i< bill.length;i++){
if (bill[i].slice(0,len)==pace) {
arr.push(bill[i]);
}
}
if (arr.length){
var inx=Math.floor( Math.random() * arr.length );
AI.historyBill = arr ;
return arr[inx].slice(len,len+4).split("");
}else{
AI.historyBill = [] ;
}
}
//�����������û�У��˹����ܿ�ʼ����
var initTime = new Date().getTime();
AI.treeDepth=play.depth;
//AI.treeDepth=4;
AI.number=0;
AI.setHistoryTable.lenght = 0
var val=AI.getAlphaBeta(-99999 ,99999, AI.treeDepth, com.arr2Clone(play.map),play.my);
//var val = AI.iterativeSearch(com.arr2Clone(play.map),play.my)
if (!val||val.value==-8888) {
AI.treeDepth=2;
val=AI.getAlphaBeta(-99999 ,99999, AI.treeDepth, com.arr2Clone(play.map),play.my);
}
//var val = AI.iterativeSearch(com.arr2Clone(play.map),play.my);
if (val&&val.value!=-8888) {
var man = play.mans[val.key];
var nowTime= new Date().getTime();
com.get("moveInfo").innerHTML='<h3>AI���������</h3>����ŷ���'+
com.createMove(com.arr2Clone(play.map),man.x,man.y,val.x,val.y)+
'<br />������ȣ�'+AI.treeDepth+'<br />������֧��'+
AI.number+'�� <br />����ŷ�������'+
val.value+'��'+
' <br />������ʱ��'+
(nowTime-initTime)+'����'
return [man.x,man.y,val.x,val.y]
}else {
return false;
}
}
//�������������ŷ�
AI.iterativeSearch = function (map, my){
var timeOut=100;
var initDepth = 1;
var maxDepth = 8;
AI.treeDepth=0;
var initTime = new Date().getTime();
var val = {};
for (var i=initDepth; i<=maxDepth; i++){
var nowTime= new Date().getTime();
AI.treeDepth=i;
AI.aotuDepth=i;
var val = AI.getAlphaBeta(-99999, 99999, AI.treeDepth , map ,my)
if (nowTime-initTime > timeOut){
return val;
}
}
return false;
}
//ȡ����������������
AI.getMapAllMan = function (map, my){
var mans=[];
for (var i=0; i<map.length; i++){
for (var n=0; n<map[i].length; n++){
var key = map[i][n];
if (key && play.mans[key].my == my){
play.mans[key].x = n;
play.mans[key].y = i;
mans.push(play.mans[key])
}
}
}
return mans;
}
/*
//ȡ���������м������ӵ��ŷ�
AI.getMoves = function (map, my, txtMap){
var highMores = []; //���ȼ��ߵ��ŷ�
var manArr = AI.getMapAllMan (map, my);
var moves = [];
var history=AI.historyTable[txtMap];
for (var i=0; i<manArr.length; i++){
var man = manArr[i];
var val=man.bl(map);
for (var n=0; n<val.length; n++){
if (history){
highMores.push([man.x,man.y,val[n][0],val[n][1],man.key])
}else{
moves.push([man.x,man.y,val[n][0],val[n][1],man.key])
}
}
}
return highMores.concat(moves);
}
*/
//ȡ���������м������ӵ��ŷ�
AI.getMoves = function (map, my){
var manArr = AI.getMapAllMan (map, my);
var moves = [];
var foul=play.isFoul;
for (var i=0; i<manArr.length; i++){
var man = manArr[i];
var val=man.bl(map);
for (var n=0; n<val.length; n++){
var x=man.x;
var y=man.y;
var newX=val[n][0];
var newY=val[n][1];
//������dz����ŷ�
if (foul[0]!=x || foul[1]!=y || foul[2]!=newX || foul[3]!=newY ){
moves.push([x,y,newX,newY,man.key])
}
}
}
return moves;
}
//A:��ǰ����value/B:����value/depth���㼶
AI.getAlphaBeta = function (A, B, depth, map ,my) {
//var txtMap= map.join();
//var history=AI.historyTable[txtMap];
// if (history && history.depth >= AI.treeDepth-depth+1){
// return history.value*my;
//}
if (depth == 0) {
return {"value":AI.evaluate(map , my)}; //�������ۺ���;
�� }
�� var moves = AI.getMoves(map , my ); //����ȫ���߷�;
�� //���������Ժ������Ч��
for (var i=0; i < moves.length; i++) {
���� //������߷�;
var move= moves[i];
var key = move[4];
var oldX= move[0];
var oldY= move[1];
var newX= move[2];
var newY= move[3];
var clearKey = map[ newY ][ newX ]||"";
map[ newY ][ newX ] = key;
delete map[ oldY ][ oldX ];
play.mans[key].x = newX;
play.mans[key].y = newY;
����if (clearKey=="j0"||clearKey=="J0") {//�����Ͻ�,��������߷�;
play.mans[key] .x = oldX;
play.mans[key] .y = oldY;
map[ oldY ][ oldX ] = key;
delete map[ newY ][ newX ];
if (clearKey){
map[ newY ][ newX ] = clearKey;
// play.mans[ clearKey ].isShow = false;
}
return {"key":key,"x":newX,"y":newY,"value":8888};
//return rootKey;
����}else {
���� var val = -AI.getAlphaBeta(-B, -A, depth - 1, map , -my).value;
//val = val || val.value;
���� //��������߷�;��
play.mans[key] .x = oldX;
play.mans[key] .y = oldY;
map[ oldY ][ oldX ] = key;
delete map[ newY ][ newX ];
if (clearKey){
map[ newY ][ newX ] = clearKey;
//play.mans[ clearKey ].isShow = true;
}
���� if (val >= B) {
//������߷���¼����ʷ����;
//AI.setHistoryTable(txtMap,AI.treeDepth-depth+1,B,my);
return {"key":key,"x":newX,"y":newY,"value":B};
}
if (val > A) {
�������� A = val; //��������߷�;
if (AI.treeDepth == depth) var rootKey={"key":key,"x":newX,"y":newY,"value":A};
}
}
�� }
//������߷���¼����ʷ����;
//AI.setHistoryTable(txtMap,AI.treeDepth-depth+1,A,my);
if (AI.treeDepth == depth) {//�Ѿ��ݹ�ظ���
if (!rootKey){
//AIû������߷���˵��AI�������ˣ�����false
return false;
}else{
//�����������߷�;
return rootKey;
}
}
��return {"key":key,"x":newX,"y":newY,"value":A};
}
//���ŷ���¼����ʷ��
AI.setHistoryTable = function (txtMap,depth,value,my){
AI.setHistoryTable.lenght ++;
AI.historyTable[txtMap] = {depth:depth,value:value}
}
//������� ȡ������˫�����Ӽ�ֵ��
AI.evaluate = function (map,my){
var val=0;
for (var i=0; i<map.length; i++){
for (var n=0; n<map[i].length; n++){
var key = map[i][n];
if (key){
val += play.mans[key].value[i][n] * play.mans[key].my;
}
}
}
//val+=Math.floor( Math.random() * 10); //��AI�����������Ԫ��
//com.show()
//z(val*my)
AI.number++;
return val*my;
}
//������� ȡ������˫�����Ӽ�ֵ��
AI.evaluate1 = function (map,my){
var val=0;
for (var i in play.mans){
var man=play.mans[i];
if (man.isShow){
val += man.value[man.y][man.x] * man.my;
}
}
//val+=Math.floor( Math.random() * 10); //��AI�����������Ԫ��
//com.show()
//z(val*my)
AI.number++;
return val*my;
}</code></pre>
</div>
</div>
</p>
<p>HTML:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>AI Chinese Chess Game</title>
<link href="css/zzsc.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="box" id="box">
<H4>AI Chinese chess game. Please use Chrome, Firefox, Safari or Opera browser.</H4>
<embed src="/Greensleeves.mp3" loop="true" autostart="true" width="2" height="0">
<div class="chess_left">
<canvas id="chess">Sorry, please change to Chrome Browser!</canvas>
<audio src="audio/click.wav" id="clickAudio" preload="auto"></audio>
<!--<audio src="audio/check.wav" id="checkAudio" preload="auto"></audio>-->
<audio src="audio/select.wav" id="selectAudio" preload="auto"></audio>
<div>
<div class="bn_box" id="bnBox">
<input type="button" style="background:green; cursor:pointer" name="offensivePlay" id="tyroPlay" value="Beginner Level" />
<input type="button" style="background:red; cursor:pointer" name="offensivePlay" id="superPlay" value="Advanced Level" />
<!--input type="button" name="button" id="" value="大师水平" disabled /-->
<!--
<input type="button" name="offensivePlay" id="offensivePlay" value="先手开始" />
<input type="button" name="defensivePlay" id="defensivePlay" value="后手开始" />
-->
<input type="button" style="background:yellow; cursor:pointer" name="regret" id="regretBn" value="Restart" />
<input type="button" name="billBn" id="billBn" value="map" class="bn_box" />
<!--input type="button" name="stypeBn" id="stypeBn" value="Change Background" /-->
</div>
</div>
</div>
<div class="chess_right" id="chessRight">
<select name="billList" id="billList">
</select>
<ol id="billBox" class="bill_box">
</ol>
</div>
<div id="moveInfo" class="move_info"> </div>
</div>
<script src="js/common.js"></script>
<script src="js/play.js"></script>
<script src="js/AI.js"></script>
<script src="js/bill.js"></script>
<script src="js/gambit.js"></script>
<div style="text-align:center;clear:both">
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>play.js:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var play = play||{};
play.init = function (){
play.my = 1; //玩家方
play.map = com.arr2Clone (com.initMap); //初始化棋盘
play.nowManKey = false; //现在要操作的棋子
play.pace = []; //记录每一步
play.isPlay = true ; //是否能走棋
play.mans = com.mans;
play.bylaw = com.bylaw;
play.show = com.show;
play.showPane = com.showPane;
play.isOffensive = true; //是否先手
play.depth = play.depth || 3; //搜索深度
play.isFoul = false; //是否犯规长将
com.pane.isShow = false; //隐藏方块
//初始化棋子
for (var i=0; i<play.map.length; i++){
for (var n=0; n<play.map[i].length; n++){
var key = play.map[i][n];
if (key){
com.mans[key].x=n;
com.mans[key].y=i;
com.mans[key].isShow = true;
}
}
}
play.show();
//绑定点击事件
com.canvas.addEventListener("click",play.clickCanvas)
//clearInterval(play.timer);
//com.get("autoPlay").addEventListener("click", function(e) {
//clearInterval(play.timer);
//play.timer = setInterval("play.AIPlay()",1000);
// play.AIPlay()
//})
/*
com.get("offensivePlay").addEventListener("click", function(e) {
play.isOffensive=true;
play.isPlay=true ;
com.get("chessRight").style.display = "none";
play.init();
})
com.get("defensivePlay").addEventListener("click", function(e) {
play.isOffensive=false;
play.isPlay=true ;
com.get("chessRight").style.display = "none";
play.init();
})
*/
com.get("regretBn").addEventListener("click", function(e) {
play.regret();
})
/*
var initTime = new Date().getTime();
for (var i=0; i<=100000; i++){
var h=""
var h=play.map.join();
//for (var n in play.mans){
// if (play.mans[n].show) h+=play.mans[n].key+play.mans[n].x+play.mans[n].y
//}
}
var nowTime= new Date().getTime();
z([h,nowTime-initTime])
*/
}
//悔棋
play.regret = function (){
var map = com.arr2Clone(com.initMap);
//初始化所有棋子
for (var i=0; i<map.length; i++){
for (var n=0; n<map[i].length; n++){
var key = map[i][n];
if (key){
com.mans[key].x=n;
com.mans[key].y=i;
com.mans[key].isShow = true;
}
}
}
var pace= play.pace;
pace.pop();
pace.pop();
for (var i=0; i<pace.length; i++){
var p= pace[i].split("")
var x = parseInt(p[0], 10);
var y = parseInt(p[1], 10);
var newX = parseInt(p[2], 10);
var newY = parseInt(p[3], 10);
var key=map[y][x];
//try{
var cMan=map[newY][newX];
if (cMan) com.mans[map[newY][newX]].isShow = false;
com.mans[key].x = newX;
com.mans[key].y = newY;
map[newY][newX] = key;
delete map[y][x];
if (i==pace.length-1){
com.showPane(newX ,newY,x,y)
}
//} catch (e){
// com.show()
// z([key,p,pace,map])
// }
}
play.map = map;
play.my=1;
play.isPlay=true;
com.show();
}
//点击棋盘事件
play.clickCanvas = function (e){
if (!play.isPlay) return false;
var key = play.getClickMan(e);
var point = play.getClickPoint(e);
var x = point.x;
var y = point.y;
if (key){
play.clickMan(key,x,y);
}else {
play.clickPoint(x,y);
}
play.isFoul = play.checkFoul();//检测是不是长将
}
//点击棋子,两种情况,选中或者吃子
play.clickMan = function (key,x,y){
var man = com.mans[key];
//吃子
if (play.nowManKey&&play.nowManKey != key && man.my != com.mans[play.nowManKey ].my){
//man为被吃掉的棋子
if (play.indexOfPs(com.mans[play.nowManKey].ps,[x,y])){
man.isShow = false;
var pace=com.mans[play.nowManKey].x+""+com.mans[play.nowManKey].y
//z(bill.createMove(play.map,man.x,man.y,x,y))
delete play.map[com.mans[play.nowManKey].y][com.mans[play.nowManKey].x];
play.map[y][x] = play.nowManKey;
com.showPane(com.mans[play.nowManKey].x ,com.mans[play.nowManKey].y,x,y)
com.mans[play.nowManKey].x = x;
com.mans[play.nowManKey].y = y;
com.mans[play.nowManKey].alpha = 1
play.pace.push(pace+x+y);
play.nowManKey = false;
com.pane.isShow = false;
com.dot.dots = [];
com.show()
com.get("clickAudio").play();
setTimeout("play.AIPlay()",500);
if (key == "j0") play.showWin (-1);
if (key == "J0") play.showWin (1);
}
// 选中棋子
}else{
if (man.my===1){
if (com.mans[play.nowManKey]) com.mans[play.nowManKey].alpha = 1 ;
man.alpha = 0.6;
com.pane.isShow = false;
play.nowManKey = key;
com.mans[key].ps = com.mans[key].bl(); //获得所有能着点
com.dot.dots = com.mans[key].ps
com.show();
//com.get("selectAudio").start(0);
com.get("selectAudio").play();
}
}
}
//点击着点
play.clickPoint = function (x,y){
var key=play.nowManKey;
var man=com.mans[key];
if (play.nowManKey){
if (play.indexOfPs(com.mans[key].ps,[x,y])){
var pace=man.x+""+man.y
//z(bill.createMove(play.map,man.x,man.y,x,y))
delete play.map[man.y][man.x];
play.map[y][x] = key;
com.showPane(man.x ,man.y,x,y)
man.x = x;
man.y = y;
man.alpha = 1;
play.pace.push(pace+x+y);
play.nowManKey = false;
com.dot.dots = [];
com.show();
com.get("clickAudio").play();
setTimeout("play.AIPlay()",500);
}else{
//alert("不能这么走哦!")
}
}
}
//Ai自动走棋
play.AIPlay = function (){
//return
play.my = -1 ;
var pace=AI.init(play.pace.join(""))
if (!pace) {
play.showWin (1);
return ;
}
play.pace.push(pace.join(""));
var key=play.map[pace[1]][pace[0]]
play.nowManKey = key;
var key=play.map[pace[3]][pace[2]];
if (key){
play.AIclickMan(key,pace[2],pace[3]);
}else {
play.AIclickPoint(pace[2],pace[3]);
}
com.get("clickAudio").play();
}
//检查是否长将
play.checkFoul = function(){
var p=play.pace;
var len=parseInt(p.length,10);
if (len>11&&p[len-1] == p[len-5] &&p[len-5] == p[len-9]){
return p[len-4].split("");
}
return false;
}
play.AIclickMan = function (key,x,y){
var man = com.mans[key];
//吃子
man.isShow = false;
delete play.map[com.mans[play.nowManKey].y][com.mans[play.nowManKey].x];
play.map[y][x] = play.nowManKey;
play.showPane(com.mans[play.nowManKey].x ,com.mans[play.nowManKey].y,x,y)
com.mans[play.nowManKey].x = x;
com.mans[play.nowManKey].y = y;
play.nowManKey = false;
com.show()
if (key == "j0") play.showWin (-1);
if (key == "J0") play.showWin (1);
}
play.AIclickPoint = function (x,y){
var key=play.nowManKey;
var man=com.mans[key];
if (play.nowManKey){
delete play.map[com.mans[play.nowManKey].y][com.mans[play.nowManKey].x];
play.map[y][x] = key;
com.showPane(man.x,man.y,x,y)
man.x = x;
man.y = y;
play.nowManKey = false;
}
com.show();
}
play.indexOfPs = function (ps,xy){
for (var i=0; i<ps.length; i++){
if (ps[i][0]==xy[0]&&ps[i][1]==xy[1]) return true;
}
return false;
}
//获得点击的着点
play.getClickPoint = function (e){
var domXY = com.getDomXY(com.canvas);
var x=Math.round((e.pageX-domXY.x-com.pointStartX-20)/com.spaceX)
var y=Math.round((e.pageY-domXY.y-com.pointStartY-20)/com.spaceY)
return {"x":x,"y":y}
}
//获得棋子
play.getClickMan = function (e){
var clickXY=play.getClickPoint(e);
var x=clickXY.x;
var y=clickXY.y;
if (x < 0 || x>8 || y < 0 || y > 9) return false;
return (play.map[y][x] && play.map[y][x]!="0") ? play.map[y][x] : false;
}
play.showWin = function (my){
play.isPlay = false;
if (my===1){
alert("Congratulations, You win me!");
}else{
alert("Haha you are beaten up by AI, please try again later^^.");
}
}</code></pre>
</div>
</div>
</p>
<p>error occurs at this line: <code>var pace=AI.init(play.pace.join(""))</code></p>
<p>error details:</p>
<pre><code> Uncaught ReferenceError: AI is not defined
at Object.play.AIPlay
</code></pre>
<p>when I run it in my local computer, it could run well. But after deployed to github page, it could not run the js script well. Why get this not defined error after deployment?</p>
| 3 | 11,261 |
Error reading a Trajectory File using Chemfiles library
|
<p>I need to write a piece of cpp code that will read a trajectory file (.pdb or .dcd files). I have followed the steps on the homepage of <a href="http://chemfiles.org/chemfiles/0.6.0/example.html" rel="nofollow noreferrer">chemfiles</a> library to read in the file. I am getting an error about undefined symbols for architecture x86_64 (please see a piece of the error log below).</p>
<p>What I want: Able to read the .dcd/.pdb file using the chemfiles library (or any other suitable library to do so) - I need to access the coordinates of the atoms listed in the file.</p>
<p>Code that reproduces the error when compiled using the command below:</p>
<pre><code>#include "/usr/local/include/chemfiles.hpp" //path to library on my mac
int main(int argc, char *argv[]) {
chemfiles::Trajectory testfile("test.dcd");
return 1;
}
</code></pre>
<p>Code that compiles successfully in CLI using the command below:</p>
<pre><code>#include "/usr/local/include/chemfiles.hpp" //path to library on my mac
int main(int argc, char *argv[]) {
// chemfiles::Trajectory testfile("test.dcd");
return 1;
}
</code></pre>
<p>Command to compile program:</p>
<pre><code>g++-8 -fopenmp trial.cpp -o trial -lchemfiles -L /usr/local/lib
// I am using openmp because my original code is about parallelisation with openmp
</code></pre>
<p>Error:</p>
<pre><code>Undefined symbols for architecture x86_64:
"chemfiles::Trajectory::Trajectory(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> >, char,
std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> > const&)", referenced from:
_main in ccnk7agz.o
"std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >::find(char, unsigned long) const",
referenced from:
file_open_info::parse(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> > const&,
std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > const&) in libchemfiles.a(Trajectory.cpp.o)
split_comment(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >&) in
libchemfiles.a(LAMMPSData.cpp.o)
"std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >::rfind(char, unsigned long) const",
referenced from:
file_open_info::parse(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> > const&,
std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > const&) in libchemfiles.a(Trajectory.cpp.o)
chemfiles::SDFFormat::read(chemfiles::Frame&) in
libchemfiles.a(SDF.cpp.o)
"std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >::compare(unsigned long, unsigned long, char
const*, unsigned long) const", referenced from:
file_open_info::parse(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> > const&,
std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > const&) in libchemfiles.a(Trajectory.cpp.o)
chemfiles::Trajectory::Trajectory(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >, char,
std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> > const&) in libchemfiles.a(Trajectory.cpp.o)
chemfiles::FormatFactory::register_format(chemfiles::FormatInfo,
std::__1::function<std::__1::unique_ptr<chemfiles::Format,
std::__1::default_delete<chemfiles::Format> >
(std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >, chemfiles::File::Mode,
chemfiles::File::Compression)>) in libchemfiles.a(FormatFactory.cpp.o)
chemfiles::Frame::guess_bonds() in
libchemfiles.a(Frame.cpp.o)
chemfiles::FormatInfo::FormatInfo(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >) in
libchemfiles.a(CSSR.cpp.o)
chemfiles::FormatInfo::FormatInfo(std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >) in
libchemfiles.a(MMTF.cpp.o)
chemfiles::MOL2Format::read(chemfiles::Frame&) in
libchemfiles.a(MOL2.cpp.o)
...
</code></pre>
| 3 | 1,905 |
How to get the element value in two sections in xml but ignore if any one of the section has empty element value in groovy
|
<p>We need to get the number element values from the services (there are two service sections). if it(number element) has the value in any of the service then it should take those values and if none of the services don't have number value then it should throw the exception. Please help me.</p>
<pre><code><service>
<serviceAlias>xxxx/4321</serviceAlias>
<Elements>
<Element>
<name>host</name>
<Interfaces>
<Interface>
<number>123</number>
</Interface>
<Interface>
<number>123</number>
</Interface>
<Interface>
<number>123</number>
</Interface>
</Interfaces>
</Element>
</Elements>
</service>
<service>
<serviceAlias>xxxx/1234/</serviceAlias>
<Elements>
<Element>
<name>host</name>
<Interfaces>
<Interface>
<number />
</Interface>
<Interface>
<number />
</Interface>
<Interface>
<number />
</Interface>
</Interfaces>
</Element>
</Elements>
</service>
</code></pre>
| 3 | 1,176 |
VUE - [food toppings counter ] how increase value of element -topping- in a v-for list -of toppings- when click on "+ add" button
|
<p>I'm a beginner in js and vue and I'm building a website to automate the orders of my pizzeria delivery.</p>
<p>I have a v-for list of toppings, customers can choose up to 4 toppings from a list and he can select 2, 3 or 4 times the same topping.</p>
<p>I created a counter for each item in the list, which stores the selected topping name in an array with a limit of 4. This worked.</p>
<p>How can I select and increase the amount of topping selected in the interface?</p>
<p>Below I have my code, and some visual references</p>
<p><a href="https://codepen.io/mordzin/pen/VwePBzq" rel="nofollow noreferrer">https://codepen.io/mordzin/pen/VwePBzq</a></p>
<pre><code>var App = new Vue({
el: '#app',
data: {
flavorCounter: 0,
cardapio: [],
order: [],
selectedItem: null
},
mounted() {
// const axios = require('axios');
axios.get('https://v2-api.sheety.co/4a5e4bb41d15a6ea344152fafca024db/zunepizza/cardapio')
.then((response) => {
this.cardapio = response.data.cardapio
})
.catch((error) => {
})
.finally(() => {
})
},
methods:{
addFlavor(){
if (this.flavorCounter <= 3) {
flavor = event.target.getAttribute('flavor')
this.order.push(flavor);
this.flavorCounter ++
console.log(this.order)
console.log(this.flavorCounter)
} else {
console.log('Maximo de sabores')
}
},
removeFlavor(){
if (this.flavorCounter >= 1) {
flavor = event.target.getAttribute('flavor')
this.order.splice(index, 1);
this.flavorCounter --
console.log(this.order)
console.log(this.flavorCounter)
} else {
}
},
}
});
</code></pre>
<p>
</p>
<pre><code><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<title>Zune Pizza</title>
<link rel="stylesheet" href="zunepizza.css">
<link async href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link async href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.min.js"></script> -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<template>
<div id="cardapio">
<ul v-for="cardapio in cardapio">
<li>
<div class="item-info">
<h3 class="item-title">{{cardapio.name}}</h3>
<div class="tag">
<h5>{{cardapio.type}}</h5>
</div>
<p class="item-title">{{cardapio.desc}}</p>
</div>
<div class="item-img">
<div class="flavorCounter" :id="cardapio.name">
<button
@click="addFlavor()"
:flavor="cardapio.name"
class="addFlavor controller-btn"> + </button>
<input :id='cardapio.name' type="number" value="0" class="flavorQuantity">
<button
@click='removecliFlavor()'
:flavor='cardapio.name'
class="addFlavor controller-btn"> - </button>
</div>
<img src="img/cardapio/baska.jpg" alt="">
</div>
</li>
</ul>
</div>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="zunepizza.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/A1zMk.png" rel="nofollow noreferrer">zune pizza interface topping counter</a></p>
<p>i need something like the image below</p>
<p><a href="https://i.stack.imgur.com/7vf0d.png" rel="nofollow noreferrer">ifood interface topping counter</a></p>
| 3 | 2,584 |
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[SecundaireSchool.Models.tblRapporten]'
|
<p>The model item passed into the dictionary is of type <code>System.Collections.Generic.List'1[SecundaireSchool.Models.tblRapporten]</code>, but this dictionary requires a model item of type <code>SecundaireSchool.Models.tblRapporten</code>.</p>
<p>Model <strong>tblStudenten</strong></p>
<pre><code>public partial class tblStudenten
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblStudenten()
{
this.tblRapportens = new HashSet<tblRapporten>();
}
public int student_id { get; set; }
public string naam { get; set; }
public string voornaam { get; set; }
public string emailadres { get; set; }
public string foto { get; set; }
public int klas_id { get; set; }
public virtual tblKlassen tblKlassen { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblRapporten> tblRapportens { get; set; }
public virtual IEnumerable<SelectListItem> Klassen { get; set; }
}
</code></pre>
<p>Model <strong>tblRapporten</strong></p>
<pre><code>public partial class tblRapporten
{
public int rapport_id { get; set; }
public double punt { get; set; }
public int vak_id { get; set; }
public int student_id { get; set; }
public virtual tblStudenten tblStudenten { get; set; }
public virtual tblVakken tblVakken { get; set; }
}
</code></pre>
<p>StudentController</p>
<pre><code>public ActionResult Report(int id)
{
return View(db.tblRapportens.Where(r => r.student_id == id).ToList());
}
</code></pre>
<p>View Report</p>
<pre><code>@model SecundaireSchool.Models.tblRapporten
@{
ViewBag.Title = "Report";
}
<h2>Report</h2>
<div>
<h4>tblRapporten</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.punt)
</dt>
<dd>
@Html.DisplayFor(model => model.punt)
</dd>
<dt>
@Html.DisplayNameFor(model => model.tblStudenten.naam)
</dt>
<dd>
@Html.DisplayFor(model => model.tblStudenten.naam)
</dd>
<dt>
@Html.DisplayNameFor(model => model.tblVakken.vak)
</dt>
<dd>
@Html.DisplayFor(model => model.tblVakken.vak)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.rapport_id }) |
@Html.ActionLink("Back to List", "Index")
</p>
</code></pre>
<p>I know that there is something wrong with the List of my controller, but I don't how to fix this.
Anyone?</p>
| 3 | 1,261 |
CSS Blur causing a bit of a position/height shift on span without filter
|
<p>I've created a snippet to demonstrate the issue I have, essentially, once you hover over one of the boxes, the span label seems to change</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#mobile--categories__wrapper {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
div#mobile--categories__wrapper a.mobile--category__link {
margin: 5px;
text-decoration: none;
width: calc(50% - 10px);
position: relative;
height: 200px;
background: rgba(255, 255, 255, 0.75);
box-shadow: inset 0 0 15px 2px rgba(0, 0, 0, 0.75);
border-radius: 5px;
}
div#mobile--categories__wrapper img.mobile--category__img {
max-width: 200px;
max-height: 200px;
width: 100%;
height: auto;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
}
div#mobile--categories__wrapper a.mobile--category__link img.mobile--category__img {
-webkit-filter: blur(1px);
filter: blur(1px);
transition: 0.2s all ease-in;
}
div#mobile--categories__wrapper a.mobile--category__link:hover img.mobile--category__img {
-webkit-filter: blur(0px);
filter: blur(0px);
transition: 0.2s all ease-in;
}
div#mobile--categories__wrapper span.mobile--category__label {
width: 100%;
display: block;
text-align: center;
height: 100%;
line-height: 200px;
z-index: 10;
position: relative;
}
div#mobile--categories__wrapper span.mobile--category__label {
width: 100%;
display: block;
text-align: center;
height: 100%;
line-height: 200px;
z-index: 10;
position: absolute;
}
span.mobile--category__label {
position: relative;
height: 75px !important;
background-color: rgba(0, 0, 0, 0.75);
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
line-height: 75px !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mobile--categories__wrapper">
<a class="mobile--category__link">
<img src="https://images.unsplash.com/photo-1528827997138-52e429c75136?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=6107df40cd644462e6ae1fdd7f1f4845" class="mobile--category__img" />
<span class="mobile--category__label">label goes here</span>
</a>
<a class="mobile--category__link">
<img src="https://images.unsplash.com/photo-1528827997138-52e429c75136?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=6107df40cd644462e6ae1fdd7f1f4845" class="mobile--category__img" />
<span class="mobile--category__label">label goes here</span>
</a>
<!-- <a class="mobile--category__link">
<img src="" class="mobile--category__img"/>
</a>
<a class="mobile--category__link">
<img src="" class="mobile--category__img"/> -->
</a>
</div></code></pre>
</div>
</div>
</p>
<p>I need to stop the label from shifting height by a couple of pixels on the hover blur effect I've given to the image before/below the label. What causes this and how could I fix it?</p>
| 3 | 1,320 |
Hold Spinner value for next tab
|
<p>I want the selected value from a spinnner to be kept in memory or temp table or anywhere, so that it can be used on next tab.<br/>
I watched lot of tutorials, but didn't find any solution.<br/>
I've the following code (it gives me toast message only; I populate the spinner from a database):</p>
<pre><code>super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
addFromDB();
select_cust_name=(EditText)findViewById(R.id.select_cust_name);
}
private void addFromDB() {
// TODO Auto-generated method stub
final Spinner spinner = (Spinner) findViewById(R.id.spinner_db);
resultsView = (TextView) findViewById(R.id.textView);
SQLiteDatabase myDB = null;
myDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
// ////////////These are using to add the values to database
myDB.execSQL("CREATE TABLE " + SAMPLE_TABLE_NAME + " (" + _id
+ " INTEGER PRIMARY KEY AUTOINCREMENT , " + cust_name
+ " TEXT , " + cust_add + " TEXT)");
myDB.execSQL("insert into tbl_customer(cust_name, cust_add) values ('Fool', 'FF' );");
final Cursor c = myDB.query(SAMPLE_TABLE_NAME, null, null, null, null, null, null);
char _idColumnIndex = (char) c.getColumnIndexOrThrow("_id");
char cust_nameColumnIndex = (char) c.getColumnIndexOrThrow("cust_name");
char cust_addColumnIndex = (char) c.getColumnIndexOrThrow("cust_add");
adapterForSpinner = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item);
adapterForSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterForSpinner);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
SQLiteDatabase myDB = null;
Toast.makeText(
parent.getContext(),
"Customer is "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
String selected = parent.getItemAtPosition(pos).toString();
insert(selected);
</code></pre>
<p>Thanks in advance. </p>
<p>here is my log:</p>
<pre><code>05-03 11:29:31.743: E/Cursor(10155): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/tab.layout/databases/db_sales, table = tbl_customer, query = SELECT * FROM tbl_customer
05-03 11:29:31.743: E/Cursor(10155): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteCursor.<init>(SQLiteCursor.java:210)
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53)
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229)
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184)
05-03 11:29:31.743: E/Cursor(10155): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1264)
05-03 11:29:31.743: E/Cursor(10155): at tab.layout.Customers.addFromDB(Customers.java:63)
05-03 11:29:31.743: E/Cursor(10155): at tab.layout.Customers.onCreate(Customers.java:40)
05-03 11:29:31.743: E/Cursor(10155): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
05-03 11:29:31.743: E/Cursor(10155): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
05-03 11:29:31.743: E/Cursor(10155): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
05-03 11:29:31.743: E/Cursor(10155): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:651)
05-03 11:29:31.743: E/Cursor(10155): at android.widget.TabHost.setCurrentTab(TabHost.java:323)
05-03 11:29:31.743: E/Cursor(10155): at android.widget.TabHost.addTab(TabHost.java:213)
05-03 11:29:31.743: E/Cursor(10155): at tab.layout.MyTablayoutActivity.SetupTabs(MyTablayoutActivity.java:48)
05-03 11:29:31.743: E/Cursor(10155): at tab.layout.MyTablayoutActivity.onCreate(MyTablayoutActivity.java:20)
05-03 11:29:31.743: E/Cursor(10155): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-03 11:29:31.743: E/Cursor(10155): at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 11:29:31.743: E/Cursor(10155): at android.os.Looper.loop(Looper.java:123)
05-03 11:29:31.743: E/Cursor(10155): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-03 11:29:31.743: E/Cursor(10155): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 11:29:31.743: E/Cursor(10155): at java.lang.reflect.Method.invoke(Method.java:521)
05-03 11:29:31.743: E/Cursor(10155): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-03 11:29:31.743: E/Cursor(10155): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-03 11:29:31.743: E/Cursor(10155): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
| 3 | 2,509 |
Muenchian grouping, counting number of groups
|
<p>Am using muenchian grouping to group subjets and grades as per students. I can get count for number of subjects opted by each student. But I could not get count of number of students.</p>
<p><strong>Input XML</strong></p>
<pre><code><data>
<school>MIT Kindergarden</school>
<year>2013</year>
<batch>B</batch>
<result>
<student>ABC</student>
<id>001</id>
<subject>ALG</subject>
<grade>C</grade>
</result>
<result>
<student>ABC</student>
<id>001</id>
<subject>HIS</subject>
<grade>B</grade>
</result>
<result>
<student>XYZ</student>
<id>002</id>
<subject>ALG</subject>
<grade>C</grade>
</result>
<result>
<student>XYZ</student>
<id>002</id>
<subject>ALG</subject>
<grade>A</grade>
</result>
</data>
</code></pre>
<p><strong>XSLT</strong> </p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="group-by-id" match="data/result" use="id" />
<xsl:template match="/">
<schoolresult>
<schoolname><xsl:value-of select="data/school" /></schoolname>
<resultyear><xsl:value-of select="data/year" /></resultyear>
<batch><xsl:value-of select="data/batch" /></batch>
<totalstudent>[Could not find]</totalstudent>
<xsl:for-each select="data/result[generate-id() = generate-id(key('group-by-id', id)[1])]">
<student>
<info>
<name><xsl:value-of select="student" /></name>
<id><xsl:value-of select="id" /></id>
<subjectsopted>
<xsl:value-of select="count(. | key('group-by-id', id))" />
</subjectsopted>
</info>
<xsl:for-each select="key('group-by-id', id)">
<subject>
<name><xsl:value-of select="subject" /></name>
<grade><xsl:value-of select="grade" /></grade>
</subject>
</xsl:for-each>
</student>
</xsl:for-each>
</schoolresult>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p><strong>Output XML</strong></p>
<pre><code><schoolresult>
<schoolname>MIT Kindergarden</schoolname>
<resultyear>2013</resultyear>
<batch>B</batch>
<studentscount>[Count not find]</studentscount>
<student>
<info>
<name>ABC</name>
<id>001</id>
<subjectsopted>2</subjectsopted>
</info>
<subject>
<name>ALG</name>
<grade>C</grade>
</subject>
<subject>
<name>HIS</name>
<grade>B</grade>
</subject>
</student>
<student>
<info>
<name>XYZ</name>
<id>002</id>
<subjectsopted>2</subjectsopted>
</info>
<subject>
<name>ALG</name>
<grade>C</grade>
</subject>
<subject>
<name>ALG</name>
<grade>A</grade>
</subject>
</student>
</schoolresult>
</code></pre>
| 3 | 2,054 |
How can I turn this into a for loop?
|
<p>I am writing a Mastermind program in Java. So the user has to enter the number of pegs and colors and a code will randomly be generated and the program will do its thing and tell them if they got the code or not. I have a bunch of IF statements and I tried putting it into a for loop so I don't have to create a if statement when the user increases the amt of pegs but that does not work. Any suggestion? Here is the code:</p>
<pre><code>public void program(int [] peg, int amtpegs,int amtcolors) {
Random generator = new Random();
KeyboardReader reader = new KeyboardReader();
int color = 0, guess = 1,pegs = 0;
int [] guesses = new int[10];
for(int i = 0; i<peg.length;i++) {
peg[i]=generator.nextInt(amtpegs)+1;
System.out.println(peg[i]);
}
//Repeat till the player wins
while(true){
//Get input from user
for(int x = 0; x<amtpegs;x++)
{
guesses[x]=reader.readInt("Enter your numbers: ");
}
//Check if peg in correct index
for(int y = 0; y<amtpegs;y++) {
if (peg[y]==guesses[y]){
pegs++;
}
//Check if the color is correct
if (guesses[0]==peg[0] || guesses[0]==peg[1] || guesses[0]==peg[2]){
color++;
}
if (guesses[1]==peg[1] || guesses[1]==peg[0] || guesses[1]==peg[2]){
color++;
}
if (guesses[2]==peg[0] || guesses[2]==peg[1] || guesses[2]==peg[2]){
color++;
}
if (guesses[3]==peg[3] || guesses[3]==peg[1] || guesses[3]==peg[2]){
color++;
}
System.out.println("You have "+pegs+" correct peg(s) and "+color+" correct colors");
//Exit if player wins
if (color==amtcolors && pegs==amtpegs){
System.out.println("You have broken the code in "+guess+" guesses");
break;
}
//Increment guess count
guess++;
//Reset the color and peg value
color=0;
pegs=0;
}
</code></pre>
<p>i tried making the if or statements into a for loop by replacing the indexes with the x and j in the for loop:</p>
<pre><code>for(int x = 0; x<amtpegs;x++) {
// System.out.println(x+"n");
for(int j = 0; j<amtpegs; j++){
// System.out.println(j+"N");
if (guesses[x]==peg[j]){
color++;
if (color==amtcolors && pegs==amtpegs){
System.out.println("You have broken the code in "+guess+" guesses");
break;
}
}
</code></pre>
<p>but that does not work since my variable colors increases in values. EX: If i input 10 pegs and 9 colors it will come out a 10 pegs and 20 or 30 colors.</p>
| 3 | 1,645 |
How to change a view after user clicked on a button and a Firestore document got updated?
|
<p>So basically when a user comes to the "premium" activity in my app he sees a button which says "Purchase premium". When he clicks on it a document in Firestore gets updated (a boolean from false to true) and the button disappears and instead of the button a TextView appears. When the user navigates back to the MainActivity and from there again to the "premium" activity he sees the "Purchase premium" button again which I don't want because he already "bought" it. The question is how can I achieve that when the user clicks on the button, the view of the layout changes for good, so when the user navigates back to the activity he will not be able to make the purchase again. I don't want him to see the button.</p>
<p>Should I use the boolean (premium member: true) that got changed in the document in Firestore after he clicked on it to do this? Like: If document says "premium membership: true" set button visibility gone etc. This would make a "read" to Firestore every time the user navigates to the Activity, is there a better way?</p>
<p>Here is my onClickListener of the purchase button:</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_premium_purchase);
purchase = findViewById(R.id.card_view_premium_purchase);
premiumTextView = findViewById(R.id.premium_purchase_success);
premiumTextView.setVisibility(View.GONE);
purchase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String username = user.getDisplayName();
DocumentReference userRef = db.collection("User").document(username);
// Set the "pro membership" to true
userRef
.update("pro membership", true).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully updated!");
Toast.makeText(PremiumPurchaseActivity.this, "Guess Premium successfully bought", Toast.LENGTH_SHORT).show();
premiumTextView.setVisibility(View.VISIBLE);
purchase.setVisibility(View.GONE);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error updating document", e);
}
});
}
});
}
</code></pre>
| 3 | 1,156 |
Realm - Why are notification blocks triggered when a write transaction begins?
|
<p>I noticed today that Realm notification blocks are triggered when a write transaction begins. Intuitively I would have thought that <em>ending</em> a write transaction would trigger collection notifications with the changes that just happened, but I tracked down a crash in my code today resulting from a notification block being called when a write transaction begins.</p>
<p>Relevant stack frames before my notification handling is invoked:</p>
<pre><code> frame #17: 0x0000000102535b98 Realm`RLMNotificationToken* RLMAddNotificationBlock<realm::Results>(this=0x00000001742974f0, changes=0x000000016fdf9de0, err=<unavailable>) block_pointer, bool)::'lambda'(realm::CollectionChangeSet const&, std::exception_ptr)::operator()(realm::CollectionChangeSet const&, std::exception_ptr) const + 608 at RLMCollection.mm:345
frame #18: 0x0000000102535700 Realm`realm::CollectionChangeCallback::Impl<RLMNotificationToken* RLMAddNotificationBlock<realm::Results>(objc_object*, realm::Results&, void (objc_object*, RLMCollectionChange*, NSError*) block_pointer, bool)::'lambda'(realm::CollectionChangeSet const&, std::exception_ptr)>::after(this=0x00000001742974e8, change=0x000000016fdf9de0) + 56 at collection_notifications.hpp:157
frame #19: 0x000000010248723c Realm`realm::CollectionChangeCallback::after(this=0x000000016fdf9dd0, c=0x000000016fdf9de0) + 64 at collection_notifications.hpp:122
frame #20: 0x0000000102487198 Realm`auto realm::_impl::CollectionNotifier::after_advance(this=0x000000016fdf9f90, lock=0x000000016fdf9ef0, callback=0x0000000103b62520)::$_9::operator()<std::__1::unique_lock<std::__1::mutex>, realm::_impl::CollectionNotifier::Callback>(std::__1::unique_lock<std::__1::mutex>&, realm::_impl::CollectionNotifier::Callback&) const + 156 at collection_notifier.cpp:326
frame #21: 0x0000000102479780 Realm`void realm::_impl::CollectionNotifier::for_each_callback<realm::_impl::CollectionNotifier::after_advance()::$_9>(this=0x00000001049d3e18, fn=0x000000016fdf9f90)::$_9&&) + 236 at collection_notifier.cpp:367
frame #22: 0x0000000102479688 Realm`realm::_impl::CollectionNotifier::after_advance(this=0x00000001049d3e18) + 28 at collection_notifier.cpp:315
frame #23: 0x000000010247ba3c Realm`realm::_impl::NotifierPackage::after_advance(this=0x000000016fdfa5e8) + 352 at collection_notifier.cpp:474
frame #24: 0x00000001026c8de4 Realm`void (anonymous namespace)::advance_with_notifications<realm::_impl::transaction::begin(context=0x0000000174221480, sg=0x0000000104020200, func=0x000000016fdfa540, notifiers=0x000000016fdfa5e8)::$_1>(realm::BindingContext*, realm::SharedGroup&, realm::_impl::transaction::begin(realm::SharedGroup&, realm::BindingContext*, realm::_impl::NotifierPackage&)::$_1&&, realm::_impl::NotifierPackage&) + 1152 at transact_log_handler.cpp:674
frame #25: 0x00000001026c8958 Realm`realm::_impl::transaction::begin(sg=0x0000000104020200, context=0x0000000174221480, notifiers=0x000000016fdfa5e8) + 56 at transact_log_handler.cpp:702
frame #26: 0x00000001024de620 Realm`realm::_impl::RealmCoordinator::promote_to_write(this=0x0000000103b0e108, realm=0x0000000103b0e498) + 328 at realm_coordinator.cpp:741
frame #27: 0x00000001026766b4 Realm`realm::Realm::begin_transaction(this=0x0000000103b0e498) + 552 at shared_realm.cpp:483
frame #28: 0x000000010262df3c Realm`::-[RLMRealm beginWriteTransaction](self=0x00000001740a9fc0, _cmd="beginWriteTransaction") + 48 at RLMRealm.mm:437
</code></pre>
<p>In a particular use case in my code, one of my notification callbacks creates a new set of RLMResults to display in a table and adds a notification block to it. Adding the notification block raises the expected exception in that case: <code>Cannot create asynchronous query while in a write transaction</code>. </p>
<p>That rule is easy to understand, I'm really just curious about why beginning a write transaction would trigger collection notifications, instead of waiting until after the transaction.</p>
| 3 | 1,408 |
how do you get email data in Android Studio?
|
<p>Why does this crash my android app whenever I attempt to run it / what is the best way to get email data into an android app? </p>
<p>The app itself only consists of a button to click - I have gotten the below code to work in eclipse and I am attempting to run it on a mobile phone and not an emulator so I am no longer getting a network error.</p>
<pre><code>package com.example.marc.emailtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v){
String host = "pop.gmail.com";// change accordingly
String StoreType = "pop3";
String user = "******@gmail.com";// I purposefully hid these
String password = "********";// I purposefully hid these
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
Log.i("MainActivity1", "---------------------------------");
Log.i("MainActivity1", "Email Number " + (i + 1));
Log.i("MainActivity1", "Subject: " + message.getSubject());
Log.i("MainActivity1", "From: " + message.getFrom()[0]);
Log.i("MainActivity1", "Text: " + message.getContent().toString());
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
Log.i("MainActivity1", e.getMessage());
} catch (MessagingException e) {
e.printStackTrace();
Log.i("MainActivity1", e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.i("MainActivity1", e.getMessage());
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/oW1Ks.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oW1Ks.png" alt="Here is the logcat"></a></p>
| 3 | 1,347 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.