id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
33,408,636
Convert column in data.frame to date
<p>My dataframe</p> <pre><code>a1 &lt;- c("a","a","b","b","c","d","e","e") b2 &lt;- c("01.01.2015", "02.02.2015", "14.02.2012", "16.08.2008", "17.06.2003", "31.01.2015", "07.01.2022", "09.05.2001") c3 &lt;- c("1a", "2b", "3c", "4d", "5e", "6f", "7g", "8h") d3 &lt;- c(1:8) df2 &lt;- data.frame(a1,b2,c3,d3, stringsAsFactors = F) </code></pre> <p>My code.</p> <pre><code>library(dplyr) library(magrittr) test &lt;- df2 %&gt;% group_by(a1) %&gt;% as.Date(b2, format = "%d.%m.%Y") </code></pre> <blockquote> <p>Error in as.Date.default(., b2, format = "%d.%m.%Y") : do not know how to convert '.' to class “Date”</p> </blockquote> <p>Well, I tried without the pipe:</p> <pre><code>df$b2 &lt;- as.Date(df$b2, format = "%d.%m.%Y") </code></pre> <blockquote> <p>Error in df$b2 : object of type 'closure' is not subsettable</p> </blockquote> <p>First: Why do I get two different error messages since I am (for my understanding) am doing the same?</p> <p>Second, why cant I convert my column to date?!</p> <p>I might should add that I am aware of using <code>mutate</code> to alter the column as <code>date</code> format. But I wonder why my approach is not working.</p>
33,408,671
1
7
null
2015-10-29 07:53:38.993 UTC
5
2021-12-22 03:53:50.81 UTC
2015-10-29 08:00:53.213 UTC
user3710546
null
null
3,935,035
null
1
9
r|date|dplyr|magrittr
87,729
<p>Do the transformations within <code>mutate</code></p> <pre><code>df2 %&gt;% group_by(a1) %&gt;% mutate(b2=as.Date(b2, format = &quot;%d.%m.%Y&quot;)) # a1 b2 c3 d3 # (chr) (date) (chr) (int) #1 a 2015-01-01 1a 1 #2 a 2015-02-02 2b 2 #3 b 2012-02-14 3c 3 #4 b 2008-08-16 4d 4 #5 c 2003-06-17 5e 5 #6 d 2015-01-31 6f 6 #7 e 2022-01-07 7g 7 #8 e 2001-05-09 8h 8 </code></pre> <p>If we need to do only the transformation, we don't need to group by 'a1'.</p> <pre><code>mutate(df2, b2= as.Date(b2, format= &quot;%d.%m.%Y&quot;)) </code></pre> <p>By using <code>%&lt;&gt;%</code> operator from <code>magrittr</code>, we can transform in place.</p> <pre><code>df2 %&lt;&gt;% mutate(b2= as.Date(b2, format= &quot;%d.%m.%Y&quot;)) </code></pre>
13,489,061
parse Json text to C# object in asp mvc 4
<p>I have a huge amount of customized attributes I want to save them in the DataBase, I was confused of how to store them in the database, i thought of storing them as a string separating them by </p> <p>(<code>=</code> => name , value) (<code>;</code> => attribute , attribute) but the code wasn't elegant at all!</p> <p>so i stat thinking of saving them as <code>Json</code> string but I couldn't found a <code>Json to object parser</code> </p> <p>while we need only to call <code>json()</code> to parse <code>object to json string</code> </p> <p>is there a better way than using json string and is there json string parser provided ?</p>
13,489,134
3
2
null
2012-11-21 08:24:30.633 UTC
2
2014-10-28 15:31:33.953 UTC
2014-10-28 15:31:33.953 UTC
null
30,913
null
1,225,246
null
1
12
c#|.net|asp.net-mvc|json|asp.net-mvc-4
39,152
<p>Many people use <a href="http://james.newtonking.com/projects/json-net.aspx">Json.net</a> for serialization</p> <pre><code>var log = JsonConvert.DeserializeObject&lt;YourObject&gt;(logJson) </code></pre> <p>and the other direction</p> <pre><code> var logJson = JsonConvert.SerializeObject(log); </code></pre>
13,445,701
How to create a static Map of String -> Array
<p>I need to create a static <code>Map</code> which maps a given <code>String</code> to an array of <code>int</code>'s.</p> <p>In other words, I'd like to define something like:</p> <pre><code>"fred" -&gt; {1,2,5,8} "dave" -&gt; {5,6,8,10,11} "bart" -&gt; {7,22,10010} ... etc </code></pre> <p>Is there an easy way to do this in Java?</p> <p>And if possible, I'd like to use <code>static</code> constants for both the <code>String</code> and the <code>int</code> values.</p> <p><strong>EDIT:</strong> To clarify what I meant by <code>static</code> constants for the values, and to give what I see to be the correct code, here is my first stab at the solution:</p> <pre><code>public final static String FRED_TEXT = "fred"; public final static String DAVE_TEXT = "dave"; public final static int ONE = 1; public final static int TWO = 2; public final static int THREE = 3; public final static int FOUR = 4; public final static HashMap&lt;String, int[]&gt; myMap = new HashMap&lt;String, int[]&gt;(); static { myMap.put(FRED_TEXT, new int[] {ONE, TWO, FOUR}); myMap.put(DAVE_TEXT, new int[] {TWO, THREE}); } </code></pre> <p>Note, these names are not what I'd actually be using. This is just a contrived example.</p>
13,446,515
6
0
null
2012-11-18 23:25:33.19 UTC
1
2020-07-13 22:39:49.107 UTC
2012-11-19 01:22:30.35 UTC
null
1,026,453
null
1,026,453
null
1
13
java|map|static
55,692
<p>You <em>don't</em> need to separate declaration and initialization. If you know how, it can all be done in one line!</p> <pre><code>// assumes your code declaring the constants ONE, FRED_TEXT etc is before this line private static final Map&lt;String, int[]&gt; myMap = Collections.unmodifiableMap( new HashMap&lt;String, int[]&gt;() {{ put(FRED_TEXT, new int[] {ONE, TWO, FOUR}); put(DAVE_TEXT, new int[] {TWO, THREE}); }}); </code></pre> <p>What we have here is an anonymous class with an <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="nofollow noreferrer">initialization block</a>, which is a block of code that executes on construction after constructor, which we've used here to load the map.</p> <p>This syntax/construct is sometimes erroneously called "double brace initialization" - I suppose because there's two adjacent braces - but there's actually no such thing.</p> <p>The two cool things about this are:</p> <ul> <li>it marries the declaration with the contents, and</li> <li>because the initialization is in-line, you can also make an in-line call to <code>Collections.unmodifiableMap()</code>, resulting in a neat one-line declaration, initialization and conversion to unmodifiable.</li> </ul> <p>If you don't need/want the map to be unmodifiable, leave out that call:</p> <pre><code>private static final Map&lt;String, int[]&gt; myMap = new HashMap&lt;String, int[]&gt;() {{ put(FRED_TEXT, new int[] {ONE, TWO, FOUR}); put(DAVE_TEXT, new int[] {TWO, THREE}); }}; </code></pre>
13,487,765
How instanceof will work on an interface
<p><code>instanceof</code> can be used to test if an object is a direct or descended instance of a given class. <code>instanceof</code> can also be used with interfaces even though interfaces can't be instantiated like classes. Can anyone explain how <code>instanceof</code> works?</p>
13,487,855
8
0
null
2012-11-21 06:44:36.4 UTC
13
2021-01-18 03:27:47.733 UTC
2017-02-15 18:09:09.393 UTC
null
2,349,366
null
668,970
null
1
62
java|interface|instanceof
77,839
<p>First of all, we can store <code>instances</code> of classes that implements a particular <code>interface</code> in an <code>interface reference variable</code> like this.</p> <pre><code>package com.test; public class Test implements Testable { public static void main(String[] args) { Testable testable = new Test(); // OR Test test = new Test(); if (testeable instanceof Testable) System.out.println(&quot;instanceof succeeded&quot;); if (test instanceof Testable) System.out.println(&quot;instanceof succeeded&quot;); } } interface Testable { } </code></pre> <p>ie, any runtime instance that implements a particular interface will pass the <code>instanceof</code> test</p> <p><strong>EDIT</strong></p> <p>and the output</p> <pre><code>instanceof succeeded instanceof succeeded </code></pre> <p>@RohitJain</p> <p>You can create instances of interfaces by using anonymous inner classes like this</p> <pre><code>Runnable runnable = new Runnable() { public void run() { System.out.println(&quot;inside run&quot;); } }; </code></pre> <p>and you test the instance is of type interface, using <code>instanceof</code> operator like this</p> <pre><code>System.out.println(runnable instanceof Runnable); </code></pre> <p>and the result is 'true'</p>
20,404,957
Visual Studio 2013 Vertical Brace Lines
<p>How do you turn off the vertical lines that connect the braces in C# code? Is this a VS 2013 property? Is this resharper 8 doing this? Thanks</p>
20,424,258
5
2
null
2013-12-05 16:10:37.993 UTC
10
2022-06-06 15:37:57.333 UTC
null
null
null
null
2,137,581
null
1
67
visual-studio-2013
33,088
<p>Yes, I hate it and was going to ask the same question, but I have figured it out. You must have ProductivityPowerTools installed too. Go to Tools->Options->Productivity Power Tools->Other Extensions and there is an option group called Structure visualizer options. In there is a checkbox for Show code structure in editor. Turn this off, and job done!</p>
3,492,536
Point branch to new commit
<p><em>(This question is the opposite of <a href="https://stackoverflow.com/questions/1628563/git-move-recent-commit-to-a-new-branch">this one</a>)</em></p> <p>How can I go from this</p> <pre><code>dev C - D / master A - B </code></pre> <p>to this?</p> <pre><code>dev D / master A - B - C </code></pre> <p>I know I'm going to kick myself when I see the answer, but for the moment I'm a bit stuck...</p>
3,492,559
2
0
null
2010-08-16 11:04:36.227 UTC
24
2019-06-11 15:06:25.573 UTC
2017-05-23 12:02:36.157 UTC
null
-1
null
11,410
null
1
113
git
15,945
<h3>Solution</h3> <pre><code>git checkout master git merge C </code></pre> <p><em>With <code>C</code> being the SHA1 of commit <code>C</code>.</em></p> <h3>Result</h3> <pre><code> D (dev) / master A - B - C (move master HEAD) </code></pre> <p>It should be a fast-forward merge.</p>
9,331,352
Eclipse, refactoring a java method into a another class
<p>How can I refactor(move) a Java method in classA into classB and have all references to the method to it updated? </p> <p>Is this supported in Eclipse ?</p>
9,331,532
2
2
null
2012-02-17 15:51:51.62 UTC
1
2012-02-20 15:25:54.093 UTC
2012-02-20 15:25:54.093 UTC
null
961,018
null
961,018
null
1
34
eclipse
28,802
<p>For a static method, you can right click and select 'Move'.</p> <pre><code>Obj1.myMethod() </code></pre> <p>would then get 'moved' to</p> <pre><code>Obj2.myMethod() </code></pre> <p>and eclipse would fix your imports etc.</p> <p>For a non-static method, this may not work depending on the relationship between classA and classB. </p> <pre><code>Obj1 myobj1 = new Obj1(); myobj1.myMethod(); myobj1.myOtherMethod(); </code></pre> <p>If you move myMethod() to a different class, the refactoring would have to change the object initialization. If myOtherMethod isn't getting moved, then it can't just change the type of myobj1 to Obj2 because then myOtherMethod won't work.</p>
16,171,320
Remove all backslashes in Javascript
<p>How to remove all backslash in a JavaScript string ?</p> <pre><code>var str = "one thing\\\'s for certain: power blackouts and surges can damage your equipment."; </code></pre> <p>I want output like </p> <pre><code>one thing's for certain: power blackouts and surges can damage your equipment. </code></pre> <p>Update:</p> <p>I am scrapping data from page with help of JavaScript &amp; displaying on fancy-box popup. </p> <p>please help me on this</p>
16,171,353
4
2
null
2013-04-23 13:59:04.92 UTC
4
2019-01-30 16:21:43.65 UTC
2019-01-30 16:21:43.65 UTC
null
133,203
null
2,046,091
null
1
16
javascript|web-scraping|slash
66,594
<p>Use a simple regex to solve it</p> <pre><code>str = str.replace(/\\/g, '') </code></pre> <p>Demo: <a href="http://jsfiddle.net/arunpjohny/cW62s/">Fiddle</a></p>
16,322,869
Trying to create a confetti effect in html5, how do I get a different fill color for each element?
<p><strong>EDIT:</strong></p> <p>For anybody who is curious, here is the finished result.</p> <p><a href="http://jsfiddle.net/Javalsu/vxP5q/743/embedded/result/">http://jsfiddle.net/Javalsu/vxP5q/743/embedded/result/</a></p> <hr> <p>I'm building off of the code I found in this link</p> <p><a href="http://thecodeplayer.com/walkthrough/html5-canvas-snow-effect">http://thecodeplayer.com/walkthrough/html5-canvas-snow-effect</a></p> <p>I want to make this more of a confetti falling effect than a snow effect, and I would need to make each element a different color. But it seems that the fill color is set for entire canvas at once.</p> <p>Is there a way to specify a different fill color for each element or am I going about this the entirely wrong way?</p> <p>Thanks</p> <p>Update: Here is the finished product if anybody has a need for confetti</p> <p><a href="http://jsfiddle.net/mj3SM/6/">http://jsfiddle.net/mj3SM/6/</a></p> <pre><code>window.onload = function () { //canvas init var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //canvas dimensions var W = window.innerWidth; var H = window.innerHeight; canvas.width = W; canvas.height = H; //snowflake particles var mp = 200; //max particles var particles = []; for (var i = 0; i &lt; mp; i++) { particles.push({ x: Math.random() * W, //x-coordinate y: Math.random() * H, //y-coordinate r: Math.random() * 15 + 1, //radius d: Math.random() * mp, //density color: "rgba(" + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", 0.8)", tilt: Math.floor(Math.random() * 5) - 5 }); } //Lets draw the flakes function draw() { ctx.clearRect(0, 0, W, H); for (var i = 0; i &lt; mp; i++) { var p = particles[i]; ctx.beginPath(); ctx.lineWidth = p.r; ctx.strokeStyle = p.color; // Green path ctx.moveTo(p.x, p.y); ctx.lineTo(p.x + p.tilt + p.r / 2, p.y + p.tilt); ctx.stroke(); // Draw it } update(); } //Function to move the snowflakes //angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes var angle = 0; function update() { angle += 0.01; for (var i = 0; i &lt; mp; i++) { var p = particles[i]; //Updating X and Y coordinates //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards //Every particle has its own density which can be used to make the downward movement different for each flake //Lets make it more random by adding in the radius p.y += Math.cos(angle + p.d) + 1 + p.r / 2; p.x += Math.sin(angle) * 2; //Sending flakes back from the top when it exits //Lets make it a bit more organic and let flakes enter from the left and right also. if (p.x &gt; W + 5 || p.x &lt; -5 || p.y &gt; H) { if (i % 3 &gt; 0) //66.67% of the flakes { particles[i] = { x: Math.random() * W, y: -10, r: p.r, d: p.d, color: p.color, tilt: p.tilt }; } else { //If the flake is exitting from the right if (Math.sin(angle) &gt; 0) { //Enter from the left particles[i] = { x: -5, y: Math.random() * H, r: p.r, d: p.d, color: p.color, tilt: p.tilt }; } else { //Enter from the right particles[i] = { x: W + 5, y: Math.random() * H, r: p.r, d: p.d, color: p.color, tilt: p.tilt }; } } } } } //animation loop setInterval(draw, 20); </code></pre> <p>}</p>
16,323,005
4
0
null
2013-05-01 17:08:19.86 UTC
9
2020-11-08 12:21:32.813 UTC
2016-06-17 00:56:47.313 UTC
null
1,526,306
null
1,526,306
null
1
27
javascript|html|canvas|html5-canvas
24,059
<p>Try it like this: <a href="http://jsfiddle.net/vxP5q/">http://jsfiddle.net/vxP5q/</a></p> <p>The JS:</p> <pre><code>window.onload = function(){ //canvas init var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); //canvas dimensions var W = window.innerWidth; var H = window.innerHeight; canvas.width = W; canvas.height = H; //snowflake particles var mp = 25; //max particles var particles = []; for(var i = 0; i &lt; mp; i++) { particles.push({ x: Math.random()*W, //x-coordinate y: Math.random()*H, //y-coordinate r: Math.random()*4+1, //radius d: Math.random()*mp, //density color: "rgba(" + Math.floor((Math.random() * 255)) +", " + Math.floor((Math.random() * 255)) +", " + Math.floor((Math.random() * 255)) + ", 0.8)" }) } //Lets draw the flakes function draw() { ctx.clearRect(0, 0, W, H); for(var i = 0; i &lt; mp; i++) { var p = particles[i]; ctx.beginPath(); ctx.fillStyle = p.color; ctx.moveTo(p.x, p.y); ctx.arc(p.x, p.y, p.r, 0, Math.PI*2, true); ctx.fill(); } update(); } //Function to move the snowflakes //angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes var angle = 0; function update() { angle += 0.01; for(var i = 0; i &lt; mp; i++) { var p = particles[i]; //Updating X and Y coordinates //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards //Every particle has its own density which can be used to make the downward movement different for each flake //Lets make it more random by adding in the radius p.y += Math.cos(angle+p.d) + 1 + p.r/2; p.x += Math.sin(angle) * 2; //Sending flakes back from the top when it exits //Lets make it a bit more organic and let flakes enter from the left and right also. if(p.x &gt; W+5 || p.x &lt; -5 || p.y &gt; H) { if(i%3 &gt; 0) //66.67% of the flakes { particles[i] = {x: Math.random()*W, y: -10, r: p.r, d: p.d, color : p.color}; } else { //If the flake is exitting from the right if(Math.sin(angle) &gt; 0) { //Enter from the left particles[i] = {x: -5, y: Math.random()*H, r: p.r, d: p.d, color: p.color}; } else { //Enter from the right particles[i] = {x: W+5, y: Math.random()*H, r: p.r, d: p.d, color : p.color}; } } } } } //animation loop setInterval(draw, 33); } </code></pre> <p>What I've done. Where the pixels are generated I've added an unique (random) color. Where the update is, I'm making sure the colors are changed and where its drawn I've changed it so that it will create an inuque path for each confetti item.</p>
16,226,924
Is cross-origin postMessage broken in IE10?
<p>I'm trying to make a trivial <code>postMessage</code> example work...</p> <ul> <li>in IE10</li> <li>between windows/tabs (vs. iframes)</li> <li>across origins</li> </ul> <p>Remove any one of these conditions, and things work fine :-)</p> <p>But as far as I can tell, between-window <code>postMessage</code> only appears to work in IE10 when both windows share an origin. (Well, in fact -- and weirdly -- the behavior is slightly more permissive than that: two different origins that share a <em>host</em> seem to work, too).</p> <h1>Is this a documented bug? Any workarounds or other advice?</h1> <p>(Note: <a href="http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/a5b0acb7-0978-4677-98be-391144eb5601/" rel="noreferrer">This question</a> touches on the issues, but <a href="http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/a5b0acb7-0978-4677-98be-391144eb5601/" rel="noreferrer">its answer</a> is about IE8 and IE9 -- not 10)</p> <hr /> <p>More details + example...</p> <h3>launcher page <a href="http://jsbin.com/ahuzir/1" rel="noreferrer">demo</a></h3> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;script&gt; window.addEventListener(&quot;message&quot;, function(e){ console.log(&quot;Received message: &quot;, e); }, false); &lt;/script&gt; &lt;button onclick=&quot;window.open('http://jsbin.com/ameguj/1');&quot;&gt; Open new window &lt;/button&gt; &lt;/html&gt; </code></pre> <h3>launched page <a href="http://jsbin.com/ameguj/1" rel="noreferrer">demo</a></h3> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;script&gt; window.opener.postMessage(&quot;Ahoy!&quot;, &quot;*&quot;); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>This works at: <a href="http://jsbin.com/ahuzir/1" rel="noreferrer">http://jsbin.com/ahuzir/1</a> -- because both pages are hosted at the same origin (jsbin.com). But move the second page anywhere else, and it fails in IE10.</p>
16,313,383
8
4
null
2013-04-26 00:32:32.497 UTC
34
2021-07-05 16:07:13.203 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
318,206
null
1
93
html|cross-browser|compatibility|internet-explorer-10|postmessage
72,927
<p><strong>I was mistaken when I originally posted this answer: it doesn't actually work in IE10.</strong> Apparently people have found this useful for other reasons so I'm leaving it up for posterity. Original answer below:</p> <hr> <p>Worth noting: the link in that answer you linked to states that <code>postMessage</code> isn't cross origin for separate windows in IE8 and IE9 -- however, it was also written in 2009, before IE10 came around. So I wouldn't take that as an indication that it's fixed in IE10.</p> <p>As for <code>postMessage</code> itself, <a href="http://caniuse.com/#feat=x-doc-messaging" rel="noreferrer">http://caniuse.com/#feat=x-doc-messaging</a> notably indicates that it's still broken in IE10, which seems to match up with your demo. The caniuse page links to <a href="http://dev.opera.com/articles/view/window-postmessage-messagechannel/" rel="noreferrer">this article</a>, which contains a very relevant quote:</p> <blockquote> <p>Internet Explorer 8+ partially supports cross-document messaging: it currently works with iframes, but not new windows. Internet Explorer 10, however, will support MessageChannel. Firefox currently supports cross-document messaging, but not MessageChannel.</p> </blockquote> <p>So your best bet is probably to have a <code>MessageChannel</code> based codepath, and fallback to <code>postMessage</code> if that doesn't exist. It won't get you IE8/IE9 support, but at least it'll work with IE10.</p> <p>Docs on <code>MessageChannel</code>: <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/windows/apps/hh441303.aspx</a></p>
13,072,538
getting a value out of an arrayList
<p>I am using C# and I am creating an ArrayList called "importControlKeys" which creates fine. However, I can't for the life of my figure out a way to loop through the arrayList and pick out the values in the ArrayList for use in later code.</p> <p>I know I'm missing something easy, but what is the syntax to extract a value from an ArrayList. I was hoping it was somethign like importControlKeys[ii].value in my code below, but that isn't working.</p> <p>I've searched on these boards and can't find the exact solution, though I'm sure it's easy. msot of the solutions say to re-write as a List but I have to believe there is a way to get data out of an array list without re-writing as a List</p> <pre><code>private void button1_Click(object sender, EventArgs e) { ArrayList importKeyList = new ArrayList(); List&lt;DataGridViewRow&gt; rows_with_checked_column = new List&lt;DataGridViewRow&gt;(); foreach (DataGridViewRow row in grd1.Rows) { if (Convert.ToBoolean(row.Cells[Del2.Name].Value) == true) { rows_with_checked_column.Add(row); importKeyList.Add(row.Cells[colImportControlKey.Name].Value); //string importKey = grd1.Rows[grd1.SelectedCells[0].RowIndex].Cells[0].Value.ToString(); //grd1.ClearSelection(); //if (DeleteImport(importKey)) // LoadGrid(); } } for (int ii = 0; ii &lt; rows_with_checked_column.Count; ii++) { //grd1.ClearSelection(); string importKey = importKeyList[ii].value; //ERRORS OUT if (DeleteImport(importKey)) LoadGrid(); // Do what you want with the check rows } } </code></pre>
13,072,620
7
3
null
2012-10-25 15:56:58.74 UTC
0
2013-09-11 09:33:01.993 UTC
null
null
null
null
1,489,471
null
1
3
c#|arraylist
56,634
<p>Not sure why you are using an ArrayList but if you need to loop thru it you could do something like this this </p> <p>if an element is not convertible to the type, you'll get an InvalidCastException. In your case, you cannot cast boxed int to string causing an exception to be thrown. </p> <pre><code>foreach (object obj in importKeyList ) { string s = (string)obj; // loop body } </code></pre> <p>or you do a for loop </p> <pre><code>for (int intCounter = 0; intCounter &lt; importKeyList.Count; intCounter++) { object obj = importKeyList[intCounter]; // Something... } </code></pre>
17,172,080
insert vs emplace vs operator[] in c++ map
<p>I'm using maps for the first time and I realized that there are many ways to insert an element. You can use <code>emplace()</code>, <code>operator[]</code> or <code>insert()</code>, plus variants like using <code>value_type</code> or <code>make_pair</code>. While there is a lot of information about all of them and questions about particular cases, I still can't understand the big picture. So, my two questions are:</p> <ol> <li><p>What is the advantage of each one of them over the others?</p></li> <li><p>Was there any need for adding emplace to the standard? Is there anything that wasn't possible before without it?</p></li> </ol>
17,174,245
6
3
null
2013-06-18 14:52:30.183 UTC
109
2022-07-13 18:37:56.29 UTC
2017-10-31 15:23:24.36 UTC
null
734,069
null
2,340,918
null
1
264
c++|dictionary|insert|operators|emplace
127,578
<p>In the particular case of a map the old options were only two: <code>operator[]</code> and <code>insert</code> (different flavors of <code>insert</code>). So I will start explaining those.</p> <p>The <code>operator[]</code> is a <em>find-or-add</em> operator. It will try to find an element with the given key inside the map, and if it exists it will return a reference to the stored value. If it does not, it will create a new element inserted in place with default initialization and return a reference to it.</p> <p>The <code>insert</code> function (in the single element flavor) takes a <code>value_type</code> (<code>std::pair&lt;const Key,Value&gt;</code>), it uses the key (<code>first</code> member) and tries to insert it. Because <code>std::map</code> does not allow for duplicates if there is an existing element it will not insert anything.</p> <p>The first difference between the two is that <code>operator[]</code> needs to be able to construct a default initialized <em>value</em>, and it is thus unusable for value types that cannot be default initialized. The second difference between the two is what happens when there is already an element with the given key. The <code>insert</code> function will not modify the state of the map, but instead return an iterator to the element (and a <code>false</code> indicating that it was not inserted).</p> <pre><code>// assume m is std::map&lt;int,int&gt; already has an element with key 5 and value 0 m[5] = 10; // postcondition: m[5] == 10 m.insert(std::make_pair(5,15)); // m[5] is still 10 </code></pre> <p>In the case of <code>insert</code> the argument is an object of <code>value_type</code>, which can be created in different ways. You can directly construct it with the appropriate type or pass any object from which the <code>value_type</code> can be constructed, which is where <code>std::make_pair</code> comes into play, as it allows for simple creation of <code>std::pair</code> objects, although it is probably not what you want...</p> <p>The net effect of the following calls is <em>similar</em>:</p> <pre><code>K t; V u; std::map&lt;K,V&gt; m; // std::map&lt;K,V&gt;::value_type is std::pair&lt;const K,V&gt; m.insert( std::pair&lt;const K,V&gt;(t,u) ); // 1 m.insert( std::map&lt;K,V&gt;::value_type(t,u) ); // 2 m.insert( std::make_pair(t,u) ); // 3 </code></pre> <p>But the are not really the same... [1] and [2] are actually equivalent. In both cases the code creates a temporary object of the same type (<code>std::pair&lt;const K,V&gt;</code>) and passes it to the <code>insert</code> function. The <code>insert</code> function will create the appropriate node in the binary search tree and then copy the <code>value_type</code> part from the argument to the node. The advantage of using <code>value_type</code> is that, well, <code>value_type</code> always <em>matches</em> <code>value_type</code>, you cannot mistype the type of the <code>std::pair</code> arguments!</p> <p>The difference is in [3]. The function <code>std::make_pair</code> is a template function that will create a <code>std::pair</code>. The signature is:</p> <pre><code>template &lt;typename T, typename U&gt; std::pair&lt;T,U&gt; make_pair(T const &amp; t, U const &amp; u ); </code></pre> <p>I have intentionally not provided the template arguments to <code>std::make_pair</code>, as that is the common usage. And the implication is that the template arguments are deduced from the call, in this case to be <code>T==K,U==V</code>, so the call to <code>std::make_pair</code> will return a <code>std::pair&lt;K,V&gt;</code> (note the missing <code>const</code>). The signature requires <code>value_type</code> that is <em>close</em> but not the same as the returned value from the call to <code>std::make_pair</code>. Because it is close enough it will create a temporary of the correct type and copy initialize it. That will in turn be copied to the node, creating a total of two copies.</p> <p>This can be fixed by providing the template arguments:</p> <pre><code>m.insert( std::make_pair&lt;const K,V&gt;(t,u) ); // 4 </code></pre> <p>But that is still error prone in the same way that explicitly typing the type in case [1].</p> <p>Up to this point, we have different ways of calling <code>insert</code> that require the creation of the <code>value_type</code> externally and the copy of that object into the container. Alternatively you can use <code>operator[]</code> if the type is <em>default constructible</em> and <em>assignable</em> (intentionally focusing only in <code>m[k]=v</code>), and it requires the default initialization of one object and the <em>copy</em> of the value into that object.</p> <p>In C++11, with variadic templates and perfect forwarding there is a new way of adding elements into a container by means of <em>emplacing</em> (creating in place). The <code>emplace</code> functions in the different containers do basically the same thing: instead of getting a <em>source</em> from which to <em>copy</em> into the container, the function takes the parameters that will be forwarded to the constructor of the object stored in the container. </p> <pre><code>m.emplace(t,u); // 5 </code></pre> <p>In [5], the <code>std::pair&lt;const K, V&gt;</code> is not created and passed to <code>emplace</code>, but rather references to the <code>t</code> and <code>u</code> object are passed to <code>emplace</code> that forwards them to the constructor of the <code>value_type</code> subobject inside the data structure. In this case <em>no</em> copies of the <code>std::pair&lt;const K,V&gt;</code> are done at all, which is the advantage of <code>emplace</code> over the C++03 alternatives. As in the case of <code>insert</code> it will not override the value in the map.</p> <hr> <p>An interesting question that I had not thought about is how <code>emplace</code> can actually be implemented for a map, and that is not a simple problem in the general case.</p>
17,190,207
Setting text of li
<p>I have made list:</p> <pre><code>&lt;ul&gt; &lt;li id="one"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And then in jQuery I do:</p> <pre><code> $("#one").text("one"); </code></pre> <p>However it is not changing, also I have tried using <code>.val()</code> but it didn't help.</p> <p>Why it happens and how to change the li text?</p>
17,190,267
1
8
null
2013-06-19 11:37:57.473 UTC
1
2013-06-19 11:46:57.16 UTC
2013-06-19 11:46:57.16 UTC
null
995,579
null
242,388
null
1
15
jquery|html|html-lists
40,807
<p>There may be one of the problem you have</p> <p>1) You did not imported js files properly</p> <p>2)You might not write the code in ready function</p> <p>Write your code in ready function and import jQuery related js files.</p> <pre><code>$( document ).ready(function() { $("#one").text("one"); }); </code></pre> <p><a href="http://jsfiddle.net/zBxTm/" rel="noreferrer">http://jsfiddle.net/zBxTm/</a></p>
27,160,122
MySQL query to get "intersection" of numerous queries with limits
<p>Assume I have a single mySQL table (users) with the following fields:</p> <pre><code>userid gender region age ethnicity income </code></pre> <p>I want to be able to return the number of total records based on the number a user enters. Furthermore, they will also be providing additional criteria.</p> <p>In the simplest example, they may ask for 1,000 records, where 600 records should have gender = 'Male' and 400 records where gender = 'Female'. That's simple enough to do.</p> <p>Now, go one step further. Assume they now want to specify Region:</p> <pre><code>GENDER Male: 600 records Female: 400 records REGION North: 100 records South: 200 records East: 300 records West: 400 records </code></pre> <p>Again, only 1000 records should be returned, but in the end, there must be 600 males, 400 females, 100 Northerners, 200 Southerners, 300 Easterners and 400 Westerners.</p> <p>I know this isn't valid syntax, but using pseudo-mySQL code, it hopefully illustrates what I'm trying to do:</p> <pre><code>(SELECT * FROM users WHERE gender = 'Male' LIMIT 600 UNION SELECT * FROM users WHERE gender = 'Female' LIMIT 400) INTERSECT (SELECT * FROM users WHERE region = 'North' LIMIT 100 UNION SELECT * FROM users WHERE region = 'South' LIMIT 200 UNION SELECT * FROM users WHERE region = 'East' LIMIT 300 UNION SELECT * FROM users WHERE region = 'West' LIMIT 400) </code></pre> <p>Note that I'm not looking for a one-time query. The total number of records and the number of records within each criteria will constantly be changing based on input by the user. So, I'm trying to come up with a generic solution that can be re-used over and over, not a hard-coded solution.</p> <p>To make things more complicated, now add more criteria. There could also be age, ethnicity and income each with their own set number of records for each group, additional code appended to above:</p> <pre><code>INTERSECT (SELECT * FROM users WHERE age &gt;= 18 and age &lt;= 24 LIMIT 300 UNION SELECT * FROM users WHERE age &gt;= 25 and age &lt;= 36 LIMIT 200 UNION SELECT * FROM users WHERE age &gt;= 37 and age &lt;= 54 LIMIT 200 UNION SELECT * FROM users WHERE age &gt;= 55 LIMIT 300) INTERSECT etc. </code></pre> <p>I'm not sure if this is possible to write in one query or if this requires multiple statements and iterations.</p>
27,414,532
10
18
null
2014-11-26 22:40:14.24 UTC
8
2022-05-03 20:58:22.93 UTC
2014-12-09 08:55:37.817 UTC
null
472,495
null
4,297,784
null
1
43
mysql|sql|database|select|inner-join
2,651
<h2>Flatten Your Criteria</h2> <hr> <p>You can flatten your multi-dimensional criteria into a single level criteria</p> <p><img src="https://i.stack.imgur.com/nIid7.png" alt="enter image description here"></p> <p>Now this criteria can be achieved in one query as follow</p> <pre><code>(SELECT * FROM users WHERE gender = 'Male' AND region = 'North' LIMIT 40) UNION ALL (SELECT * FROM users WHERE gender = 'Male' AND region = 'South' LIMIT 80) UNION ALL (SELECT * FROM users WHERE gender = 'Male' AND region = 'East' LIMIT 120) UNION ALL (SELECT * FROM users WHERE gender = 'Male' AND region = 'West' LIMIT 160) UNION ALL (SELECT * FROM users WHERE gender = 'Female' AND region = 'North' LIMIT 60) UNION ALL (SELECT * FROM users WHERE gender = 'Female' AND region = 'South' LIMIT 120) UNION ALL (SELECT * FROM users WHERE gender = 'Female' AND region = 'East' LIMIT 180) UNION ALL (SELECT * FROM users WHERE gender = 'Female' AND region = 'West' LIMIT 240) </code></pre> <p><strong>Problem</strong></p> <ul> <li>It does not always return the correct result. For example, if there are less than 40 users whose are male and from north, then the query will return less than 1,000 records.</li> </ul> <hr> <h2>Adjust Your Criteria</h2> <hr> <p>Let say that there is less than 40 users whose are male and from north. Then, you need to adjust other criteria quantity to cover the missing quantity from "Male" and "North". I believe it is not possible to do it with bare SQL. This is pseudo code that I have in mind. For sake of simplification, I think we will only query for Male, Female, North, and South </p> <pre><code>conditions.add({ gender: 'Male', region: 'North', limit: 40 }) conditions.add({ gender: 'Male', region: 'South', limit: 80 }) conditions.add({ gender: 'Female', region: 'North', limit: 60 }) conditions.add({ gender: 'Female', region: 'South', limit: 120 }) foreach(conditions as condition) { temp = getResultFromDatabaseByCondition(condition) conditions.remove(condition) // there is not enough result for this condition, // increase other condition quantity if (temp.length &lt; condition.limit) { adjust(...); } } </code></pre> <p>Let say that there are only 30 northener male. So we need to adjust +10 male, and +10 northener.</p> <pre><code>To Adjust --------------------------------------------------- Male +10 North +10 Remain Conditions ---------------------------------------------------- { gender: 'Male', region: 'South', limit: 80 } { gender: 'Female', region: 'North', limit: 60 } { gender: 'Female', region: 'South', limit: 120 } </code></pre> <p>'Male' + 'South' is the first condition that match the 'Male' adjustment condition. Increase it by +10, and remove it from the "remain condition" list. Since, we increase the South, we need to decrease it back at other condition. So add "South" condition into "To Adjust" list</p> <pre><code>To Adjust --------------------------------------------------- South -10 North +10 Remain Conditions ---------------------------------------------------- { gender: 'Female', region: 'North', limit: 60 } { gender: 'Female', region: 'South', limit: 120 } Final Conditions ---------------------------------------------------- { gender: 'Male', region: 'South', limit: 90 } </code></pre> <p>Find condition that match the 'South' and repeat the same process.</p> <pre><code>To Adjust --------------------------------------------------- Female +10 North +10 Remain Conditions ---------------------------------------------------- { gender: 'Female', region: 'North', limit: 60 } Final Conditions ---------------------------------------------------- { gender: 'Female', region: 'South', limit: 110 } { gender: 'Male', region: 'South', limit: 90 } </code></pre> <p>And finally</p> <pre><code>{ gender: 'Female', region: 'North', limit: 70 } { gender: 'Female', region: 'South', limit: 110 } { gender: 'Male', region: 'South', limit: 90 } </code></pre> <p>I haven't come up with the exact implementation of adjustment yet. It is more difficult than I have expected. I will update once I can figure out how to implement it.</p>
26,435,313
AngularJs ng-if comparing dates
<p>I am looking to compare two dates in ng-if this is what my jade file looks like.</p> <pre><code>li.list-group-item(ng-if="app.Segments[0].StartDate.getTime() &gt; date.getTime()") div.row div.col-xs-12 span i.fa.fa-plus-square </code></pre> <p>This code will hopefully add an li to my ui if the startdate of the first segment is after today.</p> <pre><code>$scope.date = new Date(); $scope.app = { Segments: [{ StartDate: 2014-11-15T04:00:00.000Z EndDate: 2014-11-20T04:00:00.000Z }, { StartDate: 2014-11-21T04:00:00.000Z EndDate: 2014-11-25T04:00:00.000Z }] } </code></pre> <p>Is there anyway to make this work?</p>
26,435,454
2
2
null
2014-10-18 00:56:14.28 UTC
1
2016-01-20 23:25:22.263 UTC
2014-10-18 02:18:42.423 UTC
null
3,366,929
null
4,155,542
null
1
13
angularjs|angular-ng-if
49,344
<p>If they're date object just compare them directly without <code>.getTime()</code></p> <pre><code>$scope.date2005 = new Date('2005/01/01'); $scope.date2006 = new Date('2006-01-01T04:00:00.000Z'); </code></pre> <pre><code>&lt;div ng-if="date2005 &gt; date2006"&gt;date2005 &gt; date2006&lt;/div&gt; &lt;!-- won't show --&gt; &lt;div ng-if="date2006 &gt; date2005"&gt;date2006 &gt; date2005&lt;/div&gt; &lt;!-- will show --&gt; </code></pre> <p><a href="http://plnkr.co/edit/fNB11U6KmFszdV3lMAPJ?p=preview">http://plnkr.co/edit/fNB11U6KmFszdV3lMAPJ?p=preview</a></p>
39,679,505
Using await outside of an async function
<p>I was attempting to chain two async functions together, because the first had a conditional return parameter that caused the second to either run, or exit the module. However, I've found odd behavior I can't find in the specs.</p> <pre><code>async function isInLobby() { //promise.all([chained methods here]) let exit = false; if (someCondition) exit = true; } </code></pre> <p>This is a bastardized snippet of my code (you can see the full scope <a href="https://github.com/RUJodan/SourceUndead/blob/master/routes/lobby.js#L53" rel="noreferrer">here</a>), that simply checks if a player if already in a lobby, but that's irrelevant.</p> <p>Next we have this async function.</p> <pre><code>async function countPlayer() { const keyLength = await scardAsync(game); return keyLength; } </code></pre> <p>This function doesn't need to run if <code>exit === true</code>.</p> <p>I tried to do</p> <pre><code>const inLobby = await isInLobby(); </code></pre> <p>This I hoped would await to results, so I can use <code>inLobby</code> to conditionally run <code>countPlayer</code>, however I received a typeerror with no specific details.</p> <p>Why can't you <code>await</code> an <code>async</code> function outside of the scope of the function? I know it's a sugar promise, so it must be chained to <code>then</code> but why is it that in <code>countPlayer</code> I can await another promise, but outside, I can't <code>await</code> <code>isInLobby</code>?</p>
39,679,541
4
6
null
2016-09-24 18:12:32.457 UTC
18
2021-11-08 07:28:52.253 UTC
null
null
null
null
774,078
null
1
116
javascript|node.js|async-await
204,701
<p>Top level <code>await</code> is not supported. There are a few discussions by the standards committee on why this is, such as <a href="https://github.com/tc39/ecmascript-asyncawait/issues/9" rel="noreferrer">this Github issue</a>.</p> <p>There's also a <a href="https://gist.github.com/Rich-Harris/0b6f317657f5167663b493c722647221" rel="noreferrer">thinkpiece on Github</a> about why top level await is a bad idea. Specifically he suggests that if you have code like this:</p> <pre><code>// data.js const data = await fetch( '/data.json' ); export default data; </code></pre> <p>Now <strong>any</strong> file that imports <code>data.js</code> won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.</p> <p><strong>My perspective</strong> is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level <code>await</code> probably means you're reading from some API or calling to some service at <strong>load time.</strong> Instead you should just export async functions that consumers can use at their own pace.</p>
19,637,677
How to delete specific characters from a string in Ruby?
<p>I have several strings that look like this:</p> <pre><code>"((String1))" </code></pre> <p>They are all different lengths. How could I remove the parentheses from all these strings in a loop?</p>
19,637,751
6
6
null
2013-10-28 14:39:38.173 UTC
10
2022-08-05 21:22:42.413 UTC
2019-09-18 16:15:07.17 UTC
null
2,767,755
null
2,069,788
null
1
100
ruby|string|trim
206,343
<p>Do as below using <a href="http://ruby-doc.org/core-2.0.0/String.html#method-i-tr"><code>String#tr</code></a> :</p> <pre><code> "((String1))".tr('()', '') # =&gt; "String1" </code></pre>
44,829,824
How to store JSON in an entity field with EF Core?
<p>I am creating a reusable library using .NET Core (targeting .NETStandard 1.4) and I am using Entity Framework Core (and new to both). I have an entity class that looks like:</p> <pre><code>public class Campaign { [Key] public Guid Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } public JObject ExtendedData { get; set; } } </code></pre> <p>and I have a DbContext class that defines the DbSet:</p> <pre><code>public DbSet&lt;Campaign&gt; Campaigns { get; set; } </code></pre> <p>(I am also using the Repository pattern with DI, but I don't think that is relevant.)</p> <p>My unit tests give me this error:</p> <blockquote> <p>System.InvalidOperationException: Unable to determine the relationship represented by navigation property 'JToken.Parent' of type 'JContainer'. Either manually configure the relationship, or ignore this property from the model..</p> </blockquote> <p>Is there a way to indicate that this is not a relationship but should be stored as a big string?</p>
44,832,143
11
3
null
2017-06-29 15:49:46.39 UTC
45
2022-08-25 05:30:45.963 UTC
2020-04-04 00:26:31.4 UTC
null
7,616,528
null
345,179
null
1
119
c#|json.net|entity-framework-core
111,962
<p>@Michael's answer got me on track but I implemented it a little differently. I ended up storing the value as a string in a private property and using it as a "Backing Field". The ExtendedData property then converted JObject to a string on set and vice versa on get:</p> <pre><code>public class Campaign { // https://docs.microsoft.com/en-us/ef/core/modeling/backing-field private string _extendedData; [Key] public Guid Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } [NotMapped] public JObject ExtendedData { get { return JsonConvert.DeserializeObject&lt;JObject&gt;(string.IsNullOrEmpty(_extendedData) ? "{}" : _extendedData); } set { _extendedData = value.ToString(); } } } </code></pre> <p>To set <code>_extendedData</code> as a backing field, I added this to my context: </p> <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity&lt;Campaign&gt;() .Property&lt;string&gt;("ExtendedDataStr") .HasField("_extendedData"); } </code></pre> <p>Update: Darren's answer to use EF Core Value Conversions (new to EF Core 2.1 - which didn't exist at the time of this answer) seems to be the best way to go at this point.</p>
17,481,479
Parse comma-separated string to make IN List of strings in the Where clause
<p>My stored procedure receives a parameter which is a comma-separated string:</p> <pre><code>DECLARE @Account AS VARCHAR(200) SET @Account = 'SA,A' </code></pre> <p>I need to make from it this statement: </p> <pre><code>WHERE Account IN ('SA', 'A') </code></pre> <p>What is the best practice for doing this?</p>
17,481,595
4
0
null
2013-07-05 05:11:07.207 UTC
10
2021-11-09 16:13:36.26 UTC
2013-07-05 07:10:13.833 UTC
null
13,302
null
2,514,925
null
1
27
sql|sql-server|sql-server-2008|tsql
64,974
<p>Create this function (sqlserver 2005+)</p> <pre><code>CREATE function [dbo].[f_split] ( @param nvarchar(max), @delimiter char(1) ) returns @t table (val nvarchar(max), seq int) as begin set @param += @delimiter ;with a as ( select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq union all select t + 1, charindex(@delimiter, @param, t + 1), seq + 1 from a where charindex(@delimiter, @param, t + 1) &gt; 0 ) insert @t select substring(@param, f, t - f), seq from a option (maxrecursion 0) return end </code></pre> <p>use this statement</p> <pre><code>SELECT * FROM yourtable WHERE account in (SELECT val FROM dbo.f_split(@account, ',')) </code></pre> <hr> <p>Comparing my split function to XML split:</p> <p>Testdata:</p> <pre><code>select top 100000 cast(a.number as varchar(10))+','+a.type +','+ cast(a.status as varchar(9))+','+cast(b.number as varchar(10))+','+b.type +','+ cast(b.status as varchar(9)) txt into a from master..spt_values a cross join master..spt_values b </code></pre> <p>XML:</p> <pre><code> SELECT count(t.c.value('.', 'VARCHAR(20)')) FROM ( SELECT top 100000 x = CAST('&lt;t&gt;' + REPLACE(txt, ',', '&lt;/t&gt;&lt;t&gt;') + '&lt;/t&gt;' AS XML) from a ) a CROSS APPLY x.nodes('/t') t(c) Elapsed time: 1:21 seconds </code></pre> <p>f_split:</p> <pre><code>select count(*) from a cross apply clausens_base.dbo.f_split(a.txt, ',') Elapsed time: 43 seconds </code></pre> <p>This will change from run to run, but you get the idea</p>
18,566,608
How do I add an <a> link to an icon in bootstrap?
<p>I have the following:</p> <pre><code>&lt;a href="http://www.website.com" title="Website name"&gt;Website Link&lt;/a&gt; </code></pre> <p>and </p> <pre><code>&lt;i style="margin-right: 0.5em; color: #EEEEEE;" class="icon-home icon-4x"&gt;&lt;/i&gt; </code></pre> <p>Can someone explain to me how I can combine these in bootstrap with font awesome icons that I am using. Do I put the <code>&lt;a&gt;</code> inside the <code>&lt;i&gt;</code> or the <code>&lt;i&gt;</code> inside the <code>&lt;a&gt;</code> or do the both need to be inside a <code>&lt;div&gt;</code> ?</p>
18,566,635
2
0
null
2013-09-02 06:06:48.083 UTC
1
2017-12-19 01:54:49.83 UTC
null
null
null
user1943020
null
null
1
6
html|css|twitter-bootstrap|twitter-bootstrap-3
62,436
<p>Put the <code>&lt;i&gt;</code> inside the <code>&lt;a&gt;</code></p> <p><strong>For Instance,</strong></p> <pre><code>&lt;a href="http://www.website.com" title="Website name"&gt;&lt;i style="margin-right: 0.5em; color: #EEEEEE;" class="icon-home icon-4x"&gt;&lt;/i&gt;Website Link&lt;/a&gt; </code></pre>
26,086,848
Android Don't dismiss AlertDialog after clicking PositiveButton
<p>Can I just don't dismiss my AlertDialog after clicking PositiveButton?</p> <p>I would like to remain the dialog to show something update on my ArrayAdapter listWords.</p> <p>This is my code. </p> <pre><code>AlertDialog.Builder sayWindows = new AlertDialog.Builder(MapActivity.this); final EditText saySomething = new EditText(MapActivity.this); sayWindows.setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { say = userName + " Says: "+saySomething.getText(); showPosition.setText(say); } }); sayWindows.setNegativeButton("cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); sayWindows.setAdapter(listWords, null); sayWindows.setView(saySomething); sayWindows.create().show(); </code></pre>
26,087,947
5
4
null
2014-09-28 16:09:51.08 UTC
19
2019-02-22 07:19:53.077 UTC
2018-04-27 12:37:24.973 UTC
null
886,001
null
3,874,613
null
1
54
android|android-alertdialog
51,028
<p>After looking at @Little Child solution, I try to make this. Let us know if this works for you.</p> <pre><code> AlertDialog.Builder sayWindows = new AlertDialog.Builder( MapActivity.this); final EditText saySomething = new EditText(MapActivity.this); sayWindows.setPositiveButton("ok", null); sayWindows.setNegativeButton("cancel", null); sayWindows.setAdapter(listWords, null); sayWindows.setView(saySomething); final AlertDialog mAlertDialog = sayWindows.create(); mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Do something say = userName + " Says: "+saySomething.getText(); showPosition.setText(say); } }); } }); mAlertDialog.show(); </code></pre>
23,408,449
PyCharm Python project No such file or directory
<p>When trying to run a project in PyCharm I get the following error. I have setup the virtualbox, vagrant and all the requirements in the readme file they gave me but when pressing run...</p> <pre class="lang-none prettyprint-override"><code>ssh://[email protected]:2222/usr/bin/python -u /Users/gtas/Projects/PythonProj/manage.py runserver 0.0.0.0:8000 bash: line 0: cd: /Users/gtas/Projects/PythonProj: No such file or directory /usr/bin/python: can't open file '/Users/gtas/Projects/PythonProj/manage.py': [Errno 2] No such file or directory Process finished with exit code 2 </code></pre> <p><strong>EDIT:</strong></p> <p>It looks like the VM vagrant mappings are not properly configured/set.</p> <p>I use a Mac OS X 10.9.2 and latest PyCharm IDE.</p>
24,101,096
10
5
null
2014-05-01 13:14:49.107 UTC
2
2021-08-30 00:01:48.753 UTC
2021-08-30 00:01:48.753 UTC
null
10,794,031
null
122,769
null
1
13
python|macos|vagrant|pycharm
70,836
<p>Started having the same issue after upgrading to PyCharm 3.4 - before that everything was working fine and after the update the same error. Also fixed by updating the path mappings: go to Run/Debug Configurations and manually define the Path mappings - Local path should be the path of your Django project and remote path the path to the project in the vagrant VM.</p>
9,563,204
textbox onchange event using jquery causes JScript runtime error: 'Deductions' is undefined
<p>I have a query regarding calling jQuery for textbox onchange event.</p> <p>in my coding am calling onchange event as</p> <pre><code>&lt;asp:TextBox ID="txtTotalDeductions" Text="0" runat="server" ClientIDMode="Static" onChange="Deductions();" &gt;&lt;/asp:TextBox&gt; </code></pre> <p>and I have two div sections as</p> <pre><code>&lt;div id="Total"&gt;1000&lt;/div&gt; </code></pre> <p>and</p> <pre><code>&lt;div id="NetTotal"&gt;0&lt;/div&gt; </code></pre> <p>I need to calculate the "NetTotal" by subtracting the Total - txtTotalDeductions.</p> <p>and my jQuery for Deductions is</p> <p>//Calculate deductions.</p> <pre><code>function Deductions() { var result = new Object(); result.total = $("#Total").html(); result.totalDeductions = $("#txtTotalDeductions").val(); result.netTotal = result.total - result.totalDeductions; $('#NetTotal').html(result.netTotal); } </code></pre> <p>and when I run the application the error shows like "Microsoft JScript runtime error: 'Deductions' is undefined", and the error lies here ""</p> <p>can anyone help me out pls.....thanks in advance</p>
9,563,345
2
3
null
2012-03-05 07:43:51.703 UTC
4
2015-12-13 23:45:04.177 UTC
2015-12-13 23:45:04.177 UTC
null
1,026
null
1,239,554
null
1
4
jquery|onchange
84,491
<p>remove the OnChange handler</p> <pre><code>function Deductions() { var result = new Object(); result.total = $("#Total").html(); result.totalDeductions = $("#txtTotalDeductions").val(); result.netTotal = result.total - result.totalDeductions; $('#NetTotal').html(result.netTotal); } </code></pre> <p>also wrap the code inside the ready handler and attach a change event handler</p> <pre><code>$(document).ready(function(){ //attach with the id od deductions $("#txtTotalDeductions").bind("change",Deductions); }); </code></pre>
18,599,242
Remove certain elements from map in Javascript
<p>how can i remove all the key/value pairs from following map, where <strong>key starts with X</strong>. </p> <pre><code>var map = new Object(); map[XKey1] = "Value1"; map[XKey2] = "Value2"; map[YKey3] = "Value3"; map[YKey4] = "Value4"; </code></pre> <p><strong>EDIT</strong></p> <p>Is there any way through regular expression, probably using ^ . Something like map[^XKe], where <strong>key starts with 'Xke' instead of 'X'</strong></p>
18,599,476
4
7
null
2013-09-03 18:36:17.03 UTC
2
2015-08-07 05:37:28.457 UTC
2013-09-03 19:40:18.393 UTC
null
2,128,303
null
2,128,303
null
1
19
javascript|jquery
73,463
<p>You can iterate over map keys using <code>Object.key</code>.</p> <h2>The most simple solution is this :</h2> <h2><a href="http://jsfiddle.net/charaf11/p9cnN/" rel="noreferrer">DEMO HERE</a></h2> <pre><code>Object.keys(map).forEach(function (key) { if(key.match('^'+letter)) delete obj[key]; }); </code></pre> <p>So here is an other version of <code>removeKeyStartsWith</code> with regular expression as you said:</p> <pre><code>function removeKeyStartsWith(obj, letter) { Object.keys(obj).forEach(function (key) { //if(key[0]==letter) delete obj[key];////without regex if(key.match('^'+letter)) delete obj[key];//with regex }); } var map = new Object(); map['XKey1'] = "Value1"; map['XKey2'] = "Value2"; map['YKey3'] = "Value3"; map['YKey4'] = "Value4"; console.log(map); removeKeyStartsWith(map, 'X'); console.log(map); </code></pre> <p>Solution with <code>Regex</code> will cover your need even if you use letter=Xke as you said but for the other solution without Regex , you will need to replace : </p> <p><code>Key[0]==letter</code> with <code>key.substr(0,3)==letter</code></p>
18,682,384
angular: Validate multiple dependent fields
<p>Let's say I have the following (very simple) data structure:</p> <pre><code>$scope.accounts = [{ percent: 30, name: "Checking"}, { percent: 70, name: "Savings"}]; </code></pre> <p>Then I have the following structure as part of a form:</p> <pre><code>&lt;div ng-repeat="account in accounts"&gt; &lt;input type="number" max="100" min="0" ng-model="account.percent" /&gt; &lt;input type="text" ng-model="account.name" /&gt; &lt;/div&gt; </code></pre> <p>Now, I want to validate that the percents sum to 100 for each set of accounts, but most of the examples I have seen of custom directives only deal with validating an individual value. What is an idiomatic way to create a directive that would validate multiple dependent fields at once? There are a fair amount of solutions for this in jquery, but I haven't been able to find a good source for Angular.</p> <p>EDIT: I came up with the following custom directive ("share" is a synonym for the original code's "percent"). The share-validate directive takes a map of the form <code>"{group: accounts, id: $index}"</code> as its value.</p> <pre><code>app.directive('shareValidate', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, elem, attr, ctrl) { ctrl.$parsers.unshift(function(viewValue) { params = angular.copy(scope.$eval(attr.shareValidate)); params.group.splice(params.id, 1); var sum = +viewValue; angular.forEach(params.group, function(entity, index) { sum += +(entity.share); }); ctrl.$setValidity('share', sum === 100); return viewValue; }); } }; }); </code></pre> <p>This ALMOST works, but can't handle the case in which a field is invalidated, but a subsequent change in another field makes it valid again. For example:</p> <pre><code>Field 1: 61 Field 2: 52 </code></pre> <p>If I take Field 2 down to 39, Field 2 will now be valid, but Field 1 is still invalid. Ideas?</p>
18,686,167
5
0
null
2013-09-08 09:50:12.677 UTC
7
2018-08-30 21:14:45.573 UTC
2013-09-08 15:46:11.39 UTC
null
1,553,178
null
1,553,178
null
1
28
javascript|validation|angularjs
30,705
<p>Ok, the following works (again, "share" is "percent"): </p> <pre><code>app.directive('shareValidate', function () { return { restrict: 'A', require: 'ngModel', link: function(scope, elem, attr, ctrl) { scope.$watch(attr.shareValidate, function(newArr, oldArr) { var sum = 0; angular.forEach(newArr, function(entity, i) { sum += entity.share; }); if (sum === 100) { ctrl.$setValidity('share', true); scope.path.offers.invalidShares = false; } else { ctrl.$setValidity('share', false); scope.path.offers.invalidShares = true; } }, true); //enable deep dirty checking } }; }); </code></pre> <p>In the HTML, set the attribute as "share-validate", and the value to the set of objects you want to watch.</p>
18,410,234
How does one represent the empty char?
<p>I'm currently writing a little program but I keep getting this error when compiling</p> <blockquote> <p>error: empty character constant</p> </blockquote> <p>I realize it's because I'm trying to replace a valid char with empty space <code>c[i]=''</code> but I have not been able to find another way to represent it.</p>
18,410,258
10
2
null
2013-08-23 19:12:50.613 UTC
45
2021-11-05 16:07:57.31 UTC
2016-01-02 18:30:24.113 UTC
null
2,642,204
user2494770
null
null
1
108
c
405,315
<p>You can use <code>c[i]= '\0'</code> or simply <code>c[i] = (char) 0</code>.</p> <p>The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.</p>
38,308,600
Render HTML string in Node?
<p>Alright, so I have downloaded Express, set the port with <code>process.env.PORT || 8080</code>, and set the app variable <code>var app = express()</code>. Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?</p> <pre><code>var html = "&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;h1&gt;Hello World!&lt;/h1&gt;\n &lt;/body&gt;\n&lt;/html&gt;"; app.get('/',function(req,res){ res.render(html); }); </code></pre> <p>Is there a possible way to do this?</p>
38,310,388
3
4
null
2016-07-11 13:46:12.997 UTC
2
2022-02-11 01:19:43.7 UTC
2017-07-09 22:46:36.033 UTC
null
6,568,784
null
6,568,784
null
1
18
html|node.js|rendering
38,219
<p>the <code>res.render</code> method as specified in the doc : <strong>Renders a view and sends the rendered HTML string to the client.</strong> So you need to use a template engine eg : jade,ejs, handlebars.. but if your purpose is to only output some html you can do it with <code>res.send</code> instead.</p>
9,625,246
What are the underlying data structures used for Redis?
<p>I'm trying to answer two questions in a definitive list:</p> <ol> <li>What are the underlying data structures used for Redis?</li> <li>And what are the main advantages/disadvantages/use cases for each type?</li> </ol> <p>So, I've read the Redis lists are actually implemented with linked lists. But for other types, I'm not able to dig up any information. Also, if someone were to stumble upon this question and not have a high level summary of the pros and cons of modifying or accessing different data structures, they'd have a complete list of <strong>when to best use specific types</strong> to reference as well.</p> <p>Specifically, I'm looking to outline all types: string, list, set, zset and hash.</p> <p>Oh, I've looked at these article, among others, so far:</p> <ul> <li><a href="http://redis.io/topics/data-types" rel="noreferrer">http://redis.io/topics/data-types</a></li> <li><a href="http://redis.io/topics/data-types-intro" rel="noreferrer">http://redis.io/topics/data-types-intro</a></li> <li><a href="http://redis.io/topics/faq" rel="noreferrer">http://redis.io/topics/faq</a></li> </ul>
9,626,334
3
7
null
2012-03-08 21:31:27.027 UTC
307
2015-06-07 15:57:11.037 UTC
2012-03-08 22:59:07.763 UTC
null
249,630
null
278,976
null
1
338
algorithm|data-structures|redis
54,492
<p>I'll try to answer your question, but I'll start with something that may look strange at first: if you are not interested in Redis internals you <strong>should not care</strong> about how data types are implemented internally. This is for a simple reason: for every Redis operation you'll find the time complexity in the documentation and, if you have the set of operations and the time complexity, the only other thing you need is some clue about memory usage (and because we do many optimizations that may vary depending on data, the best way to get these latter figures are doing a few trivial real world tests).</p> <p>But since you asked, here is the underlying implementation of every Redis data type.</p> <ul> <li><strong>Strings</strong> are implemented using a C dynamic string library so that we don't pay (asymptotically speaking) for allocations in append operations. This way we have O(N) appends, for instance, instead of having quadratic behavior.</li> <li><strong>Lists</strong> are implemented with linked lists.</li> <li><strong>Sets</strong> and <strong>Hashes</strong> are implemented with hash tables.</li> <li><strong>Sorted sets</strong> are implemented with <a href="http://www.catonmat.net/blog/mit-introduction-to-algorithms-part-eight/" rel="noreferrer">skip lists</a> (a peculiar type of balanced trees).</li> </ul> <p>But when lists, sets, and sorted sets are small in number of items and size of the largest values, a different, much more compact encoding is used. This encoding differs for different types, but has the feature that it is a compact blob of data that often forces an O(N) scan for every operation. Since we use this format only for small objects this is not an issue; scanning a small O(N) blob is <em>cache oblivious</em> so practically speaking it is very fast, and when there are too many elements the encoding is automatically switched to the native encoding (linked list, hash, and so forth).</p> <p>But your question was not really just about internals, your point was <em>What type to use to accomplish what?</em>.</p> <h2>Strings</h2> <p>This is the base type of all the types. It's one of the four types but is also the base type of the complex types, because a List is a list of strings, a Set is a set of strings, and so forth.</p> <p>A Redis string is a good idea in all the obvious scenarios where you want to store an HTML page, but also when you want to avoid converting your already encoded data. So for instance, if you have JSON or MessagePack you may just store objects as strings. In Redis 2.6 you can even manipulate this kind of object server side using Lua scripts.</p> <p>Another interesting usage of strings is bitmaps, and in general random access arrays of bytes, since Redis exports commands to access random ranges of bytes, or even single bits. For instance check <a href="http://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps/" rel="noreferrer">this good blog post: Fast Easy real time metrics using Redis</a>.</p> <h2>Lists</h2> <p>Lists are good when you are likely to touch only the extremes of the list: near tail, or near head. Lists are not very good to paginate stuff, because random access is slow, O(N). So good uses of lists are plain queues and stacks, or processing items in a loop using RPOPLPUSH with same source and destination to "rotate" a ring of items.</p> <p>Lists are also good when we want just to create a capped collection of N items where <em>usually</em> we access just the top or bottom items, or when N is small.</p> <h2>Sets</h2> <p>Sets are an unordered data collection, so they are good every time you have a collection of items and it is very important to check for existence or size of the collection in a very fast way. Another cool thing about sets is support for peeking or popping random elements (SRANDMEMBER and SPOP commands).</p> <p>Sets are also good to represent relations, e.g., "What are friends of user X?" and so forth. But other good data structures for this kind of stuff are sorted sets as we'll see.</p> <p>Sets support complex operations like intersections, unions, and so forth, so this is a good data structure for using Redis in a "computational" manner, when you have data and you want to perform transformations on that data to obtain some output.</p> <p>Small sets are encoded in a very efficient way.</p> <h2>Hashes</h2> <p>Hashes are the perfect data structure to represent objects, composed of fields and values. Fields of hashes can also be atomically incremented using HINCRBY. When you have objects such as users, blog posts, or some other kind of <em>item</em>, hashes are likely the way to go if you don't want to use your own encoding like JSON or similar.</p> <p>However, keep in mind that small hashes are encoded very efficiently by Redis, and you can ask Redis to atomically GET, SET or increment individual fields in a very fast fashion.</p> <p>Hashes can also be used to represent linked data structures, using references. For instance check the lamernews.com implementation of comments.</p> <h2>Sorted Sets</h2> <p>Sorted sets are the <em>only other data structures, besides lists, to maintain ordered elements</em>. You can do a number of cool stuff with sorted sets. For instance, you can have all kinds of <strong>Top Something</strong> lists in your web application. Top users by score, top posts by pageviews, top whatever, but a single Redis instance will support tons of insertion and get-top-elements operations per second.</p> <p>Sorted sets, like regular sets, can be used to describe relations, but they also allow you to paginate the list of items and to remember the ordering. For instance, if I remember friends of user X with a sorted set I can easily remember them in order of accepted friendship.</p> <p>Sorted sets are good for priority queues.</p> <p>Sorted sets are like more powerful lists where inserting, removing, or getting ranges from the the middle of the list is always fast. But they use more memory, and are O(log(N)) data structures.</p> <h2>Conclusion</h2> <p>I hope that I provided some info in this post, but it is far better to download the source code of lamernews from <a href="http://github.com/antirez/lamernews" rel="noreferrer">http://github.com/antirez/lamernews</a> and understand how it works. Many data structures from Redis are used inside Lamer News, and there are many clues about what to use to solve a given task.</p> <p>Sorry for grammar typos, it's midnight here and too tired to review the post ;)</p>
9,509,595
Finding the shortest path in a graph without any negative prefixes
<blockquote> <p>Find the shortest path from source to destination in a directed graph with positive and negative edges, such that at no point in the path the sum of edges coming before it is negative. If no such path exists report that too.</p> </blockquote> <p>I tried to use modified Bellman Ford, but could not find the correct solution.</p> <hr> <p>I would like to clarify a few points :</p> <ol> <li>yes there can be negative weight cycles. </li> <li>n is the number of edges. </li> <li>Assume that a O(n) length path exists if the problem has a solution.</li> <li>+1/-1 edge weights.</li> </ol>
9,674,800
9
13
null
2012-03-01 02:02:19.55 UTC
11
2012-03-18 13:24:26.09 UTC
2012-03-15 18:07:45.583 UTC
null
1,240,022
null
1,240,022
null
1
17
algorithm|constraints|shortest-path|bellman-ford
2,645
<p>Admittedly this isn't a constructive answer, however it's too long to post in a comment...</p> <p>It seems to me that this problem contains the binary as well as discrete knapsack problems, so its worst-case-running-time is at best <a href="http://en.wikipedia.org/wiki/Pseudo-polynomial_time" rel="noreferrer">pseudo-polynomial</a>. Consider a graph that is connected and weighted as follows:</p> <p><img src="https://i.stack.imgur.com/2XosK.png" alt="Graph with initial edge with weight x and then a choice of -a(i) or 0 at each step"></p> <p>Then the equivalent binary knapsack problem is trying to choose weights from the set {<em>a</em><sub>0</sub>, ..., <em>a</em><sub><em>n</em></sub>} that maximizes Σ <em>a</em><sub><em>i</em></sub> where Σ <em>a</em><sub><em>i</em></sub> &lt; <em>X</em>.</p> <p>As a side note, if we introduce weighted loops it's easy to construct the unbounded knapsack problem instead.</p> <p>Therefore, any practical algorithm you might choose has a running time that depends on what you consider the "average" case. Is there a restriction to the problem that I've either not considered or not had at my disposal? You seem rather sure it's an O(<em>n</em><sup>3</sup>) problem. (Although what's <em>n</em> in this case?)</p>
8,573,636
Hibernate, JDBC and Java performance on medium and big result set
<h1>Issue</h1> <p>We are trying to optimize our dataserver application. It stores stocks and quotes over a mysql database. And we are not satisfied with the fetching performances.</p> <h1>Context</h1> <pre><code>- database - table stock : around 500 lines - table quote : 3 000 000 to 10 000 000 lines - one-to-many association : one stock owns n quotes - fetching around 1000 quotes per request - there is an index on (stockId,date) in the quote table - no cache, because in production, querys are always different - Hibernate 3 - mysql 5.5 - Java 6 - JDBC mysql Connector 5.1.13 - c3p0 pooling </code></pre> <h1>Tests and results</h1> <h2>Protocol</h2> <ul> <li>Execution times on mysql server are obtained with running the generated sql queries in mysql command line bin.</li> <li>The server is in a test context : no other DB readings, no DB writings</li> <li>We fetch 857 quotes for the AAPL stock</li> </ul> <h2>Case 1 : Hibernate with association</h2> <p>This fills up our stock object with 857 quotes object (everything correctly mapped in hibernate.xml)</p> <pre><code>session.enableFilter("after").setParameter("after", 1322910573000L); Stock stock = (Stock) session.createCriteria(Stock.class). add(Restrictions.eq("stockId", stockId)). setFetchMode("quotes", FetchMode.JOIN).uniqueResult(); </code></pre> <p>SQL generated :</p> <pre><code>SELECT this_.stockId AS stockId1_1_, this_.symbol AS symbol1_1_, this_.name AS name1_1_, quotes2_.stockId AS stockId1_3_, quotes2_.quoteId AS quoteId3_, quotes2_.quoteId AS quoteId0_0_, quotes2_.value AS value0_0_, quotes2_.stockId AS stockId0_0_, quotes2_.volume AS volume0_0_, quotes2_.quality AS quality0_0_, quotes2_.date AS date0_0_, quotes2_.createdDate AS createdD7_0_0_, quotes2_.fetcher AS fetcher0_0_ FROM stock this_ LEFT OUTER JOIN quote quotes2_ ON this_.stockId=quotes2_.stockId AND quotes2_.date &gt; 1322910573000 WHERE this_.stockId='AAPL' ORDER BY quotes2_.date ASC </code></pre> <p>Results : </p> <ul> <li>Execution time on mysql server : <strong>~10 ms</strong></li> <li>Execution time in Java : <strong>~400ms</strong></li> </ul> <h2>Case 2 : Hibernate without association without HQL</h2> <p>Thinking to increase performance, we've used that code that fetch only the quotes objects and we manually add them to a stock (so we don't fetch repeated infos about the stock for every line). We used createSQLQuery to minimize effects of aliases and HQL mess.</p> <pre><code>String filter = " AND q.date&gt;1322910573000"; filter += " ORDER BY q.date DESC"; Stock stock = new Stock(stockId); stock.addQuotes((ArrayList&lt;Quote&gt;) session.createSQLQuery("select * from quote q where stockId='" + stockId + "' " + filter).addEntity(Quote.class).list()); </code></pre> <p>SQL generated :</p> <pre><code>SELECT * FROM quote q WHERE stockId='AAPL' AND q.date&gt;1322910573000 ORDER BY q.date ASC </code></pre> <p>Results :</p> <ul> <li>Execution time on mysql server : <strong>~10 ms</strong></li> <li>Execution time in Java : <strong>~370ms</strong></li> </ul> <h2>Case 3 : JDBC without Hibernate</h2> <pre><code>String filter = " AND q.date&gt;1322910573000"; filter += " ORDER BY q.date DESC"; Stock stock = new Stock(stockId); Connection conn = SimpleJDBC.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from quote q where stockId='" + stockId + "' " + filter); while(rs.next()) { stock.addQuote(new Quote(rs.getInt("volume"), rs.getLong("date"), rs.getFloat("value"), rs.getByte("fetcher"))); } stmt.close(); conn.close(); </code></pre> <p>Results :</p> <ul> <li>Execution time on mysql server : <strong>~10 ms</strong></li> <li>Execution time in Java : <strong>~100ms</strong></li> </ul> <h1>Our understandings</h1> <ul> <li>The JDBC driver is common to all the cases</li> <li>There is a fundamental time cost in JDBC driving</li> <li>With similar sql queries, Hibernate spends more time than pure JDBC code in converting result sets in objects</li> <li>Hibernate createCriteria, createSQLQuery or createQuery are similar in time cost</li> <li>In production, where we have lots of writing concurrently, pure JDBC solution seemed to be slower than the hibernate one (maybe because our JDBC solutions was not pooled)</li> <li>Mysql wise, the server seems to behave very well, and the time cost is very acceptable</li> </ul> <h1>Our questions</h1> <ul> <li>Is there a way to optimize the performance of JDBC driver ?</li> <li>And will Hibernate benefit this optimization ?</li> <li>Is there a way to optimize Hibernate performance when converting result sets ?</li> <li>Are we facing something not tunable because of Java fundamental object and memory management ?</li> <li>Are we missing a point, are we stupid and all of this is vain ?</li> <li>Are we french ? Yes.</li> </ul> <p>Your help is very welcome.</p>
8,574,101
1
5
null
2011-12-20 09:55:49.46 UTC
10
2014-10-13 11:39:49.937 UTC
2011-12-20 10:16:14.91 UTC
null
605,744
null
1,107,380
null
1
19
java|mysql|performance|hibernate|jdbc
5,369
<p>Can you do a smoke test with the simples query possible like:</p> <pre><code>SELECT current_timestamp() </code></pre> <p>or</p> <pre><code>SELECT 1 + 1 </code></pre> <p>This will tell you what is the actual JDBC driver overhead. Also it is not clear whether both tests are performed from the same machine.</p> <blockquote> <p>Is there a way to optimize the performance of JDBC driver ?</p> </blockquote> <p>Run the same query several thousand times in Java. JVM needs some time to warm-up (class-loading, JIT). Also I assume <code>SimpleJDBC.getConnection()</code> uses C3P0 connection pooling - the cost of establishing a connection is pretty high so first few execution could be slow.</p> <p>Also prefer named queries to ad-hoc querying or criteria query.</p> <blockquote> <p>And will Hibernate benefit this optimization ?</p> </blockquote> <p>Hibernate is a very complex framework. As you can see it consumes 75% of the overall execution time compared to raw JDBC. If you need raw ORM (no lazy-loading, dirty checking, advanced caching), consider <a href="http://www.mybatis.org/" rel="nofollow noreferrer">mybatis</a>. Or maybe even <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html" rel="nofollow noreferrer"><code>JdbcTemplate</code></a> with <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/RowMapper.html" rel="nofollow noreferrer"><code>RowMapper</code></a> abstraction.</p> <blockquote> <p>Is there a way to optimize Hibernate performance when converting result sets ?</p> </blockquote> <p>Not really. Check out the <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html" rel="nofollow noreferrer"><em>Chapter 19. Improving performance</em></a> in Hibernate documentation. There is <em>a lot</em> of reflection happening out there + class generation. Once again, Hibernate might not be a best solution when you want to squeeze every millisecond from your database.</p> <p><strong>However</strong> it is a good choice when you want to increase the overall user experience due to extensive caching support. Check out the <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html" rel="nofollow noreferrer"><em>performance</em></a> doc again. It mostly talks about caching. There is a first level cache, second level cache, query cache... This is the place where Hibernate might actually outperform simple JDBC - it can cache a lot in a ways you could not even imagine. On the other hand - poor cache configuration would lead to even slower setup.</p> <p>Check out: <a href="https://stackoverflow.com/questions/5405417">Caching with Hibernate + Spring - some Questions!</a></p> <blockquote> <p>Are we facing something not tunable because of Java fundamental object and memory management ?</p> </blockquote> <p>JVM (especially in <em>server</em> configuration) is quite fast. Object creation on the heap is as fast as on the stack in e.g. C, garbage collection has been greatly optimized. I don't think the Java version running plain JDBC would be much slower compared to more native connection. That's why I suggested few improvements in your benchmark.</p> <blockquote> <p>Are we missing a point, are we stupid and all of this is vain ?</p> </blockquote> <p>I believe that JDBC is a good choice if performance is your biggest issue. Java has been used successfully in a lot of database-heavy applications.</p>
8,408,046
How to change the name of a Django app?
<p>I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run <code>python manage.py runserver</code></p> <pre><code>Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings </code></pre> <p>How can I debug and solve this error? Any clues?</p>
8,408,131
9
5
null
2011-12-06 22:51:04.023 UTC
119
2021-10-02 12:22:19.107 UTC
2014-01-10 12:51:56.71 UTC
null
1,030,960
null
488,735
null
1
215
python|django
171,647
<p>Follow these steps to change an app's name in Django:</p> <ol> <li>Rename the folder which is in your project root</li> <li>Change any references to your app in their dependencies, i.e. the app's <code>views.py</code>, <code>urls.py</code> , <code>manage.py</code> , and <code>settings.py</code> files.</li> <li>Edit the database table <code>django_content_type</code> with the following command: <code>UPDATE django_content_type SET app_label='&lt;NewAppName&gt;' WHERE app_label='&lt;OldAppName&gt;'</code></li> <li>Also, if you have models, you will have to rename the model tables. For postgres, use <code>ALTER TABLE &lt;oldAppName&gt;_modelName RENAME TO &lt;newAppName&gt;_modelName</code>. For mysql too, I think it is the same (as mentioned by @null_radix).</li> <li>(For Django &gt;= 1.7) Update the <code>django_migrations</code> table to avoid having your previous migrations re-run: <code>UPDATE django_migrations SET app='&lt;NewAppName&gt;' WHERE app='&lt;OldAppName&gt;'</code>. <strong>Note</strong>: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.</li> <li>If your <code>models.py</code> 's Meta Class has <code>app_name</code> listed, make sure to rename that too (mentioned by @will).</li> <li>If you've namespaced your <code>static</code> or <code>templates</code> folders inside your app, you'll also need to rename those. For example, rename <code>old_app/static/old_app</code> to <code>new_app/static/new_app</code>.</li> <li>For renaming django <code>models</code>, you'll need to change <code>django_content_type.name</code> entry in DB. For postgreSQL, use <code>UPDATE django_content_type SET name='&lt;newModelName&gt;' where name='&lt;oldModelName&gt;' AND app_label='&lt;OldAppName&gt;'</code></li> <li><strong>Update 16Jul2021</strong>: Also, the <code>__pycache__/</code> folder inside the app must be removed, otherwise you get <code>EOFError: marshal data too short when trying to run the server</code>. Mentioned by @Serhii Kushchenko</li> </ol> <p><strong>Meta point (If using virtualenv):</strong> Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as <code>ImportError: No module named ...</code> this might be the culprit. (thanks to @danyamachine for providing this).</p> <p><strong>Other references:</strong> you might also want to refer to the below links for a more complete picture:</p> <ol> <li><a href="https://stackoverflow.com/questions/4566978/renaming-an-app-with-django-and-south">Renaming an app with Django and South</a></li> <li><a href="https://stackoverflow.com/questions/1258130/how-do-i-migrate-a-model-out-of-one-django-app-and-into-a-new-one">How do I migrate a model out of one django app and into a new one?</a></li> <li><a href="https://stackoverflow.com/questions/8408046/how-to-change-the-name-of-a-django-app?noredirect=1&amp;lq=1">How to change the name of a Django app?</a></li> <li><a href="https://stackoverflow.com/questions/5814190/backwards-migration-with-django-south?rq=1">Backwards migration with Django South</a></li> <li><a href="https://stackoverflow.com/questions/2862979/easiest-way-to-rename-a-model-using-django-south?rq=1">Easiest way to rename a model using Django/South?</a></li> <li><a href="https://github.com/amirraouf/change-django-app-name" rel="noreferrer">Python code</a> (thanks to <a href="https://stackoverflow.com/users/1690893/a-raouf">A.Raouf</a>) to automate the above steps (Untested code. You have been warned!)</li> <li><a href="https://gist.github.com/rafaponieman/201054ddf725cda1e60be3fe845850a5" rel="noreferrer">Python code</a> (thanks to <a href="https://stackoverflow.com/users/2453104/rafaponieman">rafaponieman</a>) to automate the above steps (Untested code. You have been warned!)</li> </ol>
5,373,474
Multiple positional arguments with Python and argparse
<p>I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot of the namespace each time a positional argument is found), but the problem I'm having can be replicated with the <code>append</code> action:</p> <pre><code>&gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser() &gt;&gt;&gt; parser.add_argument('-a', action='store_true') &gt;&gt;&gt; parser.add_argument('-b', action='store_true') &gt;&gt;&gt; parser.add_argument('input', action='append') &gt;&gt;&gt; parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) usage: ipython [-h] [-a] [-b] input ipython: error: unrecognized arguments: filetwo filethree </code></pre> <p>I'd like this to result in the namespace <code>(a=True, b=True, input=['fileone', 'filetwo', 'filethree'])</code>, but cannot see how to do this - if indeed it can. I can't see anything in the docs or Google which says one way or the other if this is possible, although its quite possible (likely?) I've overlooked something. Does anyone have any suggestions?</p>
5,374,229
4
1
null
2011-03-21 03:17:12.573 UTC
8
2017-07-06 15:56:11.817 UTC
null
null
null
null
668,807
null
1
38
python|argparse
48,179
<p>srgerg was right about the definition of positional arguments. In order to get the result you want, You have to accept them as optional arguments, and modify the resulted namespace according to your need. </p> <p>You can use a custom action:</p> <pre><code>class MyAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): # Set optional arguments to True or False if option_string: attr = True if values else False setattr(namespace, self.dest, attr) # Modify value of "input" in the namespace if hasattr(namespace, 'input'): current_values = getattr(namespace, 'input') try: current_values.extend(values) except AttributeError: current_values = values finally: setattr(namespace, 'input', current_values) else: setattr(namespace, 'input', values) parser = argparse.ArgumentParser() parser.add_argument('-a', nargs='+', action=MyAction) parser.add_argument('-b', nargs='+', action=MyAction) parser.add_argument('input', nargs='+', action=MyAction) </code></pre> <p>And this is what you get:</p> <pre><code>&gt;&gt;&gt; parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree']) </code></pre> <p>Or you can modify the resulted namespace like this:</p> <pre><code>&gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser() &gt;&gt;&gt; parser.add_argument('-a', nargs='+') &gt;&gt;&gt; parser.add_argument('-b', nargs='+') &gt;&gt;&gt; parser.add_argument('input', nargs='+') &gt;&gt;&gt; result = parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) &gt;&gt;&gt; inputs = [] &gt;&gt;&gt; inputs.extend(result.a) &gt;&gt;&gt; inputs.extend(result.b) &gt;&gt;&gt; inputs.extend(result.input) &gt;&gt;&gt; modified = argparse.Namespace( a = result.a != [], b = result.b != [], input = inputs) </code></pre> <p>And this is what you get:</p> <pre><code>&gt;&gt;&gt; modified Namespace(a=True, b=True, input=['filetwo', 'filethree', 'fileone']) </code></pre> <p>However, both method result in less readable and less maintainable code. Maybe it's better to change the program logic and do it in a different way.</p>
5,320,205
Matplotlib text dimensions
<p>Is it possible to determine the dimensions of a matplotlib text object? How can I find the width and height in pixels?</p> <p>Thanks</p> <p><strong>Edit</strong>: I think I figured out a way to do this. I've included an example below.</p> <pre><code>import matplotlib as plt f = plt.figure() r = f.canvas.get_renderer() t = plt.text(0.5, 0.5, 'test') bb = t.get_window_extent(renderer=r) width = bb.width height = bb.height </code></pre>
36,959,454
4
3
null
2011-03-16 01:56:03.46 UTC
13
2020-11-22 07:59:55.327 UTC
2015-07-17 12:52:07.15 UTC
null
152,650
null
152,650
null
1
42
python|matplotlib
19,775
<pre><code>from matplotlib import pyplot as plt f = plt.figure() r = f.canvas.get_renderer() t = plt.text(0.5, 0.5, 'test') bb = t.get_window_extent(renderer=r) width = bb.width height = bb.height </code></pre>
4,961,910
Appending/concatenating two IEnumerable sequences
<p>I have two sets of datarows. They are each IEnumerable. I want to append/concatenate these two lists into one list. I'm sure this is doable. I don't want to do a for loop and noticed that there is a Union method and a Join method on the two Lists. Any ideas?</p>
4,961,949
4
2
null
2011-02-10 19:53:10.663 UTC
4
2019-09-06 22:15:54.787 UTC
2019-05-31 08:19:00.947 UTC
null
542,251
null
368,259
null
1
46
c#|ienumerable|unions
35,592
<p>Assuming your objects are of the same type, you can use either <code>Union</code> or <code>Concat</code>. Note that, like the SQL <code>UNION</code> keyword, the <code>Union</code> operation will ensure that duplicates are eliminated, whereas <code>Concat</code> (like <code>UNION ALL</code>) will simply add the second list to the end of the first.</p> <pre><code>IEnumerable&lt;T&gt; first = ...; IEnumerable&lt;T&gt; second = ...; IEnumerable&lt;T&gt; combined = first.Concat(second); </code></pre> <p>or</p> <pre><code>IEnumerable&lt;T&gt; combined = first.Union(second); </code></pre> <p>If they are of different types, then you'll have to <code>Select</code> them into something common. For example:</p> <pre><code>IEnumerable&lt;TOne&gt; first = ...; IEnumerable&lt;TTwo&gt; second = ...; IEnumerable&lt;T&gt; combined = first.Select(f =&gt; ConvertToT(f)).Concat( second.Select(s =&gt; ConvertToT(s))); </code></pre> <p>Where <code>ConvertToT(TOne f)</code> and <code>ConvertToT(TTwo s)</code> represent an operation that somehow converts an instance of <code>TOne</code> (and <code>TTwo</code>, respectively) into an instance of <code>T</code>.</p>
5,484,205
Call function with setInterval in jQuery?
<p>I'm trying to create a interval call to a function in jQuery, but it doesn't work! My first question is, can I mix common JavaScript with jQuery? </p> <p>Should I use <code>setInterval("test()",1000);</code> or something like this:</p> <pre><code>var refreshId = setInterval(function(){ code... }, 5000); </code></pre> <p>Where do I put the function that I call and how do I activate the interval? Is it a difference in how to declare a function in JavaScript compared to jQuery?</p>
5,484,273
5
1
null
2011-03-30 09:00:25.763 UTC
8
2020-07-07 09:55:42.233 UTC
2011-03-30 09:08:48.81 UTC
null
218,196
null
637,364
null
1
25
javascript|jquery
118,756
<p>To write the best code, you "should" use the latter approach, with a function reference:</p> <pre><code>var refreshId = setInterval(function() {}, 5000); </code></pre> <p>or</p> <pre><code>function test() {} var refreshId = setInterval(test, 5000); </code></pre> <p>but your approach of </p> <pre><code>function test() {} var refreshId = setInterval("test()", 5000); </code></pre> <p>is basically valid, too (as long as <code>test()</code> is global).</p> <p>Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.</p>
4,874,408
Better way of getting time in milliseconds in javascript?
<p>Is there an alternative in JavaScript of getting time in milliseconds using the date object, or at least a way to reuse that object, without having to instantiate a new object every time I need to get this value? I am asking this because I am trying to make a simple game engine in JavaScript, and when calculating the "delta frame time", I have to create a new Date object every frame. While I am not too worried about the performance implications of this, I am having some problems with the reliability of the exact time returned by this object.</p> <p>I get some strange "jumping" in the animation, every second or so, and I am not sure if this is related to JavaScript's Garbage Collection or a limitation of the Date object when updating so fast. If I set the delta value to some constant, then the animation if perfectly smooth, so I am fairly sure this "jumping" is related to the way I get the time.</p> <p>The only relevant code I can give is the way I calculate the delta time :</p> <pre><code>prevTime = curTime; curTime = (new Date()).getTime(); deltaTime = curTime - prevTime; </code></pre> <p>When calculating movement / animation I multiply a constant value with the delta time.</p> <p>If there is no way to avoid getting the time in milliseconds by using the Date object, would a function that increments a variable (being the elapsed time in milliseconds since the game started), and which is called using the SetTimer function at a rate of once every milliseconds be an efficient and reliable alternative? </p> <p>Edit : I have tested now my code in different browsers and it seems that this "jump" is really only apparent in Chrome, not in Firefox. But it would still be nice if there were a method that worked in both browsers.</p>
4,874,570
5
4
null
2011-02-02 12:22:17.287 UTC
19
2018-03-08 03:24:30.58 UTC
2018-03-08 03:22:03.947 UTC
null
933,198
null
522,895
null
1
157
javascript
184,768
<p>Try <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now" rel="noreferrer">Date.now()</a>.</p> <p>The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.</p>
4,982,277
UIView drag (image and text)
<p>Is it possible to drag UIView around the iOS screen while it has both image and text? e.g. small cards. Could you point me to the similar (solved) topic? I haven't found any.</p>
4,983,124
6
0
null
2011-02-13 03:35:09.277 UTC
19
2015-12-06 15:57:03.497 UTC
null
null
null
null
480,773
null
1
27
iphone|objective-c
23,151
<p>While UIView does not have a built-in support for moving itself along the user dragging, it should be not so difficult to implement it. It is even easier when you are only dealing with dragging on the view, and not other actions such as tapping, double tapping, multi-touches etc. </p> <p>First thing to do is to make a custom view, say <code>DraggableView</code>, by subclassing UIView. Then override UIView's <code>touchesMoved:withEvent:</code> method, and you can get a current dragging location there, and move the DraggableView. Look at the following example.</p> <pre><code>-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *aTouch = [touches anyObject]; CGPoint location = [aTouch locationInView:self.superview]; [UIView beginAnimations:@"Dragging A DraggableView" context:nil]; self.frame = CGRectMake(location.x, location.y, self.frame.size.width, self.frame.size.height); [UIView commitAnimations]; } </code></pre> <p>And because all subviews of the DraggableView object will be moved, too. So put all your images and texts as subviews of the DraggableView object.</p> <p>What I implemented here is very simple. However, if you want more complex behaviors for the dragging, (for example, the user have to tap on the view for a few seconds to move the view), then you will have to override other event handling methods (touchesBegan:withEvent: and touchesEnd:withEvent) as well.</p>
5,333,898
Best way to pop many elements from a Python dict
<p>This is my code:</p> <pre><code>a = dict(aa='aaaa', bb='bbbbb', cc='ccccc', ...) print(a.pop(['cc', ...])) </code></pre> <p>but this raises an error. What is the best simple way to pop many elements from a python dictionary?</p>
5,333,919
6
0
null
2011-03-17 01:36:08.13 UTC
7
2022-01-20 11:42:57.813 UTC
2017-09-30 20:06:50.81 UTC
null
1,959,808
null
420,840
null
1
38
python|dictionary
48,694
<p>How about the simple:</p> <pre><code>for e in ['cc', 'dd',...]: a.pop(e) </code></pre>
4,929,243
Clarifying terminology - What does "hydrating" a JPA or Hibernate entity mean when fetching the entity from the DB
<p>In the context of ORM / Lazy loading of entities, my understanding of the term "Hydration" is as follows:</p> <p>"Hydrating" describes the process of populating some or all of the previously unpopulated attributes of an entity fetched using lazy loading.</p> <p>Eg: class <code>Author</code> is loaded from the database:</p> <pre><code>@Entity class Author { @Id long id; List&lt;Book&gt; books; } </code></pre> <p>Initially, the <code>books</code> collection is not populated.</p> <p>It is my understanding that the process of loading the <code>books</code> collection from the database is referred to as "Hydrating" the collection.</p> <p>Is this definition correct, and is the term common place? Is there another more common term I should be using for this process?</p>
4,929,478
6
0
null
2011-02-08 03:19:09.71 UTC
13
2022-08-31 17:44:54.7 UTC
2020-10-27 09:27:19.703 UTC
null
1,025,118
null
59,015
null
1
92
java|hibernate|jpa|orm|lazy-loading
34,896
<p>Hydrate began as a term for populating an instantiated (but empty) value-object/model from a db, (specifically in Hibernate.)</p> <p>Various other ORMs and tools like BizTalk use Hydrate and other related terminology, (e.g. BizTalk uses the term Dehydrated to mean an instance is available but not yet populated.)</p> <p>Personally I'm averse to redundant terminology overhauls, <strong>populated</strong> means the same thing, without re-inventing language. It adds nothing and leads to confusion (common first thought on encountering re-invented terms: <em>is this somehow different and magical?</em>).</p> <p>The BizTalk extension of this style of language, specifically <strong>Dehydrated</strong> is redundant. I expect people haven't forgotten how to say, <strong><em>empty</em></strong>, or <strong><em>clear</em></strong>?</p> <p><em>Hydrated</em> and its related metaphors are essentially marketing tools, invented to differentiate Hibernate from competing products.</p> <p>At this point Hibernate and other ORM products have used these terms for many years, so Hydrate (and Dehydrate) are here to stay.</p>
5,374,311
Convert ArrayList<String> to String[] array
<p>I'm working in the android environment and have tried the following code, but it doesn't seem to be working.</p> <pre><code>String [] stockArr = (String[]) stock_list.toArray(); </code></pre> <p>If I define as follows:</p> <pre><code>String [] stockArr = {"hello", "world"}; </code></pre> <p>it works. Is there something that I'm missing?</p>
5,374,359
6
3
null
2011-03-21 05:57:59.193 UTC
236
2018-10-01 09:34:58.423 UTC
2018-07-30 18:32:04.113 UTC
null
1,746,118
null
382,906
null
1
1,208
java|arrays|arraylist
1,610,111
<p>Use like this.</p> <pre><code>List&lt;String&gt; stockList = new ArrayList&lt;String&gt;(); stockList.add("stock1"); stockList.add("stock2"); String[] stockArr = new String[stockList.size()]; stockArr = stockList.toArray(stockArr); for(String s : stockArr) System.out.println(s); </code></pre>
5,535,512
How to hack GHCi (or Hugs) so that it prints Unicode chars unescaped?
<p>Look at the problem: Normally, in the interactive Haskell environment, non-Latin Unicode characters (that make a part of the results) are printed escaped, even if the locale allows such characters (as opposed to direct output through <code>putStrLn</code>, <code>putChar</code> which looks fine and readable)--the examples show GHCi and Hugs98:</p> <pre><code>$ ghci GHCi, version 7.0.1: http://www.haskell.org/ghc/ :? for help Prelude&gt; "hello: привет" "hello: \1087\1088\1080\1074\1077\1090" Prelude&gt; 'Я' '\1071' Prelude&gt; putStrLn "hello: привет" hello: привет Prelude&gt; :q Leaving GHCi. $ hugs -98 __ __ __ __ ____ ___ _________________________________________ || || || || || || ||__ Hugs 98: Based on the Haskell 98 standard ||___|| ||__|| ||__|| __|| Copyright (c) 1994-2005 ||---|| ___|| World Wide Web: http://haskell.org/hugs || || Bugs: http://hackage.haskell.org/trac/hugs || || Version: September 2006 _________________________________________ Hugs mode: Restart with command line option +98 for Haskell 98 mode Type :? for help Hugs&gt; "hello: привет" "hello: \1087\1088\1080\1074\1077\1090" Hugs&gt; 'Я' '\1071' Hugs&gt; putStrLn "hello: привет" hello: привет Hugs&gt; :q [Leaving Hugs] $ locale LANG=ru_RU.UTF-8 LC_CTYPE="ru_RU.UTF-8" LC_NUMERIC="ru_RU.UTF-8" LC_TIME="ru_RU.UTF-8" LC_COLLATE="ru_RU.UTF-8" LC_MONETARY="ru_RU.UTF-8" LC_MESSAGES="ru_RU.UTF-8" LC_PAPER="ru_RU.UTF-8" LC_NAME="ru_RU.UTF-8" LC_ADDRESS="ru_RU.UTF-8" LC_TELEPHONE="ru_RU.UTF-8" LC_MEASUREMENT="ru_RU.UTF-8" LC_IDENTIFICATION="ru_RU.UTF-8" LC_ALL= $ </code></pre> <p>We can guess that it's because <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:print" rel="noreferrer"><code>print</code></a> and <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:show" rel="noreferrer"><code>show</code></a> are used to format the result, and these functions do their best to format the data in a canonical, maximally portable way -- so they prefer to escape the strange characters (perhaps, it's even spelled out in a standard for Haskell):</p> <pre><code>$ ghci GHCi, version 7.0.1: http://www.haskell.org/ghc/ :? for help Prelude&gt; show 'Я' "'\\1071'" Prelude&gt; :q Leaving GHCi. $ hugs -98 Type :? for help Hugs&gt; show 'Я' "'\\1071'" Hugs&gt; :q [Leaving Hugs] $ </code></pre> <p>But still it would be nice if we knew how to hack GHCi or Hugs to print these characters in the pretty human-readable way, i.e. directly, unescaped. This can be appreciated when using the interactive Haskell environment in educational purposes, for a tutorial/demonstration of Haskell in front of a non-English audience whom you want to show some Haskell on data in their human language.</p> <p>Actually, it's not only useful for educational purposes but for debugging, as well! When you have functions that are defined on strings representing words of other languages, with non-ASCII characters. So, if the program is language-specific, and only words of another language make sense as the data, and you have functions that are defined only on such words, it's important for debugging in GHCi to see this data.</p> <p><strong>To sum up my question:</strong> What ways to hack the existing interactive Haskell environments for a friendlier printing of Unicode in the results are there? ("Friendlier" means even "simpler" in my case: I'd like <code>print</code> in GHCi or Hugs to show non-Latin characters the simple direct way as done by <code>putChar</code>, <code>putStrLn</code>, i.e. unescaped.)</p> <p>(Perhaps, besides GHCi and Hugs98, I'll also have a look at existing Emacs modes for interacting with Haskell to see if they can present the results in the pretty, unescaped fashion.)</p>
5,621,230
7
8
null
2011-04-04 07:05:40.327 UTC
13
2019-11-13 00:50:40.25 UTC
2015-03-08 11:59:43.48 UTC
null
94,687
null
94,687
null
1
28
unicode|haskell|formatting|locale|ghci
6,366
<h2>Option 1 (bad):</h2> <p>Modify this line of code:</p> <p><a href="https://github.com/ghc/packages-base/blob/ba98712/GHC/Show.lhs#L356" rel="nofollow">https://github.com/ghc/packages-base/blob/ba98712/GHC/Show.lhs#L356</a></p> <pre><code>showLitChar c s | c &gt; '\DEL' = showChar '\\' (protectEsc isDec (shows (ord c)) s) </code></pre> <p>And recompile ghc.</p> <h2>Option 2 (lots of work):</h2> <p>When GHCi type checks a parsed statement it ends up in <code>tcRnStmt</code> which relies on <code>mkPlan</code> (both in <a href="https://github.com/ghc/ghc/blob/master/compiler/typecheck/TcRnDriver.lhs" rel="nofollow">https://github.com/ghc/ghc/blob/master/compiler/typecheck/TcRnDriver.lhs</a>). This attempts to type check several variants of the statement that was typed in including:</p> <pre><code>let it = expr in print it &gt;&gt; return [coerce HVal it] </code></pre> <p>Specifically:</p> <pre><code>print_it = L loc $ ExprStmt (nlHsApp (nlHsVar printName) (nlHsVar fresh_it)) (HsVar thenIOName) placeHolderType </code></pre> <p>All that might need to change here is <code>printName</code> (which binds to <code>System.IO.print</code>). If it instead bound to something like <code>printGhci</code> which was implemented like:</p> <pre><code>class ShowGhci a where showGhci :: a -&gt; String ... -- Bunch of instances? instance ShowGhci Char where ... -- The instance we want to be different. printGhci :: ShowGhci a =&gt; a -&gt; IO () printGhci = putStrLn . showGhci </code></pre> <p>Ghci could then change what is printed by bringing different instances into context.</p>
5,364,278
Creating an array of objects in Java
<p>I am new to Java and for the time created an array of objects in Java. </p> <p>I have a class A for example - </p> <pre><code>A[] arr = new A[4]; </code></pre> <p>But this is only creating pointers (references) to <code>A</code> and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception. To be able to manipulate/access the objects I had to do this:</p> <pre><code>A[] arr = new A[4]; for (int i = 0; i &lt; 4; i++) { arr[i] = new A(); } </code></pre> <p>Is this correct or am I doing something wrong? If this is correct its really odd.</p> <p>EDIT: I find this odd because in C++ you just say new <code>A[4]</code> and it creates the four objects.</p>
5,364,320
9
1
null
2011-03-19 19:13:08.553 UTC
84
2021-07-24 06:08:29.25 UTC
2020-03-29 07:24:06.707 UTC
null
452,775
null
220,201
null
1
217
java|arrays|class
808,562
<p>This is correct.</p> <pre><code>A[] a = new A[4]; </code></pre> <p>...creates 4 <code>A</code> references, similar to doing this:</p> <pre><code>A a1; A a2; A a3; A a4; </code></pre> <p>Now you couldn't do <code>a1.someMethod()</code> without allocating <code>a1</code> like this:</p> <pre><code>a1 = new A(); </code></pre> <p>Similarly, with the array you need to do this:</p> <pre><code>a[0] = new A(); </code></pre> <p>...before using it.</p>
5,546,514
Making a LinearLayout act like an Button
<p>I have a <code>LinearLayout</code> that I've styled to look like a <code>button</code>, and it contains a few text/ImageView elements. I would like to make the whole <code>LinearLayout</code> act like a <code>button</code>, in particular to give it states that are defined in a so it has a different background when it is pressed.</p> <p>Is there a better way than making an <code>ImageButton</code> the size of the whole Layout and positioning absolutely?</p>
6,310,257
10
2
null
2011-04-05 02:26:09.77 UTC
26
2020-09-17 17:57:05.523 UTC
2019-03-08 12:44:17.987 UTC
null
5,973,614
null
106,517
null
1
109
android|android-layout
94,090
<p>I ran into this problem just now. You'll have to set the LinearLayout to clickable. You can either do this in the XML with</p> <pre><code>android:clickable="true" </code></pre> <p>Or in code with</p> <pre><code>yourLinearLayout.setClickable(true); </code></pre> <p>Cheers!</p>
29,509,396
SignalR Client How to Set user when start connection?
<p>Server side:</p> <pre><code>public override Task OnConnected() { var connectionId = Context.ConnectionId; var user = Context.User.Identity.Name; // Context.User is NULL return base.OnConnected(); } </code></pre> <p>Client side (in Console project):</p> <pre><code>IHubProxy _hub; string url = @"http://localhost:8080/"; var connection = new HubConnection(url); _hub = connection.CreateHubProxy("TestHub"); connection.Start().Wait(); </code></pre> <p>When the client connect to the server, I want to know the map between userName and connectionId, But <code>Context.User</code> is NULL. How do I set this value in the client side?</p>
29,509,484
5
5
null
2015-04-08 08:18:25.33 UTC
8
2022-04-20 01:21:04.607 UTC
2015-04-14 08:22:53.57 UTC
null
3,455,216
null
3,011,354
null
1
18
javascript|c#|signalr|signalr-hub|signalr.client
18,147
<p>Pass your username using query string.</p> <p><strong>Client</strong></p> <p>First set query string</p> <pre><code>string url = @"http://localhost:8080/"; var connection = new HubConnection(url); _hub = connection.CreateHubProxy("TestHub"); connection.qs = { 'username' : 'anik' }; connection.Start().Wait(); </code></pre> <p><strong>Server</strong></p> <pre><code>public override Task OnConnected() { var username= Context.QueryString['username']; return base.OnConnected(); } </code></pre>
12,052,379
Matplotlib: draw a selection area in the shape of a rectangle with the mouse
<p>I want to be able to draw a selection area on a matplotlib plot with a mouse event. I didn't find information on how to do it with python.</p> <p>In the end, I want to be able to draw a region of interest with my mouse on a map created with matplotlib basemap and retrieve the corner coordinates.</p> <p>Anyone has an idea, example, references?</p> <p>Thanks,</p> <p>Greg</p> <pre><code>class Annotate(object): def __init__(self): self.ax = plt.gca() self.rect = Rectangle((0,0), 1, 1, facecolor='None', edgecolor='green') self.x0 = None self.y0 = None self.x1 = None self.y1 = None self.ax.add_patch(self.rect) self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press) self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release) self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) def on_press(self, event): print 'press' self.x0 = event.xdata self.y0 = event.ydata self.x1 = event.xdata self.y1 = event.ydata self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) self.rect.set_linestyle('dashed') self.ax.figure.canvas.draw() def on_motion(self,event): if self.on_press is True: return self.x1 = event.xdata self.y1 = event.ydata self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) self.rect.set_linestyle('dashed') self.ax.figure.canvas.draw() def on_release(self, event): print 'release' self.x1 = event.xdata self.y1 = event.ydata self.rect.set_width(self.x1 - self.x0) self.rect.set_height(self.y1 - self.y0) self.rect.set_xy((self.x0, self.y0)) self.rect.set_linestyle('solid') self.ax.figure.canvas.draw() print self.x0,self.x1,self.y0,self.y1 return [self.x0,self.x1,self.y0,self.y1] </code></pre>
44,281,340
2
0
null
2012-08-21 09:54:59.29 UTC
8
2017-05-31 09:46:51.19 UTC
2012-09-26 11:34:26.643 UTC
null
1,301,710
null
1,613,796
null
1
10
python|matplotlib|mouse|selection|matplotlib-basemap
22,544
<p>Matplotlib provides its own <code>RectangleSelector</code>. There is <a href="https://matplotlib.org/examples/widgets/rectangle_selector.html" rel="noreferrer">an example</a> on the matplotlib page, which you may adapt to your needs. </p> <p>A simplified version would look something like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import RectangleSelector xdata = np.linspace(0,9*np.pi, num=301) ydata = np.sin(xdata) fig, ax = plt.subplots() line, = ax.plot(xdata, ydata) def line_select_callback(eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata rect = plt.Rectangle( (min(x1,x2),min(y1,y2)), np.abs(x1-x2), np.abs(y1-y2) ) ax.add_patch(rect) rs = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=False, button=[1], minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.show() </code></pre>
12,473,030
SignalR: How to send data to IConnected.Connect()
<p>I implement the <code>Connect()</code> method on <code>IConnected</code> interface to add new connections to the correct groups. This works well except for one thing: in order to add the user to the correct group, I need to send a value to be read in this method. I tried adding property to the client hub:</p> <pre><code>var uIHub = $.connection.uIHub; uIHub.SessionType = "Edit"; </code></pre> <p>But it's not accessible from the <code>Connect</code> method: </p> <pre><code>if (string.IsNullOrEmpty(Caller.SessionType) || Caller.SessionType == "Edit") { sessionId = WAFContext.EditSession.SessionId.ToString(); } else { sessionId = WAFContext.ViewSession.SessionId.ToString(); } Groups.Add(Context.ConnectionId, sessionId); </code></pre> <p><code>Caller.SessionType</code> is always null.</p> <p>Any suggestions on how to solve this?</p>
12,473,555
1
0
null
2012-09-18 08:22:27.833 UTC
8
2015-05-07 12:47:23.81 UTC
2015-05-07 12:47:23.81 UTC
null
4,597
null
781,496
null
1
22
signalr
11,304
<p>I solved this by adding my information to the querystring, which is available on the <code>IConnected.Connect()</code> method.</p> <p>On the .NET client you pass the querystring into your <code>HubConnection</code>:</p> <pre><code>var connection = new HubConnection("http://localhost:8080/", "myInfo=12345"); </code></pre> <p>On the JS client, you set the <code>qs</code> property before starting the connection:</p> <pre><code>$.connection.hub.qs = "myInfo=12345"; </code></pre> <p>You can then access this information on the server in the <code>Connect()</code> method:</p> <pre><code>var myInfo = Context.QueryString["myInfo"]; Groups.Add(Context.ConnectionId, myInfo); </code></pre>
12,516,592
Chrome Console: reload page
<p>Is there any way to reload chrome page (like clicking F5) from command line of chrome developer console? </p> <p>I've tired searching but without effect...</p>
12,516,620
2
0
null
2012-09-20 16:08:33.337 UTC
7
2019-10-28 12:30:59.263 UTC
2019-10-28 12:30:59.263 UTC
null
860,099
null
701,951
null
1
34
javascript|google-chrome
28,582
<pre><code>location.reload() </code></pre> <p><sub>That was easy...</sub></p>
18,853,066
404 Not Found The requested URL was not found on this server
<p>I'm having small troubles and was wondering if someone can help me over the hump. I pulled a copy of a website down from Hostgator and I'm trying to set it up on my local machine using <code>WAMP</code> but, I keep getting an error when trying to access the site. Here is what I have tried..I went to Apaches <code>httpd.conf</code> file and uncommented the # from <code>LoadModule</code> rewrite_module modules/mod_rewrite.so. Also I have changed the AllowOverride None to All. With that said, Im not sure what else to look for. Please note within my application my <code>httaccess</code> files do not have a <code>(.)</code> in front of them <code>(.htaccess)</code>. I'm not sure if that is worth noting or not. Any ideas as to what I need to do to access my site? When I access the application I do see a cached version (white screen), but when I click the link to log in I see the <code>404 Not Found</code>. </p>
20,637,011
11
5
null
2013-09-17 14:49:04.433 UTC
14
2022-04-14 15:33:16.387 UTC
2014-12-03 06:36:51.773 UTC
null
2,083,854
null
1,949,828
null
1
28
apache|cakephp|mod-rewrite|cakephp-1.3|wamp
385,197
<p>In httpd.conf file you need to remove #</p> <pre><code>#LoadModule rewrite_module modules/mod_rewrite.so </code></pre> <p>after removing # line will look like this:</p> <pre><code>LoadModule rewrite_module modules/mod_rewrite.so </code></pre> <p>I am sure your issue will be solved...</p>
24,226,378
Rails routes with :name instead of :id url parameters
<p>I have a controller named 'companies' and rather than the urls for each company being denoted with an :id I'd like to have the url use their :name such as: <code>url/company/microsoft</code> instead of <code>url/company/3</code>. </p> <p>In my controller I assumed I would have </p> <pre><code> def show @company = Company.find(params[:name]) end </code></pre> <p>Since there won't be any other parameter in the url I was hoping rails would understand that :name referenced the :name column in my Company model. I assume the magic here would be in the route but am stuck at this point.</p>
24,227,109
7
4
null
2014-06-15 03:49:38.857 UTC
7
2019-11-04 23:04:25.48 UTC
2014-06-15 03:53:31.473 UTC
null
724,036
null
291,724
null
1
36
ruby-on-rails|routes
38,092
<p><strong><code>params</code></strong></p> <p>The bottom line is you're looking at the wrong solution - the <code>params</code> hash keys are rather irrelevant, you need to be able to use the data contained inside them more effectively.</p> <p>Your routes will be constructed as:</p> <pre><code>#config/routes.rb resources :controller #-&gt; domain.com/controller/:id </code></pre> <p>This means if you request this route: <code>domain.com/controller/your_resource</code>, the <code>params[:id]</code> hash value will be <code>your_resource</code> (doesn't matter if it's called <code>params[:name]</code> or <code>params[:id]</code>)</p> <p>--</p> <p><strong><a href="https://github.com/norman/friendly_id"><code>friendly_id</code></a></strong></p> <p>The reason you have several answers recommending <code>friendly_id</code> is because this overrides the <code>find</code> method of <code>ActiveRecord</code>, allowing you to use a <a href="https://en.wikipedia.org/wiki/Clean_URL#Slug"><code>slug</code></a> in your query:</p> <pre><code>#app/models/model.rb Class Model &lt; ActiveRecord::Base extend FriendlyId friendly_id :name, use: [:slugged, :finders] end </code></pre> <p>This allows you to do this:</p> <pre><code>#app/controllers/your_controller.rb def show @model = Model.find params[:id] #-&gt; this can be the "name" of your record, or "id" end </code></pre>
22,616,973
Django rest framework, use different serializers in the same ModelViewSet
<p>I would like to provide two different serializers and yet be able to benefit from all the facilities of <code>ModelViewSet</code>:</p> <ul> <li>When viewing a list of objects, I would like each object to have an url which redirects to its details and every other relation appear using <code>__unicode __</code> of the target model; </li> </ul> <p>example:</p> <pre class="lang-json prettyprint-override"><code>{ "url": "http://127.0.0.1:8000/database/gruppi/2/", "nome": "universitari", "descrizione": "unitn!", "creatore": "emilio", "accesso": "CHI", "membri": [ "emilio", "michele", "luisa", "ivan", "saverio" ] } </code></pre> <ul> <li>When viewing the details of an object, I would like to use the default <code>HyperlinkedModelSerializer</code></li> </ul> <p>example:</p> <pre class="lang-json prettyprint-override"><code>{ "url": "http://127.0.0.1:8000/database/gruppi/2/", "nome": "universitari", "descrizione": "unitn!", "creatore": "http://127.0.0.1:8000/database/utenti/3/", "accesso": "CHI", "membri": [ "http://127.0.0.1:8000/database/utenti/3/", "http://127.0.0.1:8000/database/utenti/4/", "http://127.0.0.1:8000/database/utenti/5/", "http://127.0.0.1:8000/database/utenti/6/", "http://127.0.0.1:8000/database/utenti/7/" ] } </code></pre> <p>I managed to make all this work as I wish in the following way:</p> <p><strong>serializers.py</strong></p> <pre><code># serializer to use when showing a list class ListaGruppi(serializers.HyperlinkedModelSerializer): membri = serializers.RelatedField(many = True) creatore = serializers.RelatedField(many = False) class Meta: model = models.Gruppi # serializer to use when showing the details class DettaglioGruppi(serializers.HyperlinkedModelSerializer): class Meta: model = models.Gruppi </code></pre> <p><strong>views.py</strong></p> <pre><code>class DualSerializerViewSet(viewsets.ModelViewSet): """ ViewSet providing different serializers for list and detail views. Use list_serializer and detail_serializer to provide them """ def list(self, *args, **kwargs): self.serializer_class = self.list_serializer return viewsets.ModelViewSet.list(self, *args, **kwargs) def retrieve(self, *args, **kwargs): self.serializer_class = self.detail_serializer return viewsets.ModelViewSet.retrieve(self, *args, **kwargs) class GruppiViewSet(DualSerializerViewSet): model = models.Gruppi list_serializer = serializers.ListaGruppi detail_serializer = serializers.DettaglioGruppi # etc. </code></pre> <p>Basically I detect when the user is requesting a list view or a detailed view and change <code>serializer_class</code> to suit my needs. I am not really satisfied with this code though, it looks like a dirty hack and, most importantly, <em>what if two users request a list and a detail at the same moment?</em> </p> <p>Is there a better way to achieve this using <code>ModelViewSets</code> or do I have to fall back using <code>GenericAPIView</code>?</p> <p><strong>EDIT:</strong><br> Here's how to do it using a custom base <code>ModelViewSet</code>:</p> <pre><code>class MultiSerializerViewSet(viewsets.ModelViewSet): serializers = { 'default': None, } def get_serializer_class(self): return self.serializers.get(self.action, self.serializers['default']) class GruppiViewSet(MultiSerializerViewSet): model = models.Gruppi serializers = { 'list': serializers.ListaGruppi, 'detail': serializers.DettaglioGruppi, # etc. } </code></pre>
22,755,648
9
5
null
2014-03-24 17:54:35.477 UTC
87
2022-01-29 19:53:50.647 UTC
2018-04-21 10:41:08.84 UTC
null
1,977,847
null
521,776
null
1
282
django|serialization|django-rest-framework
138,422
<p>Override your <code>get_serializer_class</code> method. This method is used in your model mixins to retrieve the proper Serializer class. </p> <p>Note that there is also a <code>get_serializer</code> method which returns an <em>instance</em> of the correct Serializer</p> <pre><code>class DualSerializerViewSet(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == 'list': return serializers.ListaGruppi if self.action == 'retrieve': return serializers.DettaglioGruppi return serializers.Default # I dont' know what you want for create/destroy/update. </code></pre>
8,928,403
Try-catch speeding up my code?
<p>I wrote some code for testing the impact of try-catch, but seeing some surprising results.</p> <pre><code>static void Main(string[] args) { Thread.CurrentThread.Priority = ThreadPriority.Highest; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime; long start = 0, stop = 0, elapsed = 0; double avg = 0.0; long temp = Fibo(1); for (int i = 1; i &lt; 100000000; i++) { start = Stopwatch.GetTimestamp(); temp = Fibo(100); stop = Stopwatch.GetTimestamp(); elapsed = stop - start; avg = avg + ((double)elapsed - avg) / i; } Console.WriteLine("Elapsed: " + avg); Console.ReadKey(); } static long Fibo(int n) { long n1 = 0, n2 = 1, fibo = 0; n++; for (int i = 1; i &lt; n; i++) { n1 = n2; n2 = fibo; fibo = n1 + n2; } return fibo; } </code></pre> <p>On my computer, this consistently prints out a value around 0.96..</p> <p>When I wrap the for loop inside Fibo() with a try-catch block like this:</p> <pre><code>static long Fibo(int n) { long n1 = 0, n2 = 1, fibo = 0; n++; try { for (int i = 1; i &lt; n; i++) { n1 = n2; n2 = fibo; fibo = n1 + n2; } } catch {} return fibo; } </code></pre> <p>Now it consistently prints out 0.69... -- it actually runs faster! But why?</p> <p>Note: I compiled this using the Release configuration and directly ran the EXE file (outside Visual Studio).</p> <p>EDIT: <a href="https://stackoverflow.com/a/8928476/282110">Jon Skeet's <em>excellent</em> analysis</a> shows that try-catch is somehow causing the x86 CLR to use the CPU registers in a more favorable way in this specific case (and I think we're yet to understand why). I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. I also tested using <code>int</code> types inside the Fibo method instead of <code>long</code> types, and then the x86 CLR was as equally fast as the x64 CLR.</p> <hr> <p><strong>UPDATE:</strong> It looks like this issue has been fixed by Roslyn. Same machine, same CLR version -- the issue remains as above when compiled with VS 2013, but the problem goes away when compiled with VS 2015. </p>
8,947,323
6
18
null
2012-01-19 15:10:57.04 UTC
325
2020-11-27 14:27:10.213 UTC
2017-05-23 12:34:50.693 UTC
null
-1
null
201,088
null
1
1,607
c#|.net|clr|try-catch|performance-testing
116,629
<p>One of the <a href="http://en.wikipedia.org/wiki/Microsoft_Roslyn" rel="noreferrer">Roslyn</a> engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation" rel="noreferrer">JIT</a> compiler does register scheduling in the corresponding x86 code. The result is suboptimal code generation on the loads and stores of the locals.</p> <p>For some reason unclear to all of us, the problematic code generation path is avoided when the JITter knows that the block is in a try-protected region. </p> <p>This is pretty weird. We'll follow up with the JITter team and see whether we can get a bug entered so that they can fix this. </p> <p>Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the JITter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.</p> <p>Thanks for bringing this to our attention, and apologies for the odd behaviour. </p>
26,198,526
NSDate Comparison using Swift
<p>I am working on an app the requires checking the due date for homework. I want to know if a due date is within the next week, and if it is then perform an action.<br> Most of the documentation I could find is in Objective-C and I can't figure out how to do it in Swift. Thanks for the help!!</p>
29,319,732
16
4
null
2014-10-05 00:40:39.823 UTC
47
2020-12-02 20:14:36.463 UTC
2015-07-28 00:28:41.897 UTC
null
2,333,544
null
4,056,706
null
1
153
swift|nsdate|xcode6
91,842
<p>I like using extensions to make code more readable. Here are a few NSDate extensions that can help clean your code up and make it easy to understand. I put this in a sharedCode.swift file:</p> <pre><code>extension NSDate { func isGreaterThanDate(dateToCompare: NSDate) -&gt; Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(dateToCompare: NSDate) -&gt; Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending { isLess = true } //Return Result return isLess } func equalToDate(dateToCompare: NSDate) -&gt; Bool { //Declare Variables var isEqualTo = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame { isEqualTo = true } //Return Result return isEqualTo } func addDays(daysToAdd: Int) -&gt; NSDate { let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24 let dateWithDaysAdded: NSDate = self.addingTimeInterval(secondsInDays) //Return Result return dateWithDaysAdded } func addHours(hoursToAdd: Int) -&gt; NSDate { let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60 let dateWithHoursAdded: NSDate = self.addingTimeInterval(secondsInHours) //Return Result return dateWithHoursAdded } } </code></pre> <p>Now if you can do something like this:</p> <pre><code>//Get Current Date/Time var currentDateTime = NSDate() //Get Reminder Date (which is Due date minus 7 days lets say) var reminderDate = dueDate.addDays(-7) //Check if reminderDate is Greater than Right now if(reminderDate.isGreaterThanDate(currentDateTime)) { //Do Something... } </code></pre>
22,283,241
How to view html output in Notepad++?
<p>How do I view my Code output in Notepad++ as a webpage or something similiar?</p> <p>I have built something but I can't find a button or something like that in Notepad to view it as a webpage or something similiar.</p>
22,283,275
5
6
null
2014-03-09 14:12:30.673 UTC
null
2020-04-30 21:45:40.28 UTC
2014-04-09 06:01:23.987 UTC
null
1,053,021
null
3,398,006
null
1
-3
editor|notepad++
46,921
<p>If it is a webpage written in html: just go where you saved it and click it.</p> <p>If it is in php: </p> <p>You will need a web server, save the file in the www directory. and access it like this:</p> <pre><code>http://localhost/yourfile.php </code></pre>
10,979,909
PHP string with decimals to number
<p>So when I try the following:</p> <pre><code>$a = '1.00'; $b = '1.01'; if($a &lt; $b){ print 'ok'; } </code></pre> <p>This works fine. But when I retrieve these variables from an xml file. the strings are EXACTLY the same, but for some reason, the if function doesn't work right. So I assume I have to convert the strings to a number. But when I do so, the decimals get removed.</p> <p>Is my assumption correct? If so, how do i solve it?</p> <p>If not, what's the problem?</p> <p>Thank you!</p>
10,979,999
2
1
null
2012-06-11 12:14:16.923 UTC
1
2012-06-11 12:20:49.167 UTC
null
null
null
null
1,048,566
null
1
6
php|variables|integer
40,480
<pre><code>$a = (float) $a; $b = (float) $b; </code></pre> <p>Related reading: <a href="http://php.net/manual/en/language.types.type-juggling.php">http://php.net/manual/en/language.types.type-juggling.php</a></p>
11,157,888
iOS Paper fold (origami / accordion) effect animation, with manual control
<p>I'm looking for tips on how to implement the popular 'paper folding / origami' effect in my iOS project. </p> <p>I'm aware of projects such as: <a href="https://github.com/xyfeng/XYOrigami" rel="noreferrer">https://github.com/xyfeng/XYOrigami</a> but they only offer the 'animated' effect, with no manual control over the opening animation. </p> <p>I've struggled to dissect that project and come up with what I'm after.</p> <p>To be more exact, I'm looking on how to implement the effect shown here: <a href="http://vimeo.com/41495357" rel="noreferrer">http://vimeo.com/41495357</a> where the folding animation is not simply animated open, but the user controls the opening folds.</p> <p>Any help would be much appreciated, thanks in advance! </p> <p>EDIT:</p> <p>Okay, here's some example code to better illustrate what I'm struggling with:</p> <p>This method triggers the origami effect animation:</p> <pre><code>- (void)showOrigamiTransitionWith:(UIView *)view NumberOfFolds:(NSInteger)folds Duration:(CGFloat)duration Direction:(XYOrigamiDirection)direction completion:(void (^)(BOOL finished))completion { if (XY_Origami_Current_State != XYOrigamiTransitionStateIdle) { return; } XY_Origami_Current_State = XYOrigamiTransitionStateUpdate; //add view as parent subview if (![view superview]) { [[self superview] insertSubview:view belowSubview:self]; } //set frame CGRect selfFrame = self.frame; CGPoint anchorPoint; if (direction == XYOrigamiDirectionFromRight) { selfFrame.origin.x = self.frame.origin.x - view.bounds.size.width; view.frame = CGRectMake(self.frame.origin.x+self.frame.size.width-view.frame.size.width, self.frame.origin.y, view.frame.size.width, view.frame.size.height); anchorPoint = CGPointMake(1, 0.5); } else { selfFrame.origin.x = self.frame.origin.x + view.bounds.size.width; view.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, view.frame.size.width, view.frame.size.height); anchorPoint = CGPointMake(0, 0.5); } UIGraphicsBeginImageContext(view.frame.size); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewSnapShot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //set 3D depth CATransform3D transform = CATransform3DIdentity; transform.m34 = -1.0/800.0; CALayer *origamiLayer = [CALayer layer]; origamiLayer.frame = view.bounds; origamiLayer.backgroundColor = [UIColor colorWithWhite:0.2 alpha:1].CGColor; origamiLayer.sublayerTransform = transform; [view.layer addSublayer:origamiLayer]; //setup rotation angle double startAngle; CGFloat frameWidth = view.bounds.size.width; CGFloat frameHeight = view.bounds.size.height; CGFloat foldWidth = frameWidth/(folds*2); CALayer *prevLayer = origamiLayer; for (int b=0; b &lt; folds*2; b++) { CGRect imageFrame; if (direction == XYOrigamiDirectionFromRight) { if(b == 0) startAngle = -M_PI_2; else { if (b%2) startAngle = M_PI; else startAngle = -M_PI; } imageFrame = CGRectMake(frameWidth-(b+1)*foldWidth, 0, foldWidth, frameHeight); } else { if(b == 0) startAngle = M_PI_2; else { if (b%2) startAngle = -M_PI; else startAngle = M_PI; } imageFrame = CGRectMake(b*foldWidth, 0, foldWidth, frameHeight); } CATransformLayer *transLayer = [self transformLayerFromImage:viewSnapShot Frame:imageFrame Duration:duration AnchorPiont:anchorPoint StartAngle:startAngle EndAngle:0]; [prevLayer addSublayer:transLayer]; prevLayer = transLayer; } [CATransaction begin]; [CATransaction setCompletionBlock:^{ self.frame = selfFrame; [origamiLayer removeFromSuperlayer]; XY_Origami_Current_State = XYOrigamiTransitionStateShow; if (completion) completion(YES); }]; [CATransaction setValue:[NSNumber numberWithFloat:duration] forKey:kCATransactionAnimationDuration]; CAAnimation *openAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position.x" function:openFunction fromValue:self.frame.origin.x+self.frame.size.width/2 toValue:selfFrame.origin.x+self.frame.size.width/2]; openAnimation.fillMode = kCAFillModeForwards; [openAnimation setRemovedOnCompletion:NO]; [self.layer addAnimation:openAnimation forKey:@"position"]; [CATransaction commit]; } </code></pre> <p>The method grabs a CATransform Layer from this method:</p> <pre><code>- (CATransformLayer *)transformLayerFromImage:(UIImage *)image Frame:(CGRect)frame Duration:(CGFloat)duration AnchorPiont:(CGPoint)anchorPoint StartAngle:(double)start EndAngle:(double)end; { CATransformLayer *jointLayer = [CATransformLayer layer]; jointLayer.anchorPoint = anchorPoint; CGFloat layerWidth; if (anchorPoint.x == 0) //from left to right { layerWidth = image.size.width - frame.origin.x; jointLayer.frame = CGRectMake(0, 0, layerWidth, frame.size.height); if (frame.origin.x) { jointLayer.position = CGPointMake(frame.size.width, frame.size.height/2); } else { jointLayer.position = CGPointMake(0, frame.size.height/2); } } else { //from right to left layerWidth = frame.origin.x + frame.size.width; jointLayer.frame = CGRectMake(0, 0, layerWidth, frame.size.height); jointLayer.position = CGPointMake(layerWidth, frame.size.height/2); } //map image onto transform layer CALayer *imageLayer = [CALayer layer]; imageLayer.frame = CGRectMake(0, 0, frame.size.width, frame.size.height); imageLayer.anchorPoint = anchorPoint; imageLayer.position = CGPointMake(layerWidth*anchorPoint.x, frame.size.height/2); [jointLayer addSublayer:imageLayer]; CGImageRef imageCrop = CGImageCreateWithImageInRect(image.CGImage, frame); imageLayer.contents = (__bridge id)imageCrop; imageLayer.backgroundColor = [UIColor clearColor].CGColor; //add shadow NSInteger index = frame.origin.x/frame.size.width; double shadowAniOpacity; CAGradientLayer *shadowLayer = [CAGradientLayer layer]; shadowLayer.frame = imageLayer.bounds; shadowLayer.backgroundColor = [UIColor darkGrayColor].CGColor; shadowLayer.opacity = 0.0; shadowLayer.colors = [NSArray arrayWithObjects:(id)[UIColor blackColor].CGColor, (id)[UIColor clearColor].CGColor, nil]; if (index%2) { shadowLayer.startPoint = CGPointMake(0, 0.5); shadowLayer.endPoint = CGPointMake(1, 0.5); shadowAniOpacity = (anchorPoint.x)?0.24:0.32; } else { shadowLayer.startPoint = CGPointMake(1, 0.5); shadowLayer.endPoint = CGPointMake(0, 0.5); shadowAniOpacity = (anchorPoint.x)?0.32:0.24; } [imageLayer addSublayer:shadowLayer]; //animate open/close animation CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"]; [animation setDuration:duration]; [animation setFromValue:[NSNumber numberWithDouble:start]]; [animation setToValue:[NSNumber numberWithDouble:end]]; [animation setRemovedOnCompletion:NO]; [jointLayer addAnimation:animation forKey:@"jointAnimation"]; //animate shadow opacity animation = [CABasicAnimation animationWithKeyPath:@"opacity"]; [animation setDuration:duration]; [animation setFromValue:[NSNumber numberWithDouble:(start)?shadowAniOpacity:0]]; [animation setToValue:[NSNumber numberWithDouble:(start)?0:shadowAniOpacity]]; [animation setRemovedOnCompletion:NO]; [shadowLayer addAnimation:animation forKey:nil]; return jointLayer; } </code></pre> <p>Basically, I need to remove the automatic animation, and control the progress of the effect using some manually set value (e.g.: uislider value, or content offset).</p> <p>Once again, any help provided is much appreciated!</p>
11,230,666
3
0
null
2012-06-22 14:10:55.883 UTC
11
2015-03-20 07:57:19.31 UTC
2012-06-25 22:07:45.183 UTC
null
1,165,911
null
1,165,911
null
1
8
iphone|ios|animation|accordion|fold
22,353
<p>I write another library for folding transition : <a href="https://github.com/geraldhuard/YFoldView">https://github.com/geraldhuard/YFoldView</a></p> <p>Hope it works for you. </p>
11,392,089
Horizontal Line in Background using Css3
<p>How to implement this type of style to text using only css3, means a horizontal line in the middle of the tag... Can it be possible using pure css...</p> <p><img src="https://i.stack.imgur.com/vqFfT.jpg" alt="enter image description here"></p> <p>Here's my structure:-</p> <pre><code>&lt;p class="datedAside"&gt;4 weeks ago&lt;/p&gt; </code></pre>
11,392,170
9
1
null
2012-07-09 09:13:34.25 UTC
4
2022-05-16 16:08:59.557 UTC
2012-07-09 09:26:33.927 UTC
null
1,425,785
null
1,425,785
null
1
19
css|background|border
49,609
<p>Here's one way to do it by adding a span inside the p.</p> <p>HTML:</p> <pre><code>&lt;p class="datedAside"&gt; &lt;span&gt; 4 weeks ago &lt;/span&gt; &lt;/p&gt;​ </code></pre> <p>CSS:</p> <pre><code>p {background: #000; height:1px; margin-top:10px;} p span{background: #fff; padding:10px; position:relative; top:-10px; left: 20px}​ </code></pre> <p><strong>DEMO:</strong> <a href="http://jsfiddle.net/9GMJz/" rel="noreferrer">http://jsfiddle.net/9GMJz/</a></p>
11,165,458
Using Github for Windows to work with own private Git through SSH
<p>Right now, I'm using msysgit to work with my own private repositories stored on a ec2 Amazon Cloud Server using SSH.</p> <p>Until now, I've been able to successfully connect to those repositories through Git Bash (creating the ssh-rsa public and private key with ssh-keygen, adding the public key to the authorized_servers on the remote machine), so I can clone, push, pull, get through the CLI.</p> <p>Now, I've seen Github for Windows, and I gotta say, it is a beautiful piece of software. Since it is based on msysgit, I was wondering that if it is possible to setup Github for Windows to connect, clone and push commits through the UI?</p> <p>In the description it looks like possible, but the documentation seems to lacks information about what the software is capable to do.</p> <p>Hope you can help me out here, cheers from Mexico.</p>
11,165,559
4
0
null
2012-06-22 23:35:28.5 UTC
13
2017-03-28 16:37:55.05 UTC
2015-09-07 01:08:29.33 UTC
null
219,229
null
768,087
null
1
20
windows|git|github|ssh|github-for-windows
21,913
<p>Here is a nice write up of what you are exactly looking for.</p> <p>Edit: I just tested with the following steps and it works like charm!!</p> <pre><code> 1. Click on repositories on the left. 2. Pull your copy of the repo from the remote , using git-shell 3. Drag and drop the Folder on to Git hub for windows dashboard. 4. now double click on the repository dropped on to githubW. It should be listed as a local repository. 5. it says login required to your non-github remote! </code></pre> <p><img src="https://i.stack.imgur.com/7fwhP.jpg" alt="enter image description here"></p> <p><a href="http://haacked.com/archive/2012/05/30/using-github-for-windows-with-non-github-repositories.aspx" rel="noreferrer">Credits</a></p> <p>For some wierd reason, GutHub didn't make it straightforward to use non-GitHub Remotes. (As you said, <a href="http://windows.github.com/help.html" rel="noreferrer">they say that they support non-github remotes</a> though!!)</p>
11,419,998
Text-decoration: none not working
<p>Totally baffled! I've tried rewriting the <code>text-decoration: none</code> line several different ways. I also managed to re-size the text by targeting it but the <code>text-decoration: none</code> code will not take.</p> <p>Help much appreciated.</p> <p>Code</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.widget { height: 320px; width: 220px; background-color: #e6e6e6; position: relative; overflow: hidden; } .title { font-family: Georgia, Times New Roman, serif; font-size: 12px; color: #E6E6E6; text-align: center; letter-spacing: 1px; text-transform: uppercase; background-color: #4D4D4D; position: absolute; top: 0; padding: 5px; width: 100%; margin-bottom: 1px; height: 28px; text-decoration: none; } a .title { text-decoration: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="#"&gt; &lt;div class="widget"&gt; &lt;div class="title"&gt;Underlined. Why?&lt;/div&gt; &lt;/div&gt; &lt;/a&gt;</code></pre> </div> </div> </p>
11,420,078
12
8
null
2012-07-10 18:55:50.58 UTC
8
2022-09-19 19:12:57.017 UTC
2016-03-09 00:54:44.947 UTC
null
5,445,670
null
1,159,248
null
1
50
css|html|text-decorations
164,283
<p>You have a block element (div) inside an inline element (a). This works in HTML 5, but not HTML 4. Thus also only browsers that actually support HTML 5.</p> <p>When browsers encounter invalid markup, they will try to fix it, but different browsers will do that in different ways, so the result varies. Some browsers will move the block element outside the inline element, some will ignore it.</p>
11,339,445
com.google.android.gsf package couldn't be found
<p>I am trying to use new Google Cloud Messaging system but I have some problems.</p> <p>I read Getting Started document and reviewed demo app; after that I applied requirements to my application then I created a new virtual device with API 16.</p> <p>But when I try to register my device to GCM, it fails because of this line:</p> <pre><code>GCMRegistrar.checkDevice(getApplicationContext()); </code></pre> <p>In logcat I see these errors:</p> <pre><code>07-05 07:06:31.925: E/AndroidRuntime(691): FATAL EXCEPTION: main 07-05 07:06:31.925: E/AndroidRuntime(691): java.lang.UnsupportedOperationException: Device does not have package com.google.android.gsf 07-05 07:06:31.925: E/AndroidRuntime(691): at com.google.android.gcm.GCMRegistrar.checkDevice(GCMRegistrar.java:83) 07-05 07:06:31.925: E/AndroidRuntime(691): at aero.tav.mobile.genel$4.onClick(genel.java:201) 07-05 07:06:31.925: E/AndroidRuntime(691): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166) 07-05 07:06:31.925: E/AndroidRuntime(691): at android.os.Handler.dispatchMessage(Handler.java:99) 07-05 07:06:31.925: E/AndroidRuntime(691): at android.os.Looper.loop(Looper.java:137) 07-05 07:06:31.925: E/AndroidRuntime(691): at android.app.ActivityThread.main(ActivityThread.java:4745) 07-05 07:06:31.925: E/AndroidRuntime(691): at java.lang.reflect.Method.invokeNative(Native Method) 07-05 07:06:31.925: E/AndroidRuntime(691): at java.lang.reflect.Method.invoke(Method.java:511) 07-05 07:06:31.925: E/AndroidRuntime(691): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 07-05 07:06:31.925: E/AndroidRuntime(691): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 07-05 07:06:31.925: E/AndroidRuntime(691): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>I had added gcm.jar to my class path; I don't know what is wrong.</p>
11,339,755
2
8
null
2012-07-05 07:14:06.247 UTC
13
2015-08-10 02:47:01.13 UTC
2012-07-05 07:19:16.82 UTC
null
423,699
null
423,699
null
1
72
android|google-cloud-messaging
49,984
<p>it seems to me like you're using the wrong emulator.</p> <p>The default emulator uses a regular Android emulator that doesn't have any Google packages and can't run all sorts of things like maps, c2dm and all sorts of stuff like that.</p> <p>what you want to do, is create a new emulator that can support the Google APIs.</p> <p>then, when you run the project, choose the emulator that runs the target name <code>Google APIs (Google Inc).</code></p> <p>good luck.</p>
11,095,179
Using HTML5 pushstate on angular.js
<p>I am trying to implement html5's pushstate instead of the # navigation used by Angularjs. I have tried searching google for an answer and also tried the angular irc chat room with no luck yet.</p> <p>This is my <code>controllers.js</code>:</p> <pre><code>function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); } function PhoneDetailCtrl($scope, $routeParams) { $scope.phoneId = $routeParams.phoneId; } function greetCntr($scope, $window) { $scope.greet = function() { $("#modal").slideDown(); } } </code></pre> <p>app.js</p> <pre><code>angular.module('phoneapp', []). config(['$routeProvider', function($routeProvider){ $routeProvider. when('/phones', { templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl }). when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl }). otherwise({ redirectTo: '/phones' }); }]) </code></pre>
11,100,438
1
0
null
2012-06-19 05:56:45.98 UTC
40
2015-12-24 03:49:47.443 UTC
2015-12-24 03:49:47.443 UTC
null
2,573,335
null
621,331
null
1
84
javascript|angularjs
42,905
<p>Inject $locationProvider into your config, and set <code>$locationProvider.html5Mode(true)</code>.</p> <p><a href="http://docs.angularjs.org/api/ng.$locationProvider" rel="noreferrer">http://docs.angularjs.org/api/ng.$locationProvider</a></p> <p>Simple example:</p> <p>JS:</p> <pre><code>myApp.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/page1', { template: 'page1.html', controller: 'Page1Ctrl' }) .when('/page2', { template: 'page2.html', controller: 'Page2Ctrl' }) }); </code></pre> <p>HTML:</p> <pre><code>&lt;a href="/page1"&gt;Page 1&lt;/a&gt; | &lt;a href="/page2"&gt;Page 2&lt;/a&gt; </code></pre>
10,962,418
How to startForeground() without showing notification?
<p>I want to create a service and make it run in the foreground. </p> <p>Most example codes have notifications on it. But I don't want to show any notification. Is that possible? </p> <p>Can you give me some examples? Are there any alternatives? </p> <p>My app service is doing mediaplayer. <strong>How to make system not kill my service except the app kill it itself</strong> (like pausing or stopping the music by button).</p>
10,964,250
16
4
null
2012-06-09 15:54:52.353 UTC
47
2022-01-14 21:26:32.653 UTC
2016-05-21 18:28:59.353 UTC
null
4,717,992
null
743,891
null
1
106
android|android-service|foreground
119,807
<p>As a security feature of the Android platform, you <em>cannot</em>, under <em>any</em> circumstance, have a foregrounded service without also having a notification. This is because a foregrounded service consumes a heavier amount of resources and is subject to different scheduling constraints (i.e., it doesn't get killed as quickly) than background services, and the user needs to know what's possibly eating their battery. So, <em>don't</em> do this.</p> <p>However, it <em>is</em> possible to have a "fake" notification, i.e., you can make a transparent notification icon (iirc). This is extremely disingenuous to your users, and you have no reason to do it, other than killing their battery and thus creating malware.</p>
48,396,092
Should I include LifecycleOwner in ViewModel?
<p>LifecycleOwner is currently needed in order for me to create an observer.</p> <p>I have code which creates an Observer in the ViewModel so I attach the LifecycleOwner when retrieving the ViewModel in my Fragment.</p> <p>According to Google's documentation.</p> <p>Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.</p> <p>Did I break that warning and If I did, what way do you recommend me to move my creation of an observer for data return?</p> <p>I only made an observer so I'm wondering if it's still valid. Since also in Google's documentation it also said.</p> <p>ViewModel objects can contain LifecycleObservers, such as LiveData objects.</p> <p><strong>MainFragment</strong></p> <pre><code>private lateinit var model: MainViewModel /** * Observer for our ViewModel IpAddress LiveData value. * @see Observer.onChanged * */ private val ipObserver = Observer&lt;String&gt; { textIp.text = it hideProgressBar() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) model = ViewModelProviders.of(this).get(MainViewModel::class.java) model.attach(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater?.inflate(R.layout.fragment_main, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) buttonRetrieveIp.setOnClickListener { showProgressBar() model.fetchMyIp().observe(this, ipObserver) //Here we attach our ipObserver } } override fun showProgressBar() { textIp.visibility = View.GONE progressBar.visibility = View.VISIBLE } override fun hideProgressBar() { progressBar.visibility = View.GONE textIp.visibility = View.VISIBLE } </code></pre> <p><strong>MainViewModel</strong></p> <pre><code>private var ipAddress = MutableLiveData&lt;String&gt;() private lateinit var owner: LifecycleOwner fun attach(fragment: MainFragment) { owner = fragment } /** * For more information regarding Fuel Request using Fuel Routing and Live Data Response. * @see &lt;a href="https://github.com/kittinunf/Fuel#routing-support"&gt;Fuel Routing Support&lt;/a&gt; * @see &lt;a href="https://github.com/kittinunf/Fuel#livedata-support"&gt;Fuel LiveData Support&lt;/a&gt; * */ fun fetchMyIp(): LiveData&lt;String&gt; { Fuel.request(IpAddressApi.MyIp()) .liveDataResponse() .observe(owner, Observer { if (it?.first?.statusCode == 200) {//If you want you can add a status code checker here. it.second.success { ipAddress.value = Ip.toIp(String(it))?.ip } } }) return ipAddress } </code></pre> <p><strong>Update 1: Improved ViewModel thanks to @pskink suggestion for using Transformations.</strong></p> <pre><code>private lateinit var ipAddress:LiveData&lt;String&gt; /** * Improved ViewModel since January 23, 2018 credits to &lt;a href="https://stackoverflow.com/users/2252830/pskink"&gt;pskink&lt;/a&gt; &lt;a href=" * * For more information regarding Fuel Request using Fuel Routing and Live Data Response. * @see &lt;a href="https://github.com/kittinunf/Fuel#routing-support"&gt;Fuel Routing Support&lt;/a&gt; * @see &lt;a href="https://github.com/kittinunf/Fuel#livedata-support"&gt;Fuel LiveData Support&lt;/a&gt; * */ fun fetchMyIp(): LiveData&lt;String&gt; { ipAddress = Transformations.map(Fuel.request(IpAddressApi.MyIp()).liveDataResponse(), { var ip:String? = "" it.second.success { ip = Ip.toIp(String(it))?.ip } ip }) return ipAddress } </code></pre>
57,090,590
3
6
null
2018-01-23 07:15:27.313 UTC
5
2021-12-09 15:09:00.097 UTC
2018-01-23 09:45:27.147 UTC
null
2,598,247
null
2,598,247
null
1
46
android|mvvm|android-viewmodel
24,789
<p>No. If you wish to observe changes of some <code>LiveData</code> inside your <code>ViewModel</code> you can use <code>observeForever()</code> which doesn't require <code>LifecycleOwner</code>.</p> <p>Remember to remove this observer on <code>ViewModel</code>'s <code>onCleared()</code> event:</p> <pre><code>val observer = new Observer() { override public void onChanged(Integer integer) { //Do something with &quot;integer&quot; } } </code></pre> <p>...</p> <pre><code>liveData.observeForever(observer); </code></pre> <p>...</p> <pre><code>override fun onCleared() { liveData.removeObserver(observer) super.onCleared() } </code></pre> <p>Very good reference with examples of <a href="http://jensklin.triangulum.uberspace.de/learn-how-to-use-livedata/#Observe_changes" rel="noreferrer">observe LiveData</a>.</p>
12,715,198
Python : AttributeError: 'NoneType' object has no attribute 'append'
<p>My program looks like </p> <pre><code># global item_to_bucket_list_map = {} def fill_item_bucket_map(items, buckets): global item_to_bucket_list_map for i in range(1, items + 1): j = 1 while i * j &lt;= buckets: if j == 1: item_to_bucket_list_map[i] = [j] else: item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j) j += 1 print "Item=%s, bucket=%s" % (i, item_to_bucket_list_map.get(i)) if __name__ == "__main__": buckets = 100 items = 100 fill_item_bucket_map(items, buckets) </code></pre> <p>When I run this, it throws me</p> <p><code>AttributeError: 'NoneType' object has no attribute 'append'</code></p> <p>Not sure why this would happen? When I am already creating a list at start of each <code>j</code></p>
12,715,226
2
0
null
2012-10-03 19:09:57.07 UTC
5
2022-01-24 20:08:31.55 UTC
2017-09-18 05:40:25.313 UTC
null
846,892
null
379,235
null
1
11
python|list
64,061
<p>Actually you stored <code>None</code> here: <code>append()</code> changes the list in place and returns <code>None</code></p> <pre><code> item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j) </code></pre> <p>example:</p> <pre><code>In [42]: lis = [1,2,3] In [43]: print lis.append(4) None In [44]: lis Out[44]: [1, 2, 3, 4] </code></pre>
13,003,044
href="#" Going to Top of Page - Prevent?
<p>I have a page with some jQuery functions. The HTML on the page looks like so: </p> <pre><code>&lt;a href="#" class="service"&gt;Open&lt;/a&gt; </code></pre> <p>When I click the Open button a hidden panel slides out. The jQuery itself works great however when I click the button it also takes me to the top of the page. </p> <p>Is this the defualt behavior and how do I prevent every <code>href="#"</code> from taking me to the top of the page. </p> <p>Note: I could add id's and tell the href to direct to that ID. I do not want to do that for various reasons (including adding unnecessary code).</p>
13,003,063
4
0
null
2012-10-21 23:00:18.53 UTC
10
2018-01-10 09:55:46.433 UTC
null
null
null
null
825,757
null
1
62
anchor|href|hashtag
63,783
<p>In your event handler, add <code>e.preventDefault();</code> (assuming <code>e</code> is the name of the variable holding the event):</p> <pre class="lang-js prettyprint-override"><code>$('.service').click(function(e) { e.preventDefault(); }); </code></pre>
12,705,309
Scala case class inheritance
<p>I have an application based on Squeryl. I define my models as case classes, mostly since I find convenient to have copy methods.</p> <p>I have two models that are strictly related. The fields are the same, many operations are in common, and they are to be stored in the same DB table. <strong>But</strong> there is some behaviour that only makes sense in one of the two cases, or that makes sense in both cases but is different.</p> <p>Until now I only have used a single case class, with a flag that distinguishes the type of the model, and all methods that differ based on the type of the model start with an if. This is annoying and not quite type safe.</p> <p>What I would like to do is factor the common behaviour and fields in an ancestor case class and have the two actual models inherit from it. But, as far as I understand, inheriting from case classes is frowned upon in Scala, and is even prohibited if the subclass is itself a case class (not my case).</p> <p><strong>What are the problems and pitfalls I should be aware in inheriting from a case class? Does it make sense in my case to do so?</strong></p>
12,706,475
4
3
null
2012-10-03 09:13:18.077 UTC
31
2022-03-28 11:16:26.373 UTC
2022-03-28 11:16:26.373 UTC
null
194,894
null
249,001
null
1
98
scala|inheritance|case-class
112,654
<p>My preferred way of avoiding case class inheritance without code duplication is somewhat obvious: create a common (abstract) base class:</p> <pre><code>abstract class Person { def name: String def age: Int // address and other properties // methods (ideally only accessors since it is a case class) } case class Employer(val name: String, val age: Int, val taxno: Int) extends Person case class Employee(val name: String, val age: Int, val salary: Int) extends Person </code></pre> <p><br/> If you want to be more fine-grained, group the properties into individual traits:</p> <pre><code>trait Identifiable { def name: String } trait Locatable { def address: String } // trait Ages { def age: Int } case class Employer(val name: String, val address: String, val taxno: Int) extends Identifiable with Locatable case class Employee(val name: String, val address: String, val salary: Int) extends Identifiable with Locatable </code></pre>
13,181,740
C# Thread safe fast(est) counter
<p>What is the way to obtain a thread safe counter in C# with best possible performance?</p> <p>This is as simple as it gets:</p> <pre><code>public static long GetNextValue() { long result; lock (LOCK) { result = COUNTER++; } return result; } </code></pre> <p>But are there faster alternatives?</p>
13,181,780
5
0
null
2012-11-01 16:47:39.977 UTC
23
2021-03-13 15:26:02.817 UTC
null
null
null
null
972,783
null
1
194
c#|multithreading|thread-safety|counter
112,906
<p>This would be simpler:</p> <pre><code>return Interlocked.Increment(ref COUNTER); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx">MSDN Interlocked.Increment</a></p>
30,679,025
Graph Visualisation (like yFiles) in JavaFX
<p>Something like Graphviz but more specifically, yFiles.</p> <p>I want a node/edge type of graph visualization.</p> <p>I was thinking about making the node a <code>Circle</code> and the edge a <code>Line</code>. The problem is what to use for the area where the nodes/edges appear. Should I use a <code>ScrollPane</code>, a regular <code>Pane</code>, a <code>Canvas</code>, etc...</p> <p>I will add scrolling functionality, zooming, selecting nodes &amp; dragging nodes.</p> <p>Thanks for the help.</p>
30,696,075
4
5
null
2015-06-06 04:47:42.68 UTC
29
2019-08-11 07:58:37.763 UTC
null
null
null
null
3,893,772
null
1
49
java|javafx|graphviz
28,302
<p>I had 2 hours to kill, so I thought I'd give it a shot. Turns out that it's easy to come up with a prototype.</p> <p>Here's what you need:</p> <ul> <li>a main class to use the graph library you create</li> <li>a graph with a data model</li> <li>easy adding and removing of nodes and edges (turns out that it's better to name the nodes cells in order to avoid confusion with JavaFX nodes during programming)</li> <li>a <a href="https://pixelduke.wordpress.com/2012/09/16/zooming-inside-a-scrollpane/">zoomable scrollpane</a></li> <li>a layout algorithm for the graph</li> </ul> <p>It's really too much to be asked on SO, so I'll just add the code with a few comments.</p> <p>The application instantiates the graph, adds cells and connects them via edges.</p> <p>application/Main.java</p> <pre><code>package application; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import com.fxgraph.graph.CellType; import com.fxgraph.graph.Graph; import com.fxgraph.graph.Model; import com.fxgraph.layout.base.Layout; import com.fxgraph.layout.random.RandomLayout; public class Main extends Application { Graph graph = new Graph(); @Override public void start(Stage primaryStage) { BorderPane root = new BorderPane(); graph = new Graph(); root.setCenter(graph.getScrollPane()); Scene scene = new Scene(root, 1024, 768); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); addGraphComponents(); Layout layout = new RandomLayout(graph); layout.execute(); } private void addGraphComponents() { Model model = graph.getModel(); graph.beginUpdate(); model.addCell("Cell A", CellType.RECTANGLE); model.addCell("Cell B", CellType.RECTANGLE); model.addCell("Cell C", CellType.RECTANGLE); model.addCell("Cell D", CellType.TRIANGLE); model.addCell("Cell E", CellType.TRIANGLE); model.addCell("Cell F", CellType.RECTANGLE); model.addCell("Cell G", CellType.RECTANGLE); model.addEdge("Cell A", "Cell B"); model.addEdge("Cell A", "Cell C"); model.addEdge("Cell B", "Cell C"); model.addEdge("Cell C", "Cell D"); model.addEdge("Cell B", "Cell E"); model.addEdge("Cell D", "Cell F"); model.addEdge("Cell D", "Cell G"); graph.endUpdate(); } public static void main(String[] args) { launch(args); } } </code></pre> <p>The scrollpane should have a white background.</p> <p>application/application.css</p> <pre><code>.scroll-pane &gt; .viewport { -fx-background-color: white; } </code></pre> <p>The zoomable scrollpane, I got the <a href="https://pixelduke.wordpress.com/2012/09/16/zooming-inside-a-scrollpane/">code base from pixel duke</a>:</p> <p>ZoomableScrollPane.java</p> <pre><code>package com.fxgraph.graph; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.ScrollPane; import javafx.scene.input.ScrollEvent; import javafx.scene.transform.Scale; public class ZoomableScrollPane extends ScrollPane { Group zoomGroup; Scale scaleTransform; Node content; double scaleValue = 1.0; double delta = 0.1; public ZoomableScrollPane(Node content) { this.content = content; Group contentGroup = new Group(); zoomGroup = new Group(); contentGroup.getChildren().add(zoomGroup); zoomGroup.getChildren().add(content); setContent(contentGroup); scaleTransform = new Scale(scaleValue, scaleValue, 0, 0); zoomGroup.getTransforms().add(scaleTransform); zoomGroup.setOnScroll(new ZoomHandler()); } public double getScaleValue() { return scaleValue; } public void zoomToActual() { zoomTo(1.0); } public void zoomTo(double scaleValue) { this.scaleValue = scaleValue; scaleTransform.setX(scaleValue); scaleTransform.setY(scaleValue); } public void zoomActual() { scaleValue = 1; zoomTo(scaleValue); } public void zoomOut() { scaleValue -= delta; if (Double.compare(scaleValue, 0.1) &lt; 0) { scaleValue = 0.1; } zoomTo(scaleValue); } public void zoomIn() { scaleValue += delta; if (Double.compare(scaleValue, 10) &gt; 0) { scaleValue = 10; } zoomTo(scaleValue); } /** * * @param minimizeOnly * If the content fits already into the viewport, then we don't * zoom if this parameter is true. */ public void zoomToFit(boolean minimizeOnly) { double scaleX = getViewportBounds().getWidth() / getContent().getBoundsInLocal().getWidth(); double scaleY = getViewportBounds().getHeight() / getContent().getBoundsInLocal().getHeight(); // consider current scale (in content calculation) scaleX *= scaleValue; scaleY *= scaleValue; // distorted zoom: we don't want it =&gt; we search the minimum scale // factor and apply it double scale = Math.min(scaleX, scaleY); // check precondition if (minimizeOnly) { // check if zoom factor would be an enlargement and if so, just set // it to 1 if (Double.compare(scale, 1) &gt; 0) { scale = 1; } } // apply zoom zoomTo(scale); } private class ZoomHandler implements EventHandler&lt;ScrollEvent&gt; { @Override public void handle(ScrollEvent scrollEvent) { // if (scrollEvent.isControlDown()) { if (scrollEvent.getDeltaY() &lt; 0) { scaleValue -= delta; } else { scaleValue += delta; } zoomTo(scaleValue); scrollEvent.consume(); } } } } </code></pre> <p>Every cell is represented as Pane into which you can put any Node as view (rectangle, label, imageview, etc)</p> <p>Cell.java</p> <pre><code>package com.fxgraph.graph; import java.util.ArrayList; import java.util.List; import javafx.scene.Node; import javafx.scene.layout.Pane; public class Cell extends Pane { String cellId; List&lt;Cell&gt; children = new ArrayList&lt;&gt;(); List&lt;Cell&gt; parents = new ArrayList&lt;&gt;(); Node view; public Cell(String cellId) { this.cellId = cellId; } public void addCellChild(Cell cell) { children.add(cell); } public List&lt;Cell&gt; getCellChildren() { return children; } public void addCellParent(Cell cell) { parents.add(cell); } public List&lt;Cell&gt; getCellParents() { return parents; } public void removeCellChild(Cell cell) { children.remove(cell); } public void setView(Node view) { this.view = view; getChildren().add(view); } public Node getView() { return this.view; } public String getCellId() { return cellId; } } </code></pre> <p>The cells should be created via some kind of factory, so they are classified by type:</p> <p>CellType.java</p> <pre><code>package com.fxgraph.graph; public enum CellType { RECTANGLE, TRIANGLE ; } </code></pre> <p>Instantiating them is quite easy:</p> <p>RectangleCell.java</p> <pre><code>package com.fxgraph.cells; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import com.fxgraph.graph.Cell; public class RectangleCell extends Cell { public RectangleCell( String id) { super( id); Rectangle view = new Rectangle( 50,50); view.setStroke(Color.DODGERBLUE); view.setFill(Color.DODGERBLUE); setView( view); } } </code></pre> <p>TriangleCell.java</p> <pre><code>package com.fxgraph.cells; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import com.fxgraph.graph.Cell; public class TriangleCell extends Cell { public TriangleCell( String id) { super( id); double width = 50; double height = 50; Polygon view = new Polygon( width / 2, 0, width, height, 0, height); view.setStroke(Color.RED); view.setFill(Color.RED); setView( view); } } </code></pre> <p>Then of course you need the edges. You can use any connection you like, even cubic curves. For sake of simplicity I use a line:</p> <p>Edge.java</p> <pre><code>package com.fxgraph.graph; import javafx.scene.Group; import javafx.scene.shape.Line; public class Edge extends Group { protected Cell source; protected Cell target; Line line; public Edge(Cell source, Cell target) { this.source = source; this.target = target; source.addCellChild(target); target.addCellParent(source); line = new Line(); line.startXProperty().bind( source.layoutXProperty().add(source.getBoundsInParent().getWidth() / 2.0)); line.startYProperty().bind( source.layoutYProperty().add(source.getBoundsInParent().getHeight() / 2.0)); line.endXProperty().bind( target.layoutXProperty().add( target.getBoundsInParent().getWidth() / 2.0)); line.endYProperty().bind( target.layoutYProperty().add( target.getBoundsInParent().getHeight() / 2.0)); getChildren().add( line); } public Cell getSource() { return source; } public Cell getTarget() { return target; } } </code></pre> <p>An extension to this would be to bind the edge to ports (north/south/east/west) of the cells.</p> <p>Then you'd want to drag the nodes, so you'd have to add some mouse gestures. The important part is to consider a zoom factor in case the graph canvas is zoomed</p> <p>MouseGestures.java</p> <pre><code>package com.fxgraph.graph; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.input.MouseEvent; public class MouseGestures { final DragContext dragContext = new DragContext(); Graph graph; public MouseGestures( Graph graph) { this.graph = graph; } public void makeDraggable( final Node node) { node.setOnMousePressed(onMousePressedEventHandler); node.setOnMouseDragged(onMouseDraggedEventHandler); node.setOnMouseReleased(onMouseReleasedEventHandler); } EventHandler&lt;MouseEvent&gt; onMousePressedEventHandler = new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { Node node = (Node) event.getSource(); double scale = graph.getScale(); dragContext.x = node.getBoundsInParent().getMinX() * scale - event.getScreenX(); dragContext.y = node.getBoundsInParent().getMinY() * scale - event.getScreenY(); } }; EventHandler&lt;MouseEvent&gt; onMouseDraggedEventHandler = new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { Node node = (Node) event.getSource(); double offsetX = event.getScreenX() + dragContext.x; double offsetY = event.getScreenY() + dragContext.y; // adjust the offset in case we are zoomed double scale = graph.getScale(); offsetX /= scale; offsetY /= scale; node.relocate(offsetX, offsetY); } }; EventHandler&lt;MouseEvent&gt; onMouseReleasedEventHandler = new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { } }; class DragContext { double x; double y; } } </code></pre> <p>Then you need a model in which you store the cells and the edges. Any time new cells can be added and existing ones can be deleted. You need to process them distinguished from the existing ones (e. g. to add mouse gestures, animate them when you add them, etc). When you implement the layout algorithm you'll be faced with the determination of a root node. So you should make an invisible root node (graphParent) which won't be added to the graph itself, but at which all nodes start that don't have a parent.</p> <p>Model.java</p> <pre><code>package com.fxgraph.graph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fxgraph.cells.TriangleCell; import com.fxgraph.cells.RectangleCell; public class Model { Cell graphParent; List&lt;Cell&gt; allCells; List&lt;Cell&gt; addedCells; List&lt;Cell&gt; removedCells; List&lt;Edge&gt; allEdges; List&lt;Edge&gt; addedEdges; List&lt;Edge&gt; removedEdges; Map&lt;String,Cell&gt; cellMap; // &lt;id,cell&gt; public Model() { graphParent = new Cell( "_ROOT_"); // clear model, create lists clear(); } public void clear() { allCells = new ArrayList&lt;&gt;(); addedCells = new ArrayList&lt;&gt;(); removedCells = new ArrayList&lt;&gt;(); allEdges = new ArrayList&lt;&gt;(); addedEdges = new ArrayList&lt;&gt;(); removedEdges = new ArrayList&lt;&gt;(); cellMap = new HashMap&lt;&gt;(); // &lt;id,cell&gt; } public void clearAddedLists() { addedCells.clear(); addedEdges.clear(); } public List&lt;Cell&gt; getAddedCells() { return addedCells; } public List&lt;Cell&gt; getRemovedCells() { return removedCells; } public List&lt;Cell&gt; getAllCells() { return allCells; } public List&lt;Edge&gt; getAddedEdges() { return addedEdges; } public List&lt;Edge&gt; getRemovedEdges() { return removedEdges; } public List&lt;Edge&gt; getAllEdges() { return allEdges; } public void addCell(String id, CellType type) { switch (type) { case RECTANGLE: RectangleCell rectangleCell = new RectangleCell(id); addCell(rectangleCell); break; case TRIANGLE: TriangleCell circleCell = new TriangleCell(id); addCell(circleCell); break; default: throw new UnsupportedOperationException("Unsupported type: " + type); } } private void addCell( Cell cell) { addedCells.add(cell); cellMap.put( cell.getCellId(), cell); } public void addEdge( String sourceId, String targetId) { Cell sourceCell = cellMap.get( sourceId); Cell targetCell = cellMap.get( targetId); Edge edge = new Edge( sourceCell, targetCell); addedEdges.add( edge); } /** * Attach all cells which don't have a parent to graphParent * @param cellList */ public void attachOrphansToGraphParent( List&lt;Cell&gt; cellList) { for( Cell cell: cellList) { if( cell.getCellParents().size() == 0) { graphParent.addCellChild( cell); } } } /** * Remove the graphParent reference if it is set * @param cellList */ public void disconnectFromGraphParent( List&lt;Cell&gt; cellList) { for( Cell cell: cellList) { graphParent.removeCellChild( cell); } } public void merge() { // cells allCells.addAll( addedCells); allCells.removeAll( removedCells); addedCells.clear(); removedCells.clear(); // edges allEdges.addAll( addedEdges); allEdges.removeAll( removedEdges); addedEdges.clear(); removedEdges.clear(); } } </code></pre> <p>And then there's the graph itself which contains the zoomable scrollpane, the model, etc. In the graph the added and removed nodes are handled (mouse gestures, cells and edges added to the scrollpane, etc).</p> <p>Graph.java</p> <pre><code>package com.fxgraph.graph; import javafx.scene.Group; import javafx.scene.control.ScrollPane; import javafx.scene.layout.Pane; public class Graph { private Model model; private Group canvas; private ZoomableScrollPane scrollPane; MouseGestures mouseGestures; /** * the pane wrapper is necessary or else the scrollpane would always align * the top-most and left-most child to the top and left eg when you drag the * top child down, the entire scrollpane would move down */ CellLayer cellLayer; public Graph() { this.model = new Model(); canvas = new Group(); cellLayer = new CellLayer(); canvas.getChildren().add(cellLayer); mouseGestures = new MouseGestures(this); scrollPane = new ZoomableScrollPane(canvas); scrollPane.setFitToWidth(true); scrollPane.setFitToHeight(true); } public ScrollPane getScrollPane() { return this.scrollPane; } public Pane getCellLayer() { return this.cellLayer; } public Model getModel() { return model; } public void beginUpdate() { } public void endUpdate() { // add components to graph pane getCellLayer().getChildren().addAll(model.getAddedEdges()); getCellLayer().getChildren().addAll(model.getAddedCells()); // remove components from graph pane getCellLayer().getChildren().removeAll(model.getRemovedCells()); getCellLayer().getChildren().removeAll(model.getRemovedEdges()); // enable dragging of cells for (Cell cell : model.getAddedCells()) { mouseGestures.makeDraggable(cell); } // every cell must have a parent, if it doesn't, then the graphParent is // the parent getModel().attachOrphansToGraphParent(model.getAddedCells()); // remove reference to graphParent getModel().disconnectFromGraphParent(model.getRemovedCells()); // merge added &amp; removed cells with all cells getModel().merge(); } public double getScale() { return this.scrollPane.getScaleValue(); } } </code></pre> <p>A wrapper for the cell layer. You'll probably want to add multiple layers (e. g. a selection layer which highlights selected cells)</p> <p>CellLayer.java</p> <pre><code>package com.fxgraph.graph; import javafx.scene.layout.Pane; public class CellLayer extends Pane { } </code></pre> <p>Now you need a layout for the cells. I suggest to create a simple abstract class which will get extended as you develop the graph.</p> <pre><code>package com.fxgraph.layout.base; public abstract class Layout { public abstract void execute(); } </code></pre> <p>For sake of simplicity here's a simple layout algorithm in which random coordinates are used. Of course you'd have to do more complex stuff like tree layouts, etc.</p> <p>RandomLayout.java</p> <pre><code>package com.fxgraph.layout.random; import java.util.List; import java.util.Random; import com.fxgraph.graph.Cell; import com.fxgraph.graph.Graph; import com.fxgraph.layout.base.Layout; public class RandomLayout extends Layout { Graph graph; Random rnd = new Random(); public RandomLayout(Graph graph) { this.graph = graph; } public void execute() { List&lt;Cell&gt; cells = graph.getModel().getAllCells(); for (Cell cell : cells) { double x = rnd.nextDouble() * 500; double y = rnd.nextDouble() * 500; cell.relocate(x, y); } } } </code></pre> <p>The example looks like this:</p> <p><img src="https://i.stack.imgur.com/eIeqk.png" alt="enter image description here"></p> <p>You can drag the cells with the mouse button and zoom in and out with the mouse wheel. </p> <hr> <p>Adding new cell types is as easy as creating subclasses of Cell:</p> <pre><code>package com.fxgraph.cells; import javafx.scene.control.Button; import com.fxgraph.graph.Cell; public class ButtonCell extends Cell { public ButtonCell(String id) { super(id); Button view = new Button(id); setView(view); } } package com.fxgraph.cells; import javafx.scene.image.ImageView; import com.fxgraph.graph.Cell; public class ImageCell extends Cell { public ImageCell(String id) { super(id); ImageView view = new ImageView("http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Siberischer_tiger_de_edit02.jpg/800px-Siberischer_tiger_de_edit02.jpg"); view.setFitWidth(100); view.setFitHeight(80); setView(view); } } package com.fxgraph.cells; import javafx.scene.control.Label; import com.fxgraph.graph.Cell; public class LabelCell extends Cell { public LabelCell(String id) { super(id); Label view = new Label(id); setView(view); } } package com.fxgraph.cells; import javafx.scene.control.TitledPane; import com.fxgraph.graph.Cell; public class TitledPaneCell extends Cell { public TitledPaneCell(String id) { super(id); TitledPane view = new TitledPane(); view.setPrefSize(100, 80); setView(view); } } </code></pre> <p>and creating the types</p> <pre><code>package com.fxgraph.graph; public enum CellType { RECTANGLE, TRIANGLE, LABEL, IMAGE, BUTTON, TITLEDPANE ; } </code></pre> <p>and creating instances depending on the type:</p> <pre><code>... public void addCell(String id, CellType type) { switch (type) { case RECTANGLE: RectangleCell rectangleCell = new RectangleCell(id); addCell(rectangleCell); break; case TRIANGLE: TriangleCell circleCell = new TriangleCell(id); addCell(circleCell); break; case LABEL: LabelCell labelCell = new LabelCell(id); addCell(labelCell); break; case IMAGE: ImageCell imageCell = new ImageCell(id); addCell(imageCell); break; case BUTTON: ButtonCell buttonCell = new ButtonCell(id); addCell(buttonCell); break; case TITLEDPANE: TitledPaneCell titledPaneCell = new TitledPaneCell(id); addCell(titledPaneCell); break; default: throw new UnsupportedOperationException("Unsupported type: " + type); } } ... </code></pre> <p>and you'll get this</p> <p><img src="https://i.stack.imgur.com/vxSQp.png" alt="enter image description here"></p>
22,254,756
SSh: Connection refused to localhost
<p>I want to install hadoop to ubuntu.</p> <p>I'm following this tutorial: <a href="http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/" rel="nofollow">Running Hadoop on Ubuntu Linux</a></p> <p>But i am facing a problem at step <code>ssh localhost</code></p> <pre><code>hduser@r:~$ ssh -vvv localhost -p 8047 OpenSSH_6.2p2 Ubuntu-6ubuntu0.1, OpenSSL 1.0.1e 11 Feb 2013 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 19: Applying options for * debug2: ssh_connect: needpriv 0 debug1: Connecting to localhost [127.0.0.1] port 8047. debug1: connect to address 127.0.0.1 port 8047: Connection refused ssh: connect to host localhost port 8047: Connection refused hduser@r:~$ which ssh /usr/bin/ssh hduser@r:~$ which sshd hduser@r:~$ </code></pre> <p>This is my /etc/ssh/sshd_config:</p> <p>last 5 lines added only!</p> <pre><code># Package generated configuration file # See the sshd_config(5) manpage for details # What ports, IPs and protocols we listen for Port 22 # Use these options to restrict which interfaces/protocols sshd will bind to #ListenAddress :: #ListenAddress 0.0.0.0 Protocol 2 # HostKeys for protocol version 2 HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key HostKey /etc/ssh/ssh_host_ecdsa_key #Privilege Separation is turned on for security UsePrivilegeSeparation yes # Lifetime and size of ephemeral version 1 server key KeyRegenerationInterval 3600 ServerKeyBits 768 # Logging SyslogFacility AUTH LogLevel INFO # Authentication: LoginGraceTime 120 PermitRootLogin yes StrictModes yes RSAAuthentication yes PubkeyAuthentication yes #AuthorizedKeysFile %h/.ssh/authorized_keys # Don't read the user's ~/.rhosts and ~/.shosts files IgnoreRhosts yes # For this to work you will also need host keys in /etc/ssh_known_hosts RhostsRSAAuthentication no # similar for protocol version 2 HostbasedAuthentication no # Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication #IgnoreUserKnownHosts yes # To enable empty passwords, change to yes (NOT RECOMMENDED) PermitEmptyPasswords no # Change to yes to enable challenge-response passwords (beware issues with # some PAM modules and threads) ChallengeResponseAuthentication no # Change to no to disable tunnelled clear text passwords #PasswordAuthentication yes # Kerberos options #KerberosAuthentication no #KerberosGetAFSToken no #KerberosOrLocalPasswd yes #KerberosTicketCleanup yes # GSSAPI options #GSSAPIAuthentication no #GSSAPICleanupCredentials yes X11Forwarding yes X11DisplayOffset 10 PrintMotd no PrintLastLog yes TCPKeepAlive yes #UseLogin no #MaxStartups 10:30:60 #Banner /etc/issue.net # Allow client to pass locale environment variables AcceptEnv LANG LC_* Subsystem sftp /usr/lib/openssh/sftp-server # Set this to 'yes' to enable PAM authentication, account processing, # and session processing. If this is enabled, PAM authentication will # be allowed through the ChallengeResponseAuthentication and # PasswordAuthentication. Depending on your PAM configuration, # PAM authentication via ChallengeResponseAuthentication may bypass # the setting of "PermitRootLogin without-password". # If you just want the PAM account and session checks to run without # PAM authentication, then enable this but set PasswordAuthentication # and ChallengeResponseAuthentication to 'no'. UsePAM yes AllowGroups hduser # disable ipv6 net.ipv6.conf.all.disable_ipv6 = 1 net.ipv6.conf.default.disable_ipv6 = 1 net.ipv6.conf.lo.disable_ipv6 = 1 </code></pre> <p>thanks in advance (and also for not voting down :D ) )</p> <p>EDIT:</p> <pre><code>hduser@r:~$ r@r:~$ netstat -tulpn tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN - tcp 0 0 127.0.1.1:53 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:17500 0.0.0.0:* LISTEN - udp 0 0 127.0.1.1:53 0.0.0.0:* - udp 0 0 0.0.0.0:68 0.0.0.0:* - udp 0 0 0.0.0.0:631 0.0.0.0:* - udp 0 0 0.0.0.0:17500 0.0.0.0:* - udp 0 0 0.0.0.0:5353 0.0.0.0:* - udp 0 0 0.0.0.0:26575 0.0.0.0:* - udp 0 0 0.0.0.0:47235 0.0.0.0:* - - </code></pre>
22,285,122
5
10
null
2014-03-07 15:55:39.623 UTC
4
2016-09-25 17:08:58.487 UTC
2014-03-07 16:30:58.753 UTC
null
1,114,121
null
1,114,121
null
1
2
linux|ubuntu|hadoop|ssh
46,392
<p>Don't panic! Your command is incorrect.</p> <pre><code>ssh -vvv localhost -p 8047 </code></pre> <p>The parameter <code>-p 8047</code> means to reach port 8047, however SSH daemon runs at port 22. The config of sshd you pasted, has already proven my assumption. </p> <p>You can try to access localhost via SSH by using</p> <pre><code>ssh hduser@localhost </code></pre>
16,797,601
maven-failsafe-plugin Errors and BUILD SUCCESS?
<p>my question is very similar to this one: <a href="https://stackoverflow.com/questions/12279160/maven-failsafe-plugin-failures-and-build-success">maven-failsafe-plugin Failures and BUILD SUCCESS?</a></p> <p>and I manage to set up failsafe plugin to fail if tests fail.</p> <p>But if test goes into error state, failsafe plugin still does not break the build.</p> <pre><code>................. ------------------------------------------------------- T E S T S ------------------------------------------------------- Running xxxxx.IntegrationTierFunctionalTestCase Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.054 sec &lt;&lt;&lt; FAILURE! Results : Tests in error: testException(xxxxx.IntegrationTierFunctionalTestCas Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is [INFO] [failsafe:verify {execution: functional-test-1024}] [INFO] Failsafe report directory: C:\projects\oec-integration-server\trunk\oec-integrati [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is [INFO] [failsafe:integration-test {execution: functional-test-24}] [INFO] Failsafe report directory: C:\projects\oec-integration-server\trunk\oec-integrati ............. [INFO] ------------------------------------------------------------------------ [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ [INFO] Total time: 58 seconds [INFO] Finished at: Tue May 28 17:48:13 BST 2013 [INFO] Final Memory: 114M/781M [INFO] ------------------------------------------------------------------------ </code></pre> <p>for simplicy IntegrationTierFunctionalTestCase contains only this code</p> <pre><code>import org.junit.Test; import static org.junit.Assert.fail; public class IntegrationTierFunctionalTestCase { @Test public void testException(){ //fail(); throw new RuntimeException("super error"); } } </code></pre> <p>if I uncomment fail() whole build fails correctly, with build failed. but if I just throw an exception, it fails as on shown above.</p> <p>oour plugin configuration looks like this</p> <pre class="lang-xml prettyprint-override"><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;2.7&lt;/version&gt; &lt;configuration&gt; &lt;redirectTestOutputToFile&gt;true&lt;/redirectTestOutputToFile&gt; &lt;systemPropertyVariables&gt; &lt;oec.env&gt;TEST&lt;/oec.env&gt; &lt;mule.test.timeoutSecs&gt;2400&lt;/mule.test.timeoutSecs&gt; &lt;/systemPropertyVariables&gt; &lt;additionalClasspathElements&gt; &lt;additionalClasspathElement&gt;${basedir}/src/main/resources/config&lt;/additionalClasspathElement&gt; &lt;/additionalClasspathElement&gt; &lt;/additionalClasspathElements&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;functional-test-1024&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/IntegrationTierFunctionalTestCase.java&lt;/include&gt; &lt;/includes&gt; &lt;forkMode&gt;once&lt;/forkMode&gt; &lt;argLine&gt;-XX:MaxPermSize=256M -Xmx1024M&lt;/argLine&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>What am I missing? And no I do not want to wrap it in try-catch blocks and fail tests manually.</p>
16,798,160
4
0
null
2013-05-28 17:01:51.957 UTC
3
2016-02-18 16:21:44.28 UTC
2017-05-23 11:53:49.883 UTC
null
-1
null
898,467
null
1
29
maven|maven-failsafe-plugin
19,258
<p>You need having two executions blocks, cause the verify goal of the maven-failsafe-plugin is intended to check the results of the integration tests.</p> <pre><code> &lt;executions&gt; &lt;execution&gt; &lt;id&gt;functional-test-1024&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/IntegrationTierFunctionalTestCase.java&lt;/include&gt; &lt;/includes&gt; &lt;forkMode&gt;once&lt;/forkMode&gt; &lt;argLine&gt;-XX:MaxPermSize=256M -Xmx1024M&lt;/argLine&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;verify&lt;/id&gt; &lt;phase&gt;verify&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; </code></pre> <p>Furthermore you should update the version of the maven-failsafe-plugin to 2.14.1 instead of 2.7. <strong>Update:</strong> In the meantime update to <a href="http://maven.apache.org/surefire/maven-failsafe-plugin/">2.17</a>.</p>
17,064,791
$http doesn't send cookie in Requests
<p>We are working on a RESTful Webservice with AngularJS and Java Servlets. When the user logs in, our backend sends a "Set-Cookie" header to the frontend. In Angular we access the header via <code>$cookies</code> (ngCookie - module) and set it. <img src="https://i.stack.imgur.com/ltMrA.png" alt="enter image description here"></p> <p>Now that the user is logged in he can for example delete some stuff. Therefore the frontend sends a GET request to the backend. Because we work on different domains we need to set some CORS Headers and Angular does an OPTIONS request before the actual GET request:</p> <p><strong>OPTIONS request:</strong> <img src="https://i.stack.imgur.com/GKMRf.png" alt="OPTIONS request"></p> <p><strong>GET request</strong> <img src="https://i.stack.imgur.com/nRnSx.png" alt="GET request"></p> <p>We do this in Angular via $http module, but it just won't send the cookie, containing <code>JSESSIONID</code>.</p> <p><strong>How can I enable Angular to send cookies?</strong></p>
17,065,576
2
0
null
2013-06-12 11:52:53.7 UTC
28
2017-05-04 23:08:51.383 UTC
2016-12-27 07:27:21.333 UTC
null
6,521,116
null
1,263,876
null
1
73
html|angularjs|webkit|xmlhttprequest
69,174
<p>In your config, DI <code>$httpProvider</code> and then set withCredentials to true:</p> <pre><code>.config(function ($httpProvider) { $httpProvider.defaults.withCredentials = true; //rest of route code }) </code></pre> <p>Info on angularjs withCredentials: <a href="http://docs.angularjs.org/api/ng.$http" rel="noreferrer">http://docs.angularjs.org/api/ng.$http</a></p> <p>Which links to the mozilla article: <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&amp;redirectslug=HTTP_access_control#section_5" rel="noreferrer">https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&amp;redirectslug=HTTP_access_control#section_5</a></p>
4,682,621
SQL: How to select rows from a table while ignoring the duplicate field values?
<p>How to select rows from a table while ignoring the duplicate field values?</p> <p>Here is an example:</p> <pre><code>id user_id message 1 Adam "Adam is here." 2 Peter "Hi there this is Peter." 3 Peter "I am getting sick." 4 Josh "Oh, snap. I'm on a boat!" 5 Tom "This show is great." 6 Laura "Textmate rocks." </code></pre> <p>What i want to achive is to select the recently active users from my db. Let's say i want to select the 5 recently active users. The problem is, that the following script selects Peter twice.</p> <pre><code>mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 5 "); </code></pre> <p>What i want is to skip the row when it gets again to Peter, and select the next result, in our case Adam. So i don't want to show my visitors that the recently active users were Laura, Tom, Josh, Peter, and Peter again. That does not make any sense, instead i want to show them this way: Laura, Tom, Josh, Peter, (skipping Peter) and Adam.</p> <p>Is there an SQL command i can use for this problem?</p>
4,682,691
2
0
null
2011-01-13 16:43:29.523 UTC
2
2018-08-09 06:42:38.73 UTC
2011-01-13 16:59:47.623 UTC
null
523,432
null
523,432
null
1
17
sql|mysql
55,040
<p>Yes. "DISTINCT".</p> <pre><code> SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5 </code></pre>
4,813,160
MongoDB 1.6.5: how to rename field in collection
<p>$rename function is available only in development version 1.7.2. How to rename field in 1.6.5?</p>
4,813,897
2
0
null
2011-01-27 05:48:01.893 UTC
10
2013-11-08 13:31:30.68 UTC
null
null
null
null
151,531
null
1
17
mongodb
12,350
<p>The simplest way to perform such an operation is to loop through the data set re-mapping the name of the field. The easiest way to do this is to write a function that performs the re-write and then use the <code>.find().forEach()</code> syntax in the shell.</p> <p>Here's a sample from the shell:</p> <pre><code>db.foo.save({ a : 1, b : 2, c : 3}); db.foo.save({ a : 4, b : 5, c : 6}); db.foo.save({ a : 7, b : 8 }); db.foo.find(); remap = function (x) { if (x.c){ db.foo.update({_id:x._id}, {$set:{d:x.c}, $unset:{c:1}}); } } db.foo.find().forEach(remap); db.foo.find(); </code></pre> <p>In the case above I'm doing an <code>$unset</code> and a <code>$set</code> in the same action. MongoDB does not support transactions across collections, but the above is a single document. So you're guaranteed that the set and unset will be atomic (<em>i.e. they both succeed or they both fail</em>).</p> <p>The only limitation here is that you'll need to manage outside writers to keep the data consistent. My normal preference for this is simply to turn off writes while this updates. If this option is not available, then you'll have to figure out what level of consistency you want for the data. (I can provide some ideas here, but it's really going to be specific to your data and system)</p>
4,799,758
Are nested Try/Catch blocks a bad idea?
<p>Let's say we have a structure like so:</p> <pre><code>Try ' Outer try code, that can fail with more generic conditions, ' that I know less about and might not be able to handle Try ' Inner try code, that can fail with more specific conditions, ' that I probably know more about, and are likely to handle appropriately Catch innerEx as Exception ' Handle the inner exception End Try Catch outerEx as Exception ' Handle outer exception End Try </code></pre> <p>I have seen some opinions that nesting <code>Try</code> blocks like this is discouraged, but I could not find any specific reasons.</p> <p>Is this bad code? If so, why?</p>
4,799,779
2
1
null
2011-01-25 22:50:48.703 UTC
8
2019-07-05 21:45:54.517 UTC
2011-01-25 22:58:10.14 UTC
null
23,199
null
84,398
null
1
91
.net|vb.net|exception-handling
89,805
<p>There are certain circumstances where they're a good idea, e.g. one try/catch for the whole method and another inside a loop as you want to handle the exception and continue processing the rest of a collection.</p> <p>Really the only reason to do it is if you want to skip the bit that errored and carry on, instead of unwinding the stack and losing context. Opening multiple files in an editor is one example.</p> <p>That said, exceptions should (as the name implies) be exceptional. A program should handle them but try to avoid them as part of normal execution flow. They're computationally expensive in <em>most</em> languages (Python being one notable exception).</p> <p>One other technique which can be useful is catching specific exception types...</p> <pre><code>Try 'Some code to read from a file Catch ex as IOException 'Handle file access issues (possibly silently depending on usage) Catch ex as Exception ' Handle all other exceptions. ' If you've got a handler further up, just omit this Catch and let the ' exception propagate Throw End Try </code></pre> <p>We also use nested try/catches in our error handling routines...</p> <pre><code> Try Dim Message = String.Format("...", ) Try 'Log to database Catch ex As Exception 'Do nothing End Try Try 'Log to file Catch ex As Exception 'Do nothing End Try Catch ex As Exception 'Give up and go home End Try </code></pre>
26,443,242
After upgrade, PHP no longer supports PNG operations
<p>After updating to Mac OS X 10.10 (Yosemite) and starting Apache with PHP support, everything works as before except for any image operations on PNG files. I get a <code>Call to undefined function imagecreatefrompng()</code>, while any operation on JPEG files work. So GD is present, but not for PNG.</p> <p>There is one line in the <code>phpinfo()</code> that looks like the problem: '--with-png-dir=no' </p> <p><img src="https://i.stack.imgur.com/o3IGg.png" alt="phpinfo()"></p> <p>The GD section from <code>phpinfo()</code>:</p> <p><img src="https://i.stack.imgur.com/adKap.png" alt="Enter image description here"></p> <p>How do I get the included PHP to work with PNG files?</p>
26,566,017
3
6
null
2014-10-18 18:40:29.817 UTC
18
2017-04-20 08:53:45.787 UTC
2017-04-20 08:53:45.787 UTC
null
1,255,289
null
1,998,479
null
1
18
php|osx-yosemite|php-gd
16,183
<p>Here's another option, from the guys from liip, <a href="http://php-osx.liip.ch/" rel="nofollow">here</a>. This is a PHP package that comes pre-built for Yosemite (older versions works too) but it is just <strong>one line</strong> of code:</p> <p><code>curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5</code></p> <p>After that, everything is ready to work as expected. The configuration that cames with that installation is well suited for Symfony 2 development, but it should work just fine with other use cases.</p> <p>Finally, if you need to use the updated PHP CLI, too, but you don't want to use the PHP version that comes with the OS, then you could also add to your <code>.bash_profile</code> or similar this line of code:</p> <p><code>export PATH=/usr/local/php5/bin:$PATH</code></p>
10,066,235
R: selecting items matching criteria from a vector
<p>I have a numeric vector in R, which consists of both negative and positive numbers. I want to separate the numbers in the list based on sign (ignoring zero for now), into two seperate lists:</p> <ul> <li>a new vector containing only the negative numbers</li> <li>another vector containing only the positive numbers</li> </ul> <p>The documentation shows how to do this for selecting rows/columns/cells in a dataframe - but this dosen't work with vectors AFAICT.</p> <p>How can it be done (without a for loop)?</p>
10,066,259
3
1
null
2012-04-08 20:29:22.827 UTC
2
2017-02-28 19:16:28.3 UTC
null
null
null
null
962,891
null
1
9
r
39,994
<p>It is done very easily (added check for NaN):</p> <pre><code>d &lt;- c(1, -1, 3, -2, 0, NaN) positives &lt;- d[d&gt;0 &amp; !is.nan(d)] negatives &lt;- d[d&lt;0 &amp; !is.nan(d)] </code></pre> <p>If you want exclude both NA and NaN, is.na() returns true for both:</p> <pre><code>d &lt;- c(1, -1, 3, -2, 0, NaN, NA) positives &lt;- d[d&gt;0 &amp; !is.na(d)] negatives &lt;- d[d&lt;0 &amp; !is.na(d)] </code></pre>
9,841,363
How to restrict number of characters that can be entered in HTML5 number input field on iPhone
<p>It seems that neither of the "maxlength", "min" or "max" HTML attributes have the desired effect on iPhone for the following markup: </p> <pre><code> &lt;input type="number" maxlength="2" min="0" max="99"/&gt; </code></pre> <p>Instead of limiting the number of digits or the value of the number entered, the number is just left as it was typed in on iPhone 4. This markup works on most other phones we tested. </p> <p>What gives?</p> <p>Any workarounds?</p> <p>If it is important to the solution, we use jQuery mobile.</p> <p>Thanks!</p>
10,656,599
11
0
null
2012-03-23 14:53:30.75 UTC
12
2021-06-03 16:05:05.313 UTC
2012-03-23 22:44:06.47 UTC
null
1,237,812
null
1,035,897
null
1
30
iphone|html|jquery-mobile|input
116,880
<p>Example</p> <p><strong>JS</strong></p> <pre><code>function limit(element) { var max_chars = 2; if(element.value.length &gt; max_chars) { element.value = element.value.substr(0, max_chars); } } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;input type="number" onkeydown="limit(this);" onkeyup="limit(this);"&gt; </code></pre> <p>If you are using jQuery you can tidy up the JavaScript a little:</p> <p><strong>JS</strong></p> <pre><code>var max_chars = 2; $('#input').keydown( function(e){ if ($(this).val().length &gt;= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } }); $('#input').keyup( function(e){ if ($(this).val().length &gt;= max_chars) { $(this).val($(this).val().substr(0, max_chars)); } }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;input type="number" id="input"&gt; </code></pre>
10,031,580
How to write simple geometric shapes into numpy arrays
<p>I would like to generate a numpy array of 200x200 elements in size and put into it a circle centered into 100,100 coordinates, radius 80 and stroke width of 3 pixels. How to do this in python 2.7 without involving file operations? Possibly using geometry or imaging libraries to allow generalisation to other shapes.</p>
10,031,877
5
0
null
2012-04-05 15:32:41.737 UTC
27
2021-10-08 07:58:32.213 UTC
null
null
null
null
1,006,828
null
1
33
python|image|numpy|geometry
51,699
<p><a href="http://www.cairographics.org/" rel="noreferrer">Cairo</a> is a modern, flexible and fast 2D graphics library. It has <a href="http://www.cairographics.org/pycairo/" rel="noreferrer">Python bindings</a> and allows creating "surfaces" based on NumPy arrays:</p> <pre class="lang-py prettyprint-override"><code>import numpy import cairo import math data = numpy.zeros((200, 200, 4), dtype=numpy.uint8) surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, 200, 200) cr = cairo.Context(surface) # fill with solid white cr.set_source_rgb(1.0, 1.0, 1.0) cr.paint() # draw red circle cr.arc(100, 100, 80, 0, 2*math.pi) cr.set_line_width(3) cr.set_source_rgb(1.0, 0.0, 0.0) cr.stroke() # write output print data[38:48, 38:48, 0] surface.write_to_png("circle.png") </code></pre> <p>This code prints</p> <pre><code>[[255 255 255 255 255 255 255 255 132 1] [255 255 255 255 255 255 252 101 0 0] [255 255 255 255 255 251 89 0 0 0] [255 255 255 255 249 80 0 0 0 97] [255 255 255 246 70 0 0 0 116 254] [255 255 249 75 0 0 0 126 255 255] [255 252 85 0 0 0 128 255 255 255] [255 103 0 0 0 118 255 255 255 255] [135 0 0 0 111 255 255 255 255 255] [ 1 0 0 97 254 255 255 255 255 255]] </code></pre> <p>showing some random fragment of the circle. It also creates this PNG:</p> <p><img src="https://i.stack.imgur.com/LHenM.png" alt="Red circle"></p>
44,094,037
Android Studio - Failed to notify project evaluation listener error
<p>Following is the build.gradle code in Android Studio</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.sg.blahblah" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } lintOptions { checkReleaseBuilds true abortOnError false xmlReport true htmlReport true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' lintOptions { disable 'MissingTranslation' } } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.android.support:support-v4:23.1.1' compile 'com.android.support:cardview-v7:23.1.1' compile 'com.google.android.apps.dashclock:dashclock-api:+' compile 'com.roughike:bottom-bar:1.4.0.1' compile 'com.diogobernardino:williamchart:2.2' } </code></pre> <p>I am getting the below error: Error:A problem occurred configuring project ':app'.</p> <blockquote> <p>Failed to notify project evaluation listener. com.android.build.gradle.tasks.factory.AndroidJavaCompile.setDependencyCacheDir(Ljava/io/File;)V</p> </blockquote> <p>Can anyone please help?</p> <p>Following is the Instant Run screenshot <a href="https://i.stack.imgur.com/PJtdd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PJtdd.png" alt="enter image description here"></a></p>
44,094,086
34
8
null
2017-05-21 06:57:29.357 UTC
15
2022-05-19 14:22:02.137 UTC
2017-05-21 07:35:34.163 UTC
null
7,765,493
null
7,765,493
null
1
109
android|android-studio|build.gradle
202,232
<p>I am facing same error before a week I solve by disabling the <code>Instant Run</code></p> <blockquote> <p>File → Settings → Build, Execution, Deployment → Instant Run and uncheck Enable Instant Run.</p> </blockquote> <p>Hope it works.</p> <p><strong>Note</strong> This answer works on below Android Studio 3</p>
9,870,512
How to obtain the query string from the current URL with JavaScript?
<p>I have URL like this:</p> <pre><code>http://localhost/PMApp/temp.htm?ProjectID=462 </code></pre> <p>What I need to do is to get the details after the <code>?</code> sign (query string) - that is <code>ProjectID=462</code>. How can I get that using JavaScript?</p> <p><strong>What I've done so far is this:</strong></p> <pre><code>var url = window.location.toString(); url.match(?); </code></pre> <p>I don't know what to do next.</p>
9,870,540
19
5
null
2012-03-26 10:30:43.16 UTC
33
2021-09-03 06:42:24.06 UTC
2018-01-02 05:51:03.807 UTC
null
4,373,584
null
1,134,935
null
1
159
javascript|query-string
382,076
<p>Have a look at the <a href="https://developer.mozilla.org/en/DOM/window.location" rel="noreferrer">MDN article</a> about <code>window.location</code>.</p> <p>The QueryString is available in <code>window.location.search</code>.</p> <p>If you want a more convenient interface to work with, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams#Example" rel="noreferrer"><code>searchParams</code></a> property of the URL interface, which returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer">URLSearchParams</a> object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:</p> <pre><code>let params = (new URL(document.location)).searchParams; let name = params.get(&quot;name&quot;); </code></pre> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer">URLSearchParams</a> interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.</p> <pre><code>let paramsString = &quot;name=foo&amp;age=1337&quot; let searchParams = new URLSearchParams(paramsString); searchParams.has(&quot;name&quot;) === true; // true searchParams.get(&quot;age&quot;) === &quot;1337&quot;; // true </code></pre> <p><em>The URLSearchParams interface is now widely adopted in browsers (95%+ according to <a href="https://caniuse.com/?search=URLSearchParams" rel="noreferrer">Can I Use</a>), but if you do need to support legacy browsers as well, you can use a <a href="https://www.npmjs.com/package/url-search-params-polyfill" rel="noreferrer">polyfill</a>.</em></p>
7,863,499
Conversion of Char to Binary in C
<p>I am trying to convert a character to its binary representation (so character --> ascii hex --> binary).</p> <p>I know to do that I need to shift and <code>AND</code>. However, my code is not working for some reason.</p> <p>Here is what I have. <code>*temp</code> points to an index in a C string.</p> <pre><code>char c; int j; for (j = i-1; j &gt;= ptrPos; j--) { char x = *temp; c = (x &gt;&gt; i) &amp; 1; printf("%d\n", c); temp--; } </code></pre>
7,863,524
3
3
null
2011-10-23 00:15:30.327 UTC
10
2018-05-10 11:39:39.867 UTC
null
null
null
null
680,441
null
1
7
c|string|binary|char|ascii
123,164
<p>We show up two functions that prints a SINGLE character to binary.</p> <pre><code>void printbinchar(char character) { char output[9]; itoa(character, output, 2); printf("%s\n", output); } </code></pre> <p>printbinchar(10) will write into the console</p> <pre><code> 1010 </code></pre> <p>itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".</p> <p>The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.</p> <pre><code>void printbincharpad(char c) { for (int i = 7; i &gt;= 0; --i) { putchar( (c &amp; (1 &lt;&lt; i)) ? '1' : '0' ); } putchar('\n'); } </code></pre> <p>printbincharpad(10) will write into the console</p> <pre><code> 00001010 </code></pre> <p>Now i present a function that prints out an entire string (without last null character).</p> <pre><code>void printstringasbinary(char* s) { // A small 9 characters buffer we use to perform the conversion char output[9]; // Until the first character pointed by s is not a null character // that indicates end of string... while (*s) { // Convert the first character of the string to binary using itoa. // Characters in c are just 8 bit integers, at least, in noawdays computers. itoa(*s, output, 2); // print out our string and let's write a new line. puts(output); // we advance our string by one character, // If our original string was "ABC" now we are pointing at "BC". ++s; } } </code></pre> <p>Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:</p> <pre><code>1000001 1000010 110001 </code></pre>
8,171,959
Confused by closures in JavaScript
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/111102/how-do-javascript-closures-work">How do JavaScript closures work?</a><br> <a href="https://stackoverflow.com/questions/8129105/javascript-closures-and-side-effects-in-plain-english-separately">Javascript closures and side effects in plain English? (separately)</a> </p> </blockquote> <p>I'm new to JavaScript but I'm really confused by how closures work. Can someone explain in layman's terms what they are or why they are useful?</p>
8,172,089
3
2
null
2011-11-17 17:56:20.097 UTC
3
2016-08-03 18:08:55.897 UTC
2017-05-23 12:17:11.7 UTC
null
-1
null
1,019,031
null
1
36
javascript|closures
1,897
<p>Closures are something like the context of a function when it is defined. Whenever a function is defined, the context is stored, and even if the 'normal' life cycle of your function is over, if you keep a reference to an element defined whithin your function execution, it can still access to elements of the context (closure), which is actually the scope of your function in its definition. Sorry for my bad english, but probably this example will make you understand: </p> <pre><code>function test() { var a = "hello world"; var checkValue = function() { alert(a); }; checkValue(); a = "hi again"; return checkValue; } var pointerToCheckValue = test(); //it will print "hello world" and a closure will be created with the context where the checkValue function was defined. pointerToCheckValue(); //it will execute the function checkValue with the context (closure) used when it was defined, so it still has access to the "a" variable </code></pre> <p>Hope it helps :-)</p>
11,686,884
Record and send/stream sound from iOS device to a server continuously
<p>I am developing an iOS app that has a button with a microphone on it (along with other features). When the user presses the microphone, it gets highlighted and the app should now start recording sound from the device´s microphone and send to a server (a server dedicated to the app, developed by people that I know, so I can affect its design).</p> <p>I am looking for the simplest yet sturdiest approach to do this, i.e. I have no need to develop a complicated streaming solution or VoIP functionality, unless it is as simple to do as anything else.</p> <p>The main problem is that we have no idea for how long the user will be recording sound, but we want to make sure that sounds are sent to the server continuously, we do not wish to wait until the user has finished recording. It is okay if the data arrives to the server in chunks however we do not wish to miss any information that the user may be recording, so one chunk must continue where the previous one ended and so on.</p> <p>Our first thought was to create "chunks" of sound clips of for example 10 seconds and send them continuously to the server. Is there any streaming solution that is better/simpler that I am missing out on?</p> <p>My question is, what would be the most simple but still reliable approach on solving this task on iOS?</p> <p>Is there a way to extract chunks of sound from a running recording by AVAudioRecorder, without actually stopping the recording?</p>
11,845,575
2
6
null
2012-07-27 11:30:22.503 UTC
18
2017-04-25 17:27:12.143 UTC
2017-04-25 17:27:12.143 UTC
null
1,033,581
null
601,396
null
1
21
iphone|ios|cocoa-touch|ipad|audio-recording
11,690
<p>look at <a href="http://www.techotopia.com/index.php/Recording_Audio_on_an_iPhone_with_AVAudioRecorder_%28iOS_4%29" rel="noreferrer">this</a><br/> in this tutorial, the sound recorded will be saved at soundFileURL, then you will just have to create an nsdata with that content, and then send it to your server.<br/> hope this helped.</p> <p>EDIT : <br/> I just created a version that contain 3 buttons, REC, SEND and Stop :<br/> REC : will start recording into a file.<br/> SEND : will save what was recorded on that file in a NSData, and send it to a server, then will restart recording.<br/> and STOP : will stop recording. <br/> here is the code : in your .h file :</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import &lt;AVFoundation/AVFoundation.h&gt; @interface ViewController : UIViewController &lt;AVAudioRecorderDelegate&gt; @property (nonatomic, retain) AVAudioRecorder *audioRecorder; @property (nonatomic, retain) IBOutlet UIButton *recordButton; @property (nonatomic, retain) IBOutlet UIButton *stopButton; @property (nonatomic, retain) IBOutlet UIButton *sendButton; @property BOOL stoped; - (IBAction)startRec:(id)sender; - (IBAction)sendToServer:(id)sender; - (IBAction)stop:(id)sender; @end </code></pre> <p>and in the .m file : <br/></p> <pre><code>#import "ViewController.h" @implementation ViewController @synthesize audioRecorder; @synthesize recordButton,sendButton,stopButton; @synthesize stoped; - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. sendButton.enabled = NO; stopButton.enabled = NO; stoped = YES; NSArray *dirPaths; NSString *docsDir; dirPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"tempsound.caf"]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey, [NSNumber numberWithInt:16], AVEncoderBitRateKey, [NSNumber numberWithInt: 2], AVNumberOfChannelsKey, [NSNumber numberWithFloat:44100.0], AVSampleRateKey, nil]; NSError *error = nil; audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&amp;error]; audioRecorder.delegate = self; if (error) { NSLog(@"error: %@", [error localizedDescription]); } else { [audioRecorder prepareToRecord]; } } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } - (BOOL) sendAudioToServer :(NSData *)data { NSData *d = [NSData dataWithData:data]; //now you'll just have to send that NSData to your server return YES; } -(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag { NSLog(@"stoped"); if (!stoped) { NSData *data = [NSData dataWithContentsOfURL:recorder.url]; [self sendAudioToServer:data]; [recorder record]; NSLog(@"stoped sent and restarted"); } } - (IBAction)startRec:(id)sender { if (!audioRecorder.recording) { sendButton.enabled = YES; stopButton.enabled = YES; [audioRecorder record]; } } - (IBAction)sendToServer:(id)sender { stoped = NO; [audioRecorder stop]; } - (IBAction)stop:(id)sender { stopButton.enabled = NO; sendButton.enabled = NO; recordButton.enabled = YES; stoped = YES; if (audioRecorder.recording) { [audioRecorder stop]; } } @end </code></pre> <p>Good Luck.</p>
11,785,565
How can I disable landscape orientation?
<p>I am making an iPhone app and I need it to be in portrait mode, so if the user moves the device sideways, it does not automatically rotate. How can I do this?</p>
11,785,618
11
0
null
2012-08-02 20:51:59.283 UTC
10
2022-06-08 16:04:35.857 UTC
2016-01-22 17:18:06.54 UTC
null
1,709,587
null
1,483,652
null
1
36
iphone|objective-c|ios|xcode|orientation
61,139
<p>To disable orientations <strong>for a particular View Controller</strong>, you should now override <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/supportedInterfaceOrientations" rel="nofollow noreferrer"><code>supportedInterfaceOrientations</code></a> and <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/preferredInterfaceOrientationForPresentation" rel="nofollow noreferrer"><code>preferredInterfaceOrientationForPresentation</code></a>.</p> <pre><code>- (UIInterfaceOrientationMask)supportedInterfaceOrientations { // Return a bitmask of supported orientations. If you need more, // use bitwise or (see the commented return). return UIInterfaceOrientationMaskPortrait; // return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { // Return the orientation you'd prefer - this is what it launches to. The // user can still rotate. You don't have to implement this method, in which // case it launches in the current orientation return UIInterfaceOrientationPortrait; } </code></pre> <p>If you're targeting something older than iOS 6, you want the <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/shouldAutorotateToInterfaceOrientation:" rel="nofollow noreferrer"><code>shouldAutorotateToInterfaceOrientation:</code></a> method. By changing when it returns yes, you'll determine if it will rotate to said orientation. This will only allow the normal portrait orientation.</p> <pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); // Use this to allow upside down as well //return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown); } </code></pre> <p><strong>Note that <code>shouldAutorotateToInterfaceOrientation:</code> has been deprecated in iOS 6.0</strong>.</p>
11,929,099
HTML5 Canvas drawImage ratio bug iOS
<p>I want to resize the image taken from the iOS camera on the client side with HTML5 Canvas but I keep running in this weird bug where the image has a wrong ratio if bigger than ~1.5mb</p> <p>It works on the desktop but not in the latest iOS version with the media upload API.</p> <p>You can see an example here: <a href="http://jsbin.com/ekuros/1">http://jsbin.com/ekuros/1</a></p> <p>Any idea how to fix this please? Is this a memory issue?</p> <pre><code>$('#file').on('change', function (e) { var file = e.currentTarget.files[0]; var reader = new FileReader(); reader.onload = function (e) { var image = $('&lt;img/&gt;'); image.on('load', function () { var square = 320; var canvas = document.createElement('canvas'); canvas.width = square; canvas.height = square; var context = canvas.getContext('2d'); context.clearRect(0, 0, square, square); var imageWidth; var imageHeight; var offsetX = 0; var offsetY = 0; if (this.width &gt; this.height) { imageWidth = Math.round(square * this.width / this.height); imageHeight = square; offsetX = - Math.round((imageWidth - square) / 2); } else { imageHeight = Math.round(square * this.height / this.width); imageWidth = square; offsetY = - Math.round((imageHeight - square) / 2); } context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight); var data = canvas.toDataURL('image/jpeg'); var thumb = $('&lt;img/&gt;'); thumb.attr('src', data); $('body').append(thumb); }); image.attr('src', e.target.result); }; reader.readAsDataURL(file); }); </code></pre>
12,816,406
5
5
null
2012-08-13 06:23:16.983 UTC
50
2014-08-10 16:51:21.253 UTC
null
null
null
null
1,097,744
null
1
55
javascript|ios|html|canvas
47,803
<p>There is a JavaScript canvas resize library which works around the subsampling and vertical squash issues encountered when drawing scaled images on canvas on iOS devices: <a href="http://github.com/stomita/ios-imagefile-megapixel" rel="nofollow noreferrer">http://github.com/stomita/ios-imagefile-megapixel</a></p> <p>There are side issues when scaling images with alpha channel (as it uses the alpha channel for the issues detection) and when trying to resize existing canvas elements, however it's the first solution I've found that actually works with the issue at hand.</p> <p>stomita is also a StackOverflow user and posted his solution here: <a href="https://stackoverflow.com/a/12615436/644048">https://stackoverflow.com/a/12615436/644048</a></p>
11,620,103
Mockito: Trying to spy on method is calling the original method
<p>I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have</p> <pre><code>final MyClass myClassSpy = Mockito.spy(myInstance); Mockito.when(myClassSpy.method1()).thenReturn(myResults); </code></pre> <p>The problem is, in the second line, <code>myClassSpy.method1()</code> is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever <code>myClassSpy.method1()</code> is called, the real method won't be called and the <code>myResults</code> object will be returned. </p> <p><code>MyClass</code> is an interface and <code>myInstance</code> is an implementation of that, if that matters.</p> <p>What do I need to do to correct this spying behaviour?</p>
11,620,196
10
1
null
2012-07-23 20:35:02.64 UTC
95
2021-11-30 14:43:43.25 UTC
2016-03-03 23:07:21.39 UTC
null
211,176
null
1,235,929
null
1
460
java|junit|mockito
313,389
<p>Let me quote <a href="https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html#13" rel="noreferrer">the official documentation</a>:</p> <blockquote> <h2>Important gotcha on spying real objects!</h2> <p>Sometimes it's impossible to use when(Object) for stubbing spies. Example:</p> <pre><code>List list = new LinkedList(); List spy = spy(list); // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn(&quot;foo&quot;); // You have to use doReturn() for stubbing doReturn(&quot;foo&quot;).when(spy).get(0); </code></pre> </blockquote> <p>In your case it goes something like:</p> <pre><code>doReturn(resultsIWant).when(myClassSpy).method1(); </code></pre>
3,950,922
Storing graphs in fully-normalized relational databases
<h2>Goal</h2> <p>Find a <em>perfect</em>, flexible schema for storing <strong>many different types of objects with a wide variety of links</strong> between them in a <strong>relational</strong> database. </p> <hr> <h2>Problem</h2> <p><strong>EAV is a workaround to the normal confinements of a RDBMS.</strong></p> <p>If you were to normalize an EAV schema, it would be ugly.</p> <hr> <h2>Idea</h2> <p>If EAV was normalized, it would be ugly. </p> <p><strong>Does the fact that we traditionally maintain these schema by hand limit their complexity and power?</strong></p> <p>But if it was maintained and queried programmatically, what would it matter?</p> <hr> <h2>Graphs</h2> <p>If you have <code>n</code> different entities in <code>n</code> different tables, <strong>why not</strong> let your code generate <code>n(n+1)/2</code> link tables and the queries between them? Would this not result in a true graph in a normalized schema?</p> <p><strong>In a highly interlinked database, there will always be exponentially more edges than vertices.</strong> Why not focus on creating proper, normalized verticles (<code>n</code> entity tables) and let our code maintain the edges (<code>n^x</code> link tables)?</p> <hr> <h2>Conclusion</h2> <p>Can a system normalize EAV and maintain the resulting complex schema?</p> <p>Can complex graphs be stored in (and remain true to) relational databases?</p> <p>I'm sure this has been done before, but I've never seen it. What am I missing?</p> <hr> <h2>Example problem</h2> <p><strong>Storing printed works and their bibliographic data</strong></p> <ul> <li><strong>Many properties</strong> which might be not just strings but whole objects. </li> <li>In the library world, there is no simple (and relational) schema which can <strong>store data "losslessly"</strong> without extremely complex schemas.</li> <li><strong>Many different types of associations</strong> and associated objects <ul> <li>And their relevant properties (which can vary wildly). </li> <li>And their many relationships, of different types, amongst themselves.</li> </ul></li> </ul> <hr> <h2>Questions</h2> <p><strong>"<em>What problem are you trying to solve?</em>"</strong><br> -Piet</p> <p>I'm looking for a normalized solution to EAV, graphs, and polymorphic relationships in a relational database system.</p> <p><strong>"<em>I would hate to be the guy who has to understand or maintain it after it's gone into production.</em>"</strong><br> -Andrew</p> <p>This "traditional maintenance" is the exact thing I'm saying we should be automating. Isn't it largely grunt work?</p>
4,776,156
4
4
null
2010-10-16 21:42:17.743 UTC
13
2011-02-08 18:09:01.387 UTC
2011-01-21 18:48:02.747 UTC
null
431,409
null
431,409
null
1
14
database-design|language-agnostic|data-structures|graph|relational-database
3,606
<p>Since you are editing the question, it must be active.</p> <p>Yes, there are much better ways of designing this, for the purpose and use you describe.</p> <p>The first issue is EAV, which is usually very badly implemented. More precisely, the EAV crowd, and therefore the literature is not of high quality, and standards are not maintained, therefore the basic integrity and quality of a Relational Database is lost. Which leads to the many well-documented problems.</p> <p>You should consider the proper academically derived alternative. This retaiins full Relational integrity and capability. It is called Sixth Normal Form. EAV is in fact a subset of 6NF, without the full understanding; the more commonly known rendition of 6NF.</p> <p>6NF implemented correctly is particularly fast, in that it stores columns, not rows. Therefore you can map your data (graph series, data points) in such a way, as to gain a flat high speed regardless of the vectors that you use to access the graphs. (You can eliminate duplication to a higher order than 5NF, but that is advanced use.)</p> <p>"Highly-interlinked" is not a problem at all. That is the nature of a Relational Database. The caveat here is, it must be truly Normalised, not a inlerlinked bunch of flat files.</p> <p>The automation or code generation is not a problem. Of course, you need to extend the SQL catalogue, and ensure it is table-driven, if you want quality and maintainability.</p> <p>My answers to these questions provide a full treatment of the subject. The last one is particularly long due the the context and arguments raised.<br> <a href="https://stackoverflow.com/questions/4011956/multiple-fixed-tables-vs-flexible-abstract-tables/4013207#4013207"><strong>EAV-6NF Answer One</strong></a><br> <a href="https://stackoverflow.com/questions/4049159/alternatives-to-entity-attribute-value-eav/4057531#4057531"><strong>EAV-6NF Answer Two</strong></a><br> <a href="https://stackoverflow.com/questions/4056093/what-are-the-disadvantages-of-using-a-key-value-table-over-nullable-columns-or/4076835#4076835"><strong>EAV-6NF Answer Three</strong></a> </p> <p>And this one is worthwhile as well:<br> <a href="https://stackoverflow.com/questions/4283842/database-schema-related-problem/4283979#4283979"><strong>Schema-Related Problem</strong></a></p>
3,442,897
How to create a three column table in ASP.Net Repeater
<p>I would like to be able to use the ASP.Net Repeater control to create an HTML Table that has three columns and as many rows as necc.</p> <p>For example if the Data were to look like this</p> <p>"Phil Hughes"</p> <p>"Andy Petite"</p> <p>"CC Sabathia"</p> <p>"AJ Burnett"</p> <p>"Javier Vazquez"</p> <p>I would like the resulting table to be like</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Phil Hughes&lt;/td&gt; &lt;td&gt;Andy Petite&lt;/td&gt; &lt;td&gt;CC Sabathia&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AJ Burnett&lt;/td&gt; &lt;td&gt;Javier Vazquez&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>How can I do this?</p>
3,442,975
6
0
null
2010-08-09 18:17:55.53 UTC
3
2017-06-09 12:55:26.71 UTC
2017-06-09 12:55:26.71 UTC
null
4,370,109
null
97,736
null
1
17
asp.net|html-table|repeater
77,899
<p>It's better to use a DataList control intstead as it has the interesting properties <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.repeatcolumns.aspx" rel="noreferrer">RepeatColumns</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.repeatdirection.aspx" rel="noreferrer">RepeatDirection</a>.</p>
3,287,801
Pointers to elements of std::vector and std::list
<p>I'm having a <code>std::vector</code> with elements of some class <code>ClassA</code>. Additionally I want to create an index using a <code>std::map&lt;key,ClassA*&gt;</code> which maps some key value to pointers to elements contained in the vector.</p> <p>Is there any guarantee that these pointers remain valid (and point to the same object) when elements are <em>added</em> at the end of the vector (not <em>inserted</em>). I.e, would the following code be correct:</p> <pre><code>std::vector&lt;ClassA&gt; storage; std::map&lt;int, ClassA*&gt; map; for (int i=0; i&lt;10000; ++i) { storage.push_back(ClassA()); map.insert(std::make_pair(storage.back().getKey(), &amp;(storage.back())); } // map contains only valid pointers to the 'correct' elements of storage </code></pre> <p>How is the situation, if I use <code>std::list</code> instead of <code>std::vector</code>?</p>
3,287,828
7
1
null
2010-07-20 07:23:47.847 UTC
9
2017-12-20 17:11:25.11 UTC
null
null
null
null
81,424
null
1
34
c++|stl|pointers|stdvector
24,654
<p>Vectors - No. Because the capacity of vectors never shrinks, it is guaranteed that references, pointers, and iterators remain valid even when elements are deleted or changed, provided they refer to a position before the manipulated elements. However, insertions may invalidate references, pointers, and iterators.</p> <p>Lists - Yes, inserting and deleting elements does not invalidate pointers, references, and iterators to other elements</p>
3,538,111
UINavigationBar autoresizing
<p>In my app, I got a UINavigationController. Unfortunately, when I rotate the device and the interface orientation changes, the UINavigationBar doesn't change its height. In other iPhone applications, such as the Contacts.app, the navigation bar gets slightly less tall in landscape mode. It must be built-in, because if you take the navigation sample app from the XCode menu and add interface orientation to it, it does change the navigation bar's height properly.</p> <p>How can I make the navigation bar resize like it does in all other iPhone apps I've seen?</p>
3,600,768
8
0
null
2010-08-21 15:54:48.877 UTC
9
2014-09-22 11:04:11.993 UTC
2010-08-22 04:41:45.31 UTC
null
30,461
null
282,635
null
1
12
cocoa-touch|uikit|uiview|uinavigationbar|autoresize
8,180
<p>I've done a little testing, and although I don't like the method, it's quite easy to do.</p> <p>Having looked for a private method that may have worked, I couldn't find one. All I found was:</p> <pre><code>@property BOOL forceFullHeightInLandscape; - (BOOL)isMinibar; </code></pre> <p>There is no setter for <code>-isMinibar</code>, so we can't set that. I guess that it returns a value based on its height. Also, <code>forceFullHeightInLandscape</code> was set to <code>NO</code>, however it still didn't adjust its height.</p> <p>While changing the <code>autoresizingMask</code> to include <code>UIViewAutoresizingFlexibleHeight</code>, the view <em>did</em> resize to be smaller, but now it was too small. However, <code>-isMinibar</code> suddenly returned <code>YES</code>. So that made me think of just letting the view resize itself, adjusting it to the right height.</p> <p>So there we go, a method that works, even without private API calls:</p> <pre><code>- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [self.navigationBar performSelector:@selector(sizeToFit) withObject:nil afterDelay:(0.5f * duration)]; } </code></pre> <hr> <p>One thing you'll have to deal with is that the views below the bar won't get adjusted to the smaller bar, so that there will be a gap between the bar and the views below. Easiest way to solve this is to add a container view, just like the case with a <code>UINavigationController</code>. You'd come up with something like:</p> <pre><code>- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [self performSelector:@selector(resizeViewsForNavigationBar) withObject:nil afterDelay:(0.5f * duration)]; } - (void)resizeViewsForNavigationBar { [self.navigationBar sizeToFit]; // Resize containerView accordingly. CGRect containerViewRect = self.containerView.frame; containerViewRect.origin.y = CGRectGetMaxY(self.navigationBar.frame); containerViewRect.size.height = CGRectGetMaxY(self.view.frame) - containerViewRect.origin.y; self.containerView.frame = containerViewRect; } </code></pre>
3,288,257
How to convert MM/DD/YYYY to YYYY-MM-DD?
<p>I have a jquery calendar that sets the input value to MM/DD/YYYY</p> <p>How would I convert it so that my database column (date) can accept it correctly?</p> <p>EDIT</p> <p>Gordon was right - his link pointed me to this answer</p> <pre><code>$mysql_date = date('Y-m-d H:i:s', strtotime($user_date)); </code></pre>
3,288,379
8
4
null
2010-07-20 08:38:33.74 UTC
7
2018-03-01 12:21:55.137 UTC
2010-07-20 08:56:48.98 UTC
null
253,348
null
253,348
null
1
24
php|jquery|date
68,181
<pre><code>$date = "07/12/2010"; $your_date = date("Y-m-d", strtotime($date)); </code></pre> <p>I hope my answer is useful :)</p>
3,624,731
What is Func, how and when is it used
<p>What is <code>Func&lt;&gt;</code> and what is it used for?</p>
3,624,745
9
2
null
2010-09-02 07:45:44.54 UTC
44
2022-01-10 18:41:59.653 UTC
2015-07-16 04:30:44.073 UTC
null
591,656
null
281,180
null
1
130
c#|.net|delegates
140,292
<p><code>Func&lt;T&gt;</code> is a predefined delegate type for a method that returns some value of the type <code>T</code>.</p> <p>In other words, you can use this type to reference a method that returns some value of <code>T</code>. E.g.</p> <pre><code>public static string GetMessage() { return "Hello world"; } </code></pre> <p>may be referenced like this</p> <pre><code>Func&lt;string&gt; f = GetMessage; </code></pre>
3,975,499
Convert SVG to image (JPEG, PNG, etc.) in the browser
<p>I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.</p>
3,976,034
12
6
null
2010-10-20 07:13:48.733 UTC
168
2022-08-24 04:53:36.447 UTC
2011-11-17 02:00:44.327 UTC
null
405,017
null
441,207
null
1
362
javascript|svg
417,356
<p>Here is how you can do it through JavaScript:</p> <ol> <li>Use the canvg JavaScript library to render the SVG image using Canvas: <a href="https://github.com/gabelerner/canvg" rel="noreferrer">https://github.com/gabelerner/canvg</a></li> <li>Capture a data URI encoded as a JPG (or PNG) from the Canvas, according to these instructions: <a href="https://stackoverflow.com/questions/923885/capture-html-canvas-as-gif-jpg-png-pdf/3514404#3514404">Capture HTML Canvas as gif/jpg/png/pdf?</a></li> </ol>
7,904,213
MSVCP100D.dll missing
<p>When I try to debug my C++ application I get the error </p> <blockquote> <p>The program can't start because MSVCP100D.dll is missing from your computer. Try reinstalling the program to fix this problem.</p> </blockquote> <p>I found someone with a similar problem here: <a href="https://stackoverflow.com/questions/5014712/remote-debugging-c-on-the-windows-server-2008-platform-with-vs2010-msvcp100d">Remote debugging C++ on the Windows Server 2008 platform with VS2010; MSVCP100D.dll missing</a> however the solution given there doesn't seem to show up when I go to the solution properties.</p> <p>Would reinstalling Visual Studio fix this problem? </p>
7,911,469
5
6
null
2011-10-26 14:33:55.88 UTC
1
2016-04-07 02:31:20.327 UTC
2017-05-23 12:32:56.293 UTC
null
-1
null
412,490
null
1
5
c++|visual-studio-2010|visual-c++
40,032
<p>Reinstalling Visual Studio fixed the problem.</p>
4,760,428
How can I make Vim's `J` and `gq` commands use one space after a period?
<p>When I use Vim's <code>J</code> command, most lines are joined with a single space for padding. But after a period Vim always uses two spaces. Take the following example:</p> <pre><code>This ends with a comma, but this ends with a period. Join with 'J' and what do you get? </code></pre> <p>For me, the result is:</p> <pre><code>This ends with a comma, but this ends with a period. Join with 'J' and what do you get? </code></pre> <p>One space after the comma, two after the period. Same story if you reformat the paragraph with the <code>gq</code> command.</p> <p>Is there a setting that I can modify to make Vim use only one space after the period?</p>
4,760,477
3
5
null
2011-01-21 15:19:58.12 UTC
12
2011-01-21 16:06:54.857 UTC
null
null
null
null
128,850
null
1
112
vim|formatting
7,416
<pre><code>:help joinspaces 'joinspaces' 'js' boolean (default on) global {not in Vi} Insert two spaces after a '.', '?' and '!' with a join command. When 'cpoptions' includes the 'j' flag, only do this after a '.'. Otherwise only one space is inserted. NOTE: This option is set when 'compatible' is set. </code></pre> <p>So, you would do a </p> <pre><code>:set nojoinspaces </code></pre> <p>to obtain what you desire.</p> <p>Alternatively, you can toggle the setting with </p> <pre><code>:set joinspaces! </code></pre>
4,134,799
Codeigniter Active record: greater than statement
<p>I'm trying to convert a "greater than" where statement to CI's Active Record syntax. When I use this snippet</p> <pre><code> $this-&gt;db-&gt;join('product_stocks', "product_stocks.size_id_fk = product_attributes.id", "left"); $this-&gt;db-&gt;where('product_stocks.stock_level', '&gt; 1'); $result = $this-&gt;db-&gt;get('product_attributes')-&gt;result_array(); </code></pre> <p>Then print $this->db->last_query(); shows <code>WHERE</code>product_stocks<code>.</code>stock_level<code>= '&gt; 1'</code> which is of course not correct. Can this be done?</p>
4,134,838
4
0
null
2010-11-09 14:32:51.333 UTC
1
2014-07-14 18:06:51.397 UTC
2010-11-09 15:08:44.917 UTC
null
492,901
null
149,664
null
1
18
php|activerecord|codeigniter
58,773
<p>I think this should do the trick:</p> <pre><code>$this-&gt;db-&gt;where('product_stocks.stock_level &gt;', '1'); //moved the &gt; </code></pre>
4,839,537
Functions vs methods in Scala
<p>I am watching <a href="https://www.youtube.com/watch?v=aAtPi23nLcw" rel="noreferrer">Runar Bjarnason present Functional Programming for Beginners</a>, and at 14:45 he defines a method:</p> <pre><code>def isDivisibleBy(k: Int): Int =&gt; Boolean = i =&gt; i % k == 0 </code></pre> <p>and a function:</p> <pre><code>val isEven = isDivisibleBy(2) </code></pre> <p>What are the pros and cons of defining <code>isEven</code> as a function rather than a method?</p> <p>I have read <a href="http://jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html" rel="noreferrer">Scala Functions vs Methods</a> as well as <a href="https://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala">Difference between method and function in Scala</a>, and I understand the semantic differences, but I wonder if there's some deeper reason in this case why a function might or might not be preferable to using a method:</p> <pre><code>def isEven = isDivisibleBy(2) </code></pre>
4,839,714
4
1
null
2011-01-29 21:24:42.72 UTC
30
2021-10-30 18:44:06.33 UTC
2017-05-23 12:10:09.08 UTC
null
-1
null
406,984
null
1
57
scala
26,564
<p>Under the hood, there are other differences between functions and methods. Generally, a plain method generated less overhead than a function (which technically is an object with an <code>apply</code> method).</p> <p>However, if you try not to care about those differences and think of <code>def</code>, <code>val</code> and <code>var</code> as <em>fields</em> with different semantics, then it’s simply that <code>def</code> evaluates every time it gets called while <code>val</code> evaluates only once.</p> <p>So, a <code>val isEven = isDivisibleBy(2)</code> should call <code>isDivisibleBy(2)</code> during its definition and assign the result of <code>isDivisibleBy(2)</code>. E.g. it replaces the <code>k</code> in</p> <pre><code>def isDivisibleBy(k: Int): Int =&gt; Boolean = i =&gt; i % k == 0 </code></pre> <p>with <code>2</code> and assigns the result of the final expression (in this case there is only one expression):</p> <pre><code>val isEven: Int =&gt; Boolean = i =&gt; i % 2 == 0 </code></pre> <p><code>def isEven</code> on the other hand does no such evaluation and results in a call to isDivisibleBy(2) every time.</p> <p>That means, later, when you execute the code, <code>isEven(11)</code> generates in case of a <code>val</code></p> <pre><code>11 % 2 == 0 </code></pre> <p>and in case of a <code>def</code>, you’ll have</p> <pre><code>isDivisibleBy(2)(11) </code></pre> <p>and only after evaluating <code>isDivisibleBy</code> you’ll get the result.</p> <p>You can add some debug code to <code>isDivisibleBy</code> to see the difference:</p> <pre><code>def isDivisibleBy(k: Int): Int =&gt; Boolean = { println("evaluating isDivisibleBy") i =&gt; i % k == 0 } </code></pre>
4,307,549
ServerSocket accept() method
<p>Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order? </p> <pre><code>ServerSocket sSocket = new ServerSocket(5050); Socket socket = sSocket.accept(); </code></pre> <p><img src="https://i.stack.imgur.com/WfeDq.png" alt="From the book"></p>
4,308,243
5
8
null
2010-11-29 20:03:28.093 UTC
9
2019-06-29 10:10:13.51 UTC
2010-11-29 20:56:21.88 UTC
null
397,991
null
397,991
null
1
13
java
51,569
<p>The diagram is incorrect (and is listed in the <a href="https://oreilly.com/catalog/errataunconfirmed.csp?isbn=9780596009205" rel="nofollow noreferrer">unconfirmed errata</a> on the O'Reilly site).</p> <p>The <em>client</em> chooses <em>its</em> port at random (you don't need to do anything special in Java) and connects to the server on whichever port you specified. Using the <code>netstat</code> commandline tool you can see this.</p> <p>First, just the listening server socket with no clients:</p> <pre> simon@lucifer:~$ netstat -n -a Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) ... tcp46 0 0 *.5050 *.* LISTEN ... </pre> <p>(there are lots of other entries, I've just removed the unrelated ones)</p> <p>Now with one client connecting from localhost (127.0.0.1):</p> <pre> simon@lucifer:~$ netstat -n -a Active Internet connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) ... tcp4 0 0 127.0.0.1.64895 127.0.0.1.5050 ESTABLISHED &lt;- 1 tcp4 0 0 127.0.0.1.5050 127.0.0.1.64895 ESTABLISHED &lt;- 2 tcp46 0 0 *.5050 *.* LISTEN &lt;- 3 ... </pre> <p>Since the client is connecting from the same machine, we see two established connections - one from client to server (1), the other from server to client (2). They have opposite local and foreign addresses (since they're talking to each other) and you can see the server is still using port 5050 while the original server socket (3) continues to listen on the same port.</p> <p>(this output is from a Mac, but Windows/Linux also have <code>netstat</code> giving similar output)</p>
4,484,246
Encrypt and Decrypt text with RSA in PHP
<p>Is there any class for PHP 5.3 that provides RSA encryption/decryption without padding?</p> <p>I've got private and public key, p,q, and modulus.</p>
4,534,385
6
0
null
2010-12-19 17:43:06.61 UTC
26
2020-02-27 13:06:46.297 UTC
2020-02-27 13:06:46.297 UTC
null
225,647
null
451,276
null
1
47
php|rsa
156,213
<p>You can use <a href="http://phpseclib.sourceforge.net/" rel="noreferrer">phpseclib, a pure PHP RSA implementation</a>:</p> <pre><code>&lt;?php include('Crypt/RSA.php'); $privatekey = file_get_contents('private.key'); $rsa = new Crypt_RSA(); $rsa-&gt;loadKey($privatekey); $plaintext = new Math_BigInteger('aaaaaa'); echo $rsa-&gt;_exponentiate($plaintext)-&gt;toBytes(); ?&gt; </code></pre>
4,623,931
Get underlying NSData from UIImage
<p>I can create <code>UIImage</code> from <code>NSData</code> using <code>[UIImage imageWithData:]</code> or <code>[UIImage initWithData:]</code> methods. </p> <p>I wonder if I can get the <code>NSData</code> back from an existing <code>UIImage</code>? Something on the line of <code>NSData *myData = [myImage getData];</code></p>
4,623,990
7
0
null
2011-01-07 09:01:55.65 UTC
19
2021-08-17 00:30:06.49 UTC
2019-07-01 20:16:36.29 UTC
null
819,340
null
433,570
null
1
109
cocoa-touch|uiimage|nsdata
66,739
<pre><code>NSData *imageData = UIImageJPEGRepresentation(image, 0.7); // 0.7 is JPG quality </code></pre> <p>or</p> <pre><code>NSData *imageData = UIImagePNGRepresentation(image); </code></pre> <p>Depending if you want your data in PNG format or JPG format.</p>
4,381,296
Android: wait on user input from dialog?
<p>I would like to implement a method that displays a dialog, waits until the dialog is dismissed, and then returns a result depending on the dialog contents. Is this possible?</p> <pre><code>public String getUserInput() { //do something to show dialog String input = //get input from dialog return input; } </code></pre> <p>I am actually trying to implement an interface which has method "public String getUserInput()", where the returned String must be retrieved via dialog. This is easily done in java, seems impossible in android?</p> <p>EDIT: Posting some sample code as requested in comment</p> <p><code>getInput()</code> must be called from a background thread (I call it from an AsynchTask). getInput() displays a dialog and calls wait. When the ok button is pressed on the dialog, the dialog sets the user input in a member variable and calls notify. When notify is called, getInput() continues and returns the member variable.</p> <pre><code>String m_Input; public synchronized String getInput() { runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder alert = new AlertDialog.Builder(context); //customize alert dialog to allow desired input alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { m_Input = alert.getCustomInput(); notify(); } }); alert.show(); } }); try { wait(); } catch (InterruptedException e) { } return m_Input; } </code></pre>
4,381,971
8
5
null
2010-12-07 20:33:55.063 UTC
15
2020-02-04 07:41:05.937 UTC
2013-04-19 14:30:45.983 UTC
null
281,545
null
426,493
null
1
44
android|modal-dialog
91,050
<p>Thanks for all the feedback, I was able to solve this using a background thread along with a wait() and notify(). I recognize this isn't the greatest idea for the given paradigm, but it was necessary to conform to a library that I am working with.</p>