title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Resolving a Promise without calling the 'then' | <p>I have this code that is part of a small API that I am writing for an NPM module called Poolio. The question I have seems to be a common question for those supporting error-first callbacks as well as promises- how do we support both while maintaining consisent APIs and consistent return values from the API? For example, if I conditionally return a promise from my API, depending on whether the consumer of my lib provides a callback, that is a little awkward in my opinion.</p>
<p>The consumer of the lib can provide a callback or use the Promise then function, but not both.</p>
<p>Here is a function exported by my lib, that I would like to promisify:</p>
<pre><code>Pool.prototype.any = function (msg, cb) {
var workId = this.counter++;
var self = this;
return new Promise(function (resolve, reject) {
if (typeof cb === 'function') {
self.resolutions.push({
workId: workId,
cb: cb
});
}
else {
self.resolutions.push({
workId: workId,
resolve: resolve,
reject: reject
});
}
if (this.available.length > 0) {
var cp = this.available.shift();
cp.workId = workId;
cp.send(msg);
}
else {
self.msgQueue.push({
workId: workId,
msg: msg
});
}
});
};
</code></pre>
<p>my question is - if the user provides a callback function in the original function arguments, how can I resolve the promise without calling 'then'?
Sorry it's hard to explain but hopefully you can understand.</p>
<p>also there is this interesting question:
<a href="https://stackoverflow.com/questions/20068467/angular-js-do-never-resolved-promises-cause-memory-leak">Do never resolved promises cause memory leak?</a></p> | 1 |
how to interprete this thread dump from a hung Java Swing application? | <p>I have the following <strong>thread dump</strong> from a <strong>hung</strong> java swing application. It hung after a <strong>button</strong> is clicked and the GUI changed to blank. Other threads in socket communication and task management are still working (from the log file I can tell). I have removed some non-relevant output.</p>
<p>The <strong>#13 AW-EventQueue-0</strong> should send out a command through the socket but it seems failed there. The <strong>#20</strong> and <strong>#21</strong> are A<strong>W-EventQueue-0-SharedResourceRunner</strong> which is not the same as the #13? It seems there is no deadlock but the GUI is not responsive and became blank.</p>
<p><strong>do you see any useful information about the cause of the hanging?</strong></p>
<pre><code>Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.20-b23 mixed mode):
"DestroyJavaVM" #32 prio=5 os_prio=0 tid=0x00007f286c009800 nid=0xa41 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"TimerQueue" #22 daemon prio=5 os_prio=0 tid=0x00007f28002a8800 nid=0xa65 waiting on condition [0x00007f284c56f000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x0000000088a8f5c0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
at java.util.concurrent.DelayQueue.take(DelayQueue.java:211)
at javax.swing.TimerQueue.run(TimerQueue.java:171)
at java.lang.Thread.run(Thread.java:745)
"AWT-EventQueue-0-SharedResourceRunner" #21 daemon prio=6 os_prio=0 tid=0x00007f280021d000 nid=0xa64 in Object.wait() [0x00007f284d434000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000088aec748> (a jogamp.opengl.SharedResourceRunner)
at java.lang.Object.wait(Object.java:502)
at jogamp.opengl.SharedResourceRunner.run(SharedResourceRunner.java:276)
- locked <0x0000000088aec748> (a jogamp.opengl.SharedResourceRunner)
at java.lang.Thread.run(Thread.java:745)
"AWT-EventQueue-0-SharedResourceRunner" #20 daemon prio=6 os_prio=0 tid=0x00007f28001f3000 nid=0xa63 in Object.wait() [0x00007f284f7f5000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000088aed588> (a jogamp.opengl.SharedResourceRunner)
at java.lang.Object.wait(Object.java:502)
at jogamp.opengl.SharedResourceRunner.run(SharedResourceRunner.java:276)
- locked <0x0000000088aed588> (a jogamp.opengl.SharedResourceRunner)
at java.lang.Thread.run(Thread.java:745)
"AWT-EventQueue-0" #13 prio=6 os_prio=0 tid=0x00007f286c444800 nid=0xa59 in Object.wait() [0x00007f2858913000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000dc467018> (a java.lang.Object)
at java.lang.Object.wait(Object.java:502)
at com.mycp.common.task.BMBTaskBase.startTask(BMBTaskBase.java:551)
- locked <0x00000000dc467018> (a java.lang.Object)
at com.mycp.uiapp.workmgmt.WorkMgmtMgr.sendBegCmd(WorkMgmtMgr.java:334)
at com.mycp.uiapp.workmgmt.WorkMgmtPanelBase.prepareAndSendBegWork(WorkMgmtPanelBase.java:559)
at com.mycp.uiapp.workmmgmt.WorkMgmtPanel.prepareAndSendBegWork(WorkMgmtPanel.java:1479)
at com.mycp.uiapp.workmgmt.WorkMgmtPanelBase.btnPrepareClicked(WorkMgmtPanelBase.java:363)
at com.mycp.uiapp.workmgmt.WorkMgmtPanel.btnPrepareClicked(WorkMgmtPanel.java:1412)
at com.mycp.uiapp.workmgmt.WorkMgmtPanel.actionPerformed(WorkMgmtPanel.java:1336)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
"AWT-Shutdown" #14 prio=5 os_prio=0 tid=0x00007f286c443000 nid=0xa58 in Object.wait() [0x00007f2858a17000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000088ae8c28> (a java.lang.Object)
at java.lang.Object.wait(Object.java:502)
at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:295)
- locked <0x0000000088ae8c28> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:745)
"AWT-XAWT" #12 daemon prio=6 os_prio=0 tid=0x00007f286c384000 nid=0xa51 runnable [0x00007f285914f000]
java.lang.Thread.State: RUNNABLE
at sun.awt.X11.XToolkit.waitForEvents(Native Method)
at sun.awt.X11.XToolkit.run(XToolkit.java:559)
at sun.awt.X11.XToolkit.run(XToolkit.java:523)
at java.lang.Thread.run(Thread.java:745)
"Java2D Disposer" #10 daemon prio=10 os_prio=0 tid=0x00007f286c35e000 nid=0xa50 in Object.wait() [0x00007f2859250000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000087ab7ec0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:142)
- locked <0x0000000087ab7ec0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:158)
at sun.java2d.Disposer.run(Disposer.java:148)
at java.lang.Thread.run(Thread.java:745)
"Thread-0" #9 prio=5 os_prio=0 tid=0x00007f286c234800 nid=0xa4f waiting on condition [0x00007f2859af5000]
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at com.mycp.logging.BMBLogging$Task.run(BMBLogging.java:1072)
at java.lang.Thread.run(Thread.java:745)
"Service Thread" #8 daemon prio=9 os_prio=0 tid=0x00007f286c0cf800 nid=0xa4d runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread2" #7 daemon prio=9 os_prio=0 tid=0x00007f286c0b2000 nid=0xa4c waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007f286c0b0000 nid=0xa4b waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007f286c0ad800 nid=0xa4a waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f286c0ab000 nid=0xa49 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f286c07c000 nid=0xa48 in Object.wait() [0x00007f285a2dd000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000087a7e6c8> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:142)
- locked <0x0000000087a7e6c8> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:158)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f286c07a000 nid=0xa47 in Object.wait() [0x00007f285a3de000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000087a7e708> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:157)
- locked <0x0000000087a7e708> (a java.lang.ref.Reference$Lock)
"VM Thread" os_prio=0 tid=0x00007f286c072800 nid=0xa46 runnable
"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f286c01e800 nid=0xa42 runnable
"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f286c020800 nid=0xa43 runnable
"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f286c022000 nid=0xa44 runnable
"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f286c024000 nid=0xa45 runnable
"VM Periodic Task Thread" os_prio=0 tid=0x00007f286c0d2000 nid=0xa4e waiting on condition
JNI global references: 485
Heap
PSYoungGen total 118272K, used 98176K [0x00000000d6e00000, 0x00000000de700000, 0x0000000100000000)
eden space 113152K, 82% used [0x00000000d6e00000,0x00000000dc8e00c8,0x00000000ddc80000)
from space 5120K, 100% used [0x00000000de180000,0x00000000de680000,0x00000000de680000)
to space 5120K, 0% used [0x00000000ddc80000,0x00000000ddc80000,0x00000000de180000)
ParOldGen total 159744K, used 76671K [0x0000000084a00000, 0x000000008e600000, 0x00000000d6e00000)
object space 159744K, 47% used [0x0000000084a00000,0x00000000894dfc50,0x000000008e600000)
Metaspace used 30027K, capacity 30212K, committed 30464K, reserved 1077248K
class space used 3528K, capacity 3582K, committed 3584K, reserved 1048576K
</code></pre> | 1 |
Make element same width as dynamically sized image? | <p>I have a responsive slideshow-type layout with captions below each image.</p>
<p>I'm attempting to get the caption to be the same width as the image. The problem is that the image is scaled to fit in the browser vertically, and my captions are the getting the width of the image prior to scaling.</p>
<p><a href="https://jsfiddle.net/601a5uqv/" rel="nofollow noreferrer">Fiddle</a></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>#big_container {
display:block;
position:relative;
width:100%;
padding-bottom:40%;
white-space:nowrap;
overflow-x:scroll;
overflow-y:hidden;
}
#big_container>div {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
}
.little_container {
display:inline-block;
height:100%;
width:100%;
text-align:center;
}
#big_container figure {
display:inline-block;
height:100%;
margin:0;
}
figure img {
max-height:calc(100% - 40px); /* subtract height of caption */
}
figcaption {
display:block;
width:100%;
text-align:left;
box-sizing:border-box;
margin:0;
padding:10px;
line-height:20px;
background-color:#ddd;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="big_container">
<div>
<div class="little_container">
<figure>
<img src="http://placekitten.com/500/440">
<figcaption>
have a kitty!!1
</figcaption>
</figure>
</div>
<div class="little_container">
<figure>
<img src="http://placekitten.com/450/400">
<figcaption>
moar kitty!
</figcaption>
</figure>
</div>
<div class="little_container">
<figure>
<img src="http://placekitten.com/300/440">
<figcaption>
too many kitty..
</figcaption>
</figure>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>How can I make a caption which is scaled based on the width of a fluid image?<br>
I'm hoping for a pure-css solution.</p>
<p><strong>Update</strong><br>
It turns out my above attempt <a href="https://stackoverflow.com/questions/35097704/make-element-same-width-as-dynamically-sized-image?noredirect=1#comment57917268_35097704">partially works in chrome and opera, but exhibits some odd behavior</a>.
I haven't found any bug reports on the subject, but I can't help wondering if this might be considered a bug in the browser.</p>
<hr>
<p>For clarity, here's a brief outline of my exact requirements:</p>
<ul>
<li>Caption element must be the same width as the image (it'd be nice to be able to left or right align the caption text to the edge of the image)</li>
<li>Image must not be cropped or stretched </li>
<li>Image and caption must both fit in their container (which may be fluid), using as much room as possible.</li>
<li>Above rules should hold true for images of any dimension</li>
<li>CSS only (compatibility with old browsers not a major concern, but it is a plus)</li>
</ul>
<p>The html markup <em>can</em> be changed.</p> | 1 |
Maven install passes but there are tests failing | <p>I am running a maven install for a spring boot project with multiple modules in STS. </p>
<p>I can see that there are few test cases failing but the maven install passes and shows build successful. </p>
<p>The tests are not being skipped, they are running during the install stage and the surefire reports are also being generated with failed tests but somehow the build passes. </p>
<p>I want the build to fail as the tests are failing, any pointers are appreciated? </p>
<pre><code><properties>
<maven-surefire-plugin-version>2.16</maven-surefire-plugin-version>
<junit.version>4.12</junit.version>
...
...
</properties>
..
..
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
...
...
</dependency>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
</plugins>
...
...
...
</pluginManagement>
</build>
</code></pre>
<p>Maven logs:</p>
<pre><code>Results :
Failed tests:
MyClassTest.testMyClass:35 null
Tests in error:
MyClass1Test.testMyClass:64 » NullPointer
Tests run: 3, Failures: 1, Errors: 1, Skipped: 0
[ERROR] There are test failures.
Please refer to /Users/XXX/yyyy/zzzz/target/surefire-reports for the individual test results.
[INFO]
[INFO] --- maven-war-plugin:2.6:war (default-war) @ zzzzz ---
[INFO] Packaging webapp
[INFO] Assembling webapp [zzzzz] in [/Users/XXXX/yyyyy/zzzz/target/zzzz-1.0.0]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/XXXX/zzzz/zzzz/src/main/webapp]
[INFO] Webapp assembled in [232 msecs]
[INFO] Building war: /Users/XXX/yyyyy/zzzzz/target/zzzzz-1.0.0.war
</code></pre>
<p>At last, it just shows all the modules build successfully. Shouldn't it stop building the war itself as soon as it detects a failure?</p> | 1 |
Error encountered while pushing to the remote Git repository | <p>I'm currently working on a project that is hosted on visualstudio.com (Visual studio online) and I choose Git as the code repository but I'm getting a error when I try to push my changes in the code to a Git repository.</p>
<p>When I'm using Visual Studio 2015 to push it I'm getting that error message:</p>
<pre><code>Error encountered while pushing to the remote repository: Chunked encoding upload is not supported on the HTTP/1.0 protocol
</code></pre>
<p>I also have Visual Studio 2013 installed on this machine, and with VS2013 I can push the changes to the repository without any errors.</p>
<ul>
<li><strong>What can I do to solve this problem?</strong></li>
</ul>
<p>PS: I'm behind a proxy server. (<strong>I can push the changes via VS2013 throught the <em>proxy</em></strong>)</p> | 1 |
TCP client/server program between ubuntu and raspberry pi | <p>I want to do the TCP client/server communication between <code>Raspberry Pi</code> and laptop with <code>Ubuntu</code> OS running using <code>VMware Workstation</code>. Raspberry Pi act as the client and Ubuntu act as the server. I am able to successfully compile the client and server program.But on the client side it throws an error <code>ERROR, no such host</code>. I made changes in Ubuntu network settings to share with other computers. But still communication is not taking place. I am able to ping successfully between Raspberry Pi and Ubuntu. But I am not able to communicate between the client and server side. Can anyone solve this issue and suggest me how to do the network settings in Ubuntu so that Pi and Ubuntu can communicate.</p>
<p>client.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return 0;
}
</code></pre>
<p>server.c</p>
<pre><code>/* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0)
error("ERROR writing to socket");
close(newsockfd);
close(sockfd);
return 0;
}
</code></pre> | 1 |
PHP: Days, hours and minutes left to a certain date? | <p>I'm trying to get remaining Days, hours and minutes to a certain date using php.</p>
<p>However i get a very strange output from my code which looks like this:</p>
<pre><code>-16828 days and -11 hours and -21 minutes and -24 seconds
</code></pre>
<p>The future dates are stored in the mysql database in this format:</p>
<pre><code>29/01/2016 7pm
</code></pre>
<p>So I went ahead and done this:</p>
<pre><code>$Draw_time = "29/01/2016 7pm";
$date = $Draw_time;
$timestamp = strtotime($date);
$new_date = date('Y-m-d a',$timestamp );
$seconds = strtotime($new_date) - time();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
echo "$days days and $hours hours and $minutes minutes and $seconds seconds";
</code></pre>
<p>But when i run this code, I get the above strange output!</p>
<p>I understand that this could be because of a number reasons but the only thing i could think of is the fact that I am using <code>a</code> in my format? </p>
<p>Could someone please advise on this issue?</p> | 1 |
Change Button's Color in Another Form C# | <p>I have 2 forms named Form1 and Form2. </p>
<p>Each forms there are 3 buttons with the same name: Button1, Button2, and Button3.</p>
<p>What I want is when each color of Buttons in Form1 are changed, and then each color of Buttons in Form 2 are also changed. For example, Button 1 in Form 1 is green, so Button 1 in Form 1 is also green. </p>
<p>How can I do this ? These are what I have done and it doesn't work</p>
<p>Form1</p>
<pre><code>Form2 form2 = new Form2();
private void Klik_Click(object sender, EventArgs e)
{
counter++;
if(counter==1)
{
Button1.BackColor = Color.Red;
Button2.BackColor = Color.Red;
Button3.BackColor = Color.Red;
form2.Button1.BackColor = Color.Red;
form2.Button2.BackColor = Color.Red;
form2.Button3.BackColor = Color.Red;
}
if (counter > 1)
{
Button1.BackColor = Color.Green;
Button2.BackColor = Color.Green;
Button3.BackColor = Color.Green;
form2.Button1.BackColor = Color.Green;
form2.Button2.BackColor = Color.Green;
form2.Button3.BackColor = Color.Green;
counter = 0;
}
}
private void StripMenu_Click(object sender, EventArgs e)
{
form2.Show();
}
</code></pre> | 1 |
Use of double underscore in C | <p>I was studying <code>C programming a modern approach</code> book. I found a question in it:</p>
<p>Why is it not a good idea for an identifier to contain more than one adjacent underscore (As in current__balance for example)?</p>
<p>Can anyone explain to me why is it so?</p> | 1 |
How to emulate a browser with JavaScript support via Mechanize? | <p>I'm using a Python script (Mechanize) to login to a proxy portal. I can login successfully. I can check that from <code>read()</code> function. </p>
<p>However, after successful login, I couldn't access the blocked sites by the proxy. So I checked the HTTP headers from FF and found that <code>Connection: Keep-alive</code>. But from <code>mechanize</code>, I found <code>Connection: close</code>. I tried to imitate the HTTP header exactly as from FF using <code>browser.addheaders</code> but this didn't work as well :(</p>
<p>After deep digging, I found a couple of suggestions that the server closes the connection because mechanize can't totally emulate a browser as the webpage contains JS which is not supported by <code>mechanize</code></p>
<p><strong>So, is there a way to emulate (make the server feel) that mechanize is a browser (supports JS), even though it doesn't?</strong></p>
<p>BTW, I don't need JS, I can login successfully as I mentioned above. And please don't suggest PhantomJS. <em>I need a Python package to do the job not a headless browser.</em></p>
<p><strong>Update:</strong></p>
<p><strong>FireFox Headers:</strong></p>
<pre><code>GET xxx HTTP/1.1
Host: xxx
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: DSLastAccess=1454082611
Connection: keep-alive
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Set-Cookie: DSEPAgentInstalled=; path=/; expires=Tue, 31-Jan-2006 16:18:32 GMT; secure
Date: Fri, 29 Jan 2016 16:18:32 GMT
x-frame-options: SAMEORIGIN
Connection: Keep-Alive
Keep-Alive: timeout=15
Pragma: no-cache
Cache-Control: no-store
Expires: -1
Transfer-Encoding: chunked
</code></pre>
<p><strong>Mechanize addheaders:</strong></p>
<pre><code>browser.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),\
('Accept-Language', 'en-US,en;q=0.5'),\
('Accept-Encoding', 'gzip, deflate'),\
('Host', 'xxx.net'),\
('Connection','keep-alive'),\
('Cookie', 'DSLastAccess=1454082611'),\
('User-agent', 'Mozilla/5.0 (X11; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0')]
</code></pre>
<p><strong>Mechanize Headers</strong></p>
<pre><code>send: 'CONNECT xxx.net:443 HTTP/1.0\r\n'
send: '\r\n'
send: 'GET xxx.cgi HTTP/1.1\r\nAccept-Language: en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nHost: xxx.net\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0\r\nConnection: close\r\nCookie: DSLastAccess=1454082611\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: text/html; charset=utf-8
header: Set-Cookie: DSEPAgentInstalled=; path=/; expires=Tue, 31-Jan-2006 16:31:03 GMT; secure
header: Date: Fri, 29 Jan 2016 16:31:03 GMT
header: x-frame-options: SAMEORIGIN
header: Connection: close
header: Pragma: no-cache
header: Cache-Control: no-store
header: Expires: -1
</code></pre>
<p>Another thing that drives me crazy, that the sent <code>Connection</code> from <code>mechanize</code> is <code>: close</code> even though I've set it as <code>keep-alive</code> as you can see in <code>addheaders</code></p> | 1 |
Why C# compiler use an invalid method's overload? | <p>I have been confused by the following code</p>
<pre><code>class A
{
public void Abc(int q)
{
Console.Write("A");
}
}
class B : A
{
public void Abc(double p)
{
Console.Write("B");
}
}
...
var b = new B();
b.Abc((int)1);
</code></pre>
<p>The result of code execution is "B" written to console.</p>
<p>In fact the B class contains two overloads of Abc method, the first for int parameter, the second one for double. Why the compiler use a double version for an integer argument?</p>
<p>Be careful the method abc(double) doesn't shadow or override the method abc(int)</p> | 1 |
Is numpy slower than c++ linear algebra libraries like eigen? | <p>I use it to implement neural networks. I prefer NumPy, because it is more convenient to prepare data with Python; however, I am concerned that NumPy is not as fast as c++ libraries.</p> | 1 |
ionic emulate ios - won't emulate and says no such file or directory | <p>Ran <code>add ios</code> and <code>build ios</code> fine, but then I ran <code>ionic emulate ios</code> and it brought up the <code>xcode</code> emulator but with no app or button for my app (just safari, maps, etc.). </p>
<p>I then later ran <code>ionic emulate ios --target="iPhone-5s"</code> and got this error:</p>
<pre><code> BUILD SUCCEEDED
An error was encountered processing the command
(domain=com.apple.CoreSimulator.SimError, code=159): Invalid device
state An error was encountered processing the command
(domain=com.apple.CoreSimulator.SimError, code=159): Invalid device
state
ENOENT: no such file or directory, stat
'/Users/sh/Library/Logs/CoreSimulator/62773263-27DC-4E83-9C6A-ED2B73DC3F0A/system.log'
Error code 1 for command: ios-sim with args:
launch,/Users/sh/Desktop/shapp/platforms/ios/build/emulator/shapp.app,--devicetypeid,com.apple.CoreSimulator.SimDeviceType.iPhone-5s,--stderr,/Users/sh/Desktop/shapp/platforms/ios/cordova/console.log,--stdout,/Users/sh/Desktop/shapp/platforms/ios/cordova/console.log,--exit
Error: /Users/sh/Desktop/shapp/platforms/ios/cordova/run: Command
failed with exit code 2
SHs-iMac:shapp sh$ q
-bash: q: command not found
</code></pre>
<p>Not sure what I did wrong as I added and built ios correctly. </p>
<p>It also worked correctly when pulled up in xcode although there are these warnings for both running with <a href="http://i.stack.imgur.com/xvuIP.png" rel="nofollow">5s and 6</a>. I think it is an ionic issue not being able to emulate ios just not sure how to fix it?</p> | 1 |
How to get a list of downloads using the Chrome.downloads api? | <p>I've created an extension and I want it to list all of the downloads in the user's downloads folder on a page rather than just opening the download folder.</p>
<p>This is my code:</p>
<pre><code>window.onload = function(){
var maxNumOfEntries = 100;
for(i = 0; i < maxNumOfEntries; i++){
para = document.createElement('p');
para.setAttribute("id", ("download" + i));
var node = document.createTextNode("");
para.appendChild(node);
var element = document.getElementById("content");
var child = document.getElementById("stuff");
element.insertBefore(para,child);
}
var num = 0;
var currentTime = new Date().getTime();
chrome.downloads.search({text: '', limit: 100}, function(data) {
data.forEach(function(DownloadItem) {
document.getElementById('download' + num).innerHTML = DownloadItem.filename;
num++;
});
});
}
</code></pre>
<p>I've tried various other methods but I just can't seem to get the downloads to appear, any advice?</p> | 1 |
How to make popup form insert data to database? | <p>I tried to make a popup form and use this form to insert data into a database.
This popup form works well, but it does not insert the information to the database. I don't know what wrong with it. Please help me.</p>
<p><a href="https://i.stack.imgur.com/SSOMc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSOMc.jpg" alt="database structure"></a></p>
<p>Here is my code:</p>
<p>HTML code:</p>
<pre><code><a href="#popupLogin" data-rel="popup" data-position-to="window" data-transition="pop">
<p align = 'center'><img src='image/add.png'></p>
</a>
<div data-role="popup" id="popupLogin" data-theme="a" class="ui-corner-all">
<form action="popup.php" method="post">
<div style="padding:10px 20px;">
<h3>ADD INFO</h3>
<label for='mail' class='ui-hidden-accessible'>Mail:</label>
<input name='mail' id='mail' value='' placeholder='Mail' data-theme='a' type='text'>
<label for='username' class='ui-hidden-accessible'>Username:</label>
<input name='username' id='username' value='' placeholder='Username' data-theme='a' type='text'>
<label for='password' class='ui-hidden-accessible'>Password:</label>
<input name='password' id='password' value='' placeholder='Password' data-theme='a' type='text'>
<button type="submit" name="Submit">ADD INFO</button>
</div>
</form>
</code></pre>
<p></p>
<p>PHP code:</p>
<pre><code> $db= mysql_connect("localhost","root","");
if(!$db)
{
echo "CAN'T CONNECT DATABASE";
exit;
}
$db_selected = mysql_select_db("sctv_data2",$db);
if(!$db_selected)
{
die("CAN'T USE THIS DATABASE: ".mysql_error());
}
if($_POST["mail"] !="" && $_POST["username"] != "" && $_POST["password"] !="" )
{
$mail = $_POST["mail"];
$username = $_POST["username"];
$password = $_POST["password"];
$sql = "INSERT INTO `login` VALUES ( '$mail','$username','$password')";
$result = mysql_query($sql,$db);
}
</code></pre> | 1 |
Execution Failed for task ':app:processDebugResources' | <p>I am getting this error from <code>build-tools\23.0.2\ (Aapt.exe)</code> </p>
<blockquote>
<p>finished with non zero exit value 1.</p>
</blockquote>
<p>I am using <code>Android Studio Version 1.4.1</code></p>
<p>I am using the <code>API level 23</code> with the updated build tools, and my log cat is often meaning out the <code>string.xml</code> where I created my strings to refer it for the list view.</p>
<blockquote>
<p>Executing tasks: [:app:generateDebugSources,
:app:generateDebugAndroidTestSources, :app:compileDebugSources,
:app:compileDebugAndroidTestSources, :mylibrary:generateDebugSources,
:mylibrary:generateDebugAndroidTestSources,
:mylibrary:compileDebugSources,
:mylibrary:compileDebugAndroidTestSources]</p>
<p>Configuration on demand is an incubating feature. :app:preBuild
UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2311Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig
UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets
UP-TO-DATE :app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE :app:mergeDebugResources
UP-TO-DATE :app:processDebugManifest UP-TO-DATE
:app:processDebugResources AGPBI: { "kind":"error","text":"Apostrophe
not preceded by \ ( in ithin the lifecycle callback methods, you can
declare how your activity behaves when the user leaves and re-enters
the activity. For example, if you\u0027re building a streaming video
player, you might pause the video and terminate the network connection
when the user switches to another app. When the user returns, you can
reconnect to the network and allow the user to resume the video from
the same spot. )", "sources":[
{"file":"C:\Users\PreciseT3\AndroidStudioProjects\ListviewApp1\app\src\main\res\values\strings.xml","position":
{ "startLine":1}}],"original":""}</p>
<p>FAILED</p>
<p>FAILURE: Build failed with an exception.</p>
<ul>
<li><p>What went wrong: Execution failed for task ':app:processDebugResources'.</p>
<blockquote>
<p>com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
'C:\Users\PreciseT3\AppData\Local\Android\sdk\build-tools\23.0.2\aapt.exe''
finished with non-zero exit value 1</p>
</blockquote></li>
<li><p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.</p></li>
</ul>
<p>BUILD FAILED</p>
<p>Total time: 12.649 secs</p>
</blockquote> | 1 |
How to remove time from datetime column in dataset? | <p>I have to export data to excel sheet in asp.net c# application. Now I have wriiten below lines of code </p>
<pre><code> DataTable dt = new DataTable();
dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
row["ExpiryDate"] = Convert.ToDateTime(row["ExpiryDate"]).ToShortDateString();
}
DataSet dsn = new DataSet();
DataTable dtcopy = dt.Clone();
dsn.Tables.Add(dtcopy);
WebUtility.GenrateExcel(ds, "ExpiredDocuments");
</code></pre>
<p>I want to first remove time from data set's Expiry date column and then pass
it to the generate Excel function so that time will not appear in Expiry date column in excel... Please help the above code is not working...</p> | 1 |
JavaFx textfield.setText() method not working | <p>JavaFx textfield.setText() method not working when called from another thread,I am calling recieved() method from another thread.but I am not able to set the text,to the text field so I used platform.runlater but it is not working.</p>
<p>DepartmentsController is my controller class which has recieved method that is called from another thread (kryonet thread-Kryonet a high level networking library).</p>
<pre><code>import com.MyCompany.Modal.DepartmentModal;
import com.MyCompany.Network.ClientMaster;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.FadeTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
public class DepartmentsController implements Initializable {
private DepartmentModal departmentModal;
@FXML
Button btn;
@FXML
VBox vBox;
@FXML
ComboBox departmentNameComboBox;
@FXML
TextField departmentNameTF;
@FXML
TextField departmentIdTF;
@FXML
TextField noOfBatchTF;
Main main;
public void customInitialize()//initialize from controllers
{ departmentModal.setRequestData(true);
ClientMaster.NETWORK_MANAGER.client.sendTCP(departmentModal);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
departmentModal=new DepartmentModal();
//String string = new StringBuilder("abcd").append(23).append(false).append("xyz").toString();
TranslateTransition tt = new TranslateTransition(Duration.millis(700),btn);
tt.setFromX(-100);
tt.setToX(0f);
tt.setCycleCount((int) 1f);
tt.setAutoReverse(false);
tt.play();
FadeTransition ft = new FadeTransition(Duration.millis(1000), vBox);
ft.setFromValue(0);
ft.setToValue(1.0);
ft.play();
}
public void initiate(Main main)
{
this.main=main;
}
public void backBtnOnClick()
{
main.controllers.dashBoardController.Initiate(main);
System.out.println("clicked");
}
public void saveBtnOnClick()
{
}
public void clearBtnOnClick()
{
}
public void recieved(DepartmentModal departmentModal)
{
if(departmentModal.isRequestData()==true)
{
Platform.runLater(new Runnable() {
@Override
public void run() {
System.out.println(departmentModal.getDepartmentId());
departmentIdTF.setText(departmentModal.getDepartmentId());//cannot set this field
}
});
}
}
}
</code></pre>
<p>I have main class that is starting of javafx applicaiton that initialize controllers class that contain all controllers of my javafx application</p>
<pre><code>import com.MyCompany.Network.ClientMaster;
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author shersha
*/
public class Main extends Application {
public Controllers controllers;
@Override
public void start(Stage stage) throws Exception {
controllers=new Controllers();
new StaticClass(stage);
new ClientMaster(this);
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
StaticClass.stage.setX(bounds.getMinX());
StaticClass.stage.setY(bounds.getMinY());
StaticClass.stage.setWidth(bounds.getWidth());
StaticClass.stage.setHeight(bounds.getHeight());
controllers.loginController.initialize(this);
Scene scene = new Scene(controllers.loginLoader.getRoot());
scene.getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
/*FadeTransition ft = new FadeTransition(Duration.millis(2000), controllers.loginLoader.getRoot());
ft.setFromValue(0.5);
ft.setToValue(1.0);
ft.play();*/
/* TranslateTransition tt = new TranslateTransition(Duration.millis(2000), controllers.loginLoader.getRoot());
tt.setByX(200f);
tt.setCycleCount((int) 4f);
tt.setAutoReverse(true);
tt.play();*/
ScaleTransition st = new ScaleTransition(Duration.millis(1000), controllers.loginLoader.getRoot());
st.setFromX(1.5f);
st.setFromY(1.5f);
st.setToX(1f);
st.setToY(1f);
st.setCycleCount((int) 1f);
st.setAutoReverse(true);
st.play();
StaticClass.stage.setFullScreen(true);
StaticClass.stage.setScene(scene);
StaticClass.stage.setFullScreenExitHint("");
//StaticClass.stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
StaticClass.stage.show();
/*
StaticClass.stage.setScene(StaticClass.LOGIN_SCENE);
StaticClass.stage.setFullScreen(true);
StaticClass.stage.setFullScreenExitHint("");
StaticClass.stage.show();
*/
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p>Controllers class create reference departmentscontroller so that i can access it from any controller like</p>
<pre><code>main.controllers.departmentcontroller
import javafx.fxml.FXMLLoader;
/**
*
* @author Shersha
*/
public class Controllers {
public LoginController loginController;
public DepartmentsController departmentsController;
public DashBoardController dashBoardController;
public SchemeDepartmentController schemeDepartmentController;
public StaffsController staffsController;
public SchemesController schemesController;
public SubjectsController subjectsController;
public StudentsController studentsController;
public StaffManagementController staffManagementController;
public StudentManagementController studentManagementController;
FXMLLoader staffManagementLoader,studentManagementLoader,subjectsLoader,studentsLoader,loginLoader,dashBoardLoader,schemesLoader,departmentsLoader,schemeDepartmentLoader,staffsLoader;
public Controllers() throws Exception
{
loginLoader= new FXMLLoader();
loginLoader.setLocation(getClass().getResource("Login.fxml"));
loginLoader.load();
loginController= loginLoader.getController();
dashBoardController= new DashBoardController();
schemesLoader= new FXMLLoader();
schemesLoader.setLocation(getClass().getResource("Schemes.fxml"));
schemesLoader.load();
schemesController= schemesLoader.getController();
departmentsLoader= new FXMLLoader();
departmentsLoader.setLocation(getClass().getResource("Departments.fxml"));
departmentsLoader.load();
departmentsController=departmentsLoader.getController();
schemeDepartmentLoader= new FXMLLoader();
schemeDepartmentLoader.setLocation(getClass().getResource("SchemeDepartment.fxml"));
schemeDepartmentLoader.load();
schemeDepartmentController=schemeDepartmentLoader.getController();
staffsLoader= new FXMLLoader();
staffsLoader.setLocation(getClass().getResource("Staffs.fxml"));
staffsLoader.load();
staffsController=staffsLoader.getController();
subjectsLoader= new FXMLLoader();
subjectsLoader.setLocation(getClass().getResource("Subjects.fxml"));
subjectsLoader.load();
subjectsController=subjectsLoader.getController();
studentsLoader= new FXMLLoader();
studentsLoader.setLocation(getClass().getResource("Students.fxml"));
studentsLoader.load();
studentsController=studentsLoader.getController();
staffManagementLoader= new FXMLLoader();
staffManagementLoader.setLocation(getClass().getResource("StaffManagement.fxml"));
staffManagementLoader.load();
staffManagementController=staffManagementLoader.getController();
studentManagementLoader= new FXMLLoader();
studentManagementLoader.setLocation(getClass().getResource("StudentManagement.fxml"));
studentManagementLoader.load();
studentManagementController=studentManagementLoader.getController();
}
public void initialize()
{
departmentsController.customInitialize();
}
}
</code></pre>
<p>NetworkManager(kryonet thread) is the class that calls recive method in departmentscontroller</p>
<pre><code>import com.MyCompany.Modal.DepartmentModal;
import com.MyCompany.Modal.LoginModal;
import com.MyCompany.Modal.SchemeModal;
import com.MyCompany.attendanceMaster.StaticClass;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import java.io.IOException;
import com.MyCompany.attendanceMaster.Main;
/**
*
* @author shersha
*/
public class NetworkManager extends Listener{
String ip = "localhost";
public Client client;
int port = 27960;
Main main;
RegisterClasses registerClasses;
public NetworkManager(Main main)
{
this.main=main;
}
public void connect(){
client = new Client();
registerClasses=new RegisterClasses(client);
client.addListener(this);
client.start();
try {
client.connect(5000, ip, port, port);
} catch (IOException e) {
e.printStackTrace();
System.out.println("server offline");
}
}
public void received(Connection c, Object o){
if(o instanceof LoginModal){
LoginModal loginModal=(LoginModal)o;
main.controllers.loginController.recieved(loginModal);
}
else if(o instanceof SchemeModal)
{
SchemeModal schemeModal=(SchemeModal)o;
main.controllers.schemesController.recieved(schemeModal);
}
else if(o instanceof DepartmentModal)
{
System.out.println("point 1");
DepartmentModal departmentModal=(DepartmentModal)o;
main.controllers.departmentsController.recieved(departmentModal);
}
}
}
</code></pre>
<p>I have one more class called dashboard controller that puts all fxml element to the stage</p>
<pre><code>public class DashBoardController implements Initializable {
SchemesController schemesController;
Main main;
ToggleButton[] tb,tb2;
Parent root ;
ImageView iv0,iva0,iv1,iva1,iv2,iva2,iv3,iva3,iv4,iva4,iv5,iva5,iv6,iva6,iv7,iva7;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println("one time");
public void Initiate(Main main)
{
this.main=main;
// tb=new ToggleButton[8];
tb2=new ToggleButton[8];
VBox up = new VBox(20);
Text text4flow = new Text("Basic");
text4flow.setFont(Font.font("Calibri", FontWeight.BOLD, 30));
text4flow.setFill(Color.WHITE);
text4flow.setUnderline(false);
VBox.setMargin(text4flow, new Insets(10, 0, 0, 10));
//creating Flow Pane
up.setPadding(new Insets(50, 50, 50, 50));
FlowPane flowpane = new FlowPane();
flowpane.setHgap(10);
flowpane.setVgap(10);
flowpane.getChildren().add(tb[1]);
tb[1].addEventHandler(MouseEvent.MOUSE_ENTERED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
tb[1].setSelected(true);
tb[1].setGraphic(iva1);
}
});
tb[1].addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>() {
private Effect shadow;
@Override public void handle(MouseEvent e) {
tb[1].setGraphic(iv1);
}
});
tb[1].setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
tb[1].setGraphic(iva1);
try {
System.out.println("kk");
FXMLLoader loader= new FXMLLoader();
loader.setLocation(getClass().getResource("Departments.fxml"));
Pane screen = (Pane) loader.load();
main.controllers.departmentsController=loader.getController();
main.controllers.departmentsController.initiate(main);
StaticClass.stage.setFullScreen(true);
/* FadeTransition ft = new FadeTransition(Duration.millis(1000), screen);
ft.setFromValue(0.7);
ft.setToValue(1.0);
ft.play();*/
StaticClass.stage.getScene().setRoot(screen);
StaticClass.stage.getScene().getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
StaticClass.stage.show();
//Execute some code here for the event..
} catch (IOException ex) {
Logger.getLogger(DashBoardController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
StaticClass.stage.getScene().setRoot(up);
StaticClass.stage.getScene().getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
StaticClass.stage.show();
}
}
</code></pre> | 1 |
$(document).ready(function()) is not working in jsp | <p><code>$(document).ready(function())</code> is not working in my jsp.I have tried in many forms.</p>
<p>My code is:</p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="scripts/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Success</title>
<script type="text/javascript" src="js/jquery/jquery.js"></script>
<script type="text/javascript" src="js/jquery/jquerymin.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
alert("Hiiii");
});
</script>
</head>
<body>
</body>
</html>
</code></pre> | 1 |
How to get the max value from a column with alphanumeric strings? | <p>I have a table which contains invoice and estimate numbers.The invoice numbers are like <code>"IN1000","IN1001","IN1002"</code> and so on.The estimate numbers are like <code>"ES101","ES102","ES103"</code>.How can I get the max of both my invoice and estimate? I would also like it to be cast into an integer like 1000.</p>
<p>I have tried the following query:</p>
<pre><code>SELECT Max(CAST (SUBSTR(invoiceNo,3) AS UNSIGNED)) FROM selected_items
WHERE invoiceNo RLIKE 'IN';
</code></pre>
<p>When I run this query I get the following error :</p>
<blockquote>
<p>#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'UNSIGNED)) FROM selected_items WHERE invoiceNo RLIKE 'IN'' at
line 1.</p>
</blockquote>
<p>And I am using similar approach for estimate :</p>
<pre><code>SELECT Max(CAST (SUBSTR(invoiceNo,3) AS UNSIGNED)) FROM selected_items
WHERE invoiceNo RLIKE 'ES';
</code></pre>
<p>How can I do both the operations in one query? Any help is appreciated.Thank you.</p> | 1 |
How to get URL from an IP address in Java? | <p>I found code to fetch host name from IP address. The code is some what like shown below:</p>
<pre><code>import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetHostName{
public static void main(String a[]){
try{
InetAddress host = InetAddress.getByName("74.125.68.94");
System.out.println(host.getHostName());
}
catch(UnknownHostException ex){
ex.printStackTrace();
}
}
}
</code></pre>
<p>It shows output like:</p>
<pre><code>sc-in-f94.1e100.net
</code></pre>
<p>But when i fired this IP address (74.125.68.94) through the browser it opens up Google website.
So my question is how can i fecth URL like <a href="http://www.google.com" rel="nofollow">http://www.google.com</a> from an IP address rather than displaying <strong>sc-in-f94.1e100.net</strong> using java?</p> | 1 |
bootstrap not working with chrome (firefox and ie work fine) | <p>I have a basic website I'm building to learn Bootstrap. On firefox and ie 11, the website works as expected. The grid system works and the navigation collapses and toggles the hamburger icon as expected.</p>
<p>On chrome the navigation starts a little under 992px to go cover the right links and it doesn't collapse/toggle the hamburger icon.</p>
<p>Why is it not working on chrome?</p>
<p>So far I have this as my code, thank you in advance:</p>
<pre><code><!doctype html>
<head>
<meta charset="utf-8">
<title>Testing Bootstrp</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<div class='navbar navbar-default navbar-fixed-top'>
<div class='container'>
<div class='navbar-header'>
<a href='#' class='navbar-brand'>
WELCOME TO MY WORLD
</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
</div>
<ul class='nav navbar-nav navbar-right collapse navbar-collapse'>
<li><a href="#">HOME</a></li>
<li><a href="#">Testimonails</a></li>
<li><a href="#">Insurance</a></li>
</ul>
</div>
</div>
</code></pre>
<p></p>
<p>Here is main.css, not much going on.</p>
<pre><code>.features .glyphicon {
font-size: 32px;
color: purple;
}
body {
padding-top: 70px;
}
</code></pre>
<p><a href="http://i.stack.imgur.com/2GUOC.jpg" rel="nofollow">996px</a></p>
<p><a href="http://i.stack.imgur.com/fOpxx.jpg" rel="nofollow">It starts to break here, the grid stops adapting under the 991 mark</a></p> | 1 |
Codepush React-Native android staging release | <p>I am trying to release the React-Native Android application using Microsoft's Codepush on staging for this have followed the given instruction on website and able to build the bundle file and release successfully on staging but didn't see the updated changes on mobile which I released.</p>
<p>Firstly I installed the application on mobile using usb (Run on device).</p>
<p>After that make some changes in application and release on staging using Codepush but when I am restarting the app on mobile is not showing the changes. </p>
<p><a href="https://github.com/Microsoft/react-native-code-push#getting-started" rel="nofollow">https://github.com/Microsoft/react-native-code-push#getting-started</a>
Android Setup</p>
<p>app/build.gradle :-</p>
<pre><code>defaultConfig : versionName: "1.0.0",
signingConfigs : release { storeFile file("my-release-key.keystore")
storePassword "myapp"
keyAlias "alias-key"
keyPassword "myapp"
}
buildTypes: signingConfig signingConfigs.release
dependencies: compile project(':react-native-code-push')
</code></pre>
<p>setting.gradle :-</p>
<pre><code>include ':app', ':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')
</code></pre>
<p>CLI command :- </p>
<pre><code>react-native bundle --platform android --entry-file index.android.js --bundle-output codepush.js --dev false;
code-push release App-Android codepush.js 1.0.0
</code></pre>
<p>I have installed the aap on mobile with versionName 1.0.0 and make some changes in application code and again build the bundle and release the app with version name 1.0.1.</p>
<p>Here I am not changing versionName in <code>buid.gradle</code> only changing the versionName in release command <code>code-push release App-Android codepush.js 1.0.1</code></p>
<p>Should I need to change the versionName every time in <code>build.gradle</code> for new release and use the same in release command?</p>
<p>Can any one help please?
Thanks</p> | 1 |
Git interactive rebase of another branch on current branch but NOT onto HEAD | <p>I was wondering if there was a way to do an interactive rebase from one branch onto the current branch but not onto the head. Kind of like combination of <code>git rebase -i otherbranch</code> and <code>git rebase -i HEAD~2</code>.</p>
<p>What I want to do is be presented with an interactive rebase file where i can arrange not only the commits from the remote branch but also a range of commits on the current branch beginning from the head.</p>
<p>The scenario I have is:</p>
<ul>
<li>i have feature branch B1</li>
<li>while waiting for code review I started a new feature by branching from B1. The new branch is B2</li>
<li>code review finally happened and I had to fix something in B1</li>
<li>changes are applied to B1 by way of an amend (not a new commit)</li>
</ul>
<p>Now I need to update B2 with the revised commit from B1. I want the revised the commit to replace the original commit.</p>
<p>Simply rebasing B1 into B2 will result in the original and the revised commit appearing in B2's history (and there will probably be some nasty merge conflicts).</p>
<p>If I could get the B1 unique commits and a range of B2's commits in the interactive rebase prompt then i can tell git to discard the old version of the commit and use the new one from B1 in it's place all in one operation.</p>
<p>So it might look something like: <code>git rebase -i B1 HEAD~2</code></p>
<p>Currently I do this by branching B1 into <code>temp</code> then cherry-picking the new commit from B2 onto it, erase B2 then move temp to B2. Which is fine I guess... but if i could do it as part of a rebase it would be nicer (i think).</p> | 1 |
$interval not working when set in AngularJS Controller | <p>I've checked out other questions on here and they didn't have the answer.</p>
<p>I have the following: (excerpt)</p>
<pre><code> ...
$scope.direction = 'left';
$scope.currentSlideIndex = 0;
$scope.nextSlide = function () {
$scope.direction = 'left';
$scope.currentSlideIndex = ($scope.currentSlideIndex < $scope.slides.length - 1) ? ++$scope.currentSlideIndex : 0;
};
$interval($scope.nextSlide, 4000);
...
</code></pre>
<p>and nothing happens. I've injected $interval. No Console error messages. I know the function itself works since when it gets called with ng-click, it works fine.</p>
<p>Potential issue: I have a newsfeed scrolling on the same page. Could the underlying interval of that newsfeed be killing this one? That's getting its movement from an outside script and I'm having a hard time nailing it down to stop it to check.</p> | 1 |
Maven doesn't find last version of a dependency | <p>I have to include <strong>fixedformat4j-root</strong> dependency in my pom.xml.
I get artifact info (group, version, ...) from the pom.xml of the project homepage:</p>
<p><a href="https://github.com/jeyben/fixedformat4j/blob/master/pom.xml" rel="nofollow">https://github.com/jeyben/fixedformat4j/blob/master/pom.xml</a></p>
<p>When I store that info to my pom.xml, I got this error from m2e eclipse plugin:</p>
<blockquote>
<p>Missing artifact
com.ancientprogramming.fixedformat4j:fixedformat4j-root:jar:1.4.0-SNAPSHOT</p>
</blockquote>
<p>This is my pom.xml</p>
<pre><code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
...
<dependencies>
...
<dependency>
<groupId>com.ancientprogramming.fixedformat4j</groupId>
<artifactId>fixedformat4j-root</artifactId>
<version>1.4.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>bintray</id>
<url>http://jcenter.bintray.com</url>
</repository>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<build>
...
</build>
<reporting>
...
</reporting>
</project>
</code></pre>
<p>How can I solve this error? Should I set a new repository? Where can I find the repository url from the project pom.xml?</p> | 1 |
Estimating the Standard Deviation of a ratio using Taylor expansion | <p>I am interested to build a R function that I can use to test the limits of the Taylor series approximation. I am aware that there is limits to what I am doing, but it's exactly those limits I wish to investigate.</p>
<p>I have two normally distributed random variables <code>x</code> and <code>y</code>. <code>x</code> has a mean of 7 and a standard deviation (sd) of 1. <code>y</code> has a mean of 5 and a sd of 4.</p>
<pre><code>me.x <- 4; sd.x <- 1
me.y <- 5; sd.y <- 4
</code></pre>
<p>I know how to estimate the mean ratio of <code>y/x</code>, like this </p>
<pre><code># E(y/x) = E(y)/E(x) - Cov(y,x)/E(x)^2 + Var(x)*E(y)/E(x)^3
me.y/me.x - 0/me.x^2 + sd.x*me.y/me.x^3
[1] 1.328125
</code></pre>
<p>I am however stuck on how to estimate the Standard Deviation of the ratio? I realize I have to use a Taylor expansion, but not how to use it. </p>
<p>Doing a simple simulation I get </p>
<pre><code> x <- rnorm(10^4, mean = 4, sd = 1); y <- rnorm(10^4, mean = 5, sd = 4)
sd(y/x)
[1] 2.027593
mean(y/x)[1]
1.362142
</code></pre> | 1 |
Restrict area for draw image object in canvas HTML5 | <p>I want to restrict the area that an image can be drawn on a canvas. I am using Fabric.js.</p>
<p>I tried the following link, but it didn't work for me. <a href="https://stackoverflow.com/questions/19979644/set-object-drag-limit-in-fabric-js">Set object drag limit in Fabric.js</a>.</p>
<p>I want any part of the image that would be drawn outside the red rectangle (pictured below) to just not be drawn.<a href="https://i.stack.imgur.com/YxVct.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YxVct.png" alt="enter image description here"></a></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-js lang-js prettyprint-override"><code>var canvas = new fabric.Canvas('canvas');
$("#canvascolor > input").click(function() {
canvas.setBackgroundImage(this.src, canvas.renderAll.bind(canvas), {
crossOrigin: 'anonymous'
});
});
// trigger the first one at startup
$("#canvascolor > input:first-of-type()")[0].click();
document.getElementById('file').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
console.log("reader " + reader);
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 140,
top: 100,
width: 250,
height: 200,
angle: 0
}).scale(0.9);
oImg.lockMovementX = true;
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function(e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> canvas {
border: 1px solid black;
}
#canvascolor input {
height: 50px;
width: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="520" height="520"></canvas>
<section id="canvascolor">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/9leyl96qd3tytn8/tshirt-front.jpg">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/tk0fs5v4muo6898/tshirt-back.jpg">
</section>
<button href='' id='txt' target="_blank">submit</button><br/>
<img id="preview" /></code></pre>
</div>
</div>
</p> | 1 |
Radial Profile from a .fits image | <p>I have been trying to plot a radial profile of a fits image using a modified script I found on-line. I always get y axis units which are completely different to what's expected. I'm not even sure what the y axis units are. I have attached the fits file and a profile I keep getting and the correct radial profile I plotted using another program. </p>
<p>I am very new to python so I have no idea why this keeps happening. Any help to fix this will be so greatly appreciated. </p>
<p>This is the code I've been using: </p>
<pre><code>import numpy as np
import pyfits
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def azimuthalAverage(image, center=None):
"""
Calculate the azimuthally averaged radial profile.
image - The 2D image
center - The [x,y] pixel coordinates used as the center. The default is
None, which then uses the center of the image (including
fracitonal pixels).
"""
# Calculate the indices from the image
y, x = np.indices(image.shape)
if not center:
center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0])
r = np.hypot(x - center[0], y - center[1])
# Get sorted radii
ind = np.argsort(r.flat)
r_sorted = r.flat[ind]
i_sorted = image.flat[ind]
# Get the integer part of the radii (bin size = 1)
r_int = r_sorted.astype(int)
# Find all pixels that fall within each radial bin.
deltar = r_int[1:] - r_int[:-1] # Assumes all radii represented
rind = np.where(deltar)[1] # location of changed radius
nr = rind[1:] - rind[:-1] # number of radius bin
# Cumulative sum to figure out sums for each radius bin
csim = np.cumsum(i_sorted, dtype=float)
tbin = csim[rind[1:]] - csim[rind[:-1]]
radial_prof = tbin / nr
print center
print i_sorted
print radial_prof
return radial_prof
#read in image
hdulist = pyfits.open('cit6ndf2fitsexample.fits')
scidata = np.array(hdulist[0].data)[0,:,:]
center = None
radi = 10
rad = azimuthalAverage(scidata, center)
plt.xlabel('radius(pixels?)', fontsize=12)
plt.ylabel('image intensity', fontsize=12)
plt.xlim(0,10)
plt.ylim(0, 3.2)
plt.plot(rad[radi:])
plt.savefig('testfig1.png')
plt.show()
</code></pre>
<p>Profile with wrong y axis units</p>
<p><a href="https://i.stack.imgur.com/kgJk9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kgJk9.png" alt="enter image description here"></a></p>
<p>Profile with expected correct units created using Celtech Aperture Photometry Tool. </p>
<p><a href="https://i.stack.imgur.com/RFyZi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RFyZi.png" alt="enter image description here"></a></p> | 1 |
What could be the cause for runtime "can't find linker symbol for virtual table..." error in Qt? | <p>This question was asked in similar ways multiple times, for example at <a href="https://stackoverflow.com/questions/33544120/memory-violation-sigsegv-and-cant-find-linker-symbol-for-virtual-table">stackoverflow</a> or <a href="http://forum.qt.io/topic/4457/can-t-find-linker-symbol-for-virtual-table/12" rel="nofollow noreferrer">forum.qt.io</a> or <a href="http://www.qtcentre.org/threads/50592-can-t-find-linker-symbol-for-virtual-table-for-QString-Data-value" rel="nofollow noreferrer">qtcentre.org</a>. The problem is that this error message is so vague that one solution cannot be applied to another scenario. Most of the threads are dead in the middle of the discussion though :-(</p>
<p>So the complete error message that I get in my Qt application is:</p>
<p><strong>can't find linker symbol for virtual table for "OneOfMyClasses" <br>value
found "QString::shared_null" instead</strong></p>
<p>The <em>OneOfMyClasses</em> changes depending on various things, the <em>QString::shared_null</em> stays the same for all errors that I get. Here is a screenshot of my logging console:</p>
<p><a href="https://i.stack.imgur.com/0wyZQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0wyZQ.png" alt="enter image description here"></a></p>
<ol>
<li>Why is the font color pink, so who is printing this message?</li>
<li>Why do I only see this message when I set a breakpoint and step through my code? This message does not appear when simply running the application.</li>
</ol>
<p>The point where it happens is in this function in the source line right before the current position (yellow arrow):</p>
<p><a href="https://i.stack.imgur.com/DYUbo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DYUbo.png" alt="enter image description here"></a></p>
<p>So according to the message I stepped into <code>m_pStateWidget->insertNavLabel(...)</code> and the error message is printed somewhere in the constructors inside Qt related to the QString class. So I tried the following, which moves the problem away from this code location:</p>
<p><a href="https://i.stack.imgur.com/kRObG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kRObG.png" alt="enter image description here"></a></p>
<p>When doing this I get the same error message a few code lines below with another class name in the message, note that the <em>QString::shared_null</em> stays the same.</p>
<p>It appears to me that I have some sort of corrupted memory.</p>
<ol start="3">
<li>How should I start investigating this issue? I'm afraid to change the code because this might hide the problem as described above.</li>
<li>What's up with the QString::shared_null? I have found that others often see the same in their error messages.</li>
</ol>
<p>Thank you for any hint or help! :-)</p>
<p><strong>Edit</strong>: It's becoming really interesting now. I have stepped into every single function just right before the message is printed and I ended up with these error messages:</p>
<p><a href="https://i.stack.imgur.com/LTyW8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LTyW8.png" alt="enter image description here"></a></p>
<p>at this location:</p>
<p><a href="https://i.stack.imgur.com/MCl2N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCl2N.png" alt="enter image description here"></a></p>
<p>When I navigate through the call stack in QtCreator the error is printed again and again everytime I select another function in the stack.</p>
<ol start="5">
<li>Does this mean that the debugger is printing the message and that it is simply too stupid to resolve some sort of vtable stuff for me or does this mean that I have serious trouble going on?</li>
</ol> | 1 |
What are unevaluated contexts in C++? | <p>One example that frequently comes to mind is :</p>
<p><code>sizeof</code> expression, where it doesn't evaluates the expression but determines the size by static type. For example :</p>
<pre><code>int func();
sizeof(func());
</code></pre>
<p>This is my limit of thinking, so if there are other unevaluated contexts, then what are they?</p> | 1 |
Swift vs Python Performance | <p>I have some code in Python that builds a dictionary of about 250K strings (words) as keys with each value having an array of strings. The Python version runs in about 0.5 seconds. I needed to port this to Swift but my Swift port runs in 10.1 seconds, 20 times slower.</p>
<p>Here is the Python code:</p>
<pre><code>wordsDictionary = defaultdict(list)
for word in words:
wordsDictionary[sort_string(word)].append(word)
</code></pre>
<p>And here is the Swift code:</p>
<pre><code>var wordsDictionary : Dictionary<String, [String]> = Dictionary()
for word in words {
let sortedWord : String = String(word.characters.sort())
if wordsDictionary[sortedWord] == nil {
wordsDictionary[sortedWord] = []
}
wordsDictionary[sortedWord]?.append(word)
}
</code></pre>
<p>Is there any way to speed up the Swift version or are Swift dictionaries still that much slower than Python?</p> | 1 |
Go map vs C# Dictionary | <p>I wrote a quick and dirty test to check the performance of Go vs C# in the area of concurrent lookup access and was surprised by the results.</p>
<p>It's a very trivial example and I'm no Go expert but the test is simply to perform 1,000,000 lock/check/add/unlock operations on a map, it's only single-threaded because I'm checking just these functions:</p>
<pre><code>package main
import (
"fmt"
"sync"
"time"
)
var mu sync.Mutex
func main() {
cache := make(map[int]int, 1000000)
start := time.Now()
for i := 0; i < 1000000; i++ {
mu.Lock()
if _, ok := cache[i]; ok == false {
cache[i] = i
}
mu.Unlock()
}
end := time.Since(start)
fmt.Println(end)
var sum int64
for _, v := range cache {
sum += int64(v)
}
fmt.Println(sum)
}
</code></pre>
<p>And the same thing in C# (via LINQPad):</p>
<pre><code>void Main()
{
var cache = new Dictionary<int, int>(1000000);
var sw = Stopwatch.StartNew();
for (var i = 0; i < 1000000; i++)
{
lock (cache)
{
int d;
if (cache.TryGetValue(i, out d) == false)
{
cache.Add(i, i);
}
}
}
$"{sw.ElapsedMilliseconds:N0}ms".Dump();
var sum = 0L;
foreach (var kvp in cache)
{
sum += kvp.Value;
}
sum.Dump();
}
</code></pre>
<p>I sum the elements of both collections to ensure they match up (499,999,500,000) and print the time taken. Here are the results:</p>
<ul>
<li>C#: 56ms</li>
<li>Go: 327ms</li>
</ul>
<p>I've checked that it's not possible to initialise the size of a map, just the capacity, so I'm wondering if there's anything I could do to improve the performance of the Go map?</p>
<p>It takes Go 32ms to perform 1,000,000 lock/unlock operations without the map access.</p> | 1 |
"function call must have a constant value in a constant expression" | <p>I have the following code:</p>
<pre><code>constexpr unsigned long long power_function(const unsigned long long prime, const unsigned long long iterations) {
return iterations > 0 ? prime * power_function(prime, iterations - 1) : prime;
}
/* Inside my Class Definition*/
private:
static constexpr unsigned long long prime = power_function(-363, 1'000'000); //Error occurs here
</code></pre>
<p>IntelliSense complains that <code>power_function</code> is being used incorrectly. But for the life of me, I can't work out what the issue is. I'm using Visual Studio 2015, FYI.</p>
<p>Error messages:</p>
<pre><code>Error C2131 expression did not evaluate to a constant Basic Server c:\<snip> 28
Error C2131 expression did not evaluate to a constant Basic Server c:\<snip> 33
</code></pre>
<p>line 28 corresponds to the line where the return function is, and line 33 corresponds to the line where the constexpr is defined.</p> | 1 |
How to implement atoi using SIMD? | <p>I'd like to try writing an atoi implementation using SIMD instructions, to be included in <a href="http://rapidjson.org/" rel="noreferrer">RapidJSON</a> (a C++ JSON reader/writer library). It currently has some SSE2 and SSE4.2 optimizations in other places.</p>
<p>If it's a speed gain, multiple <code>atoi</code> results can be done in parallel. The strings are originally coming from a buffer of JSON data, so a multi-atoi function will have to do any required swizzling.</p>
<p>The algorithm I came up with is the following:</p>
<ol>
<li>I can initialize a vector of length N in the following fashion:
[10^N..10^1]</li>
<li>I convert each character in the buffer to an integer and place them in another vector.</li>
<li>I take each number in the significant digits vector and multiply it by the matching number in the numbers vector and sum the results. </li>
</ol>
<p>I'm targeting x86 and x86-64 architectures.</p>
<p>I know that AVX2 supports three operand Fused Multiply-Add so I'll be able to perform Sum = Number * Significant Digit + Sum.<br>
That's where I got so far.<br>
Is my algorithm correct? Is there a better way?<br>
Is there a reference implementation for atoi using any SIMD instructions set?</p> | 1 |
How to register a Filter to one @RequestMapping method only? | <p>I registered the following filter for general content logging:</p>
<pre><code>@Bean
public Filter getLoggingFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(5120);
return filter;
}
</code></pre>
<p>This filter catches on any request.</p>
<p>Now I'd like to apply this filter to only one specific <code>@RequestMapping</code> method.</p>
<p>Question: is that possible at all?</p>
<p><strong>Update</strong>: the following filterbean results in a 404 when accessing the path.</p>
<pre><code>@Bean
public FilterRegistrationBean getLoggingFilter() {
FilterRegistrationBean filter = new FilterRegistrationBean(new CommonsRequestLoggingFilter());
filter.addUrlPatterns("/rest/my/specific/method/*");
return filter;
}
</code></pre> | 1 |
Files.exists(path) and path.toFile().exists() give different results for the same file | <p>I'm getting a different result for <code>Files.exists(path)</code> to <code>path.toFile().exists()</code> for a local file on Windows. I can see this file in Windows Explorer although I have (randomly) modified permissions and perhaps the permissions do not make sense.</p>
<p>However this doesn't explain why the old method returns true and the new methods returns false. The file definently exists but maybe it is invisible to the user running the Java code, so I'm not sure what the correct answer should be. Nor can I see how to see which user is running the code, there is only one real user <strong>Paul</strong> on the computer, but I'm wondering if whether if run as administrator or not effects things.</p>
<pre><code>System.out.println("Path Exists(1):"+Files.exists(path));
System.out.println("Path Exist(2) :"+path.toFile().exists());
</code></pre>
<p>gives</p>
<pre><code>Path Exists(1):false
Path Exist(2) :true
</code></pre>
<p>Also</p>
<pre><code>System.out.println("Path readable(3) :"+Files.isReadable(path));
System.out.println("Path readable(4):"+path.toFile().canRead());
</code></pre>
<p>works in same way giving</p>
<pre><code>Path readable(3) :false
Path readable(4):true
</code></pre>
<p>Permissions output</p>
<pre><code>File C:\Code\jthink\opensrc\jaudiotagger\testdata\test157.dsf permissions
owner:PCLAPTOP\Paul
NT AUTHORITY\SYSTEM:READ_DATA/WRITE_DATA/APPEND_DATA/READ_NAMED_ATTRS/WRITE_NAMED_ATTRS/EXECUTE/DELETE_CHILD/READ_ATTRIBUTES/WRITE_ATTRIBUTES/DELETE/READ_ACL/WRITE_ACL/WRITE_OWNER/SYNCHRONIZE:DENY
BUILTIN\Administrators:READ_DATA/WRITE_DATA/APPEND_DATA/READ_NAMED_ATTRS/WRITE_NAMED_ATTRS/EXECUTE/DELETE_CHILD/READ_ATTRIBUTES/WRITE_ATTRIBUTES/DELETE/READ_ACL/WRITE_ACL/WRITE_OWNER/SYNCHRONIZE:DENY
BUILTIN\Administrators:READ_DATA/WRITE_DATA/APPEND_DATA/READ_NAMED_ATTRS/WRITE_NAMED_ATTRS/EXECUTE/DELETE_CHILD/READ_ATTRIBUTES/WRITE_ATTRIBUTES/DELETE/READ_ACL/WRITE_ACL/WRITE_OWNER/SYNCHRONIZE:ALLOW
NT AUTHORITY\SYSTEM:READ_DATA/WRITE_DATA/APPEND_DATA/READ_NAMED_ATTRS/WRITE_NAMED_ATTRS/EXECUTE/DELETE_CHILD/READ_ATTRIBUTES/WRITE_ATTRIBUTES/DELETE/READ_ACL/WRITE_ACL/WRITE_OWNER/SYNCHRONIZE:ALLOW
BUILTIN\Users:READ_DATA/READ_NAMED_ATTRS/EXECUTE/READ_ATTRIBUTES/READ_ACL/SYNCHRONIZE:ALLOW
NT AUTHORITY\Authenticated Users:READ_DATA/WRITE_DATA/APPEND_DATA/READ_NAMED_ATTRS/WRITE_NAMED_ATTRS/EXECUTE/READ_ATTRIBUTES/WRITE_ATTRIBUTES/DELETE/READ_ACL/SYNCHRONIZE:ALLOW
c:\Code\jthink\opensrc\jaudiotagger>attrib C:\Code\jthink\opensrc\jaudiotagger\testdata\test157.dsf
A R C:\Code\jthink\opensrc\jaudiotagger\testdata\test157.dsf
</code></pre>
<p><strong>Update</strong>
I dont have a conclusion but thought this information could be useful.</p>
<p>I was running code in IntelliJ IDE without the IDE <strong><em>Run program as Administrator</em></strong> option enabled, enabling this did then cause the Java application to also get the administrator privileges.</p>
<p>Interesting for another file I didn't add any DENY privileges, I just disabled inherit permissions and remove READ permissions from all groups. Then when I ran as user without run as admin enabled it could not read the file and also this code could not any output any information </p>
<pre><code>AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
if (view != null)
{
sb.append("Owner:"+view.getOwner().getName()+"**");
for (AclEntry acl : view.getAcl())
{
sb.append(acl.principal()+"**");
for(AclEntryPermission aep:acl.permissions())
{
sb.append(aep.toString() + "**");
}
}
}
</code></pre>
<p>but when I run with <strong><em>Run program as adminstrator</em></strong> enabled it still couldnt read the file, but the above code did now output some of the permissions as follows:</p>
<blockquote>
<p>Owner:BUILTIN\Administrators </p>
<p>NT AUTHORITY\SYSTEM:WRITE_DATA/APPEND_DATA/WRITE_NAMED_ATTRS/WRITE_ATTRIBUTES/SYNCHRONIZE:ALLOW
PCLAPTOP\Paul:WRITE_DATA/APPEND_DATA/WRITE_NAMED_ATTRS/WRITE_ATTRIBUTES/SYNCHRONIZE:ALLOW
BUILTIN\Administrators:WRITE_DATA/APPEND_DATA/WRITE_NAMED_ATTRS/WRITE_ATTRIBUTES/SYNCHRONIZE:ALLOW </p>
</blockquote>
<p>as you can see even though <code>Administrators</code> do not have <code>READ</code> or <code>READ PERMISSIONS</code> options they can output the permissions whereas before they couldn't, perhaps due to BUILTIN/Administraor being returned as owner.</p> | 1 |
How to group words whose Levenshtein distance is more than 80 percent in Python | <p>Suppose I have a list:-</p>
<pre><code>person_name = ['zakesh', 'oldman LLC', 'bikash', 'goldman LLC', 'zikash','rakesh']
</code></pre>
<p>I am trying to group the list in such a way so the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Levenshtein distance</a> between two strings is maximum. For finding out the ratio between two words, I am using a python package <a href="https://github.com/seatgeek/fuzzywuzzy" rel="noreferrer">fuzzywuzzy</a>.</p>
<p><strong>Examples :-</strong> </p>
<pre><code>>>> from fuzzywuzzy import fuzz
>>> combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
>>> fuzz.ratio('goldman LLC', 'oldman LLC')
95
>>> fuzz.ratio('rakesh', 'zakesh')
83
>>> fuzz.ratio('bikash', 'zikash')
83
>>>
</code></pre>
<p><strong>My end goal:</strong></p>
<blockquote>
<p>My end goal is to group the words such that Levenshtein distance between them is more than 80 percent?</p>
</blockquote>
<p>My list should look something like this :- </p>
<pre><code>person_name = ['bikash', 'zikash', 'rakesh', 'zakesh', 'goldman LLC', 'oldman LLC'] because the distance between `bikash` and `zikash` is very high so they should be together.
</code></pre>
<p>Code: </p>
<p>I am trying to achieve this by sorting but key function should be <code>fuzz.ratio</code>. Well below code is not working, but I am approaching the problem in this angle.</p>
<pre><code>from fuzzywuzzy import fuzz
combined_list = ['rakesh', 'zakesh', 'bikash', 'zikash', 'goldman LLC', 'oldman LLC']
combined_list.sort(key=lambda x, y: fuzz.ratio(x, y))
print combined_list
</code></pre>
<blockquote>
<p>Could anyone help me to combine the words so that Levenshtein distance between them is more than 80 percent?</p>
</blockquote> | 1 |
in_array() performance optimization | <p>I have the following condition:</p>
<pre><code>if(in_array($needle, $haystack) ||
in_array($needle . "somePostfix", $haystack) ||
in_array($needle . "someOtherPostfix", $haystack) ||
// and some more) {
// do something
}
</code></pre>
<p>My haystack contains more than 10k elements, and this check takes about 400ms. I know that <code>in_array</code> has to iterate over the whole array multiple times. In my case the common case is that the element is not found. and I tried to improve this by creating the following method that only iterates once over the haystack:</p>
<pre><code>function wildcardInArray($needle, $haystack) {
foreach ($haystack as $value) {
if (true === fnmatch($needle . '*', $haystack)) {
return true;
}
}
return false;
}
</code></pre>
<p>But this decreases my performance even more, seems to me that <code>fnmatch</code> is the bottleneck.</p>
<p>Is there any improvement for this case of array search?</p> | 1 |
PHP File_get_contents error in connection | <p>I have a php file and all it contains is</p>
<pre><code><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo file_get_contents("http://mywebsite.com/javascript-function.php");
?>
</code></pre>
<p>And for some reason it displays the following notice:</p>
<pre><code>Notice: file_get_contents(): send of 24 bytes failed with errno=104 Connection reset by peer in /home/sites/mywebsite.com/public_html/index.php on line 6 Notice: file_get_contents(): send of 2 bytes failed with errno=32 Broken pipe in /home/sites/mywebsite.com/public_html/index.php on line 6
</code></pre>
<p>I have never come accross this message before so I have no idea what to do to solve it.</p>
<p>I have also tried using cURL but it outputs nothing and no error message.</p> | 1 |
AWS Lambda function extremely slow to retrieve S3 file | <p>I have a Lambda function that needs to read a file from S3 every time it is executed.<br>
The file is very small, about 200 bytes, the S3 bucket is in the US Standard region, the Lambda function is in the us-east-1 region (so the same region). It takes between 10 and 15 seconds to read the file, how come this is so slow? </p>
<p>Thanks. </p>
<p>EDIT: some code</p>
<pre><code>long start = System.nanoTime();
AmazonS3Client s3Client = new AmazonS3Client();
S3Object propertyFile = null;
try {
propertyFile = s3Client.getObject(S3_BUCKET_NAME, S3_PROPERTY_FILE);
} catch (Exception e) {...}
try (InputStream in = propertyFile.getObjectContent()) {
PROPERTIES.load(in);
} catch (Exception e) {...}
LOGGER.debug("S3 access " + (System.nanoTime() - start));
</code></pre>
<p>EDIT #2: After Brooks' suggestion I did</p>
<pre><code>AmazonS3Client s3Client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
</code></pre>
<p>And I get this error:</p>
<pre><code>Unable to load credentials from Amazon EC2 metadata service
</code></pre>
<p>EDIT #3:<br>
The memory allocated to the Lambda function was 256MB, when I allocate 1024MB, it takes 3-4 seconds which is still too slow (it takes about 1-2 seconds when I test locally from my computer).</p> | 1 |
Selenium Webdriver - findElement atom issue | <p>SELENIUM WEBDRIVER - IE</p>
<p>I'm trying to click on a link by using the following command:</p>
<pre><code>driver.findElement(By.linkText("Previous orders")).click();
</code></pre>
<p>and I'm getting this error ... I could make it work some times but most of the time I get this error, it's intermitent, any ideas?</p>
<pre><code>> Started InternetExplorerDriver server (32-bit)
2.50.0.0
Listening on port 25630
Only local connections are allowed
Exception in thread "main" org.openqa.selenium.WebDriverException: A JavaScript error was encountered executing the findElement atom. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 46 milliseconds
Build info: version: '2.50.1', revision: 'd7fc91b', time: '2016-01-29 19:04:49'
System info: host: 'ABC598-L1BCDL9', ip: 'xxx.xxx.xxx.xxx', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_71'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, pageLoadStrategy=normal, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=11, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:25630/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 9865fcae-fa06-46b5-a621-d8390978c515
*** Element info: {Using=link text, value=Previous orders}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByLinkText(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByLinkText.findElement(By.java:246)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at Test.main(Test.java:27)
</code></pre>
<p>Main Code:</p>
<pre><code>import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.security.UserAndPassword;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test {
public static void main(String[] args) throws InterruptedException {
String cartId = JOptionPane.showInputDialog("Type the Cart ID:");
System.setProperty("webdriver.ie.driver",
"C:\\Users\\USER_ADMIN\\Downloads\\Selenium Webdriver\\IEDriverServer.exe");
DesiredCapabilities returnCapabilities = DesiredCapabilities.internetExplorer();
returnCapabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);
WebDriver driver = new InternetExplorerDriver(returnCapabilities);
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
driver.get("https://k06proxy012.sby.com/procurement/buyondemand/common/enUS/index.html");
driver.findElement(By.linkText("Log in to Buy on demand (Bond)")).click();
login(driver);
// START
driver.findElement(By.linkText("Previous orders")).click();
driver.findElement(By.linkText("Search previous orders")).click();
new Select(driver.findElement(By.id("FIELD1"))).selectByVisibleText("Cart ID");
driver.findElement(By.id("VALUE1")).clear();
driver.findElement(By.id("VALUE1")).sendKeys(cartId);
driver.quit();
}
public static void login(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword("user", "pass"));
}
}
</code></pre> | 1 |
encrypting string in javascript without external library | <p>Basically, what I'd like to do is have a JavaScript function that checks whether you've entered a specific string -- but I don't want that string to be actually visible in the source code. In my mind, it would go something like this:</p>
<pre><code>function checkPass(input) {
if (encrypt(input) === 'OJqqyaQUD4APlZvAg3fvCii8Os9qBr23tlzWwjbw') {
alert('Success');
} else {
alert('Fail');
}
}
function encrypt(input) {
//pass it through some encryption algorithm
}
</code></pre>
<p>How might I accomplish this –– ideally, without any external libraries?</p> | 1 |
Verify static_assert in a unit test | <p>I would like to make sure that a static_assert works as it should in a unit test. That is, if I have a </p>
<pre><code>class MyClass {static_assert(my_type_trait<T>::value, "error"); };
</code></pre>
<p>then in the unit test <code>MyClass<TypeWithTrait> myClass;</code> should 'pass' and <code>MyClass<TypeWithoutTrait> myClass;</code> should 'fail'. </p>
<p>Is it possible to do something like this?</p> | 1 |
How do I enable custom domains for my users? | <p>I am looking to allow my users to use their own domain name to access my web service. </p>
<p>For example if I have a user with a profile at example.com/users/david how can I allow david to use exampledavid.com to access his profile page. </p>
<p>I don't want the users to see example.com in the address bar, but instead for david to see exampledavid.com. </p> | 1 |
Get WindowsPrincipal from UserPrincipal | <p><strong>The goal</strong></p>
<p>I'm writing a class that abstracts various Windows user mechanics. My class knows about the user's account name and domain, if any. I am trying to hydrate a property that indicates whether the user has administrative privilege on either the domain or the local environment that it belongs to.</p>
<p><strong>The problem</strong></p>
<p>The <code>WindowsPrincipal</code> class provides that information via <code>IsInRole</code>, but it's constructor requires a <code>WindowsIdentity</code>, which I can't find a way to establish without a user principal name (UPN). The <code>UserPrincipal.UserPrincipalName</code> property is available for domain users, but null for local users. Is there another way to get a <code>WindowsPrincipal</code> from a <code>UserPrincipal</code>? Alternatively, is there another way to accomplish the goal without it?</p>
<p><strong>The source</strong></p>
<pre><code>using (PrincipalContext principalContext = new PrincipalContext(PrincipalContextType, principalContextName))
{
using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, Name))
{
// Capture additional information from the user principal.
Certificates = userPrincipal.Certificates;
DisplayName = userPrincipal.DisplayName;
UserPrincipalName = userPrincipal.UserPrincipalName;
// This constructor blows up because UserPrincipalName is null for local users.
using (WindowsIdentity windowsIdentity = new WindowsIdentity(UserPrincipalName))
{
// Capture group membership information about the specified user.
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
// Determine if the user has administrative privilege on the domain or local machine.
HasAdministrativePrivilege = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
}
</code></pre>
<p>Thanks in advance.</p> | 1 |
fragment callback using interface | <p>I have an <code>Activity</code> that starts a <code>Fragmen</code>t. Inside that fragment i have an <code>EditText</code>. And when i get the text that the user types there, i want to get that from my <code>Activity</code> with the help of an <code>interface</code>. I'm using <a href="http://developer.android.com/training/basics/fragments/communicating.html" rel="nofollow">this guide</a></p>
<p>On my <code>MainActivity</code> i'm implementing the <code>commentListener interfac</code>e and i've managed to get the result inside the <strong><code>onCommentEntered</code></strong> method. But on <strong><code>doneListener</code></strong>, which is triggered when the user presses a button finishing the activity, i'm getting null.</p>
<p>Obviously <code>onCommentEntered</code> runs after <code>doneListener</code>.</p>
<p>Any suggestions on how to get the result on <code>doneListener</code>?</p>
<pre><code>class MainActivity implements fragment.commentListener{
static String comment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtransaction);
done=(TextView)findViewById(R.id.done_button);
}
// called when user presses a button and MainActivity finishes.
public void doneListener(View v){
// Here i get NULL
System.out.println(comment);
finish();
}
@Override
public void onCommentEntered(String data) {
comment=data;
// Here i get what the user typed
System.out.println(comment);
}
}
</code></pre>
<p>My fragment</p>
<pre><code>public class thefragment extends Fragment {
commentListener cListener;
static TextView note;
EditText comment;
public interface commentListener{
void onCommentEntered(String data);
}
public static thefragment newInstance(){
return new thefragment ();
}
public thefragment (){
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
cListener=(commentListener) context;
}
@Override
public void onDetach() {
super.onDetach();
cListener=null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
v=inflater.inflate(R.layout.fragment, container, false);
comment=(EditText)v.findViewById(R.id.comment_picker);
comment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
cListener.onCommentEntered(comment.getText().toString());
}
}
});
return v;
}
}
</code></pre> | 1 |
Something wrong with my ruby | <p>Always the same error:</p>
<pre><code>
AilixdeMacBook-Pro:~ Ailix$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14]
AilixdeMacBook-Pro:~ Ailix$ ruby -d
Exception `LoadError' at /Library/Ruby/Site/2.0.0/rubygems.rb:1240 - cannot load such file -- rubygems/defaults/operating_system
Exception `LoadError' at /Library/Ruby/Site/2.0.0/rubygems.rb:1249 - cannot load such file -- rubygems/defaults/ruby
Exception `NameError' at /Library/Ruby/Site/2.0.0/rubygems.rb:1257 - uninitialized constant Gem::Specification
/Library/Ruby/Site/2.0.0/rubygems.rb:1257:in `': uninitialized constant Gem::Specification (NameError)
from :1:in `require'
from :1:in `'
AilixdeMacBook-Pro:~ Ailix$ gem -v
/Library/Ruby/Site/2.0.0/rubygems.rb:1257:in `': uninitialized constant Gem::Specification (NameError)
from :1:in `require'
from :1:in `'
AilixdeMacBook-Pro:~ Ailix$ brew -v
/Library/Ruby/Site/2.0.0/rubygems.rb:1257:in `': uninitialized constant Gem::Specification (NameError)
from :1:in `require'
from :1:in `'
AilixdeMacBook-Pro:~ Ailix$ pod repo
/Library/Ruby/Site/2.0.0/rubygems.rb:1257:in `': uninitialized constant Gem::Specification (NameError)
from :1:in `require'
from :1:in `'
</code></pre>
<p>I guess something wrong with my ruby. But i don't know how to fix it</p>
<p>My environment:</p>
<pre>
MacOS 10.10.5
Xcode 7.2
</pre>
<p>Thanks in advance</p> | 1 |
g++ "warning: iteration ... invokes undefined behavior" for Seemingly Unrelated Variable | <p>Consider the following code in <code>strange.cpp</code>:</p>
<pre><code>#include <vector>
using namespace std;
int i = 0;
int *bar()
{
++i;
return &i;
}
int main()
{
for(size_t j = 0; j < 99999999999; ++j) // (*)
{
const auto p = bar();
if(!p) // (**)
return -1;
}
}
</code></pre>
<p>Compiling this with g++ gives a warning:</p>
<pre><code>$ g++ --std=c++11 -O3 strange.cpp
strange.cpp: In function ‘int main()’:
strange.cpp:12:12: warning: iteration 4294967296ul invokes undefined behavior [-Waggressive-loop-optimizations]
++i;
^
strange.cpp:19:9: note: containing loop
for(size_t j = 0; j < 99999999999; ++j) // (*)
^
</code></pre>
<p>I don't understand why the increment invokes undefined behavior. Moreover, there are two changes, each of which makes the warning disappear:</p>
<ol>
<li>changing the line <code>(*)</code> to <code>for(int j...</code></li>
<li>changing the line <code>(**)</code> to <code>if(!*p)</code></li>
</ol>
<p>What is the meaning of this warning, and why are the changes relevant to it?</p>
<p><strong>Note</strong></p>
<pre><code>$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
</code></pre> | 1 |
Year 2038 solution for embedded Linux (32 bit)? | <p>What is the proper way to handle times in C code for 32-bit embedded Linux (ARMLinux) to ensure that the code continues to work properly after 03:14:07 UTC on 19 January 2038 (when a signed 32-bit <code>time_t</code> overflows)? Given that <code>time_t</code> is signed 32-bit on the system I have to use, what are the alternatives?</p>
<p>A considerable amount of googling has uncovered nothing of practical use. Everyone seems to assume that we will all be using 64-bit OSs by then, but this patently isn't true of embedded systems.</p>
<p>On the system I am required to use, <code>__kernel_time_t</code> is defined as a <code>long</code>. Which presumably means that there is no kernel facility for 64 bit time. The version of uClibc is 0.9.29.</p>
<p>I can't believe I'm the only one with this problem, and I don't want to reinvent the wheel.</p> | 1 |
Convert html entities to unicode characters via php mysql csv export | <p>In my MySQL database this is a sample of an HTML entity that I have: </p>
<pre><code>&Uacute;
</code></pre>
<p>When I export it through my script this is what I get: </p>
<pre><code>ú
</code></pre>
<p>As you can see in my script I already have 'html_entity_decode' which should convert it appropriately to this (which is what I want): </p>
<pre><code>Ú
</code></pre>
<p>Obviously, I am doing something wrong. I have exhausted other various scripts, solutions and otherwise have been trying to resolve this issue for over a day. Here is my PHP code: </p>
<pre><code>$link = mysqli_connect("localhost", "user", "pass", "db");
$sql="SELECT * FROM wtf";
$result=mysqli_query($link,$sql);
if (!$result) die('Couldn\'t fetch records');
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header('Content-Disposition: attachment; filename="results.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, array('Nome'));
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_map('html_entity_decode',array_values($row)), ',', '"');
}
die;
}
mysqli_close($link);
exit;
</code></pre>
<p>Could someone please help or at least point me in the right direction? Having taken on a project that requires European characters in the CSV results, it has been nothing less then a nightmare...</p> | 1 |
How do I add UIView on UIScrollView | <p>I wanted to add some labels and textfields on my view and that view should scroll, so I am thinking of putting view on scrollview.</p>
<ol>
<li>I wanted to add some labels and textfields on my view</li>
<li>And that view should scroll</li>
<li>So I am thinking of putting scrollView</li>
<li>And then I wanted to put my view having labels and Textfields</li>
<li>Is it possible?</li>
</ol> | 1 |
How to share imports between modules? | <p>My package looks like this:</p>
<p><a href="https://i.stack.imgur.com/DPgqO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DPgqO.png" alt="enter image description here"></a></p>
<p>These helpers, since they are all dealing with <code>scipy</code>, all have common imports:</p>
<pre><code>from matplotlib import pyplot as plt
import numpy as np
</code></pre>
<p>I'm wondering if it is possible to extract them out, and put it somewhere else, so I can reduce the duplicate code within each module?</p> | 1 |
Notice: Variable seems to be uninitialized | <p>For some reason I am getting this notice in my code.</p>
<blockquote>
<p>Variable $conn seems to be uninitialized</p>
</blockquote>
<p>I don't understand why I'm seeing this notice. I think I'm including my <code>include</code> in the right place.</p>
<pre><code>Class Calendar {
public function show() {
include './includes/dbconn.php';
include_once './includes/functions.php';
for ($i=0; $i<$weeksInMonth; $i++) {
// Create days in a week
for ($j=1;$j<=7;$j++) {
$cal_date = (string)$this->currentDate;
$tutor_date = display_tutor_schedule($conn,$cal_date);
if(isset($tutor_date[$j]['date'])) {
$content .= $this->_showDay($i*7+$j, $tutor_date[$j]['date']);
}
else {
$content .= $this->_showDay($i*7+$j, 0);
}
}
$content .="</tr>";
}
}
}
</code></pre>
<p>My <code>$conn</code> variable is coming from <code>include './includes/dbconn.php';</code>. Since I am not getting any PHP database error, such as "Not connected to the database" or something like that, I assume that my connection is right.</p>
<h3>functions.php</h3>
<pre><code>function display_tutor_schedule($conn,$tutor_date) {
$query = "select * from [dbo].[TUTOR_SCHEDULE] "
. "LEFT JOIN [dbo].[TUTOR] "
. "ON [dbo].[TUTOR_SCHEDULE].tutor_id = [dbo].[TUTOR].tutor_id "
. "LEFT JOIN [dbo].[STATUS] "
. "ON [dbo].[STATUS].status_id = [dbo].[TUTOR_SCHEDULE].status_id "
. "WHERE [dbo].[TUTOR_SCHEDULE].date = '$tutor_date' " ;
$stmt = sqlsrv_query($conn, $query);
$i = 0;
$appt_detail = array();
while ($row = sqlsrv_fetch_array($stmt)) {
$appt_detail[$i]['date'] = $row['date'];
$appt_detail[$i]['t_shedule_id'] = $row['t_shedule_id'];
$appt_detail[$i]['start_time'] = $row['start_time'];
$appt_detail[$i]['end_time'] = $row['end_time'];
$appt_detail[$i]['tutor_fname'] = $row['tutor_fname'];
$appt_detail[$i]['tutor_lname'] = $row['tutor_lname'];
$appt_detail[$i]['status_name'] = $row['status_name'];
$appt_detail[$i]['status_id'] = $row['status_id'];
$i++;
}
return $appt_detail;
}
</code></pre>
<h3>my_class.php</h3>
<pre><code><?php
$calendar = new Calendar();
echo $calendar->show();
?>
</code></pre>
<h3>dbconn.php</h3>
<pre><code>$serverName = "myserver";
$connectionInfo = array("Database" => "my_database", "UID" => "user", "PWD" => "pwd");
$conn = sqlsrv_connect($serverName, $connectionInfo);
</code></pre> | 1 |
mysql on amazon linux - MySQL Daemon failed to start | <p>I tried that restarting EC2 instance and <code>sudo service httpd restart</code>.</p>
<p>But I still get this message:</p>
<pre><code>[ec2-user@ip-* ~]$ sudo service mysqld start
MySQL Daemon failed to start.
Starting mysqld: [FAILED]
</code></pre>
<p>Also I get this message:</p>
<pre><code>[ec2-user@ip-* ~]$ mysqld
160127 7:01:48 [Note] mysqld (mysqld 5.5.46) starting as process 2745 ...
160127 7:01:48 [Warning] Can't create test file /var/lib/mysql/ip-*.lower-test
160127 7:01:48 [Warning] Can't create test file /var/lib/mysql/ip-*.lower-test
160127 7:01:48 [Note] Plugin 'FEDERATED' is disabled.
mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
160127 7:01:48 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
160127 7:01:48 InnoDB: The InnoDB memory heap is disabled
160127 7:01:48 InnoDB: Mutexes and rw_locks use GCC atomic builtins
160127 7:01:48 InnoDB: Compressed tables use zlib 1.2.8
160127 7:01:48 InnoDB: Using Linux native AIO
160127 7:01:48 InnoDB: Initializing buffer pool, size = 128.0M
160127 7:01:48 InnoDB: Completed initialization of buffer pool
160127 7:01:48 InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
</code></pre>
<p>I don't know what should I do..</p>
<p>Cheers!</p>
<h2>EDIT</h2>
<p>(+ I'm also using amazon RDS.)</p>
<p>Now, I tried <code>sudo chown -R mysql:mysql /var/lib/mysql</code> too.</p>
<p>But</p>
<pre><code>[ec2-user@ip-* ~]$ mysql_upgrade
Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
FATAL ERROR: Upgrade failed
[ec2-user@ip-* ~]$ ls -lh /var/lib/mysql/
합계 29M
-rw-rw---- 1 mysql mysql 5.0M 1월 27 06:52 ib_logfile0
-rw-rw---- 1 mysql mysql 5.0M 1월 27 06:12 ib_logfile1
-rw-rw---- 1 mysql mysql 18M 1월 27 06:52 ibdata1
drwx------ 2 mysql mysql 4.0K 1월 20 07:03 mysql
drwx------ 2 mysql mysql 4.0K 1월 20 07:03 performance_schema
drwx------ 2 mysql mysql 4.0K 1월 20 07:03 test
</code></pre> | 1 |
Enabling CLR still doesn't allow me to run code on sql server | <p>I'm using the following command to try and enable the CLR on a SQL Server 2008 instance</p>
<pre><code>EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
</code></pre>
<p>But I still get the following error</p>
<blockquote>
<p>Execution of .NET Framework code is disabled. Set "clr enabled"
configuration option and restart the server</p>
</blockquote>
<p>Do I need to do anything else?</p> | 1 |
Check if a type is from a particular namespace | <p>I would like to check if a type is from a particular namespace. Here is what I came up with:</p>
<pre><code>#include <utility>
namespace helper
{
template <typename T, typename = void>
struct is_member_of_sample : std::false_type
{
};
template <typename T>
struct is_member_of_sample<
T,
decltype(adl_is_member_of_sample(std::declval<T>()))> : std::true_type
{
};
}
namespace sample
{
template <typename T>
auto adl_is_member_of_sample(T && ) -> void;
}
// -- Test it
namespace sample
{
struct X;
}
struct Y;
static_assert(helper::is_member_of_sample<sample::X>::value, "");
static_assert(not helper::is_member_of_sample<Y>::value, "");
int main(){}
</code></pre>
<p>This works fine as long as no one adds <code>adl_is_member_of_sample</code> to their own namespace (or even the global namespace). And of course, I would have to create such a construct for each namespace I want to test for.</p>
<p>Is there a better way to check at compile time if a type is from a particular namespace?</p>
<p><hr>
<strong>Rationale</strong> or "Why would I want that":</p>
<p>In an EDSL, I am checking type traits at compile time to see whether certain expressions are valid or not. Some of those type traits are fairly simple: If a class has a <code>using is_numeric = void</code>, then I treat it as a numeric expression. Works fine.</p>
<p><code>is_numeric</code> is pretty generic though. Others might use it as well. I therefore thought about backing the trait with a check that the type is from the expected namespace.</p> | 1 |
value <br of type java.lang.String cannot be converted to JSONObject In Android Programming | <p>When I am Create new Android Application to Fetch data from my server like xampp, But Its not Retrieval and i am using catch statement for itz exception then it says as JSONObject cannot convert it, How to Solve?</p>
<p>Solution for this, Please Help me?
Thanks in Advance</p>
<p>My Full Java Code</p>
<pre><code> package com.example.fetch;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class Disp extends Activity {
TextView user,email,phone;
String abdu,hos,em,ph;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.disp);
user=(TextView)findViewById(R.id.user);
email=(TextView)findViewById(R.id.email);
phone=(TextView)findViewById(R.id.phone);
SharedPreferences sandra=getApplicationContext().getSharedPreferences("veena", MODE_WORLD_READABLE);
abdu=sandra.getString("shyma", "");
user.setText(abdu);
aji aj=new aji();
aj.execute();
}
class aji extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try
{
DefaultHttpClient hc=new DefaultHttpClient();
ResponseHandler<String> res=new BasicResponseHandler();
HttpPost postMethod=new HttpPost("http://10.0.2.2/std/ret.php");
List<NameValuePair>nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username",abdu));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
hos = hc.execute(postMethod,res);
System.out.println(hos);
}
catch(Exception e)
{
System.out.println("Error:"+e);
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid Login",
Toast.LENGTH_LONG).show();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
parsingmethod();
}
}
public void parsingmethod()
{
try
{
JSONObject jobject=new JSONObject(hos);
JSONObject jobject1=jobject.getJSONObject("Event");
JSONArray ja=jobject1.getJSONArray("Details");
int length=ja.length();
for(int i=0;i<length;i++)
{
JSONObject data1=ja.getJSONObject(i);
em=data1.getString("email");
ph=data1.getString("pass");
System.out.println(em+ph);
email.setText(em);
phone.setText(ph);
}
}
catch(Exception e)
{
/*System.out.println("error:"+e);
Log.e("Fail 2", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();*/
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
}
private void displayExceptionMessage(String message) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>Catch Exception Shows that value
<p>My Log Cat</p>
<pre><code>01-20 16:22:31.432: I/System.out(10797): Error:org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused
01-20 16:22:31.452: I/System.out(10797): error:java.lang.NullPointerException
01-20 16:24:01.342: I/System.out(10996): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:44:57.302: I/System.out(11503): error:org.json.JSONException: No value for Event
01-20 16:50:19.062: I/System.out(11741): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:50:59.572: I/System.out(11960): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:50:59.572: E/Fail 2(11960): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:51:26.462: I/PGA(12155): New SOCKET connection: m.example.fetch (pid 12155, tid 12155)
01-20 16:51:29.142: I/System.out(12155): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:51:29.142: E/Fail 2(12155): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:51:49.742: I/System.out(12347): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:51:49.742: E/Fail 2(12347): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:52:11.062: I/System.out(12540): error:org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 16:52:11.062: E/Fail 2(12540): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:05:45.082: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:05:45.082: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:05:45.082: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:05:45.082: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:05:45.082: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:05:45.082: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:05:45.082: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:05:45.082: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:05:45.082: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:05:45.082: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:05:45.082: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:05:45.082: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:05:45.082: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:05:45.082: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:05:45.082: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:05:45.082: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:05:45.082: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:05:45.082: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:05:51.882: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:05:51.882: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:05:51.882: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:05:51.882: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:05:51.892: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:05:51.892: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:05:51.892: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:05:51.892: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:05:51.892: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:05:51.892: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:05:51.892: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:05:51.892: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:05:51.892: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:05:51.892: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:05:51.892: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:05:51.892: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:05:51.892: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:05:51.892: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:06:26.712: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:06:26.712: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:06:26.712: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:06:26.712: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:06:26.712: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:06:26.712: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:06:26.712: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:06:26.712: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:06:26.712: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:06:26.712: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:06:26.712: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:06:26.712: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:06:26.712: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:06:26.712: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:06:26.712: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:06:26.712: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:06:26.712: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:06:26.712: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:07:20.232: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:07:20.242: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:07:20.242: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:07:20.242: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:07:20.242: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:07:20.242: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:07:20.242: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:07:20.242: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:07:20.242: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:07:20.242: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:07:20.242: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:07:20.242: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:07:20.242: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:07:20.242: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:07:20.242: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:07:20.242: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:07:20.242: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:07:20.242: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:07:40.612: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:07:40.612: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:07:40.612: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:07:40.612: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:07:40.612: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:07:40.612: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:07:40.612: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:07:40.612: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:07:40.612: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:07:40.612: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:07:40.612: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:07:40.612: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:07:40.612: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:07:40.612: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:07:40.612: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:07:40.612: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:07:40.612: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:07:40.612: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:11:44.152: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:11:44.152: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:11:44.162: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:11:44.162: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:11:44.162: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:11:44.162: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:11:44.162: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:11:44.162: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:11:44.162: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:11:44.162: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:11:44.162: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:11:44.162: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:11:44.162: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:11:44.162: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:11:44.162: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:11:44.162: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:11:44.162: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:11:44.162: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:12:13.872: E/dalvikvm(13814): No JIT support for bytecode f0 at offsetPC 0
01-20 17:12:13.872: E/dalvikvm(13814): JIT implementation not found
01-20 17:12:13.872: I/dalvikvm(13814): codeGenBasicBlockJit returns negative number
01-20 17:12:13.892: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:12:13.892: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:12:13.892: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:12:13.892: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:12:13.892: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:12:13.892: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:12:13.892: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:12:13.892: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:12:13.892: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:12:13.892: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:12:13.892: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:12:13.892: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:12:13.892: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:12:13.892: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:12:13.892: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:12:13.892: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:12:13.892: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:12:13.892: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:13:12.522: W/System.err(13814): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:13:12.522: W/System.err(13814): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:13:12.522: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:13:12.522: W/System.err(13814): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:13:12.522: W/System.err(13814): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:13:12.522: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:13:12.522: W/System.err(13814): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:13:12.522: W/System.err(13814): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:13:12.522: W/System.err(13814): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:13:12.522: W/System.err(13814): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:13:12.522: W/System.err(13814): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:13:12.522: W/System.err(13814): at android.os.Looper.loop(Looper.java:137)
01-20 17:13:12.522: W/System.err(13814): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:13:12.522: W/System.err(13814): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:13:12.522: W/System.err(13814): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:13:12.522: W/System.err(13814): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:13:12.522: W/System.err(13814): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:13:12.522: W/System.err(13814): at dalvik.system.NativeStart.main(Native Method)
01-20 17:19:47.832: I/PGA(14194): New SOCKET connection: m.example.fetch (pid 14194, tid 14194)
01-20 17:19:50.772: W/System.err(14194): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
01-20 17:19:50.772: W/System.err(14194): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:19:50.772: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:91)
01-20 17:19:50.772: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:103)
01-20 17:19:50.772: W/System.err(14194): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:19:50.772: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:19:50.772: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:19:50.772: W/System.err(14194): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:19:50.772: W/System.err(14194): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:19:50.772: W/System.err(14194): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:19:50.772: W/System.err(14194): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:19:50.772: W/System.err(14194): at android.os.Looper.loop(Looper.java:137)
01-20 17:19:50.772: W/System.err(14194): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:19:50.772: W/System.err(14194): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:19:50.772: W/System.err(14194): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:19:50.772: W/System.err(14194): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:19:50.772: W/System.err(14194): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:19:50.772: W/System.err(14194): at dalvik.system.NativeStart.main(Native Method)
01-20 17:22:24.402: W/System.err(14194): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
01-20 17:22:24.402: W/System.err(14194): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:22:24.402: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:91)
01-20 17:22:24.402: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:103)
01-20 17:22:24.402: W/System.err(14194): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:22:24.402: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:22:24.402: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:22:24.402: W/System.err(14194): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:22:24.402: W/System.err(14194): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:22:24.402: W/System.err(14194): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:22:24.402: W/System.err(14194): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:22:24.402: W/System.err(14194): at android.os.Looper.loop(Looper.java:137)
01-20 17:22:24.402: W/System.err(14194): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:22:24.402: W/System.err(14194): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:22:24.402: W/System.err(14194): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:22:24.402: W/System.err(14194): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:22:24.402: W/System.err(14194): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:22:24.402: W/System.err(14194): at dalvik.system.NativeStart.main(Native Method)
01-20 17:32:17.792: W/System.err(14194): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
01-20 17:32:17.792: W/System.err(14194): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:32:17.792: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:91)
01-20 17:32:17.792: W/System.err(14194): at org.json.JSONArray.<init>(JSONArray.java:103)
01-20 17:32:17.792: W/System.err(14194): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:32:17.792: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:32:17.792: W/System.err(14194): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:32:17.792: W/System.err(14194): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:32:17.792: W/System.err(14194): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:32:17.802: W/System.err(14194): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:32:17.802: W/System.err(14194): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:32:17.802: W/System.err(14194): at android.os.Looper.loop(Looper.java:137)
01-20 17:32:17.802: W/System.err(14194): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:32:17.802: W/System.err(14194): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:32:17.802: W/System.err(14194): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:32:17.802: W/System.err(14194): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:32:17.802: W/System.err(14194): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:32:17.802: W/System.err(14194): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>My PHP Page</p>
<pre><code><?php
include("config.php");
$user=$_REQUEST['user'];
$sql1=mysql_query("select * from reg_table where user='$user'")or die (mysql_error());
$c = mysql_num_rows($sql1);
while($sql2 = mysql_fetch_array($sql1))
{
$arrDet['Event']['Details'][]=$sql2;
}
if($c>0)
{
$arrDet['Details']['status']="success";
}
else
{
$arrDet['Details']['status']="Nodata";
}
echo json_encode($arrDet);
?>
</code></pre>
<p>Main Logcat Error</p>
<pre><code>01-20 17:47:26.442: W/System.err(14954): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
01-20 17:47:26.442: W/System.err(14954): at org.json.JSON.typeMismatch(JSON.java:111)
01-20 17:47:26.442: W/System.err(14954): at org.json.JSONObject.<init>(JSONObject.java:158)
01-20 17:47:26.442: W/System.err(14954): at org.json.JSONObject.<init>(JSONObject.java:171)
01-20 17:47:26.442: W/System.err(14954): at com.example.fetch.Disp.parsingmethod(Disp.java:86)
01-20 17:47:26.442: W/System.err(14954): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:76)
01-20 17:47:26.442: W/System.err(14954): at com.example.fetch.Disp$aji.onPostExecute(Disp.java:1)
01-20 17:47:26.442: W/System.err(14954): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-20 17:47:26.442: W/System.err(14954): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-20 17:47:26.442: W/System.err(14954): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-20 17:47:26.442: W/System.err(14954): at android.os.Handler.dispatchMessage(Handler.java:99)
01-20 17:47:26.442: W/System.err(14954): at android.os.Looper.loop(Looper.java:137)
01-20 17:47:26.442: W/System.err(14954): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-20 17:47:26.442: W/System.err(14954): at java.lang.reflect.Method.invokeNative(Native Method)
01-20 17:47:26.442: W/System.err(14954): at java.lang.reflect.Method.invoke(Method.java:511)
01-20 17:47:26.442: W/System.err(14954): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
01-20 17:47:26.442: W/System.err(14954): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
01-20 17:47:26.442: W/System.err(14954): at dalvik.system.NativeStart.main(Native Method)
</code></pre> | 1 |
How to find a Minimum Spanning Tree with a given set of coordinates from an input file using Prim's Algorithm? | <p>Alright guys, I have seen this no where on the internet and I have been trying to figure it out for days. How can I find the MST of a set of coordinates from an input file using Prim's Algorithm. There are a few things about how to go about doing it, but following them along and being new to C++, they aren't much help. Can anyone show me CODE(preferably) on how to solve this issue?</p>
<p>Suppose I have a set of coordinates in an input file "Something.txt" containing:<br>
(N number of nodes/vertices)<br>
(x Coord), (y coord)<br>
etc... </p>
<p>Eg:</p>
<pre><code>9
50 100
100 150
200 150
300 150
350 100
300 50
200 50
100 50
150 100
</code></pre>
<p>Given that these points have already been plotted, How would Prim's Algorithm be written? I understand this is a lot, but I'm beyond confused at this point as a new learner to C++. (and yes, I've tried piecing out the code, I've tried looking at other examples and twisting them around to get it to work, I've tried just about everything besides seeing how it's done so I can further understand what I keep missing.)</p>
<p>Thanks in advance.</p>
<p>Edit: The code plotting the points through pygraphics using the argument .txt input file you pass to it, which then goes into a .dat file, which then gets posted through a plotting file pre-created: </p>
<pre><code>class Point
{
public:
// Constructor.
Point()
{
x = 0; y = 0;
} // end constructor
Point(int a, int b, int id)
{
x = a; y = b; pointID = id;
} // end constructor
int getX() { return x; }
int getY() { return y; }
int getID() { return pointID; }
string data;
Point(string x)
{
data = x;
}
private:
int x = 0;
int y = 0;
int v;
int xVert;
int yVert;
int pointID = 0;
list<Point*> pointList;
list<Point*> neighbors;
//vector<Neighbor> myNeighborvector;
//locate point containg value x
Point * findPoint(string x)
{
for(Point * v : pointList)
{
if (v->data == x)
return v;
}
return NULL;
}
//add Neighbor going from x to y
void addDirectedNeighbor(string x, string y)
{
Point * xVert = findPoint(x);
Point * yVert = findPoint(y);
xVert->neighbors.push_back(yVert); //I would think that this should only add y to x's neighbors, but when I try to display I get x as one of y's neighbors
}
void addNeighbor(string x, string y)
{
addDirectedNeighbor(x, y);
addDirectedNeighbor(y, x);
}
}; // end class Point
//--------------------------------------------------------------------------
class Edge
{
public:
// Constructor.
Edge()
{
} // end constructor
Edge(Point ptA, Point ptB)
{
pointA = ptA;
pointB = ptB;
length = sqrt(pow(abs(pointA.getX() - pointB.getX() ), 2) + pow(abs(pointA.getY() - pointB.getY() ), 2) );
} // end constructor
Point getPtA() { return pointA; }
Point getPtB() { return pointB; }
double getLen() { return length; }
int getPtAID() { return pointA.getID(); }
int getPtBID() { return pointB.getID(); }
private:
Point pointA;
Point pointB;
double length;
}; // end class Edge
//--------------------------------------------------------------------------
/*class Neighbor
{
public:
// Constructor.
Neighbor()
{
length = sqrt(pow(abs(pointA.getX() - pointB.getX() ), 2) + pow(abs(pointA.getY() - pointB.getY() ), 2) );
} // end constructor
double getLen() { return length; }
private:
double length;
int pointID = 0;
};*/ // end class Neighbor
vector<Point> myPointvector; // vector will expand as needed
vector<Edge> MinSpanTree;
int main (int argc, char *argv[])
{
ifstream fin;
int coordPairs; // number of coordinate pairs in the file
int ptX, ptY;
int loopCounter;
int pointCounter = 0;
double MSTLength = 0.0;
// Check the number of arguments. Expected: filename of a file
if (argc != 2) // This check is often hardcoded
{ // If failure in parameters, offer advice for correction
cout << "\nThis program uses command-line argument.\n";
cout << "Usage: a.exe <filename>\n";
exit(0);
}
try // All lines within this block are part of the same exception handler
{
fin.open(argv[1]);
}
catch (exception& ex)
{
cout << ex.what(); // display standard explanation of the exception
exit(0); // exit the program
}
// Read from the file, one token at a time. If the type of token is known, it
// can be read into a corresponding variable type, such as
// in >> x; // Read the first item into an integer variable x.
// in >> str; // Read the next item into a string variable str.
// This line provides the graphic window setup.
cout << "800 600 white" << endl;
fin >> coordPairs;
cout << coordPairs << endl;
while (fin >> ptX)
{
// Do something with the element read from the file
// cout << ptX << endl;
fin >> ptY;
// cout << ptY << endl;
cout << "circle " << ptX << " " << ptY << " " << 20 << " seagreen" << endl;
Point dummyPoint(ptX, ptY, pointCounter++);
myPointvector.push_back(dummyPoint); // vector will expand as needed
cout << "Now myPointvector has size " << myPointvector.size() << endl;
} // end while
fin.close();
return 0;
}
</code></pre> | 1 |
WCF wsHttpBinding Client Certificate Authentication without using store in client | <p>I have a WCF service registered as such using wsHttpBinding it is hosted in IIS with HTTPS binding to a valid and active certificate:</p>
<pre><code><?xml version="1.0"?>
<configuration>
<system.webServer>
<security>
<access sslFlags="Ssl, SslNegotiateCert, SslRequireCert"/>
<authorization>
<add users="*" accessType="Allow" />
</authorization>
</security>
</system.webServer>
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.serviceModel>
<protocolMapping>
<add scheme="https" binding="wsHttpBinding" />
</protocolMapping>
<bindings>
<wsHttpBinding>
<binding name="MyNameSpace.WebService_TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyNameSpace.WebService_Behaviour">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyNameSpace.WebService" behaviorConfiguration="MyNameSpace.WebService_Behaviour">
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="MyNameSpace.WebService_TransportSecurity"
contract="MyNameSpace.IMyServiceContract">
</endpoint>
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
</code></pre>
<p>I'm using .NET 4 so as far as I can tell this is the only binding that works with SSL and client certificate authentication.</p>
<p>I've generated the standard proxy using svcutil and trying to set the certificate (self signed that is also in the server) using it's base64 representation:</p>
<pre><code>X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(System.Convert.FromBase64String("thebase64ofthecertificate"));
if (certificate == null)
{
return null;
}
IMyServiceContractClient client = new IMyServiceContractClient(new System.ServiceModel.WSHttpBinding
{
Security = new System.ServiceModel.WSHttpSecurity
{
Mode = System.ServiceModel.SecurityMode.Transport,
Transport = new System.ServiceModel.HttpTransportSecurity
{
ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Certificate
}
}
},
new System.ServiceModel.EndpointAddress(new System.Uri("https://myserviceendpoint/webservice.svc")));
client.ClientCredentials.ClientCertificate.Certificate = certificate;
</code></pre>
<p>But it does not work if I don't also have the certificate in my local computer store, I get this error:</p>
<p><a href="https://i.stack.imgur.com/ed5Oa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ed5Oa.jpg" alt="enter image description here"></a></p>
<p>I'm not an expert in security, ssl or certificates, but is this feasible? </p>
<p>All I'm trying to achieve is to ensure that my service is only called by this code, and thought that using self-signed client certificates that are validated in the server would do, but if they need to be in the store it adds unnecessary complexity to the whole thing!</p>
<hr>
<h2>UPDATE 1:</h2>
<p>As suggested by Yacoub Massad exporting certificate's Base64 with X509ContentType.Pkcs12 yields exception: </p>
<pre><code>An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Key not valid for use in specified state.
</code></pre>
<p>I'm loading the certificate from store with:</p>
<pre><code> X509Certificate2 certificate = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadWrite);
var r = store.Certificates.Find(X509FindType.FindBySubjectName, "LicensingCert", false);
if (r.Count > 0)
certificate = r[0];
}
catch
{
certificate = null;
}
finally
{
if (store != null)
store.Close();
}
if (certificate == null)
{
return null;
}
File.WriteAllText(@"C:\tmp\certs\ExportLicensingCert.txt", Convert.ToBase64String(certificate.Export(X509ContentType.Pkcs12)));
</code></pre>
<h2>UPDATE 2:</h2>
<p>Made sure the certificate had been imported with Mark as exportable and it did the trick, I must have skipped that the first time I imported the certificate. Now testing the compiled code on another computer has stopped doing the error. Thank you so much Yacoub Massad for pointing me in the right direction :)</p> | 1 |
Why is the newer/faster Java 8 way of sorting acting worse? | <pre><code>List<Point> pixels = new ArrayList<>(width * height); // 1280*960
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels.add(new Point(x, y));
// Java 7 sorting
Collections.sort(pixels, comparator);
// Java 8 sorting
pixels = pixels.stream().parallel().sorted(comparator).collect(Collectors.toList());
</code></pre>
<p>When using any sorting method, I get slow performance at first and it improves later. I expect this, because the JIT compiler needs time to optimize the high-use code.</p>
<p>The weird thing is, the old sorter is a little slow at first, while the new sorter much more so, more than 60% slower. After a while, the new sorter becomes faster, as expected. But the way that the first two/three executions are so slow is simply unacceptable.</p>
<pre><code>Java 7 collection sorter
0.258992413
0.265509443
0.536536068
0.117830618
0.136303916
0.111004611
0.134771877
0.108078261
Java 8 stream sorter
0.631757108
0.868032669
0.076455248
0.087101852
0.070401965
0.056989645
0.072018371
0.078908912
0.074237648
</code></pre>
<p>Specs:<br/>
CPU: Intel I7 3770 (8-core 8M/1M/128K cache)<br/>
cmd: javaw -server -cp bin Myclass</p>
<ul>
<li>Has anyone else experienced worse performance of newer (stream) operations?</li>
<li>Is there a way to fix this slowness? (without inducing start-up delays)</li>
</ul> | 1 |
How to have separate sessionStorages for iframes on same origin | <p>The standard W3C standard says about localStorages:</p>
<blockquote>
<p>Different authors sharing one host name, for example users hosting content on <code>geocities.com</code>, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.</p>
</blockquote>
<p>But for sessionStorages it's said that it does provide separate sessionStorages for tabs and windows even from same origin.</p>
<p>But it seems iframes does share the sessionStorage.</p>
<p>Is there a way to have separate sessionStorages on via iframes on the same origin.</p>
<p>Edit:
Since there was confusion if tabs/windows do have separate sessionStorages, here is a sample page. Save the code in a file and open it with two different tabs. Then refresh one tab 5 times and refresh the other tab 1 time. You'll see that the numbers differ.</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
sessionStorage.setItem("counter", (parseInt(sessionStorage.getItem("counter"), 10) || 0 ) + 1);
document.getElementById("result").innerHTML = sessionStorage.getItem("counter");
</script>
</body>
</html>
</code></pre>
<p>Edit2: What I have tried so far is to use the iframe <code>sandbox</code> attribute. But then I got an error within the iframe and I cann't use sessionStorage at all. I had to add <code>sandbox="allow-same-origin"</code>. But then the sessionStorage is the same in all iframes again.</p>
<p>Thanks in advance.</p> | 1 |
python: argparser.add_argument() causes ArgumentError() | <p>I've encountered a very strange issue — when I'm using <code>argparser.add_argument()</code> method I'm getting <code>ArgumentError()</code>.</p>
<pre><code>from oauth2client.tools import argparser, run_flow
if __name__ == "__main__":
argparser.add_argument("--videoid", default="L-oNKK1CrnU",
help="ID of video to like.")
</code></pre>
<p>I'm running the code with pdb, that's the error I'm getting:</p>
<pre><code>(Pdb) n
ArgumentError: ArgumentError()
> c:\py\googleapitest.py(48)<module>()->None
-> help="ID of video to like.")
</code></pre>
<p>That's the root cause:</p>
<pre><code>C:\Python27\lib\argparse.pyc in _handle_conflict_error(self, action, conflicting_actions)
1452 for option_string, action
1453 in conflicting_actions])
-> 1454 raise ArgumentError(action, message % conflict_string)
</code></pre>
<p>I'm getting the error even if I'm not passing "help" param.</p>
<p>What am I doing wrong?</p> | 1 |
Angular Material input not showing value when not focused | <p>I'm using Angular Material 1.0.3 and <code><input></code> elements are correctly set but their values are visible if I click one to focus it. Once it's not focused I can't see the value.</p>
<p>The markup is as follows:</p>
<pre><code><md-input-container>
<label>Some label</label>
<input ng-model="model.someProperty">
</md-input-container>
</code></pre>
<p>After checking if it's a CSS issue, I've found that the following CSS selector is turning <code>color</code> into <code>transparent</code>:</p>
<pre><code>md-input-container:not(.md-input-has-value) input:not(:focus) {
color: transparent;
}
</code></pre>
<p>And obviously, it seems like the input doesn't have the <code>.md-input-has-value</code> CSS class.</p>
<p>For now, I can't figure out what's going wrong.</p>
<h3>Additional info</h3>
<p>In my case, in opposite of Angular Material demos, controllers are on directives and UI Router states. </p>
<p><strong>In fact, I can confirm that I've already copy-pasted the same markup in my <code>index.html</code> as direct child of <code><body></code> and then it works as expected.</strong></p>
<p>Maybe it has some relation with this open issue: <a href="https://github.com/angular/material/issues/3017" rel="noreferrer">Compiling material directives on the fly: md-input-has-value attribute not set #3017</a>.</p>
<h3><code><md-input-container></code> has the <code>md-input-has-value</code> CSS class</h3>
<p>I've also checked that <code><md-input-container></code> has the <code>md-input-has-value</code> CSS class.</p> | 1 |
Android push notification offline | <p>im trying to implement push notification in my app,already using GCM. But the case is i want it in the way which works offline too.
i.e: for multiple conditions inside android app it should trigger push notification.</p>
<p>Currently im trying : </p>
<pre><code>NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, msg);
notification.contentView = contentView;
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,randomNo, notificationIntent, 0);
</code></pre>
<p>But the problem is,
1.When the app doesnt running ,the notification arrives but it cases screen to blink(becoz i call it using intent).
2.i want to use same class for multiple conditions and forward it to different activities(currently i cant change the intent to another activity based on condtiop).</p> | 1 |
Check if file extension is valid in delphi | <p>I have a TEditbox where the user keys in some name for the file along with the extension he wants to save it as. Now I want to validate if the extension he entered is a valid extension registered with windows. How can I achieve this?</p>
<p>All I have is:</p>
<pre><code>procedure TForm2.OkBtnClick(Sender: TObject);
var
ExtractedFileExt: string;
begin
ExtractedFileExt := ExtractFileExt(cxCbxSelectedFile.Text);
end;
</code></pre>
<p>How can I use that string variable and check if it is a valid file extension registered with Windows?</p> | 1 |
GStreamer encountered a general stream error in Qt5 raspberry pi | <p>I'm trying to play a video using QtMediaPlayer in Raspberry pi 2 B. The source code is as follows:</p>
<pre><code>QMediaPlayer *media;
QVideoWidget *video;
...
...
media = new QMediaPlayer(parent);
video = new QVideoWidget(parent);
media->setVideoOutput(video);
media->setMedia(QUrl::fromLocalFile("/home/pi/Desktop/test3.mp4"));
media->play();
</code></pre>
<p>But the result is a blank video screen and the following error:</p>
<pre><code>** (Bus:2148): WARNING **: ffmpegcolorspace-vo: size 1105920 is not a
multiple of unit size 829440
Error: "GStreamer encountered a general stream error."
</code></pre>
<p><strong>System Information</strong></p>
<p>Running latest raspbian Jessie OS,
Installed Qt5.3,
Installed gstreamer0.10-plugins-good/bad/ugly/ffmpeg and
Installed Mpeg-2 License</p>
<p>Here is the video <a href="https://drive.google.com/file/d/0BzI0PXqNuH48Ukw1Y1EtZmdMRkU/view?usp=sharing">test3.mp4</a></p>
<p>I ran this code in Windows with Qt5 installed; it is working there. But it's not working in the Raspberry pi. Please tell me what I'm missing here.</p>
<p><strong>Trying Pipe from Shell</strong> </p>
<p><a href="https://i.stack.imgur.com/BVlQb.png"><img src="https://i.stack.imgur.com/BVlQb.png" alt="enter image description here"></a></p> | 1 |
The Method is undefined for the type object error | <p>I have been researching this however I can't seem to correct the error.I'm only new in android development. I have a "The Method is undefined for the type object" error on both <code>getStatusCode()</code> and <code>getReasonPhrase()</code>. Any help would be appreciated.</p>
<pre><code>package com.javapapers.java.io;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class HttpUtil {
public String getHttpResponse(HttpRequestBase request) {
String result = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reason = httpResponse.getStatusLine().getReasonPhrase();
StringBuilder sb = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
result = sb.toString();
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return result;
}
}
</code></pre>
<p>I was then told that I shouldn't use the Apache HTTP client but use HttpURLConnection instead so I changed my code and I'm wondering would this work and would the outcome be the same</p>
<pre><code>public class HttpUtil {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "https://twitter.com/aaroadwatch"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
</code></pre>
<p>or even something like this </p>
<pre><code> URL url = new URL("https://twitter.com/aaroadwatch");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
</code></pre>
<p>My Twitter API Class
I have an error on <code>getHttpResponse</code> and <code>getHttpResponse</code>
package com.javapapers.social.twitter;</p>
<pre><code>import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.javapapers.java.io.HttpUtil;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class TwitterAPI {
private String twitterApiKey;
private String twitterAPISecret;
final static String TWITTER_TOKEN_URL = "https://api.twitter.com/oauth2/token";
final static String TWITTER_STREAM_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
public TwitterAPI(String twitterAPIKey, String twitterApiSecret){
this.twitterApiKey = twitterAPIKey;
this.twitterAPISecret = twitterApiSecret;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
try {
String twitterUrlApiKey = URLEncoder.encode(twitterApiKey, "UTF-8");
String twitterUrlApiSecret = URLEncoder.encode(twitterAPISecret, "UTF-8");
String twitterKeySecret = twitterUrlApiKey + ":" + twitterUrlApiSecret;
String twitterKeyBase64 = Base64.encodeToString(twitterKeySecret.getBytes(), Base64.NO_WRAP);
TwitterAuthToken twitterAuthToken = getTwitterAuthToken(twitterKeyBase64);
twitterTweetArrayList = getTwitterTweets(screenName, twitterAuthToken);
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return twitterTweetArrayList;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName,
TwitterAuthToken twitterAuthToken) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterAuthToken != null && twitterAuthToken.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TWITTER_STREAM_URL + screenName);
httpGet.setHeader("Authorization", "Bearer " + twitterAuthToken.access_token);
httpGet.setHeader("Content-Type", "application/json");
HttpUtil httpUtil = new HttpUtil();
String twitterTweets = httpUtil.getHttpResponse(httpGet);
twitterTweetArrayList = convertJsonToTwitterTweet(twitterTweets);
}
return twitterTweetArrayList;
}
public TwitterAuthToken getTwitterAuthToken(String twitterKeyBase64) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(TWITTER_TOKEN_URL);
httpPost.setHeader("Authorization", "Basic " + twitterKeyBase64);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
HttpUtil httpUtil = new HttpUtil();
String twitterJsonResponse = httpUtil.getHttpResponse(httpPost);
return convertJsonToTwitterAuthToken(twitterJsonResponse);
}
private TwitterAuthToken convertJsonToTwitterAuthToken(String jsonAuth) {
TwitterAuthToken twitterAuthToken = null;
if (jsonAuth != null && jsonAuth.length() > 0) {
try {
Gson gson = new Gson();
twitterAuthToken = gson.fromJson(jsonAuth, TwitterAuthToken.class);
} catch (IllegalStateException ex) { }
}
return twitterAuthToken;
}
private ArrayList<TwitterTweet> convertJsonToTwitterTweet(String twitterTweets) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterTweets != null && twitterTweets.length() > 0) {
try {
Gson gson = new Gson();
twitterTweetArrayList =
gson.fromJson(twitterTweets, new TypeToken<ArrayList<TwitterTweet>>(){}.getType());
} catch (IllegalStateException e) {
}
}
return twitterTweetArrayList;
}
private class TwitterAuthToken {
String token_type;
String access_token;
}
}
</code></pre> | 1 |
Android Studio: Cannot write to Shared Preferences in instrumented test | <p>I'm trying to write a test case to verify a class that writes to Shared Preferences.
I'm using Android Studio v1.5.</p>
<p>In the good old eclipse, when using <code>AndroidTestCase</code>, a second apk file was deployed to the device, and tests could be run using the instrumentation context, so you could run tests using the instrumentation apk's shared preferences without altering the main apk's existing shared preferences files.</p>
<p>I've spent the entire morning trying to figure out how to get a non null context in Android Studio tests. Apparently unit tests made for eclipse are not compatible with the Android Studio testing framework, as calling <code>getContext()</code> returns null.
I thought I've found the answer in this question:
<a href="https://stackoverflow.com/questions/8605611/get-context-of-test-project-in-android-junit-test-case">Get context of test project in Android junit test case</a></p>
<p>Things have changed over time as old versions of Android Studio didn't have full testing support. So a lot of answers are just hacks. Apparently now instead of extending <code>InstrumentationTestCase</code> or <code>AndroidTestCase</code> you should write your tests like this:</p>
<pre><code>@RunWith(AndroidJUnit4.class)
public class MyTest {
@Test
public void testFoo(){
Context instrumentationContext = InstrumentationRegistry.getContext();
Context mainProjectContext = InstrumentationRegistry.getTargetContext();
}
}
</code></pre>
<p>So I now have a non null instrumentation context, and the <a href="http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29" rel="nofollow noreferrer"><code>getSharedPreferences</code></a> method returns an instance that seems to work, but actually no preferences file is being written.</p>
<p>If I do: </p>
<pre><code>context = InstrumentationRegistry.getContext();
</code></pre>
<p>Then the SharedPreferences editor writes and commits correctly and no exception is thrown. On closer inspection I can see that the editor is trying to write to this file:</p>
<pre><code>data/data/<package>.test/shared_prefs/PREFS_FILE_NAME.xml
</code></pre>
<p>But the file is never created nor written to. </p>
<p>However using this:</p>
<pre><code>context = InstrumentationRegistry.getTargetContext();
</code></pre>
<p>the editor works correctly and the preferences are written to this file:</p>
<pre><code>/data/data/<package>/shared_prefs/PREFS_FILE_NAME.xml
</code></pre>
<p>The preferences are instantiated in private mode:</p>
<pre><code>SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
</code></pre>
<p>As far as I know, no test apk has been uploaded to the device after running the test. This might explain why the file was not written using the instrumentation context. Is it possible that this context is a fake context that fails silently?</p>
<p>And if this were the case, <strong>how could I obtain a REAL instrumentation context so that I can write preferences without altering the main project's preferences</strong>?</p> | 1 |
C - passing argument 1 of ‘fprintf’ makes pointer from integer without a cast | <p>Very simple script throw this error : </p>
<blockquote>
<p>passing argument 1 of ‘fprintf’ makes pointer from integer without a
cast</p>
</blockquote>
<p>Why is that ? The code is : </p>
<pre><code>#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *FP;
if((FP = fopen("file.txt", "r+")) == NULL) {
printf("File won't open\n");
return(1);
}
foo(FP);
return(0);
}
int foo(FP) {
char name[31];
printf( "Please enter a name (within 30 char) : \n");
gets(name);
fprintf(FP, "%s\n", name);
return(0);
}
</code></pre> | 1 |
InvalidOperationException when registering a new user with ASP .NET Core Identity and EntityFrameworkCore | <p>I'm following the <a href="https://docs.asp.net/en/latest/security/authentication/identity.html" rel="nofollow noreferrer">documentation for using Identity</a> and am trying register a new user (executing the register action), but it fails with the following error:</p>
<blockquote>
<p>InvalidOperationException: Cannot create a DbSet for 'ApplicationUser'
because this type is not included in the model for the context.</p>
</blockquote>
<p>Startup:</p>
<pre><code>services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
//password options
options.Password.RequireDigit = false;
// ...
})
</code></pre>
<p>I am using a standard ApplicationUser:</p>
<pre><code>public class ApplicationUser : IdentityUser
{
}
</code></pre>
<p>Register action in AccountController:</p>
<pre><code>public async Task<IActionResult> Register(RegisterViewModel viewModel)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = viewModel.UserName, Email = viewModel.Email };
var result = await _userManager.CreateAsync(user, viewModel.Password); //<-- Exception happens here
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
string errorData = "";
foreach (var error in result.Errors)
{
errorData += error.Description + '\n';
}
StoreErrorMessage("Failed to create the user!", errorData);
}
return View(viewModel);
}
</code></pre>
<p>I already tried the following:</p>
<ul>
<li>Adding <code>DbSet<ApplicationUser></code> to <code>AplicationContext</code></li>
<li>I did create and apply a new migration via <code>dotnet ef</code></li>
</ul> | 0 |
How do I see the console.log output of a background script in a Firefox WebExtension? | <p>Does anyone know how to see the output from a <code>console.log()</code> call in a background script? I can see the output from the same in a content script. Here is a simple script that I am testing this with:</p>
<p>Here is my <em>background.js</em>:</p>
<pre><code>console.log("Message from background.js");
</code></pre>
<p>Here is my <em>manifest.json</em>:</p>
<pre><code>{
"name": "TestBed",
"manifest_version": 2,
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Click"
},
"applications": {
"gecko": {
"id": "[email protected]",
"strict_min_version": "48.0a1"
}
}
}
</code></pre>
<p>I've also tried this in the background script:</p>
<pre><code>chrome.browserAction.onClicked.addListener(function() {
console.log('Message from background.js onclicked handler');
});
</code></pre>
<p>I have even uninstalled Firebug as some other posts have suggested, but that made no difference either (note that the <code>console.log</code> in content scripts works).</p> | 0 |
Is Spark RDD cached on worker node or driver node (or both)? | <p>Can any one please correct my understanding on persisting by Spark.</p>
<p>If we have performed a cache() on an RDD its value is cached only on those nodes where actually RDD was computed initially.
Meaning, If there is a cluster of 100 Nodes, and RDD is computed in partitions of first and second nodes. If we cached this RDD, then Spark is going to cache its value only in first or second worker nodes.
So when this Spark application is trying to use this RDD in later stages, then Spark driver has to get the value from first/second nodes.</p>
<p>Am I correct?</p>
<p>(OR)</p>
<p>Is it something that the RDD value is persisted in driver memory and not on nodes ?</p> | 0 |
Use mutate_at to change multiple column types | <p>I'm trying to use <code>dplyr</code> to tidy a dataset. The columns I want to change have a character string that's really a double but with comma instead of a decimal point. So far I got this:</p>
<pre><code>presupuesto_2016 <- read_csv( "http://datos.gob.ar/dataset/89f1a2dd-ad79-4211-87b4-44661d81ac0d/resource/84e23782-7d52-4724-a4ba-2f9621fa5f4e/download/presupuesto-2016.csv")
names(presupuesto_2016) <- str_replace(names(presupuesto_2016), "\uFEFF", "")
presupuesto_2016 %>%
mutate_at(starts_with("monto_"),
str_replace, pattern = ",", replacement = "\\.") %>%
mutate_at(starts_with("monto_"), funs(as.numeric))
</code></pre>
<p>But this manages to change every column to numeric. What am I doing wrong here?</p> | 0 |
Lambda expression to add objects from one list to another type of list | <p>There is a <code>List<MyObject></code> and it's objects are required to create object that will be added to another List with different elements : <code>List<OtherObject></code>. </p>
<p>This is how I am doing,</p>
<pre><code>List<MyObject> myList = returnsList();
List<OtherObj> emptyList = new ArrayList();
for(MyObject obj: myList) {
OtherObj oo = new OtherObj();
oo.setUserName(obj.getName());
oo.setUserAge(obj.getMaxAge());
emptyList.add(oo);
}
</code></pre>
<p>I'm looking for a <code>lamdba</code> expression to do the exact same thing.</p> | 0 |
React Native webview get url | <p>Webview component allowing me to specify a destination url, e.g. facebook.com</p>
<pre><code>render() {
return (
<WebView
source={{uri: https://www.facebook.com}}
style={{marginTop: 20}}
/>
);
}
</code></pre>
<p>However, If i click the link in facebook, how can I get the url being clicked or the url being landed?</p> | 0 |
How to change an image source dynamically in XAML using MVVM with Xamarin | <p>I'm trying to change an image source property on a <code>ContentPage</code>. I´m using a binding context to do this. But, even if I change the source in my model view, this don't update the image in my view.</p>
<pre><code>UpdateMethod()
{
imageSource1 = imageSource[1];
}
public string ImageSource1
{
get
{
return imageSource1;
}
set
{
imageSource1 = value;
this.Notify("ImageSource1");
}
}
</code></pre>
<p>The XAML:</p>
<pre><code><ContentView HorizontalOptions="Center" Grid.Row="0" >
<Image ClassId = "1" Source="{Binding ImageSource1}" BindingContextChanged="Handle_BindingContextChanged">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OnTapGestureRecognizerTappedCommand1}" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>
</ContentView>
</code></pre> | 0 |
Activity has leaked window that was originally added here | <p>I am getting this error when i try to execute this class file.I am not getting what the error is..?can anyone pls identify where i am going wrong..?</p>
<p><strong>Mnst.class</strong></p>
<pre><code> //this is class file
public class Mnst extends AppCompatActivity implements
View.OnClickListener {
Button btnDatePicker,save;
EditText txtDate;
EditText txtnormal;
private int mYear, mMonth, mDay;
String value;
private String vault;
public static final String SHARED_PREF_NAME = "myloginapp";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String MYLAST_SHARED_PREF = "my_last_period";
public static final String NORMAL_SHARED_PREF = "normal_cycle";
public static final String REVISED_SHARED_PREF = "revised_cycle";
public static final String NEXT_SHARED_PREF = "next_period_date";
public static final String PREDICTEDSTART_SHARED_PREF = "predicted_start_date";
public static final String PREDICTEDEND_SHARED_PREF = "predicted_end_date";
DatePickerDialog datePickerDialog;
private boolean loggedIn = false;
public static final String UPLOAD_URL = "http://oursite.com/predict.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mnst);
btnDatePicker=(Button)findViewById(R.id.btn_date);
save = (Button)findViewById(R.id.save);
txtDate=(EditText)findViewById(R.id.in_date);
txtnormal = (EditText) findViewById(R.id.in_date1);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
btnDatePicker.setOnClickListener(this);
save.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == btnDatePicker) {
// Get Current Date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
value = txtDate.getText().toString();
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if( v == save)
{
registerUser();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
}
/*@Override
protected void onDestroy() {
if(datePickerDialog !=null && datePickerDialog.isShowing())
{
//<HERE I WANT THE STATE TO BE SAVED IN THE BUNDLE>
datePickerDialog.dismiss();
}
super.onDestroy();
}*/
private void registerUser() {
final String vault_no = vault;
final String my_last_period = txtDate.getText().toString();
final String normal_cycle = txtnormal.getText().toString();
register(vault_no,my_last_period,normal_cycle);
}
public void register(String vault_no , String my_last_period , String normal_cycle){
class RegisterUser extends AsyncTask<String, Integer, JSON> {
ProgressDialog loading;
RequestHandler7 ruc = new RequestHandler7();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Mnst.this, "Please Wait",null, true, true);
}
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(JSON s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Welcome to Miisky",Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences1 = Mnst.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences1.edit();
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(MYLAST_SHARED_PREF, s.my_last_period);
editor.putString(NORMAL_SHARED_PREF, s.normal_cycle);
editor.putString(REVISED_SHARED_PREF, s.revised_cycle);
editor.putString(NEXT_SHARED_PREF, s.next_period_date);
editor.putString(PREDICTEDSTART_SHARED_PREF, s.predicted_start_date);
editor.putString(PREDICTEDEND_SHARED_PREF, s.predicted_end_date);
editor.apply();
Intent i = new Intent(Mnst.this,DisplayMnst.class);
startActivity(i);
}
@Override
protected JSON doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("vault_no", params[0]);
data.put("my_last_period" , params[1]);
data.put("normal_cycle", params[2]);
JSON result = ruc.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(vault_no,my_last_period,normal_cycle);
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have added the RequestHandler class..</p>
<p><strong>RequestHandler7</strong></p>
<pre><code>public class RequestHandler7 {
public JSON sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new Gson().fromJson(sb.toString(),JSON.class);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
</code></pre>
<hr>
<p><strong>Log</strong></p>
<p>This is my logcat error..here it is showing "Activity com.example.android.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here"</p>
<pre><code>E/WindowManager: Activity com.example.miisky.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
android.view.WindowLeaked: Activity com.example.miisky.Mnst has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@5383cdc0 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at com.example.miisky.Mnst$1RegisterUser.onPreExecute(Mnst.java:132)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.example.miisky.Mnst.register(Mnst.java:178)
at com.example.miisky.Mnst.registerUser(Mnst.java:118)
at com.example.miisky.Mnst.onClick(Mnst.java:95)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
</code></pre> | 0 |
Unsure how to resolve "Cannot resolve constructor" error | <p>I am getting an error on a particular fragment (which is one of three on a tabbed activity). The error is:</p>
<pre><code>Cannot resolve constructor 'ArrayAdapter(layout.OneWayFragmen,int,java.lang.string[])'
</code></pre>
<p>I am trying to include and autocomplete field on one fragment of a tabbed activity. The java class in question is below:</p>
<pre><code>package layout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.example.alibasmaci.maral.R;
/**
* A simple {@link Fragment} subclass.
*/
public class OneWayFragment extends Fragment {
public OneWayFragment() {
// Required empty public constructor
}
public static OneWayFragment newInstance() {
OneWayFragment fragment = new OneWayFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one_way, container, false);
String[] cities =
{"Ottawa - Carp CYRP",
"Toronto - Billy Bishop CYYZ",
"Montreal - St. Hubert CYHU"
};
AutoCompleteTextView actvDeparture;
actvDeparture = (AutoCompleteTextView) rootView.findViewById(R.id.actvDeparture);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.select_dialog_item,cities);
actvDeparture.setThreshold(1);
return rootView;
}
}
</code></pre>
<p>The error I am referring to is a result of this line:</p>
<pre><code>ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.select_dialog_item,cities);
</code></pre>
<p>Any thoughts on how to fix this?</p>
<p>Thanks</p> | 0 |
How to Run a Python Script from a Rails Application? | <p>I am working on a rails application now that needs to run a single python script whenever a button is clicked on our apps home page. I am trying to figure out a way to have rails run this script, and both of my attempts so far have failed. </p>
<p>My first try was to use the exec(..) command to just run the "python script.py", but when I do this it seems to run the file but terminate the rails server so I would need to manually reboot it each time.</p>
<p>My second try was to install the gem "RubyPython" and attempt from there, but I am at a loss at what to do once I have it running.. I can not find any examples of people using it to run or load a python script.</p>
<p>Any help for this would be appreciated.</p> | 0 |
Angular 2 render page without router-outlet | <p>I have HTML template with slide menu and top nav menu and block for render main path page.
like this:</p>
<pre><code>...
<div class="content-wrapper">
<router-outlet></router-outlet>
</div>
...
</code></pre>
<p>But after it, my login page render in this <strong>content-wrapper</strong> block.
How to write some code for render <strong>LoginPage</strong> without <strong>route-outline</strong> component? (for not render top nav and slide menus)</p> | 0 |
Swagger UI does not list any of the controller/end points though I am able to see the json under v2/api-docs endpoint | <p>I am not able to get my Swagger UI to work with my project. Swagger UI comes up fine but it does not list any of my REST controllers.</p>
<p>I am using SPRING 4.2.6.RELEASE and Swagger 2.5.0 . My rest services are deployed to Tomcat 7.0.54 .</p>
<p>When Tomcat 7.0.54 comes up, it is able to fetch the swagger end points.
I am able to hit the endpoint v2/api-docs that fetches the json messages.
I am also able to hit the swagger-ui but I dont see any controllers listed.
The dropdowns are empty, as below</p>
<p><a href="https://i.stack.imgur.com/GMsax.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GMsax.png" alt="enter image description here"></a></p>
<p>**The issue I am facing currently is that </p>
<ol>
<li>I am not able to fetch the /swagger-resources/configuration/ui, when I launch the swagger UI I get 404 (Not Found) errror while the UI is trying to fetch /swagger-resources/configuration/ui . I have setup resource handlers for swagger-resources, but that does not seem to help. Can you please let me know what could be missing?</li>
<li>Should I be seeing resources folder under META-INF in my expanded WAR? Should there be any springfox related files/folder inside META-INF?
**</li>
</ol>
<p><strong>Maven dependency for Swagger</strong>
<br>
io.springfox
springfox-swagger2
2.5.0
<br>
io.springfox
springfox-swagger-ui
2.5.0
</p>
<p><strong>Below is my SwaggerCongifuration</strong></p>
<pre><code>@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api() {
List<SecurityContext> security = new ArrayList<SecurityContext>();
security.add(securityContext());
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/").securityContexts(security);
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.forPaths(PathSelectors.regex("/"))
.build();
}
}
</code></pre>
<p><strong>Below is my WebConfig.xml</strong></p>
<pre><code>@EnableWebMvc
@Configuration
@Import(SwaggerConfiguration.class)
@ComponentScan("com.bank.direct.services")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> pConverters) {
pConverters.add(RestUtils.getJSONMessageConverter());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
</code></pre>
<p><strong>Below is the SecurityCongif.xml</strong></p>
<pre><code>@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationService _authenticationService;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder pAuth) throws Exception {
pAuth.userDetailsService(_authenticationService);
}
@Override
protected void configure(HttpSecurity pHttp) throws Exception {
// Enable HTTP caching
pHttp.headers().cacheControl().disable();
// Configure security
pHttp.httpBasic()
// -- Allow only authenticated request
.and()
.authorizeRequests()
.anyRequest().authenticated()
// -- Logout configuration
.and()
.logout()
.logoutUrl("/rest/users/logout/")
.deleteCookies("XSRF-TOKEN")
.logoutSuccessUrl("/static/index.html")
.invalidateHttpSession(true)
// -- CSRF configuration
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
</code></pre>
<p>Rest Controller class as below</p>
<pre><code>@RestController
@RequestMapping(value = "/vehicles", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class VehicleResource extends Resource {
@Autowired
private IVehicleService _vehicleService;
@RequestMapping(value = "/brands", method = RequestMethod.GET)
public APIResponseEntity getBrands(WebRequest pWebRequest) {
IUser user = getUser(pWebRequest);
BrandCriteria criteria = new BrandCriteria();
criteria.setLanguageCode(user.getLanguageCode());
List<Brand> res = _vehicleService.getBrands(user, criteria);
return newResponseOK(res);
}
@RequestMapping(value = "/brands/{brand_code}", method = RequestMethod.GET)
public APIResponseEntity getBrand(WebRequest pWebRequest, @PathVariable("brand_code") String pBrandCode) {
IUser user = getUser(pWebRequest);
BrandCriteria criteria = new BrandCriteria();
criteria.setLanguageCode(user.getLanguageCode());
criteria.setBrandCode(pBrandCode);
List<Brand> res = _vehicleService.getBrands(user, criteria);
return newResponseOK(res);
}
}
</code></pre> | 0 |
Replace @Value property within @Configuration during Spring Boot test | <h1>Scenario</h1>
<p>I've got a Spring Boot application with a <code>@Configuration</code> annotated Spring configuration class which contains some <code>@Value</code> annotated fields. For testing I want to replace these field values with custom test values.</p>
<p>Unfortunately these test values cannot be overridden using a simple properties file, (String) constants or similar, instead I <strong>must</strong> use some custom written property resolving Java class (e.g. <code>TargetProperties.getProperty("some.username")</code>).</p>
<p>The problem I have is that when I add a custom <code>PropertySource</code> to the <code>ConfigurableEnvironment</code> within my test configuration, it's already too late because this <code>PropertySource</code> will be added <strong>after</strong> the e.g. <code>RestTemplate</code> has been created.</p>
<h1>Question</h1>
<p>How can I override <code>@Value</code> annotated fields <em>within</em> a <code>@Configuration</code> class with properties obtained <em>programmatically</em> via custom Java code <em>before</em> anything else gets initialized?</p>
<h1>Code</h1>
<h2>Production Configuration Class</h2>
<pre><code>@Configuration
public class SomeConfiguration {
@Value("${some.username}")
private String someUsername;
@Value("${some.password}")
private String somePassword;
@Bean
public RestTemplate someRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(
new BasicAuthorizationInterceptor(someUsername, somePassword));
return restTemplate;
}
}
</code></pre>
<h2>Test Configuration Class</h2>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {
@SpringBootConfiguration
@Import({MySpringBootApp.class, SomeConfiguration.class})
static class TestConfiguration {
@Autowired
private ConfigurableEnvironment configurableEnvironment;
// This doesn't work:
@Bean
@Lazy(false)
// I also tried a @PostConstruct method
public TargetPropertiesPropertySource targetPropertiesPropertySource() {
TargetPropertiesPropertySource customPropertySource =
new TargetPropertiesPropertySource();
configurableEnvironment.getPropertySources().addFirst(customPropertySource);
return customPropertySource;
}
}
}
</code></pre> | 0 |
Writing a BytesIO object to a file, 'efficiently' | <p>So a quick way to write a BytesIO object to a file would be to just use:</p>
<pre><code>with open('myfile.ext', 'wb') as f:
f.write(myBytesIOObj.getvalue())
myBytesIOObj.close()
</code></pre>
<p>However, if I wanted to iterate over the myBytesIOObj as opposed to writing it in one chunk, how would I go about it? I'm on Python 2.7.1. Also, if the BytesIO is huge, would it be a more efficient way of writing by iteration?</p>
<p>Thanks</p> | 0 |
Formatting XML from PowerShell | <p>I have a PowerShell script that runs a stored procedure which returns XML. I then export the XML into a file but when I open the file, each line has 3 dots at the end and the line isn't complete. This is with using <code>out-file</code>.</p>
<p>When I use <code>Export-Clixml</code> the XML that is returned from the query is dumped in a tag called <code><props></code> which is not one of my tags.</p>
<p>I am unsure where to go from here to save my XML in it's original format.</p>
<p>The PowerShell Script that I am using is similar to this:</p>
<pre><code>$Date = Get-Date -format "yyyyMMdd_HHmm"
$File = "C:\Temp\MyFile"+$Date+".xml"
$Query = "exec dbo.usp_MyProc"
Invoke-Sqlcmd -Query $Query -database MyDatabase -ServerInstance MyServer | out-file $File -Encoding utf8
</code></pre> | 0 |
Use S3DistCp to copy file from S3 to EMR | <p>I am struggling to find a way to use S3DistCp in my AWS EMR Cluster.</p>
<p>Some old examples which show how to add s3distcp as an EMR step use <code>elastic-mapreduce</code> command which is not used anymore.</p>
<p>Some other sources suggest to use <code>s3-dist-cp</code> command, which is not found in current EMR clusters. Even official documentation (<a href="http://docs.aws.amazon.com/ElasticMapReduce/latest/DeveloperGuide/UsingEMR_s3distcp.html" rel="nofollow noreferrer">online</a> and EMR developer guide 2016 pdf) present an example like this:</p>
<pre><code>aws emr add-steps --cluster-id j-3GYXXXXXX9IOK --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://mybucket/logs/j-3GYXXXXXX9IOJ/node/","--dest,hdfs:///output","--srcPattern,.*[azA-Z,]+"]
</code></pre>
<p>But there is no <code>lib</code> folder in the <code>/home/hadoop</code> path. I found some hadoop libraries in this folder: <code>/usr/lib/hadoop/lib</code>, but I cannot find <code>s3distcp</code> from anywhere.</p>
<p>Then I found that there are some libraries available in some S3 buckets. For example, from this <a href="https://stackoverflow.com/questions/14631152/copy-files-from-amazon-s3-to-hdfs-using-s3distcp-fails">question</a>, I found this path: <code>s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar</code>. This seemed to be a step in the right direction, as adding a new step to a running EMR cluster from the AWS interface with these parameters started the step (which it didn't with previous attempts) but failed after ~15seconds:</p>
<pre><code>JAR location: s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar
Main class: None
Arguments: --s3Endpoint s3-eu-west-1.amazonaws.com --src s3://source-bucket/scripts/ --dest hdfs:///output
Action on failure: Continue
</code></pre>
<p>This resulted in the following error:</p>
<pre><code>Exception in thread "main" java.lang.RuntimeException: Unable to retrieve Hadoop configuration for key fs.s3n.awsAccessKeyId
at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.getConfigOrThrow(ConfigurationCredentials.java:29)
at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.<init>(ConfigurationCredentials.java:35)
at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileListS3(S3DistCp.java:85)
at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileList(S3DistCp.java:60)
at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:529)
at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:216)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
at com.amazon.external.elasticmapreduce.s3distcp.Main.main(Main.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
</code></pre>
<p>I thought this may have been caused by the incompatibility of my S3 location (same as the endpoint) and the location of the s3distcp script, which was from us-east. I replaced it with eu-west-1 and still got the same error about the authentication.
I have used a similar setup to run my scala scripts (Custom jar type with "command-runner.jar" script with the first argument "spark-submit" to run a spark job and this works, I have not had this problem with the authentication before.</p>
<p><strong>What is the simplest way to copy a file from S3 to an EMR cluster?</strong> Either by adding an additional EMR step with AWS SDK (for Go lang) or somehow inside the Scala spark script? Or from the AWS EMR interface, but not from CLI as I need it to be automated.</p> | 0 |
How to initialize an ArrayList with lombok @Builder and @Data | <p>Using lombok for a project, I have an ArrayList. It's null because it's never initialized. I originally initialized this in the constructor before I decided to use lombok to remove the bulk of boilerplate code. </p>
<p>What's the simplest example of getting it to work?</p>
<p>Example : Calling refresh throws a null pointer after creating a builder (Note: I've omitted variables that are used in the builder, but <code>parameters</code> is not mentioned in the builder so perhaps I need to do something with it).</p>
<pre><code>@Builder
public @Data class RMF_Objective {
private ArrayList<String> parameters;
public void refresh(){
parameters.clear(); // Clear for now
}
}
</code></pre> | 0 |
Angular 2 - Singleton Services? | <p>In Angular 1 I frequently used <strong>factories</strong> for services to store shared state accessible by many components. It looks like in Angular 2 all services that are injected as @Injectable() are created each time, thus losing the shared state.</p>
<p>I 'register' the service at the root module's <code>providers</code> meta key, but still I get a transient instance.</p>
<p>What I have:</p>
<pre><code>Injectable()
export class ArtistService {
constructor(private http:Http) {
// firing on each injection
console.log("ArtistService ctor");
}
}
</code></pre>
<p>to call it in a component then:</p>
<pre><code>@Component({
selector: 'artist-display',
templateUrl: './artistDisplay.html',
})
export class ArtistDisplay {
constructor(private artistService: ArtistService) {
// instance is fine but transient
}
}
</code></pre>
<p>And the definition of the module:</p>
<pre><code>@NgModule({
declarations: [...],
imports: [BrowserModule, FormsModule, HttpModule,
RouterModule.forRoot(rootRouterConfig)],
providers : [
ArtistService,
// make sure you use this for Hash Urls rather than HTML 5 routing
{ provide: LocationStrategy, useClass: HashLocationStrategy },
],
bootstrap: [AppComponent]
})
</code></pre>
<p>I suspect there is maybe some other way to 'register' the <code>ArtistService</code> so it stays loaded as a static instance? Is that possible via DI or is it necessary to create a static instance method manually?</p>
<p><strong>Update:</strong><br>
Turns out that the above code <strong>does work</strong>. I was looking in the wrong place along with a logic error that caused data not to cache correctly. </p>
<p>The above code works and assigning the service in the <code>providers</code> section of the <strong>top level AppModule</strong> is the key to making the parent reference stay loaded for the duration of the AppComponent. which effectively stays loaded for the lifetime of the app providing the <strong>Singleton</strong> instance. </p>
<p>To get a <strong>transient</strong> instance you can declare the <code>providers</code> meta tag and the service name <strong>on the actual component</strong> which will then create the service whenever the component is loaded/re-loaded.</p> | 0 |
How do you concatenate multiple columns in a DataFrame into a another column when some values are null? | <p><code>def column_concat(a,b):
return concat(a,b)<br>
searches_df = searches_df.withColumn('unique_id',reduce(column_concat,(searches_df[col] for col in search_parameters)))
</code></p>
<p>This works except when a column contains a null value, then the whole concatenated string is null. I'd like the a place holder or some character instead in the concatenated string. </p> | 0 |
c++: function cannot be overloaded | <p>I am encountering a compile time error with the following output:</p>
<pre><code>$ g++ -ggdb `pkg-config --cflags opencv` -o `basename main.cpp .cpp` main.cpp StringMethods/StringMethods.cpp `pkg-config --libs opencv` -std=c++0x
In file included from main.cpp:2:0:
VideoFile.hpp:32:10: error: ‘bool VideoFile::fileExists(const string&)’ cannot be overloaded
bool fileExists(const std::string & path)
^
VideoFile.hpp:15:10: error: with ‘bool VideoFile::fileExists(const string&)’
bool fileExists(const std::string & path);
</code></pre>
<p>However, I do not see how that error makes sense, because I have only function declaration which I directly copied and pasted when writing the definition.</p>
<pre><code>class VideoFile
{
private:
std::string filePath;
bool fileExists(const std::string & path);
public:
VideoFile(const std::string & path)
:filePath(path)
{
filePath = StringMethods::trim(path);
if (!fileExists(filePath))
throw std::runtime_error("The file: " + filePath + " was not accessible");
}
~VideoFile()
{
}
bool fileExists(const std::string & path)
{
std::ifstream file(path);
return file.good();
}
};
</code></pre> | 0 |
How to verify element/text is present in dropdown list using selenium java | <p>How to verify element/text is present in drop down list using selenium java</p>
<pre><code>new Select(driver.findElement(By.id("airlineid"))).selectByVisibleText("Delta");
</code></pre> | 0 |
How to disable UC browser news feeds? | <p>On the latest update of UCBrowser ( V11.0.0.828 ) android lots of annoying news feeds are there. Is there any way to disable it?</p> | 0 |
SonarQube: Coverage on New Code never calculated | <p>I have set up SonarQube, Maven and Cobertura to upload unit test coverage at every build run. I want to use the differential views to get coverage for the delta (new code only).</p>
<p>The coverage itself is successfully uploaded, and I can see the delta in lines of code. However, I can't get the "Coverage on new Code" to work. </p>
<p>I tried different values for the leak period, including <code>previous_analysis</code> and <code>previous_version</code> (changing the version from 1.0 to 1.1 in the new analysis). I also used <code>-Dsonar.projectDate</code> to simulate a past date of analysis but still no luck.</p>
<p>Any thoughts?</p>
<p><a href="https://i.stack.imgur.com/SJG3l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SJG3l.png" alt="enter image description here"></a></p> | 0 |
coloring cells in excel with pandas | <p>I need some help here. So i have something like this </p>
<pre><code>import pandas as pd
path = '/Users/arronteb/Desktop/excel/ejemplo.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx,'Sheet1')
df['is_duplicated'] = df.duplicated('#CSR')
df_nodup = df.loc[df['is_duplicated'] == False]
df_nodup.to_excel('ejemplo.xlsx', encoding='utf-8')
</code></pre>
<p>So basically this program load the <code>ejemplo.xlsx</code> (ejemplo is example in Spanish, just the name of the file) into <code>df</code> (a <code>DataFrame</code>), then checks for duplicate values in a specific column. It deletes the duplicates and saves the file again. That part works correctly. The problem is that instead of removing duplicates, I need highlight the cells containing them with a different color, like yellow.</p> | 0 |
Cordova / Ionic build android Gradle error: Minimum supported Gradle version is 2.14.1. Current version is 2.13 | <p>This is a solution to the above error that I want to document. I found other similar posts, but none described how this error can be associated with Cordova or Ionic.</p>
<p>If you are not careful, there can be a mismatch between the version of Gradle that Android Studio uses and the version of Gradle that Cordova / cordova-android specifies in its auto-generated application code. As you know, running</p>
<pre><code>$ cordova platform add android
</code></pre>
<p>(or <code>$ ionic platform add android</code>, if you are building an Ionic app) creates the native application code at the-project/platforms/android. </p>
<p>Inside that folder, the file: /the-project/platforms/android/cordova/lib/builders/GradleBuilder.js exports a variable as shown below:</p>
<pre><code>var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'http\\://services.gradle.org/distributions/gradle-x.y-all.zip';
</code></pre>
<p>Where x and y depened on which version of Cordova / cordova-android are being used to build the native application code. </p>
<p>When you run</p>
<pre><code>$ cordova build android
</code></pre>
<p>The version of Gradle specified in the <code>distributionUrl</code> var is the version used for the build.</p>
<p>Now here comes the tricky part. When you import the project into Android Studio, you will most likely get a message strongly recommending that you upgrade Gradle to a newer version, as shown below: </p>
<p><a href="https://i.stack.imgur.com/N1ytd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/N1ytd.png" alt="enter image description here"></a>
If you do this, Android Studio will download a new version of Gradle and store it locally and configure the project to use the newly download local Gradle distribution, which is the radio option below the selected “Use default grade wrapper”, which I ended up deselecting because this will cause errors.</p>
<p><a href="https://i.stack.imgur.com/geQN9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/geQN9.png" alt="enter image description here"></a> </p>
<p>This will cause problems because Android Studio and Cordova will now be attempting to build the application with different versions of Gradle and you will get build errors within Android Studio and also with </p>
<pre><code>$ cordova build android
</code></pre>
<p>in the command line. The solution with Cordova apps is to always keep the Android Studio project set to "Use default gradle wrapper" and ignore the tempting messages to upgrade. If you do want to use a newer version of Gradle, you can always change the distributionUrl var in the file mentioned above (however Cordova strongly discourages modifying code within the platforms folder since it is easily overwritten). At the time of writing this, I cannot tell is there is a way to set the Gradle version at the </p>
<pre><code>$ cordova platform add android
</code></pre>
<p>step, which is when you would want to do it so you are never directly modifiying code inside of the-project/platforms</p> | 0 |
Get total number of files and Sub folders in a folder | <p>I have a task to carry out 3 times a day on a WS2012R2 to get the Disk size, total number of files and folders including subdirectories from a folder on a remote server.</p>
<p>Currently I get this information by RDP'ing to the target, navigating to the folder and right clicking the folder to copy the info:</p>
<p><a href="https://i.stack.imgur.com/JxXFY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JxXFY.png" alt="enter image description here"></a></p>
<p>I have already tried the PowerShell script :</p>
<pre><code>Get-ChildItem E:\Data -Recurse -File | Measure-Object | %{$_.Count}
</code></pre>
<p>and other PowerShell scripts.</p>
<p>Which produced countless errors pertaining to not having permissions for some sub directories or simply gave results I didn't want such.</p>
<p>I have tried VBscript but VBscript simply cannot get this information.</p> | 0 |
How to set Entity Framework Core migration timeout? | <p>I'm using the latest (1.0.0) version of EF Core. I have a migration to run on a quite big database.</p>
<p>I run:</p>
<blockquote>
<p>dotnet ef database update -c ApplicationDbContext</p>
</blockquote>
<p>And get:</p>
<blockquote>
<p>Timeout expired. The timeout period elapsed prior to completion of
the operation or the server is not responding.</p>
</blockquote>
<p>In the connection string I explicitly set the timeout like so:</p>
<blockquote>
<p>Connect Timeout=150000</p>
</blockquote>
<p>Unfortunately, it didn't help. How should I do this?</p> | 0 |
Get current location from react-router-redux | <p>How do you get the current location when using "react-router-redux"?</p>
<p>This is the <code>routing</code> state:</p>
<pre><code>{
routing: {
locationBeforeTransition: {
pathname: "/foo",
search: "",
hash: "",
state: null,
action: "PUSH",
key: "e8jfk"
},
query: null,
$searchBase: {
search: "",
searchBase: ""
}
}
}
</code></pre>
<p>I can clearly access the current location as <code>state.routing.locationBeforeTransition.pathname</code>, but the name "locationBeforeTransition" seems like it would be the previous page location, not the current one. It also seems odd that this is the only property in my routing state. I suspect I am doing something wrong.</p>
<p>Here is a simplified reducer that only has routing:</p>
<p><strong>reducer.js</strong></p>
<pre><code>import { combineReducers, createStore, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import { browserHistory } from 'react-router';
import thunkMiddleware from 'redux-thunk';
const reducer = combineReducers({
routing: routerReducer,
});
export const store = createStore(reducer, {}, compose(
applyMiddleware(
routerMiddleware(browserHistory),
thunkMiddleware
),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
</code></pre> | 0 |
How to tell jenkins not to kill processes after successful execution of job in multijob project? | <p>I have a jenkins <strong>multijob project</strong>.</p>
<p><strong>In 1st phase</strong>, I start databases and build core part.</p>
<p>sample shell command to start Mongodb:</p>
<pre><code>/root/software/mongodb-linux-x86_64-2.6.3/bin/mongod&
</code></pre>
<p><strong>In 2nd phase</strong>, I have various jobs to build some clients.</p>
<p>After 1st phase job, after starting servers and building core part. I see logs- </p>
<pre><code>Process leaked file descriptors. See http://wiki.jenkins-ci.org/display/JENKINS/Spawning+processes+from+build for more information
2016-08-26T20:23:00.815+0530 [signalProcessingThread] got signal 15 (Terminated), will terminate after current cmd ends
2016-08-26T20:23:00.833+0530 [signalProcessingThread] now exiting
2016-08-26T20:23:00.879+0530 [signalProcessingThread] dbexit:
2016-08-26T20:23:00.903+0530 [signalProcessingThread] shutdown: going to close listening sockets...
2016-08-26T20:23:00.903+0530 [signalProcessingThread] closing listening socket: 7
2016-08-26T20:23:00.903+0530 [signalProcessingThread] closing listening socket: 8
2016-08-26T20:23:00.903+0530 [signalProcessingThread] removing socket file: /tmp/mongodb-27017.sock
Finished: SUCCESS
</code></pre>
<p>This is stopping all the databases and build is failing for phase2 jobs.</p>
<p>How to tell jenkins not to kill processes after a job?</p> | 0 |
How to get the current fragment displayed in a specific tab of a viewpager? | <p>I want to get the last fragment in the backstack, or the current displayed it's the same for me, in the <code>tab b_1</code>. As you can see in the following image, I have a ViewPager, and another one inner <code>tab b</code>. Thus there are four current fragments displayed.</p>
<p><strong>Question</strong>: How can I get the <code>Fragment 2</code> instance?</p>
<p>I have seen another solutions, but none works for this scenario.</p>
<p><strong>Annotation:</strong> The fragment to return is not necessary the hosted in the ViewPager. I can have opened two more fragments in a tab.</p>
<p><a href="https://i.stack.imgur.com/S1aP1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S1aP1.png" alt="scenario"></a></p>
<p>With this method I get all the current visible fragments, but not the one specific I want.</p>
<pre><code>public ArrayList<Fragment> getVisibleFragment() {
List<Fragment> fragments = getSupportFragmentManager().getFragments();
ArrayList<Fragment> visibleFragments = new ArrayList<>();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
visibleFragments.add(fragment);
}
}
return visibleFragments;
}
</code></pre>
<p><strong>Some interesting code</strong></p>
<p>activity_main.xml</p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>MainActivity.java</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private static ViewPagerAdapter adapter;
private static ViewPager viewPager;
private TabLayout tabLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager();
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupViewPager() {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// Wrap with HostFragment to get separate tabbed nagivation.
adapter.addFrag(HostFragment.newInstance(new Fragment1()), null);
adapter.addFrag(HostFragment.newInstance(new RootFragment2()), null);
adapter.addFrag(HostFragment.newInstance(new Fragment4()), null);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
public void openNewFragment(Fragment fragment) {
HostFragment hostFragment = (HostFragment) adapter.getItem(viewPager.getCurrentItem());
hostFragment.replaceFragment(fragment, true);
}
}
</code></pre>
<p>fragment_host.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hosted_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</code></pre>
<p>HostFragment.java</p>
<pre><code>/**
* This class implements separate navigation for a tabbed viewpager.
*
* Based on https://medium.com/@nilan/separate-back-navigation-for-
* a-tabbed-view-pager-in-android-459859f607e4#.u96of4m4x
*/
public class HostFragment extends BackStackFragment {
private Fragment fragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_host, container, false);
if (fragment != null) {
replaceFragment(fragment, false);
}
return view;
}
public void replaceFragment(Fragment fragment, boolean addToBackstack) {
if (addToBackstack) {
getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).addToBackStack(null).commit();
} else {
getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
}
}
public static HostFragment newInstance(Fragment fragment) {
HostFragment hostFragment = new HostFragment();
hostFragment.fragment = fragment;
return hostFragment;
}
public Fragment getFragment() {
return fragment;
}
}
</code></pre>
<p>fragment2_root.xml</p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment2_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tab2_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/tab2_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</LinearLayout>
</code></pre>
<p>RootFragment2.java</p>
<pre><code>public class RootFragment2 extends Fragment {
private ViewPagerAdapter adapter;
private ViewPager viewPager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment.
View root = inflater.inflate(R.layout.fragment2_root, container, false);
viewPager = (ViewPager) root.findViewById(R.id.tab2_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) root.findViewById(R.id.tab2_tabs);
tabLayout.setupWithViewPager(viewPager);
return root;
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
// Wrap with HostFragment to get separate tabbed nagivation.
adapter.addFrag(HostFragment.newInstance(new Fragment2()), null);
adapter.addFrag(HostFragment.newInstance(new Fragment3()), null);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
}
public ViewPagerAdapter getAdapter() {
return adapter;
}
public ViewPager getViewPager() {
return viewPager;
}
}
</code></pre> | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.