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
8,512,802
Checking if a variable is defined in SASS
<p>AS the title says I am trying to check whether a variable is defined in SASS. (I am using compass if that makes any different difference)</p> <p>I've found the Ruby equivalent which is:</p> <pre><code>defined? foo</code></pre> <p>Gave that a shot in the dark but it just gave me the error:</p> <p><code>defined": expected "{", was "?</code></p> <p>I've found a work around (which is obviously just to define the variable in all cases, which in this case it actually makes more sense) but I'd really like to know if this is possible for the future</p>
13,237,776
3
4
null
2011-12-14 22:43:17.927 UTC
15
2020-04-20 20:45:20.473 UTC
2011-12-15 02:06:13.697 UTC
null
708,689
null
708,689
null
1
59
ruby|sass
57,756
<h3>For Sass 3.3 and later</h3> <p>As of Sass 3.3 there is a <code>variable-exists()</code> function. From <a href="http://sass-lang.com/documentation/file.SASS_CHANGELOG.html" rel="noreferrer">the changelog</a>:</p> <blockquote> <ul> <li>It is now possible to determine the existence of different Sass constructs using these new functions: <ul> <li><code>variable-exists($name)</code> checks if a variable resolves in the current scope.</li> <li><code>global-variable-exists($name)</code> checks if a global variable of the given name exists. ...</li> </ul></li> </ul> </blockquote> <p>Example usage:</p> <pre class="lang-sass prettyprint-override"><code>$some_variable: 5; @if variable-exists(some_variable) { /* I get output to the CSS file */ } @if variable-exists(nonexistent_variable) { /* But I don't */ } </code></pre> <hr> <h3>For Sass 3.2.x and earlier (my original answer)</h3> <p>I ran into the same problem today: trying to check if a variable is set, and if so adding a style, using a mixin, etc.</p> <p>After reading that an <code>isset()</code> function <a href="https://github.com/nex3/sass/issues/47" rel="noreferrer">isn't going to be added to sass</a>, I found a simple workaround using the <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#variable_defaults_" rel="noreferrer"><code>!default</code></a> keyword:</p> <pre class="lang-sass prettyprint-override"><code>@mixin my_mixin() { // Set the variable to false only if it's not already set. $base-color: false !default; // Check the guaranteed-existing variable. If it didn't exist // before calling this mixin/function/whatever, this will // return false. @if $base-color { color: $base-color; } } </code></pre> <p>If <code>false</code> is a valid value for your variable, you can use:</p> <pre class="lang-sass prettyprint-override"><code>@mixin my_mixin() { $base-color: null !default; @if $base-color != null { color: $base-color; } } </code></pre>
8,512,588
Tomcat: LifecycleException when deploying
<p>I just downloaded the Tomcat 7.0.23 package on my Ubuntu 11.10. </p> <p>I followed the instructions on a Google API website to <a href="http://code.google.com/apis/chart/interactive/docs/dev/dsl_get_started.html#webapp" rel="noreferrer">deploy their example webapp</a>. It basically consists of <code>jar</code> files placed in the <code>WEB-INF/lib</code> directory and a <code>web.xml</code> file placed in the <code>WEB-INF</code> directory. </p> <p>Yet the app is not automatically deployed and when trying to <em>force</em> the server to deploy it through the manager gui, I get the following message:</p> <pre><code>FAIL - Application at context path /myWebApp could not be started FAIL - Encountered exception org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/myWebApp]] </code></pre> <p>However, the JSP examples provided with Tomcat do work!</p> <p>I have the same problem on Tomcat6.</p> <p>So what did I do wrong ? Is this a permission problem ? (I even try to change the mod of all files to 777).</p>
8,512,930
17
5
null
2011-12-14 22:25:09.127 UTC
5
2022-03-21 14:43:59.94 UTC
2016-01-13 10:55:12.257 UTC
null
3,885,376
null
749,588
null
1
50
tomcat|lifecycleexception
213,779
<p>This means something is wrong with your application configuration or startup. </p> <p>There is always information about that in the logs - check <code>logs/catalina.out</code> and figure out what is wrong.</p>
8,389,812
How are generators and coroutines implemented in CPython?
<p>I've read that in CPython, the interpreter stack (the list of Python functions called to reach this point) is mixed with the C stack (the list of C functions that were called in the interpreter's own code). If so, then how are generators and coroutines implemented? How do they remember their execution state? Does CPython copy each generator's / coroutine's stack to and from an OS stack? Or does CPython simply keep the generator's topmost stack frame on the heap, since the generator can only yield from that topmost frame?</p>
8,390,077
2
5
null
2011-12-05 18:10:16.553 UTC
22
2015-05-06 04:02:59.853 UTC
null
null
null
null
618,967
null
1
58
python|coroutine
6,809
<p>The <code>yield</code> instruction takes the current executing context as a closure, and transforms it into an own living object. This object has a <code>__iter__</code> method which will continue after this yield statement.</p> <p>So the call stack gets transformed into a heap object.</p>
5,111,828
How to have a UISwipeGestureRecognizer AND UIPanGestureRecognizer work on the same view
<p>How would you setup the gesture recognizers so that you could have a <strong>UISwipeGestureRecognizer</strong> and a <strong>UIPanGestureRecognizer</strong> work at the same time? Such that if you touch and move quickly (quick swipe) it detects the gesture as a swipe but if you touch then move (short delay between touch &amp; move) it detects it as a pan?</p> <p>I've tried various permutations of <strong>requireGestureRecognizerToFail</strong> and that didn't help exactly, it made it so that if the SwipeGesture was left then my pan gesture would work up, down and right but any movement left was detected by the swipe gesture.</p>
5,113,187
4
0
null
2011-02-24 23:24:26.373 UTC
14
2019-07-17 23:22:26.743 UTC
null
null
null
null
155,513
null
1
26
iphone|objective-c|uigesturerecognizer|gesture-recognition
15,421
<p>You're going to want to set one of the two <code>UIGestureRecognizer</code>'s delegates to an object that makes sense (likely <code>self</code>) then listen, and return <code>YES</code> for this <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIGestureRecognizerDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIGestureRecognizerDelegate" rel="nofollow noreferrer">method</a>:</p> <pre><code>- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer: (UIGestureRecognizer *)otherGestureRecognizer { return YES; } </code></pre> <p>This method is called when recognition of a gesture by either <code>gestureRecognizer</code> or <code>otherGestureRecognizer</code> would block the other gesture recognizer from recognizing its gesture. Note that returning <code>YES</code> is guaranteed to allow simultaneous recognition; returning <code>NO</code>, on the other hand, is not guaranteed to prevent simultaneous recognition because the other gesture recognizer's delegate may return <code>YES</code>.</p>
5,029,183
Android dialer application
<p>I am figuring out a way to replace the default dialer application from my custom dialer application, but I am not getting how to achieve this.</p> <p>Here is what I want</p> <ul> <li>Create a custom dialer UI</li> <li>My application is called whenever call button hardware or that one in Android is pressed</li> <li>The application can also be called from the contact screen</li> </ul> <p>I am referring to <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_DIAL" rel="noreferrer">public static final String ACTION_DIAL</a>.</p>
5,029,367
4
1
null
2011-02-17 12:56:20.783 UTC
26
2018-04-16 18:26:07.827 UTC
2017-08-18 12:07:13.113 UTC
null
1,000,551
null
517,247
null
1
32
android|phone-call
57,399
<ol> <li><p>Create a simple Android application (our dialer). To actually call someone, you just need that method:</p> <pre><code>private void performDial(String numberString) { if (!numberString.equals("")) { Uri number = Uri.parse("tel:" + numberString); Intent dial = new Intent(Intent.ACTION_CALL, number); startActivity(dial); } } </code></pre></li> <li><p>Give your application permission to call in AndroidManifest</p> <pre><code>&lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt; </code></pre></li> <li><p>Set in AndroidManifest intention that says to your phone to use your app when need a dialer</p></li> </ol> <p>When someone press the call button:</p> <pre><code> &lt;intent-filter&gt; &lt;action android:name="android.intent.action.CALL_BUTTON" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; </code></pre> <p>When someone fire an URI:</p> <pre><code> &lt;intent-filter&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;action android:name="android.intent.action.DIAL" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:scheme="tel" /&gt; &lt;/intent-filter&gt; </code></pre>
4,880,286
Is a Markov chain the same as a finite state machine?
<p>Is a finite state machine just an implementation of a Markov chain? What are the differences between the two?</p>
4,880,350
6
2
null
2011-02-02 21:52:02.137 UTC
22
2019-07-06 22:45:17.14 UTC
2017-07-13 07:56:42.763 UTC
null
527,702
null
200,619
null
1
92
math|statistics|state-machine|fsm|markov-chains
27,805
<p>Markov chains can be represented by finite state machines. The idea is that a Markov chain describes a process in which the transition to a state at time t+1 depends only on the state at time t. The main thing to keep in mind is that the transitions in a Markov chain are probabilistic rather than deterministic, which means that you can't always say with perfect certainty what will happen at time t+1. </p> <p>The Wikipedia articles on <a href="http://en.wikipedia.org/wiki/Finite_state_machine" rel="noreferrer">Finite-state machines</a> has a subsection on <a href="https://en.wikipedia.org/wiki/Finite-state_machine#Finite_Markov_chain_processes" rel="noreferrer">Finite Markov-chain processes</a>, I'd recommend reading that for more information. Also, the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">Markov chains</a> has a brief sentence describing the use of finite state machines in representing a Markov chain. That states:</p> <blockquote> <p>A finite state machine can be used as a representation of a Markov chain. Assuming a sequence of independent and identically distributed input signals (for example, symbols from a binary alphabet chosen by coin tosses), if the machine is in state y at time n, then the probability that it moves to state x at time n + 1 depends only on the current state.</p> </blockquote>
5,061,640
make arrayList.toArray() return more specific types
<p>So, normally <code>ArrayList.toArray()</code> would return a type of <code>Object[]</code>....but supposed it's an <code>Arraylist</code> of object <code>Custom</code>, how do I make <code>toArray()</code> to return a type of <code>Custom[]</code> rather than <code>Object[]</code>?</p>
5,061,692
6
2
null
2011-02-21 02:07:10.953 UTC
31
2021-10-19 12:51:58.46 UTC
2013-11-26 00:01:57.843 UTC
null
1,102,512
null
380,714
null
1
218
java|arrays|object|types|arraylist
183,065
<p>Like this:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(); String[] a = list.toArray(new String[0]); </code></pre> <p>Before Java6 it was recommended to write:</p> <pre><code>String[] a = list.toArray(new String[list.size()]); </code></pre> <p>because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see <a href="https://stackoverflow.com/questions/174093">.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?</a></p> <p>If your list is not properly typed you need to do a cast before calling toArray. Like this:</p> <pre><code> List l = new ArrayList&lt;String&gt;(); String[] a = ((List&lt;String&gt;)l).toArray(new String[l.size()]); </code></pre>
5,183,251
Querying Users who 'like' my Facebook Page
<p>I was wondering if it was possible to query the following:</p> <ul> <li>List of (all) users who like my facebook page, and</li> <li>Additional information those users have made publicly available (beyond first and last name)</li> </ul> <p>Basically looking to generate detailed marketing stats of users who like my facebook page, if possible. Any suggestions or alternatives welcome.</p> <p>Thank you.</p>
5,186,725
8
2
null
2011-03-03 16:03:16.543 UTC
16
2018-09-28 13:49:40.827 UTC
null
null
null
null
643,274
null
1
23
facebook|facebook-graph-api
46,016
<p>I am afraid this is <strong>NOT</strong> possible, follow this <a href="https://developers.facebook.com/bugs/147185208750426">bug</a> for more information. </p> <p>Another proof is the <code>page_fan</code> table you will notice that only the <code>uid</code> field is indexable so you <strong>need</strong> to know the user id to search it and not the <code>page_id</code>, as you know if a user "<em>likes</em>" a page this would mean he is a "<em>fan</em>" of that page. </p> <hr> <p>After being actively working with the Facebook API for a while now, and following the announcements and API releases (and deprecations) along with the introduction and changes of policies, I <em>can</em> understand that Facebook will only share info about their users by letting them explicitly do so (a.k.a interact/authorize your Apps). </p> <p>And hence the best thing to do in the absence of such feature is: </p> <ol> <li>Understand your audience through <a href="https://www.facebook.com/help/336893449723054/">Page Insights</a></li> <li>Collect fans interests &amp; info by creating custom apps through <a href="https://developers.facebook.com/docs/appsonfacebook/pagetabs/">Page Tabs</a> and using other Facebook features like <a href="https://www.facebook.com/help/facebook-questions">Questions</a></li> </ol>
5,346,694
How to implement a lock in JavaScript
<p>How could something equivalent to <code>lock</code> in C# be implemented in JavaScript?</p> <p>So, to explain what I'm thinking a simple use case is: </p> <p>User clicks button <code>B</code>. <code>B</code> raises an onclick event. If <code>B</code> is in <code>event-state</code> the event waits for <code>B</code> to be in <code>ready-state</code> before propagating. If <code>B</code> is in <code>ready-state</code>, <code>B</code> is locked and is set to <code>event-state</code>, then the event propagates. When the event's propagation is complete, <code>B</code> is set to <code>ready-state</code>.</p> <p>I could see how something close to this could be done, simply by adding and removing the class <code>ready-state</code> from the button. However, the problem is that a user can click a button twice in a row faster than the variable can be set, so this attempt at a lock will fail in some circumstances.</p> <p>Does anyone know how to implement a lock that will not fail in JavaScript?</p>
5,347,055
9
7
null
2011-03-17 23:57:20.66 UTC
30
2022-08-25 05:36:24.097 UTC
2020-07-19 11:17:28.527 UTC
null
4,370,109
null
344,211
null
1
104
javascript|events|locking|dom-events|deadlock
127,898
<p>Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:</p> <pre><code>var functionLock = false; var functionCallbacks = []; var lockingFunction = function (callback) { if (functionLock) { functionCallbacks.push(callback); } else { $.longRunning(function(response) { while(functionCallbacks.length){ var thisCallback = functionCallbacks.pop(); thisCallback(response); } }); } } </code></pre> <p>You can also implement this using DOM event listeners or a pubsub solution.</p>
12,541,419
PHP keep checkbox checked after submitting form
<p>Hi all i have a contact form and captcha is there. i want keep the check is checked after submitting the form. I posted the textbox values and it showing correctly but checkbox is not working. here is my code.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action = "" name="frmSubmit" method="post"&gt; &lt;input type="checkbox" name="txtCheck" value="&lt;?php echo $_POST['txtCheck'];?&gt;" /&gt;&lt;br /&gt; &lt;label&gt;Name&lt;/label&gt;&lt;br /&gt; &lt;input type="text" name="txtName" id="NameTextBox" value="&lt;?php echo $_POST['txtName']; ?&gt;" /&gt; &lt;br /&gt; &lt;label&gt;E Mail&lt;/label&gt;&lt;br /&gt; &lt;input type="text" name="txtEmail" id="EmailTextBox" value="&lt;?php echo $_POST['txtEmail'];?&gt;" /&gt; &lt;input name="BtnSubmit" type="submit" onclick="MM_validateForm('NameTextBox','','R','EmailTextBox','','R');return document.MM_returnValue" value="Send" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How to keep check box after submitting the form.?</p>
12,541,453
5
0
null
2012-09-22 06:40:05.347 UTC
2
2021-02-19 06:19:41.067 UTC
null
null
null
null
1,567,706
null
1
11
php|html
54,652
<p>change</p> <pre><code>&lt;input type="checkbox" name="txtCheck" value="&lt;?php echo $_POST['txtCheck'];?&gt;" /&gt;&lt;br /&gt; </code></pre> <p>to</p> <pre><code>&lt;input type="checkbox" name="txtCheck" value="your value" &lt;?php if(isset($_POST['txtCheck'])) echo "checked='checked'"; ?&gt; /&gt;&lt;br /&gt; </code></pre> <p>this will keep checkbox checked..</p>
12,530,085
How to setup SVN on Mac OS X 10.8.2?
<p>I have found information that SVN comes with Mac OS X. But there was no SVN on my system. I have installed <code>Subversion-1.6.17-1_10.7.x.pkg</code> and all was good. But after update to Mac OS X 10.8.2 all SVN files were automatically removed from the system. I have tried to install <code>Subversion-1.6.17-1_10.7.x.pkg</code> again - but Next button is disabled. I have tried to found an updated version - but there is no Mac OS support now.</p> <p>How to simply setup SVN on Mac OS X 10.8.2?</p> <p>Thanks a lot for the help.</p>
12,532,138
1
5
null
2012-09-21 11:54:30.753 UTC
2
2012-09-21 14:04:41.997 UTC
2012-09-21 12:03:55.167 UTC
null
865,475
null
865,475
null
1
12
macos|svn|installation
66,756
<p>After you have installed Xcode 4.5 you need to follow <a href="https://stackoverflow.com/a/9329325/253056">these instructions</a> in order to install the command line tools. Once you've done that successfully then you should see that svn is installed:</p> <pre><code>$ which svn /usr/bin/svn $ svn --version svn, version 1.6.18 (r1303927) compiled Aug 4 2012, 19:46:53 Copyright (C) 2000-2009 CollabNet. Subversion is open source software, see http://subversion.apache.org/ This product includes software developed by CollabNet (http://www.Collab.Net/). The following repository access (RA) modules are available: * ra_neon : Module for accessing a repository via WebDAV protocol using Neon. - handles 'http' scheme - handles 'https' scheme * ra_svn : Module for accessing a repository using the svn network protocol. - handles 'svn' scheme * ra_local : Module for accessing a repository on local disk. - handles 'file' scheme $ </code></pre>
12,527,433
correct way of comparing string jquery operator =
<p>Is this the correct way? I want the statement to run if the value of somevar equals the string? </p> <pre><code>if (somevar = '836e3ef9-53d4-414b-a401-6eef16ac01d6'){ $("#code").text(data.DATA[0].ID); } </code></pre>
12,527,475
3
1
null
2012-09-21 09:05:08.873 UTC
2
2012-09-21 09:14:38.04 UTC
null
null
null
null
578,822
null
1
19
jquery
161,108
<p>No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.</p> <p>Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.</p> <p>More information also in <a href="https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use">this great answer</a></p>
12,400,860
ActiveRecord includes. Specify included columns
<p>I have model Profile. Profile has_one User. User model has field email. When I call</p> <pre><code>Profile.some_scope.includes(:user) </code></pre> <p>it calls</p> <pre><code>SELECT users.* FROM users WHERE users.id IN (some ids) </code></pre> <p>But my User model has many fields that I am not using in rendering. Is it possible to load only emails from users? So, SQL should look like</p> <pre><code>SELECT users.email FROM users WHERE users.id IN (some ids) </code></pre>
12,409,672
6
0
null
2012-09-13 06:48:17.783 UTC
13
2020-06-10 12:47:09.197 UTC
2018-09-08 04:21:36.37 UTC
null
2,262,149
null
1,262,284
null
1
37
ruby-on-rails|ruby-on-rails-3|rails-activerecord
30,132
<p>Rails doesn't have the facility to pass the options for <strong>include</strong> query. But we can pass these params with the <strong>association declaration</strong> under the model.</p> <p>For your scenario, you need to create a new association with users model under the profile model, like below</p> <pre><code>belongs_to :user_only_fetch_email, :select =&gt; "users.id, users.email", :class_name =&gt; "User" </code></pre> <p>I just created one more association but it points to User model only. So your query will be,</p> <pre><code>Profile.includes(:user_only_fetch_email) </code></pre> <p>or</p> <pre><code>Profile.includes(:user_only_fetch_email).find(some_profile_ids) </code></pre>
12,095,113
R knitr: Possible to programmatically modify chunk labels?
<p>I'm trying to use knitr to generate a report that performs the same set of analyses on different subsets of a data set. The project contains two Rmd files: the first file is a master document that sets up the workspace and the document, the second file only contains chunks that perform the analyses and generates associated figures.</p> <p>What I would like to do is knit the master file, which would then call the second file for each data subset and include the results in a single document. Below is a simple example.</p> <p>Master document:</p> <pre><code># My report ```{r} library(iterators) data(mtcars) ``` ```{r create-iterator} cyl.i &lt;- iter(unique(mtcars$cyl)) ``` ## Generate report for each level of cylinder variable ```{r cyl4-report, child='analysis-template.Rmd'} ``` ```{r cyl6-report, child='analysis-template.Rmd'} ``` ```{r cyl8-report, child='analysis-template.Rmd'} ``` </code></pre> <p>analysis-template.Rmd:</p> <pre><code>```{r, results='asis'} cur.cyl &lt;- nextElem(cyl.i) cat("###", cur.cyl) ``` ```{r mpg-histogram} hist(mtcars$mpg[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders")) ``` ```{r weight-histogam} hist(mtcars$wt[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders")) ``` </code></pre> <p>The problem is knitr does not allow for non-unique chunk labels, so knitting fails when <code>analysis-template.Rmd</code> is called the second time. This problem could be avoided by leaving the chunks unnamed since unique labels would then be automatically generated. This isn't ideal, however, because I'd like to use the chunk labels to create informative filenames for the exported plots.</p> <hr> <p>A potential solution would be using a simple function that appends the current cylinder to the chunk label:</p> <pre><code>```r{paste('cur-label', cyl, sep = "-")} ``` </code></pre> <p>But it doesn't appear that knitr will evaluate an expression in the chunk label position.</p> <hr> <p>I also tried using a custom <a href="http://yihui.name/knitr/hooks#chunk_hooks">chunk hook</a> that modified the current chunk's label: </p> <pre><code>knit_hooks$set(cyl.suffix = function(before, options, envir) { if (before) options$label &lt;- "new-label" }) </code></pre> <p>But changing the chunk label didn't affect the filenames for generated plots, so I didn't think knitr was utilizing the new label.</p> <hr> <p>Any ideas on how to change chunk labels so the same child document can be called multiple times? Or perhaps an alternative strategy to accomplish this? </p>
14,368,148
3
0
null
2012-08-23 15:27:37.567 UTC
26
2019-04-09 00:58:27.92 UTC
null
null
null
null
1,560,000
null
1
50
r|knitr
7,539
<p>For anyone else who comes across this post, I wanted to point out that @Yihui has provided a <a href="https://github.com/yihui/knitr/blob/master/vignettes/knit_expand.Rmd" rel="noreferrer">formal solution</a> to this question in knitr 1.0 with the introduction of the <code>knit_expand()</code> function. It works great and has really simplified my workflow. </p> <p>For example, the following will process the template script below for every level of <code>mtcars$cyl</code>, each time replacing all instances of <code>{{ncyl}}</code> (in the template) with its current value:</p> <pre><code># My report ```{r} data(mtcars) cyl.levels &lt;- unique(mtcars$cyl) ``` ## Generate report for each level of cylinder variable ```{r, include=FALSE} src &lt;- lapply(cyl.levels, function(ncyl) knit_expand(file = "template.Rmd")) ``` `r knit(text = unlist(src))` </code></pre> <p>Template:</p> <pre><code>```{r, results='asis'} cat("### {{ncyl}} cylinders") ``` ```{r mpg-histogram-{{ncyl}}cyl} hist(mtcars$mpg[mtcars$cyl == {{ncyl}}], main = paste({{ncyl}}, "cylinders")) ``` ```{r weight-histogam-{{ncyl}}cyl} hist(mtcars$wt[mtcars$cyl == {{ncyl}}], main = paste({{ncyl}}, "cylinders")) ``` </code></pre>
12,077,083
What is the difference between allprojects and subprojects
<p>On a multi-project gradle build, can someone tell me what exactly is the difference between the "allprojects" section and the "subprojects" one? Just the parent directory? Does anyone use both? If so, do you have general rules that determines what typically is put in each one?</p> <p>Related question: what is the difference between the two syntaxes (really for allprojects AND subprojects):</p> <pre><code>subprojects { ... } </code></pre> <p>and </p> <pre><code>configure(subprojects) { ... } </code></pre> <p>When would you one over the other?</p>
12,077,290
2
0
null
2012-08-22 16:02:50.613 UTC
16
2012-08-22 16:32:51.81 UTC
null
null
null
null
1,538,856
null
1
159
gradle
52,528
<p>In a multi-project gradle build, you have a rootProject and the subprojects. The combination of both is allprojects. The rootProject is where the build is starting from. A common pattern is a rootProject has no code and the subprojects are java projects. In which case, you apply the java plugin to only the subprojects:</p> <pre><code>subprojects { apply plugin: 'java' } </code></pre> <p>This would be equivalent to a maven aggregate pom project that just builds the sub-modules.</p> <p>Concerning the two syntaxes, they do the exact same thing. The first one just looks better.</p>
44,328,225
Can't change emulated performance of AVD in Android Studio
<p>I can't change the graphics to software as I'm sure this is the fix for my AVD not launching. The option is greyed out (see screenshot). Has anyone has experience with this? I couldn't find anyone who had the same issue.</p> <p>I'm running the latest version of Android Studio on Ubuntu 17.04.</p> <p><a href="https://i.stack.imgur.com/Vzv1W.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vzv1W.png" alt="Screenshot of the configuration of the AVD"></a></p>
46,720,472
9
5
null
2017-06-02 11:49:28.987 UTC
26
2021-11-16 14:04:31.703 UTC
null
null
null
null
3,722,568
null
1
131
android|android-studio|avd|ubuntu-17.04
100,819
<p>Actually, this problem seems to be limited to devices with <strong>Play Store</strong> available, so Nexus 5X and Nexus 5 images will be forced to use Automatic Graphics, but all other devices allow you to choose either Automatic, Hardware or Software graphics.</p> <hr> <p><em>edit:</em> I've just tested this today and it seems to no longer be the case. At least on MacOS with Android Studio 3.3.2, I can now make a Nexus 5X image with Play Store and Hardware Graphics. I'll do more testing at home later, on Windows and Linux to see if it's related to OS or graphics drivers. <a href="https://i.stack.imgur.com/kn3RO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kn3RO.png" alt="AVD screen showing a Nexus 5X device with hardware graphics"></a></p>
18,824,461
Display data from database inside <table> using wordpress $wpdb
<p>Can someone help me, how to code the logic to print the data from my database into a <code>&lt;table&gt;</code>?</p> <pre><code>&lt;table border=&quot;1&quot;&gt; &lt;tr&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;th&gt;Points&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;?php global $wpdb; $result = $wpdb-&gt;get_results ( &quot;SELECT * FROM myTable&quot; ); foreach ( $result as $print ) { echo '&lt;td&gt;' $print-&gt;firstname.'&lt;/td&gt;'; } ?&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><img src="https://i.stack.imgur.com/f4vKl.png" alt="table" /></p> <p>I know this is so basic, but I'm having a hard time making this work.</p>
18,824,758
4
5
null
2013-09-16 09:20:32.3 UTC
4
2022-08-05 10:02:02.09 UTC
2022-08-05 10:02:02.09 UTC
null
19,664,042
null
1,933,824
null
1
3
php|wordpress|html-table
61,759
<p>Try this: </p> <pre><code>&lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;th&gt;Points&lt;/th&gt; &lt;/tr&gt; &lt;?php global $wpdb; $result = $wpdb-&gt;get_results ( "SELECT * FROM myTable" ); foreach ( $result as $print ) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $print-&gt;firstname;?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; </code></pre> <p></p>
24,009,119
UTF-8 Encoding ; Only some Japanese characters are not getting converted
<p>I am getting the parameter value as parameter from the <strong>Jersey Web Service</strong>, which is in Japaneses characters.</p> <p>Here, <strong>'japaneseString'</strong> is the web service parameter containing the characters in japanese language.</p> <pre><code> String name = new String(japaneseString.getBytes(), "UTF-8"); </code></pre> <p>However, I am able to convert a few sting literals successfully, while some of them are creating problems.</p> <p>The following were successfully converted:</p> <pre><code> 1) アップル 2) 赤 3) 世丕且且世两上与丑万丣丕且丗丕 4) 世世丗丈 </code></pre> <p>While these din't:</p> <pre><code> 1) ひほわれよう 2) 存在する </code></pre> <p>When I further investigated, i found that these 2 strings are getting converted in to some JUNK characters.</p> <pre><code> 1) Input: ひほわれよう Output : �?��?��?れよ�?� 2) Input: 存在する Output: 存在�?�る </code></pre> <p>Any idea why some of the japanese characters are not converted properly?</p> <p>Thanks.</p>
24,074,921
3
5
null
2014-06-03 07:13:14.623 UTC
2
2014-06-06 05:40:26.153 UTC
null
null
null
null
2,323,536
null
1
9
java|encoding|utf-8|character-encoding|utf
62,235
<p>Try with JVM parameter file.encoding to set with value UTF-8 in startup of Tomcat(JVM). E.x.: -Dfile.encoding=UTF-8</p>
3,905,734
How to send 100,000 emails weekly?
<p>How can one send an email to 100,000 users on a weekly basis in PHP? This includes mail to subscribers using the following providers:</p> <ul> <li>AOL</li> <li>G-Mail</li> <li>Hotmail</li> <li>Yahoo</li> </ul> <p>It is important that all e-mail actually be delivered, to the extent that it is possible. Obviously, just sending the mail conventionally would do nothing but create problems.</p> <p>Is there a library for PHP that makes this simpler? </p>
3,905,805
3
0
null
2010-10-11 11:24:18.32 UTC
325
2014-02-05 00:54:39.12 UTC
2012-06-15 10:36:09.943 UTC
null
367,456
null
244,413
null
1
-146
php|email|mailing-list|massmail
163,079
<p><strong>Short answer:</strong> While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to <strong>outsource this</strong> to one of the companies that specialize in it (I <em>did</em> say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).</p> <p><strong>Long answer:</strong> If you decide that you <em>absolutely want</em> to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:</p> <ul> <li>e-mail content that <em>is not</em> spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)</li> <li>in addition, your content should be easy to <em>distinguish</em> from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)</li> <li>a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)</li> <li>some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's <code>mail()</code> is horrible enough by itself)</li> <li>your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)</li> </ul> <p>Surprisingly, that was the easy part. The hard part is actually sending it:</p> <ul> <li>some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])</li> <li>you need to have correct <a href="http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html" rel="nofollow noreferrer">PTR, SPF, DKIM records</a></li> <li>handling remote server timeouts, misconfigured DNS records and other network pleasantries</li> <li>handling invalid e-mails (and no, <a href="https://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378">regex is the wrong tool for that</a>)</li> <li>handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)</li> <li>handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")</li> <li>handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it <em>will</em> happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On <em>average</em>, it takes weeks to get yourself removed from a blacklist.)</li> </ul> <p>And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).</p> <p>I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:</p> <ul> <li>the remote SMTP servers don't want to talk to your SMTP server</li> <li>your mails are getting marked as spam (<code>&lt;blink&gt;</code> is not your friend here, nor is <code>&lt;font color=...&gt;</code>)</li> <li>your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)</li> <li>your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)</li> <li>your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail <em>looks</em> more suspicious)</li> <li>your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))</li> <li>users with various versions of Microsoft Outlook and its <em>special</em> handling of Internet mail</li> <li>wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you <strong>really</strong> don't want to be the one to set this off, as you'd anger half the internet at yourself)</li> </ul> <p>and it'll be <em>your</em> job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.</p> <p>If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.</p>
38,118,572
Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources
<p>I'm trying to run the spark examples from <code>Eclipse</code> and getting this generic error: <code>Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources.</code></p> <p>The version I have is <code>spark-1.6.2-bin-hadoop2.6.</code> I started spark using the <code>./sbin/start-master.sh</code> command from a shell, and set my <code>sparkConf</code> like this: </p> <pre><code>SparkConf conf = new SparkConf().setAppName("Simple Application"); conf.setMaster("spark://My-Mac-mini.local:7077"); </code></pre> <p>I'm not bringing any other code here because this error pops up with any of the examples I'm running. The machine is a Mac OSX and I'm pretty sure it has enough resources to run the simplest examples. </p> <p>What am I missing? </p>
38,123,434
7
9
null
2016-06-30 09:07:53.047 UTC
6
2022-05-24 15:57:58.353 UTC
null
null
null
null
373,386
null
1
33
java|hadoop|apache-spark
64,245
<p>The error indicates that you cluster has insufficient resources for current job.Since you have not started the slaves i.e worker . The cluster won't have any resources to allocate to your job. Starting the slaves will work.</p> <pre><code>`start-slave.sh &lt;spark://master-ip:7077&gt;` </code></pre>
8,835,373
UI Issue with kal calendar for ipad?
<p>I have UI issue with Kal Calendar for iPad. On the iPad there is an empty space but on the iPhone it's fine. How can i get it to fit in the frame on the iPad?</p> <pre><code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { [kal.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { [kal.view setFrame:CGRectMake(0, 0,768 ,1004)]; } </code></pre> <p>I tried to use the code listed above but it did not work for me!</p> <p><img src="https://i.stack.imgur.com/pesIK.png" alt="enter image description here"></p>
8,839,910
1
6
null
2012-01-12 12:51:22.763 UTC
10
2014-05-23 12:54:04.063 UTC
2012-08-05 13:13:22.453 UTC
null
106,435
null
905,582
null
1
6
objective-c|ios|cocoa-touch|ipad
1,816
<p>in KalGridView.m you'll find this.</p> <pre><code>const CGSize kTileSize = { 46.f, 44.f }; </code></pre> <p>I'd change the code to a property where you can set the frame dynamically to the idiom and/or orientation.</p> <p>in KalGridView.m</p> <pre><code> const CGSize kTileSize = { 109.0f, 109.0f }; </code></pre> <p>and in KalView.m</p> <pre><code>- (void)addSubviewsToHeaderView:(UIView *)headerView … for (CGFloat xOffset = 0.f; xOffset &lt; headerView.width; xOffset += 109.f, i = (i+1)%7) { CGRect weekdayFrame = CGRectMake(xOffset, 30.f, 109.f, kHeaderHeight - 29.f); UILabel *weekdayLabel = [[UILabel alloc] initWithFrame:weekdayFrame]; weekdayLabel.backgroundColor = [UIColor clearColor]; weekdayLabel.font = [UIFont boldSystemFontOfSize:10.f]; weekdayLabel.textAlignment = UITextAlignmentCenter; weekdayLabel.textColor = [UIColor colorWithRed:0.3f green:0.3f blue:0.3f alpha:1.f]; weekdayLabel.shadowColor = [UIColor whiteColor]; weekdayLabel.shadowOffset = CGSizeMake(0.f, 1.f); weekdayLabel.text = [weekdayNames objectAtIndex:i]; [headerView addSubview:weekdayLabel]; [weekdayLabel release]; } } </code></pre> <p>results in:</p> <p><img src="https://i.stack.imgur.com/mA8P3.png" alt="screenshot "></p>
8,461,851
What is better, appending new elements via DOM functions, or appending strings with HTML tags?
<p>I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either </p> <pre><code>document.getElementById('foo').innerHTML ='&lt;p&gt;Here is a brand new paragraph!&lt;/p&gt;'; </code></pre> <p>or</p> <pre><code>newElement = document.createElement('p'); elementText = document.createTextNode('Here is a brand new parahraph!'); newElement.appendChild(elementText); document.getElementById('foo').appendChild(newElement); </code></pre> <p>but I'm not sure of the advantages to doing either one. Is there a rule of thumb as to when one should be done over the other, or is one of these just flat out wrong?</p>
8,461,877
6
8
null
2011-12-11 03:55:52.423 UTC
10
2019-03-22 21:51:41.483 UTC
2011-12-11 16:27:03.75 UTC
null
153,110
null
153,110
null
1
23
javascript|dom|appendchild
7,208
<p>Some notes:</p> <ul> <li><p>Using <code>innerHTML</code> is faster in IE, but slower in chrome + firefox. <a href="http://jsperf.com/innerhtml-vs-w3c-dom/6" rel="noreferrer">Here's one benchmark</a> showing this with a constantly varying set of <code>&lt;div&gt;</code>s + <code>&lt;p&gt;</code>s; <a href="http://jsperf.com/dom-table-generation" rel="noreferrer">here's a benchmark</a> showing this for a constant, simple <code>&lt;table&gt;</code>.</p></li> <li><p>On the other hand, the DOM methods are the traditional standard -- <code>innerHTML</code> is standardized in HTML5 -- and allow you to retain references to the newly created elements, so that you can modify them later.</p></li> <li><p>Because innerHTML is fast (enough), concise, and easy to use, it's tempting to lean on it for every situation. But beware that using <strong><code>innerHTML</code> detaches all existing DOM nodes</strong> from the document. Here's an example you can test on this page.</p> <p>First, let's create a function that lets us test whether a node is on the page:</p> <pre><code>function contains(parent, descendant) { return Boolean(parent.compareDocumentPosition(descendant) &amp; 16); } </code></pre> <p>This will return <code>true</code> if <code>parent</code> contains <code>descendant</code>. Test it like this:</p> <pre><code>var p = document.getElementById("portalLink") console.log(contains(document, p)); // true document.body.innerHTML += "&lt;p&gt;It's clobberin' time!&lt;/p&gt;"; console.log(contains(document, p)); // false p = document.getElementById("portalLink") console.log(contains(document, p)); // true </code></pre> <p>This will print:</p> <pre><code>true false true </code></pre> <p>It may not look like our use of <code>innerHTML</code> should have affected our reference to the <code>portalLink</code> element, but it does. It needs to be retrieved again for proper use. </p></li> </ul>
20,623,883
Sublime text find in selection
<p>When I select multiple lines of text in text editor Sublime Text 3, and try to find (<kbd>Ctrl</kbd>+<kbd>F</kbd>) an existing string in it, it fails. In fact, any highlighting I do somehow makes the string unfindable. For example, if I highlight all text in my file, and <kbd>Ctrl</kbd>+<kbd>F</kbd> an existing string, it is unable to find any matches. Only when the string I want to find is not highlighted can the string be searched.</p> <p>I have the 'in selection', 'highlight matches', and 'wrap' flags on when highlighting. My user preferences are as follows:</p> <pre><code>{ "color_scheme": "Packages/Color Scheme - Default/Monokai.tmTheme", "font_size": 10, "auto_find_in_selection": true, "trim_trailing_white_space_on_save": true, "ignored_packages": [ "Vintage" ] } </code></pre> <p>Any help will be appreciated. I have been trying to figure this out for an hour. Originally I had "auto_find_in_selection" set to false - I thought that was the culprit, but the problem persisted even after setting it to true.</p>
20,799,096
2
4
null
2013-12-17 00:48:13.037 UTC
3
2018-10-02 09:16:59.877 UTC
2014-09-30 00:55:25.08 UTC
null
1,696,030
null
2,827,314
null
1
34
sublimetext|sublimetext3
16,805
<p>I had been fighting with this problem as well and for now (ST3 Build 3059) it still seems to be a bug. It seems like that the editor is not updating the selection for the search/replace bar while you have it open.</p> <p>Here's a workaround:</p> <p>1) Close the find/replace bar</p> <p>2) Make your selection </p> <p>3) Open search/replace bar and enter your search query</p> <p>Hope this helps!</p>
11,204,891
How to open .msu extension file?
<p>I have downloaded a file WINDOWS POWERSHELL that has an .msu extension how do i install this package in my winxp professional sp3 OS.</p>
11,235,020
1
1
null
2012-06-26 09:58:55.807 UTC
1
2016-09-29 19:39:54.85 UTC
2016-09-29 19:39:54.85 UTC
null
848,199
null
1,067,943
null
1
8
windows|windows-xp|windows-update
70,778
<p>There is this link on microsoft support site that explains how to install the .msu file:</p> <ul> <li><a href="https://support.microsoft.com/en-us/kb/934307" rel="nofollow">Description of the Windows Update Standalone Installer in Windows</a> </li> </ul>
11,149,759
Remove all non alphabetic characters from a String array in java
<p>I'm trying to write a method that removes all non alphabetic characters from a Java <code>String[]</code> and then convert the String to an lower case string. I've tried using regular expression to replace the occurence of all non alphabetic characters by <code>""</code> .However, the output that I am getting is not able to do so. Here is the code</p> <pre><code>static String[] inputValidator(String[] line) { for(int i = 0; i &lt; line.length; i++) { line[i].replaceAll("[^a-zA-Z]", ""); line[i].toLowerCase(); } return line; } </code></pre> <p>However if I try to supply an input that has non alphabets (say <code>-</code> or <code>.</code>) the output also consists of them, as they are not removed.</p> <p><strong>Example Input</strong></p> <pre><code>A dog is an animal. Animals are not people. </code></pre> <p><strong>Output that I'm getting</strong></p> <pre><code>A dog is an animal. Animals are not people. </code></pre> <p><strong>Output that is expected</strong></p> <pre><code>a dog is an animal animals are not people </code></pre>
11,149,783
9
1
null
2012-06-22 03:21:34.827 UTC
8
2021-06-07 03:50:06.36 UTC
2018-11-19 18:32:47.34 UTC
null
1,475,228
null
1,148,918
null
1
23
java|regex|string
98,779
<p>The problem is your changes are not being stored because Strings are <a href="https://stackoverflow.com/questions/279507/what-is-meant-by-immutable">immutable</a>. Each of the <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replaceAll" rel="noreferrer">method calls</a> is returning a new <code>String</code> representing the change, with the current <code>String</code> staying the same. You just need to store the returned <code>String</code> back into the array.</p> <pre><code>line[i] = line[i].replaceAll("[^a-zA-Z]", ""); line[i] = line[i].toLowerCase(); </code></pre> <p>Because the each method is returning a <code>String</code> you can chain your method calls together. This will perform the second method call on the result of the first, allowing you to do both actions in one line.</p> <pre><code>line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase(); </code></pre>
11,267,309
Importing zipped files in Mysql using command line
<p><a href="https://stackoverflow.com/q/11258811/1488173">Importing zipped files in Mysql using CMD</a></p> <p>What is the right syntax to import sql zipped files into mysql using cmd ?</p> <p>I am doing the following</p> <pre><code>xz &lt; backup.sql.gz | mysql -u root test </code></pre> <p>But always getting the following error <img src="https://i.stack.imgur.com/CwIli.png" alt="enter image description here"></p>
12,154,202
4
0
null
2012-06-29 18:43:46.067 UTC
12
2016-05-05 10:21:17.277 UTC
2017-05-23 12:19:42.377 UTC
null
-1
null
1,488,173
null
1
35
mysql|database|cmd|winzip|xz
70,116
<p>I got the answer from my other question. This is the command to import zipped file when you are using 7zip</p> <blockquote> <p>7z x -so backup.7z | mysql -u root test</p> </blockquote> <p>x is the extraction command</p> <p><code>-so</code> option makes 7-zip write to stdout</p>
11,274,906
Play RTSP streaming in an Android application
<p>I am trying to develop an Android based application, which can play video from a live stream. This live stream is produced using <a href="https://en.wikipedia.org/wiki/Wowza_Streaming_Engine">Wowza Media Server</a>.</p> <p>The URL is:</p> <pre><code>rtsp://tv.hindiworldtv.com:1935/live/getpun </code></pre> <p>I have tried following code in ecliplse:</p> <pre><code>package com.kalloh.wpa; import android.app.Activity; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Bundle; import android.view.Window; import android.widget.MediaController; import android.widget.VideoView; public class a extends Activity { VideoView videoView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //Create a VideoView widget in the layout file //use setContentView method to set content of the activity to the layout file which contains videoView this.setContentView(R.layout.videoplayer); videoView = (VideoView)this.findViewById(R.id.videoView); //add controls to a MediaPlayer like play, pause. MediaController mc = new MediaController(this); videoView.setMediaController(mc); //Set the path of Video or URI videoView.setVideoURI(Uri.parse("rtsp://tv.hindiworldtv.com:1935/live/getpnj")); // //Set the focus videoView.requestFocus(); } } </code></pre> <p>At first, it was not working.</p> <p>Now it started working, but it stops after 20 to 30 seconds. How can I fix this problem?</p>
12,833,897
6
5
null
2012-06-30 14:33:37.75 UTC
16
2021-03-24 12:55:25.667 UTC
2015-01-02 16:28:28.15 UTC
null
63,550
null
1,447,054
null
1
36
android|streaming|live|rtsp|wowza
102,368
<p>I found the solution. Transmission should be within the preferred setting by Android. For more details, see <em><a href="http://developer.android.com/guide/appendix/media-formats.html" rel="nofollow">Supported Media Formats</a></em>.</p>
11,274,864
What does 'qualified' mean in 'import qualified Data.List' statement?
<p>I understand <code>import Data.List</code>.</p> <p>But what does <code>qualified</code> mean in the statement <code>import qualified Data.List</code>?</p>
11,274,880
3
0
null
2012-06-30 14:28:58.21 UTC
9
2019-12-03 16:13:45.687 UTC
2019-12-03 16:13:45.687 UTC
null
775,954
null
1,417,244
null
1
56
haskell
10,729
<p>A qualified import makes the imported entities available only in qualified form, e.g.</p> <pre><code>import qualified Data.List result :: [Int] result = Data.List.sort [3,1,2,4] </code></pre> <p>With just <code>import Data.List</code>, the entities are available in qualified form and in unqualified form. Usually, just doing a qualified import leads to too long names, so you</p> <pre><code>import qualified Data.List as L result :: [Int] result = L.sort [3,1,2,4] </code></pre> <p>A qualified import allows using functions with the same name imported from several modules, e.g. <code>map</code> from the <code>Prelude</code> and <code>map</code> from <code>Data.Map</code>.</p>
12,755,945
Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"
<p>I'm using this script to upload my image files: <a href="http://jsfiddle.net/eHmSr/" rel="noreferrer">http://jsfiddle.net/eHmSr/</a></p> <pre><code>$('.uploader input:file').on('change', function() { $this = $(this); $('.alert').remove(); $.each($this[0].files, function(key, file) { $('.files').append('&lt;li&gt;' + file.name + '&lt;/li&gt;'); data = new FormData(); data.append(file.name, file); $.ajax({ url: $('.uploader').attr('action'), type: 'POST', dataType: 'json', data: data }); }); }); </code></pre> <p>But when I click in upload button, the JavaScript console returns this error:</p> <pre><code>Uncaught TypeError: Illegal invocation </code></pre> <p><img src="https://i.stack.imgur.com/cxsX3.png" alt="jQuery Error"></p> <p>Can you help me?</p>
12,756,023
5
3
null
2012-10-06 01:36:27.283 UTC
11
2020-11-29 15:58:13.353 UTC
null
null
null
null
977,687
null
1
86
jquery|ajax|html|upload
123,582
<p>jQuery processes the <code>data</code> attribute and converts the values into strings.</p> <p><a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">Adding <code>processData: false</code></a> to your options object fixes the error, but I'm not sure if it fixes the problem.</p> <p><strong>Demo: <a href="http://jsfiddle.net/eHmSr/1/" rel="noreferrer">http://jsfiddle.net/eHmSr/1/</a></strong></p>
17,031,999
How to pass user credentials to web service?
<p>I am consuming a webservice using WSDL in windows application. When I try to use method, i get the following error:-</p> <blockquote> <p>The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was '"</p> <p>{"The remote server returned an error: (401) Unauthorized."}</p> </blockquote> <p>I have user credentials but don't know how to pass it using c# code in windows application.</p>
17,093,801
2
2
null
2013-06-10 20:11:49.447 UTC
6
2013-06-13 17:52:25.73 UTC
2013-06-10 20:19:15.15 UTC
null
1,327,064
null
1,327,064
null
1
13
c#|winforms|web-services
62,149
<p>Here is the how it is working for me:-</p> <p>Config file setting looks like this:-</p> <pre><code>&lt;configuration&gt; &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="bindingName" &gt; &lt;security mode="TransportCredentialOnly"&gt; &lt;transport clientCredentialType="Basic" proxyCredentialType="None" realm=""/&gt; &lt;message clientCredentialType="UserName" algorithmSuite="Default"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://10.10.10.10:1880/testpad/services/Testwebservice" binding="basicHttpBinding" bindingConfiguration="bindingName" contract=testService.GetData" name="test_Port1" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p>and here i am passing user credentials:-</p> <pre><code> var ser = new GetDataClient(); ser.ClientCredentials.UserName.UserName = "userid"; ser.ClientCredentials.UserName.Password = "Pa$$word1"; </code></pre>
16,931,895
Exact number of bins in Histogram in R
<p>I'm having trouble making a histogram in R. The problem is that I tell it to make 5 bins but it makes 4 and I tell to make 5 and it makes 8 of them.</p> <pre><code>data &lt;- c(5.28, 14.64, 37.25, 78.9, 44.92, 8.96, 19.22, 34.81, 33.89, 24.28, 6.5, 4.32, 2.77, 17.6, 33.26, 52.78, 5.98, 22.48, 20.11, 65.74, 35.73, 56.95, 30.61, 29.82); hist(data, nclass = 5,freq=FALSE,col="orange",main="Histogram",xlab="x",ylab="f(x)",yaxs="i",xaxs="i") </code></pre> <p>Any ideas on how to fix it?</p>
16,932,344
5
0
null
2013-06-05 05:02:19.48 UTC
9
2020-04-15 20:23:23.183 UTC
2014-04-27 14:34:32.257 UTC
null
2,091,025
null
645,608
null
1
17
r|statistics|histogram
65,995
<p>Use the breaks argument:</p> <pre><code>hist(data, breaks=seq(0,80,l=6), freq=FALSE,col="orange",main="Histogram", xlab="x",ylab="f(x)",yaxs="i",xaxs="i") </code></pre> <p><img src="https://i.stack.imgur.com/BB0Yt.png" alt="enter image description here"></p>
16,749,121
What does `<>` mean in Python?
<p>I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are <code>&lt;&gt;</code> signs in the source file, e.g.:</p> <pre><code>if (cnum &lt; 1000 and nnum &lt;&gt; 1000 and ntext[-1] &lt;&gt; "s": ... </code></pre> <p>I guess it's a now-abandoned sign in the language.</p> <p>What exactly does it mean, and which (more recent) sign should I replace it with?</p>
16,749,135
5
4
null
2013-05-25 11:33:54.893 UTC
11
2021-10-28 03:47:54.05 UTC
2013-05-26 04:31:07.217 UTC
null
319,931
null
2,002,452
null
1
67
python|syntax|operators|python-2.x
78,005
<p>It means not equal to. It was taken from <code>ABC</code> (python's predecessor) see <a href="http://homepages.cwi.nl/%7Esteven/abc/qr.html#TESTS" rel="noreferrer">here</a>:</p> <blockquote> <p><code>x &lt; y, x &lt;= y, x &gt;= y, x &gt; y, x = y, x &lt;&gt; y, 0 &lt;= d &lt; 10</code></p> <p>Order tests (<code>&lt;&gt;</code> means <em>'not equals'</em>)</p> </blockquote> <p>I believe <code>ABC</code> took it from Pascal, a language Guido began programming with.</p> <p>It has now been removed in Python 3. Use <code>!=</code> instead. If you are <strong>CRAZY</strong> you can scrap <code>!=</code> and allow only <code>&lt;&gt;</code> in Py3K using <a href="http://www.python.org/dev/peps/pep-0401/#official-acts-of-the-flufl" rel="noreferrer">this easter egg</a>:</p> <pre><code>&gt;&gt;&gt; from __future__ import barry_as_FLUFL &gt;&gt;&gt; 1 != 2 File &quot;&lt;stdin&gt;&quot;, line 1 1 != 2 ^ SyntaxError: with Barry as BDFL, use '&lt;&gt;' instead of '!=' &gt;&gt;&gt; 1 &lt;&gt; 2 True </code></pre>
25,860,975
Send Email through Asp.Net Web Api
<p>My client want to send E-mail through asp.net Web API. I am new in web services and have 0 knowledge of this please guide me how to achieve this task and if anyone can provide the code, there must be some web service available like this.</p> <pre><code>using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text)) { mm.Subject = txtSubject.Text; mm.Body = txtBody.Text; mm.IsBodyHtml = false; SmtpClient smtp = new SmtpClient(); smtp.EnableSsl = true; smtp.Send(mm); ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true); } </code></pre>
25,861,230
2
5
null
2014-09-16 04:59:45.103 UTC
1
2015-04-06 07:43:43.973 UTC
2014-09-16 05:15:16.85 UTC
null
2,126,088
null
2,126,088
null
1
3
c#|asp.net|email|asp.net-web-api
43,355
<p>The .NET mail API sends emails via SMTP. The ASP.NET Web API allows you to host a REST interface.</p> <p>You said you know how to program with both, so do that.</p> <p>Create your Web API method which receives the necessary arguments, exactly like you would for a normal method that will do your emailing duties for you. Then create your route to the method.</p> <p>If you have issues with either not working, then write tests.</p> <p>Documentation for Web API: <a href="http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api" rel="noreferrer">http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api</a></p> <p>Documentation for SmtpClient: <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx</a></p>
25,680,269
Why is the word `false` written blue and the word `FALSE` written purple in Visual Studio?
<p>Why does Visual Studio change the word color depending on the way it is entered:</p> <p><code>false</code> with blue, but <code>FALSE</code> with purple.<br> <code>true</code> with blue but <code>TRUE</code> with purple.</p> <p>Is there any difference in the meaning of them and if yes what is it?</p>
25,680,325
3
8
null
2014-09-05 07:01:38.54 UTC
0
2014-12-10 20:43:37.293 UTC
2014-09-05 10:19:02.587 UTC
null
445,517
null
2,376,693
null
1
29
c++|visual-studio|ide|syntax-highlighting
4,237
<p><code>true</code> and <code>false</code> are <em>keywords</em> in C++ so your IDE (not the compiler) is painting them blue.</p> <p>TRUE and FALSE are often defined by various headers, primarily for compatibility with C and older C++ compilers where <code>true</code> and <code>false</code> are <strong>not</strong> keywords.</p> <p>As for their equivalence, the C++ standard does <strong>not</strong> define <code>sizeof(true)</code> and <code>sizeof(false)</code> to be 1 but they <strong>will</strong> be the same as <code>sizeof(bool)</code>. Footnote 69 for C++ standard:</p> <blockquote> <p>sizeof(bool) is not required to be 1.</p> </blockquote> <p>You'll probably find that <code>sizeof(TRUE)</code> and <code>sizeof(FALSE)</code> are <code>sizeof(int)</code> since TRUE and FALSE are often defined as <code>int</code> types, but it would be unwise to assume this.</p>
57,770,464
Android Studio Error "Installation did not succeed. The application could not be installed. Installation failed due to: 'null'"
<p>I am trying to run my app on my Xiaomi RedMi S2 from Android Studio 3.5. It throws an error while installing the app on the phone:</p> <blockquote> <p>Installation did not succeed.<br /> The application could not be installed.<br /> Installation failed due to: 'null'</p> </blockquote> <p>REAL DEVICE: XIAOMI REDMI S2</p>
58,492,367
27
3
null
2019-09-03 11:09:49.863 UTC
2
2022-09-01 06:48:33.733 UTC
2022-03-25 16:05:50.44 UTC
null
10,749,567
null
1,906,738
null
1
24
android|android-studio|apk|failed-installation|xiaomi
93,181
<p>I had the Same issue on a MAC, this is how I solve it, note: I was tried the method that mention @Manoj Kumar,</p> <p>Un check this field in Preferences/Build,Execution,Deployment/Debugger <img src="https://i.stack.imgur.com/wVIE9.png" alt="" /></p>
4,745,923
prevent div moving on window resize
<p>I have a page with two divs "list_events" and "right_content" one next to each other. When I resize the window "right_content" moves down "list_events" but i dont want that! I dont want those two divs to move neither to scale down on window resizement..how can I achieve that?</p> <p>this is the code </p> <pre><code>.list_events{margin-left:1em;float:left;} .right_content{float:left;margin-left:1em;} </code></pre> <p>thanks Luca</p>
7,466,816
2
0
null
2011-01-20 10:25:55.043 UTC
2
2011-09-19 05:32:44.493 UTC
null
null
null
null
505,762
null
1
14
html|resize|window|position
43,825
<p>first add a parent div/wrap and put those two divs of yours into it.</p> <p>like so:</p> <pre><code>&lt;div id="wrap"&gt; &lt;div id="list_events"&gt;&lt;/div&gt; &lt;div id="right_content"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>then you can try the </p> <p>min-width(px/ems/ etc) on the parent/wrapper div like so:</p> <pre><code>#wrap{ min-width: 600px; } </code></pre> <p>Overall, whatever size you add to the min-width itll scale the parent div down to the size specified.</p> <p>once the window is sized down past your specified size, itll behave like any other window.</p> <p>this is my way of doing it.</p>
70,374,005
Invalid options object. Dev Server has been initialized using an options object that does not match the API schema
<p>I have been stock on this error on my project when I add <code>&quot;proxy&quot;: &quot;http://localhost:6000&quot;</code> in my package.json.</p> <p>This is the error response after yarn start.</p> <blockquote> <p>Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.</p> <ul> <li>options.allowedHosts[0] should be a non-empty string. error Command failed with exit code 1. info Visit <a href="https://yarnpkg.com/en/docs/cli/run" rel="noreferrer">https://yarnpkg.com/en/docs/cli/run</a> for documentation about this command.</li> </ul> </blockquote> <p>But everything is fine when I remove the <code>&quot;proxy&quot;: &quot;http://localhost:6000&quot;</code>.</p> <p>This is on my package.json:</p> <pre><code>{ &quot;name&quot;: &quot;client&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@material-ui/core&quot;: &quot;^4.12.3&quot;, &quot;@testing-library/jest-dom&quot;: &quot;^5.16.1&quot;, &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;, &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;, &quot;axios&quot;: &quot;^0.24.0&quot;, &quot;moment&quot;: &quot;^2.29.1&quot;, &quot;react&quot;: &quot;^17.0.2&quot;, &quot;react-dom&quot;: &quot;^17.0.2&quot;, &quot;react-file-base64&quot;: &quot;^1.0.3&quot;, &quot;react-redux&quot;: &quot;^7.2.6&quot;, &quot;react-scripts&quot;: &quot;5.0.0&quot;, &quot;redux&quot;: &quot;^4.1.2&quot;, &quot;redux-thunk&quot;: &quot;^2.4.1&quot;, &quot;web-vitals&quot;: &quot;^2.1.2&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;proxy&quot;: &quot;http://localhost:6000&quot; } </code></pre>
70,413,065
18
3
null
2021-12-16 04:57:13.54 UTC
3
2022-09-22 17:46:29.143 UTC
2021-12-16 06:01:55.78 UTC
null
8,690,857
null
11,194,137
null
1
37
node.js|reactjs|package.json
55,023
<p>Here is a workaround. Delete <strong>&quot;proxy&quot;: &quot;http://localhost:6000&quot;</strong>. Install package http-proxy-middleware with command <strong>npm install http-proxy-middleware --save</strong>. Create a file setupProxy.js inside your src folder or the root of your folder. Add these lines inside:</p> <pre><code>const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:6000', changeOrigin: true, }) ); }; </code></pre> <p>Now, run your app. It should work.</p>
10,167,266
How to set cornerRadius for only top-left and top-right corner of a UIView?
<p>Is there a way to set <code>cornerRadius</code> for only top-left and top-right corner of a <code>UIView</code>?</p> <p>I tried the following, but it end up not seeing the view anymore.</p> <pre><code>UIView *view = [[UIView alloc] initWithFrame:frame]; CALayer *layer = [CALayer layer]; UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)]; layer.shadowPath = shadowPath.CGPath; view.layer.mask = layer; </code></pre>
41,197,790
30
7
null
2012-04-15 23:58:26.2 UTC
171
2022-05-09 15:54:41.353 UTC
2018-09-21 13:46:33.157 UTC
null
1,033,581
null
180,862
null
1
521
ios|cocoa-touch|uiview|cornerradius
353,010
<p>Pay attention to the fact that if you have layout constraints attached to it, you must refresh this as follows in your UIView subclass:</p> <pre><code>override func layoutSubviews() { super.layoutSubviews() roundCorners(corners: [.topLeft, .topRight], radius: 3.0) } </code></pre> <p>If you don't do that it won't show up.</p> <hr /> <p>And to round corners, use the extension:</p> <pre><code>extension UIView { func roundCorners(corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath layer.mask = mask } } </code></pre> <hr /> <hr /> <p><strong>Additional view controller case</strong>: Whether you can't or wouldn't want to subclass a view, you can still round a view. Do it from its view controller by overriding the <code>viewWillLayoutSubviews()</code> function, as follows:</p> <pre><code>class MyVC: UIViewController { /// The view to round the top-left and top-right hand corners let theView: UIView = { let v = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200)) v.backgroundColor = .red return v }() override func loadView() { super.loadView() view.addSubview(theView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Call the roundCorners() func right there. theView.roundCorners(corners: [.topLeft, .topRight], radius: 30) } } </code></pre>
10,090,949
Accessing to enum values by '::' in C++
<p>I have class like following: </p> <pre><code>class Car { public: Car(); // Some functions and members and &lt;b&gt;enums&lt;/b&gt; enum Color { Red, Blue, Black }; Color getColor(); void setColor(Color); private: Color myColor; } </code></pre> <p>I want to:</p> <ol> <li>access to <code>Color</code> values as <code>Color::Red</code>. It is really hardly to understand code when <code>Car::Red</code> is used, when class have a lot enums, subclasses etc. </li> <li>use type <code>Color</code> as function argument or return value </li> <li>use variable type <code>Color</code> in <code>switch</code></li> </ol> <p>I know 3 partial solutions: </p> <ol> <li>Using embedded class <code>Color</code> and enum in it </li> <li>Using embedded namespace <code>Color</code> and enum in it </li> <li>Using <code>enum class</code> </li> </ol> <p>1 and 2 solutions solves a <code>Color::Red</code> accession problem, but I can't use functions like <code>Color getColor()</code> and <code>void setColor(Color)</code>.</p> <p>3 solution has a problem: VS2010 doen't support <code>enum class</code>. GCC v.4.1.2 doesn't support it too. I don't know about later versions of gcc. </p> <p>Yes, I'm working on cross-platform project.<br> I have found <a href="http://www.gamedev.net/topic/299161-c-using--to-get-enum-members/page__view__findpost__p__2898948" rel="noreferrer">this</a> solution, but it seems ... heavy.<br> I hope somebody can help me here :)</p>
10,092,148
3
3
null
2012-04-10 14:46:46.05 UTC
3
2018-12-13 15:27:06.047 UTC
2012-04-10 14:51:02.593 UTC
null
11,343
null
1,105,597
null
1
14
c++|enums
66,419
<p>In current C++ (i.e. C++11 and beyond), you <em>can</em> already access enum values like that:</p> <pre><code>enum Color { Red }; Color c = Color::Red; Color d = Red; </code></pre> <p>You can go further and enforce the use of this notation:</p> <pre><code>enum class Color { Red }; Color c = Color::Red; // Color d = Red; &lt;-- error now </code></pre> <p>And on a sidenote, you now define the underlying type, which was previously only possible with hacky code (<code>FORCEDWORD</code> or so anyone?):</p> <pre><code>enum class Color : char { Red }; </code></pre>
10,114,526
How to build a Meteor smart package
<p>How can one build a <a href="http://docs.meteor.com/#packages" rel="noreferrer">Meteor smart package</a> that would show up in <code>meteor list</code>?</p> <p>Building <a href="http://atmosphere.meteor.com" rel="noreferrer">Atmosphere</a> packages is reasonably well <a href="https://atmosphere.meteor.com/wtf/package" rel="noreferrer">documented</a>, but building Meteor packages isn't.</p>
23,950,265
5
1
null
2012-04-11 21:53:45.977 UTC
17
2015-07-20 03:45:46.133 UTC
2014-06-04 20:53:38.477 UTC
null
311,744
null
258,689
null
1
42
meteor|package
19,253
<p>Meteor now supports a <strong><code>create --package</code></strong> command.</p> <p>See <a href="http://docs.meteor.com/#/full/writingpackages">the meteor docs</a>.</p> <p>Example (substitute your own <a href="https://www.meteor.com/services/developer-accounts">meteor developer account</a> for "cunneen"):</p> <pre class="lang-sh prettyprint-override"><code>meteor create --package cunneen:foo </code></pre> <p>Output:</p> <p><code>cunneen:foo: created in your app</code></p> <p>Results:</p> <p><strong>packages/cunneen:foo/package.js</strong></p> <pre class="lang-js prettyprint-override"><code>Package.describe({ name: 'cunneen:foo', version: '0.0.1', // Brief, one-line summary of the package. summary: '', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.0.3.1'); api.addFiles('cunneen:foo.js'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('cunneen:foo'); api.addFiles('cunneen:foo-tests.js'); }); </code></pre> <p><strong>packages/cunneen:foo/foo.js (empty file)</strong></p> <pre class="lang-js prettyprint-override"><code>// Write your package code here! </code></pre> <p><strong>packages/cunneen:foo/foo-tests.js</strong></p> <pre class="lang-js prettyprint-override"><code>// Write your tests here! // Here is an example. Tinytest.add('example', function (test) { test.equal(true, true); }); </code></pre> <p><strong>packages/cunneen:foo/README.md (empty file)</strong></p> <pre><code># cunneen:foo package </code></pre> <p>For a good (VERY comprehensive) example, take a look at <a href="https://github.com/EventedMind/iron-router">iron-router</a>.</p>
9,822,313
Remote connect to clearDB heroku database
<p>How can i perform a remote connect to ClearDB MySQL database on heroku using for example MySQL Query Browser. Where to get url, port, login and password?</p>
10,357,757
13
0
null
2012-03-22 12:29:07.443 UTC
39
2021-11-02 07:09:08.563 UTC
null
null
null
null
1,022,108
null
1
119
mysql|database|heroku|database-connection
97,485
<p>In heroku website, go to My Apps and select the app on which you have installed ClearDB. </p> <p>On the top corner click on <strong>Addons</strong> and then select <strong>ClearDB MySQL Database</strong>. Once there, click on your database and choose the '<strong>Endpoint Information</strong>' tab. There you see your username/password. The URL to the database can be acquired by running <code>heroku config --app &lt;YOUR-APP-NAME&gt;</code> in the command line.</p> <p>In my case, it was something like: mysql://user:pass@<strong>us-cdbr-east.cleardb.com</strong>/<code>DATABASE</code>?reconnect=true What you need is this part: <strong>us-cdbr-east.cleardb.com</strong></p>
9,945,409
How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?
<p>I can't seem to connect to my database from a site. I get this error:</p> <blockquote> <p>Named Pipes Provider, error: 40 - Could not open a connection to SQL Server</p> </blockquote> <p>I tried using the local IP address to connect as well as a public one. I've tried:</p> <ol> <li>Yes, the site can communicate with the server</li> <li>Named pipes/TCP is enabled.</li> <li>Remote connections are allowed.</li> <li><a href="http://en.wikipedia.org/wiki/Windows_Firewall" rel="noreferrer">Windows Firewall</a> is off</li> <li>Created an exception for port 1433 in Windows Firewall.</li> <li>Enabled everything in SQL Server Configuration Manager.</li> </ol> <p>What else can I do here?</p>
34,573,742
32
6
null
2012-03-30 14:56:12.107 UTC
43
2022-09-20 15:25:20.66 UTC
2013-01-06 10:27:27.267 UTC
null
63,550
null
584,765
null
1
174
sql-server|sql-server-2005|database-connectivity
787,351
<p>Solving this problem is very easy:</p> <ol> <li>Go to control panel.</li> <li>search for services.</li> <li>Open Local services window from your search results</li> <li>Restart your MSSQLSERVER service.</li> </ol> <p>Screenshot of the steps:</p> <p><img src="https://i.stack.imgur.com/KAcPr.png" alt="Screenshot of the steps"></p>
7,765,548
Get a single value from dataSet in asp.net
<p>I am doing a query to get Title and RespondBY from the tbl_message table, I want to decrypt the Title before I do databinding to the repeater. How can I access the title value before doing databind.</p> <pre><code>string MysqlStatement = "SELECT Title, RespondBy FROM tbl_message WHERE tbl_message.MsgID = @MsgID"; using (DataServer server = new DataServer()) { MySqlParameter[] param = new MySqlParameter[1]; param[0] = new MySqlParameter("@MsgID", MySqlDbType.Int32); param[0].Value = MessageID; command.Parameters.AddWithValue("@MsgID", MessageID); ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param); } rptList.DataSource = ds; rptList.DataBind(); &lt;table style="width: 498px; color: #F5F5F5;"&gt; &lt;asp:Repeater ID="rptList" runat="server"&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;tr&gt; &lt;td width="15%"&gt; &lt;b&gt;Subject&lt;/b&gt; &lt;/td&gt; &lt;td width="60%"&gt; &lt;asp:Label ID="lbl_Subj" runat="server" Text='&lt;%#Eval("Title")%&gt;' /&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
7,765,619
3
1
null
2011-10-14 09:20:14.037 UTC
1
2015-09-24 21:41:05.79 UTC
2011-11-14 22:49:00.51 UTC
null
3,043
null
931,064
null
1
12
c#|asp.net|dataset
88,283
<p>Probably, like following code part you can get the Title and try this coding before</p> <pre><code>rptList.DataSource = ds; rptList.DataBind(); </code></pre> <p>The following code part can get the Title from <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset%28v=vs.71%29.aspx" rel="noreferrer">dataset</a></p> <pre><code>string title = ds.Tables[0].Rows[0]["Title"].ToString(); </code></pre>
11,520,189
Difference between shutdown and shutdownNow of Executor Service
<p>I want to know the basic difference between <code>shutdown()</code> and <code>shutdownNow()</code> for shutting down the <code>Executor Service</code>?</p> <p><strong><em>As far as I understood:</em></strong> </p> <p><code>shutdown()</code> should be used for <strong>graceful</strong> shutdown which means all tasks that were running and queued for processing but not started should be allowed to complete </p> <p><code>shutdownNow()</code> does an <strong>abrupt</strong> shut down meaning that some unfinished tasks are cancelled and unstarted tasks are also cancelled. Is there anything else which is implicit/explicit that I am missing?</p> <p>P.S: I found another question on <a href="https://stackoverflow.com/questions/10504172/how-to-shutdown-an-executor-service">How to shutdown an executor service</a> related to this but not exactly what I want to know.</p>
11,520,233
3
6
null
2012-07-17 10:02:09.293 UTC
38
2020-03-24 18:25:35.767 UTC
2020-03-24 18:25:35.767 UTC
null
1,498,427
null
1,527,084
null
1
82
java|java.util.concurrent
59,261
<p>In summary, you can think of it that way:</p> <ul> <li><code>shutdown()</code> will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run</li> <li><code>shutdownNow()</code> will do the same AND will <strong>try to cancel</strong> the already submitted tasks by interrupting the relevant threads. Note that if your tasks ignore the interruption, <code>shutdownNow</code> will behave exactly the same way as <code>shutdown</code>.</li> </ul> <p>You can try the example below and replace <code>shutdown</code> by <code>shutdownNow</code> to better understand the different paths of execution:</p> <ul> <li>with <code>shutdown</code>, the output is <code>Still waiting after 100ms: calling System.exit(0)...</code> because the running task is <strong>not</strong> interrupted and continues to run.</li> <li>with <code>shutdownNow</code>, the output is <code>interrupted</code> and <code>Exiting normally...</code> because the running task is interrupted, catches the interruption and then stops what it is doing (breaks the while loop).</li> <li>with <code>shutdownNow</code>, if you comment out the lines within the while loop, you will get <code>Still waiting after 100ms: calling System.exit(0)...</code> because the interruption is not handled by the running task any longer.</li> </ul> <pre><code>public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(new Runnable() { @Override public void run() { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("interrupted"); break; } } } }); executor.shutdown(); if (!executor.awaitTermination(100, TimeUnit.MICROSECONDS)) { System.out.println("Still waiting after 100ms: calling System.exit(0)..."); System.exit(0); } System.out.println("Exiting normally..."); } </code></pre>
3,462,995
jQuery - keydown / keypress /keyup ENTERKEY detection?
<p>Trying to get jQuery to detect enter input, but space and other keys are detected, enter isn't detected. What's wrong below: </p> <pre><code>$("#entersomething").keyup(function(e) { alert("up"); var code = (e.keyCode ? e.keyCode : e.which); if (code==13) { e.preventDefault(); } if (code == 32 || code == 13 || code == 188 || code == 186) { $("#displaysomething").html($(this).val()); }); &lt;input id="entersomething" /&gt; &lt;div id="displaysomething"&amp;gt;&amp;lt;/div&amp;gt; </code></pre> <p><a href="http://jsfiddle.net/zeRrv/" rel="noreferrer">http://jsfiddle.net/zeRrv/</a></p>
3,463,044
4
2
null
2010-08-11 21:28:52.313 UTC
2
2020-02-06 15:42:35.26 UTC
2012-03-14 02:51:58.03 UTC
null
486,233
null
357,189
null
1
49
jquery
111,036
<p>JavaScript/jQuery</p> <pre><code>$("#entersomething").keyup(function(e){ var code = e.key; // recommended to use e.key, it's normalized across devices and languages if(code==="Enter") e.preventDefault(); if(code===" " || code==="Enter" || code===","|| code===";"){ $("#displaysomething").html($(this).val()); } // missing closing if brace }); </code></pre> <p>HTML</p> <pre><code>&lt;input id="entersomething" type="text" /&gt; &lt;!-- put a type attribute in --&gt; &lt;div id="displaysomething"&gt;&lt;/div&gt; </code></pre>
3,770,100
How-to init a ListPreference to one of its values
<p>I'm trying to set a defaultValue to a ListPreference item.</p> <p>Here is an sample of my preference.xml file:</p> <pre><code>&lt;ListPreference android:key="notification_delay" android:title="@string/settings_push_delay" android:entries="@array/settings_push_delay_human_value" android:entryValues="@array/settings_push_delay_phone_value" android:defaultValue="????"&gt; &lt;/ListPreference&gt; </code></pre> <p>The two arrays:</p> <pre><code>&lt;string-array name="settings_push_delay_human_value"&gt; &lt;item&gt;every 5 minutes&lt;/item&gt; &lt;item&gt;every 10 minutes&lt;/item&gt; &lt;item&gt;every 15 minutes&lt;/item&gt; &lt;/string-array&gt; &lt;string-array name="settings_push_delay_phone_value"&gt; &lt;item&gt;300&lt;/item&gt; &lt;item&gt;600&lt;/item&gt; &lt;item&gt;900&lt;/item&gt; &lt;/string-array&gt; </code></pre> <p>When i go into the preference activity, no item of the ListPreference is selected. I've tried to set an int value like 1 in the "android:defaultValue" fied to select "10 minutes" but it does not work.</p> <pre><code>&lt;ListPreference android:key="notification_delay" android:title="@string/settings_push_delay" android:entries="@array/settings_push_delay_human_value" android:entryValues="@array/settings_push_delay_phone_value" android:defaultValue="1"&gt; &lt;/ListPreference&gt; </code></pre> <p>Any Idea?</p>
3,968,752
4
0
null
2010-09-22 14:11:42.047 UTC
12
2014-01-29 22:24:18.937 UTC
2011-08-08 21:22:49.053 UTC
null
39,709
null
384,483
null
1
72
android
43,236
<p>You need to specify the <em>value</em>. So to get the first entry selected by default specify <code>defaultValue="300"</code> in your example.</p>
3,799,935
Sort the rows according to the order specified in WHERE IN clause
<p>I have something like:</p> <pre><code>SELECT * FROM table WHERE id IN (118, 17, 113, 23, 72); </code></pre> <p>It returns the rows ordered by ID, ascending. Is there a way to get back the rows in the order specified in the <code>IN</code> clause?</p>
3,799,966
6
0
null
2010-09-26 21:39:35.013 UTC
16
2022-02-04 12:31:39.55 UTC
2022-02-04 12:31:39.55 UTC
null
87,015
null
378,861
null
1
58
mysql|sql|sql-order-by
60,166
<p>You should use &quot;ORDER BY <a href="https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_field" rel="noreferrer">FIELD</a>&quot;. So, for instance:</p> <pre><code>SELECT * FROM table WHERE id IN (118,17,113,23,72) ORDER BY FIELD(id,118,17,113,23,72) </code></pre>
3,345,857
How to get a list of IP connected in same network (subnet) using Java
<p>How do I get list of IP addresses for devices connected to my same subnet using Java?</p>
3,345,981
8
2
null
2010-07-27 16:41:26.207 UTC
24
2021-02-19 20:55:59.33 UTC
2016-01-05 21:39:41.477 UTC
null
2,676,531
null
260,990
null
1
43
java|networking
80,748
<p>this should work when the hosts on your network react to ICMP packages (ping) (>JDK 5):</p> <pre><code>public void checkHosts(String subnet){ int timeout=1000; for (int i=1;i&lt;255;i++){ String host=subnet + "." + i; if (InetAddress.getByName(host).isReachable(timeout)){ System.out.println(host + " is reachable"); } } } </code></pre> <p>invoke the method for a subnet (192.168.0.1-254) like this: </p> <pre><code>checkHosts("192.168.0"); </code></pre> <p>didnt test it but should work kinda like this. Obviously this only checks the 254 hosts in the last byte of the ip address...</p> <p>check:</p> <p><a href="http://download-llnw.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28int%29" rel="noreferrer">http://download-llnw.oracle.com/javase/6/docs/api/java/net/InetAddress.html#isReachable%28int%29</a> <a href="http://blog.taragana.com/index.php/archive/how-to-do-icmp-ping-in-java-jdk-15-and-above/" rel="noreferrer">http://blog.taragana.com/index.php/archive/how-to-do-icmp-ping-in-java-jdk-15-and-above/</a></p> <p>hope that helped</p>
3,345,348
How to specify a min but no max decimal using the range data annotation attribute?
<p>I would like to specify that a decimal field for a price must be >= 0 but I don't really want to impose a max value.</p> <p>Here's what I have so far...I'm not sure what the correct way to do this is.</p> <pre><code>[Range(typeof(decimal), "0", "??"] public decimal Price { get; set; } </code></pre>
3,352,614
10
1
null
2010-07-27 15:41:17.327 UTC
16
2020-05-19 16:29:48.66 UTC
2015-11-05 17:00:29.577 UTC
null
4,370,109
null
169,867
null
1
200
c#|.net|asp.net-mvc|data-annotations
206,272
<p>It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.</p> <pre><code>[Range(typeof(decimal), "0", "79228162514264337593543950335")] public decimal Price { get; set; } </code></pre>
3,762,561
How to animate the background color of a UILabel?
<p>This looks like it should work, but doesn't. The color turns green at once.</p> <pre><code>self.labelCorrection.backgroundColor = [UIColor whiteColor]; [UIView animateWithDuration:2.0 animations:^{ self.labelCorrection.backgroundColor = [UIColor greenColor]; }]; </code></pre>
3,762,950
11
1
null
2010-09-21 16:51:15.063 UTC
17
2018-06-25 02:25:57.44 UTC
2017-01-19 00:36:52.183 UTC
null
3,681,880
null
136
null
1
81
ios|iphone|core-animation
52,758
<p>I can't find it documented anywhere, but it appears the <code>backgroundColor</code> property of <code>UILabel</code> is not animatable, as your code works fine with a vanilla <code>UIView</code>. This hack appears to work, however, as long as you don't set the background color of the label view itself:</p> <pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; ... theLabel.layer.backgroundColor = [UIColor whiteColor].CGColor; [UIView animateWithDuration:2.0 animations:^{ theLabel.layer.backgroundColor = [UIColor greenColor].CGColor; } completion:NULL]; </code></pre>
3,921,616
Leaking this in constructor warning
<p>I'd like to avoid (most of the) warnings of Netbeans 6.9.1, and I have a problem with the <code>'Leaking this in constructor'</code> warning.</p> <p>I understand the problem, calling a method in the constructor and passing "<code>this</code>" is dangerous, since "<code>this</code>" may not have been fully initialized.</p> <p>It was easy to fix the warning in my singleton classes, because the constructor is private and only called from the same class.</p> <p>Old code (simplified):</p> <pre><code>private Singleton() { ... addWindowFocusListener(this); } public static Singleton getInstance() { ... instance = new Singleton(); ... } </code></pre> <p>New code (simplified):</p> <pre><code>private Singleton() { ... } public static Singleton getInstance() { ... instance = new Singleton(); addWindowFocusListener( instance ); ... } </code></pre> <p>This fix is not working if the constructor is public and can be called from other classes. How is it possible to fix the following code:</p> <pre><code>public class MyClass { ... List&lt;MyClass&gt; instances = new ArrayList&lt;MyClass&gt;(); ... public MyClass() { ... instances.add(this); } } </code></pre> <p>Of course I want a fix which does not require to modify all my codes using this class ( by calling an init method for instance).</p>
3,921,636
11
3
null
2010-10-13 07:36:17.54 UTC
17
2022-01-20 18:01:15.887 UTC
2017-01-01 21:32:05.923 UTC
null
179,850
null
21,348
null
1
89
java|netbeans|constructor|this|netbeans-6.9
58,341
<p>Since you make sure to put your <code>instances.add(this)</code> at the end of the constructor you <strike>should IMHO be safe to tell the compiler to simply suppress the warning</strike> <strong>(*)</strong>. A warning, by its nature, doesn't necessarily mean that there's something wrong, it just requires your attention.</p> <p>If you know what you're doing you can use a <code>@SuppressWarnings</code> annotation. Like Terrel mentioned in his comments, the following annotation does it as of NetBeans 6.9.1:</p> <pre><code>@SuppressWarnings("LeakingThisInConstructor") </code></pre> <p><strong>(*) Update:</strong> As Isthar and Sergey pointed out there are cases where "leaking" constructor code can look perfectly safe (as in your question) and yet it is not. Are there more readers that can approve this? I am considering deleting this answer for the mentioned reasons.</p>
3,985,619
How to calculate a logistic sigmoid function in Python?
<p>This is a logistic sigmoid function:</p> <p><img src="https://i.stack.imgur.com/SUuRi.png" alt="enter image description here"></p> <p>I know x. How can I calculate F(x) in Python now?</p> <p>Let's say x = 0.458.</p> <p>F(x) = ?</p>
3,985,630
16
0
null
2010-10-21 08:36:07.707 UTC
42
2021-07-25 22:22:43.65 UTC
2020-01-31 13:24:50.503 UTC
null
10,407,023
null
95,944
null
1
204
python|sigmoid
404,634
<p>This should do it:</p> <pre><code>import math def sigmoid(x): return 1 / (1 + math.exp(-x)) </code></pre> <p>And now you can test it by calling:</p> <pre><code>&gt;&gt;&gt; sigmoid(0.458) 0.61253961344091512 </code></pre> <p><strong>Update</strong>: Note that the above was mainly intended as a straight one-to-one translation of the given expression into Python code. It is <em>not</em> tested or known to be a numerically sound implementation. If you know you need a very robust implementation, I'm sure there are others where people have actually given this problem some thought.</p>
8,311,090
Why not use heap sort always
<p>The <strong>Heap Sort</strong> sorting algorithm seems to have a worst case complexity of O(nlogn), and uses O(1) space for the sorting operation.</p> <p>This seems better than most sorting algorithms. Then, why wouldn't one use Heap Sort always as a sorting algorithm (and why do folks use sorting mechanisms like Merge sort or Quick sort)?</p> <p>Also, I have seen people use the term 'instability' with Heap sort. What does that imply?</p>
8,312,128
5
7
null
2011-11-29 12:57:30.323 UTC
30
2014-06-16 07:40:30.357 UTC
2011-11-29 13:11:44.273 UTC
null
946,312
null
946,312
null
1
73
algorithm|sorting|heapsort
50,201
<p>A stable sort maintains the relative order of items that have the same key. For example, imagine your data set contains records with an employee id and a name. The initial order is:</p> <pre><code>1, Jim 2, George 3, Jim 4, Sally 5, George </code></pre> <p>You want to sort by name. A stable sort will arrange the items in this order:</p> <pre><code>2, George 5, George 1, Jim 3, Jim 4, Sally </code></pre> <p>Note that the duplicate records for "George" are in the same relative order as they were in the initial list. Same with the two "Jim" records.</p> <p>An unstable sort might arrange the items like this:</p> <pre><code>5, George 2, George 1, Jim 3, Jim 4, Sally </code></pre> <p>Heapsort is not stable because operations on the heap can change the relative order of equal items. Not all Quicksort implementations are stable. It depends on how you implement the partitioning.</p> <p>Although Heapsort has a worst case complexity of <code>O(n log(n))</code>, that doesn't tell the whole story. In real-world implementation, there are constant factors that the theoretical analysis doesn't take into account. In the case of Heapsort vs. Quicksort, it turns out that there are ways (median of 5, for example) to make Quicksort's worst cases very rare indeed. Also, maintaining a heap is not free.</p> <p>Given an array with a normal distribution, Quicksort and Heapsort will both run in <code>O(n log(n))</code>. But Quicksort will execute faster because its constant factors are smaller than the constant factors for Heapsort. To put it simply, partitioning is faster than maintaining the heap.</p>
8,227,820
Alert Dialog Two Buttons
<p>Hello all i have a simple problem i have a alertDialog and i want it to show two buttons i have searched here but it seems the options before don't work anymore and are deprecated.</p> <p>Anyone know the new way of doing this you can see my code below that doesn't work.</p> <pre><code> Button share = (Button) findViewById(R.id.btn_share); share.setOnClickListener(new OnClickListener() { public void onClick(View v) { // call some other methods before that I guess... AlertDialog alertDialog = new AlertDialog.Builder(PasswActivity.this).create(); //Read Update alertDialog.setTitle("Uprgade"); alertDialog.setMessage("Upgrade Text Here"); alertDialog.setButton("Upgrade", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { }); alertDialog.setButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { }); alertDialog.show(); //&lt;-- See This! } }); </code></pre>
8,227,964
7
0
null
2011-11-22 13:45:16.517 UTC
17
2021-02-04 06:56:02.297 UTC
2014-09-30 03:44:31.66 UTC
null
1,075,936
null
993,346
null
1
41
android|android-alertdialog
87,851
<p>try this</p> <pre><code>public void showDialog(Activity activity, String title, CharSequence message) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (title != null) builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton("OK", null); builder.setNegativeButton("Cancel", null); builder.show(); } </code></pre>
4,552,893
How to copy as admin in windows7
<p>My requirement is to copy the updated jar into our application directory in Program Files when a new update is available. I face an access denied problem while copying in Windows 7. Can someone kindly help me find out how to copy the file as admin? </p> <p>Any alternate solution for installing the update is welcome.</p>
4,552,957
3
4
null
2010-12-29 09:25:28.28 UTC
null
2013-11-12 14:13:21.253 UTC
2012-06-09 07:34:21.247 UTC
null
306,651
null
556,944
null
1
4
java|windows-7|permissions|admin
38,659
<p>As a one time action, you could give additional permissions for your application directory for the specified user.</p> <ul> <li>From Windows Explorer, right-click specified folder. </li> <li>Goto Properties</li> <li>Click on Security tab</li> <li>Click on Edit...</li> <li>Change permission as suitable</li> </ul>
4,136,632
How to kill a child thread with Ctrl+C?
<p>I would like to stop the execution of a process with <kbd>Ctrl</kbd>+<kbd>C</kbd> in Python. But I have read somewhere that <code>KeyboardInterrupt</code> exceptions are only raised in the main thread. I have also read that the main thread is blocked while the child thread executes. So how can I kill the child thread?</p> <p>For instance, <kbd>Ctrl</kbd>+<kbd>C</kbd> has no effect with the following code:</p> <pre class="lang-py prettyprint-override"><code>def main(): try: thread = threading.Thread(target=f) thread.start() # thread is totally blocking (e.g. while True) thread.join() except KeyboardInterrupt: print &quot;Ctrl+C pressed...&quot; sys.exit(1) def f(): while True: pass # do the actual work </code></pre>
4,749,550
3
2
null
2010-11-09 17:30:52.687 UTC
8
2022-02-04 22:04:36.927 UTC
2021-07-07 14:28:07.993 UTC
null
2,326,961
null
304,932
null
1
22
python|multithreading|kill|keyboardinterrupt
38,687
<p>The problem there is that you are using <code>thread1.join()</code>, which will cause your program to wait until that thread finishes to continue.</p> <p>The signals will always be caught by the main process, because it's the one that receives the signals, it's the process that has threads.</p> <p>Doing it as you show, you are basically running a 'normal' application, without thread features, as you start 1 thread and wait until it finishes to continue.</p>
4,387,419
Why does ArrayList have "implements List"?
<p>In the Collection Framework we have the interface <code>List</code> and the class <code>AbstractList</code>:</p> <pre><code>AbstractList implements List </code></pre> <p>And <code>ArrayList</code> extends <code>AbstractList</code> and </p> <pre><code>implements List </code></pre> <p>My question: why does <code>ArrayList</code> have the <code>implements List</code> clause?</p> <p>If <code>ArrayList extends AbstractList</code> and <code>AbstractList implements List</code>, can't we say, that <code>ArrayList implement List</code>?</p>
4,387,445
3
0
null
2010-12-08 12:29:56.903 UTC
10
2012-12-20 14:12:25.667 UTC
2012-12-20 14:12:25.667 UTC
null
40,342
null
471,011
null
1
41
java|collections
7,458
<p>Yes. It could've been omitted. But thus it is immediately visible that it is a <code>List</code>. Otherwise an extra click through the code / documentation would be required. I think that's the reason - clarity.</p> <p>And to add what Joeri Hendrickx commented - it is for the purpose of showing that <code>ArrayList</code> implements <code>List</code>. <code>AbstractList</code> in the whole picture is just for convenience and to reduce code duplication between <code>List</code> implementations.</p>
4,047,427
How does async works in C#?
<p>Microsoft announced the <a href="http://msdn.microsoft.com/en-us/vstudio/async.aspx" rel="nofollow noreferrer">Visual Studio Async CTP</a> today (October 28, 2010) that introduces the <code>async</code> and <code>await</code> keywords into C#/VB for asynchronous method execution.</p> <p>First I thought that the compiler translates the keywords into the creation of a thread but according to the <a href="http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=d7ccfefa-123a-40e5-8ed5-8d2edd68acf4&amp;displaylang=en" rel="nofollow noreferrer">white paper</a> and Anders Hejlsberg's <a href="http://player.microsoftpdc.com/Session/1b127a7d-300e-4385-af8e-ac747fee677a" rel="nofollow noreferrer">PDC presentation</a> (at 31:00) the asynchronous operation happens completely on the main thread.</p> <p>How can I have an operation executed in parallel on the same thread? How is it technically possible and to what is the feature actually translated in IL?</p>
4,047,607
3
0
null
2010-10-28 21:47:43.393 UTC
20
2022-07-18 20:06:05.313 UTC
2021-11-01 11:33:18.33 UTC
null
11,178,549
null
40,347
null
1
47
c#|.net|vb.net|asynchronous|async-await
14,482
<p>It works similarly to the <code>yield return</code> keyword in C# 2.0.</p> <p>An asynchronous method is not actually an ordinary sequential method. It is compiled into a state machine (an object) with some state (local variables are turned into fields of the object). Each block of code between two uses of <code>await</code> is one "step" of the state machine. </p> <p>This means that when the method starts, it just runs the first step and then the state machine returns and schedules some work to be done - when the work is done, it will run the next step of the state machine. For example this code:</p> <pre><code>async Task Demo() { var v1 = foo(); var v2 = await bar(); more(v1, v2); } </code></pre> <p>Would be translated to something like:</p> <pre><code>class _Demo { int _v1, _v2; int _state = 0; Task&lt;int&gt; _await1; public void Step() { switch(this._state) { case 0: this._v1 = foo(); this._await1 = bar(); // When the async operation completes, it will call this method this._state = 1; op.SetContinuation(Step); case 1: this._v2 = this._await1.Result; // Get the result of the operation more(this._v1, this._v2); } } </code></pre> <p>The important part is that it just uses the <code>SetContinuation</code> method to specify that when the operation completes, it should call the <code>Step</code> method again (and the method knows that it should run the second bit of the original code using the <code>_state</code> field). You can easily imagine that the <code>SetContinuation</code> would be something like <code>btn.Click += Step</code>, which would run completely on a single thread. </p> <p>The asynchronous programming model in C# is very close to F# asynchronous workflows (in fact, it is essentially the same thing, aside from some technical details), and writing reactive single-threaded GUI applications using <code>async</code> is quite an interesting area - at least I think so - see for example <a href="http://dotnetslackers.com/articles/net/Programming-user-interfaces-using-f-sharp-workflows.aspx" rel="noreferrer">this article</a> (maybe I should write a C# version now :-)).</p> <p>The translation is similar to iterators (and <code>yield return</code>) and in fact, it was possible to use iterators to implement asynchronous programming in C# earlier. I wrote <a href="http://tomasp.net/blog/csharp-async.aspx" rel="noreferrer">an article about that</a> a while ago - and I think it can still give you some insight on how the translation works.</p>
4,669,704
How do I install the Visual Web Developer feature for Visual Studio 2010
<p>I have Visual Studio 2010 Premium installed, and I want to install the Silverlight 4 SDK.</p> <p>The SDK says that it requires the Visual Web Developer feature for Visual Studio 2010. Any idea as to how to install, or activate this feature?</p> <hr> <p><img src="https://i.stack.imgur.com/orCLl.png" alt="enter image description here"></p>
4,669,738
4
1
null
2011-01-12 14:09:51.41 UTC
2
2017-03-08 07:49:59.967 UTC
2013-03-26 11:57:29.337 UTC
null
284,795
null
394,157
null
1
33
visual-studio|visual-studio-2010|visual-web-developer
53,894
<p>Run the Visual Studio installer and double check the installed components. Make sure Web Developer is enabled (Web Developer should be part of the standard installation for VS 2010 Premium) and then hit OK.</p> <p>Once the installation has completed try installing the Silverlight SDK again.</p>
4,492,678
Swap rows with columns (transposition) of a matrix in javascript
<p>For instance I have a matrix like this:</p> <pre><code>|1 2 3| |4 5 6| |7 8 9| </code></pre> <p>and I need it to convert into a matrix like this:</p> <pre><code>|1 4 7| |2 5 8| |3 6 9| </code></pre> <p>What is the best and optimal way to achieve this goal?</p>
4,492,703
5
0
null
2010-12-20 18:31:41.15 UTC
8
2019-05-24 18:56:45.953 UTC
2015-10-10 23:03:08.527 UTC
null
3,183,756
null
282,887
null
1
35
javascript|matrix|multidimensional-array|swap
62,072
<p>See article: <a href="http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery" rel="noreferrer">Transpose An Array In JavaScript and jQuery</a></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>function transpose(a) { // Calculate the width and height of the Array var w = a.length || 0; var h = a[0] instanceof Array ? a[0].length : 0; // In case it is a zero matrix, no transpose routine needed. if(h === 0 || w === 0) { return []; } /** * @var {Number} i Counter * @var {Number} j Counter * @var {Array} t Transposed data is stored in this array. */ var i, j, t = []; // Loop through every item in the outer array (height) for(i=0; i&lt;h; i++) { // Insert a new row (array) t[i] = []; // Loop through every item per item in outer array (width) for(j=0; j&lt;w; j++) { // Save transposed data. t[i][j] = a[j][i]; } } return t; } console.log(transpose([[1,2,3],[4,5,6],[7,8,9]]));</code></pre> </div> </div> </p>
4,050,381
Regular expression for checking if capital letters are found consecutively in a string
<p>I want to know the regexp for the following case:</p> <p>The string should contain only alphabetic letters. It must start with a capital letter followed by small letter. Then it can be small letters or capital letters.</p> <pre><code>^[A-Z][a-z][A-Za-z]*$ </code></pre> <p>But the string must also not contain any consecutive capital letters. How do I add that logic to the regexp?</p> <p>That is, <code>HttpHandler</code> is correct, but <code>HTTPHandler</code> is wrong.</p>
4,052,496
5
0
null
2010-10-29 08:54:06.347 UTC
29
2021-11-10 01:45:50.787 UTC
2021-11-10 01:34:13.33 UTC
null
63,550
null
454,660
null
1
78
regex|capitalize
251,956
<p>Take a look at <a href="https://stackoverflow.com/questions/4050381/regular-expression-for-checking-if-capital-letters-are-found-consecutively-in-a#answer-4052294">tchrist's answer</a>, especially if you develop for the web or something more &quot;international&quot;.</p> <p><a href="https://stackoverflow.com/questions/4050381/regular-expression-for-checking-if-capital-letters-are-found-consecutively-in-a/4050419#4050419">Oren Trutner's answer</a> isn't quite right (see sample input of &quot;RightHerE&quot; which must be matched, but isn't).</p> <p>Here is the correct solution:</p> <pre><code>(?!^.*[A-Z]{2,}.*$)^[A-Za-z]*$ </code></pre> <p>Explained:</p> <pre><code>(?!^.*[A-Z]{2,}.*$) // don't match the whole expression if there are two or more consecutive uppercase letters ^[A-Za-z]*$ // match uppercase and lowercase letters </code></pre> <p>/edit</p> <p>The key for the solution is a negative lookahead. See: <em><a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow noreferrer">Lookahead and Lookbehind Zero-Length Assertions</a></em></p>
4,641,476
Using Dynamic Memory allocation for arrays
<p>How am I supposed to use dynamic memory allocations for arrays?</p> <p>For example here is the following array in which i read individual words from a .txt file and save them word by word in the array:</p> <p>Code:</p> <pre><code>char words[1000][15]; </code></pre> <p>Here 1000 defines the number of words the array can save and each word may comprise of not more than 15 characters.</p> <p>Now I want that that program should dynamically allocate the memory for the number of words it counts. For example, a .txt file may contain words greater that 1000. Now I want that the program should count the number of words and allocate the memory accordingly.</p> <p>Since we cannot use a variable in place of [1000], I am completely blank at how to implement my logic. Please help me in this regard.</p>
4,641,532
8
0
null
2011-01-09 20:10:05.427 UTC
5
2015-04-01 06:27:24.053 UTC
2011-01-09 20:13:35.59 UTC
null
260,990
null
569,085
null
1
13
c|arrays|memory|dynamic-memory-allocation
80,580
<p>You use pointers.</p> <p>Specifically, you use a pointer to an address, and using a standard c library function calls, you ask the operating system to expand the heap to allow you to store what you need to.</p> <p>Now, it might refuse, which you will need to handle.</p> <p>The next question becomes - how do you ask for a 2D array? Well, you ask for an array of pointers, and then expand each pointer.</p> <p>As an example, consider this:</p> <pre><code>int i = 0; char** words; words = malloc((num_words)*sizeof(char*)); if ( words == NULL ) { /* we have a problem */ printf("Error: out of memory.\n"); return; } for ( i=0; i&lt;num_words; i++ ) { words[i] = malloc((word_size+1)*sizeof(char)); if ( words[i] == NULL ) { /* problem */ break; } } if ( i != num_words ) { /* it didn't allocate */ } </code></pre> <p>This gets you a two-dimensional array, where each element <code>words[i]</code> can have a different size, determinable at run time, just as the number of words is.</p> <p>You will need to <code>free()</code> all of the resultant memory by looping over the array when you're done with it:</p> <pre><code>for ( i = 0; i &lt; num_words; i++ ) { free(words[i]); } free(words); </code></pre> <p>If you don't, you'll create a memory leak.</p> <p>You could also use <code>calloc</code>. The difference is in calling convention and effect - <code>calloc</code> initialises all the memory to <code>0</code> whereas <code>malloc</code> does not.</p> <p>If you need to resize at runtime, use <code>realloc</code>.</p> <ul> <li><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/" rel="noreferrer">Malloc</a></li> <li><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/calloc/" rel="noreferrer">Calloc</a></li> <li><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/" rel="noreferrer">Realloc</a></li> <li><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/free/" rel="noreferrer">Free</a></li> </ul> <hr> <p>Also, important, <strong>watch out for the word_size+1</strong> that I have used. Strings in C are zero-terminated and this takes an extra character which you need to account for. To ensure I remember this, I usually set the size of the variable <code>word_size</code> to whatever the size of the word should be (the length of the string as I expect) and explicitly leave the +1 in the malloc for the zero. Then I know that the allocated buffer can take a string of <code>word_size</code> characters. Not doing this is also fine - I just do it because I like to explicitly account for the zero in an obvious way.</p> <p><strong>There is also a downside to this approach</strong> - I've explicitly seen this as a shipped bug recently. Notice I wrote <code>(word_size+1)*sizeof(type)</code> - imagine however that I had written <code>word_size*sizeof(type)+1</code>. For <code>sizeof(type)=1</code> these are the same thing but Windows uses <code>wchar_t</code> very frequently - and in this case you'll reserve one byte for your last zero rather than two - and they are zero-terminated elements of type <code>type</code>, not single zero bytes. This means you'll overrun on read and write. &nbsp;</p> <p>Addendum: do it whichever way you like, just watch out for those zero terminators if you're going to pass the buffer to something that relies on them.</p>
4,389,572
How to fetch a non-ascii url with urlopen?
<p>I need to fetch data from a URL with non-ascii characters but urllib2.urlopen refuses to open the resource and raises:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u0131' in position 26: ordinal not in range(128) </code></pre> <p>I know the URL is not standards compliant but I have no chance to change it. </p> <p>What is the way to access a resource pointed by a URL containing non-ascii characters using Python?</p> <p><strong>edit:</strong> In other words, can / how urlopen open a URL like:</p> <pre><code>http://example.org/Ñöñ-ÅŞÇİİ/ </code></pre>
4,391,299
10
0
null
2010-12-08 16:06:33.36 UTC
21
2021-10-17 06:18:56.15 UTC
2021-04-25 16:05:07.48 UTC
null
355,230
null
287,923
null
1
51
python|unicode|urllib2|non-ascii-characters|urlopen
34,232
<p>Strictly speaking URIs can't contain non-ASCII characters; what you have there is an <a href="http://en.wikipedia.org/wiki/Internationalized_Resource_Identifier">IRI</a>.</p> <p>To convert an IRI to a plain ASCII URI:</p> <ul> <li><p>non-ASCII characters in the hostname part of the address have to be encoded using the <a href="http://en.wikipedia.org/wiki/Punycode">Punycode</a>-based IDNA algorithm;</p></li> <li><p>non-ASCII characters in the path, and most of the other parts of the address have to be encoded using UTF-8 and %-encoding, as per Ignacio's answer.</p></li> </ul> <p>So:</p> <pre><code>import re, urlparse def urlEncodeNonAscii(b): return re.sub('[\x80-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), b) def iriToUri(iri): parts= urlparse.urlparse(iri) return urlparse.urlunparse( part.encode('idna') if parti==1 else urlEncodeNonAscii(part.encode('utf-8')) for parti, part in enumerate(parts) ) &gt;&gt;&gt; iriToUri(u'http://www.a\u0131b.com/a\u0131b') 'http://www.xn--ab-hpa.com/a%c4%b1b' </code></pre> <p>(Technically this still isn't quite good enough in the general case because <code>urlparse</code> doesn't split away any <code>user:pass@</code> prefix or <code>:port</code> suffix on the hostname. Only the hostname part should be IDNA encoded. It's easier to encode using normal <code>urllib.quote</code> and <code>.encode('idna')</code> at the time you're constructing a URL than to have to pull an IRI apart.)</p>
14,540,262
How does git push work with android's repo tool?
<p>I'm used to using <code>git</code> with a single repository. However, I've lately been dabbling with Android development and am trying to wrap my head around <code>repo</code>. I have set up some custom git repos by creating xmls in the <code>.repo/local_manifests</code> directory (I'm using repo 1.19) and <code>repo sync</code> works fine.</p> <p>When I look at the custom git repos they say <code># Not currently on any branch.</code> This looks just like when I use a command like <code>git checkout abcd1234</code> (to check out commit abcd1234) rather than <code>git checkout origin/master</code>. As far as making changes, I'm not sure how to push back to origin. Here's my normal git workflow.</p> <pre><code>git checkout origin/master #make changes to working directory git add . git commit -m 'useful message' #assume time has passed and there could be changes upstream git fetch git rebase origin/master git push origin master </code></pre> <p>Now that I'm no longer technically on a branch, how can I push changes? I know there is a tool <code>repo upload</code> but I'm not exactly sure how it works. I've never used Gerrit, but maybe it would be worth setting up so other team members can review code before it gets pushed to Github. Honestly I still have a very abstract understanding of <code>repo</code> and <code>Gerrit</code>.</p>
14,545,270
1
0
null
2013-01-26 18:42:51.137 UTC
9
2013-01-27 07:11:54.47 UTC
null
null
null
null
817,950
null
1
13
android|git|github|gerrit|repository
10,973
<p>Technically, if you do</p> <pre><code>git checkout origin/master </code></pre> <p>you immediately get into detached HEAD state.</p> <p>For better or worse, this is exactly what <code>repo sync</code> does by default - such that every one of your repositories listed in manifest is in detached HEAD state after fresh <code>repo sync</code>.</p> <p>Detached HEAD is perfectly normal state for <code>repo</code> - if origin/master moves forward, <code>repo sync</code> will also move your local state (effectively it does <code>git checkout origin/master</code> again).</p> <p>However, this weird state is not good if you want to make your own changes and push them upstream. In this case, you can do one of the following:</p> <pre><code>repo start master . </code></pre> <p>which means start tracking branch called <code>master</code> in current project (<code>.</code>).</p> <p>Alternatively, you can use (and I prefer this, actually):</p> <pre><code>git checkout --track origin/master </code></pre> <p>Both methods will give you almost identical result: you no longer will be in detached HEAD state, but on local branch which will be tracking remote branch.</p> <p>At this point, you can make local commits and push them directly upstream using standard <code>git push</code> (but this may not be permitted by server policy) or you can submit for Gerrit code review (highly recommended and is default choice for most Android shops). Once tracking branch is in place, submitting to Gerrit is as simple as</p> <pre><code>repo upload # upload changes in multiple repositories at once </code></pre> <p>or</p> <pre><code>repo upload . # upload changes in current git repo only, fast! </code></pre> <p>(this assumes that your manifest contains proper settings for review server).</p>
14,707,742
How to indent my code in codeblocks?
<p>What are the best code blocks short cuts ? Also is there some way we can directly indent all our code ? In addition how can we move through the active tabs in codeblocks ? </p>
14,711,209
6
1
null
2013-02-05 12:37:01.21 UTC
4
2020-11-17 18:44:58.527 UTC
null
null
null
null
1,737,817
null
1
15
codeblocks
65,135
<p>You (these are the default settings I believe) can select a block of code and press the <kbd>Tab</kbd> key. This will <strong>indent</strong> the entire block. </p> <p>So for indenting a whole file: <kbd>Ctrl</kbd> + <kbd>A</kbd>, then <kbd>Tab</kbd>. </p> <p>In addition, you can use <kbd>Shift</kbd> + <kbd>Tab</kbd> on a selected block to <strong>"unindent"</strong></p> <p>You can move through the open tabs with <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Tab</kbd>.</p> <p><strong>As for the best shortcuts:</strong></p> <p>I like <kbd>Ctrl</kbd> + <kbd>D</kbd> to duplicate a line and </p> <p><kbd>Ctrl</kbd> + <kbd>L</kbd> to copy it. </p> <p>Anyway, you can set whatever shortkeys you like in the Editor menu (there you will also be able to find all shortkey currently set).</p>
14,904,776
Parse JavaScript with jsoup
<p>In an <code>HTML</code> page, I want to pick the value of a <code>javascript</code> variable.<br /> Below is the snippet of <code>HTML</code> page:</p> <pre><code>&lt;input id=&quot;hidval&quot; value=&quot;&quot; type=&quot;hidden&quot;&gt; &lt;form method=&quot;post&quot; style=&quot;padding: 0px;margin: 0px;&quot; name=&quot;profile&quot; autocomplete=&quot;off&quot;&gt; &lt;input name=&quot;pqRjnA&quot; id=&quot;pqRjnA&quot; value=&quot;&quot; type=&quot;hidden&quot;&gt; &lt;script type=&quot;text/javascript&quot;&gt; key=&quot;pqRjnA&quot;; &lt;/script&gt; </code></pre> <p>My aim is to read the value of variable <code>key</code> from this page using <code>jsoup</code>.<br /> Is it possible with <code>jsoup</code>? If yes then how?</p>
14,925,848
2
3
null
2013-02-15 22:58:04.31 UTC
6
2021-11-14 20:04:47.973 UTC
2021-11-14 15:23:30.287 UTC
null
8,583,692
null
1,175,065
null
1
16
javascript|java|html|kotlin|jsoup
40,576
<p>Since jsoup isn't a javascript library you have two ways to solve this:</p> <h2>A. Use a javascript library</h2> <ul> <li><p><strong>Pro:</strong></p> <ul> <li>Full Javascript support</li> </ul></li> <li><p><strong>Con:</strong></p> <ul> <li>Additional libraray / dependencies</li> </ul></li> </ul> <h2>B. Use Jsoup + manual parsing</h2> <ul> <li><p><strong>Pro:</strong></p> <ul> <li>No extra libraries required</li> <li>Enough for simple tasks</li> </ul></li> <li><p><strong>Con:</strong></p> <ul> <li>Not as flexible as a javascript library</li> </ul></li> </ul> <p>Here's an example how to get the <code>key</code> with jsoupand some <em>"manual"</em> code:</p> <pre><code>Document doc = ... Element script = doc.select("script").first(); // Get the script part Pattern p = Pattern.compile("(?is)key=\"(.+?)\""); // Regex for the value of the key Matcher m = p.matcher(script.html()); // you have to use html here and NOT text! Text will drop the 'key' part while( m.find() ) { System.out.println(m.group()); // the whole key ('key = value') System.out.println(m.group(1)); // value only } </code></pre> <p><strong>Output (using your html part):</strong></p> <pre><code>key="pqRjnA" pqRjnA </code></pre>
14,878,706
Merge xml files with nested elements without external libraries
<p>I am trying to merge multiple XML files together using Python and no external libraries. The XML files have nested elements.</p> <p><strong>Sample File 1:</strong></p> <pre><code>&lt;root&gt; &lt;element1&gt;textA&lt;/element1&gt; &lt;elements&gt; &lt;nested1&gt;text now&lt;/nested1&gt; &lt;/elements&gt; &lt;/root&gt; </code></pre> <p><strong>Sample File 2:</strong></p> <pre><code>&lt;root&gt; &lt;element2&gt;textB&lt;/element2&gt; &lt;elements&gt; &lt;nested1&gt;text after&lt;/nested1&gt; &lt;nested2&gt;new text&lt;/nested2&gt; &lt;/elements&gt; &lt;/root&gt; </code></pre> <p><strong>What I Want:</strong></p> <pre><code>&lt;root&gt; &lt;element1&gt;textA&lt;/element1&gt; &lt;element2&gt;textB&lt;/element2&gt; &lt;elements&gt; &lt;nested1&gt;text after&lt;/nested1&gt; &lt;nested2&gt;new text&lt;/nested2&gt; &lt;/elements&gt; &lt;/root&gt; </code></pre> <p><strong>What I have tried:</strong></p> <p>From <a href="https://stackoverflow.com/a/11315257/1561176">this answer</a>. </p> <pre><code>from xml.etree import ElementTree as et def combine_xml(files): first = None for filename in files: data = et.parse(filename).getroot() if first is None: first = data else: first.extend(data) if first is not None: return et.tostring(first) </code></pre> <p><strong>What I Get:</strong></p> <pre><code>&lt;root&gt; &lt;element1&gt;textA&lt;/element1&gt; &lt;elements&gt; &lt;nested1&gt;text now&lt;/nested1&gt; &lt;/elements&gt; &lt;element2&gt;textB&lt;/element2&gt; &lt;elements&gt; &lt;nested1&gt;text after&lt;/nested1&gt; &lt;nested2&gt;new text&lt;/nested2&gt; &lt;/elements&gt; &lt;/root&gt; </code></pre> <p>I hope you can see and understand my problem. I am looking for a proper solution, any guidance would be wonderful.</p> <p>To clarify the problem, using the current solution that I have, nested elements are not merged.</p>
14,879,370
3
0
null
2013-02-14 15:51:02.93 UTC
13
2021-05-11 16:00:52.753 UTC
2017-05-23 11:55:10.85 UTC
null
-1
null
1,561,176
null
1
17
python|xml|python-2.7|elementtree
23,317
<p>What the code you posted is doing is combining all the elements regardless of whether or not an element with the same tag already exists. So you need to iterate over the elements and manually check and combine them the way you see fit, because it is not a standard way of handling XML files. I can't explain it better than code, so here it is, more or less commented:</p> <pre><code>from xml.etree import ElementTree as et class XMLCombiner(object): def __init__(self, filenames): assert len(filenames) &gt; 0, 'No filenames!' # save all the roots, in order, to be processed later self.roots = [et.parse(f).getroot() for f in filenames] def combine(self): for r in self.roots[1:]: # combine each element with the first one, and update that self.combine_element(self.roots[0], r) # return the string representation return et.tostring(self.roots[0]) def combine_element(self, one, other): """ This function recursively updates either the text or the children of an element if another element is found in `one`, or adds it from `other` if not found. """ # Create a mapping from tag name to element, as that's what we are fltering with mapping = {el.tag: el for el in one} for el in other: if len(el) == 0: # Not nested try: # Update the text mapping[el.tag].text = el.text except KeyError: # An element with this name is not in the mapping mapping[el.tag] = el # Add it one.append(el) else: try: # Recursively process the element, and update it in the same way self.combine_element(mapping[el.tag], el) except KeyError: # Not in the mapping mapping[el.tag] = el # Just add it one.append(el) if __name__ == '__main__': r = XMLCombiner(('sample1.xml', 'sample2.xml')).combine() print '-'*20 print r </code></pre>
14,429,703
When to call .join() on a process?
<p>I am reading various tutorials on the multiprocessing module in Python, and am having trouble understanding why/when to call <code>process.join()</code>. For example, I stumbled across this example:</p> <pre><code>nums = range(100000) nprocs = 4 def worker(nums, out_q): """ The worker function, invoked in a process. 'nums' is a list of numbers to factor. The results are placed in a dictionary that's pushed to a queue. """ outdict = {} for n in nums: outdict[n] = factorize_naive(n) out_q.put(outdict) # Each process will get 'chunksize' nums and a queue to put his out # dict into out_q = Queue() chunksize = int(math.ceil(len(nums) / float(nprocs))) procs = [] for i in range(nprocs): p = multiprocessing.Process( target=worker, args=(nums[chunksize * i:chunksize * (i + 1)], out_q)) procs.append(p) p.start() # Collect all results into a single result dict. We know how many dicts # with results to expect. resultdict = {} for i in range(nprocs): resultdict.update(out_q.get()) # Wait for all worker processes to finish for p in procs: p.join() print resultdict </code></pre> <p>From what I understand, <code>process.join()</code> will block the calling process until the process whose join method was called has completed execution. I also believe that the child processes which have been started in the above code example complete execution upon completing the target function, that is, after they have pushed their results to the <code>out_q</code>. Lastly, I believe that <code>out_q.get()</code> blocks the calling process until there are results to be pulled. Thus, if you consider the code:</p> <pre><code>resultdict = {} for i in range(nprocs): resultdict.update(out_q.get()) # Wait for all worker processes to finish for p in procs: p.join() </code></pre> <p>the main process is blocked by the <code>out_q.get()</code> calls until <em>every single worker process</em> has finished pushing its results to the queue. Thus, by the time the main process exits the for loop, each child process should have completed execution, correct? </p> <p>If that is the case, is there any reason for calling the <code>p.join()</code> methods at this point? Haven't all worker processes already finished, so how does that cause the main process to "wait for all worker processes to finish?" I ask mainly because I have seen this in multiple different examples, and I am curious if I have failed to understand something.</p>
14,430,044
3
3
null
2013-01-20 21:45:34.94 UTC
15
2020-03-09 22:12:58.827 UTC
2013-01-20 22:09:30.4 UTC
null
815,632
null
1,356,561
null
1
36
python|multiprocessing
40,750
<p>Try to run this:</p> <pre><code>import math import time from multiprocessing import Queue import multiprocessing def factorize_naive(n): factors = [] for div in range(2, int(n**.5)+1): while not n % div: factors.append(div) n //= div if n != 1: factors.append(n) return factors nums = range(100000) nprocs = 4 def worker(nums, out_q): """ The worker function, invoked in a process. 'nums' is a list of numbers to factor. The results are placed in a dictionary that's pushed to a queue. """ outdict = {} for n in nums: outdict[n] = factorize_naive(n) out_q.put(outdict) # Each process will get 'chunksize' nums and a queue to put his out # dict into out_q = Queue() chunksize = int(math.ceil(len(nums) / float(nprocs))) procs = [] for i in range(nprocs): p = multiprocessing.Process( target=worker, args=(nums[chunksize * i:chunksize * (i + 1)], out_q)) procs.append(p) p.start() # Collect all results into a single result dict. We know how many dicts # with results to expect. resultdict = {} for i in range(nprocs): resultdict.update(out_q.get()) time.sleep(5) # Wait for all worker processes to finish for p in procs: p.join() print resultdict time.sleep(15) </code></pre> <p>And open the task-manager. You should be able to see that the 4 subprocesses go in zombie state for some seconds before being terminated by the OS(due to the join calls):</p> <p><img src="https://i.stack.imgur.com/91vJs.png" alt="enter image description here"></p> <p>With more complex situations the child processes could stay in zombie state forever(like the situation you was asking about in an other <a href="https://stackoverflow.com/questions/14423826/how-does-a-python-process-know-when-to-exit/14423951#14423951">question</a>), and if you create enough child-processes you could fill the process table causing troubles to the OS(which may kill your main process to avoid failures).</p>
14,665,491
Why are @Scripts and @Styles commands not be recognized in MVC4 Razor layout file?
<p>The following MVC4 Razor layout file loads several script and css bundles created in Bundle.config.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html class="no-js" lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;XXX Beta&lt;/title&gt; @Scripts.Render( "~/bundles/bundle_jquery", "~/bundles/bundle_modernizr", "~/bundles/bundle_foundation", "~/bundles/bundle_jhs") @Styles.Render( "~/Content/bundle_foundation", "~/Content/bundle_jhs") @RenderSection("pageHeadContent", false) &lt;/head&gt; &lt;body&gt; &lt;div id="bodyContainer"&gt; @Html.Partial("Partial/_header") &lt;div id="contentContainer"&gt; &lt;div id="mainContentContainer"&gt; &lt;div id="sidebarContainer"&gt; @RenderSection("sidebarContent", required: true) &lt;/div&gt; @RenderBody() &lt;/div&gt; &lt;div class="clearBoth"&gt; &lt;/div&gt; &lt;/div&gt; @Html.Partial("Partial/_footer") &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When the page is rendered the following error occurs. For some reason the @Scripts and @Styles commands are not being recognized. If I type in "@Scripts" in the files the Intellisense does not display/show the command. The project does reference System.Web.Optimization, which is used in the Bundle.config.</p> <p>What could be causing the @Scripts and @Styles commands not to be recognized?</p> <hr> <p>Server Error in '/' Application.</p> <p>Compilation Error</p> <p>Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. </p> <p>Compiler Error Message: CS0103: The name 'Scripts' does not exist in the current context</p> <p>Source Error:</p> <p>Line 4: Line 5: XXX Beta Line 6: @Scripts.Render( Line 7: "~/bundles/bundle_jquery", Line 8: "~/bundles/bundle_modernizr",</p> <p>Source File: c:\Users\username\Documents\Visual Studio 2010\Projects\XXX\Solution\xxx.website\Views\Shared_sidebarLayout.cshtml Line: 6 </p> <p>Show Detailed Compiler Output:</p> <p>Show Complete Compilation Source:</p> <h2>Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272</h2>
14,665,528
7
0
null
2013-02-02 19:14:32.42 UTC
8
2019-01-10 03:30:50 UTC
null
null
null
null
94,508
null
1
41
asp.net|asp.net-mvc|razor|asp.net-mvc-4
62,506
<p>Make sure that the <code>System.Web.Optimization.dll</code> assembly has been referenced in your project and that the <code>&lt;add namespace="System.Web.Optimization"/&gt;</code> namespace has been added to your <code>~/Views/web.config</code> file (not <code>~/web.config</code> file):</p> <pre><code>&lt;system.web.webPages.razor&gt; &lt;host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt; &lt;pages pageBaseType="System.Web.Mvc.WebViewPage"&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Optimization"/&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web.webPages.razor&gt; </code></pre> <p>The <code>System.Web.Optimization.dll</code> assembly is contained within the <a href="http://nuget.org/packages/microsoft.aspnet.web.optimization" rel="noreferrer"><code>Microsoft.AspNet.Web.Optimization</code></a> NuGet, so make sure that it is installed in your project (when you create a new ASP.NET MVC 4 project in Visual Studio using the Internet Template this NuGet is automatically added to the project).</p>
14,358,817
Best practice for localization and globalization of strings and labels
<p>I'm a member of a team with more than 20 developers. Each developer works on a separate module (something near 10 modules). In each module we might have at least 50 CRUD forms, which means that we currently have near 500 <strong>add buttons</strong>, <strong>save buttons</strong>, <strong>edit buttons</strong>, etc.</p> <p>However, because we want to globalized our application, we need to be able to translate texts in our application. For example, everywhere, the word <strong>add</strong> should become <strong>ajouter</strong> for French users.</p> <p>What we've done till now, is that for each view in UI or Presentation Layer, we have a dictionary of key/value pairs of translations. Then while rendering the view, we translate required texts and strings using this dictionary. However, this approach, we've come to have something near 500 <strong>add</strong> in 500 dictionaries. This means that we've breached DRY principal.</p> <p>On the other hand, if we centralize common strings, like putting <strong>add</strong> in one place, and ask developers to use it everywhere, we encounter the problem of not being sure if a string is already defined in the centralized dictionary or not.</p> <p>One other options might be to have no translation dictionary and use online translation services like Google Translate, Bing Translator, etc.</p> <p>Another problem that we've encountered is that some developers under the stress of delivering the project on-time can't remember the <strong>translation keys</strong>. For example, for the text of the add button, a developer has used <strong>add</strong> while another developer has used <strong>new</strong>, etc.</p> <p>What is the best practice, or most well-known method for globalization and localization of string resources of an application?</p>
14,359,147
3
1
null
2013-01-16 12:46:05.32 UTC
48
2016-12-26 19:38:15.57 UTC
2016-12-26 19:38:15.57 UTC
null
3,100,587
user1968030
null
null
1
129
javascript|localization|translation|client-side|globalization
134,771
<p>As far as I know, there's a good library called <code>localeplanet</code> for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery) </p> <p>Here's the website of library: <a href="http://www.localeplanet.com/" rel="noreferrer">http://www.localeplanet.com/</a></p> <p>Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: <a href="http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/" rel="noreferrer">http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/</a></p> <p>The common part of all those articles/libraries is that they use a <code>i18n</code> class and a <code>get</code> method (in some ways also defining an smaller function name like <code>_</code>) for retrieving/converting the <code>key</code> to the <code>value</code>. In my explaining the <code>key</code> means that string you want to translate and the <code>value</code> means translated string.<br> Then, you just need a JSON document to store <code>key</code>'s and <code>value</code>'s.</p> <p>For example:</p> <pre><code>var _ = document.webL10n.get; alert(_('test')); </code></pre> <p>And here the JSON:</p> <pre><code>{ test: "blah blah" } </code></pre> <p>I believe using current popular libraries solutions is a good approach. </p>
14,541,823
How to use concerns in Rails 4
<p>The default Rails 4 project generator now creates the directory "concerns" under controllers and models. I have found some explanations about how to use routing concerns, but nothing about controllers or models.</p> <p>I am pretty sure it has to do with the current "DCI trend" in the community and would like to give it a try.</p> <p>The question is, how am I supposed to use this feature, is there a convention on how to define the naming / class hierarchy in order to make it work? How can I include a concern in a model or controller?</p>
15,078,070
6
0
null
2013-01-26 21:36:27.56 UTC
238
2020-03-28 23:09:45.85 UTC
2015-12-14 10:04:37.48 UTC
null
2,202,702
null
784,270
null
1
642
ruby-on-rails|ruby-on-rails-4|dci
246,277
<p>So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.</p> <p>As an example, I'll put one well known pattern, the taggable pattern:</p> <pre><code># app/models/product.rb class Product include Taggable ... end # app/models/concerns/taggable.rb # notice that the file name has to match the module name # (applying Rails conventions for autoloading) module Taggable extend ActiveSupport::Concern included do has_many :taggings, as: :taggable has_many :tags, through: :taggings class_attribute :tag_limit end def tags_string tags.map(&amp;:name).join(', ') end def tags_string=(tag_string) tag_names = tag_string.to_s.split(', ') tag_names.each do |tag_name| tags.build(name: tag_name) end end # methods defined here are going to extend the class, not the instance of it module ClassMethods def tag_limit(value) self.tag_limit_value = value end end end </code></pre> <p>So following the Product sample, you can add Taggable to any class you desire and share its functionality.</p> <p>This is pretty well explained by <a href="http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns" rel="noreferrer">DHH</a>:</p> <blockquote> <p>In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.</p> </blockquote>
62,793,544
Efficient way to remove half of the duplicate items in a list
<p>If I have a list say <code>l = [1, 8, 8, 8, 1, 3, 3, 8]</code> and it's guaranteed that every element occurs an even number of times, how do I make a list with all elements of <code>l</code> now occurring <code>n/2</code> times. So since <code>1</code> occurred <code>2</code> times, it should now occur once. Since <code>8</code> occurs <code>4</code> times, it should now occur twice. Since <code>3</code> occurred twice, it should occur once.</p> <p>So the new list will be something like <code>k=[1,8,8,3]</code></p> <p>What is the fastest way to do this? I did <code>list.count()</code> for every element but it was very slow.</p>
62,793,817
12
9
null
2020-07-08 11:14:08.523 UTC
12
2020-07-30 21:25:16.063 UTC
2020-07-22 20:16:37.083 UTC
null
5,446,749
null
13,064,271
null
1
60
python|algorithm
11,016
<p>If order isn't important, a way would be to get the odd or even indexes only after a sort. Those lists will be the same so you only need one of them.</p> <pre><code>l = [1,8,8,8,1,3,3,8] l.sort() # Get all odd indexes odd = l[1::2] # Get all even indexes even = l[::2] print(odd) print(odd == even) </code></pre> <p>Result:</p> <pre><code>[1, 3, 8, 8] True </code></pre>
2,905,692
PostgreSQL - How to convert seconds in a numeric field to HH:MM:SS
<p>I'm new to PostgreSQL (I have been using MS SQL for many years) and need to convert a numeric column which contains a time in seconds to HH:MM:SS format.</p> <p>I have Googled and found that <code>to_char(interval '1000s', 'HH24:MI:SS')</code> works so I am attempting to use this with my field name:</p> <p><code>to_char(fieldname, 'HH24:MI:SS')</code> gives an error <code>cannot use "S" and "PL"/"MI"/"SG"/"PR" together</code></p> <p><code>to_char(fieldname::interval, 'HH24:MI:SS')</code> gives an error <code>cannot cast type numeric to interval</code></p> <p>Can anyone show me where I am going wrong?</p>
2,905,726
2
4
null
2010-05-25 14:42:16.37 UTC
9
2020-01-13 08:26:22.85 UTC
null
null
null
null
243,189
null
1
32
datetime|postgresql
54,770
<pre><code>SELECT TO_CHAR('1000 second'::interval, 'HH24:MI:SS') </code></pre> <p>or, in your case</p> <pre><code>SELECT TO_CHAR((mycolumn || ' second')::interval, 'HH24:MI:SS') FROM mytable </code></pre>
2,804,007
selectively execute task in ssis control flow
<p>I have a SSIS package with a control flow containing a bunch of execute sql tasks in a sequence.</p> <p>I need to check a flag for each of the tasks and run the task if it is set, if not skip and go to the next one.</p> <p>Each of the these task executes a stored proc. So i can check in the proc and "Return" if not set. I was looking for a "SSIS" solution if any.</p> <p>TIA</p> <p>PS</p>
2,804,229
2
0
null
2010-05-10 15:37:03.277 UTC
1
2019-10-17 21:27:26.71 UTC
2010-05-10 15:45:37.543 UTC
user65663
null
null
212,469
null
1
35
sql-server|sql-server-2008|ssis
56,469
<p>Between your control flow tasks, click on the arrow and choose Edit. When you do this, you get a dialog that allows you to check the "constraint" (success, completion or failure) of the task, an "expression" (i.e. you can have your execute sql task return a value, store that value in a variable, and check the value of that variable in an expression to determine whether to continue down the path you are editing), an "expression and a constraint", and an "expression or a constraint". These last two are the same except for the logic. "Expression and constraint" requires a true condition on both the expression and the constraint, "expression or constraint" requires a true condition on only one of the expression and the constraint.</p>
41,337,477
Select non-null rows from a specific column in a DataFrame and take a sub-selection of other columns
<p>I have a dataFrame which has several coulmns, so i choosed some of its coulmns to create a variable like this <code>xtrain = df[['Age','Fare', 'Group_Size','deck', 'Pclass', 'Title' ]]</code> i want to drop from these coulmns all raws that the Survive coulmn in the main dataFrame is nan.</p>
41,337,493
2
0
null
2016-12-27 00:06:47.46 UTC
11
2019-03-08 22:56:48.027 UTC
2019-03-08 22:56:48.027 UTC
null
3,367,799
user7308269
null
null
1
33
python|pandas
94,842
<p>You can pass a boolean mask to your df based on <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="noreferrer"><code>notnull()</code></a> of 'Survive' column and select the cols of interest:</p> <pre><code>In [2]: # make some data df = pd.DataFrame(np.random.randn(5,7), columns= ['Survive', 'Age','Fare', 'Group_Size','deck', 'Pclass', 'Title' ]) df['Survive'].iloc[2] = np.NaN df Out[2]: Survive Age Fare Group_Size deck Pclass Title 0 1.174206 -0.056846 0.454437 0.496695 1.401509 -2.078731 -1.024832 1 0.036843 1.060134 0.770625 -0.114912 0.118991 -0.317909 0.061022 2 NaN -0.132394 -0.236904 -0.324087 0.570660 0.758084 -0.176421 3 -2.145934 -0.020003 -0.777785 0.835467 1.498284 -1.371325 0.661991 4 -0.197144 -0.089806 -0.706548 1.621260 1.754292 0.725897 0.860482 </code></pre> <p>Now pass a mask to <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-label" rel="noreferrer"><code>loc</code></a> to take only non <code>NaN</code> rows:</p> <pre><code>In [3]: xtrain = df.loc[df['Survive'].notnull(), ['Age','Fare', 'Group_Size','deck', 'Pclass', 'Title' ]] xtrain Out[3]: Age Fare Group_Size deck Pclass Title 0 -0.056846 0.454437 0.496695 1.401509 -2.078731 -1.024832 1 1.060134 0.770625 -0.114912 0.118991 -0.317909 0.061022 3 -0.020003 -0.777785 0.835467 1.498284 -1.371325 0.661991 4 -0.089806 -0.706548 1.621260 1.754292 0.725897 0.860482 </code></pre>
35,206,125
How can I find and update values in an array of objects?
<p>I have an array of objects. I want to find by some field, and then to change it:</p> <pre><code>var item = {...} var items = [{id:2}, {id:2}, {id:2}]; var foundItem = items.find(x =&gt; x.id == item.id); foundItem = item; </code></pre> <p>I want it to change the original object. How? (I don't care if it will be in Lodash too.)</p>
35,206,193
10
1
null
2016-02-04 16:17:40.857 UTC
54
2022-07-25 21:32:23.803 UTC
2022-01-06 13:48:51.213 UTC
null
1,264,804
null
3,712,353
null
1
237
javascript|arrays|ecmascript-6|lodash
353,338
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="noreferrer">findIndex</a> to find the index in the array of the object and replace it as required:</p> <pre><code>var item = {...} var items = [{id:2}, {id:2}, {id:2}]; var foundIndex = items.findIndex(x =&gt; x.id == item.id); items[foundIndex] = item; </code></pre> <p>This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:</p> <pre><code>items.forEach((element, index) =&gt; { if(element.id === item.id) { items[index] = item; } }); </code></pre>
31,240,148
Spark specify multiple column conditions for dataframe join
<p>How to give more column conditions when joining two dataframes. For example I want to run the following :</p> <pre><code>val Lead_all = Leads.join(Utm_Master, Leaddetails.columns("LeadSource","Utm_Source","Utm_Medium","Utm_Campaign") == Utm_Master.columns("LeadSource","Utm_Source","Utm_Medium","Utm_Campaign"), "left") </code></pre> <p>I want to join only when these columns match. But above syntax is not valid as cols only takes one string. So how do I get what I want.</p>
31,247,623
9
0
null
2015-07-06 07:35:53.51 UTC
26
2019-11-17 15:57:37.17 UTC
2015-07-07 10:46:36.203 UTC
null
1,560,062
null
568,109
null
1
52
apache-spark|apache-spark-sql|rdd
140,624
<p>There is a Spark <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/DataFrame.scala#L514" rel="noreferrer">column/expression API join</a> for such case:</p> <pre class="lang-scala prettyprint-override"><code>Leaddetails.join( Utm_Master, Leaddetails("LeadSource") &lt;=&gt; Utm_Master("LeadSource") &amp;&amp; Leaddetails("Utm_Source") &lt;=&gt; Utm_Master("Utm_Source") &amp;&amp; Leaddetails("Utm_Medium") &lt;=&gt; Utm_Master("Utm_Medium") &amp;&amp; Leaddetails("Utm_Campaign") &lt;=&gt; Utm_Master("Utm_Campaign"), "left" ) </code></pre> <p>The <code>&lt;=&gt;</code> operator in the example means "<a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/Column.scala#L320" rel="noreferrer">Equality test that is safe for null values</a>".</p> <p>The main difference with simple <a href="https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/Column.scala#L132" rel="noreferrer">Equality test</a> (<code>===</code>) is that the first one is safe to use in case one of the columns may have null values.</p>
27,435,798
unhashable type: 'dict' Type Error
<p>Suppose I have this dictionary:</p> <pre><code>items = {1: {'title': u'testing123', 'description': u'testing456'}, 2: {'description': u'testing123', 'description': u'testing456'}, 3: {'description': u'testing123', 'description': u'testing456'}, 4: {'description': u'testing123', 'description': u'testing456'}, 5: {'description': u'testing123', 'description': u'testing456'}, 6: {'description': u'somethingelse', 'description': u'somethingelse'}} </code></pre> <p>I want to filter out the duplicate values, so that in the end I'd get </p> <pre><code>{1: {'title': u'testing123', 'description': u'testing456'}, 6: {'title': u'something', 'description': u'somethingelse'}} </code></pre> <p>I wrote this code:</p> <pre><code>dic = {} for key, value in items.items(): if not set(value.values()).issubset(set(dic.values())): dic[key] = value </code></pre> <p>however I get the error message <code>TypeError: unhashable type: 'dict'</code>. I am not sure why this happens and how to fix it. </p> <p>This is inspired by <a href="https://stackoverflow.com/questions/27435395/removing-duplicate-items-by-value-within-a-dict">another question</a> and my failed attempt to solve it. </p>
27,435,964
3
0
null
2014-12-12 02:14:49.313 UTC
3
2014-12-12 02:54:18.483 UTC
2017-05-23 12:25:08.173 UTC
null
-1
null
4,321,788
null
1
3
python|dictionary|python-3.3
45,171
<p>dic.values() return list of dict</p> <pre><code>&gt;&gt;&gt; for key, value in items.items(): ... print dic.values() ... [{'description': u'testing456', 'title': u'testing123'}] [{'description': u'testing456', 'title': u'testing123'}] [{'description': u'testing456', 'title': u'testing123'}] [{'description': u'testing456', 'title': u'testing123'}] [{'description': u'testing456', 'title': u'testing123'}] [{'description': u'testing456', 'title': u'testing123'}] &gt;&gt;&gt; </code></pre> <p>So, you can't apply set on dict as dict is not hashable.</p> <p>Btw you can fix it by:</p> <pre><code>&gt;&gt;&gt; dic = {} &gt;&gt;&gt; for key, value in items.items(): ... if not set(value.values()).issubset(set(sum([x.values() for x in dic.values()],[]))): ... dic[key] = value ... &gt;&gt;&gt; dic {1: {'description': u'testing456', 'title': u'testing123'}, 6: {'description': u'somethingelse', 'title': u'somethingelse'}} &gt;&gt;&gt; </code></pre> <p>For python > 3.x</p> <pre><code>if not set(value.values()).issubset(set(sum([list(x.values()) for x in list(dic.values())],[]))): </code></pre>
54,069,863
Swap two rows in a numpy array in python
<p>How to swap xth and yth rows of the 2-D NumPy array? x &amp; y are inputs provided by the user. Lets say x = 0 &amp; y =2 , and the input array is as below:</p> <pre><code>a = [[4 3 1] [5 7 0] [9 9 3] [8 2 4]] Expected Output : [[9 9 3] [5 7 0] [4 3 1] [8 2 4]] </code></pre> <p>I tried multiple things, but did not get the expected result. this is what i tried:</p> <pre><code>a[x],a[y]= a[y],a[x] output i got is: [[9 9 3] [5 7 0] [9 9 3] [8 2 4]] </code></pre> <p>Please suggest what is wrong in my solution.</p>
54,069,951
1
0
null
2019-01-07 07:06:39.66 UTC
4
2019-01-07 07:13:34.557 UTC
null
null
null
null
10,855,019
null
1
39
python|arrays|numpy|swap
63,144
<p>Put the index as a whole:</p> <pre><code>a[[x, y]] = a[[y, x]] </code></pre> <p>With your example:</p> <pre><code>a = np.array([[4,3,1], [5,7,0], [9,9,3], [8,2,4]]) a # array([[4, 3, 1], # [5, 7, 0], # [9, 9, 3], # [8, 2, 4]]) a[[0, 2]] = a[[2, 0]] a # array([[9, 9, 3], # [5, 7, 0], # [4, 3, 1], # [8, 2, 4]]) </code></pre>
53,842,697
How do you add a label (title text) to a Checkbox in Flutter?
<p>I am playing with Checkbox to see how it works, but I don't see a title option with it. </p> <pre><code>Checkbox( title: Text("Checkbox label"), // The named parameter 'title' isn't defined. value: true, onChanged: (newValue) { }, ); </code></pre> <p>Do I have to create my own widget to add a title to it?</p>
53,842,698
4
0
null
2018-12-18 23:43:05.307 UTC
8
2022-06-20 17:44:33.273 UTC
2019-05-02 16:43:04.96 UTC
null
3,681,880
null
3,681,880
null
1
40
checkbox|dart|flutter
40,888
<p>If you need a <a href="https://docs.flutter.io/flutter/material/Checkbox-class.html" rel="noreferrer"><code>Checkbox</code></a> with a label then you can use a <a href="https://docs.flutter.io/flutter/material/CheckboxListTile-class.html" rel="noreferrer"><code>CheckboxListTile</code></a>. </p> <p><a href="https://i.stack.imgur.com/PZesI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PZesI.png" alt="enter image description here"></a></p> <pre><code> CheckboxListTile( title: Text("title text"), // &lt;-- label value: checkedValue, onChanged: (newValue) { ... }, ) </code></pre> <p>If you want the checkbox on the left of the text then you can set the <code>controlAffinity</code> parameter.</p> <p><a href="https://i.stack.imgur.com/X6luX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X6luX.png" alt="enter image description here"></a></p> <pre><code> CheckboxListTile( title: Text("title text"), value: checkedValue, onChanged: (newValue) { ... }, controlAffinity: ListTileControlAffinity.leading, // &lt;-- leading Checkbox ) </code></pre> <h2>Notes</h2> <ul> <li>Since it is a ListTile, clicking anywhere on the row activates the <code>onChanged()</code> callback. You need to rebuild it with the correct checked values yourself, though. See <a href="https://stackoverflow.com/a/45154259/3681880">this answer</a>.</li> <li>An alternate solution would be to make your own widget using a Row with a Checkbox and a Text widget. You would probably want to wrap it in a gesture detector, though, so that taps on the text would also trigger an <code>onChanged()</code> callback. You could start with the <a href="https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/checkbox_list_tile.dart" rel="noreferrer"><code>CheckboxListTile</code> source code</a> as a reference.</li> </ul>
36,133,430
How to call function every 2 mins in angular2?
<p>How do I call a save function every two minutes in Angular2?</p>
36,133,464
1
0
null
2016-03-21 14:16:24.39 UTC
7
2019-08-23 15:57:27.237 UTC
2017-06-20 11:15:24.553 UTC
user663031
null
null
3,953,749
null
1
26
angular|ionic2
49,171
<p><strong>rxjs 6</strong></p> <pre><code> import { interval } from 'rxjs'; interval(2000 * 60).subscribe(x =&gt; { doSomething(); }); </code></pre> <p><strong>rxjs 5</strong></p> <p>You can either use </p> <pre><code>import {Observable} from 'rxjs'; // Angular 6 // import {Observable} from 'rxjs/Rx'; // Angular 5 Observable.interval(2000 * 60).subscribe(x =&gt; { doSomething(); }); </code></pre> <p>or just <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval" rel="noreferrer">setInterval()</a></p> <p><strong>Hint:</strong></p> <p>Angular >= 6.0.0 uses RxJS 6.0.0 <a href="https://github.com/angular/angular/blob/master/CHANGELOG.md#600-2018-05-03" rel="noreferrer">Angular Changelog 6.0.0</a></p> <p><a href="https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md" rel="noreferrer">RxJS v5.x to v6 Update Guide</a> </p>
50,032,950
Google gmail script that triggers on incoming email
<p>I've been reading through <a href="https://developers.google.com/gmail/add-ons/how-tos/building" rel="noreferrer" title="gmail add-ons">gmail addons</a>. They have contextual triggers that trigger when you open an email.</p> <p>Is it possible to trigger a service when an email is received by me? Best I can find is <code>unconditional</code> but that only triggers when the email is opened.</p>
50,033,834
4
1
null
2018-04-26 00:04:43.267 UTC
9
2022-03-10 02:42:48.167 UTC
2018-04-26 00:40:49.56 UTC
null
1,595,451
null
843,443
null
1
20
google-apps-script|gmail|gmail-addons
18,545
<p>You can't create a trigger for every email, however you can do something similar <a href="https://stackoverflow.com/questions/36108478/how-to-trigger-a-google-apps-script-once-an-email-get-in-the-inbox">as described in this answer</a>. </p> <p>For example you can:</p> <ol> <li><p>Set up a filter that puts a special label on incoming emails that you want to process.</p></li> <li><p>Set up a reoccurring script that runs every 10 minutes, or even every minute. In the script, you can pull all of the emails that have the given label, and process them accordingly, removing the label when you are done.</p></li> </ol> <pre><code>function processEmails() { var label = GmailApp.getUserLabelByName("Need To Process"); var threads = label.getThreads(); for (var i = threads.length - 1; i &gt;= 0; i--) { //Process them in the order received threads[i].removeLabel(label).refresh(); } } </code></pre> <p>You can then set this on a <a href="https://developers.google.com/apps-script/guides/triggers/installable" rel="noreferrer">time based trigger</a> to have it run as often as you would like.</p> <p>If you want to keep track of the emails you have processed, you can create another "processed" label and add that to the message when you are done processing.</p>
22,782,932
MySQL get first non null value after group by
<p>I have a large table with data that is not unique but needs to be. This table is a result of multiple union selects so is not an actual table. I cannot make it an actual table for other reasons.</p> <p>All of the UNION'd tables have an email column which will eventually be unique. The resulting records look like this:</p> <pre><code>1 [email protected] Ozzy 2 [email protected] Tony 3 [email protected] Steve 4 [email protected] 13 [email protected] Tony 14 [email protected] Ozzy 15 [email protected] Dave 16 [email protected] Tim </code></pre> <p>As you can see, some emails appear more then once with different names or non-existent names. When I add a <code>GROUP BY email</code> clause at the end, the results look like this:</p> <pre><code>1 [email protected] Ozzy 2 [email protected] Tony 3 [email protected] Steve 4 [email protected] 13 [email protected] Tony </code></pre> <p>As you can see, email 4 does not have a name because it chose the first entry with <code>NULL</code> for a name. Then I tried to use <code>GROUP_CONCAT</code> which made the results look like this:</p> <pre><code>1 [email protected] Ozzy 14 [email protected] Ozzy,Tony 15 [email protected] Dave,Steve 16 [email protected] Tim 13 [email protected] Tony </code></pre> <p>As you can see, now everyone has a name but some rows have more then one name concatenated. What I want to do is <code>GROUP BY email</code> and choose the first <code>NOT NULL</code> entry of each column for each row to theoretically look like so:</p> <pre><code>1 [email protected] Ozzy 2 [email protected] Tony 3 [email protected] Steve 4 [email protected] Tim 13 [email protected] Tony </code></pre> <p>I have tried using <code>COALESCE</code> but it doesn't work as intended. My current query looks like so:</p> <pre><code>SELECT id, email, `name` FROM ( SELECT email, `name` FROM multiple_tables_and_unions ) AS emails GROUP BY email </code></pre> <p>I have removed the code from the temporary table as it contains many tables but all select the <code>email</code> and <code>name</code> column. Essentially I need a function like <code>GROUP_COALESCE</code> but unfortunately it does not exist. What are my options?</p>
22,783,112
2
0
null
2014-04-01 10:18:11.38 UTC
8
2021-04-16 17:07:14.387 UTC
2021-04-16 17:07:14.387 UTC
null
3,964,927
null
104,452
null
1
39
mysql|group-by|group-concat
26,917
<p>Try using <code>MAX</code>, like this:</p> <pre><code>SELECT email, MAX(`name`) FROM ( SELECT email, `name` FROM multiple_tables_and_unions ) AS emails GROUP BY email </code></pre>
46,458,657
non-nominal type X does not support explicit initialization
<p>I'm trying to understand what I'm doing wrong with generics in swift.</p> <p>I created this sample playground</p> <pre><code>import UIKit public protocol MainControllerToModelInterface : class { func addGoal() init() } public protocol MainViewControllerInterface : class { associatedtype MODELVIEW var modelView: MODELVIEW? {get set} init(modelView: MODELVIEW) } public class MainViewController&lt;M&gt; : UIViewController, MainViewControllerInterface where M : MainControllerToModelInterface { public weak var modelView: M? required public init(modelView: M) { self.modelView = modelView super.init(nibName: String(describing: MainViewController.self), bundle: Bundle.main) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class Other&lt;C, M&gt; : NSObject where C : MainViewControllerInterface, C : UIViewController, M : MainControllerToModelInterface, C.MODELVIEW == M { var c : C? override init() { let m = M() self.c = C(modelView: m) super.init() } } </code></pre> <p>the line <code>self.c = C(modelView: m)</code> gives me this error <code>non-nominal type 'C' does not support explicit initialization</code></p> <p>From <a href="https://stackoverflow.com/questions/46086345/swift-generics-non-nominal-type-does-not-support-explicit-initialization">this other stack overflow</a> question I see that this error in older Xcode versions means </p> <p><code>cannot invoke initializer for type '%type' with an argument list of type '...' expected an argument list of type '...'</code></p> <p>But in the playground above what is the compiler missing?</p> <p>I'm on swift4/xcode9.</p> <p><strong>Update</strong></p> <p>After following the suggestion <code>Use C.init(modelView: m) rather than C(modelView: m)</code> the error changes in:</p> <p><code>No 'C.Type.init' candidates produce the expected contextual result type '_?'</code></p> <p>Than @vini-app suggested to remove the UIViewController to make it works. By I still don't understand why the compiler is not happy when UIViewController is there. Is it not enough to know that C has that valid init method?</p>
46,458,701
3
0
null
2017-09-27 23:22:19.11 UTC
1
2017-09-28 17:46:37.347 UTC
2017-09-28 17:46:37.347 UTC
null
2,104,263
null
2,104,263
null
1
32
ios|swift|xcode|generics|swift4
15,362
<p>You just need to use <code>init</code> explicitly whenever you're initializing a generic parameter rather than a "real" type:</p> <pre><code>self.c = C.init(modelView: m) </code></pre>
37,548,408
D3 4.0 rangeRoundBands equivalent?
<p>I see a lot of D3 code that has something like this:</p> <pre><code>var x = d3.scale.ordinal() .rangeRoundBands([0, width], .1); </code></pre> <p>As of D3 version 4.0 <code>d3.scale.ordinal()</code> is now <code>d3.scaleOrdinal</code> and <code>rangeRoundBands</code> seems to be gone.</p> <pre><code>&gt; d3.scaleOrdinal() { [Function: scale] domain: [Function], range: [Function], unknown: [Function], copy: [Function] } </code></pre> <p>What would the D3 v4 equivalent of this code (from Mike Bostock's <a href="http://bl.ocks.org/mbostock/3885304" rel="noreferrer">bar chart example</a>) be?</p> <pre><code>var x = d3.scale.ordinal() .rangeRoundBands([0, width], .1); </code></pre>
37,548,699
3
0
null
2016-05-31 14:25:00.383 UTC
10
2017-06-28 14:05:57.52 UTC
2017-04-24 08:25:52.41 UTC
null
4,155,792
null
130,006
null
1
65
javascript|d3.js
41,496
<p>In D3 4.x <code>rangeRoundBands</code> was moved to the new <em>Band</em> scale:</p> <pre><code>d3.scaleBand() .range([range]) .round([round]); </code></pre> <p>That's equivalent to:</p> <pre><code>d3.scaleBand() .rangeRound([range]); </code></pre> <p>Here is the API: <a href="https://github.com/d3/d3-scale#band-scales" rel="noreferrer">https://github.com/d3/d3-scale#band-scales</a></p>
37,262,047
React with TypeScript - define defaultProps in stateless function
<p>I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.</p> <pre><code>interface CenterBoxProps extends React.Props&lt;CenterBoxProps&gt; { minHeight?: number; } export const CenterBox = (props: CenterBoxProps) =&gt; { const minHeight = props.minHeight || 250; const style = { minHeight: minHeight }; return &lt;div style={style}&gt;Example div&lt;/div&gt;; }; </code></pre> <p>Everything is great and this code is working correctly. But there's my question: how can I define <code>defaultProps</code> for <code>CenterBox</code> component?</p> <p>As it is mentioned in <a href="https://facebook.github.io/react/docs/reusable-components.html#stateless-functions" rel="noreferrer">react docs</a>:</p> <blockquote> <p>(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and <strong>.defaultProps</strong> by setting them as properties on the function, just as you would set them on an ES6 class. (...)</p> </blockquote> <p>it should be easy as:</p> <pre><code>CenterBox.defaultProps = { minHeight: 250 } </code></pre> <p>But this code generates TSLint error: <code>error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) =&gt; Element'.</code></p> <p>So again: how can I correctly define <code>defaultProps</code> in my above stack (React + TypeScript)?</p>
37,262,331
7
0
null
2016-05-16 19:46:04.79 UTC
11
2020-02-14 23:16:17.387 UTC
2016-05-16 20:05:41.28 UTC
null
382,971
null
382,971
null
1
29
reactjs|typescript
30,836
<p>After 2 hours of looking for solution... <strong>it's working</strong>.</p> <p>If you want to define <code>defaultProps</code>, your arrow function should look like:</p> <pre><code>export const CenterBox: React.SFC&lt;CenterBoxProps&gt; = props =&gt; { (...) }; </code></pre> <p>Then you can define props like:</p> <pre><code>CenterBox.defaultProps = { someProp: true } </code></pre> <p>Note that <code>React.SFC</code> is alias for <code>React.StatelessComponent</code>.</p> <p>I hope that this question (and answer) help somebody. Make sure that you have installed newest React typings.</p>
31,484,742
(0xE8008018): The identity used to sign the executable is no longer valid
<p>I'm trying to debug my app on Xcode and I'm having the following error:</p> <pre><code>The identity used to sign the executable is no longer valid. Please verify that your device’s clock is properly set, and that your signing certificate is not expired. (0xE8008018). </code></pre> <p><img src="https://i.stack.imgur.com/Xe8Qu.png" alt="enter image description here"></p> <p>Now I know there are many questions regarding this issue, and I have tried every possible way to solve it, <strong>what I have tried so far (didn't work)</strong>:</p> <ul> <li>Some suggested to restart Xcode.</li> <li>Refreshing the account.</li> <li>Deleting all the certificates from the keychain.</li> <li>Revoking all the certificates from the member center.</li> <li>Installing the certificates manually.</li> <li>Checked my Devices clocks (obviously)</li> <li>Removed Xcode (disparately) and re-installed it.</li> <li>Checking my project Build config, and made sure that the developer account is selected.</li> <li>Checked my account expiration date (it's renewed 5 days ago)</li> <li>Checked if I have to accept some Conditions and Terms (none)</li> <li>Disabled the devices I have in the Member profile</li> <li>Tested on multiple iPhones (same result)</li> <li>Checked out a git tag/branch which is stable (I thought the project might be corrupted also disparately) </li> </ul> <p>My concern is that it might be a temporary issue from apple, or a bug in Xcode, although it was working hours ago on my iMac, when I switched to the MacBook Pro I had this issue (and I always do this with no problems at all).</p> <p>Running: </p> <ul> <li>OSX Yosemite 10.10.4 (14E46)</li> <li>Xcode 6.4</li> </ul>
31,485,634
11
1
null
2015-07-17 21:08:00.7 UTC
5
2016-06-04 09:28:01.017 UTC
2015-07-17 21:33:31.047 UTC
null
833,031
null
833,031
null
1
44
ios|xcode
35,371
<p>After hours of investigating, the shell script for signing the project was failing at some point, without reporting back to Xcode.</p> <p>I noticed that in the DerivedData folder (found in <code>/Users/yourUsername/Library/Developer/Xcode/DerivedData/</code>) of Xcode there were two folders with the same name of my project ending with a different hash, for example:</p> <pre><code>ProjectName--dcakkvkdhqvxstehdiuzwbpsmdal ProjectName--kurbctkdhqvxuytrwnczwbpsmdal </code></pre> <p>I closed Xcode, and made sure to <strong>delete both folders</strong>, somehow Xcode generated two different folders for the project at some point, restarting Xcode after the deletion of the folders fixed this.</p>
41,859,311
Cumsum as a new column in an existing Pandas data
<p>I have a pandas dataframe defined as:</p> <pre><code>A B SUM_C 1 1 10 1 2 20 </code></pre> <p>I would like to do a cumulative sum of SUM_C and add it as a new column to the same dataframe. In other words, my end goal is to have a dataframe that looks like below:</p> <pre><code>A B SUM_C CUMSUM_C 1 1 10 10 1 2 20 30 </code></pre> <p><a href="https://stackoverflow.com/questions/15755057/using-cumsum-in-pandas-on-group">Using cumsum in pandas on group()</a> shows the possibility of generating a new dataframe where column name SUM_C is replaced with cumulative sum. However, my ask is to add the cumulative sum as a new column to the existing dataframe.</p> <p>Thank you</p>
41,859,343
1
0
null
2017-01-25 18:48:09.93 UTC
6
2020-11-29 17:32:23.79 UTC
2018-08-31 10:06:50.543 UTC
null
7,053,679
null
1,124,702
null
1
34
python|pandas|dataframe|cumsum
45,490
<p>Just apply <code>cumsum</code> on the <code>pandas.Series</code> <code>df['SUM_C']</code> and assign it to a new column:</p> <pre><code>df['CUMSUM_C'] = df['SUM_C'].cumsum() </code></pre> <p>Result:</p> <pre><code>df Out[34]: A B SUM_C CUMSUM_C 0 1 1 10 10 1 1 2 20 30 </code></pre>
2,881,682
How to insert Arabic characters into SQL database?
<p>How can I insert Arabic characters into a SQL Server database? I tried to insert Arabic data into a table and the Arabic characters in the insert script were inserted as <code>'??????'</code> in the table.</p> <p>I tried to directly paste the data into the table through SQL Server Management Studio and the Arabic characters was successfully and accurately inserted.</p> <p>I looked around for resolutions for this problems and some threads suggested changing the datatype to <code>nvarchar</code> instead of <code>varchar</code>. I tried this as well but without any luck.</p> <p>How can we insert Arabic characters into SQL Server database?</p>
2,881,793
3
2
null
2010-05-21 11:42:14.047 UTC
8
2022-07-06 06:16:39.14 UTC
2021-09-23 08:29:49.757 UTC
null
1,127,428
null
227,809
null
1
27
sql|sql-server|tsql|insert|arabic
44,689
<p>For the field to be able to store unicode characters, you have to use the type <code>nvarchar</code> (or other similar like <code>ntext</code>, <code>nchar</code>).</p> <p>To insert the unicode characters in the database you have to send the text as unicode by using a parameter type like <code>nvarchar</code> / <code>SqlDbType.NVarChar</code>.</p> <p>(For completeness: if you are creating SQL dynamically (against common advice), you put an N before a string literal to make it unicode. For example: <code>insert into table (name) values (N'Pavan')</code>.)</p>
3,107,151
Persistent data structures in Scala
<p>Are all immutable data structures in Scala persistent? If not, which of them are and which not? What are the behavioural characteristics of those which are persistent? Also, how do they compare to the persistent data structures in Clojure?</p>
3,108,380
4
0
null
2010-06-24 03:57:56.333 UTC
18
2012-03-12 10:30:28.033 UTC
null
null
null
null
126,916
null
1
27
data-structures|scala|clojure|persistent
10,782
<p>Scala's immutable data structures are all persistent, in the sense that the old value is maintained by an `update' operation. In fact, I do not know of a difference between immutable and persistent; for me the two terms are aliases.</p> <p>Two of Scala's 2.8 immutable data structures are vectors and hash tries, represented as 32-ary trees. These were originally designed by Phil Bagwell, who was working with my team at EPFL, then adopted for Clojure, and now finally adopted for Scala 2.8. The Scala implementation shares a common root with the Clojure implementation, but is certainly not a port of it. </p>
28,889,977
R boxplot: How to customize the appearance of the box-and-whisker plots (e.g., remove lines or borders, change symbol of outliers)
<p>Today, I was wondering how to customize the appearance of the box-and-whisker plots. E.g., I wanted to remove the line around the box. However, the problem is, that the <code>border</code> argument changes the color of all lines of the box-and-whisker plots simultaneously. So, if one has the great idea to set <code>border = "white"</code> then the whiskers are also going to “disappear” and you have a white line representing your median.</p> <p>As I could not find a solution on the internet dealing with exactly my problem, I fiddled around a little and figured some mighty settings which seem to be nearly undocumented as a whole. These settings allow you to customize the appearance of your box-and-whisker plots to a large extend. I know, some of the features have already been unveiled on stackoverflow (e.g. <a href="https://stackoverflow.com/questions/17869343/make-a-boxplot-without-whiskers-in-r">here</a>). However, I could not find a complete documentation. Thus, this post.</p>
28,890,144
2
0
null
2015-03-05 23:44:04.277 UTC
18
2018-01-24 21:07:22.043 UTC
2018-01-24 21:07:22.043 UTC
null
3,162,788
null
3,162,788
null
1
12
r|shapes|boxplot|appearance|linestyle
39,142
<p>For complete documentation you should look at <code>?bxp</code> (linked from the <code>...</code> description in <code>?boxplot</code>, and in the "See Also" in <code>?boxplot</code>, and in the <code>pars</code> description in <code>?boxplot</code>.). It documents that <code>outpch</code> can change the shape of the outliers (though <code>pch</code> works fine too). It also has <code>boxlty</code>, <code>boxlwd</code>, <code>boxcol</code> and <code>boxfill</code> for the box, and many others for the whiskers, the staples, median line...</p>
37,697,866
NEST Conditional filter query with multiple terms
<p>I would like to do a ElasticSearch query like this:</p> <pre><code>{ "query" : { "bool" : { "filter" : [ { "terms" : { "name" : ["name1", "name2"] } }, { "terms" : { "color" : ["orange", "red"] } } ] } } } </code></pre> <p>I've tried to implement it in NEST like this:</p> <pre><code>_elasticClient .SearchAsync&lt;MyDocument&gt;(s =&gt; s.Index("myindex") .Query(q =&gt; q .Bool(bq =&gt; bq .Filter(fq =&gt; { QueryContainer query = null; if (nameList.Any()) { query &amp;= fq.Terms(t =&gt; t.Field(f =&gt; f.Name).Terms(nameList)); } if (colorList.Any()) { query &amp;= fq.Terms(t =&gt; t.Field(f =&gt; f.Color).Terms(colorList)); } return query; }) ) ) ); </code></pre> <p>But that gives me a query like this where the filters are wrapped inside a <em>bool must</em>:</p> <pre><code>{ "query" : { "bool" : { "filter" : [ { "bool" : { "must" : [ { "terms" : { "name" : ["name1", "name2"] } }, { "terms" : { "color" : ["orange", "red"] } } ] } } ] } } } </code></pre> <p>How should I change my NEST code to give me the right query? Do have have to add my terms to something other then a <em>QueryContainer</em>?</p>
37,708,493
3
0
null
2016-06-08 09:00:05.873 UTC
9
2018-12-05 10:40:08.157 UTC
null
null
null
null
617,413
null
1
23
c#|elasticsearch|nest
24,792
<p>You can create a list of filters before you make a query if you want to check conditional filters as shown below:</p> <pre><code>var nameList = new[] {"a", "b"}; var colorList = new[] {1, 2}; var filters = new List&lt;Func&lt;QueryContainerDescriptor&lt;MyDocument&gt;, QueryContainer&gt;&gt;(); if (nameList.Any()) { filters.Add(fq=&gt; fq.Terms(t =&gt; t.Field(f =&gt; f.Name).Terms(nameList))); } if (colorList.Any()) { filters.Add(fq =&gt; fq.Terms(t =&gt; t.Field(f =&gt; f.Color).Terms(colorList))); } ISearchResponse&lt;Property&gt; searchResponse = elasticClient.Search&lt;MyDocument&gt;(x =&gt; x.Query(q =&gt; q .Bool(bq =&gt; bq.Filter(filters)))); </code></pre> <p>If you don't need to check any condition before making filter query then you can have something like that:</p> <pre><code>ISearchResponse&lt;MyDocument&gt; searchResponse = elasticClient.Search&lt;MyDocument&gt;(x =&gt; x.Query(q =&gt; q .Bool(bq =&gt; bq .Filter( fq =&gt; fq.Terms(t =&gt; t.Field(f =&gt; f.Name).Terms(nameList)), fq =&gt; fq.Terms(t =&gt; t.Field(f =&gt; f.Color).Terms(colorList)) )))); </code></pre>
46,316,259
Timer countdown Angular 2
<p>I'm trying to make a countdown timer for my Ionic2 app, the thing is that I was using this method from now <a href="https://stackoverflow.com/a/44489685/4329781"><code>countdown timer</code></a> but now I have to create the countdown like 30:00 min, what's the better way to do it? Time could change, and if I want to fire something when the countdown it's done I only have to be comparing the <code>time</code> if it's 0, right?</p>
46,316,755
3
0
null
2017-09-20 07:50:12.413 UTC
4
2021-05-23 21:58:10.313 UTC
2019-05-11 07:47:03.693 UTC
null
5,468,463
null
4,329,781
null
1
10
javascript|angular|typescript|timer|countdown
39,621
<p>You can 'listen' to the timer and trigger the action when the countdown is 0. And to display the timer, use a pipe. </p> <p><strong>HTML</strong></p> <pre><code>{{counter | formatTime}} </code></pre> <p><strong>TypeScript</strong></p> <pre><code> countDown:Subscription; counter = 1800; tick = 1000; ngOnInit() { this.countDown = timer(0, this.tick) .subscribe(() =&gt; --this.counter) } ngOnDestroy(){ this.countDown=null; } </code></pre> <p><strong>Pipe</strong></p> <pre><code>//for MM:SS format transform(value: number): string { const minutes: number = Math.floor(value / 60); return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2); } </code></pre> <p><strong><a href="https://stackblitz.com/edit/angular-3fdr3k" rel="noreferrer">DEMO</a></strong></p> <pre><code>//for HH:MM:SS format transform(value: number): string { const hours: number = Math.floor(value / 3600); const minutes: number = Math.floor((value % 3600) / 60); return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2); } </code></pre> <p><a href="https://stackblitz.com/edit/angular-qsbdpt" rel="noreferrer"><strong>DEMO</strong></a> <hr> If you wish to use a service:</p> <p><strong>Service</strong></p> <pre><code> ... getCounter(tick) { return timer(0, tick) } ... </code></pre> <p><strong>Component</strong></p> <pre><code> countDown; counter=1800 ; tick=1000; constructor(private myService: MyService) { } ngOnInit() { this.countDown = this.myService.getCounter(this.tick).subscribe(() =&gt; this.counter--); } ngOnDestroy(){ this.countDown=null; } </code></pre> <p><strong>Pipe</strong></p> <pre><code> ... transform(value: number): string { //MM:SS format const minutes: number = Math.floor(value / 60); return ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2); // for HH:MM:SS //const hours: number = Math.floor(value / 3600); //const minutes: number = Math.floor((value % 3600) / 60); //return ('00' + hours).slice(-2) + ':' + ('00' + minutes).slice(-2) + ':' + ('00' + Math.floor(value - minutes * 60)).slice(-2); } </code></pre> <p><a href="https://stackblitz.com/edit/angular-aqkmsw" rel="noreferrer"><strong>DEMO</strong></a></p>
37,512,662
Is there anything wrong with using I/O + ManagedBlocker in Java8 parallelStream()?
<p>The default "paralellStream()" in Java 8 uses the common <code>ForkJoinPool</code> which may be a latency problem if the common Pool threads are exhausted when a task is submitted. However in many cases enough CPU power is available and the tasks are short enough so that this is not a problem. If we do have some long running tasks this will of course need some careful consideration, but for this question let's assume that this is not the problem.</p> <p>However filling the <code>ForkJoinPool</code> with I/O tasks that don't actually do any CPU-bound work is a way to introduce a bottleneck even though enough CPU power is available. <a href="https://stackoverflow.com/a/37257685/327301">I understood that</a>. However that is what we have the <code>ManagedBlocker</code> for. So if we have an I/O task we should simply allow the <code>ForkJoinPool</code> to manage that within a <code>ManagedBlocker</code>. That sounds incredibly easy. However to my surprise using a <code>ManagedBlocker</code> is rather complicated API for the simple thing that it is. And after all I think that this is a common problem. So I just built a simple utility method that makes <code>ManagedBlocker</code>s easy to use for the common case:</p> <pre class="lang-java prettyprint-override"><code>public class BlockingTasks { public static&lt;T&gt; T callInManagedBlock(final Supplier&lt;T&gt; supplier) { final SupplierManagedBlock&lt;T&gt; managedBlock = new SupplierManagedBlock&lt;&gt;(supplier); try { ForkJoinPool.managedBlock(managedBlock); } catch (InterruptedException e) { throw new Error(e); } return managedBlock.getResult(); } private static class SupplierManagedBlock&lt;T&gt; implements ForkJoinPool.ManagedBlocker { private final Supplier&lt;T&gt; supplier; private T result; private boolean done = false; private SupplierManagedBlock(final Supplier&lt;T&gt; supplier) { this.supplier = supplier; } @Override public boolean block() { result = supplier.get(); done = true; return true; } @Override public boolean isReleasable() { return done; } public T getResult() { return result; } } } </code></pre> <p>Now if I want to download the html code of a couple of websites in paralell I could to it like this without the I/O causing any trouble:</p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) { final List&lt;String&gt; pagesHtml = Stream .of("https://google.com", "https://stackoverflow.com", "...") .map((url) -&gt; BlockingTasks.callInManagedBlock(() -&gt; download(url))) .collect(Collectors.toList()); } </code></pre> <p>I am a little bit surprised that there is no class like the <code>BlockingTasks</code> above shipped with Java (or I did not find it?), but it was not that hard to build.</p> <p>When I google for "java 8 parallel stream" I get in the first four results those articles that claim that due to the I/O problem Fork/Join sucks in Java:</p> <ul> <li><a href="https://dzone.com/articles/think-twice-using-java-8" rel="noreferrer">https://dzone.com/articles/think-twice-using-java-8</a></li> <li><a href="http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/" rel="noreferrer">http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/</a> (at least mentions <code>ManagedBlocker</code> but also says "in a <strong>different</strong> use case you’d be able to give it a ManagedBlocker instance". It does not mention why not in this case.</li> </ul> <p>I have altered my search terms somewhat and while there a lot of people complaining about how horrible life is I found nobody talking about a solution like the above. Since I don't feel like Marvin (brain like a planet) and Java 8 is available for quite a while I suspect that there is something terribly wrong with what I am proposing up there.</p> <p>I banged together a small test:</p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) { System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(LocalTime.now()) + ": Start"); IntStream.range(0, 10).parallel().forEach((x) -&gt; sleep()); System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(LocalTime.now()) + ": End"); } public static void sleep() { try { System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(LocalTime.now()) + ": Sleeping " + Thread.currentThread().getName()); Thread.sleep(10000); } catch (InterruptedException e) { throw new Error(e); } } </code></pre> <p>I ran that an got the following result:</p> <pre><code>18:41:29.021: Start 18:41:29.033: Sleeping main 18:41:29.034: Sleeping ForkJoinPool.commonPool-worker-1 18:41:29.034: Sleeping ForkJoinPool.commonPool-worker-2 18:41:29.034: Sleeping ForkJoinPool.commonPool-worker-5 18:41:29.034: Sleeping ForkJoinPool.commonPool-worker-4 18:41:29.035: Sleeping ForkJoinPool.commonPool-worker-6 18:41:29.035: Sleeping ForkJoinPool.commonPool-worker-3 18:41:29.035: Sleeping ForkJoinPool.commonPool-worker-7 18:41:39.034: Sleeping main 18:41:39.034: Sleeping ForkJoinPool.commonPool-worker-1 18:41:49.035: End </code></pre> <p>So on my 8 CPU computer the <code>ForkJoinPool</code> naturally choose 8 threads, completed the first 8 tasks and finally the last two tasks which means that this took 20 seconds and if there were other tasks queued the pool could still have not used the clearly idle CPUs (except for 6 cores in the last 10 seconds).</p> <p>Then I used...</p> <pre><code>IntStream.range(0, 10).parallel().forEach((x) -&gt; callInManagedBlock(() -&gt; { sleep(); return null; })); </code></pre> <p>...instead of...</p> <pre><code>IntStream.range(0, 10).parallel().forEach((x) -&gt; sleep()); </code></pre> <p>...and got the following result:</p> <pre><code>18:44:10.93: Start 18:44:10.945: Sleeping main 18:44:10.953: Sleeping ForkJoinPool.commonPool-worker-7 18:44:10.953: Sleeping ForkJoinPool.commonPool-worker-1 18:44:10.953: Sleeping ForkJoinPool.commonPool-worker-6 18:44:10.953: Sleeping ForkJoinPool.commonPool-worker-3 18:44:10.955: Sleeping ForkJoinPool.commonPool-worker-2 18:44:10.956: Sleeping ForkJoinPool.commonPool-worker-4 18:44:10.956: Sleeping ForkJoinPool.commonPool-worker-5 18:44:10.956: Sleeping ForkJoinPool.commonPool-worker-0 18:44:10.956: Sleeping ForkJoinPool.commonPool-worker-11 18:44:20.957: End </code></pre> <p>It looks to me like this works, extra threads were started to compensate my mock "blocking I/O action" (sleep). Time was cut down to 10 seconds and I suppose that if I'd queue more tasks that those could still use the available CPU power.</p> <p><strong>Is there anything wrong with this solution or in general using I/O in streams if the I/O operation is wrapped in a <code>ManagedBlock</code>?</strong></p>
37,518,272
1
0
null
2016-05-29 17:06:45.08 UTC
10
2016-05-30 05:37:44.47 UTC
2017-05-23 11:58:47.887 UTC
null
-1
null
327,301
null
1
28
java|java-stream
3,279
<p>In short, yes, there are some problems with your solution. It definitely improves using blocking code inside parallel stream, and some third-party libraries provide similar solution (see, for example, <a href="http://www.jooq.org/products/jOO%CE%BB/javadoc/0.9.11/org/jooq/lambda/Blocking.html" rel="noreferrer"><code>Blocking</code></a> class in jOOλ library). However this solution does not change the internal splitting strategy used in Stream API. The number of subtasks created by Stream API is controlled by the predefined constant in <code>AbstractTask</code> class:</p> <pre><code>/** * Default target factor of leaf tasks for parallel decomposition. * To allow load balancing, we over-partition, currently to approximately * four tasks per processor, which enables others to help out * if leaf tasks are uneven or some processors are otherwise busy. */ static final int LEAF_TARGET = ForkJoinPool.getCommonPoolParallelism() &lt;&lt; 2; </code></pre> <p>As you can see it's four times bigger than common pool parallelism (which is by default number of CPU cores). The real splitting algorithm is a little bit more tricky, but roughly you cannot have more than 4x-8x tasks even if all of them are blocking.</p> <p>For example, if you have 8 CPU cores, your <code>Thread.sleep()</code> test will work nicely up to <code>IntStream.range(0, 32)</code> (as 32 = 8*4). However for <code>IntStream.range(0, 64)</code> you will have 32 parallel tasks each processing two input numbers, so the whole processing would take 20 seconds, not 10.</p>
49,050,799
What does 'pending' test mean in Mocha, and how can I make it pass/fail?
<p>I am running my tests and noticed:</p> <pre><code>18 passing (150ms) 1 pending </code></pre> <p>I haven't seen this before. Previously test either passed, or failed. Timeouts caused failures. I can see which test is failing because it's also blue. But it has a timeout on it. Here's a simplified version:</p> <pre><code>test(`Errors when bad thing happens`), function(){ try { var actual = doThing(option) } catch (err) { assert(err.message.includes('invalid')) } throw new Error(`Expected an error and didn't get one!`) } </code></pre> <ul> <li>What does 'pending' mean? <strong>How could a test be 'pending' when Mocha has exited and node is no longer running?</strong></li> <li>Why is this test not timing out?</li> <li>How can I make the test pass or fail?</li> </ul> <p>Thanks!</p>
49,051,847
4
0
null
2018-03-01 13:31:50.817 UTC
4
2019-05-07 07:59:02.923 UTC
2018-03-01 14:26:18.643 UTC
null
123,671
null
123,671
null
1
30
javascript|unit-testing|mocha.js
14,782
<p>The test <a href="https://mochajs.org/#pending-tests" rel="nofollow noreferrer">had a callback</a> (ie, an actual function, not done) but refactoring the code solved the issue. The issue was how code that expects error should run:</p> <pre><code>test('Errors when bad thing happens', function() { var gotExpectedError = false; try { var actual = doThing(option) } catch (err) { if ( err.message.includes('Invalid') ) { gotExpectedError = true } } if ( ! gotExpectedError ) { throw new Error(`Expected an error and didn't get one!`) } }); </code></pre>
2,611,747
Rails Resque workers fail with PGError: server closed the connection unexpectedly
<p>I have site running rails application and resque workers running in production mode, on Ubuntu 9.10, Rails 2.3.4, ruby-ee 2010.01, PostgreSQL 8.4.2</p> <p>Workers constantly raised errors: PGError: server closed the connection unexpectedly.</p> <p>My best guess is that master resque process establishes connection to db (e.g. authlogic does that when use User.acts_as_authentic), while loading rails app classes, and that connection becomes corrupted in fork()ed process (on exit?), so next forked children get kind of broken global ActiveRecord::Base.connection</p> <p>I could reproduce very similar behaviour with this <a href="http://pastie.org/911921" rel="noreferrer">sample code</a> imitating fork/processing in resque worker. (AFAIK, users of libpq recommended to recreate connections in forked process anyway, otherwise it's not safe )</p> <p>But, the odd thing is that when I use pgbouncer or pgpool-II instead of direct pgsql connection, such errors do not appear. </p> <p>So, the question is where and how should I dig to find out why it is broken for plain connection and is working with connection pools? Or reasonable workaround?</p>
2,612,210
5
0
null
2010-04-10 00:27:45.943 UTC
14
2013-09-02 22:20:42.71 UTC
null
null
null
null
313,262
null
1
20
ruby-on-rails|ruby|postgresql|activerecord|resque
7,345
<p>When I created <a href="http://github.com/francois/nestor" rel="nofollow noreferrer">Nestor</a>, I had the same kind of problem. The solution was to re-establish the connection in the forked process. See the relevant code at <a href="http://github.com/francois/nestor/blob/master/lib/nestor/mappers/rails/test/unit.rb#L162" rel="nofollow noreferrer">http://github.com/francois/nestor/blob/master/lib/nestor/mappers/rails/test/unit.rb#L162</a></p> <p>From my <em>very</em> limited look at Resque code, I believe a call to #establish_connection should be done right about here: <a href="https://github.com/resque/resque/blob/master/lib/resque/worker.rb#L123" rel="nofollow noreferrer">https://github.com/resque/resque/blob/master/lib/resque/worker.rb#L123</a></p>
3,162,551
How do I mock static methods in a class with easymock?
<p>Suppose I have a class like so:</p> <pre><code>public class StaticDude{ public static Object getGroove() { // ... some complex logic which returns an object }; } </code></pre> <p>How do I mock the static method call using easy mock? <code>StaticDude.getGroove()</code>.</p> <p>I am using easy mock 3.0</p>
3,162,598
5
0
null
2010-07-02 00:27:00.703 UTC
7
2017-02-16 14:15:41.387 UTC
2010-07-17 20:43:40.927 UTC
null
70,604
null
99,033
null
1
34
java|unit-testing|static|tdd|easymock
75,723
<p>Not sure how to with pure EasyMock, but consider using the <a href="https://github.com/jayway/powermock" rel="noreferrer">PowerMock</a> extensions to EasyMock.</p> <p>It has a lot of cool functions for doing just what you need - <a href="https://github.com/jayway/powermock/wiki/MockStatic" rel="noreferrer">https://github.com/jayway/powermock/wiki/MockStatic</a></p>
2,835,627
php is_function() to determine if a variable is a function
<p>I was pretty excited to read about <a href="http://php.net/manual/en/functions.anonymous.php" rel="noreferrer">anonymous functions</a> in php, which let you declare a variable that is function easier than you could do with <a href="http://us2.php.net/manual/en/function.create-function.php" rel="noreferrer">create_function</a>. Now I am wondering if I have a function that is passed a variable, how can I check it to determine if it is a function? There is no is_function() function yet, and when I do a var_dump of a variable that is a function::</p> <pre><code>$func = function(){ echo 'asdf'; }; var_dump($func); </code></pre> <p>I get this:</p> <pre><code>object(Closure)#8 (0) { } </code></pre> <p>Any thoughts on how to check if this is a function? </p>
2,835,660
5
0
null
2010-05-14 16:03:44.033 UTC
12
2020-02-27 03:56:49.613 UTC
null
null
null
null
88,310
null
1
95
php|anonymous-function
47,715
<p>Use <a href="http://php.net/manual/en/function.is-callable.php" rel="noreferrer"><code>is_callable</code></a> to determine whether a given variable is a function. For example:</p> <pre><code>$func = function() { echo 'asdf'; }; if( is_callable( $func ) ) { // Will be true. } </code></pre>
2,458,723
C Macro for minimum of two numbers
<p>I want to make a simple macro with #define for returning the smaller of two numbers.</p> <p>How can i do this in C ? Suggest some ideas, and see if you can make it more obfuscated too. </p>
2,458,899
7
1
null
2010-03-16 22:51:39.72 UTC
null
2017-09-19 18:23:48.617 UTC
2015-03-31 02:12:20.9 UTC
null
1,257,035
null
281,619
null
1
5
c|c-preprocessor|minimum
42,696
<p>For slightly obfuscated, try this:</p> <pre><code>#define MIN(a,b) ((((a)-(b))&amp;0x80000000) &gt;&gt; 31)? (a) : (b) </code></pre> <p>Basically, it subtracts them, and looks at the sign-bit as a 1-or-0. If the subtraction results in a negative number, the first parameter is smaller.</p>
3,000,209
Service reference not generating client types
<p>I am trying to consume a WCF service in a class library by adding a service reference to it. In one of the class libraries it gets consumed properly and I can access the client types in order to generate a proxy off of them. However in my second class library (or even in a console test app), when i add the same service reference, it only exposes the types that are involved in the contract operations and not the client type for me to generate a proxy against. </p> <p>e.g. Endpoint has 2 services exposed - ISvc1 and ISvc2. When I add a service reference to this endpoint in the first class library I get ISvc1Client andf ISvc2Client to generate proxies off of in order to use the operations exposed via those 2 contracts. In addition to these clients the service reference also exposes the types involved in the operations like (type 1, type 2 etc.) this is what I need. However when i try to add a service reference to the same endpoing in another console application or class library only Type 1, Type 2 etc. are exposed and not ISvc1Client and ISvc2Client because of which I cannot generate a proxy to access the operations I need. I am unable to determine why the service reference gets properly generated in one class library but not in the other or the test console app.</p>
3,000,363
7
1
null
2010-06-08 18:35:54.893 UTC
3
2017-11-20 10:52:05.44 UTC
null
null
null
null
313,197
null
1
31
.net|wcf|service|reference
33,368
<p>Apparently you have to add a reference to System.Web in your project before adding the Service Reference. That did it. </p>