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
11,050,269
Fixed width buttons with Bootstrap
<p>Does Bootstrap support fixed width buttons? Currently if I have 2 buttons, "Save" and "Download", the button size changes based on content.</p> <p>Also what is the right way of extending Bootstrap?</p>
12,527,816
13
4
null
2012-06-15 12:02:22.483 UTC
44
2021-10-20 22:22:38.563 UTC
2015-05-27 09:25:18.69 UTC
null
224,368
null
406,659
null
1
212
css|twitter-bootstrap
367,095
<p>You can also use the <code>.btn-block</code> class on the button, so that it expands to the parent's width.</p> <p>If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;span2&quot;&gt; &lt;p&gt;&lt;button class=&quot;btn btn-primary btn-block&quot;&gt;Save&lt;/button&gt;&lt;/p&gt; &lt;p&gt;&lt;button class=&quot;btn btn-success btn-block&quot;&gt;Download&lt;/button&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;div class="span2"&gt; &lt;p&gt;&lt;button class="btn btn-primary btn-block"&gt;Save&lt;/button&gt;&lt;/p&gt; &lt;p&gt;&lt;button class="btn btn-success btn-block"&gt;Download&lt;/button&gt;&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
16,725,848
How to split text into words?
<p>How to split text into words?</p> <p>Example text:</p> <blockquote> <p>'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'</p> </blockquote> <p>The words in that line are:</p> <ol> <li>Oh</li> <li>you</li> <li>can't</li> <li>help</li> <li>that</li> <li>said</li> <li>the</li> <li>Cat</li> <li>we're</li> <li>all</li> <li>mad</li> <li>here</li> <li>I'm</li> <li>mad</li> <li>You're</li> <li>mad</li> </ol>
16,734,675
7
3
null
2013-05-24 00:03:47.06 UTC
13
2021-07-26 06:24:15.03 UTC
2015-04-29 09:01:28.997 UTC
null
284,795
null
284,795
null
1
27
c#|.net
52,406
<p>Split text on whitespace, then trim punctuation.</p> <pre><code>var text = "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"; var punctuation = text.Where(Char.IsPunctuation).Distinct().ToArray(); var words = text.Split().Select(x =&gt; x.Trim(punctuation)); </code></pre> <p>Agrees exactly with example.</p>
62,923,230
Disable Chrome v 84 Issues Tab in JS console
<p>Is there a way to toggle on/off the &quot;Issues&quot; tab in the Chrome dev tools console? It's a noble idea but I don't need it all the time. (Sorry I'm not allowed to post pictures inline but the links are below)</p> <p><a href="https://i.stack.imgur.com/6P7jq.png" rel="noreferrer">The tab appears regardless of logging level</a></p> <p><a href="https://i.stack.imgur.com/spAnY.png" rel="noreferrer">The only way I know to hide it is to click &quot;Go to Issues&quot;</a></p> <p>Clicking that button opens the lower console, and then I have to close the Issues tab every single time. I'm only working on a handful of pages and most of the issues are warnings that are out of my control (Same-Site cookies from 3rd parties etc.).</p>
63,013,794
1
7
null
2020-07-15 20:25:44.07 UTC
1
2020-07-21 11:43:29.607 UTC
null
null
null
null
13,938,042
null
1
28
javascript|google-chrome|google-chrome-devtools
2,850
<p>Good news. Chrome 85 will show it less frequently. <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1068116#c25" rel="noreferrer">https://bugs.chromium.org/p/chromium/issues/detail?id=1068116#c25</a></p>
26,788,464
How to change color of the back arrow in the new material theme?
<p>I've updated my SDK to API 21 and now the back/up icon is a black arrow pointing to the left.</p> <p><img src="https://i.stack.imgur.com/FUEND.jpg" alt="Black back arrow" /></p> <p>I would like it to be grey. How can I do that?</p> <p>In the Play Store, for example, the arrow is white.</p> <p>I've done this to set some styles. I have used <code>@drawable/abc_ic_ab_back_mtrl_am_alpha</code> for <code>homeAsUpIndicator</code>. That drawable is transparent (only alpha) but the arrow is displayed in black. I wonder if I can set the color like I do in the <code>DrawerArrowStyle</code>. Or if the only solution is to create my <code>@drawable/grey_arrow</code> and use it for <code>homeAsUpIndicator</code>.</p> <pre class="lang-xml prettyprint-override"><code>&lt;!-- Base application theme --&gt; &lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light&quot;&gt; &lt;item name=&quot;android:actionBarStyle&quot; tools:ignore=&quot;NewApi&quot;&gt;@style/MyActionBar&lt;/item&gt; &lt;item name=&quot;actionBarStyle&quot;&gt;@style/MyActionBar&lt;/item&gt; &lt;item name=&quot;drawerArrowStyle&quot;&gt;@style/DrawerArrowStyle&lt;/item&gt; &lt;item name=&quot;homeAsUpIndicator&quot;&gt;@drawable/abc_ic_ab_back_mtrl_am_alpha&lt;/item&gt; &lt;item name=&quot;android:homeAsUpIndicator&quot; tools:ignore=&quot;NewApi&quot;&gt;@drawable/abc_ic_ab_back_mtrl_am_alpha&lt;/item&gt; &lt;/style&gt; &lt;!-- ActionBar style --&gt; &lt;style name=&quot;MyActionBar&quot; parent=&quot;@style/Widget.AppCompat.Light.ActionBar.Solid&quot;&gt; &lt;item name=&quot;android:background&quot;&gt;@color/actionbar_background&lt;/item&gt; &lt;!-- Support library compatibility --&gt; &lt;item name=&quot;background&quot;&gt;@color/actionbar_background&lt;/item&gt; &lt;/style&gt; &lt;!-- Style for the navigation drawer icon --&gt; &lt;style name=&quot;DrawerArrowStyle&quot; parent=&quot;Widget.AppCompat.DrawerArrowToggle&quot;&gt; &lt;item name=&quot;spinBars&quot;&gt;true&lt;/item&gt; &lt;item name=&quot;color&quot;&gt;@color/actionbar_text&lt;/item&gt; &lt;/style&gt; </code></pre> <p>My solution so far has been to take the <code>@drawable/abc_ic_ab_back_mtrl_am_alpha</code>, which seems to be white, and paint it in the color I desire using a photo editor. It works, although I would prefer to use <code>@color/actionbar_text</code> like in <code>DrawerArrowStyle</code>.</p>
26,837,072
25
4
null
2014-11-06 20:06:12.907 UTC
69
2022-06-29 14:31:09.35 UTC
2022-06-29 14:31:09.35 UTC
null
2,911,458
null
1,121,497
null
1
210
java|android|user-interface|colors|android-styles
183,029
<p>You can achieve it through code. Obtain the back arrow drawable, modify its color with a filter, and set it as back button.</p> <pre><code>final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha); upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP); getSupportActionBar().setHomeAsUpIndicator(upArrow); </code></pre> <p><strong>Revision 1:</strong></p> <p>Starting from API 23 (Marshmallow) the drawable resource <code>abc_ic_ab_back_mtrl_am_alpha</code> is changed to <code>abc_ic_ab_back_material</code>.</p> <p>EDIT:</p> <p>You can use this code to achieve the results you want:</p> <pre><code>toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.blue_gray_15), PorterDuff.Mode.SRC_ATOP); </code></pre>
10,043,376
Java X509 Certificate parsing and validating
<p>I'm trying to process X509 certificates in several steps and running into a couple of problems. I'm new to JCE so I not completely up to date on everything yet.</p> <p>We want to be able to parse several different X509 certificates based on different encodings (PEM, DER and PCKS7). I've exported the same certificate from <a href="https://belgium.be">https://belgium.be</a> in PEM and PCKS7 format using FireFox (certificate including chain). I've left couple lines out that are not needed for the questions</p> <pre><code>public List&lt;X509Certificate&gt; parse(FileInputStream fis) { /* * Generate a X509 Certificate initialized with the data read from the inputstream. * NOTE: Generation fails when using BufferedInputStream on PKCS7 certificates. */ List&lt;X509Certificate&gt; certificates = null; log.debug("Parsing new certificate."); certificates = (List&lt;X509Certificate&gt;) cf.generateCertificates(fis); return certificates; } </code></pre> <p>This code is working fine aslong as I work with a FileInputStream instead of a BufferedInputStream for PCKS7, which is quite strange already I think? But I can live with it.</p> <p>The next step is to validate these certificate chains. 1) Check if all certificates have a valid date (easy) 2) Validate certificate chain using OCSP (and fallback to CRL if no OCSP URL is found in the certificate). This is where I'm not completely sure how to handle this.</p> <p>I'm using the Sun JCE, but it seems there is not that much documentation available (in examples) for this?</p> <p>I first made a simple implementation that only checks the chain without going through the OCSP/CRL checks.</p> <pre><code>private Boolean validateChain(List&lt;X509Certificate&gt; certificates) { PKIXParameters params; CertPath certPath; CertPathValidator certPathValidator; Boolean valid = Boolean.FALSE; params = new PKIXParameters(keyStore); params.setRevocationEnabled(false); certPath = cf.generateCertPath(certificates); certPathValidator = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) certPathValidator.validate(certPath, params); if(null != result) { valid = Boolean.TRUE; } return valid; } </code></pre> <p>This is working fine for my PEM certificate, but not for the PCKS7 certificate (same certifcate, only exported in other format). <strong>java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors.</strong></p> <p>The only difference I'm able to see is that the order in which the CertPath is formed is not the same? I was not able to figure out what was going wrong so I left this for now and kept on going with the PEM certificate, but lets call this QUESTION 1 ;)</p> <p>What I wanted to implement afterwards was the OCSP checking. Apparently if I enable OCSP using: <strong>Security.setProperty("ocsp.enable", "true");</strong> and set <strong>params.setRevocationEnabled(true);</strong> it should be able to find the OCSP URL on its own, but that does not seem to be the case. What is the standard implementation supposed to do (QUESTION 2)? <strong>java.security.cert.CertPathValidatorException: Must specify the location of an OCSP Responder</strong></p> <p>Going past this, I found a way to retrieve the OCSP url from the certificate using AuthorityInfoAccessExtension and such.</p> <p>But after setting the OCSP url manually in the ocsp.url property, I'm getting an <strong>java.security.cert.CertPathValidatorException: OCSP response error: UNAUTHORIZED</strong></p> <p>It seems like I'm missing a lot of necessary steps while alot of online references say setting the <strong>ocsp.enable</strong> property should be all you need to do? </p> <p>Perhaps any of you whizkids cant guide me through the process a little bit? Show me where I'm completely wrong :)</p> <p>The next step would be implementing CRL checks if no OCSP was found, if anyone could point out any example or show me some documentation on this it would also be much appreciated!</p> <p>Thanks!</p> <p><strong>EDIT:</strong> Since it's not picking up the properties on its own, I've been trying to set all the properties myself using the following:</p> <pre><code> // Activate OCSP Security.setProperty("ocsp.enable", "true"); // Activate CRLDP -- no idea what this is Security.setProperty("com.sun.security.enableCRLDP", "true"); X509Certificate target = (X509Certificate) certPath.getCertificates().get(0); Security.setProperty("ocsp.responderURL","http://ocsp.pki.belgium.be/"); Security.setProperty("ocsp.responderCertIssuerName", target.getIssuerX500Principal().getName()); Security.setProperty("ocsp.responderCertSubjectName", target.getSubjectX500Principal().getName()); Security.setProperty("ocsp.responderCertSerialNumber", target.getSerialNumber().toString(16)); </code></pre> <p>Which gives an exception: java.security.cert.CertPathValidatorException: Cannot find the responder's certificate (set using the OCSP security properties).</p>
10,068,006
1
3
null
2012-04-06 12:17:34.983 UTC
13
2014-08-19 19:42:50.727 UTC
2012-04-06 18:04:16.25 UTC
null
492,723
null
492,723
null
1
14
java|validation|x509certificate|pki|jce
18,752
<p>For future reference I'll post the answer to my own question (partly atleast)</p> <p>OCSP and CRL checks are implemented in the standard Java implementation already and there is no need for custom code or other providers (BC, ..). They are disabled by default.</p> <p>To enable this, you have to atleast set two parameters:</p> <pre><code>(PKIXParameters or PKIXParameterBuilder) params.setRevocationEnabled(true); Security.setProperty("ocsp.enable", "true"); </code></pre> <p>This will activate OCSP checking when you are trying to validate the certificate path (PKIXCertPathValidatorResult.validate()).</p> <p>When you want to add the fallback check for CRL if no OCSP is available, add an aditional property:</p> <pre><code>System.setProperty("com.sun.security.enableCRLDP", "true"); </code></pre> <p>A lot of my problems are happening due to the fact that I have to support different certificate formats (PKCS7, PEM). My implementation works fine for PEM, but since PKCS7 does NOT save ordering of the certificates in the chain it is a bit harder (<a href="http://bugs.sun.com/view_bug.do?bug_id=6238093" rel="noreferrer">http://bugs.sun.com/view_bug.do?bug_id=6238093</a>)</p> <pre><code>X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(certificates.get(0)); // Here's the issue for PKCS7 certificates since they are not ordered, // but I havent figured out how I can see what the target certificate // (lowest level) is in the incoming certificates.. PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, targetConstraints); </code></pre> <p>Hope this will be useful remarks for other people as well, perhaps someone can shed a light on how to find the target certificate in an unordered PKCS7 list?</p>
9,736,833
new int[size] vs std::vector
<p>To allocate dynamic memory, I have been using vectors all this time in C++. But recently, while reading some source code, I found the use of "new int[size]" and on some research, found that it too allocates dynamic memory.</p> <p>Can anyone give me advice as to which is better? I am looking from an algorithmic and ICPC point of view?</p>
9,741,542
7
5
null
2012-03-16 12:00:44.08 UTC
18
2022-01-20 14:22:48.017 UTC
2012-03-16 12:09:31.713 UTC
user195488
null
null
1,236,990
null
1
17
c++|memory|dynamic|vector
15,725
<p>Always <em>prefer</em> the standard containers. They have well-defined copying semantics, are exception safe, and release properly.</p> <p>When you allocate manually, you must guarantee that the release code is executed, and as members, you must write correct copy assignment and copy constructor which does the right thing without leaking in case of exception.</p> <p>Manual:</p> <pre><code>int *i = 0, *y = 0; try { i = new int [64]; y = new int [64]; } catch (...) { delete [] y; delete [] i; } </code></pre> <p>If we want our variables to have only the scope they really need, it gets smelly:</p> <pre><code>int *i = 0, *y = 0; try { i = new int [64]; y = new int [64]; // code that uses i and y int *p; try { p = new int [64]; // code that uses p, i, y } catch(...) {} delete [] p; } catch (...) {} delete [] y; delete [] i; </code></pre> <p>Or just:</p> <pre><code>std::vector&lt;int&gt; i(64), y(64); { std::vector&lt;int&gt; p(64); } </code></pre> <p>It is a horror to implement that for a class that has copy semantics. Copying may throw, allocation may throw, and we want transaction semantics, ideally. An example would burst this answer tho.</p> <hr /> <p>Ok here.</p> <h1>Copyable class - Manual resource management vs containers</h1> <p>We have this innocent looking class. As it turns out, it is pretty evil. I feel reminded of American McGee's Alice:</p> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} private: Bar *b_; Frob *f_; }; </code></pre> <p>Leaks. Most beginner C++ programmers recognize that there's missing deletes. Add them:</p> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} ~Foo() { delete f_; delete b_; } private: Bar *b_; Frob *f_; }; </code></pre> <p>Undefined behavior. Intermediate C++ programmers recognize that the wrong delete-operator is used. Fix this:</p> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} ~Foo() { delete [] f_; delete [] b_; } private: Bar *b_; Frob *f_; }; </code></pre> <p>Bad design, leaks and double deletes lurk there if the class is copied. The copying itself is fine, the compiler cleanly copies the pointers for us. But the compiler won't emit code to create copies of the <em>arrays</em>.</p> <p>Slightly more experienced C++ programmers recognize that the Rule of Three was not respected, which says that if you have explicitly written any of destructor, copy assignment or copy constructor, you probably also need to write out the others, or make them private without implementation:</p> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} ~Foo() { delete [] f_; delete [] b_; } Foo (Foo const &amp;f) : b_(new Bar[64]), f_(new Frob[64]) { *this = f; } Foo&amp; operator= (Foo const&amp; rhs) { std::copy (rhs.b_, rhs.b_+64, b_); std::copy (rhs.f_, rhs.f_+64, f_); return *this; } private: Bar *b_; Frob *f_; }; </code></pre> <p>Correct. ... Provided you can guarantee to never run out of memory and that neither Bar, nor Frob can fail on copying. Fun starts in next section.</p> <h2>The wonderland of writing exception safe code.</h2> <h2>Construction</h2> <pre><code>Foo() : b_(new Bar[64]), f_(new Frob[64]) {} </code></pre> <ul> <li>Q: What happens if the initialization of <code>f_</code> fails?</li> <li>A: All <code>Frobs</code> that have been constructed are destroyed. Imagine 20 <code>Frob</code> were constructed, the 21st will fail. Than, in LIFO order, the first 20 <code>Frob</code> will be correctly destroyed.</li> </ul> <p>That's it. Means: You have 64 zombie <code>Bars</code> now. The <code>Foos</code> object itself never comes to life, its destructor will therefore not be called.</p> <p>How to make this exception safe?</p> <p>A constructor should always succeed <em>completely</em> or fail <em>completely</em>. It shouldn't be half-live or half-dead. Solution:</p> <pre><code>Foo() : b_(0), f_(0) { try { b_ = new Bar[64]; f_ = new Frob[64]; } catch (std::exception &amp;e) { delete [] f_; // Note: it is safe to delete null-pointers -&gt; nothing happens delete [] b_; throw; // don't forget to abort this object, do not let it come to life } } </code></pre> <h2>Copying</h2> <p>Remember our definitions for copying:</p> <pre><code>Foo (Foo const &amp;f) : b_(new Bar[64]), f_(new Frob[64]) { *this = f; } Foo&amp; operator= (Foo const&amp; rhs) { std::copy (rhs.b_, rhs.b_+64, b_); std::copy (rhs.f_, rhs.f_+64, f_); return *this; } </code></pre> <ul> <li>Q: What happens if any copy fails? Maybe <code>Bar</code> will have to copy heavy resources under the hood. It can fail, it will.</li> <li>A: At the time-point of exception, all objects copied so far will remain like that.</li> </ul> <p>This means that our <code>Foo</code> is now in inconsistent and unpredictable state. To give it transaction semantics, we need to build up the new state fully or not at all, and then use operations that cannot throw to implant the new state in our <code>Foo</code>. Finally, we need to clean up the interim state.</p> <p>The solution is to use the copy and swap idiom (<a href="http://gotw.ca/gotw/059.htm" rel="nofollow noreferrer">http://gotw.ca/gotw/059.htm</a>).</p> <p>First, we refine our copy constructor:</p> <pre><code>Foo (Foo const &amp;f) : f_(0), b_(0) { try { b_ = new Bar[64]; f_ = new Frob[64]; std::copy (rhs.b_, rhs.b_+64, b_); // if this throws, all commited copies will be thrown away std::copy (rhs.f_, rhs.f_+64, f_); } catch (std::exception &amp;e) { delete [] f_; // Note: it is safe to delete null-pointers -&gt; nothing happens delete [] b_; throw; // don't forget to abort this object, do not let it come to life } } </code></pre> <p>Then, we define a non-throwing swap function</p> <pre><code>class Foo { public: friend void swap (Foo &amp;, Foo &amp;); }; void swap (Foo &amp;lhs, Foo &amp;rhs) { std::swap (lhs.f_, rhs.f_); std::swap (lhs.b_, rhs.b_); } </code></pre> <p>Now we can use our new exception safe copy-constructor and exception-safe swap-function to write an exception-safe copy-assignment-operator:</p> <pre><code>Foo&amp; operator= (Foo const &amp;rhs) { Foo tmp (rhs); // if this throws, everything is released and exception is propagated swap (tmp, *this); // cannot throw return *this; // cannot throw } // Foo::~Foo() is executed </code></pre> <p>What happened? At first, we build up new storage and copy rhs' into it. This may throw, but if it does, our state is not altered and the object remains valid.</p> <p>Then, we exchange our guts with the temporary's guts. The temporary gets what is not needed anymore, and releases that stuff at the end of scope. We effectively used <em>tmp</em> as a garbage can, and properly choose RAII as the garbage collection service.</p> <p>You may want to look at <a href="http://gotw.ca/gotw/059.htm" rel="nofollow noreferrer">http://gotw.ca/gotw/059.htm</a> or read <code>Exceptional C++</code> for more details on this technique and on writing exception safe code.</p> <h2>Putting it together</h2> <p>Summary of what can't throw or is not allowed to throw:</p> <ul> <li><strong>copying primitive types</strong> never throws</li> <li><strong>destructors are not allowed to throw</strong> (because otherwise, exception safe code would not be possible at all)</li> <li><strong>swap</strong> functions shall not throw** (and C++ programmers as well as the whole standard library expect it to not throw)</li> </ul> <p>And here is finally our carefully crafted, exception safe, corrected version of Foo:</p> <pre><code>class Foo { public: Foo() : b_(0), f_(0) { try { b_ = new Bar[64]; f_ = new Frob[64]; } catch (std::exception &amp;e) { delete [] f_; // Note: it is safe to delete null-pointers -&gt; nothing happens delete [] b_; throw; // don't forget to abort this object, do not let it come to life } } Foo (Foo const &amp;f) : f_(0), b_(0) { try { b_ = new Bar[64]; f_ = new Frob[64]; std::copy (rhs.b_, rhs.b_+64, b_); std::copy (rhs.f_, rhs.f_+64, f_); } catch (std::exception &amp;e) { delete [] f_; delete [] b_; throw; } } ~Foo() { delete [] f_; delete [] b_; } Foo&amp; operator= (Foo const &amp;rhs) { Foo tmp (rhs); // if this throws, everything is released and exception is propagated swap (tmp, *this); // cannot throw return *this; // cannot throw } // Foo::~Foo() is executed friend void swap (Foo &amp;, Foo &amp;); private: Bar *b_; Frob *f_; }; void swap (Foo &amp;lhs, Foo &amp;rhs) { std::swap (lhs.f_, rhs.f_); std::swap (lhs.b_, rhs.b_); } </code></pre> <p>Compare that to our initial, innocent looking code that is evil to the bones:</p> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} private: Bar *b_; Frob *f_; }; </code></pre> <p>You better don't add more variables to it. Sooner or later, you will forget to add proper code at some place, and your whole class becomes ill.</p> <h2>Or make it non-copyable.</h2> <pre><code>class Foo { public: Foo() : b_(new Bar[64]), f_(new Frob[64]) {} Foo (Foo const &amp;) = delete; Foo&amp; operator= (Foo const &amp;) = delete; private: Bar *b_; Frob *f_; }; </code></pre> <p>For some classes this makes sense (streams, for an instance; to share streams, be explicit with std::shared_ptr), but for many, it does not.</p> <h2>The real solution.</h2> <pre><code>class Foo { public: Foo() : b_(64), f_(64) {} private: std::vector&lt;Bar&gt; b_; std::vector&lt;Frob&gt; f_; }; </code></pre> <p>This class has clean copying semantics, is exception safe (remember: being exception safe does not mean to not throw, but rather to not leak and possibly have transaction semantics), and does not leak.</p>
10,096,577
How to save passwords in PL/SQL Developer?
<p>I've put my database info into Tnsnames.ora, and now each time I start PL/SQL Developer I get a dropdown list of my databases, but I have to type in the password every time.</p> <p>There is an option under Tools>Preferences to store passwords for multiple connections, but it doesn't seem to have any effect. The password field is always blank when I start the application.</p> <p>How can I get this to remember the password?</p> <p><em>I'm using PL/SQL Developer 9.0.2.1621</em></p>
10,120,846
4
0
null
2012-04-10 21:15:24.63 UTC
6
2020-06-25 11:43:32.08 UTC
null
null
null
null
318,519
null
1
20
plsqldeveloper
39,885
<p>After you login for the first time, password is saved. Next time, no need to type, click on the [...] next to the UserName and select database, it will autologon. Hope it helps!</p>
9,780,443
How to select all children of an element with javascript and change CSS property?
<p>I am working on a project that has a div with 32 children. I need to create a dropdown menu that will change the background of each div and the parent. For the other parts of the project that don't have children, I have been using the following code:</p> <pre><code>function changediv(color) { document.getElementById('div1').style.background = color; } </code></pre> <p>HTML:</p> <pre><code>&lt;select&gt; &lt;option onClick="changediv('#555');"&gt;Hex&lt;/option&gt; &lt;option onClick="changediv('blue');"&gt;Colorname&lt;/option&gt; &lt;option onClick="changediv('url(example.com/example.png)');"&gt;Image&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I could just add a different ID to each child (id1,id2,id3,...), but there are 32 children and not only would I have to add 32 IDs, but also 32 lines of Javascript. There has to be a better way; somehow selecting children or even changing the actual CSS code that selects the children.</p> <p>Thanks, Ian</p>
9,780,508
5
5
null
2012-03-20 01:59:28.933 UTC
15
2022-04-29 11:24:14.823 UTC
2012-03-20 03:24:38.61 UTC
null
315,828
null
1,243,041
null
1
27
javascript
100,462
<p>While this can be done in one line with JQuery, I am assuming you are not using JQuery - in which case, your code will be:</p> <pre><code>var nodes = document.getElementById('ID_of_parent').childNodes; for(var i=0; i&lt;nodes.length; i++) { if (nodes[i].nodeName.toLowerCase() == 'div') { nodes[i].style.background = color; } } </code></pre> <p>See <a href="http://jsfiddle.net/SxPxN/" rel="noreferrer">http://jsfiddle.net/SxPxN/</a> for a quick example I created - Click on "change 'em" to see it in action</p>
10,191,733
How to do a HTTP DELETE request with Requests library
<p>I'm using the <a href="http://docs.python-requests.org/en/latest/user/quickstart/#response-status-codes">requests</a> package for interacting with the toggl.com API. </p> <p>I can perform GET and POST requests:</p> <pre><code> payload = {'some':'data'} headers = {'content-type': 'application/json'} url = "https://www.toggl.com/api/v6/" + data_description + ".json" response = requests.post(url, data=json.dumps(payload), headers=headers,auth=HTTPBasicAuth(toggl_token, 'api_token')) </code></pre> <p>but i cant seem to find a way to perform a DELETE request. Is this possible? </p>
10,191,804
2
0
null
2012-04-17 12:57:30.82 UTC
6
2019-08-27 13:19:50.73 UTC
2012-04-17 12:58:35.963 UTC
null
269,581
null
628,918
null
1
39
python|django|httprequest
78,929
<p>Use <a href="http://docs.python-requests.org/en/latest/api/?highlight=delete#requests.delete" rel="noreferrer">requests.delete</a> instead of <code>requests.post</code></p> <pre class="lang-py prettyprint-override"><code>payload = {'some':'data'} headers = {'content-type': 'application/json'} url = "https://www.toggl.com/api/v6/" + data_description + ".json" response = requests.delete( url, data=json.dumps(payload), headers=headers, auth=HTTPBasicAuth(toggl_token, 'api_token') ) </code></pre>
9,808,488
How to optimize gradle build performance regarding build duration and RAM usage?
<p>I am currently switching from ant to gradle for my multi module web application and at the moment it seems that the current version of Gradle (M9) might be running up against its limits. But maybe (hopefully) it is just a problem of me not understanding the concepts of Gradle good enough or not knowing the "magic performance boost switch". I'd be happy for any hint on how the build performance could be optimized.</p> <p>The problems: several minutes pass before the first <code>compileJava</code> is displayed, and even if nothing has changed in the sources, the process is running at least 7 minutes until it crashes halfway through <code>:testClasses</code> (at varying subprojects) with the following message:</p> <pre><code>* What went wrong: Could not resolve all dependencies for configuration ':mysubproject_X:testRuntime'. &gt; Java heap space </code></pre> <p>The project consists of about 30 (partly interdependent) subprojects, the build.gradle of them being more or less the same and are used to build a jar file from each subproject, e.g.</p> <pre><code>sourceSets { main { java { srcDirs 'src' } } } dependencies { compile project(':mysubproject_A') compile project(':mysubproject_B') compile project(':mysubproject_E') compile group: 'commons-lang', name: 'commons-lang', version: '2.2' } // copy all non-java files from src copy { from sourceSets.main.java.srcDirs into "$buildDir/classes/main" exclude '**/*.java' } jar { } </code></pre> <p>I tried to resolve the heap space problem by ramping up max memory size to 1024M, but it did not help. My main build.gradle file looks like this:</p> <pre><code> sourceCompatibility = 1.6 version = 0.5 useFindBugs = false apply plugin: 'java' configurations { } repositories { mavenCentral() mavenRepo url:"http://repository.jboss.org/maven2", artifactUrls: ["https://repository.jboss.org/nexus/content/repositories/public","http://opensource.55minutes.com/maven-releases"] } dependencies { } buildscript { repositories { mavenRepo url: 'http://gradle.artifactoryonline.com/gradle/plugins' flatDir(dirs: "$projectDir/lib") } dependencies { classpath "org.gradle.plugins:gradle-idea-plugin:0.3.1" } } subprojects { apply plugin: 'java' apply plugin: 'idea' repositories { mavenCentral() mavenRepo url:"http://repository.jboss.org/maven2", artifactUrls: ["https://repository.jboss.org/nexus/content/repositories/public","http://opensource.55minutes.com/maven-releases"] } dependencies { testCompile 'junit:junit:4.8.2' } compileJava { options.encoding = 'UTF-8' options.fork (memoryMaximumSize: '1024m') } javadoc { options.encoding = 'UTF-8' } test { testReportDir = file(rootProject.testReportDir) forkEvery = 1 jvmArgs = ['-ea', '-Xmx1024m'] } } dependsOnChildren() task wrapper(type: Wrapper) { gradleVersion = '1.0-milestone-9' } </code></pre>
9,813,900
9
2
null
2012-03-21 16:10:26.367 UTC
17
2021-10-08 06:04:44.52 UTC
2021-10-08 06:04:44.52 UTC
null
5,459,839
null
1,006,823
null
1
44
performance|gradle|build|heap-memory
77,241
<p>You need to give more memory to the Gradle JVM, not to the compile task/JVM. One way to do so is via the <code>GRADLE_OPTS</code> environment variable (<code>GRADLE_OPTS=-Xmx512m</code>).</p>
9,779,710
SVN "Already Locked Error"
<p>When trying to commit a change to a repository ( where I am the only user ) I get an error</p> <pre><code>Path '/trunk/TemplatesLibrary/constraints/templates/TP145210GB01_PersonWithOrganizationUniversal.cs' is already locked by user 'admin' in filesystem '/guest/gam/subversion/cdaapi/db' </code></pre> <p>I am the user 'admin'.</p> <p>I have tried the following, all without success</p> <ul> <li>running a "clean up" from Tortoise SVN</li> <li>checking out a new copy</li> <li><p>using the "repo browser" to break locks, but no locks are shown ( as per <a href="https://stackoverflow.com/questions/8470730/svn-file-locked-by-me-now-cannot-commit-it">SVN file locked by me, now cannot commit it</a> )</p> <p>I am completely stuck now as I have a repository now that I can not commit any updates to.</p> <p>Any ideas how I fix this</p> <p>More Info, as requested :</p> <p>SVN Status command yields ( I have made edits to one file )</p> <pre><code> 92 77 admin TP146228GB01_EncompassingEncounter.cs 92 83 admin TP145212GB02_WorkgroupUniversal.cs 92 83 admin TP146248GB01_ReferenceURL.cs 92 85 admin TP145201GB01_PatientUniversal.cs 92 83 admin TP145204GB02_RecipientWorkgroupUniversal.cs 92 83 admin TP145202GB01_RecipientPersonUniversal.cs 92 83 admin TP145203GB02_RecipientOrganizationUniversal.cs 92 77 admin TP145205GB01_PersonUniversal.cs 92 83 admin TP145202GB02_RecipientPersonUniversal.cs 92 83 admin TP145203GB03_RecipientOrganizationUniversal.cs 92 85 admin TP145211GB01_HealthCareFacilityUniversal.cs 92 85 admin TP145200GB01_AuthorPersonUniversal.cs 92 83 admin TP145207GB01_AuthorDeviceUniversal.cs M 92 87 admin TP146226GB02_Consent.cs 92 85 admin TP146229GB01_TextSection.cs 92 83 admin TP145204GB03_RecipientWorkgroupUniversal.cs 92 86 admin TP145018UK03_CustodianOrganizationUniversal.cs 92 83 admin TP145208GB01_AuthorNonNamedPersonUniversal.cs 92 70 admin TP145214GB01_DocumentParticipantUniversal.cs 92 85 admin TP145007UK03_RelatedEntity.cs 92 80 admin TP146224GB02_Atachment.cs 92 83 admin TP146227GB02_ServiceEvent.cs 92 77 admin TP145210GB01_PersonWithOrganizationUniversal.cs </code></pre></li> </ul> <p>A svn commit then yields</p> <pre><code>svn commit --message updates Sending TP146226GB02_Consent.cs Transmitting file data .svn: E195022: Commit failed (details follow): svn: E195022: File 'D:\BENBUN_CODE\WORK\cdaapi\trunk\TemplatesLibrary\constraints\templates\TP146226GB02_Consent.cs' is locked in another working copy svn: E170007: No lock on path '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs' (Status 423 on PUT Request) svn: E175002: Server sent unexpected return value (423 Locked) in response to PUT request for '/subversion/cdaapi/!svn/wrk/3c75d861-8462-b94e-8729-df54843044f9/trunk/TemplatesLibrary/constraints/templates/TP146226GB02_Consent.cs' </code></pre> <p>As requested output of SVN st -u is shown below </p> <pre><code>&gt;svn st -u M 92 TP146226GB02_Consent.cs Status against revision: 92 </code></pre>
9,810,249
13
0
null
2012-03-20 00:01:19.983 UTC
5
2020-02-20 14:58:50.09 UTC
2017-05-23 12:02:50.75 UTC
null
-1
null
240,218
null
1
54
svn|tortoisesvn
140,758
<p>After discussing with the hosting of my SVN repository they gave me the following answer.</p> <p>Apparently my repository is replicated to a remote repository using SVNSYNC. SVNSYNC has known limitations with enforcing locking across the replicated repositories and this is where the problem lies.</p> <p>The locks were introduced by the AnkhSVN plugin in Visual Studio.</p> <p>As the locks appears to be on the remote repository this explains why I can't actually see them using SVN commands.</p> <p>The locks are being removed via the hosting company and hopefully all will soon be well again.</p>
10,025,032
What is the meaning of the prefix N in T-SQL statements and when should I use it?
<p>I have seen prefix N in some insert T-SQL queries. Many people have used <code>N</code> before inserting the value in a table.</p> <p>I searched, but I was not able to understand what is the purpose of including the <code>N</code> before inserting any strings into the table.</p> <pre><code>INSERT INTO Personnel.Employees VALUES(N'29730', N'Philippe', N'Horsford', 20.05, 1), </code></pre> <p>What purpose does this 'N' prefix serve, and when should it be used?</p>
10,025,043
4
0
null
2012-04-05 08:19:53.52 UTC
93
2021-04-16 08:11:07.263 UTC
2020-02-16 17:53:46.013 UTC
null
366,904
null
1,253,970
null
1
468
sql|sql-server|tsql
387,788
<p>It's declaring the string as <code>nvarchar</code> data type, rather than <code>varchar</code></p> <blockquote> <p>You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.</p> </blockquote> <p>To quote <a href="https://docs.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql" rel="noreferrer">from Microsoft</a>:</p> <blockquote> <p>Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. <strong>This default code page may not recognize certain characters</strong>.</p> </blockquote> <hr /> <p>If you want to know the difference between these two data types, see this SO post:</p> <p><a href="https://stackoverflow.com/questions/144283/what-is-the-difference-between-varchar-and-nvarchar">What is the difference between varchar and nvarchar?</a></p>
11,815,295
Javascript inline onclick goto local anchor
<p>I have a button as an image...</p> <pre><code>&lt;img src="button.png" /&gt; </code></pre> <p>I need some javascript in an onclick where when click it will navigate to a local anchor. For example:</p> <pre><code>&lt;img src="button.png" onclick="navigateTo #page10" /&gt; </code></pre> <p>How can I do this?</p> <p>Update: This is the code I'm using:</p> <pre><code>onclick="document.location=#goToPage';return false;" </code></pre>
11,815,633
4
4
null
2012-08-05 09:22:41.417 UTC
3
2019-11-28 11:51:44.47 UTC
2012-08-05 10:03:51.32 UTC
null
218,196
null
683,553
null
1
21
javascript
40,563
<p>it looks the <code>onClick</code> should be:</p> <pre><code>onclick="document.location+='#goToPage';return false;" </code></pre>
11,804,332
Insert an image in chrome extension
<p>I want to know how to insert an image in a Chrome extension. </p> <pre class="lang-html prettyprint-override"><code>&lt;img id="image" src="logo.png" /&gt; </code></pre> <p>I'm inserting that html tag correctly into a website, but naturally can't load that logo.png image. </p> <p>Any ideas on how to modify manifest.json?</p>
11,807,411
3
2
null
2012-08-03 22:54:55.303 UTC
9
2022-07-04 13:30:46.79 UTC
2012-08-03 23:04:53.633 UTC
null
194,970
null
1,341,526
null
1
44
google-chrome|google-chrome-extension
41,605
<p>There are two possible causes for the problem.</p> <ol> <li><p>You're injecting an image with <code>src=&quot;logo.png&quot;</code>. The inserted image element becomes a part of the page, so the browser <strong>does not try to</strong> load the image from the extension.<br /> To fix this problem, use <a href="https://developer.chrome.com/docs/extensions/mv2/xhr/#extension-origin" rel="nofollow noreferrer"><code>chrome.extension.getURL('logo.png');</code></a> to get the absolute URL of the resource.</p> </li> <li><p><a href="https://developer.chrome.com/docs/extensions/mv2" rel="nofollow noreferrer"><code>&quot;manifest_version&quot;: 2</code></a> is enabled in the manifest file. That disables all resources for external use, by default. When this error occurs, the following message appears in the console:</p> </li> </ol> <blockquote>Not allowed to load local resource: chrome://gbmfhbpbiibnbbgjcoankapcmcgdkkno/logo.png</blockquote> To solve the problem, add the resource to a whitelist, namely [`"web_accessible_resources"`][3] in the manifest file: <pre><code> ..., &quot;web_accessible_resources&quot;: [&quot;logo.png&quot;] } </code></pre> <p>UPDATE: <code>chrome.extension.getURL('logo.png')</code></p> <blockquote> <p>Deprecated since Chrome 58. Please use <a href="https://developer.chrome.com/extensions/runtime#method-getURL" rel="nofollow noreferrer"><code>runtime.getURL</code></a>.</p> </blockquote>
19,862,116
How to merge two dictionaries with same key names
<p>I am new to Python and am trying to write a function that will merge two dictionary objects in python. For instance </p> <pre><code>dict1 = {'a':[1], 'b':[2]} dict2 = {'b':[3], 'c':[4]} </code></pre> <p>I need to produce a new merged dictionary </p> <pre><code>dict3 = {'a':[1], 'b':[2,3], 'c':[4]} </code></pre> <p>Function should also take a parameter “conflict” (set to True or False). When conflict is set to False, above is fine. When conflict is set to True, code will merge the dictionary like this instead: </p> <pre><code>dict3 = {'a':[1], 'b_1':[2], 'b_2':[3], 'c':[4]} </code></pre> <p>I am trying to append the 2 dictionaries, but not sure how to do it the right way.</p> <pre><code>for key in dict1.keys(): if dict2.has_key(key): dict2[key].append(dict1[key]) </code></pre>
19,862,858
2
7
null
2013-11-08 15:02:26.537 UTC
4
2018-12-12 21:55:32.797 UTC
2018-01-04 12:07:53.763 UTC
null
1,170,207
null
2,850,931
null
1
31
python|dictionary
5,146
<p>If you want a merged copy that does not alter the original dicts and watches for name conflicts, you might want to try this solution:</p> <pre><code>#! /usr/bin/env python3 import copy import itertools def main(): dict_a = dict(a=[1], b=[2]) dict_b = dict(b=[3], c=[4]) complete_merge = merge_dicts(dict_a, dict_b, True) print(complete_merge) resolved_merge = merge_dicts(dict_a, dict_b, False) print(resolved_merge) def merge_dicts(a, b, complete): new_dict = copy.deepcopy(a) if complete: for key, value in b.items(): new_dict.setdefault(key, []).extend(value) else: for key, value in b.items(): if key in new_dict: # rename first key counter = itertools.count(1) while True: new_key = f'{key}_{next(counter)}' if new_key not in new_dict: new_dict[new_key] = new_dict.pop(key) break # create second key while True: new_key = f'{key}_{next(counter)}' if new_key not in new_dict: new_dict[new_key] = value break else: new_dict[key] = value return new_dict if __name__ == '__main__': main() </code></pre> <p>The program displays the following representation for the two merged dictionaries:</p> <pre><code>{'a': [1], 'b': [2, 3], 'c': [4]} {'a': [1], 'b_1': [2], 'b_2': [3], 'c': [4]} </code></pre>
3,369,640
When is using __call__ a good idea?
<p>What are peoples' opinions on using the <code>__call__</code>. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour.</p>
3,369,912
4
2
null
2010-07-30 08:02:34.443 UTC
7
2010-08-30 18:35:48.947 UTC
null
null
null
null
395,287
null
1
33
python|oop
4,640
<p>I think your intuition is about right.</p> <p>Historically, callable objects (or what I've sometimes heard called "functors") have been used in the OO world to simulate closures. In C++ they're frequently indispensable.</p> <p>However, <code>__call__</code> has quite a bit of competition in the Python world:</p> <ul> <li>A regular named method, whose behavior can sometimes be a lot more easily deduced from the name. Can convert to a bound method, which can be called like a function.</li> <li>A closure, obtained by returning a function that's defined in a nested block.</li> <li>A lambda, which is a limited but quick way of making a closure.</li> <li>Generators and coroutines, whose bodies hold accumulated state much like a functor can.</li> </ul> <p>I'd say the time to use <code>__call__</code> is when you're not better served by one of the options above. Check the following criteria, perhaps:</p> <ul> <li>Your object has state.</li> <li>There is a clear "primary" behavior for your class that's kind of silly to name. E.g. if you find yourself writing <code>run()</code> or <code>doStuff()</code> or <code>go()</code> or the ever-popular and ever-redundant <code>doRun()</code>, you may have a candidate.</li> <li>Your object has state that exceeds what would be expected of a generator function.</li> <li>Your object wraps, emulates, or abstracts the concept of a function.</li> <li>Your object has other auxilliary methods that conceptually belong with your primary behavior.</li> </ul> <p>One example I like is UI command objects. Designed so that their primary task is to execute the comnand, but with extra methods to control their display as a menu item, for example, this seems to me to be the sort of thing you'd still want a callable object for.</p>
3,717,420
Is there a benefit to using a return statement that returns nothing?
<p>I'm refactoring a large javascript document that I picked up from an open source project. A number of functions use inconsistent return statements. Here's a simple example of what I mean:</p> <pre><code>var func = function(param) { if (!param) { return; } // do stuff return true; } </code></pre> <p>Sometimes the functions return boolean, sometimes strings or other things. Usually they are inconsistently paired with a simple <code>return;</code> statement inside of a conditional.</p> <p>The problem is that the code is complex. It is a parser that uses a multitude of unique RegEx matches, creates and destroys DOM nodes on the fly, etc. Preliminary testing shows that, in the above example, I could change the <code>return;</code> statement to become <code>return false;</code>, but I'm concerned that I may not realize that it had a negative impact (i.e. some feature stopped working) on the script until much later.</p> <p>So my questions: Is there a benefit to using a blank return statement? Could this have been intentionally coded this way or was it just lazy? Can I change them all to <code>return false;</code>, or <code>return null;</code> or do I need to dig through every call and find out what they are doing with the results of those functions?</p>
3,717,548
5
1
null
2010-09-15 12:08:36.82 UTC
20
2020-07-10 03:13:37.293 UTC
2014-08-22 02:54:14.52 UTC
null
15,168
null
262,056
null
1
65
javascript|refactoring|return-value
85,266
<p><strong>Using <code>return</code> without a value will return the value <code>undefined</code>.</strong></p> <p>If the value is evaluated as a boolean, <code>undefined</code> will work as <code>false</code>, but if the value for example is compared to <code>false</code>, you will get a different behaviour:</p> <pre><code>var x; // x is undefined alert(x); // shows "undefined" alert(!x); // shows "true" alert(x==false); // shows "false" </code></pre> <p>So, while the code should logically return <code>true</code> or <code>false</code>, not <code>true</code> or <code>undefined</code>, you can't just change <code>return;</code> to <code>return false;</code> without checking how the return value is used.</p>
3,464,007
ruby convert class name in string to actual class
<p>How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)</p> <p>The reason I ask is because I'm using the <code>acts_as_commentable</code> plugin, among others, and these store the commentable_type as a column. I want to be able to call whatever particular commentable class to do a <code>find(commentable_id)</code> on it.</p> <p>Thanks.</p>
3,464,012
6
0
null
2010-08-12 01:05:28.477 UTC
18
2021-06-03 19:00:52.777 UTC
null
null
null
null
146,478
null
1
105
ruby-on-rails
62,849
<p>I think what you want is <a href="http://apidock.com/rails/Inflector/constantize" rel="noreferrer"><code>constantize</code></a></p> <p>That's an RoR construct. I don't know if there's one for ruby core</p>
4,004,377
Splitting comma separated string in a PL/SQL stored proc
<p>I've CSV string 100.01,200.02,300.03 which I need to pass to a PL/SQL stored procedure in Oracle. Inside the proc,I need to insert these values in a Number column in the table.</p> <p>For this, I got a working approach from over here:</p> <p><a href="https://stackoverflow.com/questions/1089508/how-to-best-split-csv-strings-in-oracle-9i">How to best split csv strings in oracle 9i</a></p> <p>[2) Using SQL's connect by level.].</p> <p>Now,I've another requirement. I need to pass 2 CSV strings[equal in length] as input to PL/SQL stored proc.And, I need to break this string and insert each value from two CSV strings into two different columns in the table.Could you please let me know how to go about it?</p> <p>Example of CSV inputs: mystring varchar2(2000):='0.75, 0.64, 0.56, 0.45';</p> <p>myAmount varchar2(2000):= '0.25, 0.5, 0.65, 0.8';</p> <p>myString values would go into Column A and myAmount values into Column B in the table.</p> <p>Could you please let me know how to achieve this?</p> <p>Thanks.</p>
4,035,763
8
1
null
2010-10-23 14:09:32.047 UTC
9
2019-05-18 20:30:23.407 UTC
2017-05-23 12:25:48.557 UTC
null
-1
null
68,717
null
1
23
oracle|plsql|tokenize
110,513
<p>This should do what you are looking for.. It assumes your list will always be just numbers. If that is not the case, just change the references to DBMS_SQL.NUMBER_TABLE to a table type that works for all of your data:</p> <pre><code>CREATE OR REPLACE PROCEDURE insert_from_lists( list1_in IN VARCHAR2, list2_in IN VARCHAR2, delimiter_in IN VARCHAR2 := ',' ) IS v_tbl1 DBMS_SQL.NUMBER_TABLE; v_tbl2 DBMS_SQL.NUMBER_TABLE; FUNCTION list_to_tbl ( list_in IN VARCHAR2 ) RETURN DBMS_SQL.NUMBER_TABLE IS v_retval DBMS_SQL.NUMBER_TABLE; BEGIN IF list_in is not null THEN /* || Use lengths loop through the list the correct amount of times, || and substr to get only the correct item for that row */ FOR i in 1 .. length(list_in)-length(replace(list_in,delimiter_in,''))+1 LOOP /* || Set the row = next item in the list */ v_retval(i) := substr ( delimiter_in||list_in||delimiter_in, instr(delimiter_in||list_in||delimiter_in, delimiter_in, 1, i ) + 1, instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i+1) - instr (delimiter_in||list_in||delimiter_in, delimiter_in, 1, i) -1 ); END LOOP; END IF; RETURN v_retval; END list_to_tbl; BEGIN -- Put lists into collections v_tbl1 := list_to_tbl(list1_in); v_tbl2 := list_to_tbl(list2_in); IF v_tbl1.COUNT &lt;&gt; v_tbl2.COUNT THEN raise_application_error(num =&gt; -20001, msg =&gt; 'Length of lists do not match'); END IF; -- Bulk insert from collections FORALL i IN INDICES OF v_tbl1 insert into tmp (a, b) values (v_tbl1(i), v_tbl2(i)); END insert_from_lists; </code></pre>
3,619,693
Getting View's coordinates relative to the root layout
<p>Can I get a View's x and y position relative to the root layout of my Activity in Android?</p>
3,621,042
10
0
null
2010-09-01 15:28:00.033 UTC
51
2020-08-08 11:19:31.603 UTC
2013-11-29 12:54:03.537 UTC
null
56,285
null
243,225
null
1
152
android|android-layout|coordinates
175,383
<p>This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.</p> <pre><code>private int getRelativeLeft(View myView) { if (myView.getParent() == myView.getRootView()) return myView.getLeft(); else return myView.getLeft() + getRelativeLeft((View) myView.getParent()); } private int getRelativeTop(View myView) { if (myView.getParent() == myView.getRootView()) return myView.getTop(); else return myView.getTop() + getRelativeTop((View) myView.getParent()); } </code></pre> <p>Let me know if that works.</p> <p>It should recursively just add the top and left positions from each parent container. You could also implement it with a <code>Point</code> if you wanted.</p>
3,260,653
Algorithm to find top 10 search terms
<p>I'm currently preparing for an interview, and it reminded me of a question I was once asked in a previous interview that went something like this:</p> <p>"You have been asked to design some software to continuously display the top 10 search terms on Google. You are given access to a feed that provides an endless real-time stream of search terms currently being searched on Google. Describe what algorithm and data structures you would use to implement this. You are to design two variations: </p> <p>(i) Display the top 10 search terms of all time (i.e. since you started reading the feed). </p> <p>(ii) Display only the top 10 search terms for the past month, updated hourly. </p> <p>You can use an approximation to obtain the top 10 list, but you must justify your choices." <br />I bombed in this interview and still have really no idea how to implement this. </p> <p>The first part asks for the 10 most frequent items in a continuously growing sub-sequence of an infinite list. I looked into selection algorithms, but couldn't find any online versions to solve this problem. </p> <p>The second part uses a finite list, but due to the large amount of data being processed, you can't really store the whole month of search terms in memory and calculate a histogram every hour. </p> <p>The problem is made more difficult by the fact that the top 10 list is being continuously updated, so somehow you need to be calculating your top 10 over a sliding window.</p> <p>Any ideas?</p>
3,260,893
16
2
null
2010-07-15 22:40:42.333 UTC
147
2017-12-10 16:10:31.46 UTC
2014-08-07 07:00:05.277 UTC
null
3,154,233
null
393,304
null
1
119
algorithm|data-structures
63,849
<p>Well, looks like an awful lot of data, with a perhaps prohibitive cost to store all frequencies. <strong>When the amount of data is so large</strong> that we cannot hope to store it all, we enter the domain of <strong>data stream algorithms</strong>.</p> <p>Useful book in this area: <a href="http://books.google.com/books?id=415loiMd_c0C&amp;lpg=PP1&amp;dq=Data%20Streams:%20Algorithms%20and%20Application&amp;hl=el&amp;pg=PP1#v=onepage&amp;q=Data%20Streams%3A%20Algorithms%20and%20Application&amp;f=false" rel="noreferrer">Muthukrishnan - "Data Streams: Algorithms and Applications"</a></p> <p>Closely related reference to the problem at hand which I picked from the above: <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.19.8594&amp;rep=rep1&amp;type=pdf" rel="noreferrer">Manku, Motwani - "Approximate Frequency Counts over Data Streams" [pdf]</a></p> <p>By the way, Motwani, of Stanford, (edit) was an author of the very important <a href="https://rads.stackoverflow.com/amzn/click/com/0521474655" rel="noreferrer" rel="nofollow noreferrer">"Randomized Algorithms"</a> book. <strike><strong>The 11th chapter of this book deals with this problem</strong></strike>. <strong>Edit:</strong> Sorry, bad reference, that particular chapter is on a different problem. After checking, I instead recommend <a href="http://books.google.com/books?id=415loiMd_c0C&amp;lpg=PP1&amp;dq=Data%20Streams%3A%20Algorithms%20and%20Application&amp;hl=el&amp;pg=PA33#v=onepage&amp;q&amp;f=false" rel="noreferrer">section 5.1.2 of <em>Muthukrishnan's</em> book</a>, available online.</p> <p>Heh, nice interview question. </p>
7,778,444
SQL SELECT - Return boolean based on condition
<p>Essentially I'm trying to do this</p> <pre><code>select u.Hostname, u.IsCustom, (u.Status = 5) as IsActive from SiteUrlMappings u </code></pre> <p>Where 5 is an int representing an "Active" url.</p> <p>Of course this doesn't work, and my sql is rusty like an old screwdriver.</p>
7,778,500
5
1
null
2011-10-15 14:34:28.203 UTC
4
2016-12-14 16:37:46.47 UTC
2011-10-15 19:28:37.197 UTC
null
13,302
null
231,216
null
1
30
sql-server|tsql
51,478
<p>You don't need a CASE expression<br> Just leverage how <code>bit</code> works: all non-zero values give 1 when cast to bit</p> <pre><code>SELECT u.Hostname, u.IsCustom, ~ CAST((u.Status - 5) AS bit) AS IsActive from SiteUrlMappings u </code></pre>
8,151,527
How do I connect to Kindle Fire for development?
<p>What do I need to do to use my Kindle Fire for android development? (Specifically for testing my apps on the device.)</p>
8,151,549
6
1
null
2011-11-16 12:17:00.587 UTC
12
2014-12-04 18:43:05.313 UTC
2011-11-30 19:03:57.587 UTC
null
260,408
null
260,408
null
1
26
android|kindle-fire
13,315
<p>You can find the instructions for connecting Kindle Fire to the ADB in a <a href="http://g-ecx.images-amazon.com/images/G/01/sdk/Connecting_your_Kindle_Fire_to_ADB.pdf">PDF of instructions</a> provided by Amazon.</p> <p>Paraphrased from the document:</p> <ol> <li><p>Edit the adb_usb.ini file (located in ~/.android/)</p></li> <li><p>Add the lines:</p> <blockquote> <pre><code>0x1949 0x0006 </code></pre> </blockquote></li> <li><p>Save the file.</p></li> <li><p>Run these commands to restart adb:</p> <blockquote> <pre><code>adb kill-server adb start-server adb devices </code></pre> </blockquote></li> </ol> <p>NOTE: For Windows 7 users you need to download <a href="http://g-ecx.images-amazon.com/images/G/01/sdk/kindle-fire-windows-7-driver.zip">an additional driver</a>.</p>
7,981,786
Line breaks in textarea element
<p>This is PURE HTML. (no php or anything like that, if you want to know the background its a C# application with HTML in a web view).</p> <p>All my HTML files are nicely formatted and correctly indented for maintainability and such.</p> <p>Here is an excerpt:</p> <pre class="lang-html prettyprint-override"><code>&lt;tr&gt; &lt;td class="label"&gt;Clinic Times:&lt;/td&gt; &lt;td&gt;&lt;textarea name="familyPlanningClinicSessionsClinicTimes"&gt;Monday: Tuesday: Wednesday: Thursday: Friday: Saturday: Sunday:&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>The line breaks in the <code>&lt;textarea&gt;&lt;/textarea&gt;</code> element are there to get the line breaks on the page. However it also includes the indentation in the textarea element.</p> <p>e.g.</p> <p><img src="https://i.stack.imgur.com/tI0aM.png" alt="example"></p> <p>The only way I can think to remove this issue is to remove the indentation. Its not the end of the world, but is there another way, to keep the nice formatting? Thanks.</p>
7,981,984
8
6
null
2011-11-02 14:14:53.303 UTC
4
2020-01-18 15:28:21.613 UTC
2017-06-20 09:29:29.393 UTC
null
2,857,638
null
414,972
null
1
26
html|css|internet-explorer|textarea
75,150
<p>You could use the <code>&amp;#10;</code> (it means new line in html) but maybe that's not a nice formatting, like you said...</p> <blockquote> <p>The only way I can think to remove this issue is to remove the indentation. Its not the end of the world, but is there another way, to keep the nice formatting?</p> </blockquote> <pre><code>&lt;tr&gt; &lt;td class="label"&gt;Clinic Times:&lt;/td&gt; &lt;td&gt;&lt;textarea name="familyPlanningClinicSessionsClinicTimes"&gt;Monday:&amp;#10;Tuesday:&amp;#10;Wednesday:&amp;#10;Thursday:&amp;#10;Friday:&amp;#10;Saturday:&amp;#10;Sunday:&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre>
4,574,090
Installed jvm is 64 bit or 32 bit
<p>How can I identity whether the installed version of Java is <code>64 bit</code> or <code>32 bit</code> ?</p>
4,574,108
3
2
null
2011-01-01 12:48:46.543 UTC
5
2013-08-09 01:45:52.883 UTC
2012-11-19 06:53:25.37 UTC
null
355,785
null
559,768
null
1
15
java|32bit-64bit
42,273
<p>You can get the <code>os.arch</code> property:</p> <pre><code>String osArch = System.getProperty("os.arch"); </code></pre> <p>This will tell you the architecture of the OS, so not exactly the one of the VM.</p> <p>Sun's JREs have the following properties (values from my machine) that may be useful:</p> <pre><code>sun.arch.data.model : 32 sun.cpu.isalist : pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86 </code></pre> <p>But have in mind that these will not work on VMs from other vendors. So you may want to find such properties of other VMs as well, so that you are not vendor-dependent.</p>
4,551,424
How to refer to a variable name with spaces?
<p>In <code>ggplot2</code>, how do I refer to a variable name with spaces?</p> <p>Why do <code>qplot()</code> and <code>ggplot()</code> break when used on variable names with quotes?</p> <p>For example, this works:</p> <pre><code>qplot(x,y,data=a) </code></pre> <p>But this does not:</p> <pre><code>qplot("x","y",data=a) </code></pre> <p>I ask because I often have data matrices with spaces in the name. Eg, "State Income". ggplot2 needs data frames; ok, I can convert. So I'd want to try something like:</p> <pre><code>qplot("State Income","State Ideology",data=as.data.frame(a.matrix)) </code></pre> <p>That fails.</p> <p>Whereas in base R graphics, I'd do:</p> <pre><code>plot(a.matrix[,"State Income"],a.matrix[,"State Ideology"]) </code></pre> <p>Which would work.</p> <p>Any ideas?</p>
4,554,977
3
3
null
2010-12-29 04:15:38.11 UTC
10
2016-06-25 07:14:53.48 UTC
2013-03-11 20:06:39.133 UTC
null
563,329
null
170,408
null
1
29
r|plot|ggplot2
64,011
<p>Answer: because 'x' and 'y' are considered a length-one character vector, not a variable name. Here you discover why it is not smart to use variable names with spaces in R. Or any other programming language for that matter.</p> <p>To refer to variable names with spaces, you can use either hadleys solution</p> <pre><code>a.matrix &lt;- matrix(rep(1:10,3),ncol=3) colnames(a.matrix) &lt;- c("a name","another name","a third name") qplot(`a name`, `another name`,data=as.data.frame(a.matrix)) # backticks! </code></pre> <p>or the more formal</p> <pre><code>qplot(get('a name'), get('another name'),data=as.data.frame(a.matrix)) </code></pre> <p>The latter can be used in constructs where you pass the name of a variable as a string in eg a loop construct :</p> <pre><code>for (i in c("another name","a third name")){ print(qplot(get(i),get("a name"), data=as.data.frame(a.matrix),xlab=i,ylab="a name")) Sys.sleep(5) } </code></pre> <p>Still, the best solution is not to use variable names with spaces.</p>
4,123,603
Python unsubscriptable
<p>What does <code>unsubscriptable</code> mean in the context of a TypeError as in:</p> <pre><code>TypeError: 'int' object is unsubscriptable </code></pre> <p>EDIT: Short code example that results in this phenomena.</p> <pre><code>a=[[1,2],[5,3],5,[5,6],[2,2]] for b in a: print b[0] &gt; 1 &gt; 5 &gt; TypeError: 'int' object is unsubscriptable </code></pre>
4,123,614
4
6
null
2010-11-08 12:00:11.153 UTC
2
2020-07-30 04:29:48.757 UTC
2010-11-09 09:11:48.043 UTC
null
441,337
null
441,337
null
1
31
python|typeerror
101,200
<p>It means you tried treating an integer as an array. For example:</p> <pre><code>a = 1337 b = [1,3,3,7] print b[0] # prints 1 print a[0] # raises your exception </code></pre>
4,371,181
Namespaces in R packages
<p>How do people learn about giving an R package a namespace? I find the documention in "R Extensions" fine, but I don't really get what is happening when a variable is imported or exported - I need a dummy's guide to these directives. </p> <p>How do you decide what is exported? Is it just everything that really shouldn't required the pkg:::var syntax? What about imports? </p> <p>Do imports make it easier to ensure that your use of other package functions doesn't get confused when function names overlap? </p> <p>Are there special considerations for S4 classes? </p> <p>Packages that I'm familiar with that use namespaces such as sp and rgdal are quite complicated - are there simple examples that could make things clearer? </p>
4,388,071
5
0
null
2010-12-06 21:34:06.997 UTC
15
2022-07-27 13:40:56.737 UTC
null
null
null
null
355,270
null
1
62
r
28,995
<p>I have a start on an answer on the devtools wiki: <a href="https://r-pkgs.org/Metadata.html" rel="nofollow noreferrer">https://r-pkgs.org/Metadata.html</a></p>
4,826,951
How to run rake tasks from console?
<p>I want to invoke my rake task from console. Is it doable? if yes, how to do so?</p> <p>I tried this on console:</p> <pre class="lang-rb prettyprint-override"><code>require 'rake' Rake::Task['my_task'].invoke </code></pre> <p>but it give me this error:</p> <pre><code>RuntimeError: Don't know how to build task </code></pre> <p>it's like the rake cannot found the task.</p> <p>any help would be appreciated.</p> <p>Thank you</p> <p>Edit: I am using rails 2.3.5</p>
10,061,815
5
0
null
2011-01-28 10:04:55.16 UTC
35
2019-01-30 18:53:38.433 UTC
2013-05-30 08:34:45.357 UTC
null
23,368
null
273,183
null
1
111
console|rake
61,708
<p>Running your Rake tasks requires two steps:</p> <ol> <li>Loading <strong>Rake</strong></li> <li>Loading your <strong>Rake tasks</strong></li> </ol> <p>You are missing the second step.</p> <p>Normally this is done in the Rakefile, but you have to do it manually here:</p> <pre class="lang-rb prettyprint-override"><code>require 'rake' Rails.application.load_tasks # &lt;-- MISSING LINE Rake::Task['my_task'].invoke </code></pre>
4,281,101
Convert contents of DataGridView to List in C#
<p>What is the best way to grab the contents of a DataGridView and place those values into a list in C#?</p>
4,281,144
6
0
null
2010-11-25 21:54:02.063 UTC
1
2021-10-13 20:26:01.7 UTC
null
null
null
null
411,409
null
1
14
c#|list|datagridview
54,938
<pre><code> List&lt;MyItem&gt; items = new List&lt;MyItem&gt;(); foreach (DataGridViewRow dr in dataGridView1.Rows) { MyItem item = new MyItem(); foreach (DataGridViewCell dc in dr.Cells) { ...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value } items.Add(item); } </code></pre>
4,743,254
Setting a width and height on an A tag
<p>Is it possible to set the width and height in pixels on an anchor tag? I'd like to have the anchor tag to have a background image while retaining the text inside the anchor.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>li { width: 32px; height: 32px; background-color: orange; } li a { width: 32px; height: 32px; background-color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;li&gt;&lt;a href="#"&gt;Something&lt;/a&gt;&lt;/li&gt;</code></pre> </div> </div> </p>
4,743,269
6
0
null
2011-01-20 03:48:29.507 UTC
27
2021-06-09 10:25:21.617 UTC
2019-01-27 23:01:50.803 UTC
null
8,620,333
null
21,406
null
1
154
html|css|cross-browser
187,867
<p>You need to make your anchor <code>display: block</code> or <code>display: inline-block;</code> and then it will accept the width and height values.</p>
4,494,775
mysql concat function
<p>when i <code>concat($name, $surname)</code>, is there a way of putting a space in between the <code>$name $surname</code> using my sql not php so when i get the result it formats a little cleaner?</p> <p>many thanks</p>
4,494,805
7
0
null
2010-12-20 22:50:26.23 UTC
2
2022-08-17 07:40:05.387 UTC
2010-12-20 22:58:57.743 UTC
null
427,328
null
442,794
null
1
32
mysql
49,352
<p>You can concatenate string literals along with your fields, so you can add a space character in a string between the fields you're concatenating.</p> <p>Use this:</p> <pre><code> CONCAT(name, " ", surname) </code></pre> <p>This functionality is documented quite clearly on the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat" rel="noreferrer">MySQL manual page for the <code>CONCAT()</code> function</a>.</p> <p>There is also the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws" rel="noreferrer"><code>CONCAT_WS</code> function</a> which allows you to specify a separator to be used between each of the other fields passed to the function. If you're concatenating more than two fields in the same way, this function might be considered cleaner than repeating the separator between each field.</p> <p>For example, if you wanted to add a middle name field, you could use this function to specify the separator only once:</p> <pre><code>CONCAT_WS(" ", first_name, middle_name, surname) </code></pre>
4,065,518
Java: How to get the caller function name
<p>To fix a test case I need to identify whether the function is called from a particular caller function. I can't afford to add a boolean parameter because it would break the interfaces defined. How to go about this?</p> <p>This is what I want to achieve. Here I can't change the parameters of operation() as it is an interface implementation.</p> <pre><code>operation() { if not called from performancetest() method do expensive bookkeeping operation ... } </code></pre>
4,065,546
7
4
null
2010-10-31 22:36:56.723 UTC
8
2021-08-05 22:50:31.767 UTC
2010-10-31 22:50:42.223 UTC
null
94,169
null
94,169
null
1
41
java|unit-testing
60,900
<p>You could try</p> <pre><code>StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected String methodName = e.getMethodName(); </code></pre>
4,104,544
How to access static members of a class?
<p>I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors. </p> <p>I'm using <code>g++4.4.2</code> on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class A { public: static int x; static int getX() {return x;} }; int main() { int A::x = 100; // error: invalid use of qualified-name 'A::x' cout&lt;&lt;A::getX(); // error: : undefined reference to 'A::x' return 0; } </code></pre> <p>I think it's exactly the same as declared <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr038.htm" rel="noreferrer">here</a> and <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr038.htm" rel="noreferrer">here</a> (isn't it?). So what's wrong with the above code?</p>
4,104,571
9
0
null
2010-11-05 09:04:06.037 UTC
5
2022-04-24 08:06:44.03 UTC
2018-06-29 00:47:49.53 UTC
null
4,618,308
null
275,221
null
1
35
c++|static
71,490
<p>You've declared the static members fine, but not <a href="http://dietmar-kuehl.de/mirror/c++-faq/ctors.html#faq-10.12">defined</a> them anywhere.</p> <p>Basically what you've said "there exists some static member", but never set aside some memory for it, you need:</p> <pre><code>int A::x = 100; </code></pre> <p>Somewhere outside the class and <em>not</em> inside main.</p>
14,558,289
Java: Insert into a table datetime data
<p>I am trying to insert into a variable in MS- SQL database the current date and the time. I use this format: </p> <pre><code>DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); </code></pre> <p>and I get this as a result 2013-01-28 09:29:37.941</p> <p>My field in the database is defined <code>datetime</code> and as I have seen in other tables which have the same field, the date and the time is written exactly like this 2011-07-05 14:18:33.000.</p> <p>I try to insert into the database with a query that I do inside a java program, but I get this error</p> <blockquote> <p>SQL Exception: State : S0003 Message: The conversion of a varchar data type to a datetime data type of the value is out of range. Error : 242</p> </blockquote> <p>My query is like that: </p> <pre><code>query = "INSERT INTO Companies CreatedOn"+ "VALUES ('" + dateFormat.format(cal.getTime()) + "')" </code></pre> <p>but I don't understand what I am doing wrong.</p>
14,558,378
6
4
null
2013-01-28 08:38:56.73 UTC
4
2015-05-28 07:45:04.883 UTC
2013-01-28 08:46:15.503 UTC
null
1,554,314
null
938,285
null
1
11
java|sql|sql-server|datetime|jdbc
83,346
<p>According to the <a href="http://www.sql-server-helper.com/error-messages/msg-242.aspx" rel="noreferrer">error description</a>, you are inserting an incorrect type into the database. See <a href="http://msdn.microsoft.com/en-us/library/ms378878.aspx" rel="noreferrer">JDBC to MSSQL</a>. You should convert Calendar to <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html" rel="noreferrer">Timestamp</a>.</p> <p>Try using:</p> <pre><code>PrepareStatement statement = connection.prepareStatement("INSERT INTO Companies CreatedOn VALUES(?)"); java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis()); statement.setTimestamp(1, timstamp); int insertedRecordsCount = statement.executeUpdate(); </code></pre>
14,686,332
What does this line mean in Java: boolean retry = id == 1;
<p>I have been learning Java for a while now and still learning new syntax tricks and stuff. I came across this in Android source code:</p> <pre><code>boolean retry = id == 1; </code></pre> <p>What does it mean?</p>
14,686,342
17
4
null
2013-02-04 12:01:02.017 UTC
10
2018-03-17 06:10:16.623 UTC
2015-05-24 20:25:55.27 UTC
null
2,441,442
null
949,280
null
1
66
java|syntax
14,769
<p><code>retry</code> is <code>true</code> if <code>id</code> has the value 1, otherwise <code>retry</code> is <code>false</code>.</p>
14,787,761
Convert True->1 and False->0 in Javascript?
<p>Besides : </p> <p><code>true ? 1 : 0</code></p> <p>is there any short trick which can "translate" <code>True-&gt;1</code> and <code>False-&gt;0</code> in Javascript ?</p> <p>I've searched but couldn't find any alternative</p> <p><em><strong>What</strong> do you mean by "short trick" ?</em></p> <p>answer : same as <code>~~6.6</code> is a trick for<code>Math.floor</code></p>
14,787,812
4
7
null
2013-02-09 11:44:16.797 UTC
25
2022-04-22 23:47:55.92 UTC
null
null
null
null
859,154
null
1
82
javascript
44,884
<p>Lots of ways to do this</p> <pre><code>// implicit cast +true; // 1 +false; // 0 // bit shift by zero true &gt;&gt;&gt; 0; // 1, right zerofill false &gt;&gt;&gt; 0; // 0 true &lt;&lt; 0; // 1, left false &lt;&lt; 0; // 0 // double bitwise NOT ~~true; // 1 ~~false; // 0 // bitwise OR ZERO true | 0; // 1 false | 0; // 0 // bitwise AND ONE true &amp; 1; // 1 false &amp; 1; // 0 // bitwise XOR ZERO, you can negate with XOR ONE true ^ 0; // 1 false ^ 0; // 0 // even PLUS ZERO true + 0; // 1 false + 0; // 0 // and MULTIPLICATION by ONE true * 1; // 1 false * 1; // 0 </code></pre> <p>You can also use division by <code>1</code>, <code>true / 1; // 1</code>, but I'd advise avoiding division where possible.</p> <p>Furthermore, many of the non-unary operators have an <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Assignment_Operators" rel="noreferrer"><strong>assignment version</strong></a> so if you have a variable you want converted, you can do it very quickly.</p> <p>You can see a comparison of the different methods with <a href="http://jsperf.com/bool-to-int-many" rel="noreferrer"><strong>this jsperf</strong></a>.</p>
2,700,311
Localization of icon and default screen in iPhone
<p>Can the app icon and default screen be localized in iPhone? Has anyone tried it?</p> <p>In theory it should be possible as they're just image resources, but I found no explicit mention of this in the documentation, and I wouldn't like to have my app rejected or failing for this.</p>
2,700,465
2
0
null
2010-04-23 16:38:24.36 UTC
11
2013-05-22 20:08:46.913 UTC
null
null
null
null
143,378
null
1
21
iphone|localization|icons
6,953
<p><a href="https://developer.apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html" rel="nofollow noreferrer">Official documentation</a> quote:</p> <p>"An iPhone application should be internationalized and have a language.lproj directory for each language it supports. In addition to providing localized versions of your application’s custom resources, you can also localize your application icon (Icon.png), default image (Default.png), and Settings icon (Icon-Settings.png) by placing files with the same name in your language-specific project directories. Even if you provide localized versions, however, you should always include a default version of these files at the top-level of your application bundle. The default version is used in situations where a specific localization is not available."</p>
27,025,618
How to handle multiple submit buttons in a form using Angular JS?
<p>I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form and then reset it - allowing them to enter another entry.</p> <p>How do I accomplish this in angular? I was thinking I could have two submit buttons with ng-click tags, but I'm using ng-submit on the form element. Is there any reason I NEED to be using ng-submit - I can't remember why I started using that instead of ng-click on the button.</p> <p>The code looks something like:</p> <pre><code>&lt;div ng-controller="SomeController"&gt; &lt;form ng-submit="save(record)"&gt; &lt;input type="text" name="shoppingListItem" ng-model="record.shoppingListItem"&gt; &lt;button type="submit"&gt;Save&lt;/button&gt; &lt;button type="submit"&gt;Save and Add Another&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>And in the controller <code>SomeController</code></p> <pre><code>$scope.record = {}; $scope.save = function (record) { $http.post('/api/save', record). success(function(data) { // take action based off which submit button pressed }); } </code></pre>
27,025,886
7
0
null
2014-11-19 19:45:13.45 UTC
2
2018-09-19 13:18:58.94 UTC
2016-11-23 17:55:22.947 UTC
null
323,041
null
128,532
null
1
24
javascript|angularjs|forms
48,310
<p><code>ngSubmit</code> allows you to press <code>Enter</code> while typing on the textbox to submit. If that behavior isn't important, just use 2 <code>ngClick</code>. If it is important, you can modify the second button to use <code>ngClick</code>. So your code becomes:</p> <pre><code>&lt;div ng-controller="SomeController"&gt; &lt;form ng-submit="save(record)"&gt; &lt;input type="text" name="shoppingListItem" ng-model="record.shoppingListItem"&gt; &lt;button type="submit"&gt;Save&lt;/button&gt; &lt;button ng-click="saveAndAdd(record)"&gt;Save and Add Another&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
27,823,273
Counting frequency of values by date using pandas
<p>Let's suppose I have following Time Series:</p> <pre><code>Timestamp Category 2014-10-16 15:05:17 Facebook 2014-10-16 14:56:37 Vimeo 2014-10-16 14:25:16 Facebook 2014-10-16 14:15:32 Facebook 2014-10-16 13:41:01 Facebook 2014-10-16 12:50:30 Orkut 2014-10-16 12:28:54 Facebook 2014-10-16 12:26:56 Facebook 2014-10-16 12:25:12 Facebook ... 2014-10-08 15:52:49 Youtube 2014-10-08 15:04:50 Youtube 2014-10-08 15:03:48 Vimeo 2014-10-08 15:02:27 Youtube 2014-10-08 15:01:56 DailyMotion 2014-10-08 13:27:28 Facebook 2014-10-08 13:01:08 Vimeo 2014-10-08 12:52:06 Facebook 2014-10-08 12:43:27 Facebook Name: summary, Length: 600 </code></pre> <p>I would like to make a count of each category (Unique Value/Factor in the Time Series) per week and year.</p> <pre><code>Example: Week/Year Category Count 1/2014 Facebook 12 1/2014 Google 5 1/2014 Youtube 2 ... 2/2014 Facebook 2 2/2014 Google 5 2/2014 Youtube 20 ... </code></pre> <p>How can this be achieved using Python pandas?</p>
27,823,917
3
0
null
2015-01-07 15:52:45.007 UTC
12
2017-09-17 08:42:49.137 UTC
2017-09-17 08:41:43.143 UTC
null
3,923,281
null
401,056
null
1
33
pandas|datetime|dataframe|count|time-series
45,815
<p>It might be easiest to turn your Series into a DataFrame and use Pandas' <code>groupby</code> functionality (if you already have a DataFrame then skip straight to adding another column below). </p> <p>If your Series is called <code>s</code>, then turn it into a DataFrame like so:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'Timestamp': s.index, 'Category': s.values}) &gt;&gt;&gt; df Category Timestamp 0 Facebook 2014-10-16 15:05:17 1 Vimeo 2014-10-16 14:56:37 2 Facebook 2014-10-16 14:25:16 ... </code></pre> <p>Now add another column for the week and year (one way is to use <code>apply</code> and generate a string of the week/year numbers):</p> <pre><code>&gt;&gt;&gt; df['Week/Year'] = df['Timestamp'].apply(lambda x: "%d/%d" % (x.week, x.year)) &gt;&gt;&gt; df Timestamp Category Week/Year 0 2014-10-16 15:05:17 Facebook 42/2014 1 2014-10-16 14:56:37 Vimeo 42/2014 2 2014-10-16 14:25:16 Facebook 42/2014 ... </code></pre> <p>Finally, group by <code>'Week/Year'</code> and <code>'Category'</code> and aggregate with <code>size()</code> to get the counts. For the data in your question this produces the following:</p> <pre><code>&gt;&gt;&gt; df.groupby(['Week/Year', 'Category']).size() Week/Year Category 41/2014 DailyMotion 1 Facebook 3 Vimeo 2 Youtube 3 42/2014 Facebook 7 Orkut 1 Vimeo 1 </code></pre>
64,946,753
How to test if element exists?
<p>I want to check if inside my component exists a button.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, {useState} from 'react'; const Text = ({text}) =&gt; { const [state, setState]= useState(0); const add = () =&gt; { setState(state+1) }; return ( &lt;div&gt; &lt;h1&gt;Hello World&lt;/h1&gt; &lt;h2&gt;Hello {text}&lt;/h2&gt; &lt;h2&gt;Count {state}&lt;/h2&gt; &lt;button role="button" onClick={add}&gt;Increase&lt;/button&gt; &lt;/div&gt; ); }; export default Text;</code></pre> </div> </div> </p> <p>For that test i created:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>test('check counter', ()=&gt; { const { getByText } = render(&lt;Text /&gt;); const button = getByText("Increase"); expect(button.toBeTruthy()) });</code></pre> </div> </div> </p> <p>After running the test i get <code>TypeError: button.toBeTruthy is not a function</code>. Why this errror appears and how to solve the issue?</p>
64,947,022
3
0
null
2020-11-21 18:42:59.503 UTC
1
2021-05-10 12:30:09.07 UTC
2021-03-18 11:24:40.103 UTC
null
3,257,186
null
12,540,500
null
1
15
reactjs|react-testing-library
39,501
<p>You have a mistake; The toBeTruthy() is not a function from the button is a function from the expect method.</p> <pre><code> test('check counter', ()=&gt; { const { getByText } = render(&lt;Text /&gt;); const button = getByText(&quot;Increase&quot;); expect(button).toBeTruthy() }); </code></pre>
33,577,868
Filter Array Not in Another Array
<p>Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript</p> <p>First :</p> <pre><code>var obj1 = [{ "visible": "true", "id": 1 }, { "visible": "true", "id": 2 }, { "visible": "true", "id": 3 }, { "Name": "Test3", "id": 4 }]; </code></pre> <p>Second :</p> <pre><code>var obj2 = [ 2,3] </code></pre> <p>Now i need to filter obj1 based on obj2 and return items from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 <strong>Id</strong>)</p> <p>output:</p> <pre><code>[{ "visible": "true", "id": 1 }, { "Name": "Test3", "id": 4 }]; </code></pre>
33,577,903
3
0
null
2015-11-07 00:51:51.363 UTC
4
2022-03-04 09:53:19.443 UTC
null
null
null
null
1,481,690
null
1
36
javascript|knockout.js
46,878
<p>You can simply run through <code>obj1</code> using <code>filter</code> and use <code>indexOf</code> on <code>obj2</code> to see if it exists. <code>indexOf</code> returns <code>-1</code> if the value isn't in the array, and <code>filter</code> includes the item when the callback returns <code>true</code>.</p> <pre><code>var arr = obj1.filter(function(item){ return obj2.indexOf(item.id) === -1; }); </code></pre> <hr> <p>With newer ES syntax and APIs, it becomes simpler:</p> <pre><code>const arr = obj1.filter(i =&gt; !obj2.includes(i.id)) </code></pre>
30,245,990
How to merge two geometries or meshes using three.js r71?
<p>Here I bumped to the problem since I need to merge two geometries (or meshes) to one. Using the earlier versions of three.js there was a nice function:</p> <pre><code>THREE.GeometryUtils.merge(pendulum, ball); </code></pre> <p>However, it is not on the new version anymore.</p> <p>I tried to merge <code>pendulum</code> and <code>ball</code> with the following code:</p> <p><code>ball</code> is a mesh.</p> <pre><code>var ballGeo = new THREE.SphereGeometry(24,35,35); var ballMat = new THREE.MeshPhongMaterial({color: 0xF7FE2E}); var ball = new THREE.Mesh(ballGeo, ballMat); ball.position.set(0,0,0); var pendulum = new THREE.CylinderGeometry(1, 1, 20, 16); ball.updateMatrix(); pendulum.merge(ball.geometry, ball.matrix); scene.add(pendulum); </code></pre> <p>After all, I got the following error:</p> <pre><code>THREE.Object3D.add: object not an instance of THREE.Object3D. THREE.CylinderGeometry {uuid: "688B0EB1-70F7-4C51-86DB-5B1B90A8A24C", name: "", type: "CylinderGeometry", vertices: Array[1332], colors: Array[0]…}THREE.error @ three_r71.js:35THREE.Object3D.add @ three_r71.js:7770(anonymous function) @ pendulum.js:20 </code></pre>
30,246,157
5
0
null
2015-05-14 19:44:08.717 UTC
19
2022-08-04 03:35:28.463 UTC
2017-12-13 14:44:55.467 UTC
null
5,769,640
null
2,663,883
null
1
34
javascript|merge|three.js
48,464
<p>Finally, I found a possible solution. I am posting since it could be useful for somebody else while I wasted a lot of hours. The tricky thing is about manipulating the concept of meshes and geometries:</p> <pre><code>var ballGeo = new THREE.SphereGeometry(10,35,35); var material = new THREE.MeshPhongMaterial({color: 0xF7FE2E}); var ball = new THREE.Mesh(ballGeo, material); var pendulumGeo = new THREE.CylinderGeometry(1, 1, 50, 16); ball.updateMatrix(); pendulumGeo.merge(ball.geometry, ball.matrix); var pendulum = new THREE.Mesh(pendulumGeo, material); scene.add(pendulum); </code></pre>
49,673,660
Return ResponseEntity vs returning POJO
<p>My application is based on Spring Boot with some REST endpoints. Is there any difference between below return statements?</p> <ul> <li><p><code>return new ResponseEntity&lt;MyBean&gt;(myBean, HttpStatus.OK)</code> </p></li> <li><p><code>return myBean;</code></p></li> </ul> <p>Is there any best practice guidelines or any technical difference?</p>
49,673,748
2
0
null
2018-04-05 13:31:07.643 UTC
8
2019-03-14 12:54:19.453 UTC
2019-03-14 12:54:19.453 UTC
null
1,426,227
null
1,573,161
null
1
31
rest|spring-boot
13,861
<p><a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html" rel="noreferrer"><code>ResponseEntity&lt;T&gt;</code></a> represents the <strong>entire HTTP response</strong>. Besides the <em>body</em>, its API allows you to set <em>headers</em> and a <em>status code</em> to the response.</p> <p>Returning just a bean is fine but doesn't give you much flexibility: In the future, if you need to add a header to the response or modify the status code, for example, you need to change the method return type.</p> <p>For more details on return values, refer to the Spring MVC <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-return-types" rel="noreferrer">documentation</a>.</p>
31,942,048
When to use the "identity" tmp trick?
<p>I have seen this meta function used, but never really understod why and in what context it is required. Can someone explain it with an example?</p> <pre><code>template &lt;typename T&gt; struct identity { using type = T; }; </code></pre>
31,943,182
2
0
null
2015-08-11 12:38:36.687 UTC
13
2018-12-01 18:31:36.477 UTC
2015-08-11 12:40:23.857 UTC
null
3,953,764
null
5,082,245
null
1
22
c++
1,834
<h3>Trick #1</h3> <p>Prevents template argument deduction:</p> <pre><code>template &lt;typename T&gt; void non_deducible(typename identity&lt;T&gt;::type t) {} non_deducible(1); // error non_deducible&lt;int&gt;(1); // ok template &lt;typename T&gt; void first_deducible(T a, typename identity&lt;T&gt;::type b) {} first_deducible(5, 'A'); // ok </code></pre> <hr> <h3>Trick #2</h3> <p>Disables unsafe/unwanted implicit deduction guides (<a href="/questions/tagged/c%2b%2b17" class="post-tag" title="show questions tagged &#39;c++17&#39;" rel="tag">c++17</a>):</p> <pre><code>template &lt;typename T&gt; struct smart_ptr { smart_ptr(typename identity&lt;T&gt;::type* ptr) {} }; smart_ptr{new int[10]}; // error smart_ptr&lt;int&gt;{new int}; // ok </code></pre> <hr> <h3>Trick #3</h3> <p>Makes defining type-traits (and other metafunctions) easier:</p> <pre><code>template &lt;typename T&gt; struct remove_pointer : identity&lt;T&gt; {}; template &lt;typename T&gt; struct remove_pointer&lt;T*&gt; : identity&lt;T&gt; {}; </code></pre> <hr> <h3>Trick #4</h3> <p>Can be used for tag dispatching:</p> <pre><code>void foo(identity&lt;std::vector&lt;int&gt;&gt;) {} void foo(identity&lt;std::list&lt;int&gt;&gt;) {} template &lt;typename T&gt; void bar(T t) { foo(identity&lt;T&gt;{}); } </code></pre> <hr> <h3>Trick #5</h3> <p>Can be used for <em>returning</em> types:</p> <pre><code>template &lt;int I&gt; constexpr auto foo() { if constexpr (I == 0) return identity&lt;int&gt;{}; else return identity&lt;float&gt;{}; } decltype(foo&lt;1&gt;())::type i = 3.14f; </code></pre> <hr> <h3>Trick #6</h3> <p>Helps to specialize functions accepting a forwarding-reference:</p> <pre><code>template &lt;typename T, typename U&gt; void foo(T&amp;&amp; t, identity&lt;std::vector&lt;U&gt;&gt;) {} template &lt;typename T&gt; void foo(T&amp;&amp; t) { foo(std::forward&lt;T&gt;(t), identity&lt;std::decay_t&lt;T&gt;&gt;{}); } foo(std::vector&lt;int&gt;{}); </code></pre> <hr> <h3>Trick #7</h3> <p>Provides alternative syntax for declaring types, e.g. pointers/references:</p> <pre><code>int foo(char); identity&lt;int(char)&gt;::type* fooPtr = &amp;foo; // int(*fooPtr)(char) identity&lt;const char[4]&gt;::type&amp; strRef = "foo"; // const char(&amp;strRef)[4] </code></pre> <hr> <h3>Trick #8</h3> <p>Can be used as a wrapper for code expecting nested <code>T::type</code> to exist or deferring its evaluation:</p> <pre><code>struct A {}; struct B { using type = int; }; std::conditional&lt;has_type&lt;A&gt;, A, identity&lt;float&gt;&gt;::type::type; // float std::conditional&lt;has_type&lt;B&gt;, B, identity&lt;float&gt;&gt;::type::type; // B </code></pre> <hr> <h3>Trick #9</h3> <p>In the past, it used to serve as a workaround for a missing scope operator from the <code>decltype()</code> specifier:</p> <pre><code>std::vector&lt;int&gt; v; identity&lt;decltype(v)&gt;::type::value_type i; // nowadays one can say just decltype(v)::value_type </code></pre> <hr> <p>The <code>identity</code> utility is <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0887r1.pdf" rel="noreferrer">proposed</a> to be added to <a href="/questions/tagged/c%2b%2b20" class="post-tag" title="show questions tagged &#39;c++20&#39;" rel="tag">c++20</a>:</p> <pre><code>namespace std { template &lt;typename T&gt; struct type_identity { using type = T; }; template &lt;typename T&gt; using type_identity_t = typename type_identity&lt;T&gt;::type; } </code></pre>
28,099,892
How to evaluate single integrals of multivariate functions with Python's scipy.integrate.quad?
<p>There is a function I am trying to integrate in Python using <code>scipy.integrate.quad</code>. This particular function takes two arguments. There is only one argument I want to integrate over. An example is shown below.</p> <pre><code>from scipy import integrate as integrate def f(x,a): #a is a parameter, x is the variable I want to integrate over return a*x result = integrate.quad(f,0,1) </code></pre> <p>This example doesn't work (as is likely clear to you) since, as Python reminds me when I try it:</p> <pre><code>TypeError: f() takes exactly 2 arguments (1 given) </code></pre> <p>I am wondering how to use <code>integrate.quad()</code> to integrate in a single variable sense when the function given is, in general, a multi-variable function, with the extra variables providing parameters to the function.</p>
28,099,926
2
0
null
2015-01-22 22:34:57.717 UTC
9
2015-01-22 22:46:17.697 UTC
null
null
null
null
2,457,243
null
1
16
python|scipy
20,553
<p>Found the answer in <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html" rel="noreferrer">the scipy documentation</a>.</p> <p>You can do the following:</p> <pre><code>from scipy import integrate as integrate def f(x,a): #a is a parameter, x is the variable I want to integrate over return a*x result = integrate.quad(f,0,1,args=(1,)) </code></pre> <p>The <code>args=(1,)</code> argument in the <code>quad</code> method will make <code>a=1</code> for the integral evalution.</p> <p>This can also be carried to functions with more than two variables:</p> <pre><code>from scipy import integrate as integrate def f(x,a,b,c): #a is a parameter, x is the variable I want to integrate over return a*x + b + c result = integrate.quad(f,0,1,args=(1,2,3)) </code></pre> <p>This will make <code>a=1, b=2, c=3</code> for the integral evaluation.</p> <p>The important thing to remember for the function you want to integrate this way is to make the variable you want to integrate over the <em>first</em> argument to the function.</p>
2,998,655
How to isolate a single element from a scraped web page in R
<p>I want to use R to scrape this page: (<a href="http://www.fifa.com/worldcup/archive/germany2006/results/matches/match=97410001/report.html" rel="nofollow noreferrer">http://www.fifa.com/worldcup/archive/germany2006/results/matches/match=97410001/report.html</a> ) and others, to get the goal scorers and times.</p> <p>So far, this is what I've got:</p> <pre><code>require(RCurl) require(XML) theURL &lt;-"http://www.fifa.com/worldcup/archive/germany2006/results/matches/match=97410001/report.html" webpage &lt;- getURL(theURL, header=FALSE, verbose=TRUE) webpagecont &lt;- readLines(tc &lt;- textConnection(webpage)); close(tc) pagetree &lt;- htmlTreeParse(webpagecont, error=function(...){}, useInternalNodes = TRUE) </code></pre> <p>and the pagetree object now contains a pointer to my parsed html (I think). The part I want is:</p> <pre><code>&lt;div class="cont")&lt;ul&gt; &lt;div class="bold medium"&gt;Goals scored&lt;/div&gt; &lt;li&gt;Philipp LAHM (GER) 6', &lt;/li&gt; &lt;li&gt;Paulo WANCHOPE (CRC) 12', &lt;/li&gt; &lt;li&gt;Miroslav KLOSE (GER) 17', &lt;/li&gt; &lt;li&gt;Miroslav KLOSE (GER) 61', &lt;/li&gt; &lt;li&gt;Paulo WANCHOPE (CRC) 73', &lt;/li&gt; &lt;li&gt;Torsten FRINGS (GER) 87'&lt;/li&gt; &lt;/ul&gt;&lt;/div&gt; </code></pre> <p>But I'm now lost as to how to isolate them, and frankly <code>xpathSApply</code> and <code>xpathApply</code> confuse the beejeebies out of me!</p> <p>So, does anyone know how to formulate a command to suck out the element contained within the <code>&lt;div class="cont"&gt;</code> tags?</p>
2,998,896
1
1
null
2010-06-08 15:14:21.67 UTC
9
2013-09-05 00:07:51.6 UTC
2013-09-05 00:07:51.6 UTC
null
2,077,901
null
74,658
null
1
12
xml|r|web-scraping|rcurl
4,028
<p>These questions are very helpful when dealing with web scraping and XML in R:</p> <ol> <li><a href="https://stackoverflow.com/questions/1395528/scraping-html-tables-into-r-data-frames-using-the-xml-package">Scraping html tables into R data frames using the XML package</a></li> <li><a href="https://stackoverflow.com/questions/2067098/how-to-transform-xml-data-into-a-data-frame">How to transform XML data into a data.frame?</a></li> </ol> <p>With regards to your particular example, while I'm not sure what you want the output to look like, this gets the "goals scored" as a character vector:</p> <pre><code>theURL &lt;-"http://www.fifa.com/worldcup/archive/germany2006/results/matches/match=97410001/report.html" fifa.doc &lt;- htmlParse(theURL) fifa &lt;- xpathSApply(fifa.doc, "//*/div[@class='cont']", xmlValue) goals.scored &lt;- grep("Goals scored", fifa, value=TRUE) </code></pre> <p>The <code>xpathSApply</code> function gets all the values that match the given criteria, and returns them as a vector. Note how I'm looking for a div with class='cont'. Using class values is frequently a good way to parse an HTML document because they are good markers.</p> <p>You can clean this up however you want:</p> <pre><code>&gt; gsub("Goals scored", "", strsplit(goals.scored, ", ")[[1]]) [1] "Philipp LAHM (GER) 6'" "Paulo WANCHOPE (CRC) 12'" "Miroslav KLOSE (GER) 17'" "Miroslav KLOSE (GER) 61'" "Paulo WANCHOPE (CRC) 73'" [6] "Torsten FRINGS (GER) 87'" </code></pre>
21,223,164
Multiplying two inputs with JavaScript & displaying in text box
<p>I am new to JavaScript &amp; am looking for some help doing simple multiplication of two numbers &amp; displaying the result in another text box. I have been trying to get this working for days to no avail :(</p> <p>Here is the basic HTML along with the JavaScript &amp; a link to a fiddle here <a href="http://jsbin.com/egeKAXif/1/edit" rel="noreferrer">http://jsbin.com/egeKAXif/1/edit</a></p> <p>What am I doing wrong?</p> <p>The application I want to write will have at least 12 rows, how would I extend the JavaScript / HTML to accommodate this? Would each input identifier need to be unique?</p> <p>Any help appreciated :)</p> <pre><code> &lt;table width="80%" border="0"&gt; &lt;tr&gt; &lt;th&gt;Box 1&lt;/th&gt; &lt;th&gt;Box 2&lt;/th&gt; &lt;th&gt;Result&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input id="box1" type="text" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="box2" type="text" onchange="calculate()" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="result" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;script&gt; function calculate() { var myBox1 = document.getElementById('box1').value; var myBox2 = document.getElementById('box2').value; var result = document.getElementById('result'); var myResult = box1 * box2; result.innerHTML = myResult; } &lt;/script&gt; </code></pre>
21,223,332
2
0
null
2014-01-19 21:52:34.073 UTC
5
2019-09-26 20:59:18.01 UTC
null
null
null
null
3,213,157
null
1
9
javascript
84,815
<p>The first thing you have got to change is the line with the multiplication. It should be: <code>var myResult = myBox1 * myBox2;</code></p> <p>You should not use innerHTML with input fields - use value.</p> <p>Additional to that, the <code>onchange</code> event fires only when the input looses the focus. You might want to use the <code>oninput</code> event.</p> <p>Take a look at the working example: <a href="http://jsbin.com/OJOlARe/1/edit" rel="noreferrer">http://jsbin.com/OJOlARe/1/edit</a></p>
37,333,165
Plot specific rows of a pandas dataframe
<p>I have a pandas dataframe with three columns and I am plotting each column separately using the following code:</p> <pre><code>data.plot(y='value') </code></pre> <p>Which generates a figure like this one:</p> <p><a href="https://i.stack.imgur.com/3UeYf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3UeYf.png" alt="enter image description here"></a></p> <p>What I need is a subset of these values and not all of them. For example, I want to plot values at rows 500 to 1000 and not from 0 to 3500. Any idea how I can tell the plot function to only pick those?</p> <p>Thanks</p>
37,333,192
2
0
null
2016-05-19 20:14:10.633 UTC
3
2020-03-15 21:58:30.127 UTC
2018-01-30 15:00:14.907 UTC
null
2,827,771
null
2,827,771
null
1
19
python|pandas|plot
79,879
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="noreferrer"><code>iloc</code></a> to slice your df:</p> <pre><code>data.iloc[499:999].plot(y='value') </code></pre> <p>this will slice from row 500 up to but not including row 1000</p> <p>Example:</p> <pre><code>In [35]: df = pd.DataFrame(np.random.randn(10,2), columns=list('ab')) df.iloc[2:6] Out[35]: a b 2 0.672884 0.202798 3 0.514998 1.744821 4 -1.982109 -0.770861 5 1.364567 0.341882 df.iloc[2:6].plot(y='b') </code></pre> <p><a href="https://i.stack.imgur.com/bkQjP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bkQjP.png" alt="enter image description here"></a></p>
25,809,332
When should I wrap variables with ${...} in CMake?
<p>I wonder why often variables in CMake are wrapped with a dollar sign and curly brackets. For example, I saw this call <a href="https://github.com/LaurentGomila/SFML/wiki/Tutorial:-Build-your-SFML-project-with-CMake" rel="noreferrer">in a CMake tutorial</a>.</p> <pre><code>include_directories(${PROJECT_BINARY_DIR}) </code></pre> <p>But from what I tried, this does the same thing.</p> <pre><code>include_directories(PROJECT_BINARY_DIR) </code></pre> <p>When is the wrapping with <code>${...}</code> needed and what does it mean? Why are variables often wrapped with this even if it makes no difference?</p>
25,809,646
2
0
null
2014-09-12 13:20:47.297 UTC
10
2022-09-17 23:06:27.093 UTC
null
null
null
null
1,079,110
null
1
27
cmake
7,947
<p>Quoting <a href="http://www.cmake.org/cmake/help/latest/manual/cmake-language.7.html#variable-references" rel="nofollow noreferrer">the CMake documentation</a>:</p> <blockquote> <p>A <em>variable reference</em> has the form <code>${variable_name}</code> and is evaluated inside a Quoted Argument or an Unquoted Argument. A variable reference is replaced by the value of the variable, or by the empty string if the variable is not set.</p> </blockquote> <p>In other words, writing <code>PROJECT_BINARY_DIR</code> refers, literally, to the string &quot;PROJECT_BINARY_DIR&quot;. Encapsulating it in <code>${...}</code> gives you <em>the contents</em> of the variable with the name PROJECT_BINARY_DIR.</p> <p>Consider:</p> <pre><code>set(FOO &quot;Hello there!&quot;) message(FOO) # prints FOO message(${FOO}) # prints Hello there! </code></pre> <p>As you have probably guessed already, <code>include_directories(PROJECT_BINARY_DIR)</code> simply attempts to add a subdirectory of the name PROJECT_BINARY_DIR to the include directories. On most build systems, if no such directory exists, it will simply ignore the command, which might have tricked you into the impression that it works as expected.</p> <p>A popular source of confusion comes from the fact that <code>if()</code> does not require explicit dereferencing of variables:</p> <pre><code>set(FOO TRUE) if(FOO) message(&quot;Foo was set!&quot;) endif() </code></pre> <p>Again <a href="http://www.cmake.org/cmake/help/latest/command/if.html" rel="nofollow noreferrer">the documentation explains this behavior</a>:</p> <blockquote> <p><code>if(&lt;constant&gt;)</code></p> <p>True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number. False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND. Named boolean constants are case-insensitive. If the argument is not one of these constants, it is treated as a variable.</p> <p><code>if(&lt;variable&gt;)</code></p> <p>True if the variable is defined to a value that is not a false constant. False otherwise. (Note macro arguments are not variables.)</p> </blockquote> <p>In particular, one can come up with weird examples like:</p> <pre><code>unset(BLA) set(FOO &quot;BLA&quot;) if(FOO) message(&quot;if(&lt;variable&gt;): True&quot;) else() message(&quot;if(&lt;variable&gt;): False&quot;) endif() if(${FOO}) message(&quot;if(&lt;constant&gt;): True&quot;) else() message(&quot;if(&lt;constant&gt;): False&quot;) endif() </code></pre> <p>Which will take the <code>TRUE</code> branch in the variable case, and the <code>FALSE</code> branch in the constant case. This is due to the fact that in the constant case, CMake will go look for a variable <code>BLA</code> to perform the check on (which is not defined, hence we end up in the FALSE branch).</p>
7,308,058
Best Resources for UIAutomation Testing for iOS Applications
<p>Testing with UIAutomation on Instruments is great, however, the documentation and resources around it are either non-existent or in hiding. What are the best resources (documentation, blog posts, Stack Overflow questions) that have helped you in implementing this on your projects? Are there any good open source testing scripts in the wild?</p>
7,309,798
1
2
null
2011-09-05 12:26:45.037 UTC
12
2011-09-05 16:49:23.507 UTC
2011-09-05 16:49:23.507 UTC
null
765,031
null
765,031
null
1
16
iphone|ios|automated-tests|instruments|ios-ui-automation
9,925
<p>As I point out in <a href="https://stackoverflow.com/questions/5393190/is-there-a-good-tutorial-on-cocoa-touch-automated-ui-testing/5409640#5409640">my answer</a> to <a href="https://stackoverflow.com/questions/5393190/is-there-a-good-tutorial-on-cocoa-touch-automated-ui-testing">this similar question</a>, I covered UI Automation as part of my recent course on advanced iPhone development. The video for the "Testing" session that covers this instrument can be found for free <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=407243028" rel="nofollow noreferrer">on iTunes U</a>, and the course notes on UI Automation, along with sample scripts, are available <a href="http://www.sunsetlakesoftware.com/sites/default/files/Fall2010CourseNotes/ui%20automation.html" rel="nofollow noreferrer">here</a>.</p> <p>If you have access to the <a href="http://developer.apple.com/videos/wwdc/2010/" rel="nofollow noreferrer">WWDC 2010 videos</a>, make sure to watch session 306 - "Automating User Interface Testing with Instruments". That was my first introduction to the topic, and they do a great job of running through the core concepts. </p> <p>In addition, James Turner's "<a href="http://answers.oreilly.com/topic/1646-how-to-use-uiautomation-to-create-iphone-ui-tests/" rel="nofollow noreferrer">How to use UIAutomation to create iPhone UI tests</a>" and Alex Vollmer's "<a href="http://alexvollmer.com/posts/2010/07/03/working-with-uiautomation/" rel="nofollow noreferrer">Working with UIAutomation</a>" are both write-ups that I've found useful.</p> <p>Finally, the <a href="/questions/tagged/ui-automation" class="post-tag" title="show questions tagged &#39;ui-automation&#39;" rel="tag">ui-automation</a> tag here on Stack Overflow contains many useful scripts and specific examples of UI Automation in action.</p>
24,547,555
How to analyze memory using android studio
<p>Recently switch to android studio from eclipse. How to check app heap and memory allocation in android studio? In Eclipse we have MAT is there anything in the studio to check heap dump, hprof file?</p>
24,547,957
10
0
null
2014-07-03 07:28:04.067 UTC
52
2021-08-10 09:01:35.973 UTC
2021-08-10 09:01:35.973 UTC
null
5,459,839
null
559,379
null
1
74
android|android-studio|profiling|heap-memory
70,630
<p>I'll explain it in an easy way with steps:</p> <ol> <li><p>First, you have install <strong>MAT</strong> ( <a href="http://www.eclipse.org/mat/downloads.php" rel="noreferrer">download</a> ) or use:</p> <blockquote> <p>brew cask install memoryanalyzer</p> </blockquote></li> <li><p>In Android Studio open Android Device Monitor or DDMS.</p></li> <li><p>Select your process "com.example.etc.."</p></li> <li><p>Click Update Heap above the process list.</p></li> <li><p>In the right-side panel, select the Heap tab.</p></li> <li><p>Click in Cause GC.</p></li> <li><p>Click Dump HPROF file above the process list.</p></li> <li><p>When we downloaded the file HPROF, we have to open the Terminal and run this command to generate the file to open it with MAT.</p></li> <li><p>Open terminal and run this command </p></li> </ol> <blockquote> <p>./hprof-conv path/file.hprof exitPath/heap-converted.hprof</p> </blockquote> <p>The command "hprof-conv" is in the platform-tools folder of the sdk.</p> <ol start="10"> <li>And ready and MAT can open and open the converted file ( heap-converted.hprof ) .</li> </ol>
39,006,349
Defining a UDF that accepts an Array of objects in a Spark DataFrame?
<p>When working with Spark's DataFrames, User Defined Functions (UDFs) are required for mapping data in columns. UDFs require that argument types are explicitly specified. In my case, I need to manipulate a column that is made up of arrays of objects, and I do not know what type to use. Here's an example:</p> <pre><code>import sqlContext.implicits._ // Start with some data. Each row (here, there's only one row) // is a topic and a bunch of subjects val data = sqlContext.read.json(sc.parallelize(Seq( """ |{ | "topic" : "pets", | "subjects" : [ | {"type" : "cat", "score" : 10}, | {"type" : "dog", "score" : 1} | ] |} """))) </code></pre> <p>It's relatively straightforward to use the built-in <code>org.apache.spark.sql.functions</code> to perform basic operations on the data in the columns</p> <pre><code>import org.apache.spark.sql.functions.size data.select($"topic", size($"subjects")).show +-----+--------------+ |topic|size(subjects)| +-----+--------------+ | pets| 2| +-----+--------------+ </code></pre> <p>and it's generally easy to write custom UDFs to perform arbitrary operations</p> <pre><code>import org.apache.spark.sql.functions.udf val enhance = udf { topic : String =&gt; topic.toUpperCase() } data.select(enhance($"topic"), size($"subjects")).show +----------+--------------+ |UDF(topic)|size(subjects)| +----------+--------------+ | PETS| 2| +----------+--------------+ </code></pre> <p>But what if I want to use a UDF to manipulate the array of objects in the "subjects" column? What type do I use for the argument in the UDF? For example, if I want to reimplement the size function, instead of using the one provided by spark:</p> <pre><code>val my_size = udf { subjects: Array[Something] =&gt; subjects.size } data.select($"topic", my_size($"subjects")).show </code></pre> <p>Clearly <code>Array[Something]</code> does not work... what type should I use!? Should I ditch <code>Array[]</code> altogether? Poking around tells me <code>scala.collection.mutable.WrappedArray</code> may have something to do with it, but still there's another type I need to provide. </p>
39,006,468
1
0
null
2016-08-17 21:11:23.793 UTC
9
2019-02-18 06:50:47.143 UTC
2018-12-17 10:33:52.26 UTC
null
1,560,062
null
4,347,717
null
1
30
scala|apache-spark|dataframe|apache-spark-sql|user-defined-functions
24,045
<p>What you're looking for is <code>Seq[o.a.s.sql.Row]</code>:</p> <pre><code>import org.apache.spark.sql.Row val my_size = udf { subjects: Seq[Row] =&gt; subjects.size } </code></pre> <p><strong>Explanation</strong>:</p> <ul> <li>Current representation of <code>ArrayType</code> is, as you already know, <code>WrappedArray</code> so <code>Array</code> won't work and it is better to stay on the safe side.</li> <li><a href="https://spark.apache.org/docs/2.3.2/sql-programming-guide.html#data-types" rel="noreferrer">According to the official specification</a>, the local (external) type for <code>StructType</code> is <code>Row</code>. Unfortunately it means that access to the individual fields is not type safe.</li> </ul> <p><strong>Notes</strong>:</p> <ul> <li><p>To create <code>struct</code> in Spark &lt; 2.3, function passed to <code>udf</code> has to return <code>Product</code> type (<code>Tuple*</code> or <code>case class</code>), not <code>Row</code>. That's because corresponding <code>udf</code> variants <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$" rel="noreferrer">depend on Scala reflection</a>:</p> <blockquote> <p>Defines a Scala closure of <em>n</em> arguments as user-defined function (UDF). The data types are automatically inferred based on the Scala closure's signature.</p> </blockquote></li> <li><p>In Spark >= 2.3 it is possible to return <code>Row</code> directly, <a href="https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$@udf(f:AnyRef,dataType:org.apache.spark.sql.types.DataType):org.apache.spark.sql.expressions.UserDefinedFunction" rel="noreferrer">as long as the schema is provided</a>.</p> <blockquote> <p><code>def udf(f: AnyRef, dataType: DataType): UserDefinedFunction</code> Defines a deterministic user-defined function (UDF) using a Scala closure. For this variant, the caller must specify the output data type, and there is no automatic input type coercion. </p> </blockquote> <p>See for example <a href="https://stackoverflow.com/q/50949384">How to create a Spark UDF in Java / Kotlin which returns a complex type?</a>.</p></li> </ul>
2,589,711
Find full path of the Python interpreter?
<p>How do I find the full path of the currently running Python interpreter from within the currently executing Python script?</p>
2,589,722
3
0
null
2010-04-07 02:50:25.927 UTC
77
2022-02-11 03:11:17.307 UTC
2016-10-16 08:58:22.18 UTC
null
63,550
null
51,167
null
1
556
python|path
374,243
<p><code>sys.executable</code> contains full path of the currently running Python interpreter.</p> <pre class="lang-py prettyprint-override"><code>import sys print(sys.executable) </code></pre> <p>which is now <a href="https://docs.python.org/library/sys.html" rel="noreferrer">documented here</a></p>
37,292,167
PHP Laravel: How to set or get Session Data?
<p>I want to store some data in session for some testing purpose. I have written the session code also in controller. But in console.log ->resources -> session I couldn't find any value which I stored. If anyone help me to find the mistake which I have done in my controller please.</p> <p>Here is my controller:</p> <pre><code>&lt;?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Department; use App\Http\Requests; use Cookie; use Tracker; use Session; public function postdepartmentSave(Request $request) { $this-&gt;validate($request,[ 'code' =&gt; 'required|min:2|max:7|unique:departments', 'name' =&gt; 'required|unique:departments', ]); $department = new Department(); $department-&gt;code = $request-&gt;Input(['code']); $department-&gt;name = $request-&gt;Input(['name']); $name= $department-&gt;name; Session::put('name', $name); dd($name); $department-&gt;save(); return redirect('departmentSavePage'); } </code></pre>
37,292,226
3
0
null
2016-05-18 06:47:40.533 UTC
6
2022-02-12 13:38:48.953 UTC
2016-05-18 07:54:41.147 UTC
null
6,196,521
null
6,196,521
null
1
16
php|laravel|session|laravel-5
112,299
<h2>Storing data</h2> <p>To store data, you can use:</p> <pre class="lang-php prettyprint-override"><code>Session::put('variableName', $value); </code></pre> <p>There is also another way, through the global helper:</p> <pre class="lang-php prettyprint-override"><code>session(['variableName' =&gt; $value]); </code></pre> <h2>Getting data</h2> <p>To get the variable, you'd use:</p> <pre class="lang-php prettyprint-override"><code>Session::get('variableName'); </code></pre>
308,588
Where can I find a "ESC/POS" Epson Barcode Test Program?
<p>I am struggling to get an Epson "ESC/POS" printer to print barcodes (Using Delphi) and want to test if the printer is not faulty. Do you know where I can find a program to print a barcode in "ESC/POS"? I suppose as a last resort an OPOS program will also be OK.</p> <p>Also, a demo Delphi Program that works will also be fine. All the Delphi snippets I have so far is not working.</p> <p>The printer I am using is an Epson TM-L60II</p>
308,829
2
3
null
2008-11-21 12:17:09.38 UTC
10
2015-06-27 19:31:08.68 UTC
2010-04-06 18:32:19.727 UTC
null
213,269
mm2010
3,535,708
null
1
9
delphi|barcode|point-of-sale|opos|epson
23,608
<p>I Have a full tests program written in Delphi 5 for the TMT88's but the source is abit big for here so here is the barcode bits</p> <p>Please note that as its snippets from the full object some vars/functions may be missing</p> <p>To get the barcode chars</p> <pre><code>{** * @param a ean13 barcode numeric value * @return the escpos code for the barcode print * Description uses escpos code, return code needed to print a ean13 barcode *} function TPrintEscPosToPort.getBarcodeEscPosCode(l_ean13:String):String; var l_return:String; begin l_return := CHR(29) + 'k' + CHR(67) + CHR(12); l_return := l_return + l_ean13; // Print bar code l_return := l_return + l_ean13; // Print bar code number under thge barcode Result := l_return end; </code></pre> <p>to print to a printer</p> <pre><code>{** * @param Printer Name, Item be printed, Cut the papers after the cut, #no of copies to print * @return boolen, true if it printed * Description prints a test page to the tysso printer *} function TPrintEscPosToPort.escPosPrint(const l_printer, l_textToPrint :String;l_cutPaper:Boolean=true;l_copies:integer=1): Boolean; var l_pPort,l_pName,l_tmp:String; i,x:integer; PrinterFile: TextFile; begin // set result to false so any thing other then a good print will be false Result:= FALSE; try //Find if the printer exists, else set to defult -1 i := Printer.Printers.IndexOf(l_printer); if (i &gt; -1) then begin Printer.PrinterIndex := i; l_pName := Printer.Printers[i]; //Get the printer name (incase its the defult and not the one passed) l_pPort := Self.getPrinterPort(l_pName) ; // get the port name from the reg end; // If true add headers and footers to the passed text if (Self.aPrintHeadersFooters) then begin l_tmp := Self.getHeader() + l_textToPrint + Self.GetFooter(); end else begin l_tmp := l_textToPrint; end; //Send the Document To the printer try for x:= 1 to l_copies do //Print multi-copies Begin //Assign the file to a tmp file in the printer port if (length(trim(l_pPort)) &gt; 0) then AssignFile(PrinterFile,l_pPort) else begin //only use if we cant get the port //(may look bad as ctrl codes are still in place) AssignPrn(PrinterFile); l_tmp := Self.stripEscPos(l_tmp); end; Rewrite(PrinterFile); try //Send the passed Text to the printer WriteLn(PrinterFile,l_tmp); if (Self.aPrinterReset) then WriteLn(PrinterFile,escReset); // Reset the printer alignment if (l_cutPaper) then WriteLn(PrinterFile,escFeedAndCut); //Cut the paper if needed finally CloseFile(PrinterFile); Result:= true; end; end; except end; except end; end; </code></pre> <p><strong>Update</strong></p> <p>Here is a lost of control code constants from the code above, hopefully the names are descriptive enough.</p> <pre><code>const escNewLine = chr(10); // New line (LF line feed) escUnerlineOn = chr(27) + chr(45) + chr(1); // Unerline On escUnerlineOnx2 = chr(27) + chr(45) + chr(2); // Unerline On x 2 escUnerlineOff = chr(27) + chr(45) + chr(0); // Unerline Off escBoldOn = chr(27) + chr(69) + chr(1); // Bold On escBoldOff = chr(27) + chr(69) + chr(0); // Bold Off escNegativeOn = chr(29) + chr(66) + chr(1); // White On Black On' escNegativeOff = chr(29) + chr(66) + chr(0); // White On Black Off esc8CpiOn = chr(29) + chr(33) + chr(16); // Font Size x2 On esc8CpiOff = chr(29) + chr(33) + chr(0); // Font Size x2 Off esc16Cpi = chr(27) + chr(77) + chr(48); // Font A - Normal Font esc20Cpi = chr(27) + chr(77) + chr(49); // Font B - Small Font escReset = chr(27) + chr(64); //chr(27) + chr(77) + chr(48); // Reset Printer escFeedAndCut = chr(29) + chr(86) + chr(65); // Partial Cut and feed escAlignLeft = chr(27) + chr(97) + chr(48); // Align Text to the Left escAlignCenter = chr(27) + chr(97) + chr(49); // Align Text to the Center escAlignRight = chr(27) + chr(97) + chr(50); // Align Text to the Right </code></pre>
3,145,980
How to Insert Double or Single Quotes
<p>I have a long list of names that I need to have quotes around (it can be double or single quotes) and I have about 8,000 of them. I have them in Excel without any quotes and I can copy all of the names and paste them no problem but there are still no quotes. I have looked and looked for an Excel formula to add quotes to the name in each row but I have had no luck. I have also tried some clever find and replace techniques but no have worked either. The format I am looking for is this:</p> <p>"Allen" or 'Allen'</p> <p>Any of those would work. I need this so I can store the info into a database. Any help is greatly appreciated. Thanks</p> <p><strong>PS:</strong></p> <p>I have found other people online needing the same thing done that I need done and this solution has worked for them but I do not know what do with it:</p> <blockquote> <p>You can fix it by using a range variable (myCell for example) and then use that to iterate the 'selection' collection of range objects, like so</p> </blockquote> <pre><code>Sub AddQuote() Dim myCell As Range For Each myCell In Selection If myCell.Value &lt;&gt; "" Then myCell.Value = Chr(34) &amp; myCell.Value End If Next myCell End Sub </code></pre> <p>Another solution that also worked for others was:</p> <pre><code>Sub OneUglyExport() Dim FileToSave, c As Range, OneBigOleString As String FileToSave = Application.GetSaveAsFilename Open FileToSave For Output As #1 For Each c In Selection If Len(c.Text) &lt;&gt; 0 Then _ OneBigOleString = OneBigOleString &amp; ", " &amp; Chr(34) &amp; Trim(c.Text) &amp; Chr(34) Next Print #1, Mid(OneBigOleString, 3, Len(OneBigOleString)) Close #1 End Sub </code></pre>
3,146,077
6
0
null
2010-06-30 01:49:31.323 UTC
14
2021-04-06 08:12:30.137 UTC
2021-04-06 08:12:30.137 UTC
null
4,592,583
null
317,740
null
1
31
excel|vba|double-quotes|single-quotes
207,479
<h3>To Create New Quoted Values from Unquoted Values</h3> <ul> <li>Column A contains the names.</li> <li>Put the following formula into Column B <code>= &quot;&quot;&quot;&quot; &amp; A1 &amp; &quot;&quot;&quot;&quot;</code></li> <li>Copy Column B and Paste Special -&gt; Values</li> </ul> <h3>Using a Custom Function</h3> <pre><code>Public Function Enquote(cell As Range, Optional quoteCharacter As String = &quot;&quot;&quot;&quot;) As Variant Enquote = quoteCharacter &amp; cell.value &amp; quoteCharacter End Function </code></pre> <p><code>=OfficePersonal.xls!Enquote(A1)</code></p> <p><code>=OfficePersonal.xls!Enquote(A1, &quot;'&quot;)</code></p> <p>To get permanent quoted strings, you will have to copy formula values and paste-special-values.</p>
2,866,358
Git: Checkout only files without repository?
<p>i'd like to just checkout the files without the .git files and the whole repository. It's because i'd like to manage a website (php &amp; html) with git and i'm looking for an easy way to update the files in the htdocs folder from the repository, without having the repository public. (now it's in the home-dir and is accessed via ssh, but i have to put the new files to htdocs manually.</p>
2,867,314
6
2
null
2010-05-19 14:22:00.713 UTC
14
2019-07-02 10:01:35.043 UTC
null
null
null
null
345,163
null
1
39
git
30,638
<p>The <a href="http://www.kernel.org/pub/software/scm/git/docs/git-archive.html" rel="noreferrer">git-archive</a> manpage contains the following example:</p> <blockquote> <p><code>git archive --format=tar --prefix=junk/ HEAD | (cd /var/tmp/ &amp;&amp; tar xf -)</code></p> <blockquote> <p>Create a tar archive that contains the contents of the latest commit on the current branch, and extract it in the '/var/tmp/junk' directory.</p> </blockquote> </blockquote> <p>Or you can use low level <a href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html" rel="noreferrer">git-checkout-index</a>, which manpage contains the following example:</p> <blockquote> <h2>Using git checkout-index to "export an entire tree"</h2> <blockquote> <p>The prefix ability basically makes it trivial to use '<code>git checkout-index</code>' as an "export as tree" function. Just read the desired tree into the index, and do</p> <pre><code> $ git checkout-index --prefix=git-export-dir/ -a </code></pre> <p><code>git checkout-index</code> will "export" the index into the specified directory.</p> <p>The final "/" is important. The exported name is literally just prefixed with the specified string.</p> </blockquote> </blockquote> <p>Or you can try to use <code>--work-tree</code> option to git wrapper, or GIT_WORK_TREE environment variable, e.g. by using "<code>git --work-tree=/somwehere/else checkout -- .</code>".</p>
2,421,995
How can I create a route constraint of type System.Guid?
<p>Can anyone point me in the right direction on how to map a route which requires two guids?</p> <p>ie. <a href="http://blah.com/somecontroller/someaction/" rel="noreferrer">http://blah.com/somecontroller/someaction/</a>{firstGuid}/{secondGuid}</p> <p>where both firstGuid and secondGuid are not optional and must be of type system.Guid?</p>
2,430,152
6
0
null
2010-03-11 01:44:02.63 UTC
9
2015-04-20 12:33:23.957 UTC
2011-12-09 02:15:18.483 UTC
null
5,640
null
206,463
null
1
40
asp.net-mvc|asp.net-mvc-routing
10,934
<p>Create a RouteConstraint like the following:</p> <pre><code>public class GuidConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (values.ContainsKey(parameterName)) { string stringValue = values[parameterName] as string; if (!string.IsNullOrEmpty(stringValue)) { Guid guidValue; return Guid.TryParse(stringValue, out guidValue) &amp;&amp; (guidValue != Guid.Empty); } } return false; }} </code></pre> <p>Next when adding the route :</p> <pre><code>routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}/{guid2}", new { controller = "YourController", action = "YourAction" }, new { guid1 = new GuidConstraint(), guid2 = new GuidConstraint() }); </code></pre>
2,657,268
What's the difference between compiled and interpreted language?
<p>After reading some material on this subject I'm still not sure what the difference between a compiled language and an interpreted language is. I was told this is one of the differences between Java and JavaScript. Would someone please help me in understanding it?</p>
2,657,453
7
0
null
2010-04-17 04:44:03.213 UTC
100
2020-07-20 08:02:21.323 UTC
2016-03-08 21:27:40.387 UTC
null
2,756,409
null
300,414
null
1
122
java|javascript|programming-languages
157,302
<blockquote> <p>What’s the difference between compiled and interpreted language?</p> </blockquote> <p><strong>The difference is <em>not</em> in the language; it is in the <em>implementation</em>.</strong></p> <p>Having got that out of my system, here's an answer:</p> <ul> <li><p>In a compiled implementation, the original program is translated into native machine instructions, which are executed directly by the hardware.</p></li> <li><p>In an interpreted implementation, the original program is translated into something else. Another program, called "the interpreter", then examines "something else" and performs whatever actions are called for. Depending on the language and its implementation, there are a variety of forms of "something else". From more popular to less popular, "something else" might be</p> <ul> <li><p>Binary instructions for a virtual machine, often called <em>bytecode</em>, as is done in Lua, Python, Ruby, Smalltalk, and many other systems (the approach was popularized in the 1970s by the UCSD P-system and UCSD Pascal)</p></li> <li><p>A tree-like representation of the original program, such as an abstract-syntax tree, as is done for many prototype or educational interpreters</p></li> <li><p>A tokenized representation of the source program, similar to Tcl</p></li> <li><p>The characters of the source program, as was done in MINT and TRAC</p></li> </ul></li> </ul> <p>One thing that complicates the issue is that <em>it is possible to translate (compile) bytecode into native machine instructions</em>. Thus, a successful intepreted implementation might eventually acquire a compiler. If the compiler runs dynamically, behind the scenes, it is often called a just-in-time compiler or JIT compiler. JITs have been developed for Java, JavaScript, Lua, and I daresay many other languages. At that point you can have a hybrid implementation in which some code is interpreted and some code is compiled.</p>
2,433,024
How to reload windows form without closing it using VB.NET?
<p>Can you please tell me how I can reload a windows form without closing it using VB.NET?</p>
2,433,038
8
0
null
2010-03-12 13:33:34.18 UTC
1
2022-06-22 23:41:32.65 UTC
2012-06-11 03:21:36.96 UTC
null
651,104
null
207,376
null
1
9
vb.net
110,879
<p>Put all your initialization code into a method and not the constructor or the Form.Load event and just call that method. This can also include the designer-generated InitializeComponent() method which sets up all controls on the form. You should remove all controls on the form as your first action in that method, though.</p>
2,920,116
check if a value is NULL or Less than 0 in one TSQL statement
<pre><code>ISNULL(SUM(MyTable.Total), 0) AS Total </code></pre> <p>How can I modify the above statement to also check if Total is less than 0 <strong>(zero)</strong>, such that If Total is NULL or less than 0 <strong>(negative)</strong>, I assign 0 to <strong>Total</strong> </p>
2,920,139
9
0
null
2010-05-27 10:03:41.923 UTC
2
2017-10-31 11:05:21.783 UTC
2016-05-26 05:57:27.12 UTC
null
1,156,018
null
77,121
null
1
15
sql-server-2005|tsql
63,642
<pre><code>CASE WHEN ISNULL(SUM(MyTable.Total), 0) &lt;= 0 THEN 0 ELSE SUM(MyTable.Total) END AS Total </code></pre>
2,931,573
Determining if two rays intersect
<p>I have two rays on a 2D plane that extend to infinity, but both have a starting point. They are both described by a starting point and a vector in the direction of the ray extending to infinity. I want to find out if the two rays intersect, but I don't need to know where they intersect (it's part of a collision detection algorithm).</p> <p>Everything I have looked at so far describes finding the intersection point of two lines or line segments. Is there a fast algorithm to solve this?</p>
2,931,703
9
11
null
2010-05-28 18:30:54.803 UTC
9
2021-06-24 11:15:46.55 UTC
2016-10-13 15:04:31.397 UTC
null
3,576,214
null
134,046
null
1
27
algorithm|math|geometry|intersection
30,429
<p>Given: two rays a, b with starting points (origin vectors) as, bs, and direction vectors ad, bd.</p> <p>The two lines intersect if there is an intersection point p:</p> <pre><code>p = as + ad * u p = bs + bd * v </code></pre> <p>If this equation system has a solution for u>=0 and v>=0 (the positive direction is what makes them rays), the rays intersect.</p> <p>For the x/y coordinates of the 2d vectors, this means:</p> <pre><code>p.x = as.x + ad.x * u p.y = as.y + ad.y * u p.x = bs.x + bd.x * v p.y = bs.y + bd.y * v </code></pre> <p>Further steps:</p> <pre><code>as.x + ad.x * u = bs.x + bd.x * v as.y + ad.y * u = bs.y + bd.y * v </code></pre> <p>Solving against v:</p> <pre><code>v := (as.x + ad.x * u - bs.x) / bd.x </code></pre> <p>Inserting and solving against u:</p> <pre><code>as.y + ad.y * u = bs.y + bd.y * ((as.x + ad.x * u - bs.x) / bd.x) u := (as.y*bd.x + bd.y*bs.x - bs.y*bd.x - bd.y*as.x ) / (ad.x*bd.y - ad.y*bd.x) </code></pre> <p>Calculate u, then calculate v, if both are positive the rays intersect, else not.</p>
3,180,375
select * vs select column
<p>If I just need 2/3 columns and I query <code>SELECT *</code> instead of providing those columns in select query, is there any performance degradation regarding more/less I/O or memory?</p> <p>The network overhead might be present if I do select * without a need.</p> <p>But in a select operation, does the database engine always pull atomic tuple from the disk, or does it pull only those columns requested in the select operation?</p> <p>If it always pulls a tuple then I/O overhead is the same.</p> <p>At the same time, there might be a memory consumption for stripping out the requested columns from the tuple, if it pulls a tuple.</p> <p>So if that's the case, select someColumn will have more memory overhead than that of select *</p>
3,180,412
12
8
null
2010-07-05 14:45:15.9 UTC
44
2019-05-06 18:12:00.25 UTC
2018-01-20 23:31:03.01 UTC
null
4,907,496
null
256,007
null
1
134
sql|performance
92,709
<p>It always pulls a tuple (except in cases where the table has been vertically segmented - broken up into columns pieces), so, to answer the question you asked, it doesn't matter from a performance perspective. However, for many other reasons, (below) you should always select specifically those columns you want, by name. </p> <p>It always pulls a tuple, because (in every vendors RDBMS I am familiar with), the underlying on-disk storage structure for everything (including table data) is based on defined <strong><em>I/O Pages</em></strong> (in SQL Server for e.g., each Page is 8 kilobytes). And every I/O read or write is by Page.. I.e., every write or read is a complete Page of data. </p> <p>Because of this underlying structural constraint, a consequence is that Each row of data in a database must always be on one and only one page. It cannot span multiple Pages of data (except for special things like blobs, where the actual blob data is stored in separate Page-chunks, and the actual table row column then only gets a pointer...). But these exceptions are just that, exceptions, and generally do not apply except in special cases ( for special types of data, or certain optimizations for special circumstances)<br> Even in these special cases, generally, the actual table row of data itself (which contains the pointer to the actual data for the Blob, or whatever), it must be stored on a single IO Page... </p> <p>EXCEPTION. The only place where <code>Select *</code> is OK, is in the sub-query after an <code>Exists</code> or <code>Not Exists</code> predicate clause, as in:</p> <pre><code> Select colA, colB From table1 t1 Where Exists (Select * From Table2 Where column = t1.colA) </code></pre> <p>EDIT: To address @Mike Sherer comment, Yes it is true, both technically, with a bit of definition for your special case, and aesthetically. First, even when the set of columns requested are a subset of those stored in some index, the query processor must fetch <em>every</em> column stored in that index, not just the ones requested, for the same reasons - ALL I/O must be done in pages, and index data is stored in IO Pages just like table data. So if you define "tuple" for an index page as the set of columns stored in the index, the statement is still true.<br> and the statement is true aesthetically because the point is that it fetches data based on what is stored in the I/O page, not on what you ask for, and this true whether you are accessing the base table I/O Page or an index I/O Page.</p> <p>For other reasons not to use <code>Select *</code>, see <a href="https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful">Why is <code>SELECT *</code> considered harmful?</a> :</p>
24,985,989
check if .one() is empty sqlAlchemy
<p>I am running a query based off of other ids for the query. The problem i have is that sometimes the query won't find a result. Instead of having the entire program crash, how can I check to see if the result will be None?</p> <p>This is the query I have:</p> <pre><code>sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).one() </code></pre> <p>When the code gets executed and no results are found, I get a NoResultFound exception</p> <pre><code>NoResultFound: No row was found for one() </code></pre> <p>is there a way to just skip the query if there is not going to be a result?</p> <p><strong><em>Found the solution on SO</em></strong>(couldn't find it before) <a href="https://stackoverflow.com/questions/18110033/getting-first-row-from-sqlalchemy">Getting first row from sqlalchemy</a></p>
24,986,025
3
0
null
2014-07-27 21:48:04.867 UTC
9
2021-06-24 00:50:33.987 UTC
2021-06-24 00:50:33.987 UTC
null
6,083,378
null
1,713,047
null
1
48
python|sqlalchemy
55,508
<p>Use <code>first()</code> function instead of <code>one()</code>. It will return None if there is no results.</p> <pre><code>sub_report_id = DBSession.query(TSubReport.ixSubReport).filter(and_(TSubReport.ixSection==sectionID[0], TSubReport.ixReport== reportID[0])).first() </code></pre> <p>see documentation <a href="https://docs.sqlalchemy.org/en/stable/orm/query.html#sqlalchemy.orm.Query.first" rel="noreferrer">here</a></p>
42,445,703
git clone with https error - fatal: repository not found
<p>I forked a <strong>private</strong> repository that I was invited to collaborate on but every time I try to <strong>clone with HTTPS</strong>, I get the following error message:</p> <pre><code>$ git clone https://github.com/usernamex/privat-repo.git cloning into 'privat-repo'... Username for 'https://github.com':usernamex Password for 'https://[email protected]': remote: Repository not found. fatal: repository 'https://github.com/usernamex/privat-repo.git/' not found </code></pre> <hr> <p><code>Note: 'usernamex' and 'privat-repo' are just examples</code></p> <hr> <p>Here's some things I have tried with no success:</p> <ul> <li>Verified the validity of the URL - Checked spelling and case. I am able to access the repo URL and download its contents through my browser by clicking the <code>download ZIP</code> button. </li> <li>Asked owner to clone my fork - He had no problems cloning my fork but I do.</li> <li>Contacted GitHub support...</li> <li>Per GitHub support, <a href="https://help.github.com/articles/updating-credentials-from-the-osx-keychain/" rel="noreferrer">cleared cached credentials</a> - this is confirmed by the fact that the system requires my username and password with <code>git clone</code> and <code>git push</code>. In fact, I can clone and push other (public) repositories in my account.</li> <li>Went through GitHub's <a href="https://help.github.com/enterprise/2.8/user/articles/https-cloning-errors/" rel="noreferrer">HTTPS Cloning Errors</a> guide with the exception of <strong>"Using SSH instead"</strong> because this doesn't really address the issue.</li> <li>Viewed similar questions in stackoverflow.com - tried most suggested answers (see above).</li> </ul> <p>I am running git 2.10 on a mac through Terminal and, as I mentioned, I am not interested in workarounds to HTTPS (e.g.: SSH or GitHub Desktop).</p> <p>Any ideas why this is happening?</p>
42,445,764
9
0
null
2017-02-24 18:21:33.35 UTC
5
2022-07-07 06:42:11.653 UTC
null
null
null
null
2,709,391
null
1
24
git|github|https|git-clone
69,801
<p><a href="https://help.github.com/en/github/using-git/which-remote-url-should-i-use#cloning-with-https-urls-recommended" rel="noreferrer">This Github document</a> reads:</p> <blockquote> <p>The <code>https://</code> clone URLs are available on all repositories, public and private.</p> </blockquote> <p>But since you are trying to access a private repository, authentication is required. One way is appending username and password the address as below:</p> <pre><code>git clone https://username:[email protected]/usernamex/privat-repo.git </code></pre> <p>But the <a href="https://help.github.com/en/github/using-git/which-remote-url-should-i-use#cloning-with-https-urls-recommended" rel="noreferrer">same page</a> reads:</p> <blockquote> <p>If you have enabled two-factor authentication, or if you are accessing an organization that uses SAML single sign-on (SSO), you must authenticate with a personal access token instead of your username and password for GitHub.</p> </blockquote> <p>If you have 2FA enabled, check <a href="https://help.github.com/articles/creating-an-access-token-for-command-line-use" rel="noreferrer">this page</a> for steps to generate a personal access token. Bear in mind that you should check full <code>repo</code> scope (as shown below) for your personal token.</p> <p><a href="https://i.stack.imgur.com/4ESGR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4ESGR.png" alt="enter image description here"></a></p>
10,524,990
Button or Link That Changes Page in Iframe
<p>I wish to make a link or button in a page that changes the page the iframe is on. It would be a local page:</p> <blockquote> <p>idreesinc.com/iframe.html</p> </blockquote> <p>and you can see what I have already here: </p> <blockquote> <p>idreesinc.com/research</p> </blockquote> <p>Help would be much appreciated as i have been looking for an answer for ages. Thanks!</p>
10,525,134
4
0
null
2012-05-09 22:27:37.103 UTC
4
2020-08-14 21:26:07.713 UTC
2016-03-02 13:02:52.57 UTC
null
773,259
null
1,373,771
null
1
5
javascript|html|button|iframe|hyperlink
55,590
<pre><code>&lt;script&gt; function setURL(url){ document.getElementById('iframe').src = url; } &lt;/script&gt; &lt;iframe id="iframe" src="idreesinc.com/research.html" /&gt; &lt;input type="button" onclick="setURL('URLHere')" /&gt; </code></pre>
10,733,641
What is a .pem file and How to use it?
<p>I am designing a new chrome extension and when I package it then I get 2 file: a <strong>.crx</strong> file and a <strong>.pem</strong> file.</p> <p>I want to distribuite my extension on my server ( shared ) and on Chrome webstore.</p> <p>Could you tell me what is a pem file and how to use it ?</p> <p>I can't find documentation about it.</p>
10,733,750
1
0
null
2012-05-24 08:17:44.503 UTC
4
2013-09-19 02:56:47.37 UTC
2012-05-24 08:24:22.887 UTC
null
244,413
null
244,413
null
1
20
google-chrome|google-chrome-extension|pem
52,070
<p><strong>The packager creates two files:</strong></p> <ul> <li>a <strong>.crx</strong> file, which is the actual extension that can be installed.</li> <li>a <strong>.pem</strong> file, which contains the private key.</li> </ul> <p><strong>You'll need the .pem later if you want to:</strong></p> <ul> <li>Update the extension</li> <li>Uploading a previously packaged extension to the Chrome Web Store (make sure that the file is called <strong>key.pem</strong> (<a href="https://groups.google.com/forum/?fromgroups=#!topic/chromium-extensions/3vvygtEajMQ" rel="noreferrer">more info</a>))</li> </ul> <p>So, do not lose your private key (<strong>.pem</strong>)!</p>
10,579,041
graphviz: Create new node with this same label
<p>I'm starting working with graphviz and I have problem with creating new nodes with this same label. For example for word "sentence" I would like to create graph with 8 nodes: s -> e -> n -> t -> e -> n -> c -> e Now I'm receiving graph with only 5 nodes (one "e" instead of 3 and one "n" instead of 2). I need to create more nodes with this same label (value).</p> <p>Example of my problem may be this image <a href="http://rdftwig.sourceforge.net/paper/diagrams/bfsdeep.png" rel="noreferrer">http://rdftwig.sourceforge.net/paper/diagrams/bfsdeep.png</a> where there are 2 nodes with value "C", "E" and "D".</p> <p>Is it possible? If it is possible how can I access in my example with word "sentence" first, second or third "e" node?</p>
10,579,155
2
0
null
2012-05-14 07:22:33.707 UTC
4
2018-01-20 12:59:39.337 UTC
2016-06-24 06:05:15.113 UTC
null
908,939
null
775,886
null
1
29
graphviz
13,112
<p>You could define your nodes explicitly and set the label for them. Then each node has an unique id, but can have the same labels. Consider this example:</p> <pre><code>strict graph G { 1 [label="A"]; 2 [label="B"]; 3 [label="B"]; 4 [label="A"]; 1 -- 2; 2 -- 3; 3 -- 4; } </code></pre> <p>which will output (with <code>dot</code>):</p> <p><img src="https://i.stack.imgur.com/DCUcj.png" alt="Nodes with same labels"></p>
6,052,341
Using a Django variable in a CSS file
<p>I am trying to create a <em>dynamic</em> CSS file using the Django templating engine or any other means.</p> <p>Currently, I have a CSS rule that looks like this:</p> <pre><code>background-image: url('http://static.example.com/example.png'); </code></pre> <p>Where <code>http://static.example.com</code> corresponds to the <code>STATIC_URL</code> variable in Python. Using the Django templating engine, I could theoretically write something like this:</p> <pre><code>background-image: url('{{ STATIC_URL }}example.png'); </code></pre> <p>My question is, how can I use the Django templating engine (or any other means) to generate CSS dynamically?</p>
6,052,381
2
0
null
2011-05-18 23:51:52.327 UTC
9
2011-05-19 12:12:54.843 UTC
null
null
null
null
610,632
null
1
18
python|css|django|templates|django-templates
11,791
<p>You basically have two options:</p> <ol> <li><p>Serve your CSS dynamically, with an entry in urls.py, etc., just as if it were an HTML page. Your template file will simply be CSS instead of HTML, but will use normal Django template syntax, etc.</p></li> <li><p>Shortcut: Reference your background image with a relative path. This may or may not be possible for your environment, but it's a convenient way of having a static CSS file reference different paths depending on where it's hosted.</p></li> </ol>
33,149,878
experimental::filesystem linker error
<p>I try to use the new c++1z features actually on the head of development within gcc 6.0.</p> <p>If I try this little example:</p> <pre><code>#include &lt;iostream&gt; #include &lt;experimental/filesystem&gt; namespace fs = std::experimental::filesystem; int main() { fs::path p1 = "/home/pete/checkit"; std::cout &lt;&lt; "p1 = " &lt;&lt; p1 &lt;&lt; std::endl; } </code></pre> <p>I got:</p> <pre> /opt/linux-gnu_6-20151011/bin/g++ --std=c++1z main.cpp -O2 -g -o go /tmp/ccaGzqFO.o: In function \`std::experimental::filesystem::v1::__cxx11::path::path(char const (&) [36])': /opt/linux-gnu_6-20151011/include/c++/6.0.0/experimental/bits/fs_path.h:167: undefined reference to `std::experimental::filesystem::v1::__cxx11::path::_M_split_cmpts()' collect2: error: ld returned 1 exit status </pre> <p>gcc version is the snapshot linux-gnu_6-20151011</p> <p>Any hints how to link for the new c++1z features?</p>
33,159,746
6
0
null
2015-10-15 13:28:27.913 UTC
32
2020-12-03 15:53:02.19 UTC
2015-10-15 13:53:40.897 UTC
null
440,558
null
878,532
null
1
121
c++|gcc|c++17
86,781
<p>The Filesystem TS is nothing to do with C++1z support, it is a completely separate specification not part of the C++1z working draft. GCC's implementation (in GCC 5.3 and later) is even available in C++11 mode.</p> <p>You just need to link with <code>-lstdc++fs</code> to use it.</p> <p>(The relevant library, <code>libstdc++fs.a</code>, is a static library, so as with any static library it should come <em>after</em> any objects that depend on it in the linker command.)</p> <p><strong>Update Nov 2017:</strong> as well as the Filesystem TS, GCC 8.x <em>also</em> has an implementation of the C++17 Filesystem library, defined in <code>&lt;filesystem&gt;</code> and in namespace <code>std::filesystem</code> (N.B. no &quot;experimental&quot; in those names) when using <code>-std=gnu++17</code> or <code>-std=c++17</code>. GCC's C++17 support is not complete or stable yet, and until it's considered ready for prime time use you also need to link to <code>-lstdc++fs</code> for the C++17 Filesystem features.</p> <p><strong>Update Jan 2019:</strong> starting with GCC 9, the C++17 <code>std::filesystem</code> components can be used without <code>-lstdc++fs</code> (but you still need that library for <code>std::experimental::filesystem</code>).</p>
30,913,594
Handling XML data with Alamofire in Swift
<p>I started to use cocoapods with my current ios project. I need to use SOAP to get content with easy way for my ios project. I have googled it and Alamofire pod is great for me. Because I am using Swift programming language.</p> <p>I have inited easily this pod. But my web services return me XML result. And I want to serialisation to array this XML result. But I can't.</p> <p>When I call my web service with a browser I get this kind of result</p> <p><img src="https://i.stack.imgur.com/UlcN6.png" alt="enter image description here"></p> <p>Alamofire response method is like this:</p> <pre><code>Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil) .response { (request, response, data, error) in println(request) println(response) println(error) } </code></pre> <p>When I run this method I see this output on the terminal:</p> <pre><code>&lt;NSMutableURLRequest: 0x170010a30&gt; { URL: http://my-web-service-domain.com } Optional(&lt;NSHTTPURLResponse: 0x1704276c0&gt; { URL: http://my-web-service-domain.com } { status code: 200, headers { "Cache-Control" = "private, max-age=0"; "Content-Length" = 1020; "Content-Type" = "text/xml; charset=utf-8"; Date = "Thu, 18 Jun 2015 10:57:07 GMT"; Server = "Microsoft-IIS/7.5"; "X-AspNet-Version" = "2.0.50727"; "X-Powered-By" = "ASP.NET"; } }) nil </code></pre> <p>I want to get result to an array which see on browser to show my storyboard. Can anybody help me how to serialise this data with Alamofire framework or Swift language?</p>
30,980,470
7
0
null
2015-06-18 11:03:20.21 UTC
11
2020-08-11 01:28:20.277 UTC
2015-06-18 12:22:07.16 UTC
null
902,968
null
1,012,075
null
1
22
ios|xml|swift|alamofire
25,071
<p>If I did not misunderstand your description, I think you would like to get the XML data and parse it, right? Regarding to this, you may handle with wrong variables in the response callback. You should <code>println(data)</code> to check the XML document. </p> <p>For parsing XML data, you could consider <a href="https://github.com/drmohundro/SWXMLHash">SWXMLHash</a>. The Alamofire request could look like: </p> <pre><code>Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil) .response { (request, response, data, error) in println(data) // if you want to check XML data in debug window. var xml = SWXMLHash.parse(data!) println(xml["UserDTO"]["FilmID"].element?.text) // output the FilmID element. } </code></pre> <p>Further information about XML management, please check <a href="https://github.com/drmohundro/SWXMLHash">SWXMLHash</a>.</p>
21,037,263
Converting Map<String,String> to Map<String,Object>
<p>I have Two Maps</p> <pre><code>Map&lt;String, String&gt; filterMap Map&lt;String, Object&gt; filterMapObj </code></pre> <p>What I need is I would like to convert that <code>Map&lt;String, String&gt;</code> to <code>Map&lt;String, Object&gt;</code>. Here I am using the code</p> <pre><code> if (filterMap != null) { for (Entry&lt;String, String&gt; entry : filterMap.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); Object objectVal = (Object)value; filterMapObj.put(key, objectVal); } } </code></pre> <p>It works fine, Is there any other ways by which I can do this without iterating through all the entries in the Map.</p>
21,037,427
4
1
null
2014-01-10 06:06:21.863 UTC
4
2020-11-18 01:23:23.383 UTC
null
null
null
null
432,216
null
1
43
java|string|optimization|map|hashmap
35,542
<p>Instead of writing your own loop that calls <code>put</code>, you can <code>putAll</code>, which does the same thing:</p> <pre><code>filterMapObj.putAll(filterMap); </code></pre> <p>(See <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#putAll%28java.util.Map%29" rel="noreferrer">the Javadoc</a>.)</p> <p>And as Asanka Siriwardena points out in his/her answer, if your plan is to populate <code>filterMapObj</code> immediately after creating it, then you can use the constructor that does that automatically:</p> <pre><code>filterMapObj = new HashMap&lt;&gt;(filterMap); </code></pre> <p>But to be clear, the above are more-or-less equivalent to iterating over the map's elements: it will make your code cleaner, but if your reason for not wanting to iterate over the elements is actually a performance concern (e.g., if your map is enormous), then it's not likely to help you. Another possibility is to write:</p> <pre><code>filterMapObj = Collections.&lt;String, Object&gt;unmodifiableMap(filterMap); </code></pre> <p>which creates an unmodifiable &quot;view&quot; of <code>filterMap</code>. That's more restrictive, of course, in that it won't let you modify <code>filterMapObj</code> and <code>filterMap</code> independently. (<code>filterMapObj</code> can't be modified, and any modifications to <code>filterMap</code> will affect <code>filterMapObj</code> as well.)</p>
30,108,372
How to make Matplotlib scatterplots transparent as a group?
<p>I'm making some scatterplots using Matplotlib (python 3.4.0, matplotlib 1.4.3, running on Linux Mint 17). It's easy enough to set alpha transparency for each point individually; is there any way to set them as a group, so that two overlapping points from the same group don't change the color?</p> <p>Example code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def points(n=100): x = np.random.uniform(size=n) y = np.random.uniform(size=n) return x, y x1, y1 = points() x2, y2 = points() fig = plt.figure(figsize=(4,4)) ax = fig.add_subplot(111, title="Test scatter") ax.scatter(x1, y1, s=100, color="blue", alpha=0.5) ax.scatter(x2, y2, s=100, color="red", alpha=0.5) fig.savefig("test_scatter.png") </code></pre> <p>Results in this output:</p> <p><img src="https://i.stack.imgur.com/wAZ0p.png" alt="enter image description here"></p> <p>but I want something more like this one:</p> <p><img src="https://i.stack.imgur.com/yHYTx.png" alt="enter image description here"></p> <p>I can workaround by saving as SVG and manually grouping then in Inkscape, then setting transparency, but I'd really prefer something I can code. Any suggestions?</p>
30,110,950
6
1
null
2015-05-07 17:54:04.29 UTC
8
2022-08-26 03:52:16.11 UTC
2015-05-07 18:09:10.163 UTC
null
249,341
null
4,876,118
null
1
32
python|matplotlib|transparency|scatter-plot
63,076
<p>Yes, interesting question. You can get this scatterplot with <a href="https://pypi.python.org/pypi/Shapely" rel="noreferrer">Shapely</a>. Here is the code :</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as ptc import numpy as np from shapely.geometry import Point from shapely.ops import cascaded_union n = 100 size = 0.02 alpha = 0.5 def points(): x = np.random.uniform(size=n) y = np.random.uniform(size=n) return x, y x1, y1 = points() x2, y2 = points() polygons1 = [Point(x1[i], y1[i]).buffer(size) for i in range(n)] polygons2 = [Point(x2[i], y2[i]).buffer(size) for i in range(n)] polygons1 = cascaded_union(polygons1) polygons2 = cascaded_union(polygons2) fig = plt.figure(figsize=(4,4)) ax = fig.add_subplot(111, title="Test scatter") for polygon1 in polygons1: polygon1 = ptc.Polygon(np.array(polygon1.exterior), facecolor="red", lw=0, alpha=alpha) ax.add_patch(polygon1) for polygon2 in polygons2: polygon2 = ptc.Polygon(np.array(polygon2.exterior), facecolor="blue", lw=0, alpha=alpha) ax.add_patch(polygon2) ax.axis([-0.2, 1.2, -0.2, 1.2]) fig.savefig("test_scatter.png") </code></pre> <p>and the result is :</p> <p><img src="https://i.stack.imgur.com/u9neg.png" alt="Test scatter"></p>
25,783,161
How to check if two files have the same content?
<p>I am using <code>mocha/supertest/should.js</code> to test REST Service</p> <p><code>GET /files/&lt;hash&gt;</code> returns file as stream.</p> <p>How can I assert in <code>should.js</code> that file contents are the same?</p> <pre><code>it('should return file as stream', function (done) { var writeStream = fs.createWriteStream('test/fixtures/tmp.json'); var req = api.get('/files/676dfg1430af3595'); req.on('end', function(){ var tmpBuf = fs.readFileSync('test/fixtures/tmp.json'); var testBuf = fs.readFileSync('test/fixtures/test.json'); // How to assert with should.js file contents are the same (tmpBuf == testBuf ) // ... done(); }); }); </code></pre>
48,265,499
6
0
null
2014-09-11 08:55:41.513 UTC
7
2021-12-20 16:46:55.78 UTC
2021-12-20 16:46:55.78 UTC
null
4,891,717
null
444,079
null
1
32
javascript|node.js|compare|mocha.js|should.js
27,780
<p>Surprisingly, no one has suggested <a href="https://nodejs.org/api/all.html#buffer_buf_equals_otherbuffer" rel="noreferrer">Buffer.equals</a>. That seems to be the fastest and simplest approach and has been around since v0.11.</p> <p>So your code would become <code>tmpBuf.equals(testBuf)</code></p>
25,570,025
.NET Identity Email/Username change
<p>Does anyone know how to enable a user to change username/email with ASP.NET identity with email confirmation? There's plenty of examples on how to change the password but I can't find anything on this.</p>
25,585,969
5
0
null
2014-08-29 14:08:45.763 UTC
32
2019-02-22 23:27:06.437 UTC
null
null
null
null
3,915,272
null
1
59
asp.net|asp.net-identity
52,123
<p><strong>Update Dec 2017</strong> Some good points have been raised in comments:</p> <ul> <li>Better have a separate field for new email while it is getting confirmed - in cases when user have entered incorrect email. Wait till the new email is confirmed, then make it the primary email. See very detailed answer from Chris_ below.</li> <li>Also there could be a case when account with that email already exist - make sure you check for that too, otherwise there can be trouble.</li> </ul> <p>This is a very basic solution that does not cover all possible combinations, so use your judgment and make sure you read through the comments - very good points have been raised there.</p> <pre><code>// get user object from the storage var user = await userManager.FindByIdAsync(userId); // change username and email user.Username = "NewUsername"; user.Email = "[email protected]"; // Persiste the changes await userManager.UpdateAsync(user); // generage email confirmation code var emailConfirmationCode = await userManager.GenerateEmailConfirmationTokenAsync(user.Id); // generate url for page where you can confirm the email var callbackurl= "http://example.com/ConfirmEmail"; // append userId and confirmation code as parameters to the url callbackurl += String.Format("?userId={0}&amp;code={1}", user.Id, HttpUtility.UrlEncode(emailConfirmationCode)); var htmlContent = String.Format( @"Thank you for updating your email. Please confirm the email by clicking this link: &lt;br&gt;&lt;a href='{0}'&gt;Confirm new email&lt;/a&gt;", callbackurl); // send email to the user with the confirmation link await userManager.SendEmailAsync(user.Id, subject: "Email confirmation", body: htmlContent); // then this is the action to confirm the email on the user // link in the email should be pointing here public async Task&lt;ActionResult&gt; ConfirmEmail(string userId, string code) { var confirmResult = await userManager.ConfirmEmailAsync(userId, code); return RedirectToAction("Index"); } </code></pre>
8,754,814
How to pass an Integer Array to IN clause in MyBatis
<p>There is a query in my Mybatis containing an IN clause which is basically a set of Id's ( Integers)</p> <p>I am now stuck on how can I pass an Integer array to this IN clause so that it pulls up the proper records.Tried by passing a String containing the ID's to the IN clause , but this did not work as expected.</p> <p>Code Sample below</p> <p>Mybatis Method using Annotations</p> <pre><code>@Select(SEL_QUERY) @Results(value = {@Result(property="id",column="ID")}) List&lt;Integer&gt; getIds(@Param("usrIds") Integer[] usrIds); </code></pre> <p>Query</p> <pre><code>select distinct ID from table a where a.id in ( #{usrIds} ) </code></pre> <p>Method Call</p> <pre><code>Integer[] arr = new Integer[2]; arr[0] = 1; arr[1] = 2; mapper.getIds(arr) </code></pre> <p>This is not working , Mybatis throws an error when I call the mapper method</p> <p>Any suggestions please</p>
8,757,810
4
0
null
2012-01-06 07:39:42.323 UTC
12
2020-08-18 11:33:20.177 UTC
null
null
null
null
900,841
null
1
30
java|jakarta-ee|mybatis
50,667
<p>The <a href="http://www.mybatis.org/mybatis-3/dynamic-sql.html" rel="noreferrer">myBatis User Guide on Dynamic SQL</a> has an example on how to use a foreach loop to build the query string, which works for lists and arrays.</p> <p>Prior to release 3.2 you had to use xml configuration to use dynamic sql, with newer versions it should also be possible to use <a href="https://stackoverflow.com/questions/3428742/how-to-use-annotations-with-ibatis-mybatis-for-an-in-query/22646475#22646475">dynamic sql in annotations</a>.</p> <pre><code>&lt;select id="selectPostIn" resultType="domain.blog.Post"&gt; SELECT * FROM POST P WHERE ID in &lt;foreach item="item" index="index" collection="list" open="(" separator="," close=")"&gt; #{item} &lt;/foreach&gt; &lt;/select&gt; </code></pre>
60,815,037
AWS DotNet SDK Error: Unable to get IAM security credentials from EC2 Instance Metadata Service
<p>I use an example from <a href="https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/dotnet/example_code/SecretsManager/GetSecretValue/GetSecretValue.cs" rel="noreferrer">here</a> in order to retreive a secret from AWS SecretsManager in c# code.</p> <p>I have set credentials locally via AWS CLI, and I am able to retreive secret list using AWS CLI command "aws secretsmanager list-secrets".</p> <p>But c# console app fails with an error:</p> <pre><code>&gt; Unhandled exception. System.AggregateException: One or more errors occurred. (Unable to get IAM security credentials from EC2 Instance Metadata Service.) ---&gt; Amazon.Runtime.AmazonServiceException: Unable to get IAM security credentials from EC2 Instance Metadata Service. at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials() at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials() at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentialsAsync() at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result() at AWSConsoleApp2.GetSecretValueFirst.GetSecret() in D:\Work\Projects\Training\AWSConsoleApp2\AWSConsoleApp2\GetSecretValueFirst.cs:line 53 at AWSConsoleApp2.Program.Main(String[] args) in D:\Work\Projects\Training\AWSConsoleApp2\AWSConsoleApp2\Program.cs:line 11 </code></pre> <p>When I change original constructor call </p> <blockquote> <p>IAmazonSecretsManager client = new AmazonSecretsManagerClient();</p> </blockquote> <p>with adding inherited parameter of type AWSCredentials</p> <blockquote> <p>IAmazonSecretsManager client = new AmazonSecretsManagerClient(new StoredProfileAWSCredentials());</p> </blockquote> <p>it works fine.</p> <p>Class StoredProfileAWSCredentials is obsolete but it works to use it. I use libraries that work without errors on the other machines and I cannot change them.</p> <p>I use credentials for user that belongs to Administrators group and has full access to SecretsMnager. Region has set properly in c# code, profile is default.</p> <p>Any ideas? Thanks for advance</p>
62,061,272
16
0
null
2020-03-23 14:01:34.603 UTC
4
2022-07-29 16:18:38.463 UTC
2020-03-23 14:06:46.49 UTC
null
5,078,898
null
5,078,898
null
1
19
.net|amazon-web-services|sdk|credentials
52,849
<p>I had the same issue, here is how I fixed it on my development environment</p> <ol> <li>I created an AWS profile using the AWS extension for Visual studio</li> <li>Once the profile is set up the credentials are passed using the profile and it worked fine for me</li> </ol> <p>Point to note here, the user profile accessing the key manager should have a valid security group assigned for the Secrets manager.</p> <p>Try it out let me know, how it went.</p>
48,372,019
ImportError: cannot import name 'ensure_dir_exists'
<p>I update the Jupyter notebook from the old version to latest 5.3.1. However, when I try to launch the notebook from anaconda, it throws an import error: I tried to remove and install Jupyter package, still, the issue persists.</p> <pre><code>Traceback (most recent call last): File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\__init__.py", line 25, in from .nbextensions import install_nbextension File "C:\Users\v-kangsa\AppData\Local\Continuum\anaconda3\lib\site-packages\notebook\nbextensions.py", line 27, in from jupyter_core.utils import ensure_dir_exists ImportError: cannot import name 'ensure_dir_exists' </code></pre>
48,373,567
6
1
null
2018-01-21 21:44:04.523 UTC
7
2018-06-26 20:46:09.247 UTC
2018-05-16 13:17:37.963 UTC
null
3,938,208
null
3,274,277
null
1
30
python|jupyter-notebook
22,868
<p>You need to update jupyter_core and jupyter_client manually from your terminal:</p> <pre><code>conda update jupyter_core jupyter_client </code></pre>
30,474,767
No tests found for given includes Error, when running Parameterized Unit test in Android Studio
<p>I have tried to run Parameterized Unit Tests in Android Studio, as shown below:</p> <pre class="lang-java prettyprint-override"><code>import android.test.suitebuilder.annotation.SmallTest; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) @SmallTest public class FibonacciTest extends TestCase { @Parameters public static Collection&lt;Object[]&gt; data() { return Arrays.asList(new Object[][] { {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8} }); } @Parameter // first data value (0) is default public /* NOT private */ int fInput; @Parameter(value = 1) public /* NOT private */ int fExpected; @Test public void test() { assertEquals(fExpected, Fibonacci.calculate(fInput)); } } </code></pre> <p>The result is an error stating <code>No Test Run</code>. However, if I remove the Parameterized tests, and change them to individual tests, it works.</p> <p>Can anyone shed some light on why this is not working? Ar Parameterized unit tests not supported in Android development yet?</p> <p>Below is the error with stack trace:</p> <pre class="lang-none prettyprint-override"><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:testDebug'. &gt; No tests found for given includes: [com.example.......FibonacciTest] * Try: Run with --info or --debug option to get more log output. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:testDebug'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90) at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54) at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28) at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72) at org.gradle.util.Swapper.swap(Swapper.java:38) at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50) at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40) Caused by: org.gradle.api.GradleException: No tests found for given includes: [com.example........FibonacciTest] at org.gradle.api.internal.tasks.testing.NoMatchingTestsReporter.afterSuite(NoMatchingTestsReporter.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy46.afterSuite(Unknown Source) at org.gradle.api.internal.tasks.testing.results.TestListenerAdapter.completed(TestListenerAdapter.java:48) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy45.completed(Unknown Source) at org.gradle.api.internal.tasks.testing.results.StateTrackingTestResultProcessor.completed(StateTrackingTestResultProcessor.java:69) at org.gradle.api.internal.tasks.testing.results.AttachParentTestResultProcessor.completed(AttachParentTestResultProcessor.java:52) at org.gradle.api.internal.tasks.testing.processors.TestMainAction.run(TestMainAction.java:51) at org.gradle.api.internal.tasks.testing.detection.DefaultTestExecuter.execute(DefaultTestExecuter.java:75) at org.gradle.api.tasks.testing.Test.executeTests(Test.java:527) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:226) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:589) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:572) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 57 more BUILD FAILED Total time: 4.153 secs No tests found for given includes: [com.example......FibonacciTest] </code></pre>
57,309,718
33
0
null
2015-05-27 06:29:14.997 UTC
32
2022-08-02 07:40:45.973 UTC
2022-05-28 00:11:02.357 UTC
null
65,863
null
3,286,489
null
1
239
android|android-studio|unit-testing|junit|parameterized-unit-test
276,416
<p>Add to your build.gradle:</p> <pre><code>test { useJUnitPlatform() } </code></pre>
1,201,179
How to identify top-level X11 windows using xlib?
<p>I'm trying to get a list of all top level desktop windows in an X11 session. Basically, I want to get a list of all windows that are shown in the window managers application-switching UI (commonly opened when the user presses ALT+TAB).</p> <p>I've never done any X11 programming before, but so far I've managed to enumerate through the entire window list, with code that looks something like this:</p> <pre><code>void CSoftwareInfoLinux::enumerateWindows(Display *display, Window rootWindow) { Window parent; Window *children; Window *child; quint32 nNumChildren; XTextProperty wmName; XTextProperty wmCommand; int status = XGetWMName(display, rootWindow, &amp;wmName); if (status &amp;&amp; wmName.value &amp;&amp; wmName.nitems) { int i; char **list; status = XmbTextPropertyToTextList(display, &amp;wmName, &amp;list, &amp;i); if (status &gt;= Success &amp;&amp; i &amp;&amp; *list) { qDebug() &lt;&lt; "Found window with name:" &lt;&lt; (char*) *list; } status = XGetCommand(display, rootWindow, &amp;list, &amp;i); if (status &gt;= Success &amp;&amp; i &amp;&amp; *list) { qDebug() &lt;&lt; "... and Command:" &lt;&lt; i &lt;&lt; (char*) *list; } Window tf; status = XGetTransientForHint(display, rootWindow, &amp;tf); if (status &gt;= Success &amp;&amp; tf) { qDebug() &lt;&lt; "TF set!"; } XWMHints *pHints = XGetWMHints(display, rootWindow); if (pHints) { qDebug() &lt;&lt; "Flags:" &lt;&lt; pHints-&gt;flags &lt;&lt; "Window group:" &lt;&lt; pHints-&gt;window_group; } } status = XQueryTree(display, rootWindow, &amp;rootWindow, &amp;parent, &amp;children, &amp;nNumChildren); if (status == 0) { // Could not query window tree further, aborting return; } if (nNumChildren == 0) { // No more children found. Aborting return; } for (int i = 0; i &lt; nNumChildren; i++) { enumerateWindows(display, children[i]); } XFree((char*) children); } </code></pre> <p><code>enumerateWindows()</code> is called initially with the root window.</p> <p>This works, in so far as it prints out information about hundreds of windows - what I need, is to work out which property I can interrogate to determine if a given <code>Window</code> is a top-level Desktop application window (not sure what the official terminology is), or not.</p> <p>Can anyone shed some light on this? All the reference documentation I've found for X11 programming has been terribly dry and hard to understand. Perhaps someone could point be to a better resource?</p>
1,211,242
3
0
null
2009-07-29 15:38:43.58 UTC
10
2017-12-04 13:14:06.743 UTC
2010-10-05 05:33:50.073 UTC
null
19,750
null
1,304
null
1
13
c++|x11|xlib|icccm|ewmh
15,309
<p>I have a solution!</p> <p>Well, sort of.</p> <p>If your window manager uses the extended window manager hints (EWMH), you can query the root window using the "<code>_NET_CLIENT_LIST</code>" atom. This returna list of client windows the window manager is managing. For more information, see <a href="http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html#id2449346" rel="noreferrer">here</a>.</p> <p>However, there are some issues with this. For a start, the window manager in use must support the EWMH. KDE and GNOME do, and I'm sure some others do as well. However, I'm sure there are many that don't. Also, I've noticed a few issues with KDE. Basically, some non-KDE applications don't get included in the list. For example, if you run xcalc under KDE it won't show up in this list.</p> <p>If anyone can provide any improvements on this method, I'd be glad to hear them. For reference, the code I'm using is listed below:</p> <pre><code> Atom a = XInternAtom(m_pDisplay, "_NET_CLIENT_LIST" , true); Atom actualType; int format; unsigned long numItems, bytesAfter; unsigned char *data =0; int status = XGetWindowProperty(m_pDisplay, rootWindow, a, 0L, (~0L), false, AnyPropertyType, &amp;actualType, &amp;format, &amp;numItems, &amp;bytesAfter, &amp;data); if (status &gt;= Success &amp;&amp; numItems) { // success - we have data: Format should always be 32: Q_ASSERT(format == 32); // cast to proper format, and iterate through values: quint32 *array = (quint32*) data; for (quint32 k = 0; k &lt; numItems; k++) { // get window Id: Window w = (Window) array[k]; qDebug() &lt;&lt; "Scanned client window:" &lt;&lt; w; } XFree(data); } </code></pre>
903,864
How to exit a child process and return its status from execvp()?
<p>In my simple custom shell I'm reading commands from the standard input and execute them with execvp(). Before this, I create a fork of the current process and I call the execvp() in that child process, right after that, I call exit(0).</p> <p>Something like this:</p> <pre><code>pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { // CHILD PROCESS CODE GOES HERE... execvp(pArgs[0], pArgs); exit(0); } else { // PARENT PROCESS CODE GOES HERE... } </code></pre> <p>Now, the commands run with execvp() can return errors right? I want to handle that properly and right now, I'm always calling exit(0), which will mean the child process will always have an "OK" state.</p> <p>How can I return the proper status from the execvp() call and put it in the exit() call? Should I just get the int value that execvp() returns and pass it as an exit() argument instead of 0. Is that enough and correct?</p>
903,871
3
4
null
2009-05-24 14:22:24.433 UTC
4
2014-03-04 02:50:10.643 UTC
2009-05-24 14:26:46.97 UTC
null
37,213
null
40,480
null
1
19
c|exec|fork|exit
63,564
<p>You need to use <code>waitpid(3)</code> or <code>wait(1)</code> in the parent code to wait for the child to exit and get the error message.</p> <p>The syntax is:</p> <pre><code>pid_t waitpid(pid_t pid, int *status, int options); </code></pre> <p>or</p> <pre><code>pid_t wait(int *status); </code></pre> <p><code>status</code> contains the exit status. Look at the <a href="http://linux.die.net/man/2/waitpid" rel="noreferrer">man pages</a> to see you how to parse it.</p> <hr> <p>Note that you can't do this from the child process. Once you call <code>execvp</code> the child process <strong><em>dies</em></strong> (for all practical purposes) and is <em>replaced</em> by the <code>exec</code>'d process. The only way you can reach <code>exit(0)</code> there is if <code>execvp</code> itself fails, but then the failure isn't because the new program ended. It's because it never ran to begin with.</p> <p><strong>Edit:</strong> the child process doesn't <em>really</em> die. The PID and environment remain unchanged, but the entire code and data are replaced with the <code>exec</code>'d process. You can count on <em>not</em> returning to the original child process, unless <code>exec</code> fails.</p>
39,715,135
Problems deploying code with Capistrano since upgrading to macOS 10.12 (Sierra), “Permission denied (publickey).”
<p>So I just upgraded my Mac mini (Late 2012) to macOS 10.12 (Sierra) and everything seems fine, but I’m running into one odd problem deploying code with <a href="http://capistranorb.com/" rel="noreferrer">Capistrano</a>. I get the following error:</p> <pre><code>Permission denied (publickey). </code></pre> <p>Never had this problem before in Mac OS X 10.11 (El Capitan) or any version prior to it. Why is this suddenly happening now? Full output of the failed Capistrano deployment below:</p> <pre><code>jakes_mac:SomeCode jake$ cap staging deploy INFO [hkdgad21] Running /usr/bin/env mkdir -p /tmp/somecode/ as [email protected] DEBUG [hkdgad21] Command: /usr/bin/env mkdir -p /tmp/somecode/ [email protected]'s password: INFO [hkdgad21] Finished in 5.166 seconds with exit status 0 (successful). DEBUG Uploading /tmp/somecode/git-ssh.sh 0.0% INFO Uploading /tmp/somecode/git-ssh.sh 100.0% INFO [xyz20312] Running /usr/bin/env chmod +x /tmp/somecode/git-ssh.sh as [email protected] DEBUG [xyz20312] Command: /usr/bin/env chmod +x /tmp/somecode/git-ssh.sh INFO [xyz20312] Finished in 0.240 seconds with exit status 0 (successful). INFO [abcdef01] Running /usr/bin/env git ls-remote --heads [email protected]:SomeUser/SomeCode.git as [email protected] DEBUG [abcdef01] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/somecode/git-ssh.sh /usr/bin/env git ls-remote --heads [email protected]:SomeUser/SomeCode.git ) DEBUG [abcdef01] Permission denied (publickey). DEBUG [abcdef01] fatal: Could not read from remote repository. DEBUG [abcdef01] DEBUG [abcdef01] Please make sure you have the correct access rights DEBUG [abcdef01] and the repository exists. (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as [email protected]: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. SSHKit::Command::Failed: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Tasks: TOP =&gt; git:check (See full trace by running task with --trace) The deploy has failed with an error: Exception while executing as [email protected]: git exit status: 128 git stdout: Nothing written git stderr: Permission denied (publickey). fatal: Could not read from remote repository. </code></pre> <p>Please make sure you have the correct access rights and the repository exists.</p>
39,715,149
3
1
null
2016-09-27 02:32:41.05 UTC
10
2018-09-02 23:00:28.037 UTC
2016-09-27 02:58:57.573 UTC
null
117,259
null
117,259
null
1
21
macos|ssh|capistrano
13,836
<p>Seems like it’s an issue with SSH keys not being automatically added as it used to be in Mac OS X 10.11 (El Capitan). Is this expected behavior from macOS Sierra or something connected to OpenSSH?</p> <h3>Method 1: Add <em>all known</em> keys to the SSH agent.</h3> <p>So one solution I found is to run <a href="https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/ssh-add.1.html" rel="noreferrer"><code>ssh-add</code></a> with the <code>-A</code> option—which adds all known identities to the SSH agent using any passphrases stored in your keychain—like this:</p> <pre><code>ssh-add -A </code></pre> <p>Now this works but it won’t persist across reboots. So if you want to never worry about this again, just open up your user’s <code>~/.bash_profile</code> file like this:</p> <pre><code>nano ~/.bash_profile </code></pre> <p>And add this line to the bottom:</p> <pre><code>ssh-add -A 2&gt;/dev/null; </code></pre> <p>Now when you open a new Terminal window, all should be good!</p> <h3>Method 2: Add <em>only SSH keys that are in the keychain</em> to the agent.</h3> <p>So while the <code>ssh-add -A</code> option should work for most basic cases, I ran into an issue recently where I had 6-7 Vagrant boxes (which uses SSH keys/identities for access) setup on a machine on top of the more common <code>id_rsa.pub</code> in place.</p> <p>Long story short, I ended up being locked out of a remote server due to too many failed tries based on SSH keys/identities since the server access was based on a password and SSH keys/identities are SSH keys/identities. So the SSH agent tried <em>all</em> of my SSH keys, failed and I couldn’t even get to the password prompt.</p> <p>The problem is that <code>ssh-add -A</code> will just arbitrarily add every single SSH key/identity you have to the agent even if it’s not necessary to do so; such as in the case of Vagrant boxes.</p> <p>My solution after much testing was as follows.</p> <p>First, if you have more SSH keys/identities added to your agent than you need—as shown with <code>ssh-add -l</code> then purge them all from the agent like so:</p> <pre><code>ssh-add -D </code></pre> <p>With that done, then start the SSH agent as a background process like so:</p> <pre><code>eval "$(ssh-agent -s)" </code></pre> <p>Now, it gets weird and I am not too sure why. In some cases you can specifically add the <code>~/.ssh/id_rsa.pub</code> key/identity to the agent like so:</p> <pre><code>ssh-add ~/.ssh/id_rsa.pub </code></pre> <p>Type in your passphrase, hit <kbd>Return</kbd> and you should be good to go.</p> <p>But in other cases simply running this is enough to get the key/identity added:</p> <pre><code>ssh-add -K </code></pre> <p>If that’s all worked, type in <code>ssh-add -l</code> and you should see one lone SSH key/identity listed.</p> <p>All good? Now open up your <code>.bash_profile</code>:</p> <pre><code>nano ~/.bash_profile </code></pre> <p>And add this line to the bottom; comment or remove the <code>-A</code> version if you have that in place:</p> <pre><code>ssh-add -K </code></pre> <p>That will allow the SSH key/identity to be reloaded to the SSH agent on each startup/reboot.</p> <hr> <p><strong>UPDATE 1:</strong> Based on <a href="https://stackoverflow.com/a/39904591/117259"><strong>davidalger</strong>’s answer</a> I discovered a nicer, global solution that can work for all user’s on a system. Just open up the global SSH config located here via <code>sudo</code>:</p> <pre><code>sudo nano /etc/ssh/ssh_config </code></pre> <p>And add this line to the bottom of the file:</p> <pre><code>AddKeysToAgent yes </code></pre> <p>Did that—after removing the <code>.bash_profile</code> fix and all is good as well.</p> <hr> <h3>UPDATE 2: Apple has now added a <code>UseKeychain</code> option to the open SSH config options and considers <code>ssh-add -A</code> a solution as well.</h3> <p>As of macOS Sierra 10.12.2, Apple (I assume) has added a <code>UseKeychain</code> config option for SSH configs. Checking the man page (via <code>man ssh_config</code>) shows the following info:</p> <pre><code>UseKeychain On macOS, specifies whether the system should search for passphrases in the user's keychain when attempting to use a par- ticular key. When the passphrase is provided by the user, this option also specifies whether the passphrase should be stored into the keychain once it has been verified to be correct. The argument must be ``yes'' or ``no''. The default is ``no''. </code></pre> <p>Which boils down to Apple seeing the solution as either adding <code>ssh-add -A</code> to your <code>.bash_profile</code> <a href="https://openradar.appspot.com/27348363" rel="noreferrer">as explained in this Open Radar ticket</a> or adding <code>UseKeychain</code> as one of the options in a per user <code>~/.ssh/config</code>.</p>
41,707,721
NgrxStore and Angular - Use the async pipe massively or subscribe just once in the constructor
<p>I am starting to look at ngrx Store and I see the convenience to use the Angular async pipe. At the same time I am not sure whether using the Angular async pipe massively is a good choice.</p> <p>I make a simple example. Let's assume that in the same template I need to show different attributes of an object (e.g. a Person) which is retrieved from the Store.</p> <p>A piece of template code could be</p> <pre><code>&lt;div&gt;{{(person$ | async).name}}&lt;/div&gt; &lt;div&gt;{{(person$ | async).address}}&lt;/div&gt; &lt;div&gt;{{(person$ | async).age}}&lt;/div&gt; </code></pre> <p>while the component class constructor would have</p> <pre><code>export class MyComponent { person$: Observable&lt;Person&gt;; constructor( private store: Store&lt;ApplicationState&gt; ) { this.person$ = this.store.select(stateToCurrentPersonSelector); } ..... ..... } </code></pre> <p>As far as I understand this code implies 3 subscriptions (made in the template via the async pipe) to the same Observable (<code>person$</code>).</p> <p>An alternative would be to define 1 property (<code>person</code>) in MyComponent and to have only 1 subscription (in the constructor) that fills the property, such as</p> <pre><code>export class MyComponent { person: Person; constructor( private store: Store&lt;ApplicationState&gt; ) { this.store.select(stateToCurrentPersonSelector) .subscribe(person =&gt; this.person = person); } ..... ..... } </code></pre> <p>while the template uses standard property binding (i.e. without the async pipe), such as</p> <pre><code>&lt;div&gt;{{person.name}}&lt;/div&gt; &lt;div&gt;{{person.address}}&lt;/div&gt; &lt;div&gt;{{person.age}}&lt;/div&gt; </code></pre> <p><strong>Now the question</strong></p> <p>Is there any difference in terms of performance between the 2 approaches? Is the massive use of async pipe (i.e. a massive use of subscriptions) going to affect the efficiency of the code?</p>
41,708,840
3
1
null
2017-01-17 21:56:12.83 UTC
13
2018-12-04 14:51:43.433 UTC
2018-12-04 14:51:43.433 UTC
null
1,033,581
null
5,699,993
null
1
53
angular|ngrx
12,979
<p>Neither, you should compose your application as smart and presentation components. </p> <p><strong>Advantages:</strong></p> <ul> <li>All buissness logic on the smart controller. </li> <li>Just one subscribe</li> <li>Reusability</li> <li>The presentation controller has only one responsibility, only to present data and does not know from where the data come from. (loosely coupled)</li> </ul> <p><strong>Answering the last question:</strong></p> <p>The massive use of async pipe will affect the efficiency, because it will subscribe to every async pipe. You can notice this more if you are calling a http service, because it will call the http request for each async pipe.</p> <p><strong>Smart Component</strong></p> <pre><code>@Component({ selector: 'app-my', template: ` &lt;app-person [person]="person$ | async"&gt;&lt;/app-person&gt; `, styleUrls: ['./my.component.css'] }) export class MyComponent implements OnInit { person$: Observable&lt;Person&gt;; constructor(private store: Store&lt;ApplicationState&gt;) {} ngOnInit() { this.person$ = this.store.select(stateToCurrentPersonSelector); } } </code></pre> <p><strong>Presentation Component</strong></p> <pre><code>@Component({ selector: 'app-person', template: ` &lt;div&gt;{{person.name}}&lt;/div&gt; &lt;div&gt;{{person.address}}&lt;/div&gt; &lt;div&gt;{{person.age}}&lt;/div&gt; `, styleUrls: ['./my.component.css'] }) export class PersonComponent implements OnInit { @Input() person: Person; constructor() {} ngOnInit() { } } </code></pre> <p>For more info check:</p> <ul> <li><a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u27zmzf25" rel="noreferrer">https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u27zmzf25</a></li> <li><a href="http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/" rel="noreferrer">http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/</a></li> </ul>
36,598,885
change font size on gnuplot
<p>I know there have been several posts on how to change the font size on gnuplot. However, in my code, even though I take the solution in previous posts, the output figures have no change. My code is :</p> <pre><code>set terminal png size 1280, 480; set xrange [0:100] set yrange [0:1] set xlabel 'n' set ylabel 'x_n' set tics font ",1" set output './time_series/r'.i.'.'.j.''.k.''.l.'.png'; set title 'r = '.i.'.'.j.''.k.''.l; do for [i=0:3]{ do for [j=0:9]{ do for [k=0:9]{ do for [l=0:9]{ plot './time_series/r'.i.'.'.j.''.k.''.l.'.txt' every ::0::100 with linespoints ls 1 ps 1 pt 7 notitle } } } } </code></pre> <p>The command has no effect with any number I put into, i.e. </p> <pre><code>set tics font ",a number" </code></pre> <p>Any number produces the same font. Is there anything I missed?</p> <p>Thank you everyone.</p> <p>Update : Thanks Raphael. Here are two png produced. The first is with [set tics font ",1"]. The second, [set tics font ",10"]. <a href="https://i.stack.imgur.com/W80jk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W80jk.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/fom3x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fom3x.png" alt="enter image description here"></a></p>
36,710,783
2
1
null
2016-04-13 12:47:36.437 UTC
4
2022-06-27 11:11:08.713 UTC
2016-04-15 13:50:49.343 UTC
null
5,085,783
null
5,085,783
null
1
16
fonts|gnuplot
56,263
<p><strong>AD1:</strong> the correct way to set tics font size is</p> <pre><code>set tics font "name{,&lt;size&gt;}" </code></pre> <p>eg.</p> <pre><code>set tics font "Helvetica,10" </code></pre> <p><strong>AD2</strong>: set tics font resizes only the fonts of x-y axes. To resize all the fonts (eg. the <code>title</code>) use</p> <pre><code>set terminal png size 1280, 480 font "Helvetica,30" </code></pre> <p>(or any other fontname and/or size :o) )</p>
20,647,454
How can you create GitHub gists that live under an organization account instead of a personal account?
<p>I manage an organization <a href="https://github.com/marklogic" rel="noreferrer">https://github.com/marklogic</a>. I see we actually have one gist under <a href="https://gist.github.com/marklogic/" rel="noreferrer">https://gist.github.com/marklogic/</a> ; I can't figure out how to get any more gists there though. Is there a way?</p>
20,651,975
1
0
null
2013-12-18 00:26:43.993 UTC
5
2022-03-09 00:41:44.16 UTC
null
null
null
null
288,959
null
1
112
github|gist
30,143
<p>I don't think you can currently create gists as an organization account, but in my experience, if your account was a personal account and you created a gist under that account and then upgraded the account to an organization account, the gist stays but no new gists can be created.</p> <p>Also, seems like <a href="https://webapps.stackexchange.com/a/42847">this answer on WebApps</a> confirms my experience.</p> <p>Hope this helps</p>
20,760,681
LINQ join two DataTables
<p>Hi I have a problem joining two DataTables using LINQ. Tables have columns like this:</p> <pre><code>table1 table2 ID, name ID, stock 1, item1 1, 100 2, item2 3, 50 3, item3 </code></pre> <p>I used linq to join like this:</p> <pre><code>DataTable dtResult = new DataTable(); dtResult.Columns.Add("ID", typeof(string)); dtResult.Columns.Add("name", typeof(string)); dtResult.Columns.Add("stock", typeof(int)); var result = from dataRows1 in table1.AsEnumerable() join dataRows2 in table2.AsEnumerable() on dataRows1.Field&lt;string&gt;("ID") equals dataRows2.Field&lt;string&gt;("ID") select dtResult.LoadDataRow(new object[] { dataRows1.Field&lt;string&gt;("ID"), dataRows1.Field&lt;string&gt;("name"), dataRows2.Field&lt;int&gt;("stock"), }, false); result.CopyToDataTable(); </code></pre> <p>Problem is, result only shows IDs which are in the table2.</p> <pre><code>dtResult ID, name, stock 1, item1, 100 3, item3, 50 </code></pre> <p>I need to show also the missing items. This is the wanted result:</p> <pre><code>dtResult ID, name, stock 1, item1, 100 2, item2, 0 //Prefer if it is "0", otherwise can be left "null" 3, item3, 50 </code></pre> <p>I believe I should do left outer join, but I do not have enough knowledge about linq. Help appreciated. Thank you!</p>
20,760,794
4
0
null
2013-12-24 12:08:05.48 UTC
16
2015-07-22 14:32:02.9 UTC
2015-01-22 10:14:19.277 UTC
null
1,776,428
null
1,080,533
null
1
27
c#|winforms|linq|join
98,521
<p>This will let you default to 0 if the row doesn't exist in table2:</p> <pre><code>var result = from dataRows1 in table1.AsEnumerable() join dataRows2 in table2.AsEnumerable() on dataRows1.Field&lt;string&gt;("ID") equals dataRows2.Field&lt;string&gt;("ID") into lj from r in lj.DefaultIfEmpty() select dtResult.LoadDataRow(new object[] { dataRows1.Field&lt;string&gt;("ID"), dataRows1.Field&lt;string&gt;("name"), r == null ? 0 : r.Field&lt;int&gt;("stock") }, false); </code></pre> <p>MSDN <a href="http://msdn.microsoft.com/en-us/library/bb397895.aspx" rel="noreferrer">source</a></p>
36,112,445
Golang blocking and non blocking
<p>I am somewhat confused over how Go handles non blocking IO. API's mostly look synchronous to me, and when watching presentations on Go, its not uncommon to hear comments like "and the call blocks"</p> <p>Is Go using blocking IO when reading from files or network? Or is there some kind of magic that re-writes the code when used from inside a Go Routine?</p> <p>Coming from a C# background, this feels very non intuitive, in C# we have the <code>await</code> keyword when consuming async API's. Which clearly communicates that the API can yield the current thread and continue later inside a continuation.</p> <p>So TLDR; Will Go block the current thread when doing IO inside a Go routine, or will it be transformed into a C# like async await state machine using continuations?</p>
36,112,564
2
1
null
2016-03-20 10:09:50.56 UTC
16
2022-02-15 04:43:46.517 UTC
null
null
null
null
317,384
null
1
54
multithreading|go|nonblocking
35,677
<p>Go has a scheduler that lets you write synchronous code, and does context switching on its own and uses async IO under the hood. So if you're running several goroutines, they might run on a single system thread, and when your code is blocking from the goroutine's view, it's not really blocking. It's not magic, but yes, it masks all this stuff from you.</p> <p>The scheduler will allocate system threads when they're needed, and during operations that are really blocking (I think file IO is blocking for example, or calling C code). But if you're doing some simple http server, you can have thousands and thousands of goroutine using actually a handful of "real threads". </p> <p>You can read more about the inner workings of Go here: </p> <p><a href="https://morsmachine.dk/go-scheduler">https://morsmachine.dk/go-scheduler</a></p>
5,630,743
Trying to resolve an "invalid use of Null" in VBA
<p>Quick snippet first:</p> <pre><code>Dim GUID As String Dim givenNames, familyName, preferredName, gender, comments, carer, medicareNumber, patientNumber As String Dim dob As Variant Dim deceased, resolved, consultNotes As Boolean Dim age As Variant givenNames = Null familyName = Null preferredName = Null gender = Null dob = Null comments = Null deceased = False resolved = False carer = Null age = Null consultNotes = False patientNumber = Null ' This is where I get the error </code></pre> <p>Any idea why this last variable would be the one to trip up? I've assigned Null to a bunch of other strings without any errors.</p>
5,630,767
4
1
null
2011-04-12 05:22:12.423 UTC
null
2020-12-18 08:29:07.76 UTC
2020-07-13 14:08:14.563 UTC
null
7,296,893
null
184,124
null
1
8
ms-access|vba
39,137
<p>In VBA/VB6, strings cannot be set to Null; only Variants can be set to null. In addition, when you declare variables inline comma-separated like in the question, only the last one will be typed as string; all of the others are typed as variants. To declare them on one line as a type you have to include the type</p> <pre><code>Dim a As String, Dim b As String ... </code></pre> <p>That's why it makes sense to just declare them on a single line.</p> <p>(Btw, it should be noted that <code>deceased, resolved</code> are also typed as variants for the same reason.)</p>
6,068,009
Difference between Ctrl+Shift+F and Ctrl+I in Eclipse
<p>I have been used <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> to correct indentation but I heard there is another shortcut to do that: <kbd>Ctrl</kbd>+<kbd>I</kbd></p> <p>According a <a href="http://www.allapplabs.com/eclipse/eclipse_shortcuts.htm" rel="noreferrer">reference</a> found in google, <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd> is Reformat and <kbd>Ctrl</kbd>+<kbd>I</kbd> is Correct indentation.</p> <p>Is there any difference between them? or between Reformat and Correct indentation?</p>
6,068,027
4
1
null
2011-05-20 05:59:43.65 UTC
24
2019-04-08 13:05:10.92 UTC
2012-06-20 01:26:46.887 UTC
null
1,341,006
null
625,851
null
1
94
eclipse|auto-indent
138,994
<p>If you press <kbd>CTRL</kbd> + <kbd>I</kbd> it will just format tabs/whitespaces in code and pressing <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>F</kbd> format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.</p>
52,530,578
How use TPU in google colab
<p>Google colab brings TPUs in the Runtime Accelerator. I found an example, How to use TPU in <a href="https://github.com/tensorflow/tpu/blob/master/models/experimental/keras/mnist.py" rel="noreferrer">Official Tensorflow github</a>. But the example not worked on google-colaboratory. It stuck on following line:</p> <pre><code>tf.contrib.tpu.keras_to_tpu_model(model, strategy=strategy) </code></pre> <p>When I <a href="https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow">print available devices</a> on colab it return <code>[]</code> for TPU accelerator. Does anyone knows how to use TPU on colab?</p> <p><a href="https://i.stack.imgur.com/t25us.png" rel="noreferrer"><img src="https://i.stack.imgur.com/t25us.png" alt="enter image description here"></a></p>
52,540,630
1
2
null
2018-09-27 06:16:55.2 UTC
9
2018-11-20 00:35:37.53 UTC
2018-11-20 00:35:37.53 UTC
null
8,841,057
null
1,462,770
null
1
13
tensorflow|keras|google-colaboratory|google-cloud-tpu
16,607
<p>Here's a Colab-specific TPU example: <a href="https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/shakespeare_with_tpu_and_keras.ipynb" rel="noreferrer">https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/shakespeare_with_tpu_and_keras.ipynb</a></p> <p>The key lines are those to connect to the TPU itself:</p> <pre><code># This address identifies the TPU we'll use when configuring TensorFlow. TPU_WORKER = 'grpc://' + os.environ['COLAB_TPU_ADDR'] ... tpu_model = tf.contrib.tpu.keras_to_tpu_model( training_model, strategy=tf.contrib.tpu.TPUDistributionStrategy( tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) </code></pre> <p>(Unlike a GPU, use of the TPU requires an explicit connection to the TPU worker. So, you'll need to tweak your training and inference definition in order to observe a speedup.)</p>
1,712,417
How to wrap selected text in a textarea?
<p>How can I get the user selected text (just inside textarea) and apply actions to it something like wrap the selection <code>[#bold]selected text[/bold]</code>?</p>
1,712,588
2
0
null
2009-11-11 01:24:52.53 UTC
9
2019-04-18 18:42:29.41 UTC
2019-04-18 18:42:29.41 UTC
null
10,607,772
null
185,555
null
1
17
jquery|textarea
12,905
<p>Building off what Soufiane posted, here's the code translated to jquery with the ability to pass in the open and close tags:</p> <pre><code>function wrapText(elementID, openTag, closeTag) { var textArea = $('#' + elementID); var len = textArea.val().length; var start = textArea[0].selectionStart; var end = textArea[0].selectionEnd; var selectedText = textArea.val().substring(start, end); var replacement = openTag + selectedText + closeTag; textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len)); } </code></pre> <p>Usage would then be like so:</p> <pre><code>wrapText("myTextArea", "[#bold]", "[/bold]"); </code></pre>
2,204,140
Codeigniter - handling errors when using active record
<p>I am putting together a few models for my codeigniter site and can't seem to find any word in the documentation of how to handle errors that could occur when using the Active Record system.</p> <p>The documentation demonstrates how to perform CRUD along with some relatively involved queries but no where along the line is error handling discussed. I have done a quick google search and it would appear that the Active Record classes do not throw exceptions. Is this the case? No try catch then...</p> <p>So, how do you code to handle database errors in codeigniter? (failed connection, duplicate key, broken referential integrity, truncation, bad data types etc etc)</p>
2,205,504
2
0
null
2010-02-04 23:58:01.767 UTC
14
2016-01-29 14:19:02.387 UTC
2015-11-22 20:19:00.903 UTC
null
2,680,216
null
178,570
null
1
49
php|codeigniter|activerecord
42,588
<p>Whether you're using the active record class or not, you can access database errors using <code>$this-&gt;db-&gt;_error_message()</code> and <code>$this-&gt;db-&gt;_error_number()</code>.</p> <p>If you're using a mysql database, these functions are equivalent to <code>mysql_error()</code> and <code>mysql_errno()</code> respectively. You can check out these functions by looking at the source code for the database driver for the database you're using. They're located in system/database/drivers.</p> <p>So, after you run a query, you can check for errors using something like:</p> <pre><code>if ($this-&gt;db-&gt;_error_message()) \\handle error </code></pre>
57,157,372
Is there a way to shorten this while condition?
<pre><code>while (temp-&gt;left-&gt;oper == '+' || temp-&gt;left-&gt;oper == '-' || temp-&gt;left-&gt;oper == '*' || temp-&gt;left-&gt;oper == '/' || temp-&gt;right-&gt;oper == '+' || temp-&gt;right-&gt;oper == '-' || temp-&gt;right-&gt;oper == '*' || temp-&gt;right-&gt;oper == '/') { // do something } </code></pre> <p>For clarity: <code>temp</code> is a pointer that points to following <code>node</code> structure:</p> <pre><code>struct node { int num; char oper; node* left; node* right; }; </code></pre>
57,157,451
11
2
null
2019-07-23 05:43:09.523 UTC
7
2020-08-02 16:54:30.173 UTC
2019-11-12 12:03:21.4 UTC
null
9,609,840
null
11,822,605
null
1
53
c++|algorithm|if-statement|while-loop|simplify
7,387
<p>Sure, you could just use a string of valid operators and search it.</p> <pre><code>#include &lt;cstring&gt; // : : const char* ops = "+-*/"; while(strchr(ops, temp-&gt;left-&gt;oper) || strchr(ops, temp-&gt;right-&gt;oper)) { // do something } </code></pre> <p>If you are concerned about performance, then maybe table lookups:</p> <pre><code>#include &lt;climits&gt; // : : // Start with a table initialized to all zeroes. char is_op[1 &lt;&lt; CHAR_BIT] = {0}; // Build the table any way you please. This way using a string is handy. const char* ops = "+-*/"; for (const char* op = ops; *op; op++) is_op[*op] = 1; // Then tests require no searching while(is_op[temp-&gt;left-&gt;oper] || is_op[temp-&gt;right-&gt;oper]) { // do something } </code></pre>
5,737,923
How do I limit the number of connections Jetty will accept?
<p>I'm running Jetty 7.2.2 and want to limit the number of connections it will handle, such that when it reaches a limit (eg 5000), it will start refusing connections. </p> <p>Unfortunately, all the <code>Connectors</code> appear to just go ahead and accept incoming connections as fast as they can and dispatch them to the configured thread pool.</p> <p>My problem is that I'm running in a constrained environment, and I only have access to 8K file descriptors. If I get a bunch of connections coming in I can quickly run out of file descriptors and get into an inconsistent state. </p> <p>One option I have is to return an HTTP <code>503 Service Unavailable</code>, but that still requires me to accept and respond to the connection - and I'd have keep track of the number of incoming connections somewhere, perhaps by writing a servlet filter. </p> <p>Is there a better solution to this?</p>
13,749,849
5
0
null
2011-04-20 23:48:31.747 UTC
9
2018-04-11 20:48:45.767 UTC
2012-12-06 18:13:15.683 UTC
null
389,939
null
389,939
null
1
18
java|jetty|embedded-jetty
54,017
<p>I ended up going with a solution which keeps track of the number of requests and sends a 503 when the load is too high. It's not ideal, and as you can see I had to add a way to always let continuation requests through so they didn't get starved. Works well for my needs:</p> <pre><code>public class MaxRequestsFilter implements Filter { private static Logger cat = Logger.getLogger(MaxRequestsFilter.class.getName()); private static final int DEFAULT_MAX_REQUESTS = 7000; private Semaphore requestPasses; @Override public void destroy() { cat.info("Destroying MaxRequestsFilter"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long start = System.currentTimeMillis(); cat.debug("Filtering with MaxRequestsFilter, current passes are: " + requestPasses.availablePermits()); boolean gotPass = requestPasses.tryAcquire(); boolean resumed = ContinuationSupport.getContinuation(request).isResumed(); try { if (gotPass || resumed ) { chain.doFilter(request, response); } else { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } finally { if (gotPass) { requestPasses.release(); } } cat.debug("Filter duration: " + (System.currentTimeMillis() - start) + " resumed is: " + resumed); } @Override public void init(FilterConfig filterConfig) throws ServletException { cat.info("Creating MaxRequestsFilter"); int maxRequests = DEFAULT_MAX_REQUESTS; requestPasses = new Semaphore(maxRequests, true); } } </code></pre>
5,799,946
Python OCR Module in Linux?
<p>I want to find a easy-to-use OCR python module in linux, I have found pytesser <a href="http://code.google.com/p/pytesser/" rel="noreferrer">http://code.google.com/p/pytesser/</a>, but it contains a .exe executable file.</p> <p>I tried changed the code to use wine, and it really works, but it's too slow and really not a good idea.</p> <p>Is there any Linux alternatives that as easy-to-use as it?</p>
5,799,989
5
1
null
2011-04-27 05:51:45.387 UTC
12
2014-11-20 17:09:01.343 UTC
null
null
null
null
646,735
null
1
21
python|ocr
16,812
<p>You can just wrap <code>tesseract</code> in a function:</p> <pre><code>import os import tempfile import subprocess def ocr(path): temp = tempfile.NamedTemporaryFile(delete=False) process = subprocess.Popen(['tesseract', path, temp.name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.communicate() with open(temp.name + '.txt', 'r') as handle: contents = handle.read() os.remove(temp.name + '.txt') os.remove(temp.name) return contents </code></pre> <p>If you want document segmentation and more advanced features, try out <a href="http://code.google.com/p/ocropus/" rel="noreferrer">OCRopus</a>.</p>
6,155,638
jQuery what instead $(this).parent().children()
<p>Just a quick example:</p> <pre><code>&lt;p&gt; &lt;span class="example"&gt;&lt;/span&gt; &lt;input type="text" name="e_name" id="e_id /&gt; &lt;/p&gt; &lt;script type="text/javascript"&gt; $('input').click(function(){ $(this).parent().children('span').text('Suprise!'); } &lt;/script&gt; </code></pre> <p>What can I use instead parent().children()? </p> <p>I think it's a bit inelegant piece of code. Is any function i.e : $(this).fun('span').text('just better'); ??</p>
6,155,660
5
1
null
2011-05-27 17:19:43.64 UTC
2
2011-05-27 17:23:17.937 UTC
null
null
null
null
772,972
null
1
21
javascript|jquery|parent|children
57,390
<pre><code>$(this).siblings('span').text('Suprise!'); </code></pre>
6,247,066
PHP - Reasons to use Iterators?
<p>I was perusing the manual today and noticed the <a href="http://us2.php.net/manual/en/spl.iterators.php" rel="noreferrer">various iterators</a>. To me, it seems like they are all somewhat pointless; I don't see a reason to use them unless you prefer their syntax, or don't know how to write a recursive function. Are there any reasons to use built-in iterators in PHP over just writing a loop or making a recursive method?</p> <p>I'm only looking for factual responses, not subjective preferences (ie: I don't care if you think it's more "readable" or "more object-oriented", I want to know if they're faster, offer functionality that can't be achieved when rolling your own, etc.).</p>
6,247,166
5
5
null
2011-06-06 01:24:29.813 UTC
12
2014-09-03 12:06:15.8 UTC
2014-09-03 12:06:15.8 UTC
null
225,037
null
638,483
null
1
26
php|iterator
9,458
<p>I believe the main reason is versatility. They don't make things more readable and you can accomplish most of what the <a href="http://www.php.net/manual/en/spl.iterators.php" rel="noreferrer">spl iterators</a> do with a simple <code>foreach</code>.</p> <p>But iterators can serve as sort of a compacted loop or loop source that you can pass around. You can have more diverse data sources than just a list/array. And the real advantage is that you can wrap or stack them for aggregation.</p> <p>The naming is somewhat unobvious, but I guess you could use the <a href="http://php.net/AppendIterator" rel="noreferrer"><code>AppendIterator</code></a> to for example combine a static list of filenames and the result of a <a href="http://php.net/DirectoryIterator" rel="noreferrer"><code>DirectoryIterator</code></a>. Or otherwise wrap that in a <a href="http://php.net/LimitIterator" rel="noreferrer"><code>LimitIterator</code></a> instead of hardwiring that into a <code>for</code> condition. All of these are pretty basic features and can be done manually in a foreach. But at least <a href="http://php.net/RegexIterator" rel="noreferrer"><code>RegexIterator</code></a> and <a href="http://php.net/FilterIterator" rel="noreferrer"><code>FilterIterator</code></a> seem suitable to reduce some complexity.</p> <p>But in the end it's really a stylistic choice. It would make most sense if you have custom objects which traverse something (for example a VFS object which can either point to real files or database entries). But even then you could just <a href="http://php.net/iterator_to_array" rel="noreferrer"><code>iterator_to_array</code></a> convert such a list, and use a normal <code>foreach</code>-over-array.</p> <p>The only case were it is really imperative to prefer iterators were if the data source is unlimited in size. Unfolded arrays for use in a <code>foreach</code> can consume more memory than an iterator which can retrieve element by element.</p>
5,954,021
Animate UIButton state change
<p>I'm using a UIButton with images for normal and highlighted states. They work as expected but I want to have some fading/merging transition and not just a sudden swap.</p> <p>How can I do that?</p>
12,023,139
6
0
null
2011-05-10 17:34:34.823 UTC
19
2021-01-12 10:16:26.657 UTC
null
null
null
null
547,564
null
1
51
iphone|objective-c|uibutton
21,284
<p>This can be done using transition animation of a UIView. It does not matter the <code>isHighlighted</code> property is not animatable, because it transitions the whole view.</p> <h3>Swift 3</h3> <pre><code>UIView.transition(with: button, duration: 4.0, options: .transitionCrossDissolve, animations: { button.isHighlighted = true }, completion: nil) </code></pre> <h3>Objective-C</h3> <pre><code>[UIView transitionWithView:button duration:4.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ button.highlighted = YES; } completion:nil]; </code></pre>
5,645,412
Parsing GET request parameters in a URL that contains another URL
<p>Here is the url:</p> <pre><code>http://localhost/test.php?id=http://google.com/?var=234&amp;key=234 </code></pre> <p>And I can't get the full $_GET['id'] or $_REQUEST['d'].</p> <pre><code>&lt;?php print_r($_REQUEST['id']); //And this is the output http://google.com/?var=234 //the **&amp;key=234** ain't show ?&gt; </code></pre>
5,645,515
7
3
null
2011-04-13 06:47:00.483 UTC
6
2015-09-17 09:52:53.787 UTC
2013-07-20 17:35:55.357 UTC
null
1,356,098
null
569,292
null
1
16
php|get|request|urlencode
112,122
<pre><code>$get_url = "http://google.com/?var=234&amp;key=234"; $my_url = "http://localhost/test.php?id=" . urlencode($get_url); </code></pre> <p>$my_url outputs:</p> <pre><code>http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234 </code></pre> <p>So now you can get this value using <code>$_GET['id']</code> or <code>$_REQUEST['id']</code> (decoded).</p> <pre><code>echo urldecode($_GET["id"]); </code></pre> <p>Output</p> <pre><code>http://google.com/?var=234&amp;key=234 </code></pre> <p>To get every GET parameter:</p> <pre><code>foreach ($_GET as $key=&gt;$value) { echo "$key = " . urldecode($value) . "&lt;br /&gt;\n"; } </code></pre> <p><code>$key</code> is GET key and <code>$value</code> is GET value for <code>$key</code>.</p> <p>Or you can use alternative solution to get array of GET params</p> <pre><code>$get_parameters = array(); if (isset($_SERVER['QUERY_STRING'])) { $pairs = explode('&amp;', $_SERVER['QUERY_STRING']); foreach($pairs as $pair) { $part = explode('=', $pair); $get_parameters[$part[0]] = sizeof($part)&gt;1 ? urldecode($part[1]) : ""; } } </code></pre> <p><code>$get_parameters</code> is same as url decoded <code>$_GET</code>.</p>