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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21,099,386 | How do I remove settings icon (overflow menu) on top-right of action bar? | <p>How do I remove the settings icon from the top-right of the action bar? When I emulate on my actual Samsung galaxy s3 phone, it is not there, however, when I emulate on an AVD for the Nexus 7, it appears. Here is the code for my menu:</p>
<pre class="lang-xml prettyprint-override"><code><menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/main_menu_actionbutton"
android:orderInCategory="100"
android:showAsAction="always"
android:title="@string/Menu"/>
</menu>
</code></pre> | 21,099,479 | 3 | 1 | null | 2014-01-13 19:10:52.88 UTC | 5 | 2018-03-02 14:28:38.883 UTC | 2018-03-02 14:28:38.883 UTC | null | 3,183,924 | null | 3,183,924 | null | 1 | 27 | java|android|android-actionbar | 38,758 | <p>If you mean the three dots, that's called the overflow menu. It exists on devices which do not have a hardware menu button - which your Galaxy S3 has, while the Nexus 7 does not. So on your S3 you press the menu button and get the popup at the bottom, but on the Nexus you press the 3 dots and get the overflow popup dropping down from the action bar. If it wasn't there, how would you be able to access overflow items?</p>
<p>If you'd simply like to remove it altogether, just delete the first <code><item /></code> entry in the <code>menu.xml</code> you posted.</p> |
35,530,640 | Pandas Use Value if Not Null, Else Use Value From Next Column | <p>Given the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'COL1': ['A', np.nan,'A'],
'COL2' : [np.nan,'A','A']})
df
COL1 COL2
0 A NaN
1 NaN A
2 A A
</code></pre>
<p>I would like to create a column ('COL3') that uses the value from COL1 per row unless that value is null (or NaN). If the value is null (or NaN), I'd like for it to use the value from COL2.</p>
<p>The desired result is:</p>
<pre><code> COL1 COL2 COL3
0 A NaN A
1 NaN A A
2 A A A
</code></pre>
<p>Thanks in advance!</p> | 35,530,670 | 5 | 1 | null | 2016-02-21 00:05:42.723 UTC | 9 | 2022-07-08 07:33:56.463 UTC | null | null | null | null | 4,392,566 | null | 1 | 42 | python-3.x|pandas | 49,967 | <pre><code>In [8]: df
Out[8]:
COL1 COL2
0 A NaN
1 NaN B
2 A B
In [9]: df["COL3"] = df["COL1"].fillna(df["COL2"])
In [10]: df
Out[10]:
COL1 COL2 COL3
0 A NaN A
1 NaN B B
2 A B A
</code></pre> |
18,876,078 | List all the databases on one SQL Server in the order they were created | <p>I have probably in excess of 100 databases on this one SQL Server (2005) instance. I'd like to list them in order of their create dates, or even better, in the order of the date of the latest modification to any table.</p>
<p>Is there a SELECT query I can write, and just as importantly, from what context do I write it and with what permissions do I need to execute it?</p> | 18,876,332 | 3 | 0 | null | 2013-09-18 15:14:37.04 UTC | 4 | 2018-12-10 12:22:01.807 UTC | 2018-12-10 12:22:01.807 UTC | null | 1,080,354 | null | 28,939 | null | 1 | 19 | sql|sql-server|tsql|sql-server-2005 | 46,762 | <p>You can easily write this query against the <code>sys.databases</code> catalog view</p>
<pre><code>SELECT * FROM sys.databases
ORDER BY create_date
</code></pre>
<p>but unfortunately, there's no equivalent for the "last modification date" that I'm aware of ...</p>
<p>This should work from any database on that server - doesn't matter which database you're in, those <code>sys</code> catalog views should be accessible from anywhere.</p> |
46,846,128 | EditorConfig for VS Code not working | <p>I use VS Code as editor. We have a <code>.editorconfig</code> file with format configs within. We all use in our editors the extenion EditorConfig to format our HTML and CSS general. I have installed the extension EditorConfig for VS Code from here: <a href="https://github.com/editorconfig/editorconfig-vscode" rel="noreferrer">https://github.com/editorconfig/editorconfig-vscode</a></p>
<p>Our .editorconfig file looks like this:</p>
<pre><code># This is the top-most .editorconfig file (do not search in parent directories)
root = true
### All files
[*]
# Force charset utf-8
charset = utf-8
# Indentation
indent_style = tab
indent_size = 4
# line breaks and whitespace
insert_final_newline = true
trim_trailing_whitespace = true
# end_of_line = lf
### Frontend files
[*.{css,scss,less,js,json,ts,sass,php,html,hbs,mustache,phtml,html.twig}]
### Markdown
[*.md]
indent_style = space
indent_size = 4
trim_trailing_whitespace = false
### YAML
[*.yml]
indent_style = space
indent_size = 2
### Specific files
[{package,bower}.json]
indent_style = space
indent_size = 2
</code></pre>
<p>I can't find any keyboard shortcut, setting or else. How to get my extension do the stuff from the <code>.editorconfig</code> file?</p> | 48,523,398 | 3 | 1 | null | 2017-10-20 09:25:48.747 UTC | 5 | 2022-09-11 08:29:04.55 UTC | null | null | null | null | 5,466,074 | null | 1 | 56 | html|css|visual-studio-code|editorconfig | 27,717 | <p><strong>MY OWN SOLUTION:</strong></p>
<p>The problem I had was, that I added the extension <code>editorconfig</code> to my <code>vscode</code>, but didn't install the <code>npm package</code> for it. So it's not enough, to add the extension only to your vscode, you have also to install the package, so it could run.</p>
<p>I installed the <code>npm package</code> global like this: <code>npm install -g editorconfig</code></p>
<p>After that I added the extension and enabled it. Now it works perfectly.</p>
<p>Required npm package: <a href="https://www.npmjs.com/package/editorconfig" rel="nofollow noreferrer">https://www.npmjs.com/package/editorconfig</a></p>
<p>Required vscode extension: <a href="https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig" rel="nofollow noreferrer">https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig</a></p> |
46,662,513 | Convert Array to List in Kotlin | <p>I try to do this with (same as java)</p>
<pre><code>val disabledNos = intArrayOf(1, 2, 3, 4)
var integers = Arrays.asList(disabledNos)
</code></pre>
<p>but this doesn't give me a list.
Any ideas?</p> | 46,662,879 | 3 | 1 | null | 2017-10-10 08:55:46.1 UTC | 3 | 2020-05-29 06:51:26.167 UTC | 2019-04-01 09:29:36.083 UTC | null | 6,202,869 | null | 1,729,085 | null | 1 | 44 | kotlin | 36,687 | <p>Kotlin support in the standard library this conversion.</p>
<p>You can use directly</p>
<pre><code>disableNos.toList()
</code></pre>
<p>or if you want to make it mutable:</p>
<pre><code>disableNos.toMutableList()
</code></pre> |
8,438,439 | Html.ValidationMessageFor Text Color | <p>Probably a simple question, but i cant seem to find the answer. </p>
<p>using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.</p>
<pre><code><%= Html.TextBoxFor(Model => Model.Chest, new { @class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>
</code></pre>
<p>if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont work!</p>
<p>thanks </p> | 8,438,577 | 5 | 0 | null | 2011-12-08 22:11:59.963 UTC | 1 | 2021-06-27 14:16:36.923 UTC | 2013-01-22 13:39:34.243 UTC | null | 727,208 | null | 1,080,800 | null | 1 | 14 | c#|css|asp.net-mvc|validation | 43,345 | <p>There's a variant that takes htmlAttributes as the third argument (the second is the message that should be displayed, or you can use null for the default validation message)</p>
<pre><code>Html.ValidationMessageFor(
Model => Model.Chest,
"Please enter a value",
new { @class = "redText" })
</code></pre>
<p>For more info see <a href="http://msdn.microsoft.com/en-us/library/ee721293%28v=vs.98%29.aspx">http://msdn.microsoft.com/en-us/library/ee721293%28v=vs.98%29.aspx</a></p> |
8,704,801 | glVertexAttribPointer clarification | <p>Just want to make sure I understand this correctly (I'd ask on SO Chat, but it's dead in there!):</p>
<p>We've got a Vertex Array, which we make "current" by binding it<br>
then we've got a Buffer, which we bind to a Target<br>
then we fill that Target via <code>glBufferData</code>
which essentially populates whatever was bound to that target, i.e. our Buffer<br>
and then we call <code>glVertexAttribPointer</code> which describes how the data is laid out -- the data being whatever is bound to <code>GL_ARRAY_BUFFER</code>
and this descriptor is saved to our original Vertex Array </p>
<p>(1) Is my understanding correct?<br>
The <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml" rel="noreferrer">documentation</a> is a little sparse about how everything correlates.</p>
<p>(2) Is there some kind of default Vertex Array? Because I forgot/omitted <code>glGenVertexArrays</code> and <code>glBindVertexArray</code> and my program worked fine without it.</p>
<hr>
<p><strong>Edit:</strong> I missed a step... <code>glEnableVertexAttribArray</code>. </p>
<p>(3) Is the Vertex Attrib tied to the Vertex Array at the time <code>glVertexAttribPointer</code> is called, and then we can enable/disable that attrib via <code>glEnableVertexAttribArray</code> at any time, regardless of which Vertex Array is currently bound?</p>
<p>Or (3b) Is the Vertex Attrib tied to the Vertex Array at the time <code>glEnableVertexAttribArray</code> is called, and thus we can add the same Vertex Attrib to multiple Vertex Arrays by calling <code>glEnableVertexAttribArray</code> at different times, when different Vertex Arrays are bound?</p> | 8,705,304 | 2 | 0 | null | 2012-01-02 19:58:06.457 UTC | 73 | 2017-05-12 22:02:56.243 UTC | 2017-05-12 22:02:56.243 UTC | null | 6,214,222 | null | 65,387 | null | 1 | 95 | opengl | 48,502 | <p>Some of the terminology is a bit off:</p>
<ul>
<li>A <code>Vertex Array</code> is just an array (typically a <code>float[]</code>) that contains vertex data. It doesn't need to be bound to anything. Not to be confused with a <code>Vertex Array Object</code> or VAO, which I will go over later</li>
<li>A <code>Buffer Object</code>, commonly referred to as a <code>Vertex Buffer Object</code> when storing vertices, or VBO for short, is what you're calling just a <code>Buffer</code>.</li>
<li>Nothing gets saved back to the vertex array, <code>glVertexAttribPointer</code> works exactly like <code>glVertexPointer</code> or <code>glTexCoordPointer</code> work, just instead of named attributes, you get to provide a number that specifies your own attribute. You pass this value as <code>index</code>. All your <code>glVertexAttribPointer</code> calls get queued up for the next time you call <code>glDrawArrays</code> or <code>glDrawElements</code>. If you have a VAO bound, the VAO will store the settings for all your attributes.</li>
</ul>
<p>The main issue here is that you're confusing vertex attributes with VAOs. Vertex attributes are just the new way of defining vertices, texcoords, normals, etc. for drawing. VAOs store state. I'm first going to explain how drawing works with vertex attributes, then explain how you can cut down the number of method calls with VAOs:</p>
<ol>
<li>You must enable an attribute before you can use it in a shader. For example, if you want to send vertices over to a shader, you're most likely going to send it as the first attribute, 0. So before you render, you need to enable it with <code>glEnableVertexAttribArray(0);</code>.</li>
<li>Now that an attribute is enabled, you need to define the data it's going to use. In order to do so you need to bind your VBO - <code>glBindBuffer(GL_ARRAY_BUFFER, myBuffer);</code>.</li>
<li>And now we can define the attribute - <code>glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);</code>. In order of parameter: 0 is the attribute you're defining, 3 is the size of each vertex, <code>GL_FLOAT</code> is the type, <code>GL_FALSE</code> means to not normalize each vertex, the last 2 zeros mean that there's no stride or offset on the vertices.</li>
<li>Draw something with it - <code>glDrawArrays(GL_TRIANGLES, 0, 6);</code></li>
<li>The next thing you draw may not use attribute 0 (realistically it will, but this is an example), so we can disable it - <code>glDisableVertexAttribArray(0);</code></li>
</ol>
<p>Wrap that in <code>glUseProgram()</code> calls and you have a rendering system that works with shaders properly. But let's say you have 5 different attributes, vertices, texcoords, normals, color, and lightmap coordinates. First of all, you would be making a single <code>glVertexAttribPointer</code> call for each of these attributes, and you'd have to enable all the attributes beforehand. Let's say you define the attributes 0-4 as I have them listed. You would enable all of them like so:</p>
<pre><code>for (int i = 0; i < 5; i++)
glEnableVertexAttribArray(i);
</code></pre>
<p>And then you would have to bind different VBOs for each attribute (unless you store them all in one VBO and use offsets/stride), then you need to make 5 different <code>glVertexAttribPointer</code> calls, from <code>glVertexAttribPointer(0,...);</code> to <code>glVertexAttribPointer(4,...);</code> for vertices to lightmap coordinates respectively.</p>
<p>Hopefully that system alone makes sense. Now I'm going to move on to VAOs to explain how to use them to cut down on the number of method calls when doing this type of rendering. Note that using a VAO is not necessary.</p>
<p>A <code>Vertex Array Object</code> or VAO is used to store the state of all the <code>glVertexAttribPointer</code> calls and the VBOs that were targeted when each of the <code>glVertexAttribPointer</code> calls were made.</p>
<p>You generate one with a call to <code>glGenVertexArrays</code>. To store everything you need in a VAO, bind it with <code>glBindVertexArray</code><strike>, then do a full draw call</strike>. All the <strike>draw</strike> bind calls get intercepted and stored by the VAO. You can unbind the VAO with <code>glBindVertexArray(0);</code></p>
<p>Now when you want to draw the object, you don't need to re-call all the VBO binds or the <code>glVertexAttribPointer</code> calls, you just need to bind the VAO with <code>glBindVertexArray</code> then call <code>glDrawArrays</code> or <code>glDrawElements</code> and you'll be drawing the exact same thing as though you were making all those method calls. You probably want to unbind the VAO afterwards too.</p>
<p>Once you unbind the VAO, all the state returns to how it was before you bound the VAO. I'm not sure if any changes you make while the VAO is bound is kept, but that can easily be figured out with a test program. I guess you can think of <code>glBindVertexArray(0);</code> as binding to the "default" VAO...</p>
<hr>
<p><strong>Update:</strong> Someone brought to my attention the need for the actual draw call. As it turns out, you don't actually need to do a FULL draw call when setting up the VAO, just all the binding stuff. Don't know why I thought it was necessary earlier, but it's fixed now.</p> |
48,402,823 | embed openstreetmap iframe in github markdown | <p>From the share tab on the openstreetmap page, I can export a map view as HTML e.g.:</p>
<pre><code><iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.openstreetmap.org/export/embed.html?bbox=6.047544479370118%2C46.23053702499607%2C6.061706542968751%2C46.23821801159735&amp;layer=mapnik" style="border: 1px solid black"></iframe>
<br/><small><a href="https://www.openstreetmap.org/#map=17/46.23438/6.05463">View Larger Map</a></small>
</code></pre>
<p>I would like to embed this in a README.md page on github e.g.</p>
<p>Searching around, the closest to embedding <code>iframe</code>s in markdown was the <a href="https://about.gitlab.com/handbook/product/technical-writing/markdown-guide/#embed-documents" rel="noreferrer">git<strong>lab</strong> guide</a>. Following which I tried the <code><figure class="video_container"></code> tag, but don't see that working either on gitlab or github.</p>
<pre><code># how to find us?
we will be here:
<figure class="video_container">
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.openstreetmap.org/export/embed.html?bbox=6.047544479370118%2C46.23053702499607%2C6.061706542968751%2C46.23821801159735&amp;layer=mapnik" style="border: 1px solid black"></iframe>
</figure>
</code></pre>
<p>Am I missing something, or is this something better left to real HTML and beyond what markdown can/should do?</p> | 54,613,247 | 1 | 1 | null | 2018-01-23 13:23:16.983 UTC | 4 | 2019-02-14 06:58:50.123 UTC | null | null | null | null | 4,588,453 | null | 1 | 30 | iframe|openstreetmap|github-flavored-markdown | 22,303 | <h2>Not supported in GFM</h2>
<p>Embedding an <code><iframe></code> into GitHub-flavored Markdown (GFM) is <strong>not supported</strong>. Here's the official stance on it <a href="https://github.github.com/gfm/#example-630" rel="noreferrer">from their specs</a>:</p>
<blockquote>
<p><strong>6.11 Disallowed Raw HTML (extension)</strong></p>
<p>GFM enables the tagfilter extension, where <strong>the following HTML tags will be filtered</strong> when rendering HTML output:</p>
<p><code><title></code>
<code><textarea></code>
<code><style></code>
<code><xmp></code>
<strong><code><iframe></code></strong>
<code><noembed></code>
<code><noframes></code>
<code><script></code>
<code><plaintext></code></p>
<p>[...] These tags are chosen in particular as they change how HTML is interpreted in a way unique to them [...], and this is usually undesireable in the context of other rendered Markdown content.</p>
<p>All other HTML tags are left untouched.</p>
</blockquote>
<hr />
<h2>Possible Work-around</h2>
<p>Similar to solutions mentioned for videos in <a href="https://stackoverflow.com/a/14945782/5717580">other answers</a>, you could <strong>embed a screenshot</strong> of your map, and <strong>make it a link</strong> to the URL of your OSM map section:</p>
<p><a href="https://www.openstreetmap.org/#map=14/21.0544/105.8194" rel="noreferrer"><img src="https://i.stack.imgur.com/EAN8o.png" alt="detail of map section of Hanoi, Vietnam" /></a></p> |
54,245,618 | Unexpected behaviour with a conditional generator expression | <p>I was running a piece of code that unexpectedly gave a logic error at one part of the program. When investigating the section, I created a test file to test the set of statements being run and found out an unusual bug that seems very odd.</p>
<p>I tested this simple code:</p>
<pre><code>array = [1, 2, 2, 4, 5] # Original array
f = (x for x in array if array.count(x) == 2) # Filters original
array = [5, 6, 1, 2, 9] # Updates original to something else
print(list(f)) # Outputs filtered
</code></pre>
<p>And the output was:</p>
<pre><code>>>> []
</code></pre>
<p>Yes, nothing. I was expecting the filter comprehension to get items in the array with a count of 2 and output this, but I didn't get that:</p>
<pre><code># Expected output
>>> [2, 2]
</code></pre>
<p>When I commented out the third line to test it once again:</p>
<pre><code>array = [1, 2, 2, 4, 5] # Original array
f = (x for x in array if array.count(x) == 2) # Filters original
### array = [5, 6, 1, 2, 9] # Ignore line
print(list(f)) # Outputs filtered
</code></pre>
<p>The output was correct (you can test it for yourself):</p>
<pre><code>>>> [2, 2]
</code></pre>
<p>At one point I outputted the type of the variable <code>f</code>:</p>
<pre><code>array = [1, 2, 2, 4, 5] # Original array
f = (x for x in array if array.count(x) == 2) # Filters original
array = [5, 6, 1, 2, 9] # Updates original
print(type(f))
print(list(f)) # Outputs filtered
</code></pre>
<p>And I got:</p>
<pre><code>>>> <class 'generator'>
>>> []
</code></pre>
<p>Why is updating a list in Python changing the output of another generator variable? This seems very odd to me.</p> | 54,249,614 | 8 | 3 | null | 2019-01-17 23:11:04.25 UTC | 13 | 2019-02-04 17:42:22.793 UTC | 2019-02-04 17:42:22.793 UTC | null | 100,297 | null | 5,428,880 | null | 1 | 60 | python|generator|variable-assignment|generator-expression | 4,024 | <p>Python's generator expressions are late binding (see <a href="https://www.python.org/dev/peps/pep-0289/" rel="noreferrer">PEP 289 -- Generator Expressions</a>) (what the other answers call "lazy"):</p>
<blockquote>
<h2>Early Binding versus Late Binding</h2>
<p>After much discussion, it was decided that the first (outermost) for-expression [of the generator expression] should be evaluated immediately and that the remaining expressions be evaluated when the generator is executed.</p>
<p>[...] Python takes a late binding approach to lambda expressions and has no precedent for automatic, early binding. It was felt that introducing a new paradigm would unnecessarily introduce complexity.</p>
<p>After exploring many possibilities, a consensus emerged that binding issues were hard to understand and that users should be strongly encouraged to use generator expressions inside functions that consume their arguments immediately. For more complex applications, full generator definitions are always superior in terms of being obvious about scope, lifetime, and binding.</p>
</blockquote>
<p>That means it <strong>only</strong> evaluates the outermost <code>for</code> when creating the generator expression. So it actually <strong>binds</strong> the value with the name <code>array</code> in the "subexpression" <code>in array</code> (in fact it's binding the equivalent to <code>iter(array)</code> at this point). But when you iterate over the generator the <code>if array.count</code> call actually refers to what is currently named <code>array</code>.</p>
<hr />
<p>Since it's actually a <code>list</code> not an <code>array</code> I changed the variable names in the rest of the answer to be more accurate.</p>
<p>In your first case the <code>list</code> you iterate over and the <code>list</code> you count in will be different. It's as if you used:</p>
<pre><code>list1 = [1, 2, 2, 4, 5]
list2 = [5, 6, 1, 2, 9]
f = (x for x in list1 if list2.count(x) == 2)
</code></pre>
<p>So you check for each element in <code>list1</code> if its count in <code>list2</code> is two.</p>
<p>You can easily verify this by modifying the second list:</p>
<pre><code>>>> lst = [1, 2, 2]
>>> f = (x for x in lst if lst.count(x) == 2)
>>> lst = [1, 1, 2]
>>> list(f)
[1]
</code></pre>
<p>If it iterated over the first list and counted in the first list it would've returned <code>[2, 2]</code> (because the first list contains two <code>2</code>). If it iterated over and counted in the second list the output should be <code>[1, 1]</code>. But since it iterates over the first list (containing one <code>1</code>) but checks the second list (which contains two <code>1</code>s) the output is just a single <code>1</code>.</p>
<h2>Solution using a generator function</h2>
<p>There are several possible solutions, I generally prefer not to use "generator expressions" if they aren't iterated over immediately. A simple generator function will suffice to make it work correctly:</p>
<pre><code>def keep_only_duplicated_items(lst):
for item in lst:
if lst.count(item) == 2:
yield item
</code></pre>
<p>And then use it like this:</p>
<pre><code>lst = [1, 2, 2, 4, 5]
f = keep_only_duplicated_items(lst)
lst = [5, 6, 1, 2, 9]
>>> list(f)
[2, 2]
</code></pre>
<p>Note that the PEP (see the link above) also states that for anything more complicated a full generator definition is preferrable.</p>
<h2>A better solution using a generator function with a Counter</h2>
<p>A better solution (avoiding the quadratic runtime behavior because you iterate over the whole array for each element in the array) would be to count (<a href="https://docs.python.org/library/collections.html#collections.Counter" rel="noreferrer"><code>collections.Counter</code></a>) the elements once and then do the lookup in constant time (resulting in linear time):</p>
<pre><code>from collections import Counter
def keep_only_duplicated_items(lst):
cnts = Counter(lst)
for item in lst:
if cnts[item] == 2:
yield item
</code></pre>
<h2>Appendix: Using a subclass to "visualize" what happens and when it happens</h2>
<p>It's quite easy to create a <code>list</code> subclass that prints when specific methods are called, so one can verify that it really works like that.</p>
<p>In this case I just override the methods <code>__iter__</code> and <code>count</code> because I'm interested over which list the generator expression iterates and in which list it counts. The method bodies actually just delegate to the superclass and print something (since it uses <code>super</code> without arguments and f-strings it requires Python 3.6 but it should be easy to adapt for other Python versions):</p>
<pre><code>class MyList(list):
def __iter__(self):
print(f'__iter__() called on {self!r}')
return super().__iter__()
def count(self, item):
cnt = super().count(item)
print(f'count({item!r}) called on {self!r}, result: {cnt}')
return cnt
</code></pre>
<p>This is a simple subclass just printing when the <code>__iter__</code> and <code>count</code> method are called:</p>
<pre><code>>>> lst = MyList([1, 2, 2, 4, 5])
>>> f = (x for x in lst if lst.count(x) == 2)
__iter__() called on [1, 2, 2, 4, 5]
>>> lst = MyList([5, 6, 1, 2, 9])
>>> print(list(f))
count(1) called on [5, 6, 1, 2, 9], result: 1
count(2) called on [5, 6, 1, 2, 9], result: 1
count(2) called on [5, 6, 1, 2, 9], result: 1
count(4) called on [5, 6, 1, 2, 9], result: 0
count(5) called on [5, 6, 1, 2, 9], result: 1
[]
</code></pre> |
26,645,795 | Visual Studio settings: How to set vertical split view to default | <p>I am working with C#(WPF) and when I open <code>XAML</code> file it splits to <code>Vertical</code> every time, I'm changing to <code>Horizontal</code>, but when I reopen again it still <code>Vertical</code>, is it possible to set default to <code>Horizontal</code> view.<br/>
Examples:<br/>
First is Vertical view<br/>
Second is Horizontal view<br/></p>
<p><img src="https://i.stack.imgur.com/IZh33.png" alt="Vertical view" /></p>
<p><img src="https://i.stack.imgur.com/gJ2vi.png" alt="Horizontal view" /></p> | 34,522,476 | 2 | 0 | null | 2014-10-30 05:36:27.033 UTC | 2 | 2021-06-08 07:42:06.52 UTC | 2021-06-08 07:42:06.52 UTC | null | 2,077,676 | null | 2,077,676 | null | 1 | 29 | c#|wpf|visual-studio|xaml | 6,866 | <p>This is late answer, since this feature is available on <code>Visual Studio 2015</code>. For setting the <code>Xaml</code> code view to <code>Vertical</code> or <code>Horizontal</code> you can see steps below:
<a href="https://i.stack.imgur.com/DVOdP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DVOdP.png" alt="Picture"></a></p> |
30,625,380 | find in MongoCollection<Document> | <p>I have a <code>MongoCollection<Document></code> in which I assign a collection.
I'm trying to find a user by his id.</p>
<pre><code>user = (Document) usersCollection.find(new Document("_id", username));
</code></pre>
<p>with that I'm getting an error </p>
<blockquote>
<p>java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be
cast to org.bson.Document</p>
</blockquote>
<p>When I try </p>
<pre><code> BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("_id", username);
usersCollection.find(query, fields);
</code></pre>
<p>I'm getting an error </p>
<blockquote>
<p>The method find(Bson, Class) in the type MongoCollection is not applicable for the arguments (BasicDBObject, BasicDBObject)</p>
</blockquote> | 30,625,638 | 5 | 0 | null | 2015-06-03 16:11:01.547 UTC | null | 2020-11-11 15:40:27.953 UTC | null | null | null | null | 1,693,990 | null | 1 | 12 | java|mongodb | 41,133 | <p>Try to create a filter to pass to the <a href="http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/" rel="nofollow noreferrer"><strong><code>find()</code></strong></a> method to get a subset of the documents in your collection. For example, to find the document for which the value of the <code>_id</code> field is <code>test</code>, you would do the following:</p>
<pre><code>import static com.mongodb.client.model.Filters.*;
MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycoll");
Document myDoc = collection.find(eq("_id", "test")).first();
System.out.println(myDoc.toJson());
</code></pre> |
43,806,643 | How can I calculate an entire workbook, but not all open workbooks? | <p>Is there a way to calculate entire workbook but not all open workbooks in VBA?</p>
<p>I know about</p>
<pre><code>worksheet.Calculate
</code></pre>
<p>but it will only do 1 sheet. I also know about</p>
<pre><code>Application.CalculateFull
</code></pre>
<p>But I think this recalculate all open workbooks at the same time.</p>
<p>Is it possible to do only 1 workbook?</p>
<p><strong>Edit:</strong>
I get the approach:</p>
<pre><code>For Each wks In ActiveWorkbook.Worksheets
wks.Calculate
Next
</code></pre>
<p>but this is very dangerous if sheets have links between them, then the order of calculation is important. I know I could find the exact sequence and apply it, problem is that on very large workbooks this can get somewhat tricky</p> | 43,811,323 | 8 | 0 | null | 2017-05-05 13:45:15.94 UTC | 2 | 2020-08-11 10:42:28.073 UTC | 2019-04-01 16:14:28.883 UTC | null | 2,756,409 | null | 5,626,112 | null | 1 | 13 | excel|vba | 50,818 | <p>After some investigation and testing, selecting all sheets first and calculating afterward works :</p>
<pre><code>Application.Calculation = xlManual
ThisWorkbook.Sheets.Select
ActiveSheet.Calculate
</code></pre>
<p>this calculate all selected sheet at the same time creating the right order of calculation</p> |
990,817 | Are ints always initialized to 0? | <p>Is it safe to count on <code>int</code>s always being initialized to 0 in Objective-C?</p>
<p>More specifically, when an object with <code>int</code> ivars has been newly instantiated, is it safe to assume that its ivars have value 0?</p> | 990,826 | 3 | 0 | null | 2009-06-13 14:58:09.927 UTC | 17 | 2013-10-28 02:50:16.69 UTC | 2013-01-08 06:49:29.207 UTC | null | 603,977 | null | 96,531 | null | 1 | 76 | objective-c|initialization|int|instance-variables | 23,496 | <p>Yes, class instance variables are always initialized to 0 (or <code>nil</code>, <code>NULL</code>, or <code>false</code>, depending on the exact data type). See the <a href="http://web.archive.org/web/20111006112529/http://developer.apple.com/library/mac/#/web/20111006132944/http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW1" rel="noreferrer">Objective-C 2.0 Programming Language</a>:</p>
<blockquote>
<p>The <code>alloc</code> method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the <code>isa</code> variable that connects the new instance to its class.</p>
</blockquote>
<hr>
<p><strong>EDIT 2013-05-08</strong><br>
Apple seems to have removed the above document (now linked to The Wayback Machine). The (currently) active document <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html" rel="noreferrer">Programming With Objective-C</a> contains a similar citation:</p>
<blockquote>
<p>The <code>alloc</code> method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.</p>
</blockquote>
<hr>
<p>However, this is <em>only</em> true for instance variables of a class; it is also true for POD types declared at global scope:</p>
<pre><code>// At global scope
int a_global_var; // guaranteed to be 0
NSString *a_global_string; // guaranteed to be nil
</code></pre>
<p>With one exception, it is <em>not</em> true for local variables, or for data allocated with <code>malloc()</code> or <code>realloc()</code>; it is true for <code>calloc()</code>, since <code>calloc()</code> explicitly zeros out the memory it allocates.</p>
<p>The one exception is that when Automatic Reference Counting (ARC) is enabled, stack pointers to Objective-C objects are implicitly initialized to <code>nil</code>; however, it's still good practice to explicitly initialize them to <code>nil</code>. From the <a href="https://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW5" rel="noreferrer">Transitioning to to ARC Release Notes</a>:</p>
<blockquote>
<p>Stack Variables Are Initialized with <code>nil</code></p>
<p>Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with <code>nil</code></p>
</blockquote>
<p>In C++ (and C++ objects being used in Objective-C++), class instance variables are also <em>not</em> zero-initialized. You must explicitly initialize them in your constructor(s).</p> |
6,606,725 | Best way to integrate SqlAlchemy into a Django project | <p>I changed my Django application to use SQLAlchemy, and it works now.</p>
<p>But I'm wondering where I should put these lines:</p>
<pre><code>engine = sqlalchemy.create_engine(settings.DATABASE_URL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()
</code></pre>
<p>The reason I'm asking is because I want to use SQLAlchemy at many place, and I don't think its correct/powerful/well-written to call this three lines everytime I need to use the database.</p>
<p>The place I will require SA is :</p>
<ul>
<li>In my views, of course</li>
<li>In some middleware I wrote</li>
<li>In my models. Like in <code>get_all_tags</code> for a BlogPost Model.</li>
</ul>
<p>What I think would be correct, is to get the session, by re-connecting to the database if the session is closed, or just returning the current, connected session if exists.</p>
<p>How can I use SQLAlchemy correctly with my Django apps?</p>
<p>Thanks for your help!</p>
<p>Note: I already followed this tutorial to implement SA into my Django application, but this one doesn't tell me exactly where to put those 3 lines (<a href="http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/" rel="noreferrer">http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/</a>).</p> | 6,607,461 | 1 | 19 | null | 2011-07-07 06:32:19.813 UTC | 16 | 2013-07-02 14:33:50.3 UTC | null | null | null | null | 330,867 | null | 1 | 17 | python|django|sqlalchemy | 13,643 | <p>for the first two, <code>engine</code> and <code>Session</code>, you can put them in <code>settings.py</code>; they are, configuration, after all. </p>
<p>Actually creating a session requires slightly more care, since a <code>session</code> is essentially a 'transaction'. The simplest thing to do is to create it in each view function when needed, and commit them just before returning. If you'd like a little bit more magic than that, or if you want/need to use the session outside of the view function, you should instead define some <a href="https://docs.djangoproject.com/en/1.3/topics/http/middleware/#writing-your-own-middleware" rel="noreferrer">middleware</a>, something like</p>
<pre><code>class MySQLAlchemySessionMiddleware(object):
def process_request(self, request):
request.db_session = settings.Session()
def process_response(self, request, response):
try:
session = request.db_session
except AttributeError:
return response
try:
session.commit()
return response
except:
session.rollback()
raise
def process_exception(self, request, exception):
try:
session = request.db_session
except AttributeError:
return
session.rollback()
</code></pre>
<p>Then, every view will have a <code>db_session</code> attribute in their requests, which they can use as they see fit, and anything that was added will get commited when the response is finished.</p>
<p>Don't forget to add the middleware to <code>MIDDLEWARE_CLASSES</code></p> |
35,183,052 | Convert card numbers to XXXX-XXXX-XXXX-0000 Format | <p>I have a 16 character string that comes through something like this:</p>
<pre><code>1234567891234567
</code></pre>
<p>I need to be able to format the string as it would appear in a system i.e</p>
<pre><code>XXXX-XXXX-XXXX-4567
</code></pre>
<p><strong>NOTE</strong> that the 4567 digits shown above relate to the last four digits of the card number.</p>
<p><a href="https://stackoverflow.com/questions/4128263/format-a-social-security-number-ssn-as-xxx-xx-xxxx-from-xxxxxxxxx">This</a> question helps format the string to something like <code>1234-5678-9123-4567</code></p>
<p>But it does not help with the format required above. </p>
<p>While looking for answers I also came across the following solution:</p>
<pre><code> string[] subStrings = Enumerable.Range(0, 4).Select(n => cardNumber.Substring(n * 4, 4)).ToArray();
string result = String.Format("{0}-{1}-{2}-{3}", subStrings);
</code></pre>
<p>but again this will only output the string as something like <code>1234-5678-9123-4567</code></p>
<p>I seem to have reached part of the solution, but cant format the rest.</p> | 35,183,108 | 4 | 2 | null | 2016-02-03 16:54:13.747 UTC | null | 2016-02-03 17:43:29.593 UTC | 2017-05-23 10:28:24.583 UTC | null | -1 | null | 2,500,842 | null | 1 | 2 | c#|string.format | 72,971 | <p>If your string credit card number will always be 16 digits, then you can do something like:</p>
<pre><code>string str = "1234567891234567";
string output = "XXXX-XXXX-XXXX-" + str.Substring(str.Length - 4);
</code></pre> |
20,424,245 | I get "The build could not read 1 project" in maven build because undefined versions | <p>I've a parent-pom and a integration-pom:<br>
<em>integration pom</em></p>
<pre class="lang-xml prettyprint-override"><code><dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-model</artifactId>
</dependency>
</dependencies>
<parent>
<groupId>com.example</groupId>
<artifactId>example-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</code></pre>
<p><em>parent pom</em></p>
<pre class="lang-xml prettyprint-override"><code><modules>
<module>../example-business</module>
<module>../example-integration</module>
<module>../example-model</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-model</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</code></pre>
<p>Now when I will do a clean install on the parent, I get the following error:</p>
<pre><code>[INFO] Scanning for projects...
Downloading: http://www.example.com/content/groups/mirror/com/example/example-parent/0.0.1-SNAPSHOT/maven-metadata.xml
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project com.example:example-integration:0.0.1-SNAPSHOT (D:\dev\workspaces\example-git\example\example-integration\pom.xml) has 3 errors
[ERROR] 'dependencies.dependency.version' for org.json:json:jar is missing. @ line 22, column 15
[ERROR] 'dependencies.dependency.version' for commons-httpclient:commons-httpclient:jar is missing. @ line 27, column 15
[ERROR] 'dependencies.dependency.version' for com.example:example-model:jar is missing. @ line 32, column 15
</code></pre>
<p>But when I take a look to the Effective POM of the integration pom, there are the version written.<br>
So why I can't build it?</p>
<hr>
<p>Edit:<br>
Here is a snip of the <em>EFFECTIVE POM</em> view:</p>
<pre><code><dependencyManagement>
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-model</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-integration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-business</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-model</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>example-business</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</code></pre> | 20,425,229 | 4 | 0 | null | 2013-12-06 12:44:04.677 UTC | null | 2022-09-20 10:41:18.523 UTC | 2018-02-03 12:01:31.097 UTC | user2979186 | 1,033,581 | user2979186 | null | null | 1 | 11 | java|maven|pom.xml | 38,549 | <p>The problem is to do with your project structure and how you have defined the <code>parent</code> in the child poms. </p>
<p>Your child modules are actually in folders that are one level up from where your parent pom resides rather than in the same level (judging from <code><module>../example-business</module></code>). When maven tries to build the child modules it can not find the parent pom as it is not available in the maven repository (it is currently in the process of building it so it has not yet been uploaded).</p>
<p>To fix this you simply need to change the <code>parent</code> definition in the child poms to define a real <code>relativePath</code> to the location of the parent pom so that maven can find it. So change it to be something like the following:</p>
<pre><code><parent>
<groupId>com.example</groupId>
<artifactId>example-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../name-of-folder-containing-parent-pom</relativePath>
</parent>
</code></pre>
<p>Obviously you'll need to change <code>name-of-folder-containing-parent-pom</code> to be whatever the folder is.</p> |
6,240,055 | Manually converting unicode codepoints into UTF-8 and UTF-16 | <p>I have a university programming exam coming up, and one section is on unicode.</p>
<p>I have checked all over for answers to this, and my lecturer is useless so that’s no help, so this is a last resort for you guys to possibly help. </p>
<p>The question will be something like:</p>
<blockquote>
<p>The string 'mЖ丽' has these unicode codepoints <code>U+006D</code>, <code>U+0416</code> and
<code>U+4E3D</code>, with answers written in hexadecimal, manually encode the
string into UTF-8 and UTF-16.</p>
</blockquote>
<p>Any help at all will be greatly appreciated as I am trying to get my head round this.</p> | 6,240,184 | 3 | 2 | null | 2011-06-04 23:41:24.86 UTC | 35 | 2017-12-12 01:44:42.887 UTC | 2014-07-06 06:41:52.943 UTC | null | 117,259 | null | 383,691 | null | 1 | 49 | unicode|utf-8|utf-16 | 48,223 | <p>Wow. On the one hand I'm thrilled to know that university courses are teaching to the reality that character encodings are hard work, but actually knowing the UTF-8 encoding rules sounds like expecting a lot. (Will it help students <a href="http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html" rel="noreferrer">pass the Turkey test</a>?)</p>
<p>The clearest description I've seen so far for the rules to encode UCS codepoints to UTF-8 are from the <code>utf-8(7)</code> manpage on many Linux systems:</p>
<pre><code>Encoding
The following byte sequences are used to represent a
character. The sequence to be used depends on the UCS code
number of the character:
0x00000000 - 0x0000007F:
0xxxxxxx
0x00000080 - 0x000007FF:
110xxxxx 10xxxxxx
0x00000800 - 0x0000FFFF:
1110xxxx 10xxxxxx 10xxxxxx
0x00010000 - 0x001FFFFF:
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
[... removed obsolete five and six byte forms ...]
The xxx bit positions are filled with the bits of the
character code number in binary representation. Only the
shortest possible multibyte sequence which can represent the
code number of the character can be used.
The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well
as 0xfffe and 0xffff (UCS noncharacters) should not appear in
conforming UTF-8 streams.
</code></pre>
<p>It might be easier to remember a 'compressed' version of the chart:</p>
<p>Initial bytes starts of mangled codepoints start with a <code>1</code>, and add padding <code>1+0</code>. Subsequent bytes start <code>10</code>.</p>
<pre><code>0x80 5 bits, one byte
0x800 4 bits, two bytes
0x10000 3 bits, three bytes
</code></pre>
<p>You can derive the ranges by taking note of how much <em>space</em> you can fill with the bits allowed in the new representation:</p>
<pre><code>2**(5+1*6) == 2048 == 0x800
2**(4+2*6) == 65536 == 0x10000
2**(3+3*6) == 2097152 == 0x200000
</code></pre>
<p>I know <em>I</em> could remember the rules to derive the chart easier than the chart itself. Here's hoping you're good at remembering rules too. :)</p>
<p><strong>Update</strong></p>
<p>Once you have built the chart above, you can convert input Unicode codepoints to UTF-8 by finding their range, converting from hexadecimal to binary, inserting the bits according to the rules above, then converting back to hex:</p>
<pre><code>U+4E3E
</code></pre>
<p>This fits in the <code>0x00000800 - 0x0000FFFF</code> range (<code>0x4E3E < 0xFFFF</code>), so the representation will be of the form:</p>
<pre><code> 1110xxxx 10xxxxxx 10xxxxxx
</code></pre>
<p><code>0x4E3E</code> is <code>100111000111110b</code>. Drop the bits into the <code>x</code> above (start from the right, we'll fill in missing bits at the start with <code>0</code>):</p>
<pre><code> 1110x100 10111000 10111110
</code></pre>
<p>There is an <code>x</code> spot left over at the start, fill it in with <code>0</code>:</p>
<pre><code> 11100100 10111000 10111110
</code></pre>
<p>Convert from <a href="http://en.wikipedia.org/wiki/Hexadecimal#Binary_conversion" rel="noreferrer">bits to hex</a>:</p>
<pre><code> 0xE4 0xB8 0xBE
</code></pre> |
6,197,671 | which datatype to use to store a mobile number | <p>Which datatype shall I use to store mobile numbers of 10 digits (Ex.:9932234242). Shall I go for varchar(10) or for the big one- the "bigint". </p>
<p>If the number is of type- '0021-23141231' , then which datatype to use?</p> | 6,197,753 | 4 | 0 | null | 2011-06-01 07:28:36.473 UTC | 6 | 2017-05-26 06:23:42.453 UTC | null | null | null | null | 613,929 | null | 1 | 12 | sql-server-2005|sql-server-2008|sql-server-express|sqldatatypes | 78,653 | <ul>
<li>varchar/char long enough for all expected (eg UK numbers are 11 long)</li>
<li>check constraint to allow only digits (expression = <code>NOT LIKE '%[^0-9]%'</code>)</li>
<li>format in the client per locale (UK = <code>07123 456 789</code> , Switzerland = <code>071 234 56 78</code>)</li>
</ul> |
6,244,362 | Java regex: newline + white space | <p>should be simple, but I'm going crazy with it. </p>
<p>Given a text like:</p>
<pre><code>line number 1
line number 2
line number 2A
line number 3
line number 3A
line number 3B
line number 4
</code></pre>
<p>I need the Java regex that deletes the line terminators then the new line begin with space, so that the sample text above become:</p>
<pre><code>line number 1
line number 2line number 2A
line number 3line number 3Aline number 3B
line number 4
</code></pre> | 6,244,390 | 4 | 3 | null | 2011-06-05 16:52:08.263 UTC | 1 | 2011-06-05 17:08:54.493 UTC | null | null | null | null | 182,547 | null | 1 | 16 | java|regex|text-manipulation | 60,568 | <p><code>yourString.replaceAll("\n ", " ");</code> this wont help?</p> |
1,474,374 | Nginx doesn't serve static | <p>I'm running Django on Ubuntu Server 9.04.</p>
<p>Django works well, but nginx doesn't return static files - always 404.</p>
<p>Here's the config:</p>
<pre><code>server {
listen 80;
server_name localhost;
#site_media - folder in uri for static files
location /static {
root /home/user/www/oil/oil_database/static_files;
autoindex on;
}
#location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov) {
# root /home/user/www/oil/oil_database/static_files;
# access_log off;
# expires 30d;
#}
location / {
root html;
index index.html index.htm;
# host and port to fastcgi server
#fastcgi_pass 127.0.0.1:8080;
fastcgi_pass unix:/home/user/www/oil/oil_database/oil.sock;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_pass_header Authorization;
fastcgi_intercept_errors off;
}
access_log /var/log/nginx/localhost.access_log;
error_log /var/log/nginx/localhost.error_log;
}
</code></pre>
<p>Nginx version is 0.6.35.</p>
<p>All directories exist and made 777 (debugging paranoia). The commented-out block doesn't help when I uncomment it.</p> | 1,474,427 | 2 | 1 | null | 2009-09-24 21:53:49.38 UTC | 11 | 2013-11-07 18:43:38.857 UTC | 2013-11-07 18:43:38.857 UTC | null | 12,892 | null | 113,678 | null | 1 | 21 | django|static|nginx | 21,492 | <p>How is your directory setup? Do you have a folder <code>static</code> in <code>/home/user/www/oil/oil_database/static_files</code>? In that case, the directive should look like this (note the trailing slash in <code>/static/</code>):</p>
<pre><code>location /static/ {
autoindex on;
root /home/user/www/oil/oil_database/static_files;
}
</code></pre>
<p>If you want to map the path <code>/home/user/www/oil/oil_database/static_files</code> to the URL <code>/static/</code>, you have to either</p>
<ul>
<li><p>rename the folder <code>static_files</code> to <code>static</code> and use this directive:</p>
<pre><code>location /static/ {
autoindex on;
root /home/user/www/oil/oil_database/;
}
</code></pre></li>
<li><p>use an alias:</p>
<pre><code>location /static/ {
autoindex on;
alias /home/user/www/oil/oil_database/static_files/;
}
</code></pre></li>
</ul>
<p>See the documentation on the <a href="http://wiki.nginx.org/NginxHttpCoreModule#root" rel="noreferrer"><code>root</code></a> and <a href="http://wiki.nginx.org/NginxHttpCoreModule#alias" rel="noreferrer"><code>alias</code></a> directives.</p> |
29,166,827 | Execute javascript after reactjs render method has completed | <p>I have a reactjs component:</p>
<pre><code>var com1 = React.createClass({
render: function() {
return (
<a href='#'>This is a text</a>
);
}
});
</code></pre>
<p>I want to execute Javascript/Jquery once rendering of this componenet has completed. Simply adding Javascript to the render method doesn't seem to work.</p>
<p>How would I achieve this?</p> | 29,167,272 | 2 | 2 | null | 2015-03-20 12:45:04.26 UTC | 3 | 2015-03-20 13:09:23.41 UTC | null | null | null | null | 653,331 | null | 1 | 19 | javascript|jquery|html|reactjs | 52,558 | <p>Use <a href="http://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount" rel="noreferrer">componentDidMount</a> method to run code after initial render and <a href="http://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate" rel="noreferrer">componentDidUpdate</a> to run code after each update of component's state.</p> |
32,300,431 | Angular 2.0 and ng-style | <p>I am building an Angular 2.0 component and I want to control it's style dynamically (using <code>ng-style</code>). After a quick view on Angular 2's docs i tried this:</p>
<pre><code><div class="theme-preview" ng-style="{'font-size': fontSize}">
{{fontSize}}
</div>
</code></pre>
<p>And saw that the size is actually printed inside the div but did not affected the style. <code>fontSize</code> is one of component's property bindings', meaning the component gets it from its parent like this:</p>
<pre><code><my-component [font-size]="size" />
</code></pre>
<p>While inside the component I have:</p>
<pre><code>@Component({
selector: 'XXX',
properties: ['fontSize']
})
</code></pre>
<p>Am I missing something here?</p> | 32,300,835 | 3 | 2 | null | 2015-08-30 19:41:34.593 UTC | 4 | 2018-01-16 04:52:41.923 UTC | 2017-01-24 17:06:27.55 UTC | null | 1,469,028 | null | 916,450 | null | 1 | 24 | javascript|angular | 42,908 | <h1>Update</h1>
<p>People still reach this answer, so I've updated the plnkr to beta.1. Two things have changed so far</p>
<ul>
<li>NgStyle is no longer necessary to be explicitly added in directives property. It's part of the common directives that are added by default.</li>
<li>The syntax has changed, now it must be camel case.</li>
</ul>
<p><strong>Example</strong></p>
<pre class="lang-js prettyprint-override"><code>@Component({
selector : 'my-cmp',
template : `
<div class="theme-preview" [ngStyle]="{'font-size': fontSize+'px'}">
{{fontSize}}
</div>`
})
class MyCmp {
@Input('font-size') fontSize;
}
@Component({
selector: 'my-app',
directives: [MyCmp],
template: `
<my-cmp [font-size]="100"></my-cmp>
`
})
</code></pre>
<p>See this <a href="http://plnkr.co/edit/Wf3vX8Ys8cFTJF212aou?p=preview" rel="noreferrer">plnkr</a> (<em>Updated to beta.1</em>)</p> |
5,773,390 | C++ network programming | <p>I would like to expand my knowledge in C++, so the first thing I'm taking on is network programming.</p>
<p>I want to make an IRC bot (which hopefully will teach me about socket programming and networking topics), but I have no idea where to start. If anyone could explain to me how IRC bots work and how to make them, and direct me to some learning resources, that would be really great. Simple snippets as well would be awesome...</p>
<p>edit:</p>
<p>forgot to mention that I use ubuntu, so the windows way is not an option</p> | 5,773,475 | 6 | 2 | null | 2011-04-24 21:36:27.963 UTC | 15 | 2022-05-08 18:49:03.683 UTC | 2022-05-08 18:49:03.683 UTC | user17242583 | null | null | 516,146 | null | 1 | 20 | c++|sockets|network-programming|irc|bots | 30,870 | <p>To understand sockets and use them right, you <strong><em>need</em></strong> The Sockets Bible:</p>
<p>W. Richard Stevens, <a href="http://tinyurl.com/3mvggvb" rel="noreferrer"><b>Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)</b></a></p>
<p>You absolutely must have this book before you sit down to write a line of sockets code. Don't leave home without it. Really. Starting around $35 used at <a href="http://tinyurl.com/3mvggvb" rel="noreferrer"><b>Amazon</b></a>. </p>
<p><strong>EDIT:</strong> The OP asked about other volumes. Here are two others:</p>
<p> W. Richard Stevens, <a href="http://tinyurl.com/6ej68o5" rel="noreferrer"><b>
UNIX Network Programming, Volume 2:
Interprocess Communications (2nd
Edition)</a></b><br>
W. Richard Stevens, <a href="http://tinyurl.com/65fnvv3" rel="noreferrer"><b>
TCP/IP Illustrated, Vol. 1: The
Protocols</a></b></p>
<p>They are of Stevens's usual and expected superb quality. I don't know what his plans were for integrating all these books,</p> |
5,646,820 | Logger wrapper best practice | <p>I want to use a nlogger in my application, maybe in the future I will need to change the logging system.
So I want to use a logging facade.</p>
<p>Do you know any recommendations for existing examples how to write those ones ?
Or just give me link to some best practice in this area.</p> | 5,646,876 | 7 | 3 | null | 2011-04-13 09:06:46.803 UTC | 88 | 2022-03-28 14:08:19.973 UTC | 2017-07-26 05:17:39.847 UTC | null | 107,625 | null | 140,100 | null | 1 | 92 | c#|.net|logging|nlog | 65,720 | <p>I used to use logging facades such as <a href="https://github.com/net-commons/common-logging" rel="nofollow noreferrer">Common.Logging</a> (even to hide my own <a href="https://github.com/dotnetjunkie/cuttingedge.logging" rel="nofollow noreferrer">CuttingEdge.Logging</a> library), but nowadays I use the <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">Dependency Injection pattern</a>. This allows me to hide loggers behind an application-defined abstraction that adheres to both <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle" rel="nofollow noreferrer">Dependency Inversion Principle</a> and the <a href="https://en.wikipedia.org/wiki/Interface_segregation_principle" rel="nofollow noreferrer">Interface Segregation Principle</a> (ISP) because it has one member and because the interface is defined by my application; not an external library.</p>
<p>Minimizing the knowledge that the core parts of your application have about the existence of external libraries, the better; even if you have no intention to ever replace your logging library. The hard dependency on the external library makes it more difficult to test your code, and it complicates your application with an API that was never designed specifically for your application.</p>
<p>This is what the abstraction often looks like in my applications:</p>
<pre class="lang-cs prettyprint-override"><code>public interface ILogger
{
void Log(LogEntry entry);
}
public sealed class ConsoleLogger : ILogger
{
public void Log(LogEntry entry)
}
public enum LoggingEventType { Debug, Information, Warning, Error, Fatal };
// Immutable DTO that contains the log information.
public struct LogEntry
{
public LoggingEventType Severity { get; }
public string Message { get; }
public Exception Exception { get; }
public LogEntry(LoggingEventType severity, string msg, Exception ex = null)
{
if (msg is null) throw new ArgumentNullException("msg");
if (msg == string.Empty) throw new ArgumentException("empty", "msg");
this.Severity = severity;
this.Message = msg;
this.Exception = ex;
}
}
</code></pre>
<p>Optionally, this abstraction can be extended with some simple extension methods (allowing the interface to stay narrow and keep adhering to the ISP). This makes the code for the consumers of this interface much simpler:</p>
<pre class="lang-cs prettyprint-override"><code>public static class LoggerExtensions
{
public static void Log(this ILogger logger, string message) =>
logger.Log(new LogEntry(LoggingEventType.Information, message));
public static void Log(this ILogger logger, Exception ex) =>
logger.Log(new LogEntry(LoggingEventType.Error, ex.Message, ex));
// More methods here.
}
</code></pre>
<p>Because the interface contains just a single method, it becomes easily to create an <code>ILogger</code> implementation that <a href="https://stackoverflow.com/a/32342484/264697">proxies to log4net</a>, <a href="https://stackoverflow.com/questions/39499229/implementation-and-usage-of-logger-wrapper-for-serilog/39499230#39499230">to Serilog</a>, <a href="https://stackoverflow.com/questions/39610056/implementation-and-usage-of-logger-wrapper-for-microsoft-extensions-logging">Microsoft.Extensions.Logging</a>, NLog or any other logging library and configure your DI container to inject it in classes that have a <code>ILogger</code> in their constructor. It is also easy to create an implementation that writes to the console, or a fake implementation that can be used for unit testing, as shown in the listing below:</p>
<pre class="lang-cs prettyprint-override"><code>public class ConsoleLogger : ILogger
{
public void Log(LogEntry entry) => Console.WriteLine(
$"[{entry.Severity}] {DateTime.Now} {entry.Message} {entry.Exception}");
}
public class FakeLogger : List<LogEntry>, ILogger
{
public void Log(LogEntry entry) => this.Add(entry);
}
</code></pre>
<p>Having static extension methods on top of an interface with a single method is quite different from having an interface with many members. The extension methods are just helper methods that create a <code>LogEntry</code> message and pass it through the only method on the <code>ILogger</code> interface. These extension methods themselves contain no <a href="https://livebook.manning.com/book/dependency-injection-principles-practices-patterns/chapter-1/section-1-3" rel="nofollow noreferrer">Volatile Behavior</a> of themselves and, therefore, won't hinder testability. You can easily test them if you wish, and they become part of the consumer's code; not part of the abstraction.</p>
<p>Not only does this allow the extension methods to evolve without the need to change the abstraction, the extension methods and the <code>LogEntry</code> constructor are always executed when the logger abstraction is used, even when that logger is stubbed/mocked. This gives more certainty about the correctness of calls to the logger when running in a test suite. I've shot myself in the foot with this many times, where my calls to the used third-party logger abstraction succeeded during my unit test, but still failed when executed in production.</p>
<p>The one-membered interface makes testing much easier as well; Having an abstraction with many members makes it hard to create implementations (such as mocks, adapters, and decorators).</p>
<p>When you do this, there is hardly ever any need for some static abstraction that logging facades (or any other library) might offer.</p>
<p>Still, even with this <code>ILogger</code> design, prefer designing your application in such way that only a few classes require a dependency on your <code>ILogger</code> abstraction. <a href="https://stackoverflow.com/a/9915056/264697">This answer</a> talks about this in more detail.</p> |
5,845,180 | resetting bxSlider | <p>I took a different direction with a carousel I implemented, opting for bxSlider instead of jCarousel. This is for an image gallery I am building <a href="http://rjwcollective.com/equinox/rishi_gallery/eqgall.php" rel="nofollow">http://rjwcollective.com/equinox/rishi_gallery/eqgall.php</a></p>
<p>The issue I am running into is when I reset the filters, or select a different filter, the slider doesn't reset.
This is the code for the inital load:</p>
<pre><code> //first load
$.ajax({
type:"POST",
url:"sortbystate.php",
data:"city=&gender=&category=",
success:function(data){
//carousel
$('#thumbs').html(data);
//alert("whoa, careful there!");
$('#thumbs').bxSlider({auto: false, mode:'vertical',
autoControls: false,
autoHover: true,
pager: false,
displaySlideQty: 4,
speed:800,
infiniteLoop: true,
moveSlideQty: 4,
controls: true});
}
});//end ajax
</code></pre>
<p>This is the code for handling the change of a filter:</p>
<pre><code>$(".statelist :input").click(function(){
var carousel = $('#thumbs').data('jcarousel');
var state = $('.statelist input:checked').attr('value');
var gender = $('.gender input:checked').attr('value');
var category =$('.category input:checked').attr('value');
$.ajax({
type:"POST",
url:"sortbystate.php",
data:"city="+state+"&gender="+gender+"&category="+category,
success:function(data){
//alert("whoa, careful there!");
$('#thumbs').html(data);
$('#thumbs').bxSlider({auto: false, mode:'vertical',
autoControls: false,
autoHover: true,
pager: false,
displaySlideQty: 4,
speed:800,
infiniteLoop: true,
moveSlideQty: 4,
controls: true});
//$('#thumbs').jcarousel('add', index, data);
}
});//end ajax
});
</code></pre>
<p>I referred bxSlider's documentation and it had a built-in function to handle a reset:
destroyShow(): function()<br>
reloadShow(): function() </p>
<p>I am confused as to what I am doing wrong.
Even tried emptying the carousel div before loading it with data, using .empty(), no dice.</p>
<p>Thoughts?</p>
<p>Edit: link to the bxSlider website: <a href="http://bxslider.com/" rel="nofollow">http://bxslider.com/</a></p> | 8,836,687 | 9 | 0 | null | 2011-04-30 22:58:24.403 UTC | 2 | 2016-05-21 08:49:45.417 UTC | null | null | null | null | 656,708 | null | 1 | 4 | jquery|ajax|reload|carousel | 43,579 | <p>Declaring the "mySlider" variable outside the document-ready block solved the problem for me:</p>
<pre><code>var mySlider;
$(function(){
mySlider= $('#slider').bxSlider({
auto: true,
controls: true
});
mySlider.reloadShow();
})
</code></pre>
<p>Alex</p> |
46,189,533 | how to run angular 4 app and nodejs api on same port 4200 for both production and development? | <p>I have created angular 4 app and I can run it using <code>ng serve --open</code> and it runs on <code>localhost:4200</code> ,
what I want is I have also created api using <code>nodejs</code> in same angular project now I want to run that API at <code>localhost:4200/api</code> so I have tried something like this</p>
<p>my angular 4 and nodejs srtucture look like this</p>
<pre><code>/dist
/server
/routes
/server
/src
app.js
package.json
</code></pre>
<p>in app.js I used</p>
<pre><code>app.use(express.static(path.join(__dirname, 'dist')));
app.use('/app/api', apiRoutes);
const port = process.env.PORT || '3000';
server.listen(port, () => console.log(`API running on localhost:${port}`));
</code></pre>
<p>Once I run using <code>nodemon app.js</code> and go at <code>localhost:3000</code> it run my angular app and it's fine and than I go at <code>localhost:3000/app/api</code> it's also work fine and good ,</p>
<p>But when I change in angular app it's not auto refresh my app because it's running node app currently for refresh it I need to run <code>ng build</code> and than it will effect my new changes on angular app</p>
<p>So, What I want is to run <code>ng serve --open</code> it will run angular app but not node js api so want to run both and once i change in any from angular app or node js app it must be auto refresh.</p> | 46,189,882 | 3 | 2 | null | 2017-09-13 05:32:25.73 UTC | 10 | 2020-02-13 02:26:51.513 UTC | 2017-09-13 06:28:28.663 UTC | null | 6,292,127 | null | 6,292,127 | null | 1 | 12 | node.js|angular|mean-stack | 18,975 | <p>You can't have two different applications running on the same port. Angular-cli uses a nodejs server (technically it's webpack-dev-server) behind the scenes when you run <code>ng serve</code>, which means that port is already in use.</p>
<p>There are two possible solutions. </p>
<ol>
<li><p>Use your node application to serve the static frontend files. Then you can't really use <code>ng serve</code> (this is probably what you'd do when running live). </p></li>
<li><p>Use nodejs with a different port, and use Angular's proxy config, to have Angular think the api port is actually 4200 (this is probably best during development). </p></li>
</ol>
<p>This is primarily a concern during development I reckon, since you most likely wont (and shouldn't) be using <code>ng serve</code> live, so option 2 would be my best recommendation.</p>
<p>To configure a proxy, you create a file in your angular application root directory called <code>proxy.config.json</code> with the following content:</p>
<pre><code>{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}
</code></pre>
<p>Then when you run <code>ng serve</code>, you run it with <code>ng serve --proxy-config proxy.config.json</code> instead. </p>
<p><a href="https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md" rel="noreferrer">Here's a link to the documentation</a></p>
<hr>
<p><strong>Here's an alternative when building for production (solution 1 above):</strong></p>
<p>To build in production you use <code>ng build --prod</code> to <a href="https://github.com/angular/angular-cli/wiki/build" rel="noreferrer">create a production ready Angular build</a> and then (assuming you use Express on your node server), use something like <code>app.use(express.static('dist/'))</code> as explained in the <a href="https://expressjs.com/en/starter/static-files.html" rel="noreferrer">Express documentation</a>. I'm not using node myself (I'm using .NET Core) so I'm afraid I can't provide much more in terms of details.</p> |
25,207,077 | How to detect if OS X is in dark mode? | <p>My cocoa app has to change its behaviour when run in the new OS X "dark mode".</p>
<p>Is there a way to detect if OS X style is set to this mode?</p> | 25,214,873 | 12 | 1 | null | 2014-08-08 15:33:45.363 UTC | 21 | 2022-07-12 19:14:33.95 UTC | 2017-02-08 03:06:30.06 UTC | null | 2,756,409 | null | 3,914,788 | null | 1 | 59 | macos|cocoa|themes | 22,760 | <p>Don't think there's a cocoa way of detecting it yet, however you can use <code>defaults read</code> to check whether or not OSX is in dark mode.</p>
<pre><code>defaults read -g AppleInterfaceStyle
</code></pre>
<p>Either returns <code>Dark</code> (dark mode) or returns domain pair does not exist.</p>
<p><strong>EDIT:</strong></p>
<p>As Ken Thomases said you can access .GlobalPreferences via NSUserDefaults, so </p>
<pre><code>NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
</code></pre>
<p>If osxMode is <code>nil</code> then it isn't in dark mode, but if osxMode is <code>@"Dark"</code> then it is in dark mode.</p> |
27,742,698 | difference between Asynchronous and Synchronous in .net 4.5 | <p>During my reading about Asynchronous Programming in .Net 4.5 <code>async</code> and <code>await</code> keywords
I read <a href="http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4" rel="noreferrer">Here</a> the following paragraph</p>
<blockquote>
<p>Processing Asynchronous Requests</p>
<p>In web applications that sees a large number of concurrent requests at
start-up or has a bursty load (where concurrency increases suddenly),
making these web service calls asynchronous will increase the
responsiveness of your application. <strong>An asynchronous request takes
the same amount of time to process as a synchronous request. For
example, if a request makes a web service call that requires two
seconds to complete, the request takes two seconds whether it is
performed synchronously or asynchronously</strong>. However, during an
asynchronous call, a thread is not blocked from responding to other
requests while it waits for the first request to complete. Therefore,
asynchronous requests prevent request queuing and thread pool growth
when there are many concurrent requests that invoke long-running
operations.</p>
</blockquote>
<p>for the bold words, I couldn't understand them how An asynchronous request takes the same amount of time to process as a synchronous request?</p>
<p><strong>For example:</strong></p>
<pre><code>public async Task MyMethod()
{
Task<int> longRunningTask = LongRunningOperation();
//indeed you can do independent to the int result work here
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}
public async Task<int> LongRunningOperation() // assume we return an int from this long running operation
{
await Task.Delay(1000); //1 seconds delay
return 1;
}
</code></pre>
<p>What I understand that <code>LongRunningOperation()</code> starts execution from the first line calling here <code>Task<int> longRunningTask = LongRunningOperation();</code> and returns value once calling <code>await</code>,
so from my point of view asynchronous code faster than synchronous, is that right?</p>
<h2>Another question:</h2>
<p>What I understand that the main thread working on executing <code>MyMethod()</code> not blocked waiting for <code>LongRunningOperation()</code> to be accomplished but it returns to thread pool to serve another request. so is there another thread assigned to <code>LongRunningOperation();</code> to execute it?</p>
<p><strong>If yes</strong> so what is the difference between Asynchronous Programming and Multithreading Programming ?</p>
<p><strong>Update:</strong></p>
<p>let's say that code becomes like that:</p>
<pre><code>public async Task MyMethod()
{
Task<int> longRunningTask = LongRunningOperation();
//indeed you can do independent to the int result work here
DoIndependentWork();
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}
public async Task<int> LongRunningOperation() // assume we return an int from this long running operation
{
DoSomeWorkNeedsExecution();
await Task.Delay(1000); //1 seconds delay
return 1;
}
</code></pre>
<p>In this case , will <code>LongRunningOperation()</code> be executed by another thread during <code>DoIndependentWork()</code> execution?</p> | 27,742,755 | 3 | 2 | null | 2015-01-02 13:02:49.74 UTC | 9 | 2015-09-30 08:10:35.877 UTC | 2015-09-30 08:10:35.877 UTC | null | 885,318 | null | 3,309,709 | null | 1 | 20 | c#|asp.net|.net|async-await|task-parallel-library | 50,255 | <p>The asynchronous operations aren't faster. If you wait for 10 seconds asynchronously (i.e. <code>await Task.Delay(10000)</code>) or synchronously (i.e. <code>Thread.Sleep(10000)</code>) <strong>it would take the same 10 seconds</strong>. The only difference would be that the <strong>first would not hold up a thread while waiting but the second will</strong>.</p>
<p>Now, if you fire up a task and don't wait for it to complete immediately you can use the same thread to do some other work, but it doesn't "speed up" the asynchronous operation's run:</p>
<pre><code>var task = Task.Delay(10000);
// processing
await task; // will complete only after 10 seconds
</code></pre>
<p>About your second question: <code>Task.Delay</code> (like other truly asynchronous operations) doesn't need a thread to be executed and so <a href="http://blog.stephencleary.com/2013/11/there-is-no-thread.html">there is no thread</a>. <code>Task.Delay</code> is implemented using a <code>System.Threading.Timer</code> that you fire up and it raises an event when it's done, in the meantime it doesn't need a thread because there's no code to execute.</p>
<p>So when the thread that was running <code>MyMethod</code> reaches the <code>await longRunningTask</code> it is freed (as long as <code>longRunningTask</code> hasn't completed yet). If it was a <code>ThreadPool</code> thread it will return to the <code>ThreadPool</code> where it can process some other code in your application.</p>
<hr>
<p>Regarding the update the flow would be so:</p>
<ul>
<li><code>MyMethod</code> starts processing</li>
<li><code>LongRunningOperation</code> starts processing</li>
<li><code>DoSomeWorkNeedsExecution</code> is executed on the calling thread</li>
<li>An <code>await</code> is reached in <code>LongRunningOperation</code> and so a hot task is returned.</li>
<li><code>DoIndependentWork</code> is executed by the same calling thread (<code>LongRunningOperation</code> is still "running", no thread is needed)</li>
<li>An <code>await</code> is reached in <code>MyMethod</code>. If the original task completed the same thread will proceed on synchronously, if not then a hot task would be returned that would complete eventually.</li>
</ul>
<p>So the fact that you're using <code>async-await</code> allows you to use a thread that would otherwise be blocked waiting synchronously to executed CPU-intensive work.</p> |
27,700,513 | How to get "data" from JQuery Ajax requests | <p>this is the code that I have on index.html:</p>
<pre><code><html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'test.php',
data: "check",
success: function(data){
alert(data);
}
});
</script>
</head>
<body>
<div></div>
</body>
</html>
</code></pre>
<p>How do I program test.php to get the "data" that is sent in the AJAX API?</p> | 27,700,685 | 6 | 2 | null | 2014-12-30 06:17:18.01 UTC | 2 | 2017-06-01 05:27:45.353 UTC | 2014-12-30 06:33:25.503 UTC | null | 2,068,379 | null | 3,001,689 | null | 1 | 10 | javascript|php|jquery|ajax | 95,335 | <p>You are asking a very basic question here. You should first go through some Ajax tutorials. Just to help you a little (assuming you are aware of GET and POST methods of sending data), 'data' in data: "check" is different than 'data' in function (data) are different. For clarity, you should name them different as here:</p>
<pre><code>$.ajax({
type: "POST",
url: 'test.php',
data: "check",
success: function(response){
alert(response);
}
});
</code></pre>
<p>This makes it clear that one is data that you are sending to the test.php file in POST parameters and other is the response you are getting from the test.php file after it is run. In fact, the data parameter that you POST to test.php has to be a hash like here (I am assuming the key as "type" here:</p>
<pre><code>$.ajax({
type: "POST",
url: 'test.php',
data: {"type":"check"},
success: function(response){
alert(response);
}
});
</code></pre>
<p>There can obviously be more key-val pairs in data.</p>
<p>So, assuming your test.php file is something like this:</p>
<pre><code>if(isset($_POST['type'])){
//Do something
echo "The type you posted is ".$_POST['type'];
}
</code></pre>
<p>In this case your alert should read: "The type you posted is check". This will change based on what value you send for 'type' key in AJAX call.</p> |
21,736,187 | Button button = findViewById(R.id.button) always resolves to null in Android | <p>I'm new to Android development, so pardon my ignorance.</p>
<p><code>findViewById</code> of a button I added always resolves to <code>null</code>. Hence if I try to <code>setonClickListener</code> it fails the whole Activity.</p>
<p><strong>MainActivity:</strong></p>
<pre><code>public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Button buttonClick = (Button) findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
}
public void onButtonClick(Button view) {
TextView textHello = (TextView) findViewById(R.id.textView);
textHello.setText("Clicked !!!");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
</code></pre>
<p><strong>activity_main.xml</strong></p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pluralsight.activitylifecycle.MainActivity"
tools:ignore="MergeRootFrame" />
</code></pre>
<p><strong>fragment_main.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.pluralsight.activitylifecycle.MainActivity$PlaceholderFragment">
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonClick"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="54dp" />
</RelativeLayout>
</code></pre> | 21,736,279 | 3 | 1 | null | 2014-02-12 18:13:43.373 UTC | 10 | 2021-05-13 21:14:44.463 UTC | 2021-05-13 21:14:44.463 UTC | null | 208,273 | null | 3,302,899 | null | 1 | 15 | android | 119,296 | <p>This is because <code>findViewById()</code> searches in the <code>activity_main</code> layout, while the button is located in the fragment's layout <code>fragment_main</code>.</p>
<p>Move that piece of code in the <code>onCreateView()</code> method of the fragment:</p>
<pre><code>//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
</code></pre>
<p>Notice that now you access it through <code>rootView</code> view:</p>
<pre><code>Button buttonClick = (Button)rootView.findViewById(R.id.button);
</code></pre>
<p>otherwise you would get again NullPointerException.</p> |
21,817,569 | Use of Include with async await | <p>I have an EF query in which I am returning an 'Item' by it's unique identifier. I'm using the scaffolded controller provided by MVC and this works ok, but now I want it to return a list of tags which belong to the item. </p>
<p>I thought I might be able to use 'Include' as shown below to eager fetch the tags. However this does not seem to be allowed when using async.</p>
<pre><code>Item item = await db.Items.Include("Tags").FindAsync(id);
</code></pre>
<p>Can anybody explain why this won't work and suggest an alternative way to bring back the item's tags?</p>
<p>Cheers</p>
<p>Ben</p> | 21,817,908 | 2 | 1 | null | 2014-02-16 22:26:14.173 UTC | 1 | 2017-06-23 01:36:41.137 UTC | 2014-02-16 23:17:06.037 UTC | null | 727,208 | null | 991,345 | null | 1 | 37 | c#|asp.net-mvc|entity-framework|asynchronous | 20,812 | <p><code>Find()</code> and <code>FindAsync()</code> are methods on type <code>DbSet</code> (which is what <code>db.Items</code> is). <code>Include()</code> returns a <code>DbQuery</code> object, which is why <code>FindAsync()</code> is not available. Use <code>SingleOrDefaultAsync()</code> to do the same thing as <code>FindAsync()</code> (the difference is it will go straight to the database and won't look in the context to see if the entity exists first)...</p>
<pre><code>Item item = await db.Items.Include("Tags").SingleOrDefaultAsync(i => i.Id == id);
</code></pre> |
21,715,430 | SVN cleanup fails - other posted solutions aren't working | <p>I'm running tortoiseSVN and I haven't been able to commit or update successfully ever since I interrupted an update (or commit) process a while back. I've found other postings of similar issues, but not of the suggestions are applicable or work - I really need to figure out a way to fix it without starting over.</p>
<p>Details:</p>
<ul>
<li>EDIT: Running Windows7</li>
<li>If I do a commit: it doesn't find files that have changed even though I have.</li>
<li>If I do an update: 'update failed!' previous operation not finish, run cleanup..</li>
<li>if I try to cleanup:
"Cleanup failed to process the following paths:
<em>the path of the folder I'm trying to cleanup</em>
Previous operation has not finished; run 'cleanup if it was interrupted
Please execute the 'cleanup' command"</li>
<li>I updated from 1.8.1 to 1.8.4; some problem</li>
<li>I tried downgrading to 1.7.something; it said something about not being able to update the log or database... went back to 1.8.4</li>
<li>Nothing is locked, so other suggestions for deleting a lock file doesn't work</li>
<li>The suggestion here (<a href="https://stackoverflow.com/questions/158664/what-to-do-when-svn-cleanup-fails">What to do when 'svn cleanup' fails?</a>) for deleting the log file doesn't work - I don't have a log file in my .SVN folder.</li>
</ul>
<p>Anyway to fix this without checking out fresh?</p>
<p>thank you!</p>
<p>Eli</p> | 21,715,521 | 6 | 2 | null | 2014-02-11 23:27:14.933 UTC | null | 2018-01-19 22:33:15.607 UTC | 2017-05-23 12:10:32.943 UTC | null | -1 | null | 2,544,106 | null | 1 | 3 | svn|tortoisesvn | 38,932 | <p>It looks like the svn meta info on you local workstation got corrupted. I don't see that you can fix this easily until you clean your workspace.</p>
<p>Try this...</p>
<ol>
<li>Back up your folder</li>
<li>Delete .svn folder from parent directory and all subdirectories in that folder, or </li>
<li>Check out fresh code in the separate directory and ... copy files from the backup folder where you don't have .svn files, so you don't lose your changes.</li>
</ol> |
32,947,440 | Android Data Binding using include tag | <h2>Update note:</h2>
<p>The above example <strong>works properly</strong>, because release 1.0-rc4 <strong>fixed</strong> the issue of needing the unnecessary variable.</p>
<h2>Original question:</h2>
<p>I do exactly as it is described in the <a href="https://developer.android.com/topic/libraries/data-binding/index.html#includes" rel="noreferrer">documentation</a> and it does not work:</p>
<p><strong>main.xml:</strong></p>
<pre><code><layout xmlns:andr...
<data>
</data>
<include layout="@layout/buttons"></include>
....
</code></pre>
<p><strong>buttons.xml:</strong></p>
<pre><code><layout xmlns:andr...>
<data>
</data>
<Button
android:id="@+id/button"
...." />
</code></pre>
<p><strong>MyActivity.java:</strong></p>
<pre><code> ... binding = DataBindingUtil.inflate...
binding.button; ->cannot resolve symbol 'button'
</code></pre>
<p>how to get button?</p> | 32,958,608 | 8 | 1 | null | 2015-10-05 11:25:29.123 UTC | 31 | 2022-01-17 13:05:27.587 UTC | 2019-02-05 17:35:24.643 UTC | null | 3,672,883 | null | 3,871,754 | null | 1 | 170 | java|android|data-binding|android-button|android-databinding | 99,542 | <p>The problem is that the included layout isn't being thought of as a data-bound layout. To make it act as one, you need to pass a variable:</p>
<p><strong>buttons.xml:</strong></p>
<pre><code><layout xmlns:andr...>
<data>
<variable name="foo" type="int"/>
</data>
<Button
android:id="@+id/button"
...." />
</code></pre>
<p><strong>main.xml:</strong></p>
<pre><code><layout xmlns:andr...
...
<include layout="@layout/buttons"
android:id="@+id/buttons"
app:foo="@{1}"/>
....
</code></pre>
<p>Then you can access buttons indirectly through the buttons field:</p>
<pre><code>MainBinding binding = MainBinding.inflate(getLayoutInflater());
binding.buttons.button
</code></pre>
<p></p>
<p>As of 1.0-rc4 (just released), you no longer need the variable. You can simplify it to:</p>
<p><strong>buttons.xml:</strong></p>
<pre><code><layout xmlns:andr...>
<Button
android:id="@+id/button"
...." />
</code></pre>
<p><strong>main.xml:</strong></p>
<pre><code><layout xmlns:andr...
...
<include layout="@layout/buttons"
android:id="@+id/buttons"/>
....
</code></pre> |
32,829,567 | Change div order with CSS depending on device-width | <p>I am working on a responsive site and came across an interesting problem. I have some divs side by side. There could be anywhere from 2 to 6 or so of them. When the screen isn't wide enough to show all the content properly, the divs stack vertically. Simple enough to do with CSS.</p>
<p>The problem is, I need them to be in a different order depending on the layout. This is easy to do with 2 or 3 divs (<a href="https://stackoverflow.com/questions/22159235/changing-divs-order-based-on-width">Changing divs order based on width</a>), but significantly more challenging when you add a fourth.</p>
<p>I could use <code>position: absolute;</code> and manually set the position, however this causes the parent to shrink and not contain them properly.</p>
<p>To make this even more complicated, I can't use JavaScript.</p>
<h2>Working with two columns:</h2>
<p>(untested)</p>
<p>HTML:</p>
<pre><code><div id="container">
<div class="column-half column-half-2">
First div on mobile, right div on desktop
</div>
<div class="column-half column-half-1">
Second div on mobile, left div on desktop
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.container {
width: 80%;
max-width: 1200px;
margin: 0 auto;
padding-bottom: 20px;
position: relative;
}
.column-half {
display: table-cell;
padding: 25px;
vertical-align: top;
width: 40%;
}
.column-half-1 {
float: left;
}
.column-half-2 {
float: right;
}
</code></pre>
<h2>HTML, with 4 columns:</h2>
<pre><code><div id="container">
<div class="column-quarter column-quarter-3">
First div on mobile, third div on desktop
</div>
<div class="column-quarter column-quarter-2">
Second div on mobile, second div on desktop
</div>
<div class="column-quarter column-quarter-1">
Third div on mobile, first div on desktop
</div>
<div class="column-quarter column-quarter-4">
Fourth div on mobile, fourth div on desktop
</div>
</div>
</code></pre> | 32,829,829 | 1 | 2 | null | 2015-09-28 18:32:49.237 UTC | 10 | 2019-11-20 14:29:05.817 UTC | 2017-07-17 15:34:40.737 UTC | null | 2,756,409 | null | 4,060,711 | null | 1 | 34 | html|css|flexbox | 58,971 | <p>This is doable in CSS thanks to the wonderful <a href="https://drafts.csswg.org/css-flexbox-1/" rel="noreferrer">flexbox</a> spec. Using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/order" rel="noreferrer"><code>order</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow" rel="noreferrer"><code>flex-flow</code></a> properties, we can achieve what you want. Unprefixed, IE11 and all evergreen browsers will support this. IE10 prefixes <code>-ms-order</code> and doesn't support <code>flex-flow</code>.</p>
<p>The solution takes into consideration all the constraints you listed:</p>
<ul>
<li>Have a list of elements in a given order displayed as a row.</li>
<li>When the window is too small, change them to display in a column.</li>
<li>Change the order of the elements when they are displayed in a column.</li>
</ul>
<p>Because of the limitations of Stack Snippets, you'll need to view the demo in Full page mode, and resize your browser to see the effect.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container div {
width: 100px;
height: 50px;
display: inline-block;
}
.one { background: red; }
.two { background: orange; }
.three { background: yellow; }
.four { background: green; }
.five { background: blue; }
@media screen and (max-width: 531px) {
.container { display: flex; flex-flow: column; }
.five { order: 1; }
.four { order: 2; }
.three { order: 3; }
.two { order: 4; }
.one { order: 5 }
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="one">I'm first</div>
<div class="two">I'm second</div>
<div class="three">I'm third</div>
<div class="four">I'm fourth</div>
<div class="five">I'm fifth</div>
</div></code></pre>
</div>
</div>
</p>
<p>Alternatively, here is a <a href="http://jsfiddle.net/chdhhm74/" rel="noreferrer">JSFiddle</a> demo.</p>
<hr>
<p>You can also simply use <code>flex-flow: column-reverse</code> without the <code>order</code> property assigned to each div, if you are so inclined against verbose CSS. The same demo restrictions apply; view this demo in full screen and resize the browser window accordingly.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container div {
width: 100px;
height: 50px;
display: inline-block;
}
.one { background: red; }
.two { background: orange; }
.three { background: yellow; }
.four { background: green; }
.five { background: blue; }
@media screen and (max-width: 531px) {
.container { display: flex; flex-flow: column-reverse; }
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="one">I'm first</div>
<div class="two">I'm second</div>
<div class="three">I'm third</div>
<div class="four">I'm fourth</div>
<div class="five">I'm fifth</div>
</div></code></pre>
</div>
</div>
</p>
<p>It's worth pointing out that <code>flex-flow</code> is a shorthand property encompassing both <code>flex-direction</code> and <code>flex-wrap</code> properties.</p> |
9,641,458 | Subset multiple columns in R - more elegant code? | <p>I am subsetting a dataframe according to multiple criteria across several columns. I am choosing the rows in the dataframe that contain any one of several values defined in the vector "criteria" in any one of three different columns.</p>
<p>I have some code that works, but wonder what other (more elegant?) ways there are to do this. Here is what I've done:</p>
<pre><code>criteria <-c(1:10)
subset1 <-subset(data, data[, "Col1"] %in% criteria | data[, "Col2"]
%in% criteria | data[, "Col3"] %in% criteria)
</code></pre>
<p>Suggestions warmly welcomed. (I am an R beginner, so very simple explanations about what you are suggesting are also warmly welcomed.) </p> | 9,641,745 | 2 | 0 | null | 2012-03-09 21:49:04.857 UTC | 2 | 2012-03-09 22:16:24.39 UTC | null | null | null | null | 1,257,313 | null | 1 | 8 | r|subset | 57,232 | <p>I'm not sure if you need two <code>apply</code> calls here:</p>
<pre><code># Data
df=data.frame(x=1:4,Col1=c(11,12,3,13),Col2=c(9,12,10,13),Col3=c(9,13,42,23))
criteria=1:10
# Solution
df[apply(df [c('Col1','Col2','Col3')],1,function(x) any(x %in% criteria)),]
</code></pre>
<p>Unless you want to do a lot of columns, then it is probably more readable to say:</p>
<pre><code>subset(df, Col1 %in% criteria | Col2 %in% criteria | Col3 %in% criteria)
</code></pre> |
9,404,104 | Simple objective-c GET request | <p>Most of the information here refers to the abandoned ASIHTTPREQUEST project so forgive me for asking again.</p>
<p>Effectively, I need to swipe a magnetic strip and send the track 2 data to a webservice that returns "enrolled" or "notenrolled" (depending on the status of the card...)</p>
<p>So my data comes in simply as</p>
<pre><code>NSData *data = [notification object];
</code></pre>
<p>And then I need to pass this to a url to the order of</p>
<p><a href="http://example.com/CardSwipe.cfc?method=isenrolled&track2=data" rel="noreferrer">http://example.com/CardSwipe.cfc?method=isenrolled&track2=data</a></p>
<p>And then just receive a response string...</p>
<p>I've searched a ton and there seems to be some conflicting answers as to whether this should be accomplished simply with AFNetworking, RESTkit, or with the native NSURL/NSMutableURLRequest protocols.</p> | 9,404,207 | 5 | 0 | null | 2012-02-22 22:24:51.733 UTC | 12 | 2021-08-08 08:05:57.25 UTC | 2016-12-31 08:10:44.823 UTC | null | 1,033,581 | null | 990,353 | null | 1 | 32 | objective-c|http|get | 68,924 | <p>The options for performing HTTP requests in Objective-C can be a little intimidating. One solution that has worked well for me is to use <code>NSMutableURLRequest</code>. An example (using ARC, so YMMV) is:</p>
<pre><code>- (NSString *) getDataFrom:(NSString *)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:url]];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
return nil;
}
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
</code></pre>
<p><strong>Update:</strong></p>
<p>Your question's title, and tagging say POST, but your example URL would indicate a GET request. In the case of a GET request, the above example is sufficient. For a POST, you'd change it up as follows:</p>
<pre><code>- (NSString *) getDataFrom:(NSString *)url withBody:(NSData *)body{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];
[request setValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
[request setURL:[NSURL URLWithString:url]];
/* the same as above from here out */
}
</code></pre> |
9,558,867 | How to fetch field from MySQL query result in bash | <p>I would like to get only the value of a MySQL query result in a bash script. For example the running the following command:</p>
<pre><code>mysql -uroot -ppwd -e "SELECT id FROM nagios.host WHERE name='$host'"
</code></pre>
<p>returns:</p>
<pre><code>+----+
| id |
+----+
| 0 |
+----+
</code></pre>
<p>How can I fetch the value returned in my bash script?</p> | 9,558,954 | 4 | 0 | null | 2012-03-04 21:13:41.453 UTC | 11 | 2017-07-28 11:37:29.257 UTC | 2012-03-04 21:23:54.517 UTC | null | 576,831 | null | 576,831 | null | 1 | 63 | mysql|bash | 101,277 | <p>Use <code>-s</code> and <code>-N</code>:</p>
<pre><code>> id=`mysql -uroot -ppwd -s -N -e "SELECT id FROM nagios.host WHERE name='$host'"`
> echo $id
0
</code></pre>
<p>From <a href="https://dev.mysql.com/doc/refman/en/mysql-command-options.html" rel="noreferrer">the manual</a>:</p>
<blockquote>
<p>--silent, -s</p>
<pre><code> Silent mode. Produce less output. This option can be given multiple
times to produce less and less output.
This option results in nontabular output format and escaping of
special characters. Escaping may be disabled by using raw mode; see
the description for the --raw option.
</code></pre>
<p>--skip-column-names, -N</p>
<pre><code> Do not write column names in results.
</code></pre>
</blockquote>
<p><strong>EDIT</strong></p>
<p>Looks like <code>-ss</code> works as well and much easier to remember.</p> |
9,597,052 | How to retrieve Request Payload | <p>I'm using <strong>PHP</strong>, <strong>ExtJS</strong> and <strong>ajax store</strong>. </p>
<p>It sends data (on create, update, destroy) not in POST or GET. In the <strong>Chrome Console</strong> I see my outgoing params as JSON in the "<strong>Request Payload</strong>" field. <strong>$_POST</strong> and <strong>$_GET</strong> are empty.</p>
<p>How to retrieve it in PHP?</p> | 9,597,087 | 2 | 0 | null | 2012-03-07 06:56:28.993 UTC | 40 | 2015-12-09 10:04:33.53 UTC | 2015-12-09 10:04:33.53 UTC | null | 432,681 | null | 1,208,512 | null | 1 | 123 | php|javascript|json|extjs | 117,594 | <p>If I understand the situation correctly, you are just passing json data through the http body, instead of <code>application/x-www-form-urlencoded</code> data.</p>
<p>You can fetch this data with this snippet:</p>
<pre><code>$request_body = file_get_contents('php://input');
</code></pre>
<p>If you are passing json, then you can do:</p>
<pre><code>$data = json_decode($request_body);
</code></pre>
<p><code>$data</code> then contains the json data is php array.</p>
<p><code>php://input</code> is a so called <a href="http://php.net/manual/en/wrappers.php.php">wrapper</a>.</p>
<blockquote>
<p>php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".</p>
</blockquote> |
10,737,473 | HTML CSS button text alignment isn't working | <p>I have code like this:</p>
<pre><code> <button class="prikazi_pretragu">Napredna Pretraga</button>
</code></pre>
<p>and CSS:</p>
<pre><code>button {
display:inline;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
float: right;
clear: both;
padding: 0 50px 5px 5px;
text-align: left;
margin: 0 0 10px 0;
border: none;
background: url('../img/resursi/advsearch_plus.png') no-repeat 0 -28px rgba(0,0,0,.09);
font-size: 14px;
height: 28px;
text-align: right
}
</code></pre>
<p><code>text-align</code> is not working. What is the problem?</p>
<p><a href="http://jsfiddle.net/KjGBW/1/" rel="noreferrer">http://jsfiddle.net/KjGBW/1/</a></p> | 10,737,539 | 2 | 1 | null | 2012-05-24 12:26:26.747 UTC | 1 | 2020-07-19 14:11:33.917 UTC | 2012-05-24 12:29:53.96 UTC | null | 1,169,798 | null | 934,703 | null | 1 | 5 | html|css | 44,077 | <p>It is working. It is aligned to the right (quite pointlessly, since you haven't explicitly set a width). It's just that you have a 50px padding on the right and that's why it <em>seems</em> to be aligned to the left.</p>
<pre><code>padding: 0 50px 5px 5px;
</code></pre>
<p>Values are for top right bottom left, in this order.</p>
<p>Set it to <code>padding: 0 5px 5px 5px;</code></p>
<p>Also, if you set a width of let's say 300px you will see it clearly aligned to the right.</p>
<p>See <a href="http://jsfiddle.net/thebabydino/KjGBW/5/">http://jsfiddle.net/thebabydino/KjGBW/5/</a> - I have changed the padding and added a width. Now you can see clearly that it is aligned to the right.</p> |
7,417,401 | Writing JSONObject into a file | <p>I'm using Play framework. I have a JSONObject which has a structure like the below (As in console it printed)</p>
<pre><code>{
"rows_map":{
"220":["mahesh",
"outfit:bmtech,app:salesreport,uuname,ffname,llname",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
null
],
"221":["mahesh",
"outfit:bmtech,app:salesreport,uuname,ffname,llname",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
null
],
"222":["mahesh",
"outfit:bmtech,app:salesreport,uuname,ffname,llname",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
null
],
"223":["mahesh",
"outfit:bmtech,app:salesreport,uuname,ffname,llname",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
null
]
},
"columns_map":["Sender",
"Message Received",
"Device",
"Time"
]
}
</code></pre>
<p>I want to write this JSONObject to a file. Here is the code </p>
<pre><code>String path = "/var/www/html/Prj/public/CacheLayer/Incoming_Cache/CacheFileMgr.cache";
ObjectOutputStream outputStream = null;
try{
outputStream = new ObjectOutputStream(new FileOutputStream(path));
System.out.println("Start Writings");
outputStream.writeObject(object);
outputStream.flush();
outputStream.close();
}catch (Exception e){
System.err.println("Error: " + e);
}
</code></pre>
<p>The above doesn't successfully writes to the file. Serialization error occurs.</p> | 7,417,442 | 2 | 1 | null | 2011-09-14 13:47:55.387 UTC | 1 | 2011-09-18 13:11:57.647 UTC | 2011-09-14 14:11:25.757 UTC | null | 157,882 | null | 557,329 | null | 1 | 7 | java|json|file|file-io | 38,995 | <p>Call toString on the JSONObject, and then serialize the string. JSONObject itself is not serializable.</p>
<pre><code>String jsonString = jsonObject.toString();
</code></pre> |
19,284,153 | How to get a responsive button in bootstrap 3 | <p>I am using bootstrap 3 and I have the following html:</p>
<pre><code><div class="col-sm-2" >
<a id="new-board-btn" class="btn btn-success" >Create New Board</a>
</div>
</code></pre>
<p>On a small screen, the text "Create New Board" is too long to fit on the button. I would like the text to wrap on to another line and the height of the button to increase to fit the text. Any tips on how to do this?</p> | 19,284,233 | 5 | 1 | null | 2013-10-09 22:50:52.96 UTC | 14 | 2018-01-26 10:19:49.937 UTC | 2013-10-10 01:49:53.967 UTC | null | 1,789,724 | null | 2,602,173 | null | 1 | 51 | css|twitter-bootstrap|button|twitter-bootstrap-3 | 127,165 | <p>In Bootstrap, the <code>.btn</code> class has a <code>white-space: nowrap;</code> property, making it so that the button text won't wrap. So, after setting that to <code>normal</code>, and giving the button a <code>width</code>, the text should wrap to the next line if the text would exceed the set <code>width</code>.</p>
<pre><code>#new-board-btn {
white-space: normal;
}
</code></pre>
<p><a href="http://jsfiddle.net/ADewB/" rel="noreferrer">http://jsfiddle.net/ADewB/</a></p> |
18,880,735 | Change element height using Angular JS | <p>Is there a better way to change an element height using angular js?</p>
<p>I'm doing it like:</p>
<pre><code>function HomeCtrl ($scope) {
$('.banner').css('height', ($(window).height()) - $('.header').outerHeight());
}
</code></pre> | 18,881,460 | 2 | 1 | null | 2013-09-18 19:31:40.97 UTC | 8 | 2014-03-18 04:20:15.093 UTC | null | null | null | user1320990 | null | null | 1 | 16 | jquery|angularjs | 40,948 | <p>Avoid jQuery all together. Use a directive and you can access the element and make adjustments to it. As a general rule of thumb, if you have brought in jQuery to help you do DOM manipulation, you are likely doing Angular wrong. Without a lot of context its hard to suggest a better implementation than what you have here.</p>
<p>It somewhat depends on what (and where) <code>.header</code> is, but here's my idea:</p>
<p>jscript:</p>
<pre><code>var myApp = angular.module('myApp', []);
myApp.directive('banner', function ($window) {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var winHeight = $window.innerHeight;
var headerHeight = attrs.banner ? attrs.banner : 0;
elem.css('height', winHeight - headerHeight + 'px');
}
};
});
</code></pre>
<p>html:</p>
<pre><code><div banner="250" class="banner">I'm a banner!</div>
</code></pre>
<p>Since I am not sure what header is, I just assume have it get passed in as an attribute. My best guess for that would be to grab its height and store it in a controller scope that is then watched by banner. This would make it somewhat responsive as well.</p> |
36,847,431 | Remember GPG password when signing git commits | <p>Would it be possible for the GPG password to be saved, so that I am not prompted for the passphrase everytime I make a git commit?</p> | 37,369,506 | 2 | 2 | null | 2016-04-25 17:39:45.92 UTC | 14 | 2021-11-23 14:58:37.083 UTC | null | null | null | null | 5,076,225 | null | 1 | 60 | git|shell|gnupg | 16,978 | <p>You can set a timeout period for gpg-agent in <code>~/.gnupg/gpg-agent.conf</code> with this line:</p>
<pre><code>default-cache-ttl 3600
</code></pre>
<p>That would tell gpg-agent to store the passphrase for one hour. You wouldn't want it to be indefinite, but not constantly typing it is of benefit too.</p> |
3,797,221 | Why would you give a style tag an id | <p>Hi have noticed a few sites that give the style tag an id such as:</p>
<pre><code><style id=style-id></style>
</code></pre>
<p>Can anyone explain firstly why you would do this and also the benefits of doin so?</p> | 3,797,236 | 1 | 0 | null | 2010-09-26 09:35:17.93 UTC | 2 | 2010-09-26 09:39:10.373 UTC | null | null | null | null | 458,634 | null | 1 | 39 | html|css | 24,373 | <p>So you can reference it (just like any other element), i.e.</p>
<pre><code>var styles = document.getElementById('style-id');
// do anything you want, like
styles.parentNode.removeChild(styles); // remove these styles
styles.setAttribute('href', 'alternate-styles.css'); // change the style
</code></pre> |
21,122,269 | Why do these two comparisons have different results? | <p>Why does this code return true:</p>
<pre><code>new Byte() == new Byte() // returns true
</code></pre>
<p>but this code returns false:</p>
<pre><code>new Byte[0] == new Byte[0] // returns false
</code></pre> | 21,122,293 | 4 | 3 | null | 2014-01-14 19:29:25.773 UTC | 9 | 2014-12-08 18:17:45.463 UTC | 2014-01-15 13:55:00.913 UTC | null | 1,578,713 | null | 2,524,304 | null | 1 | 68 | c#|.net|equality | 3,331 | <p>Because <code>new Byte()</code> creates value type, which are compared by value (by default it will return <code>byte</code> with value <code>0</code>). And <code>new Byte[0]</code> creates array, which is a reference type and compared by reference (and these two instances of array will have different references).</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx">Value Types and Reference Types</a> article for details.</p> |
18,302,683 | How to create tooltip over text selection without wrapping? | <p>My end goal is to create a tooltip over a text selection. The user will then be able to interact with the tooltip similar to <img src="https://i.stack.imgur.com/AqGp9.png" alt="this">. Please note that I was able to accomplish this by wrapping selected text in a tag and then creating the tooltip on it however this is no longer an option for me due to some other requirements and functionality issues. If you notice in the image above in element inspector, the selected text is not wrapped in any kind of tag, the tooltip is just created over the selection. I have already looked at <a href="https://stackoverflow.com/questions/4362297/tooltip-triggered-by-text-selection">this</a> and it will not work for me because mouse position may not be the same as the end of selection. I need the actual selection position.</p>
<p>General question: What is the best way to accomplish this?
More specific questions: </p>
<ul>
<li>Should I be using the coordinates of the selection? If so is there a way to get the coordinates of the top corners of the rectangular selection so I can find the mid point and create a the tooltip over that.</li>
<li>Is there a way to get that selection as an element? So I can just place a tooltip over that? (Note the selection can be multiple nodes)</li>
</ul> | 18,302,723 | 2 | 5 | null | 2013-08-18 19:04:35.74 UTC | 19 | 2020-12-30 08:10:58.477 UTC | 2017-05-23 12:10:41.897 UTC | null | -1 | null | 2,517,849 | null | 1 | 9 | javascript|jquery|html|selection|textselection | 8,477 | <p>Assuming something selected</p>
<pre><code>var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
</code></pre>
<p><code>rect</code> is now a <em>Object</em> which holds the positions relative the the current scroll coordinates of the <em>Window</em>. More info on this <a href="https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect" rel="noreferrer"><strong>here</strong></a>. If you want to be even more precise, you can use <code>getClientRects</code> which returns a list of such <em>Objects</em>, which you would then have to put together to form the area of the selection.</p>
<p>Now, to draw a box around it (I'll take the easy route using <code>fixed</code> for demonstration purposes)</p>
<pre><code>var div = document.createElement('div'); // make box
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
</code></pre>
<p>You will probably want to take into consideration the scroll position so you can use absolute positioning. If there are no other scrollable elements, this means you just need to factor in the values of <code>window.scrollX</code> and <code>window.scrollY</code>, which are the position of the window's <em>x</em> and <em>y</em> coordinates in pixels at the time they're accessed.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var div = null;
function drawBorderAroundSelection() {
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
if (rect.width > 0) {
if (div) {
div.parentNode.removeChild(div);
}
div = document.createElement('div'); // make box
div.class = 'rect';
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
}
}
window.onmouseup = drawBorderAroundSelection;</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis
nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue
vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque.
</p></code></pre>
</div>
</div>
</p> |
28,388,597 | Removing bin executable folder from GitHub | <p>I accidentally pushed the <code>bin</code> folder of my Java program to GitHub, and now I wish to remove all those <code>.class</code> files.</p>
<p>How can I do that?</p> | 28,388,646 | 1 | 1 | null | 2015-02-07 23:11:43.777 UTC | 8 | 2018-12-11 03:15:21.623 UTC | 2015-02-08 03:31:21.893 UTC | null | 1,223,975 | null | 1,223,975 | null | 1 | 11 | git|github | 7,127 | <p>First, you should create a commit that removes this folder from git:</p>
<pre><code>$ git rm -r bin
$ git commit -m "Removed bin folder"
$ git push origin master
</code></pre>
<p>After doing that, you can ensure this mistake won't happen again by adding the <code>bin</code> directory to your <code>.gitignore</code> file, and commit that change too:</p>
<pre><code>$ echo "bin/" >> .gitignore
$ git add .gitignore
$ git commit -m "Added bin folder to gitignore"
$ git push origin master
</code></pre> |
1,704,304 | What is this error? "Database query failed: Data truncated for column 'column_name' at row 1 | <p>I'm building a PHP/MySQL application and I'm running into a problem with my create and update query. I have 5 columns that are set to type FLOAT that are also set as NULL columns. I don't plan to fill them in until much later in the workflow. </p>
<p>However, I need to create new records for this database, and I need to edit existing records, without touching these 5 float fields at all. I'm using OOP PHP that uses a standard <code>save()</code> method that checks to see if an ID exists in the object. If not, it calls <code>create()</code>, and if so, it calls <code>update()</code>. It works very well, usually.</p>
<p>The <code>update()</code> and <code>create()</code> methods are designed to pull from a <code>protected static $db_fields</code> attribute array declared at the top of each Class, that contains all of the fields used in that table. <code>update()</code> and <code>create()</code> run through that array and either <code>INSERT INTO</code> or <code>UPDATE</code> in SQL, accordingly.</p>
<p>My understanding is that if you use <code>''</code> (two single quotes, empty), SQL will skip those <code>INSERT INTO</code> or <code>UPDATE</code> requests and leave them as NULL. There aren't even form fields for those 5 float values anywhere on the page, so of course when the methods run, the values are going to be <code>''</code>. </p>
<p>Is that why I'm getting the "Data truncated" error? It seems different -- I haven't seen the truncated error before and that's why I'm coming to you geniuses. Thanks.</p> | 1,704,382 | 3 | 1 | null | 2009-11-09 22:18:00.963 UTC | 5 | 2015-06-27 18:08:46.92 UTC | null | null | null | null | 171,021 | null | 1 | 28 | php|mysql | 107,801 | <p><code>''</code> and <code>null</code> are not the same. if your mysql server is in strict mode, then it will refuse to do the insert since you have passed invalid data for the column. without strict mode, it returns a warning.</p>
<pre><code>mysql> create table a (a float not null);
Query OK, 0 rows affected (0.11 sec)
mysql> insert a values ('');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'a' at row 1 |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> set sql_mode = 'STRICT_ALL_TABLES';
Query OK, 0 rows affected (0.02 sec)
mysql> insert a values ('');
ERROR 1265 (01000): Data truncated for column 'a' at row 1
</code></pre>
<p>either insert explicit <code>null</code>s, or don't even specify the column in the insert.</p>
<p>when you're updating you can send all of the values you have because mysql will automatically ignore the unchanged ones.</p> |
1,941,755 | getting output and exit status from shell_exec() | <p>When doing something like</p>
<pre><code>$output = shell_exec("command 2>&1");
</code></pre>
<p>collecting the command's stdout & stderr in <code>$output</code>, is there a way to find the command's exit status?</p>
<p>One could write the command output to a temp file and then append the exit status, but that's rather clunky. Any better suggestions?</p> | 1,941,781 | 3 | 0 | null | 2009-12-21 18:22:49.283 UTC | 5 | 2019-01-03 13:40:17.807 UTC | null | null | null | user213154 | null | null | 1 | 36 | php | 74,128 | <p>As you've already seen, when using shell_exec you have to chain your "real" command with echo $? to get the exit status:</p>
<pre><code> $output_including_status = shell_exec("command 2>&1; echo $?");
</code></pre>
<p>but if you want the clean way, then you want to use the <a href="http://us2.php.net/manual/en/function.exec.php" rel="noreferrer">exec</a> function, which allows a 3rd agument explicitly for this purpose.</p> |
1,622,729 | Double vs float on the iPhone | <p>I have just heard that the iphone cannot do double natively thereby making them much slower that regular float.</p>
<p>Is this true? Evidence?</p>
<p>I am very interested in the issue because my program needs high precision calculations, and I will have to compromise on speed.</p> | 1,622,786 | 3 | 0 | null | 2009-10-26 01:33:00.417 UTC | 24 | 2011-02-17 21:47:28.533 UTC | 2011-02-17 21:47:28.533 UTC | null | 142,434 | null | 139,885 | null | 1 | 47 | iphone|cocoa-touch|floating-point|ieee-754 | 12,092 | <p>The iPhone can do both single and double precision arithmetic in hardware. On the 1176 (original iPhone and iPhone3G), they operate at approximately the same speed, though you can fit more single-precision data in the caches. On the Cortex-A8 (iPhone3GS, iPhone4 and iPad), single-precision arithmetic is done on the NEON unit instead of VFP, and is substantially faster.</p>
<p>Make sure to turn off thumb mode in your compile settings for armv6 if you are doing intensive floating-point computation.</p> |
8,533,546 | use of boolean to color converter in XAML | <p>I am working on WPF application.I have bound my textblock to my button. I want to set foreground of my textblock to black color when its associated button's isEnabled is true.
I want to do this using converter. <strong>But its not working</strong>. also not giving any error.
I have declared following class in my "Models" folder.</p>
<pre><code>public class BrushColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
{
{
return System.Windows.Media.Colors.Black;
}
}
return System.Windows.Media.Colors.LightGreen;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p><strong>Button's enable,isable property changes from viewmodel</strong>(e.g using RaiseCanExecuteChanged)())</p>
<p>textblock related things in XAML are:</p>
<pre><code> <Window.Resources>
<local:BrushColorConverter x:Key="BConverter"></local:BrushColorConverter>
</Window.Resources>
<Button>(!..all button properties..!)</Button>
<TextBlock x:Name="AnswerText"
Text="Answer"
Foreground="{Binding ElementName=AnswerButton,Path=IsEnabled, Converter={StaticResource BConverter}}"
TextWrapping="Wrap"/>
</code></pre> | 8,533,821 | 3 | 1 | null | 2011-12-16 11:29:26.363 UTC | 4 | 2017-12-21 05:46:14.757 UTC | 2017-12-21 05:46:14.757 UTC | null | 1,033,581 | null | 1,081,100 | null | 1 | 34 | c#|wpf|xaml|converter | 44,500 | <p>use
return new SolidColorBrush(Colors.Black); </p> |
19,401,633 | How to fire an event on class change using jQuery? | <p>I would like to have something like:</p>
<pre><code>$('#myDiv').bind('class "submission ok" added'){
alert('class "submission ok" has been added');
});
</code></pre> | 19,401,707 | 4 | 0 | null | 2013-10-16 10:58:08.19 UTC | 28 | 2022-06-23 12:33:13.483 UTC | 2021-03-05 21:49:22.787 UTC | null | 4,370,109 | null | 1,412,620 | null | 1 | 97 | javascript|jquery|jquery-events | 259,839 | <p>There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:</p>
<pre><code>$someElement.on('event', function() {
$('#myDiv').addClass('submission-ok').trigger('classChange');
});
// in another js file, far, far away
$('#myDiv').on('classChange', function() {
// do stuff
});
</code></pre>
<hr />
<p><strong>UPDATE</strong></p>
<p>This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new <code>MutationObserver</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var $div = $("#foo");
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var attributeValue = $(mutation.target).prop(mutation.attributeName);
console.log("Class attribute changed to:", attributeValue);
});
});
observer.observe($div[0], {
attributes: true,
attributeFilter: ['class']
});
$div.addClass('red');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
color: #C00;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="bar">#foo.bar</div></code></pre>
</div>
</div>
</p>
<p>Be aware that the <code>MutationObserver</code> is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See <a href="https://developer.mozilla.org/en/docs/Web/API/MutationObserver" rel="nofollow noreferrer">MDN</a> for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.</p> |
895,002 | ASP.NET Active Directory Membership Provider and SQL Profile Provider | <p>I am currently designing a Membership/Profile scheme for a new project I am working on and I was hoping to get some input from others. </p>
<p>The project is a ASP.NET web application and due to the short time frame, I am trying to use any and all built in .NET framework components I can. The site will probably entertain < 5000 users. Each user will have a profile where custom settings and objects will be persisted between visits.</p>
<p>I am required to use an existing Active Directory for authentication. Since the AD schema cannot be extended to hold new fields, I am required to hold user settings and objects in a different data store. I have also been told ADAM is probably not a possible solution.</p>
<p>I was hoping to use the Active Directory Membership Provider for my authentication scheme and the SQL Profile Provider as a user profile data store. I would prefer not to build a custom profile provider, but I do not see this posing much of a problem if need be.</p>
<p>I was wondering if this is even a possible solution, and if so, has anyone had any luck with this approach.</p>
<p>Any comments would be greatly appreciated.</p>
<p>Thanks.</p> | 895,212 | 4 | 0 | null | 2009-05-21 20:36:52.437 UTC | 11 | 2013-06-17 11:36:07.573 UTC | 2009-12-18 21:07:46.16 UTC | null | 81,941 | null | 110,715 | null | 1 | 17 | asp.net|active-directory|membership|provider | 19,731 | <p>First off - I've never done this myself.</p>
<p>There's a really excellent series (14 !! parts) on the whole topic of ASP.NET 2.0 membership, roles and profile provider systems by Scott Mitchell at <a href="https://web.archive.org/web/20211020202857/http://www.4guysfromrolla.com/articles/120705-1.aspx" rel="noreferrer">4 Guys from Rolla</a>.</p>
<p>According to my understanding, you should be able to configure this behavior you are looking for by using basically these two sections in your web.config:</p>
<pre><code> <!-- configure Active Directory membership provider -->
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web, Version=2.0.3600, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<!-- configure SQL-based profile provider -->
<profile defaultProvider="SqlProvider">
<providers>
<add name="SqlProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="SqlProfileProviderConnection"
applicationName="YourApplication" />
</providers>
<!-- specify any additional properties to store in the profile -->
<properties>
<add name="ZipCode" />
<add name="CityAndState" />
</properties>
</profile>
</code></pre>
<p>I would think this ought to work :-)</p> |
423,938 | Java: export to an .jar file in eclipse | <p>I'm trying to export a program in Eclipse to a jar file. </p>
<p>In my project I have added some pictures and PDF:s. When I'm exporting to jar file, it seems that only the <code>main</code> has been compiled and exported. </p>
<p>My will is to export everything to a jar file if it's possible, because then I want to convert it to an extraditable file, like .exe-file.</p>
<p>But how?</p> | 423,953 | 4 | 1 | null | 2009-01-08 11:20:13.967 UTC | 18 | 2017-07-10 06:40:07.837 UTC | 2017-04-27 14:59:11.14 UTC | null | 452,775 | Adis | 50,896 | null | 1 | 56 | java|eclipse|executable|extract|exe | 210,803 | <p>No need for external plugins. In the <strong>Export JAR</strong> dialog, make sure you select <em>all</em> the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
<a href="https://i.stack.imgur.com/IsQZv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/IsQZv.jpg" alt="JAR Export Dialog"></a></p> |
49,129,765 | Read json from jenkins | <p>Im trying to read a json file from within a jenkinsfile with grovvy script. Im using the pipeline-utility-steps-plugin, which allows to read the json file as string with the following.</p>
<pre><code>def projects = readJSON file: "${env.WORKSPACE}\\Projects.json"
</code></pre>
<p>after reading the doc, i was thinking i could get out with something like this, but i surely do something wrong because result is null? </p>
<pre><code>projects.project[1].name
</code></pre>
<p>Now my problem is i cant seem to figure out how i get the <strong>name</strong> of number 2 out? Please help me out</p>
<p>Content of the Projects.json</p>
<pre><code> {
"projects": {
"project": [
{
"name": "PackingStation",
"solution": "PackingStation\\BLogic.Applications.PackingStation.sln",
"analysisFiles": "BLogic.Applications.PackingStation.exe"
},
{
"name": "MasterData",
"solution": "MasterData\\BLogic.Applications.MasterData.sln",
"analysisFiles": "BLogic.Applications.MasterData.exe"
},
{
"name": "OrderManager",
"solution": "OrderManager\\BLogic.Applications.OrderManager.sln",
"analysisFiles": "BLogic.Applications.OrderManager.exe"
}
]
}
}
</code></pre> | 49,130,896 | 1 | 0 | null | 2018-03-06 11:27:56.997 UTC | 2 | 2020-12-02 22:46:52.267 UTC | null | null | null | null | 327,668 | null | 1 | 5 | jenkins|jenkins-groovy | 42,290 | <p>You are accessing it wrong. <code>projects</code> in <code>projects.project[1].name</code> refers to the variable defined here <code>def projects = readJSON file: "${env.WORKSPACE}\\Projects.json"</code>.</p>
<p>You have again inner json key as <code>projects</code>. So please use <code>projects.projects.project[1].name</code> to access the value. Hope this helps.</p> |
19,737,124 | Mocking only a single method on an object | <p>I'm familiar with other mocking libraries in other languages such as Mockito in Java, but Python's <code>mock</code> library confuses the life out of me.</p>
<p>I have the following class which I would like to test.</p>
<pre><code>class MyClassUnderTest(object):
def submethod(self, *args):
do_dangerous_things()
def main_method(self):
self.submethod("Nothing.")
</code></pre>
<p>In my tests, I'd like to make sure that the <code>submethod</code> was called when <code>main_method</code> was executed and that it was called with the right arguments. I don't want <code>submethod</code> to run, as it does dangerous things. </p>
<p>I'm entirely unsure as to how to get started with this. Mock's documentation is incredibly hard to understand and I'm not sure what to even mock or how to mock it. </p>
<p>How can I mock the <code>submethod</code> function, while leaving the functionality in <code>main_method</code> alone?</p> | 19,737,253 | 1 | 0 | null | 2013-11-01 23:33:33.03 UTC | 5 | 2017-02-27 15:45:32.317 UTC | null | null | null | null | 128,967 | null | 1 | 52 | python|mocking|python-mock | 17,705 | <p>I think what you are looking for is <code>mock.patch.object</code></p>
<pre><code>with mock.patch.object(MyClassUnderTest, "submethod") as submethod_mocked:
submethod_mocked.return_value = 13
MyClassUnderTest().main_method()
submethod_mocked.assert_called_once_with(user_id, 100, self.context,
self.account_type)
</code></pre>
<p>Here is small description</p>
<pre><code> patch.object(target, attribute, new=DEFAULT,
spec=None, create=False, spec_set=None,
autospec=None, new_callable=None, **kwargs)
</code></pre>
<blockquote>
<p>patch the named member (attribute) on an object (target) with a mock object.</p>
</blockquote> |
33,058,676 | How to remove multiple spaces in Strings with Swift 2 | <p>Until Swift 2 I used this extension to remove multiple whitespaces:</p>
<pre><code>func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
return " ".join(components)
}
</code></pre>
<p>but with Swift 2 now I get the error</p>
<blockquote>
<p>Cannot invoke 'isEmpty' with an argument list of type '(String)'</p>
</blockquote>
<p>How could I now remove multiple spaces with Swift 2?
Thnx!</p> | 33,058,765 | 6 | 0 | null | 2015-10-10 20:31:34.693 UTC | 5 | 2020-02-12 13:49:08.437 UTC | null | null | null | null | 170,085 | null | 1 | 29 | swift2|xcode7|removing-whitespace | 13,584 | <p>In <strong>Swift 2</strong>, <code>join</code> has become <code>joinWithSeparator</code> and you call it on the array.</p>
<p>In <code>filter</code>, <code>isEmpty</code> should be called on the current iteration item <code>$0</code>.</p>
<p>To replace whitespaces and newline characters with unique space characters as in your question:</p>
<pre><code>extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
</code></pre>
<p>Because your function does not take any parameter you could make it a property instead:</p>
<pre><code>extension String {
var condensedWhitespace: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace // "Hello World. Hello!"
</code></pre>
<hr>
<p>In <strong>Swift 3</strong> there's even more changes.</p>
<p>Function:</p>
<pre><code>extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace()
</code></pre>
<p>Property:</p>
<pre><code>extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace
</code></pre>
<p>In <strong>Swift 4.2</strong> NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:</p>
<pre><code>extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
</code></pre> |
33,667,752 | Start a PHP server on Mac OS X | <p>I am figuring out how to use <a href="https://github.com/openid/php-openid" rel="noreferrer">PHP OpenId</a></p>
<p>I have cloned the repo to the <code>~/www</code> directory. There are some examples in the <code>php-open-id/examples</code> directory which I wanted to run.</p>
<p>Specifically, I wanted to render the page <code>php-open-id/examples/consumer/index.php</code> in order to better understand the API. I started a server in the <code>php-open-id/examples</code> directory using</p>
<pre><code>python -m SimpleHTTPServer 8000
</code></pre>
<p>and I navigated to <code>localhost://consumer/index.php</code></p>
<p>But it didn't work. It shows a dialog box to save the file. What is the correct way to render this PHP file?</p> | 33,669,004 | 3 | 0 | null | 2015-11-12 09:06:44.603 UTC | 11 | 2021-07-21 13:45:33.923 UTC | 2021-07-21 13:45:33.923 UTC | null | 574,419 | null | 3,425,344 | null | 1 | 46 | php|macos|server | 58,239 | <p>I have found a solution :</p>
<p>Run the server using</p>
<pre><code>php -S localhost:9000
</code></pre> |
30,849,862 | Django max_length for IntegerField | <p>I have this model field:</p>
<pre><code>id_student = models.PositiveIntegerField(primary_key=True, max_length=10)
</code></pre>
<p>The <code>max_length</code> restriction doesn't work. I can log in to the admin and create a student with an id with more than 10 chars. How can I solve this?</p> | 30,850,101 | 1 | 0 | null | 2015-06-15 16:05:12.483 UTC | 11 | 2022-04-13 06:58:54.553 UTC | 2015-06-15 16:27:18.96 UTC | null | 113,962 | null | 2,848,189 | null | 1 | 46 | django|django-models|django-admin | 48,680 | <p>Django ignores <code>max_length</code> for integer fields, and will warn you in Django 1.8+. See <a href="https://code.djangoproject.com/ticket/23801" rel="noreferrer">ticket 23801</a> for more details.</p>
<p>You can either use a max value validator, </p>
<pre><code>from django.core.validators import MaxValueValidator
class MyModel(models.Model):
...
id_student = models.PositiveIntegerField(primary_key=True, validators=[MaxValueValidator(9999999999)])
</code></pre>
<p>or use a <code>CharField</code> to store the id, and use a regex validator to ensure that the id is entirely made of digits. This would have the advantage of allowing ids that start with zero.</p>
<pre><code>from django.core.validators import RegexValidator
class MyModel(models.Model):
...
id_student = models.CharField(primary_key=True, max_length=10, validators=[RegexValidator(r'^\d{1,10}$')])
</code></pre> |
19,848,315 | phpStorm 7 update docblock | <p>Is there a way to ask phpStorm to update the contents of a docblock? eg if I have the following code</p>
<pre><code>//-------------------------------------------------------------------------
/**
* @param string $url
* @return $this
*/
public function setBaseUrl($url)
{
$this->baseUrl = $url;
return $this;
}
</code></pre>
<p>and add another parameter</p>
<pre><code>//-------------------------------------------------------------------------
/**
* @param string $url
* @return $this
*/
public function setBaseUrl($url, $anotherParameter)
{
$this->baseUrl = $url;
return $this;
}
</code></pre>
<p>is there a way to ask phpStorm to create the @param $anotherParameter in my docblock? (in a single keystroke or by menu selection)?</p> | 19,848,562 | 3 | 0 | null | 2013-11-07 22:49:16.79 UTC | 6 | 2017-06-15 08:51:12.077 UTC | null | null | null | null | 117,647 | null | 1 | 30 | phpstorm|docblocks | 14,408 | <p><code>Alt+Enter</code> (Show Intention Actions) on the comment, then <code>Enter</code> again.</p>
<p>This is configurable via <code>[Settings > Keymap]</code> then <code>[Other > Show Intention Actions]</code></p>
<p>Alternatively you can do the same with mouse if you click on the comment, and then on the yellow bulb that shows up.</p> |
42,764,591 | Flex-direction column makes flex items overlap IE11 | <p>I'm running into an issue using flexbox in IE11. When using <code>flex-direction: column</code> the flex-items overlap:</p>
<p><a href="https://i.stack.imgur.com/fHBw0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fHBw0.png" alt="enter image description here" /></a></p>
<p>In other browsers (chrome, safari) it looks like this:</p>
<p><a href="https://i.stack.imgur.com/c2h7P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c2h7P.png" alt="enter image description here" /></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
display: flex;
flex-direction: column;
}
.flex {
flex: 1 1 0%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="flex">
Hello
</div>
<div class="flex">
World
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I've made a codepen to demonstrate the issue:</p>
<p><a href="http://codepen.io/csteur/pen/XMgpad" rel="nofollow noreferrer">http://codepen.io/csteur/pen/XMgpad</a></p>
<p>What am I missing to make this layout not overlap in IE11?</p> | 42,764,669 | 4 | 0 | null | 2017-03-13 13:14:22.227 UTC | 5 | 2020-09-08 13:38:54.373 UTC | 2020-08-12 16:56:57.31 UTC | null | 2,756,409 | null | 3,779,593 | null | 1 | 32 | html|css|internet-explorer|flexbox|internet-explorer-11 | 27,812 | <p>It is caused by the 0% in your <code>.flex</code> class. Change it to auto then it should not be a problem:</p>
<pre><code>.flex {
flex: 1 1 auto;
}
</code></pre> |
50,487,283 | How to print an array in comma separated string in angular html | <p>I have to display a parse an array inside a json in HTML:</p>
<pre><code> <p class="personaType">{{cardData.names}}</p>
</code></pre>
<p>where names is </p>
<pre><code>names: Array(5) 0:"Person" 1:"Artist" 2:"Performing Artist" 3:"Production Artist" 4:"Visual Artist" 5:"Intermedia Artist"
</code></pre>
<p><strong>I want to display names as:</strong> </p>
<blockquote>
<p>Person, Artist, Performing Artist, Production Artist</p>
</blockquote>
<p><strong>Right now it is displaying as (without space):</strong></p>
<blockquote>
<p>Person,Artist,Performing Artist,Production Artist</p>
</blockquote>
<p>Is there any inbuilt pipe available in angular which can be used to display such data?</p> | 50,487,323 | 2 | 0 | null | 2018-05-23 11:30:07.03 UTC | 4 | 2020-09-23 16:10:52.753 UTC | 2018-05-23 11:34:28.737 UTC | null | 3,032,338 | null | 3,032,338 | null | 1 | 32 | angular|angular-pipe | 55,217 | <p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join" rel="noreferrer">Array.prototype.join</a> (notice the white space after the comma)</p>
<pre><code><p class="personaType">{{cardData.names.join(', ')}}</p>
</code></pre>
<p>This will print all the elements in the array, separated by a comma and a white space.</p> |
22,057,505 | Bootstrap Collapse - Expand All | <p>I've implemented Bootstrap 3 Collapse. The client wants all of the target blocks to expand when any one of the heading links is clicked. I have tried to implement a modified version of <a href="https://stackoverflow.com/questions/18689845/show-all-bootstrap-accordion">this answer</a>, but can't get it working. </p>
<p>How can I get all target blocks to expand/collapse when any one of them is clicked?</p>
<p>This is the markup:</p>
<pre><code><div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h6 class="panel-title"><a data-toggle="collapse" data-parent="#accordion" href="#collapse{entry_id}">{title}</a></h6>
</div>
</div>
<div id="collapse{entry_id}" class="panel-collapse collapse">
<div class="panel-body">
{technology_body}
</div>
</div>
</div>
</code></pre>
<p>And this is the JS I have attempted:</p>
<pre><code>$('#accordion').on('click', function() {
if($('.collapse:not(.in)')) {
$.collapse("toggle");
}
});
</code></pre> | 22,159,515 | 7 | 0 | null | 2014-02-27 01:53:25.967 UTC | 5 | 2019-11-04 13:58:24.727 UTC | 2017-05-23 12:34:37.007 UTC | null | -1 | null | 498,685 | null | 1 | 17 | twitter-bootstrap-3|collapse | 80,673 | <p>I got some help offline on this question. The script to use is </p>
<pre><code>$('#accordion .panel-default').on('click', function () {
$('#accordion .panel-collapse').collapse('toggle');
});
</code></pre>
<p>and this is the JSFiddle example <a href="http://jsfiddle.net/gtowle/Vq6gt/1/" rel="noreferrer">http://jsfiddle.net/gtowle/Vq6gt/1/</a></p> |
22,066,426 | Python Error - int object has no attribute | <p>The below code gives me the error, other than changing the module that plays the (winsound) sound, this worked fine on Python2.6 on Windows. Not sure where I have gone wrong on this one. This is being run on a Linux box, previously on a Windows machine. The version on Windows was 2.6 and version on Linux is 2.7.3.</p>
<blockquote>
<p>Traceback (most recent call last): File "CallsWaiting.py", line 9,
in
first_time = time.time() AttributeError: 'int' object has no attribute 'time'</p>
</blockquote>
<pre><code>import _mysql
import sys
import time
import os
import pygame
pygame.init()
time = 3
first_time = time.time()
last_time = first_time
while True:
pass
new_time = time.time()
if new_time - last_time > timeout:
last_time = new_time
os.system('cls')
iswaiting = 0
print "Calls Waiting: "
con = _mysql.connect(host='oip-prod', port=3308, user='admin', passwd='1234', db='axpdb')
con.query("select callswaiting from callcenterinformation where date - date(now()) and skillid = 2 order by time desc limit 1;")
result = con.user_result()
iswaiting = int('',join(result.fetch_row() [0]))
print "%s" % \
iswaiting
if iswaiting > 0:
print "Calls are waiting!"
pygame.mixer.init()
sounda = pygame.mixer,Sound("ring2.wav")
sounda.play()
</code></pre> | 22,066,470 | 3 | 1 | null | 2014-02-27 10:58:26.98 UTC | null | 2014-02-27 11:05:43.477 UTC | null | null | null | null | 2,659,890 | null | 1 | 4 | python|python-2.7 | 135,749 | <p>As <code>time = 3</code> is declared as an integer,
<code>time.time</code> doesn't have any sense since time is <code>int</code> variable (that isn't a class but a primitive data type). I suppose that you expected to call <code>time</code> (module) writing <code>time</code> but, since you're redefining it as an integer, this last definition shadows the <code>time</code> module</p>
<p>Change <code>time</code> variable name to something else, like <code>myTime</code> </p>
<h3>Error messages are usefull, you should read them. Often the answer is contained directly into this errors/warning messages</h3> |
25,788,838 | What's the difference between Yii 2 advanced application and basic? | <p>What is the difference between advanced application and basic application in the Yii framework?</p>
<p>Does they have any differences regarding security?</p> | 29,955,365 | 5 | 1 | null | 2014-09-11 13:32:57.097 UTC | 7 | 2017-07-03 22:47:40.777 UTC | 2016-01-29 21:38:12.973 UTC | null | 63,550 | null | 3,955,466 | null | 1 | 47 | yii2 | 26,772 | <p>The following table shows the similarities and differences between the basic and advanced templates:</p>
<p><img src="https://i.stack.imgur.com/1pxmN.png" alt="Comparison"></p>
<p>Source: <a href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-comparison.md">https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-comparison.md</a></p>
<p>As you can see, the main differences are:</p>
<ul>
<li>Advanced template supports front- and back-end apps;</li>
<li>Advanced template is ready to use User model;</li>
<li>Advanced template supports user signup and password restore.</li>
</ul> |
36,516,848 | How to run a .Net Core dll? | <p>I've build my console application using <code>dnu build</code> command on my Mac. The output is <code>MyApp.dll</code>.</p>
<p>As it is not <code>MyApp.exe</code>, how can I execute it on windows, or even on Mac?</p>
<p>The code is:</p>
<pre><code>using System;
class Program
{
public static void Main()
{
Console.WriteLine("Hello from Mac");
}
}
</code></pre> | 36,518,972 | 2 | 4 | null | 2016-04-09 12:36:56.163 UTC | 9 | 2019-08-14 10:08:06.833 UTC | 2017-12-21 19:38:02.677 UTC | null | 102,937 | null | 1,831,530 | null | 1 | 38 | c#|.net-core | 76,682 | <p>Add this to your project.json file:</p>
<pre><code> "compilationOptions": {
"emitEntryPoint": true
},
</code></pre>
<p>It will generate the MyApp.exe on Windows (in bin/Debug) or the executable files on other platforms.</p>
<p><strong>Edit: 30/01/2017</strong></p>
<p>It is not enough anymore. You now have the possibility between Framework-dependent deployment and Self-contained deployment as described <a href="https://docs.microsoft.com/en-us/dotnet/articles/core/deploying/" rel="noreferrer">here</a>.</p>
<p>Short form:</p>
<p><strong>Framework-dependent deployment</strong> (.net core is present on the target system) </p>
<ul>
<li>Run the dll with the dotnet command line utility <code>dotnet MyApp.dll</code></li>
</ul>
<p><strong>Self-contained deployment</strong> (all components including .net core runtime are included in application)</p>
<ul>
<li>Remove <code>"type": "platform"</code> from project.json</li>
<li>Add runtimes section to project.json </li>
<li>Build with target operating system <code>dotnet build -r win7-x64</code></li>
<li>Run generated <code>MyApp.exe</code></li>
</ul>
<p>project.json file:</p>
<pre><code>{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1"
}
}
}
},
"imports": "dnxcore50",
"runtimes": { "win7-x64": {} }
}
</code></pre> |
14,221,907 | VBScript to Launch a website login | <p>I found this script online, I edited most of it. </p>
<p>It is able to enter username, and password on its down but it is not able to click login. </p>
<p>please help me fix
<strong>Here is login forum.</strong></p>
<pre><code>http://desistream.tv/en/index.shtml
</code></pre>
<p><strong>Here is Script</strong> currently it is in IE but I will need to change it open in Google Chrome.</p>
<pre><code>WScript.Quit Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "http://desistream.tv/en/index.shtml"
Wait IE
With IE.Document
.getElementByID("login_username").value = "myusername"
.getElementByID("login_password").value = "mypassword"
.getElementByID("form").submit
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
Sub IE_OnQuit
On Error Resume Next
WScript.StdErr.WriteLine "IE closed before script finished."
WScript.Quit
End Sub
</code></pre> | 14,222,160 | 2 | 0 | null | 2013-01-08 18:45:15.25 UTC | 1 | 2013-09-03 16:53:29.167 UTC | null | null | null | null | 1,512,440 | null | 1 | 4 | vbscript | 65,991 | <p>Here is...</p>
<pre><code>Call Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "http://desistream.tv/en/index.shtml"
Wait IE
With IE.Document
.getElementByID("username").value = "myusername"
.getElementByID("pass").value = "mypassword"
.getElementsByName("frmLogin")(0).Submit
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
</code></pre> |
48,660,606 | Get indexes of a vector of numbers in another vector | <p>Let's suppose we have the following vector:</p>
<pre><code>v <- c(2,2,3,5,8,0,32,1,3,12,5,2,3,5,8,33,1)
</code></pre>
<p>Given a sequence of numbers, for instance <code>c(2,3,5,8)</code>, I am trying to find what the position of this sequence of numbers is in the vector <code>v</code>. The result I expect is something like:</p>
<pre><code>FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE
</code></pre>
<p>I am trying to use <code>which(v == c(2,3,5,8))</code>, but it doesn't give me what I am looking for.</p> | 48,660,951 | 10 | 6 | null | 2018-02-07 09:48:41.793 UTC | 10 | 2022-05-12 11:07:58.993 UTC | 2022-05-11 23:14:47.263 UTC | null | 63,550 | null | 9,326,510 | null | 1 | 33 | r|vector | 6,144 | <p>Using base R you could do the following:</p>
<pre><code>v <- c(2,2,3,5,8,0,32,1,3,12,5,2,3,5,8,33,1)
x <- c(2,3,5,8)
idx <- which(v == x[1])
idx[sapply(idx, function(i) all(v[i:(i+(length(x)-1))] == x))]
# [1] 2 12
</code></pre>
<p>This tells you that the exact sequence appears twice, starting at positions 2 and 12 of your vector <code>v</code>.</p>
<p>It first checks the possible starting positions, i.e. where <code>v</code> equals the first value of <code>x</code> and then loops through these positions to check if the values after these positions also equal the other values of <code>x</code>.</p> |
6,967,297 | getElementsByName() not working? | <p>I have a Javascript function which should update a hidden input field in my form with a number that increments every time the function is called.</p>
<p>It worked originally with <strong>getElementById()</strong> however because I had to redesign my form I cannot use the php function to assign an individual ID to the element so all I have is a unique name for that element.</p>
<p>So instead I decided to use <strong>getElementsByName()</strong> from Javascript to modify the element.</p>
<p>Here is the HTML of that element</p>
<pre><code> <input type="hidden" value="" name="staff_counter">
</code></pre>
<p>This is my Javascript code:</p>
<pre><code>window.onload=function()
{
//function is activated by a form button
var staffbox = document.getElementsByName('staff_counter');
staffbox.value = s;
s++;
}
</code></pre>
<p>I am getting no errors on Firebug when the function is called and the input field is not getting a value given to it.</p>
<p>It was working with getElementById() but why all of a sudden it does not work with getElementsByName()?</p>
<ul>
<li>-I have checked that it is the only unique element in the document.</li>
<li>-I checked for any errors on Firebug when activating the function</li>
</ul>
<p>Here is the code I use from Codeigniter to make the element</p>
<pre><code>// staff_counter is name and the set_value function sets the value from what is
//posted so if the validation fails and the page is reloaded the form element does
// not lose its value
echo form_hidden('staff_counter', set_value('staff_counter'));
</code></pre>
<p>Thanks</p> | 6,967,318 | 2 | 1 | null | 2011-08-06 13:59:50.237 UTC | 3 | 2018-04-07 09:00:40.583 UTC | null | null | null | null | 859,615 | null | 1 | 22 | javascript|html|codeigniter|getelementsbyname | 75,789 | <p><code>document.getElementsByName()</code> returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F" rel="noreferrer">NodeList</a>, so you have to access it by an index: <code>document.getElementsByName('staff_counter')[0]</code> (depending on how many of these you have).</p>
<p>You also have access to a <code>length</code> property to check how many Elements were matched.</p> |
6,959,462 | In Node.js, reading a directory of .html files and searching for element attributes inside them? | <p>I can't even begin to think about how this would be done. Basically, imagine a folder and it has a static website in it. It has all the images, styles and html files etc. With my Node application, I want to look inside this folder, get just the .html files only and then pick just the .html files that have the attribute 'data-template="home"' inside them.</p>
<p>I know this seems a little odd maybe, but it's for a project that requires the user to upload their static website files and then my Node app does things to them files.</p>
<p>Anyhow, was just curious about iterating over certain filetypes and then looking inside them... Any help with approaching this would really help me.</p>
<p>Many thanks, James</p> | 6,960,795 | 2 | 0 | null | 2011-08-05 16:23:55.123 UTC | 12 | 2015-10-13 21:25:36.017 UTC | null | null | null | null | 86,128 | null | 1 | 23 | javascript|html|file|node.js|file-type | 28,949 | <p>This piece of code will scan for all files in a directory, then read the contents of <code>.html</code> files and then look for a string <code>data-template="home"</code> in them.</p>
<pre><code>var fs = require('fs');
fs.readdir('/path/to/html/files', function(err, files) {
files
.filter(function(file) { return file.substr(-5) === '.html'; })
.forEach(function(file) { fs.readFile(file, 'utf-8', function(err, contents) { inspectFile(contents); }); });
});
function inspectFile(contents) {
if (contents.indexOf('data-template="home"') != -1) {
// do something
}
}
</code></pre>
<p>If you need more flexibility, you could also use the <code>cheerio</code> module to look for an element in the html file with that attribute:</p>
<pre><code>var cheerio = require('cheerio');
function inspectFile(contents) {
var $ = cheerio.load(contents);
if ($('html[data-template="home"]').length) {
// do something
}
}
</code></pre> |
6,959,930 | Android: Need to record mic input | <p>Is there a way to record mic input in android while it is being process for playback/preview in real time? I tried to use <code>AudioRecord</code> and <code>AudioTrack</code> to do this but the problem is that my device cannot play the recorded audio file. Actually, any android player application cannot play the recorded audio file.</p>
<p>On the other hand, Using <code>Media.Recorder</code> to record generates a good recorded audio file that can be played by any player application. But the thing is that I cannot make a preview/palyback while recording the mic input in real time.</p> | 7,028,963 | 2 | 4 | null | 2011-08-05 17:01:33.097 UTC | 30 | 2021-04-08 11:38:21.007 UTC | 2021-04-08 11:38:21.007 UTC | null | 703,252 | null | 703,252 | null | 1 | 42 | android|audio|audio-recording|audiorecord | 41,058 | <p>To record and play back audio in (almost) real time you can start a separate thread and use an <code>AudioRecord</code> and an <code>AudioTrack</code>.</p>
<p>Just be careful with feedback. If the speakers are turned up loud enough on your device, the feedback can get pretty nasty pretty fast.</p>
<pre><code>/*
* Thread to manage live recording/playback of voice input from the device's microphone.
*/
private class Audio extends Thread
{
private boolean stopped = false;
/**
* Give the thread high priority so that it's not canceled unexpectedly, and start it
*/
private Audio()
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
start();
}
@Override
public void run()
{
Log.i("Audio", "Running Audio Thread");
AudioRecord recorder = null;
AudioTrack track = null;
short[][] buffers = new short[256][160];
int ix = 0;
/*
* Initialize buffer to hold continuously recorded audio data, start recording, and start
* playback.
*/
try
{
int N = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
recorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10);
track = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10, AudioTrack.MODE_STREAM);
recorder.startRecording();
track.play();
/*
* Loops until something outside of this thread stops it.
* Reads the data from the recorder and writes it to the audio track for playback.
*/
while(!stopped)
{
Log.i("Map", "Writing new data to buffer");
short[] buffer = buffers[ix++ % buffers.length];
N = recorder.read(buffer,0,buffer.length);
track.write(buffer, 0, buffer.length);
}
}
catch(Throwable x)
{
Log.w("Audio", "Error reading voice audio", x);
}
/*
* Frees the thread's resources after the loop completes so that it can be run again
*/
finally
{
recorder.stop();
recorder.release();
track.stop();
track.release();
}
}
/**
* Called from outside of the thread in order to stop the recording/playback loop
*/
private void close()
{
stopped = true;
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>The audio is not really recording to a file. The <code>AudioRecord</code> object encodes the audio as <a href="http://en.wikipedia.org/wiki/PCM">16 bit PCM data</a> and places it in a buffer. Then the <code>AudioTrack</code> object reads the data from that buffer and plays it through the speakers. There is no file on the SD card that you will be able to access later.</p>
<p>You can't read and write a file from the SD card at the same time to get playback/preview in real time, so you have to use buffers.</p> |
7,146,028 | Javascript: Detect when an alert box is OK'ed and/or closed | <p>How can I detect when a javascript alert box is OK'ed and/or closed?</p> | 7,146,074 | 3 | 3 | null | 2011-08-22 10:22:35.96 UTC | 3 | 2014-04-04 21:01:45.847 UTC | 2014-04-04 21:01:45.847 UTC | null | 445,131 | null | 364,312 | null | 1 | 49 | javascript|jquery | 65,085 | <p>Since <code>alert</code> is blocking:</p>
<pre><code>alert('foo');
function_to_call_when_oked_or_closed();
</code></pre>
<p>Just put the function after the call to <code>alert</code>.</p> |
7,631,722 | CSS :first-letter not working | <p>I'm trying to apply CSS styles to some HTML snippets that were generated from a Microsoft Word document. The HTML that Word generated is fairly atrocious, and includes a lot of inline styles. It goes something like this:</p>
<pre><code><html>
<head></head>
<body>
<center>
<p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span
style='font-size:12.0pt;line-height:115%;font-family:"Times New Roman"'>Title text goes here<o:p></o:p></span></b></p>
<p class=MsoNormal style='margin-left:18.0pt;line-height:150%'><span
style='font-size:12.0pt;line-height:150%;font-family:"Times New Roman"'>Content text goes here.<o:p></o:p></span></p>
</body>
</html>
</code></pre>
<p>...and very simply, I would like to style the first letter of the title section. It just needs to be larger and in a different font. To do this I am trying to use the <code>:first-letter</code> selector, with something kind of like:</p>
<pre><code>p b span:first-letter {
font-size: 500px !important;
}
</code></pre>
<p>But it doesn't seem to be working. Here's a fiddle demonstrating this:</p>
<p><a href="http://jsfiddle.net/KvGr2/" rel="noreferrer">http://jsfiddle.net/KvGr2/</a></p>
<p>Any ideas what is wrong/how to get the first letter of the title section styled correctly? I can make minor changes to the markup (like adding a wrapper div around things), though not without some difficulty.</p> | 7,631,782 | 3 | 0 | null | 2011-10-03 06:35:25.937 UTC | 13 | 2020-08-11 07:27:25.33 UTC | 2011-10-03 08:20:58.367 UTC | null | 609,251 | null | 609,251 | null | 1 | 93 | html|css | 71,360 | <p><code>::first-letter</code> does not work on <strong>inline</strong> elements such as a <code>span</code>. <code>::first-letter</code> works on <strong>block</strong> elements such as a paragraph, table caption, table cell, list item, or those with their <code>display</code> property set to <code>inline-block</code>.</p>
<p>Therefore it's better to apply <code>::first-letter</code> to a <code>p</code> instead of a <code>span</code>.</p>
<pre><code>p::first-letter {font-size: 500px;}
</code></pre>
<p>or if you want a <code>::first-letter</code> selector in a <code>span</code> then write it like this:</p>
<pre><code>p b span::first-letter {font-size: 500px !important;}
span {display:block}
</code></pre>
<p>MDN <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter" rel="noreferrer">provides the rationale</a> for this non-obvious behaviour:</p>
<blockquote>
<p>The <code>::first-letter</code> CSS pseudo-element selects the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line.</p>
<p>...</p>
<p>A first line has only meaning in a block-container box, therefore the <code>::first-letter</code> pseudo-element has only an effect on elements with a <code>display</code> value of <code>block</code>, <code>inline-block</code>, <code>table-cell</code>, <code>list-item</code> or <code>table-caption</code>. In all other cases, <code>::first-letter</code> has no effect.</p>
</blockquote>
<p><strong>Another odd case</strong>(apart from not working on inline items) is if you use <code>:before</code> the <code>:first-letter</code> will apply to the before not the actual first letter see <a href="https://codepen.io/T04435/pen/poyjyMb" rel="noreferrer">codepen</a></p>
<h2>Examples</h2>
<ul>
<li><a href="http://jsfiddle.net/sandeep/KvGr2/9/" rel="noreferrer">http://jsfiddle.net/sandeep/KvGr2/9/</a></li>
<li><a href="http://krijnhoetmer.nl/stuff/css/first-letter-inline-block/" rel="noreferrer">http://krijnhoetmer.nl/stuff/css/first-letter-inline-block/</a></li>
</ul>
<h2>References</h2>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter</a>
<a href="http://reference.sitepoint.com/css/pseudoelement-firstletter" rel="noreferrer">http://reference.sitepoint.com/css/pseudoelement-firstletter</a></p> |
7,578,917 | Test if a variable is defined in javascript? | <p>How should I test if a variable is defined? </p>
<pre><code>if //variable is defined
//do this
else
//do this
</code></pre> | 7,578,941 | 4 | 0 | null | 2011-09-28 05:56:06.953 UTC | 5 | 2021-02-11 02:43:14.977 UTC | 2013-09-12 07:43:24.477 UTC | null | 949,845 | null | 949,845 | null | 1 | 33 | javascript | 52,785 | <pre><code>if (typeof variable !== 'undefined') {
// ..
}
else
{
// ..
}
</code></pre>
<p>find more explanation here:</p>
<p><a href="https://stackoverflow.com/questions/2281633/javascript-isset-equivalent">JavaScript isset() equivalent</a></p> |
7,082,449 | EXISTS vs JOIN and use of EXISTS clause | <p>Below is the code sample: </p>
<pre><code>CREATE TABLE #titles(
title_id varchar(20),
title varchar(80) NOT NULL,
type char(12) NOT NULL,
pub_id char(4) NULL,
price money NULL,
advance money NULL,
royalty int NULL,
ytd_sales int NULL,
notes varchar(200) NULL,
pubdate datetime NOT NULL
)
GO
insert #titles values ('1', 'Secrets', 'popular_comp', '1389', $20.00, $8000.00, 10, 4095,'Note 1','06/12/94')
insert #titles values ('2', 'The', 'business', '1389', $19.99, $5000.00, 10, 4095,'Note 2','06/12/91')
insert #titles values ('3', 'Emotional', 'psychology', '0736', $7.99, $4000.00, 10, 3336,'Note 3','06/12/91')
insert #titles values ('4', 'Prolonged', 'psychology', '0736', $19.99, $2000.00, 10, 4072,'Note 4','06/12/91')
insert #titles values ('5', 'With', 'business', '1389', $11.95, $5000.00, 10, 3876,'Note 5','06/09/91')
insert #titles values ('6', 'Valley', 'mod_cook', '0877', $19.99, $0.00, 12, 2032,'Note 6','06/09/91')
insert #titles values ('7', 'Any?', 'trad_cook', '0877', $14.99, $8000.00, 10, 4095,'Note 7','06/12/91')
insert #titles values ('8', 'Fifty', 'trad_cook', '0877', $11.95, $4000.00, 14, 1509,'Note 8','06/12/91')
GO
CREATE TABLE #sales(
stor_id char(4) NOT NULL,
ord_num varchar(20) NOT NULL,
ord_date datetime NOT NULL,
qty smallint NOT NULL,
payterms varchar(12) NOT NULL,
title_id varchar(80)
)
GO
insert #sales values('1', 'QA7442.3', '09/13/94', 75, 'ON Billing','1')
insert #sales values('2', 'D4482', '09/14/94', 10, 'Net 60', '1')
insert #sales values('3', 'N914008', '09/14/94', 20, 'Net 30', '2')
insert #sales values('4', 'N914014', '09/14/94', 25, 'Net 30', '3')
insert #sales values('5', '423LL922', '09/14/94', 15, 'ON Billing','3')
insert #sales values('6', '423LL930', '09/14/94', 10, 'ON Billing','2')
SELECT title, price
FROM #titles
WHERE EXISTS
(SELECT *
FROM #sales
WHERE #sales.title_id = #titles.title_id
AND qty >30)
SELECT t.title, t.price
FROM #titles t
inner join #sales s on t.title_id = s.title_id
where s.qty >30
</code></pre>
<p>I want to know what is the difference between the above 2 queries which gives the same result.Also want to know the purpose of EXISTS keyword and where exactly to use?</p> | 7,082,510 | 4 | 15 | null | 2011-08-16 17:34:04.003 UTC | 29 | 2020-04-24 22:40:01.913 UTC | 2020-01-07 12:35:07.613 UTC | null | 4,196,578 | null | 754,713 | null | 1 | 73 | sql|sql-server|sql-server-2005|sql-server-2008 | 121,309 | <p><strong><code>EXISTS</code> is used to return a boolean value, <code>JOIN</code> returns a whole other table</strong></p>
<p><code>EXISTS</code> is only used to test if a subquery returns results, and short circuits as soon as it does. <code>JOIN</code> is used to extend a result set by combining it with additional fields from another table to which there is a relation.</p>
<p>In your example, the queries are semantically equivalent.</p>
<p>In general, use <code>EXISTS</code> when:</p>
<ul>
<li>You don't need to return data from the related table</li>
<li>You have dupes in the related table (<code>JOIN</code> can cause duplicate rows if values are repeated)</li>
<li>You want to check existence (use instead of <code>LEFT OUTER JOIN...NULL</code> condition)</li>
</ul>
<p>If you have proper indexes, most of the time the <code>EXISTS</code> will perform identically to the <code>JOIN</code>. The exception is on very complicated subqueries, where it is normally quicker to use <code>EXISTS</code>.</p>
<p>If your <code>JOIN</code> key is not indexed, it may be quicker to use <code>EXISTS</code> but you will need to test for your specific circumstance.</p>
<p><code>JOIN</code> syntax is easier to read and clearer normally as well.</p> |
23,993,111 | Mac + Uno + avrdude: stk500_recv(): programmer is not responding | <p>I'm trying to upload <code>.hex</code> file to Arduino. I don't have any problems with uploading code through an IDE (like blink example or any other). The port and board are correct.</p>
<p>So, the problem appears when I try to upload</p>
<pre><code>avrdude -pm328p -carduino -P/dev/tty.usbmodemfd121 -b57600 -D -Uflash:w:grbl_v0_8c_atmega328p_16mhz_9600.hex -v -v -v -v
avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2014 Joerg Wunsch
System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
User configuration file is "/Users/Mikhail/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
Using Port : /dev/tty.usbmodemfd121
Using Programmer : arduino
Overriding Baud Rate : 57600
avrdude: Send: 0 [30] [20]
avrdude: Send: 0 [30] [20]
avrdude: Send: 0 [30] [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
</code></pre>
<p>What I tried:</p>
<ul>
<li>I have 4 Uno's at the table (original + free versions), the same issue.</li>
<li>I have installed newest drivers from <a href="http://ftdichip.com/Drivers/VCP.htm" rel="nofollow noreferrer">here</a>, tried with and without them. </li>
<li>tried with avrdude which comes with Arduino IDE (1.0.5 and nightly builds) and newest avrdude v.6.1 <code>brew install avrdude</code></li>
<li>different baud rates down to 9600</li>
<li>tried to press reset after bytes are sent like suggested <a href="https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi">here</a></li>
</ul> | 28,888,378 | 8 | 1 | null | 2014-06-02 11:08:41.377 UTC | 2 | 2020-04-27 00:54:26.95 UTC | 2019-06-04 18:52:28.027 UTC | null | 1,011,722 | null | 2,716,092 | null | 1 | 12 | arduino|avrdude|arduino-uno | 41,249 | <p>Successfully solved with <a href="https://github.com/paulkaplan/HexUploader/wiki/Using-HexUploader" rel="nofollow noreferrer">Hex Uploader</a>.</p>
<p>It is created for flashing <code>.hex</code> files to Arduino for Mac OS.</p>
<p>Options for other OS are described in the <a href="https://github.com/grbl/grbl/wiki/Flashing-Grbl-to-an-Arduino" rel="nofollow noreferrer">grbl documentation</a>.</p> |
8,348,982 | MVC Pass ViewBag to Controller | <p>I have a Viewbag that is a list that I am passing from the Controller to the View.
The Viewbag is a list of 10 records in my case. Once in the view, if the user clicks on save, I like to pass the content of the View to the [HttpPost] Create controller so that I can create records that are in the Viewbag. I am on sure how to do this. I have done the creation of a new record for 1 item but how do I do it for multiple records. </p> | 8,357,738 | 1 | 0 | null | 2011-12-01 22:08:22.27 UTC | 1 | 2015-11-06 23:31:30.99 UTC | 2015-11-06 23:31:30.99 UTC | null | 304,461 | null | 996,431 | null | 1 | 7 | c#|asp.net-mvc|model-view-controller|razor|viewbag | 44,415 | <p>Here is a quick example of using the ViewBag. I would recommend switching and using a model to do your binding. Here is a great article on it. <a href="http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx">Model Binding</a></p>
<p>Get Method:</p>
<pre><code> public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
List<string> items = new List<string>();
items.Add("Product1");
items.Add("Product2");
items.Add("Product3");
ViewBag.Items = items;
return View();
}
</code></pre>
<p>Post Method</p>
<pre><code> [HttpPost]
public ActionResult Index(FormCollection collection)
{
//only selected prodcuts will be in the collection
foreach (var product in collection)
{
}
return View();
}
</code></pre>
<p>Html:</p>
<pre><code>@using (Html.BeginForm("Index", "Home"))
{
foreach (var p in ViewBag.Items)
{
<label for="@p">@p</label>
<input type="checkbox" name="@p" />
}
<div>
<input id='btnSubmit' type="submit" value='submit' />
</div>
}
</code></pre> |
21,575,253 | ClassCastException: java.util.Date cannot be cast to java.sql.Date | <p>Hello my code is throwing <code>ClassCastException</code>.
The StackTrace is showing :</p>
<pre><code>java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
at com.affiliate.DAO.AffiliateDAO.insertAffiliate(AffiliateDAO.java:48)
</code></pre>
<p>ie @ <strong><em>ps.setDate(6, (Date) affiliate.getDate());</em></strong> in DAO</p>
<p><strong>Below is my servlet:</strong></p>
<pre><code> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Affiliate af= new Affiliate();
af.setFisrtName(request.getParameter("txtFname"));
af.setLastName(request.getParameter("txtLname"));
af.setGender(request.getParameter("txtGender"));
af.setCategory(request.getParameter("txtCategory"));
String dob=(request.getParameter("txtDob"));
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date;
try {
date = (Date)formatter.parse(dob);
af.setDate(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
af.setAge(Integer.parseInt(request.getParameter("txtAge")));
af.setAddress(request.getParameter("txtAddr"));
af.setCountry("India");
af.setState(request.getParameter("txtState"));
af.setCity(request.getParameter("txtCity"));
af.setPinCode(Integer.parseInt(request.getParameter("txtPin")));
af.setEmailId(request.getParameter("txtEmail"));
af.setStd(Integer.parseInt(request.getParameter("txtStd")));
af.setContactNo(Integer.parseInt(request.getParameter("txtPhone")));
af.setMobileNo(Long.parseLong(request.getParameter("txtMobile"),10));
AffiliateService afs=new AffiliateService();
**afs.createAffiliate(af);**
}
</code></pre>
<p>Below is my DAO:</p>
<pre><code>public void insertAffiliate(Affiliate affiliate){
String sql="INSERT INTO REGISTER " +"(id,FisrtName,LastName,Gender,Category,DateOfBirth,Age,Address,Country,State,City,PinCode,EmailId,Std,ContactNo,MobileNo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Connection conn = null;
try {
**conn = dataSource.createConnection();**
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, affiliate.getId());
ps.setString(2, affiliate.getFisrtName());
ps.setString(3, affiliate.getLastName());
ps.setString(4,affiliate.getGender());
ps.setString(5, affiliate.getCategory());
***ps.setDate(6, (Date) affiliate.getDate());***
ps.setInt(7, affiliate.getAge());
ps.setString(8, affiliate.getAddress());
ps.setString(9,affiliate.getCountry());
ps.setString(10,affiliate.getState());
ps.setString(11, affiliate.getCity());
ps.setInt(12, affiliate.getPinCode());
ps.setString(13, affiliate.getEmailId());
ps.setInt(14,affiliate.getStd());
ps.setInt(15, affiliate.getContactNo());
ps.setLong(16, affiliate.getMobileNo());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
</code></pre>
<p>Below is my DTO:</p>
<pre><code>public class Affiliate {
@NotNull
@Past
Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
</code></pre>
<p>Please help me in this regard</p> | 21,575,363 | 4 | 2 | null | 2014-02-05 10:57:18.257 UTC | 2 | 2016-01-17 13:04:35.867 UTC | 2014-02-05 10:59:42.45 UTC | null | 1,173,495 | null | 3,222,718 | null | 1 | 2 | java|sql | 69,231 | <p>As the <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setDate%28int,%20java.sql.Date%29" rel="noreferrer">docs</a> say, the <code>Date</code> parameter in the <code>setDate()</code> of <code>PreparedStatement</code> takes a Date object of the type <code>java.sql.Date</code>. But you seemed to have used <code>java.util.Date</code> object in your <code>Affiliate</code> class.</p>
<p>And that is why you get the <code>ClassCastException: java.util.Date cannot be cast to java.sql.Date</code>.</p>
<p>To fix this, you need to either change the type of <code>Date</code> object in your <code>Affiliate</code> class to <code>java.sql.Date</code> or do this</p>
<pre><code>ps.setDate(6, new java.sql.Date(affiliate.getDate().getTime()));
</code></pre> |
1,849,245 | Is there an enhanced interpreter toploop for OCaml? | <p>Python has <a href="http://ipython.scipy.org/" rel="noreferrer">IPython</a>.. does OCaml have anything similar?</p>
<p>I'd very much like to have command history, although other features would be nice too. I've read that I could get command history by running it in Emacs, but I don't use Emacs..</p> | 1,849,304 | 4 | 0 | null | 2009-12-04 19:47:44.55 UTC | 9 | 2015-10-15 11:46:58.86 UTC | 2015-10-15 11:46:58.86 UTC | null | 1,315,131 | null | 149,330 | null | 1 | 26 | ocaml|ledit | 3,257 | <p><a href="http://utopia.knoware.nl/~hlub/uck/rlwrap/" rel="noreferrer">rlwrap</a> gives you readline features (history, editing commands, etc). Also, <a href="http://www.camlcity.org/archive/programming/findlib.html" rel="noreferrer">Findlib</a> adds some functionality, see the <a href="http://projects.camlcity.org/projects/dl/findlib-1.2.1/doc/guide-html/quickstart.html" rel="noreferrer">quickstart</a> for examples.</p> |
10,421,806 | about Oracle parallel insert performance | <p>I have an sql like this:</p>
<pre><code>Insert into A
Select * from B;
</code></pre>
<p>Now I want it to run in parallel. My question is to parallelize the insert or select or both? See the following sqls, can you tell me which one is correct or which one has best performance. I don't have dba permission, so I cann't check its execute plan.</p>
<p>1) <code>Insert /*+ parallel(A 6) */ into A select * from B;</code></p>
<p>2) <code>Insert into A select/*+ parallel(B 6) */ * from B;</code></p>
<p>3) <code>Insert /*+ parallel(A 6) */ into A select /*+ parallel(B 6) */ * from B;</code></p>
<p>Thank you!</p> | 10,424,916 | 2 | 2 | null | 2012-05-02 21:11:53.58 UTC | 7 | 2012-05-03 09:45:27.97 UTC | null | null | null | null | 1,005,416 | null | 1 | 9 | oracle|oracle10g|oracle11g | 38,663 | <p>Parallelizing both the <code>INSERT</code> and the <code>SELECT</code> is the fastest.</p>
<p>(If you have a large enough amount of data, you have a decent server, everything is configured sanely, etc.)</p>
<p>You'll definitely want to test it yourself, especially to find the optimal degree of parallelism. There are a lot of myths surrounding Oracle parallel execution, and even the manual is sometimes <a href="https://stackoverflow.com/a/9731552/409172">horribly wrong</a>.</p>
<p>On 11gR2, I would recommend you run your statement like this:</p>
<pre><code>alter session enable parallel dml;
insert /*+ append parallel(6) */ into A select * from B;
</code></pre>
<ol>
<li>You always want to enable parallel dml first.</li>
<li><code>parallel(6)</code> uses <a href="http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABHFDDH" rel="nofollow noreferrer">statement-level parallelism</a>, instead of object-level parallelism. This is an 11gR2 feature that allows you to easily run everything in parallel witout having to worry about object aliases or access methods. For 10G you'll have to use multiple hints.</li>
<li>Normally the <code>append</code> hint isn't necessary. If your DML runs in parallel, it will automatically use direct-path inserts. However, if your statement gets downgraded to serial, for example if there are no parallel servers available, then the <code>append</code> hint can make a big difference. </li>
</ol> |
28,432,686 | selectableItemBackground as item in layer-list | <p>I've copied a file from the Google IO Schedule app source (<a href="https://github.com/google/iosched">https://github.com/google/iosched</a>) namely</p>
<p><strong>selected_navdrawer_item_background.xml</strong></p>
<pre><code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/backgroundColor">
<shape>
<solid android:color="#12000000" />
</shape>
</item>
<item android:drawable="?android:selectableItemBackground"/>
</layer-list>
</code></pre>
<p>I want to use this to highlight the currently selected item in a NavigationDrawer. My problem is, when I launch my app, it throws an exception.</p>
<p>This is the important line I think.</p>
<pre><code>caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #22:
<item> tag requires a 'drawable' attribute or child tag defining a drawable
</code></pre>
<p>Line # 22 is this one</p>
<pre><code><item android:drawable="?android:selectableItemBackground"/>
</code></pre>
<p>I don't know what the problem is, I copied this over from source without adjusting it. It's working fine in their app.</p>
<p>I tried to change <code>?android:selectableItemBackground</code> to <code>?attr/selectableItemBackground</code>, but it gives me the same exception.
I can't seem to find any other suggested solutions.</p>
<p>If anyone knows what's causing this, please help me.</p> | 35,976,895 | 1 | 3 | null | 2015-02-10 13:17:44.983 UTC | 4 | 2016-03-13 22:50:46.443 UTC | null | null | null | null | 4,498,224 | null | 1 | 28 | android|android-xml|android-drawable | 3,427 | <p>It works but from api <strong>v21</strong>. So, you can go ahead and use it on devices with <strong>Android Lollipop</strong> and newer. If you want support older system versions you can put this xml into <strong>drawable-v21</strong> folder and prepare new xml in drawable folder with the same name.
For example: </p>
<p><strong>drawable/selected_navdrawer_item_background.xml</strong></p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#12000000" />
</shape>
</code></pre>
<p>Google IO app does the same thing:
<a href="https://github.com/google/iosched/blob/d7bab489f24cae9d33f84295e0820ebbb3f3ad4c/android/src/main/res/drawable/selected_navdrawer_item_background.xml">here is file from drawable folder</a> and
<a href="https://github.com/google/iosched/blob/d7bab489f24cae9d33f84295e0820ebbb3f3ad4c/android/src/main/res/drawable-v21/selected_navdrawer_item_background.xml/">here is file from drawable-v21 folder</a></p> |
26,257,268 | Click events on Pie Charts in Chart.js | <p>I've got a question regard Chart.js. </p>
<p>I've drawn multiple piecharts using the documentation provided. I was wondering if on click of a certain slice of one of the charts, I can make an ajax call depending on the value of that slice? </p>
<p>For example, if this is my <code>data</code></p>
<pre><code>var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
],
</code></pre>
<p>is it possible for me to click on the <code>Red</code> labelled slice and call a url of the following form:
<code>example.com?label=red&value=300</code>? If yes, how do I go about this?</p> | 26,258,671 | 12 | 1 | null | 2014-10-08 12:46:59.13 UTC | 31 | 2021-01-23 19:43:20.75 UTC | null | null | null | null | 1,411,975 | null | 1 | 83 | javascript|jquery|charts|chart.js | 199,883 | <p><strong>Update:</strong> As @Soham Shetty comments, <code>getSegmentsAtEvent(event)</code> only works for 1.x and for 2.x <a href="https://www.chartjs.org/docs/latest/developers/api.html#getelementsatevente" rel="noreferrer"><code>getElementsAtEvent</code></a> should be used.</p>
<blockquote>
<p><strong>.getElementsAtEvent(e)</strong></p>
<p>Looks for the element under the event point, then returns all elements
at the same data index. This is used internally for 'label' mode
highlighting.</p>
<p>Calling <code>getElementsAtEvent(event)</code> on your Chart instance passing an
argument of an event, or jQuery event, will return the point elements
that are at that the same position of that event.</p>
<pre><code>canvas.onclick = function(evt){
var activePoints = myLineChart.getElementsAtEvent(evt);
// => activePoints is an array of points on the canvas that are at the same position as the click event.
};
</code></pre>
</blockquote>
<p>Example: <a href="https://jsfiddle.net/u1szh96g/208/" rel="noreferrer">https://jsfiddle.net/u1szh96g/208/</a></p>
<hr>
<p><em>Original answer (valid for Chart.js 1.x version):</em></p>
<p>You can achieve this using <code>getSegmentsAtEvent(event)</code> </p>
<blockquote>
<p>Calling <code>getSegmentsAtEvent(event)</code> on your Chart instance passing an
argument of an event, or jQuery event, will return the segment
elements that are at that the same position of that event.</p>
</blockquote>
<p>From: <a href="http://www.chartjs.org/docs/#doughnut-pie-chart-prototype-methods" rel="noreferrer">Prototype Methods</a></p>
<p>So you can do:</p>
<pre><code>$("#myChart").click(
function(evt){
var activePoints = myNewChart.getSegmentsAtEvent(evt);
/* do something */
}
);
</code></pre>
<p>Here is a full working example:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
$("#myChart").click(
function(evt){
var activePoints = myNewChart.getSegmentsAtEvent(evt);
var url = "http://example.com/?label=" + activePoints[0].label + "&value=" + activePoints[0].value;
alert(url);
}
);
}
);
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>
</code></pre> |
36,352,033 | How to make HTTPS GET call with certificate in Rest-Assured java | <p>How can I make a GET call using <a href="https://github.com/jayway/rest-assured">Rest-Assured</a> in java to a endpoint which requires certificate. I have certificate as <code>.pem</code> format. In PEM file there is certificate and private key. </p> | 37,436,519 | 11 | 8 | null | 2016-04-01 08:56:44.657 UTC | 5 | 2021-06-06 09:01:03.78 UTC | null | null | null | null | 1,118,854 | null | 1 | 21 | java|certificate|rest-assured | 80,952 | <p>Got it working with following code -</p>
<pre><code>KeyStore keyStore = null;
SSLConfig config = null;
try {
keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(
new FileInputStream("certs/client_cert_and_private.p12"),
password.toCharArray());
} catch (Exception ex) {
System.out.println("Error while loading keystore >>>>>>>>>");
ex.printStackTrace();
}
if (keyStore != null) {
org.apache.http.conn.ssl.SSLSocketFactory clientAuthFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, password);
// set the config in rest assured
config = new SSLConfig().with().sslSocketFactory(clientAuthFactory).and().allowAllHostnames();
RestAssured.config = RestAssured.config().sslConfig(config);
RestAssured.given().when().get("/path").then();
</code></pre> |
36,627,337 | POST http://localhost:3000/ 404 (Not Found) | <p>I'm working on web file browser with upload function. I'm using <a href="https://github.com/nervgh/angular-file-upload" rel="noreferrer">Angular File Upload</a> directive and <a href="https://github.com/arvindr21/fileBrowserApp" rel="noreferrer">angular web file browser</a>.</p>
<p>First off I've downloaded file web browser and configured it.</p>
<p>Second I've downloaded file upload directive and did everything step by step and my page works perfect</p>
<p><a href="https://i.stack.imgur.com/PWYds.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PWYds.png" alt="enter image description here"></a></p>
<p>but when I'm trying to upload something I'm getting </p>
<blockquote>
<p>FileUploader.js:479 POST <a href="http://localhost:3000/" rel="noreferrer">http://localhost:3000/</a> 404 (Not Found)</p>
</blockquote>
<p>I understand that FileUploader.js can't find upload.php file, but I put it to the root folder and provided path:</p>
<pre><code> var uploader = $scope.uploader = new FileUploader({
url: 'upload.php'
});
</code></pre>
<p>this is how it looks: </p>
<p><a href="https://i.stack.imgur.com/4Czn7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4Czn7.png" alt="enter image description here"></a></p>
<p>angular/app.js:</p>
<pre><code>(function() {
'use strict';
window.app = angular.module('fileBrowserApp', ['ngRoute', 'jsTree.directive', 'angularFileUpload']).
config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '../partials/home.html',
controller: 'HomeCtrl'
}).
otherwise({
redirectTo: '/home'
});
}
]);
window.app.directive('attachable', function(FileUploader) {
return {
restrict: 'E',
replace: true,
templateUrl:'../partials/upload.html',
link: function(scope, element, attrs) {
scope.uploader = new FileUploader();
}
}
})
;
}());
</code></pre>
<p>server/app.js</p>
<pre><code> (function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs-extra');
var routes = require('./routes.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
}());
</code></pre>
<p>angular/controller.js</p>
<pre><code>(function() {
'use strict';
app.controller('HomeCtrl', ['$scope', 'FetchFileFactory', 'FileUploader',
function($scope, FetchFileFactory, FileUploader, $upload) {
// ****** file upload *******
var uploader = $scope.uploader = new FileUploader({
url: '/upload',
success: function (fileItem) {
$scope.alerts.push({
type: 'success',
msg: '"' + fileItem.file.name + '" uploaded'
});
},
error: function (fileItem) {
$scope.alerts.push({
type: 'danger',
msg: '"' + fileItem.file.name + '" failed'
});
}
});
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function(fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function(addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function(item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function(fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function(progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function(fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function(fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function(fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function(fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function() {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
// ****** file browser *******
$scope.fileViewer = 'Please select a file to view its contents';
$scope.tree_core = {
multiple: false, // disable multiple node selection
check_callback: function (operation, node, node_parent, node_position, more) {
// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
// in case of 'rename_node' node_position is filled with the new node name
if (operation === 'move_node') {
return false; // disallow all dnd operations
}
return true; // allow all other operations
}
};
$scope.nodeSelected = function(e, data) {
var _l = data.node.li_attr;
if (_l.isLeaf) {
FetchFileFactory.fetchFile(_l.base).then(function(data) {
var _d = data.data;
if (typeof _d == 'object') {
//http://stackoverflow.com/a/7220510/1015046//
_d = JSON.stringify(_d, undefined, 2);
}
$scope.fileViewer = _d;
});
} else {
//http://jimhoskins.com/2012/12/17/angularjs-and-apply.html//
$scope.$apply(function() {
$scope.fileViewer = 'Please select a file to view its contents';
});
}
};
}
]);
}());
</code></pre>
<p>Upload.html:</p>
<pre><code><div ng-if="uploader">
<div class="container">
<div class="row">
<div class="col-md-3">
<h3>Select files</h3>
<input type="file" nv-file-select="" uploader="uploader"/>
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader.queue.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploader.isHTML5">Size</th>
<th ng-show="uploader.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
<div>
<div>
Queue progress:
<div class="progress" style="">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.progress + '%' }"></div>
</div>
</div>
<!--<button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">-->
<!--<span class="glyphicon glyphicon-upload"></span> Upload all-->
<!--</button>-->
<!--<button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">-->
<!--<span class="glyphicon glyphicon-ban-circle"></span> Cancel all-->
<!--</button>-->
<!--<button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">-->
<!--<span class="glyphicon glyphicon-trash"></span> Remove all-->
<!--</button>-->
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>route.js</p>
<pre><code>(function() {
'use strict';
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
/* Serve the Tree */
router.get('/api/tree', function(req, res) {
var _p;
if (req.query.id == 1) {
_p = path.resolve(__dirname, '..', 'node_modules');
processReq(_p, res);
} else {
if (req.query.id) {
_p = req.query.id;
processReq(_p, res);
} else {
res.json(['No valid data found']);
}
}
});
/* Serve a Resource */
router.get('/api/resource', function(req, res) {
res.send(fs.readFileSync(req.query.resource, 'UTF-8'));
});
function processReq(_p, res) {
var resp = [];
fs.readdir(_p, function(err, list) {
for (var i = list.length - 1; i >= 0; i--) {
resp.push(processNode(_p, list[i]));
}
res.json(resp);
});
}
function processNode(_p, f) {
var s = fs.statSync(path.join(_p, f));
return {
"id": path.join(_p, f),
"text": f,
"icon" : s.isDirectory() ? 'jstree-custom-folder' : 'jstree-custom-file',
"state": {
"opened": false,
"disabled": false,
"selected": false
},
"li_attr": {
"base": path.join(_p, f),
"isLeaf": !s.isDirectory()
},
"children": s.isDirectory()
};
}
module.exports = router;
}());
</code></pre>
<p>Where is my mistake? I appreciate any help.</p>
<p>I used this <a href="https://github.com/nickholub/node-angular-file-upload" rel="noreferrer">example</a> and take out my upload.php at all, fixed server/app.j s and controller.js , but still getting same error</p>
<p><strong>Updated</strong></p>
<p>I put this code into routes.js</p>
<pre><code>var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './upload');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('test');
router.post('/',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
</code></pre>
<p>Now post returns 200, but nothing appears in folder "upload". Are there any ideas, what's wrong now?</p> | 36,635,616 | 1 | 13 | null | 2016-04-14 15:16:12.507 UTC | 2 | 2018-07-18 18:14:23.43 UTC | 2018-07-18 18:14:23.43 UTC | null | 1,033,581 | null | 4,170,705 | null | 1 | 11 | javascript|php|angularjs|node.js|file-upload | 99,837 | <p>The error is <code>POST http://localhost:3000/ 404 (Not Found)</code></p>
<p>You don't have a post route for <code>/</code></p>
<p>You can create one like so:</p>
<p><code>
router.post('/', function(req, res) {
// do something w/ req.body or req.files
});
</code></p>
<p>But also, I recommend using <em>either</em> express or upload.php</p>
<p>To use express, you'll need to update your angular FileUploader url as well</p> |
7,621,358 | what is ids.xml used for? | <p>Just a quick question, what is the ids.xml used for when developing an Android app?
I saw an example on the android resources webpage which contained:</p>
<pre><code><resources>
<item name="snack" type="id"/>
</resources>
</code></pre>
<p>What would this be used for?</p> | 7,621,398 | 5 | 0 | null | 2011-10-01 16:06:15.9 UTC | 9 | 2018-11-02 15:03:47.08 UTC | 2016-06-19 13:18:51.8 UTC | null | 844,882 | null | 665,200 | null | 1 | 54 | android | 34,434 | <p>id.xml is generally used to declare the id's that you use for the views in the layouts.</p>
<p>you could use something like</p>
<pre><code><TextView android:id="@id/snack">
</code></pre>
<p>for your given xml.</p> |
7,448,360 | Detect if time format is in 12hr or 24hr format | <p>Is there any way to detect if the current device of the app uses 12h our 24h format, so that I can use one NSDateFormatter for 12h and one for 24h depending on the users language/loaction setting? Just Like the UIDatePicker detects and shows the AM/PM picker if it is 12h format.</p> | 7,538,489 | 6 | 2 | null | 2011-09-16 17:31:48.857 UTC | 12 | 2020-10-27 13:39:08.307 UTC | 2011-09-16 17:37:51.973 UTC | null | 453,261 | null | 832,065 | null | 1 | 40 | objective-c|ios|cocoa-touch|nstimezone | 25,513 | <p>I figured it out, its pretty easy. I just added this code to <code>viewDidLoad</code> :</p>
<pre><code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];
BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
[formatter release];
NSLog(@"%@\n",(is24h ? @"YES" : @"NO"));
</code></pre>
<p>And it perfectly returns <code>YES</code> or <code>NO</code> depending on the locale.</p> |
7,074,402 | How to insert an object in an ArrayList at a specific position | <p>Suppose I have an ArrayList of objects of size n. Now I want to insert an another object at specific position, let's say at index position k (is greater than 0 and less than n) and I want other objects at and after index position k to shift one index position ahead. So is there any way to do this directly in Java. Actually i want to keep the list sorted while adding new object.</p> | 7,074,420 | 6 | 0 | null | 2011-08-16 06:34:50.557 UTC | 17 | 2021-07-27 09:16:54.347 UTC | 2011-08-16 09:24:05.8 UTC | null | 256,196 | null | 893,039 | null | 1 | 83 | java|arraylist | 255,322 | <p>To <strong>insert</strong> value into ArrayList at particular index, use: </p>
<pre><code>public void add(int index, E element)
</code></pre>
<p>This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.</p>
<hr>
<p>To <strong>replace</strong> the element at the specified position, use:</p>
<pre><code>public E set(int index, E element)
</code></pre>
<p>This method replaces the element at the specified position in the
list with the specified element, and returns the element previously
at the specified position.</p> |
7,567,502 | Why are two AtomicIntegers never equal? | <p>I stumbled across the source of <code>AtomicInteger</code> and realized that</p>
<pre><code>new AtomicInteger(0).equals(new AtomicInteger(0))
</code></pre>
<p>evaluates to <code>false</code>.</p>
<p>Why is this? Is it some "defensive" design choice related to concurrency issues? If so, what could go wrong if it was implemented differently?</p>
<p>(I do realize I could use <code>get</code> and <code>==</code> instead.)</p> | 7,568,493 | 9 | 3 | null | 2011-09-27 10:15:42.917 UTC | 4 | 2020-05-27 18:51:50.397 UTC | 2020-05-27 18:51:50.397 UTC | null | 276,052 | null | 276,052 | null | 1 | 32 | java|concurrency|equals | 6,666 | <p>This is partly because an <code>AtomicInteger</code> is not a general purpose replacement for an <code>Integer</code>.</p>
<p>The <code>java.util.concurrent.atomic</code> <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html" rel="noreferrer">package summary</a> states:</p>
<blockquote>
<p>Atomic classes are not general purpose replacements for
<code>java.lang.Integer</code> and related classes. They do not define methods
such as <code>hashCode</code> and <code>compareTo</code>. (Because atomic variables are
expected to be mutated, they are poor choices for hash table keys.)</p>
</blockquote>
<p><code>hashCode</code> is not implemented, and so is the case with <code>equals</code>. This is in part due to a far larger rationale that is <a href="http://cs.oswego.edu/pipermail/concurrency-interest/2004-January/000688.html" rel="noreferrer">discussed in the mailing list archives</a>, on whether <code>AtomicInteger</code> should extend <code>Number</code> or not.</p>
<p>One of the reasons why an AtomicXXX class is not a drop-in replacement for a primitive, and that it does not implement the <code>Comparable</code> interface, is because it is pointless to compare two instances of an AtomicXXX class in most scenarios. If two threads could access and mutate the value of an <code>AtomicInteger</code>, then <a href="http://cs.oswego.edu/pipermail/concurrency-interest/2004-January/000745.html" rel="noreferrer">the comparison result is invalid before you use the result, if a thread mutates the value of an <code>AtomicInteger</code></a>. The same rationale holds good for the <code>equals</code> method - the result for an equality test (that depends on the value of the <code>AtomicInteger</code>) is only valid before a thread mutates one of the <code>AtomicInteger</code>s in question.</p> |
7,610,871 | How to trigger an event after using event.preventDefault() | <p>I want to hold an event until I am ready to fire it e.g</p>
<pre><code>$('.button').live('click', function(e){
e.preventDefault();
// do lots of stuff
e.run() //this proceeds with the normal event
}
</code></pre>
<p><strong>Is there an equivalent to the <code>run()</code> function described above?</strong></p> | 7,610,931 | 16 | 2 | null | 2011-09-30 13:12:40.22 UTC | 35 | 2022-04-14 06:54:45.817 UTC | 2019-08-26 13:21:31.923 UTC | null | 4,370,109 | null | 220,519 | null | 1 | 188 | jquery|jquery-events | 231,414 | <p>Nope. Once the event has been canceled, it is canceled.</p>
<p>You can re-fire the event later on though, using a flag to determine whether your custom code has already run or not - such as this (please ignore the blatant namespace pollution):</p>
<pre><code>var lots_of_stuff_already_done = false;
$('.button').on('click', function(e) {
if (lots_of_stuff_already_done) {
lots_of_stuff_already_done = false; // reset flag
return; // let the event bubble away
}
e.preventDefault();
// do lots of stuff
lots_of_stuff_already_done = true; // set flag
$(this).trigger('click');
});
</code></pre>
<p>A more generalized variant (with the added benefit of avoiding the global namespace pollution) could be:</p>
<pre><code>function onWithPrecondition(callback) {
var isDone = false;
return function(e) {
if (isDone === true)
{
isDone = false;
return;
}
e.preventDefault();
callback.apply(this, arguments);
isDone = true;
$(this).trigger(e.type);
}
}
</code></pre>
<p>Usage:</p>
<pre><code>var someThingsThatNeedToBeDoneFirst = function() { /* ... */ } // do whatever you need
$('.button').on('click', onWithPrecondition(someThingsThatNeedToBeDoneFirst));
</code></pre>
<p>Bonus super-minimalistic jQuery plugin with <code>Promise</code> support:</p>
<pre><code>(function( $ ) {
$.fn.onButFirst = function(eventName, /* the name of the event to bind to, e.g. 'click' */
workToBeDoneFirst, /* callback that must complete before the event is re-fired */
workDoneCallback /* optional callback to execute before the event is left to bubble away */) {
var isDone = false;
this.on(eventName, function(e) {
if (isDone === true) {
isDone = false;
workDoneCallback && workDoneCallback.apply(this, arguments);
return;
}
e.preventDefault();
// capture target to re-fire event at
var $target = $(this);
// set up callback for when workToBeDoneFirst has completed
var successfullyCompleted = function() {
isDone = true;
$target.trigger(e.type);
};
// execute workToBeDoneFirst callback
var workResult = workToBeDoneFirst.apply(this, arguments);
// check if workToBeDoneFirst returned a promise
if (workResult && $.isFunction(workResult.then))
{
workResult.then(successfullyCompleted);
}
else
{
successfullyCompleted();
}
});
return this;
};
}(jQuery));
</code></pre>
<p>Usage:</p>
<pre><code>$('.button').onButFirst('click',
function(){
console.log('doing lots of work!');
},
function(){
console.log('done lots of work!');
});
</code></pre> |
14,315,331 | Vertically center SVG Tag | <p>I'm trying to figure out a way to center vertically my SVG Tag.</p>
<p>Basically, here is a simplified SVG code i'm trying to center :</p>
<pre><code><svg height="272" style="background-color:transparent;margin-left: auto; margin-right: auto;" width="130" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g style="font-size: 0.7em;" transform="scale(1 1) rotate(0) translate(0 270)">
<g id="1" style="font-size: 0.7em;">
<image height="32" width="32" x="49" xlink:href="../../images/JOB.GIF" y="-270"/>
</g>
</g>
</svg>
</code></pre>
<p>I have no trouble putting it in the middle (horizontally speaking) of the page, however i'd like it to be vertically centered as well.</p>
<p>I can add wrappers, but i'd like to know a generic way of doing this, not depending on the SVG size nor the window size.</p>
<p>I have tried multiple ways, but nothing worked.</p>
<p>Thanks,</p> | 14,330,729 | 5 | 3 | null | 2013-01-14 08:48:14.97 UTC | 5 | 2020-07-16 13:54:26.067 UTC | null | null | null | null | 1,729,268 | null | 1 | 17 | css|html|svg|center | 39,876 | <p>I've finally used some JS code to do so.</p>
<p>I was using the solution from here : <a href="https://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-and-horizontally">Best way to center a <div> on a page vertically and horizontally?</a></p>
<p>Which is :</p>
<pre><code>div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
</code></pre>
<p>}</p>
<p>But the problem is that if the SVG is bigger than the window size, it gets cropped.
Here is the JS code i've used in <code>onLoad</code> :</p>
<pre><code>var heightDiff = window.innerHeight - svg.height.baseVal.value;
var widthDiff = window.innerWidth - svg.width.baseVal.value;
if (heightDiff > 0)
svg.style.marginTop = svg.style.marginBottom = heightDiff / 2;
if (widthDiff > 0)
svg.style.marginLeft = svg.style.marginRight = widthDiff / 2;
</code></pre> |
13,950,589 | Difference between eng and user-debug build in Android | <p>I would like to know the difference between the two <code>build_flavor</code>'s viz. </p>
<blockquote>
<p>eng & user-debug</p>
</blockquote>
<p>The difference between eng and user build flavors is quiet evident. But eng and user-debug is confusing me somewhat. What are the additional Debug facilities provided in eng that are not present in user-debug?</p>
<p>For eg. </p>
<pre><code>If I take only the Kernel being built:
</code></pre>
<p><code>Will the Debugging levels differ for the eng and user-debug builds?</code></p>
<p>I am facing an issue where the user-debug build is booting up on the android phone. But the eng build is not and the build_flavor is the only difference between the two builds.</p>
<p>Any help/pointers is appreciated.
Thanks!</p> | 14,472,511 | 2 | 0 | null | 2012-12-19 10:45:15.547 UTC | 12 | 2016-08-04 08:07:01.78 UTC | null | null | null | null | 1,635,107 | null | 1 | 32 | android|linux|makefile|linux-kernel|android-build | 56,524 | <p>Well the difference between the three builds viz. eng, user and user-debug is as follows:</p>
<blockquote>
<p><strong>eng</strong> - Engineering build comes with default root access.</p>
<p><strong>user</strong> - User build is the one flashed on production phones. Has no root access. </p>
<p><strong>user-debug</strong> - User debug build does not come with default root access but can be rooted. It also contains extra logging.</p>
</blockquote>
<p>One thing to note here is although an eng build might suggest extra logging it is not so. The user-debug will contain maximum logging and should be used during development</p> |
14,149,422 | Using pip behind a proxy with CNTLM | <p>I am trying to use pip behind a proxy at work.</p>
<p>One of the answers from <a href="https://stackoverflow.com/questions/9698557/how-to-use-pip-on-windows-behind-an-authenticating-proxy">this post</a> suggested using <a href="http://cntlm.sourceforge.net/" rel="noreferrer">CNTLM</a>. I installed and configured it per <a href="https://stackoverflow.com/questions/9181637/how-to-fill-proxy-information-in-cntlm-config-file">this other post</a>, but running <code>cntlm.exe -c cntlm.ini -I -M http://google.com</code> gave the error <code>Connection to proxy failed, bailing out</code>.</p>
<p>I also tried <code>pip install -–proxy=user:pass@localhost:3128</code> (the default CNTLM port) but that raised <code>Cannot fetch index base URL http://pypi.python.org/simple/</code>. Clearly something's up with the proxy.</p>
<p>Does anyone know how to check more definitively whether CNTLM is set up right, or if there's another way around this altogether? I know you can also set the <code>http_proxy</code> environment variable as described <a href="https://stackoverflow.com/questions/11726881/how-to-set-an-http-proxy-in-python-2-7">here</a> but I'm not sure what credentials to put in. The ones from <code>cntlm.ini</code>?</p> | 14,188,155 | 33 | 2 | null | 2013-01-04 00:22:17.577 UTC | 102 | 2022-05-09 20:00:34.14 UTC | 2019-06-18 09:16:35.193 UTC | null | 3,423,146 | null | 676,001 | null | 1 | 291 | python|proxy|pip | 767,574 | <p>To setup CNTLM for windows, follow this <a href="http://stormpoopersmith.com/2012/03/20/using-applications-behind-a-corporate-proxy/" rel="noreferrer">article</a>. For Ubuntu, read <a href="http://annelagang.blogspot.com/2012/11/installing-gems-in-ubuntu-1204-using.html" rel="noreferrer">my blog post</a>. </p>
<p><strong>Edit:</strong></p>
<p>Basically, to use CNTLM in any platform, you need to setup your username and <em>hashed</em> password, before using <code>http://127.0.0.1:3128</code> as a proxy to your parent proxy.</p>
<ol>
<li><p>Edit the config and add important information like domain, username, password and parent proxy. </p></li>
<li><p>Generate hashed password.</p>
<p><strong>Windows</strong> <code>cntlm –c cntlm.ini –H</code></p>
<p><strong>Ubuntu/Linux</strong> <code>cntlm -v -H -c /etc/cntlm.conf</code></p></li>
<li><p>Remove plain text password from the config and replace them with the generated passwords.</p></li>
</ol>
<p>To check if working:</p>
<p><strong>Windows</strong> <code>cntlm –M http://www.google.com</code></p>
<p><strong>Ubuntu/Linux</strong> <code>sudo cntlm -M http://www.google.com/</code></p>
<p>For more detailed instructions, see links above.</p>
<p><strong>Update:</strong> </p>
<p>Just for completeness sake, I was able to configure and use CNTLM in Windows recently. I encountered a problem during the syncing process of Kindle for PC because of our proxy and installing and configuring CNTLM for Windows fixed that issue for me. Refer to <a href="http://annelagang.blogspot.com/2014/01/register-and-download-books-using.html" rel="noreferrer">my article</a> for more details. </p> |
14,024,228 | iter_swap() versus swap() -- what's the difference? | <p><a href="http://msdn.microsoft.com/en-us/library/f1863z4b.aspx" rel="noreferrer">MSDN says</a>:</p>
<blockquote>
<p><code>swap</code> should be used in preference to <code>iter_swap</code>, which was included in the C++ Standard for backward compatibility.</p>
</blockquote>
<p>But <a href="https://groups.google.com/forum/?fromgroups=#!topic/comp.std.c++/AMH7TXg5EsI" rel="noreferrer">comp.std.c++ says</a>:</p>
<blockquote>
<p>Most STL algorithms operate on iterator ranges. It therefore makes sense to
use <code>iter_swap</code> when swapping elements within those ranges, since that is its
intended purpose --- swapping the elements pointed to by two iterators. This
allows optimizations for node-based sequences such as <code>std::list</code>, whereby the
nodes are just relinked, rather than the data actually being swapped.</p>
</blockquote>
<p>So which one is correct? Should I use <code>iter_swap</code>, or should I use <code>swap</code>? (Is <code>iter_swap</code> only for backwards compatibility?) Why?</p> | 14,494,007 | 6 | 6 | null | 2012-12-24 17:42:13.977 UTC | 9 | 2020-01-30 04:51:23.173 UTC | null | null | null | null | 541,686 | null | 1 | 55 | c++|swap | 14,144 | <p>The standard itself has very few mentions of <code>iter_swap</code>:</p>
<ul>
<li>It should have the effect of <code>swap(*a, *b)</code>, although there is no stipulation that it must be implemented that way.</li>
<li>The dereferenced values <code>*a</code> and <code>*b</code> must be "swappable", which implies that <code>swap(*a, *b)</code> must be valid, and thus the dereferenced types must be identical, although the iterator types do not have to be.</li>
<li><code>iter_swap</code> is required to be used in the implementation of <code>std::reverse</code>. No such requirement is placed on any other algorithm, so this seems to be an oddity.</li>
</ul>
<p>To borrow <a href="https://stackoverflow.com/a/13991936/1435577">what <em>sehe</em> had found</a> from the <em><a href="http://www.sgi.com/tech/stl/iter_swap.html" rel="noreferrer">SGI docs</a></em>:</p>
<blockquote>
<p>Strictly speaking, <code>iter_swap</code> is redundant. It exists only for technical reasons: in some circumstances, some compilers have difficulty performing the type deduction required to interpret <code>swap(*a, *b)</code>.</p>
</blockquote>
<p>All of these seem to suggest that it is an artifact of the past.</p> |
14,291,170 | How does Hadoop process records split across block boundaries? | <p>According to the <code>Hadoop - The Definitive Guide</code></p>
<blockquote>
<p>The logical records that FileInputFormats define do not usually fit neatly into HDFS blocks. For example, a TextInputFormat’s logical records are lines, which will cross HDFS boundaries more often than not. This has no bearing on the functioning of your program—lines are not missed or broken, for example—but it’s worth knowing about, as it does mean that data-local maps (that is, maps that are running on the same host as their input data) will perform some remote reads. The slight overhead this causes is not normally significant.</p>
</blockquote>
<p>Suppose a record line is split across two blocks (b1 and b2). The mapper processing the first block (b1) will notice that the last line doesn't have a EOL separator and fetches the remaining of the line from the next block of data (b2).</p>
<p>How does the mapper processing the second block (b2) determine that the first record is incomplete and should process starting from the second record in the block (b2)?</p> | 14,540,272 | 6 | 0 | null | 2013-01-12 07:10:57.05 UTC | 92 | 2022-06-29 15:25:31.947 UTC | 2022-06-29 15:25:31.947 UTC | null | 4,294,399 | null | 614,157 | null | 1 | 124 | hadoop|split|mapreduce|hdfs | 35,862 | <p>Interesting question, I spent some time looking at the code for the details and here are my thoughts. The splits are handled by the client by <code>InputFormat.getSplits</code>, so a look at FileInputFormat gives the following info:</p>
<ul>
<li>For each input file, get the file length, the block size and calculate the split size as <code>max(minSize, min(maxSize, blockSize))</code> where <code>maxSize</code> corresponds to <code>mapred.max.split.size</code> and <code>minSize</code> is <code>mapred.min.split.size</code>.</li>
<li><p>Divide the file into different <code>FileSplit</code>s based on the split size calculated above. What's important here is that <strong>each <code>FileSplit</code> is initialized with a <code>start</code> parameter corresponding to the offset in the input file</strong>. There is still no handling of the lines at that point. The relevant part of the code looks like this:</p>
<pre><code>while (((double) bytesRemaining)/splitSize > SPLIT_SLOP) {
int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);
splits.add(new FileSplit(path, length-bytesRemaining, splitSize,
blkLocations[blkIndex].getHosts()));
bytesRemaining -= splitSize;
}
</code></pre></li>
</ul>
<p>After that, if you look at the <code>LineRecordReader</code> which is defined by the <code>TextInputFormat</code>, that's where the lines are handled:</p>
<ul>
<li>When you initialize your <code>LineRecordReader</code> it tries to instantiate a <code>LineReader</code> which is an abstraction to be able to read lines over <code>FSDataInputStream</code>. There are 2 cases:</li>
<li>If there is a <code>CompressionCodec</code> defined, then this codec is responsible for handling boundaries. Probably not relevant to your question.</li>
<li><p>If there is no codec however, that's where things are interesting: if the <code>start</code> of your <code>InputSplit</code> is different than 0, then you <strong>backtrack 1 character and then skip the first line you encounter identified by \n or \r\n (Windows)</strong> ! The backtrack is important because in case your line boundaries are the same as split boundaries, this ensures you do not skip the valid line. Here is the relevant code:</p>
<pre><code>if (codec != null) {
in = new LineReader(codec.createInputStream(fileIn), job);
end = Long.MAX_VALUE;
} else {
if (start != 0) {
skipFirstLine = true;
--start;
fileIn.seek(start);
}
in = new LineReader(fileIn, job);
}
if (skipFirstLine) { // skip first line and re-establish "start".
start += in.readLine(new Text(), 0,
(int)Math.min((long)Integer.MAX_VALUE, end - start));
}
this.pos = start;
</code></pre></li>
</ul>
<p>So since the splits are calculated in the client, the mappers don't need to run in sequence, every mapper already knows if it neds to discard the first line or not.</p>
<p>So basically if you have 2 lines of each 100Mb in the same file, and to simplify let's say the split size is 64Mb. Then when the input splits are calculated, we will have the following scenario:</p>
<ul>
<li>Split 1 containing the path and the hosts to this block. Initialized at start 200-200=0Mb, length 64Mb.</li>
<li>Split 2 initialized at start 200-200+64=64Mb, length 64Mb.</li>
<li>Split 3 initialized at start 200-200+128=128Mb, length 64Mb.</li>
<li>Split 4 initialized at start 200-200+192=192Mb, length 8Mb.</li>
<li>Mapper A will process split 1, start is 0 so don't skip first line, and read a full line which goes beyond the 64Mb limit so needs remote read.</li>
<li>Mapper B will process split 2, start is != 0 so skip the first line after 64Mb-1byte, which corresponds to the end of line 1 at 100Mb which is still in split 2, we have 28Mb of the line in split 2, so remote read the remaining 72Mb.</li>
<li>Mapper C will process split 3, start is != 0 so skip the first line after 128Mb-1byte, which corresponds to the end of line 2 at 200Mb, which is end of file so don't do anything.</li>
<li>Mapper D is the same as mapper C except it looks for a newline after 192Mb-1byte.</li>
</ul> |
43,616,649 | How can Comparator be a Functional Interface when it has two abstract methods? | <p>In Java 8, the <code>@FunctionalInterface</code> annotation is introduced to denote any interface that has exactly one abstract method as a functional interface. One of the reason for its introduction is to indicate the user (programmer), that lambda expression can be used in context of a functional interface. </p>
<p>The <code>Comparator</code> interface is annotated with <code>@FunctionalInterface</code>. But, two methods are abstract.</p>
<pre><code>int compare(T o1, T o2);
</code></pre>
<p>and</p>
<pre><code>boolean equals(Object obj);
</code></pre>
<p>In the docs of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html" rel="noreferrer"><code>FunctionalInterface</code></a>, it is clearly mentioned as</p>
<blockquote>
<p>Conceptually, a functional interface has exactly one abstract method.</p>
</blockquote>
<p>Isn't the <code>equals</code> method not considered as abstract here? </p> | 43,616,692 | 2 | 2 | null | 2017-04-25 16:50:45.577 UTC | 8 | 2017-04-26 01:03:11.253 UTC | 2017-04-26 00:36:18.313 UTC | null | 7,256,039 | null | 1,062,597 | null | 1 | 40 | java|java-8|comparator|functional-interface | 8,277 | <p>The docs also state:</p>
<blockquote>
<p>If an interface declares an abstract method overriding one of the public methods of <code>java.lang.Object</code>, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from <code>java.lang.Object</code> or elsewhere.</p>
</blockquote>
<p>And since <code>equals</code> is one of those methods, the "abstract method count" of the interface is still 1.</p> |
29,992,066 | Rcpp warning: "directory not found for option '-L/usr/local/Cellar/gfortran/4.8.2/gfortran'" | <p>This question relates to some others out there, like <a href="https://stackoverflow.com/questions/19920281/rcpparmadillo-compile-errors-on-os-x-mavericks">RccpArmadillo</a> or <a href="https://stackoverflow.com/questions/19917023/element-wise-matrix-multiplication-in-rcpp">element-wise-multiplication</a>.</p>
<p>However, my settings are such that I do not know what I have to edit/simlink to make Rccp run without giving me warnings. </p>
<p>I am on an Mac 10.9 (mavericks) using the latest R version.</p>
<p>At the very beginning, trying the following code I got from here <a href="http://brainchronicle.blogspot.co.uk/2012/06/rcpp-vs-r-implementation-of-cosine.html" rel="noreferrer">RccpvsR</a>, I got an error: </p>
<pre><code>ld: library not found for -lgfortran
clang: error: linker command failed with exit code 1 (use -v to see invocation)`
</code></pre>
<p>Then, based on <a href="https://stackoverflow.com/questions/19920281/rcpparmadillo-compile-errors-on-os-x-mavericks">RccpArmadillo</a> I did the following: </p>
<pre><code># Update FLIBS in ~/.R/Makevars
FLIBS=-L/usr/local/Cellar/gfortran/4.8.2/gfortran
#Re-Install from source
install.packages(c("Rcpp","RcppArmadillo","inline"),type="source")
#Restart R
</code></pre>
<p>this was JUST trying things out since I have NO <code>/usr/local/Cellar/gfortran/</code> directory. In fact, all my <code>libgfortran*</code> files are here (At the macports dir):</p>
<pre><code>>ls /opt/local/lib/gcc48/libgfortran.*
/opt/local/lib/gcc48/libgfortran.3.dylib /opt/local/lib/gcc48/libgfortran.dylib
/opt/local/lib/gcc48/libgfortran.a /opt/local/lib/gcc48/libgfortran.spec
</code></pre>
<p>and here <code>/opt/local/lib/gcc48/gcc/x86_64-apple-darwin13/4.8.3/libgfortranbegin.a</code> and I have no <code>gfortran</code> file anywhere.</p>
<p>Then I tried the code <a href="http://brainchronicle.blogspot.co.uk/2012/06/rcpp-vs-r-implementation-of-cosine.html" rel="noreferrer">RccpvsR</a> again and surprisingly, it worked!. Apart from the fact that I get a warning:</p>
<pre><code>ld: warning: directory not found for option '-L/usr/local/Cellar/gfortran/4.8.2/gfortran'
</code></pre>
<p>because of course, it does not exists, but the function created by that code, <code>cosineRcpp</code>, runs with no problems.</p>
<p>Therefore, all that, to ask if anyone knows if I have to simlink the <code>libgfortran</code> files at <code>/opt/local/lib/gcc48/</code> as:</p>
<pre><code>ln -s /opt/local/lib/gcc48/libgfortran.* /usr/local/lib/
</code></pre>
<p>and then remove/edit the line:</p>
<pre><code>FLIBS=-L/usr/local/Cellar/gfortran/4.8.2/gfortran
</code></pre>
<p>at <code>~/.R/Makevars</code></p>
<p>or if I have to install something new.</p>
<p>thanks in advance for your time!</p> | 29,993,906 | 2 | 5 | null | 2015-05-01 17:42:03.403 UTC | 10 | 2020-07-01 01:10:13.647 UTC | 2017-05-23 10:31:15.87 UTC | null | -1 | null | 3,501,942 | null | 1 | 12 | r|rcpp | 8,404 | <h1>Short Answer</h1>
<p>Just put the path to <code>libgfortran</code> into <code>FLIBS</code>, e.g.</p>
<pre><code>FLIBS=-L/opt/local/lib/gcc48/
</code></pre>
<p>Or, symlink the files within to <code>/usr/local/lib/</code>, if you're comfortable with that. This solution is, however, quite brittle as it's easy to forget to update this path if you update <code>gfortran</code>, or move it to a different directory.</p>
<h1>Slightly Longer Answer</h1>
<p>You can query <code>gfortran</code> for the path to <code>libgfortran.dylib</code> as e.g.</p>
<pre><code>gfortran -print-file-name=libgfortran.dylib
</code></pre>
<p>You can just execute this directly in your <code>Makevars</code> file; e.g.</p>
<pre><code>FLIBS = -L`gfortran -print-file-name=libgfortran.dylib | xargs dirname`
</code></pre>
<hr>
<h1>Obsolete Long Answer</h1>
<p>Try parsing an appropriate <code>FLIBS</code> directly from <code>gfortran</code> output.</p>
<p>First, some background. The <code>/usr/local/Cellar</code> directory is the default path used by <a href="http://brew.sh/" rel="noreferrer">homebrew</a>, a package manager for OS X. Think of it as an alternative to <code>macports</code>.</p>
<p>Homebrew now provides <code>gfortran</code> and its associated libraries as part of the <code>gcc</code> package, and so the paths where it installs FORTRAN libraries has now changed. However, these can (in general) be discovered using <code>gfortran -print-search-dirs</code>. For example, on my system,</p>
<pre><code>gfortran -print-search-dirs
</code></pre>
<p>will give me</p>
<pre><code>install: /usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/
programs: =/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/bin/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/bin/
libraries: =/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../x86_64-apple-darwin14.0.0/4.9.2/:/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../:/lib/x86_64-apple-darwin14.0.0/4.9.2/:/lib/:/usr/lib/x86_64-apple-darwin14.0.0/4.9.2/:/usr/lib/
</code></pre>
<p>Split, and printed with R, I see:</p>
<pre><code>[[1]]
[1] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/"
[[2]]
[1] "/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/"
[2] "/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/4.9.2/"
[3] "/usr/local/Cellar/gcc/4.9.2_1/libexec/gcc/x86_64-apple-darwin14.0.0/"
[4] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/"
[5] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/"
[6] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/bin/x86_64-apple-darwin14.0.0/4.9.2/"
[7] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/bin/"
[[3]]
[1] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/"
[2] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/x86_64-apple-darwin14.0.0/4.9.2/"
[3] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/"
[4] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../x86_64-apple-darwin14.0.0/4.9.2/"
[5] "/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../"
[6] "/lib/x86_64-apple-darwin14.0.0/4.9.2/"
[7] "/lib/"
[8] "/usr/lib/x86_64-apple-darwin14.0.0/4.9.2/"
[9] "/usr/lib/"
</code></pre>
<p>In my case, <code>libgfortran</code> actually lives here:</p>
<pre><code>/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../
</code></pre>
<p>And so this is the path we want to pass to <code>FLIBS</code>. But, pulling that out is kind of a pain, so let's just tell <code>FLIBS</code> to use whatever paths are normally used by <code>gfortran</code>:</p>
<pre><code>gfortran -print-search-dirs | grep ^libraries: | sed 's|libraries: =||'
</code></pre>
<p>This is nice, but we want the library paths in a format suitable for the compiler; ie, with <code>-L</code> prepended. Let's do that with <code>sed</code>:</p>
<pre><code>gfortran -print-search-dirs | grep ^libraries: | sed 's|libraries: =||' | sed 's|:| -L|g' | sed 's|^|-L|'
</code></pre>
<p>This outputs (split for readability)</p>
<pre><code>-L/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/
-L/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/x86_64-apple-darwin14.0.0/4.9.2/
-L/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../../../../x86_64-apple-darwin14.0.0/lib/
-L/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../x86_64-apple-darwin14.0.0/4.9.2/
-L/usr/local/Cellar/gcc/4.9.2_1/lib/gcc/4.9/gcc/x86_64-apple-darwin14.0.0/4.9.2/../../../
-L/lib/x86_64-apple-darwin14.0.0/4.9.2/
-L/lib/
-L/usr/lib/x86_64-apple-darwin14.0.0/4.9.2/
-L/usr/lib/
</code></pre>
<p>All together, this implies that the following should work for you, at least on OS X, but should (in general) work on any platform with <code>gfortran</code> (as long as it's on the <code>PATH</code>):</p>
<pre><code>FLIBS=`gfortran -print-search-dirs | grep ^libraries: | sed 's|libraries: =||' | sed 's|:| -L|g' | sed 's|^|-L|'`
</code></pre>
<p>This isn't perfect, e.g. it will fail if you have spaces in your paths -- if you do, 1) you deserve what you get and 2) it should also be a 'relatively' easy fix.</p> |
43,216,971 | Moving file using cmd? | <p>I have a file that I have downloaded from Google (it is inside the download folder)
and I want to move it to the autorun folder ( The folder where files run when the computer turns on).</p>
<p>I need to move the file using a cmd command ( the reason why is that it's going to be done using the USB rubber ducky.
I am using windows 10 64 bit if it is any help.</p>
<p>The path where the file is</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\%USERPROFILE%\Downloads\Test.exe
</code></pre>
<p>and the path I want to move it to is</p>
<pre class="lang-none prettyprint-override"><code>C:\Users\%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
</code></pre>
<p>The reason why <code>%USERPROFILE%</code> is that it should work on all computer.</p> | 43,219,429 | 2 | 2 | null | 2017-04-04 20:20:58.083 UTC | 3 | 2018-09-21 03:49:17.513 UTC | 2017-04-05 08:59:09.507 UTC | null | 692,942 | null | 7,816,587 | null | 1 | 1 | batch-file|cmd|window | 121,654 | <p>To move a file, you use the <code>move</code> command.</p>
<pre><code>move "%USERPROFILE%\Downloads\Test.exe" "%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
</code></pre>
<p>I put quotes around the source and target in case you're one of those people who has spaces in their username for some reason (and the target needs them anyway for the spaces in "Start Menu").</p>
<p>From the output of <code>move /?</code>:</p>
<pre class="lang-none prettyprint-override"><code>Moves files and renames files and directories.
To move one or more files:
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
[drive:][path]filename1 Specifies the location and name of the file
or files you want to move.
destination Specifies the new location of the file. Destination
can consist of a drive letter and colon, a
directory name, or a combination. If you are moving
only one file, you can also include a filename if
you want to rename the file when you move it.
[drive:][path]dirname1 Specifies the directory you want to rename.
dirname2 Specifies the new name of the directory.
/Y Suppresses prompting to confirm you want to
overwrite an existing destination file.
/-Y Causes prompting to confirm you want to overwrite
an existing destination file.
</code></pre> |
9,627,093 | What is the difference between accessor and mutator methods? | <p>How are accessors and mutators different? An example and explanation would be great.</p> | 9,627,148 | 2 | 1 | null | 2012-03-09 00:13:52.267 UTC | 7 | 2015-04-08 06:32:17.493 UTC | 2015-04-08 06:32:17.493 UTC | null | 1,066,497 | null | 385,251 | null | 1 | 15 | c++ | 50,159 | <p>An <strong>accessor</strong> is a class method used to <em>read</em> data members, while a <strong>mutator</strong> is a class method used to <em>change</em> data members.</p>
<p>Here's an example:</p>
<pre><code>class MyBar;
class Foo
{
public:
MyBar GetMyBar() const { return mMyBar; } // accessor
void SetMyBar(MyBar aMyBar) { mMyBar = aMyBar; } // mutator
private:
MyBar mMyBar;
}
</code></pre>
<p>It's best practice to make data members <code>private</code> (as in the example above) and only access them via accessors and mutators. This is for the following reasons:</p>
<ul>
<li>You know when they are accessed (and can debug this via a breakpoint).</li>
<li>The mutator can validate the input to ensure it fits within certain constraints.</li>
<li>If you need to change the internal implementation, you can do so without breaking a lot of external code -- instead you just modify the way the accessors/mutators reference the internal data.</li>
</ul> |
9,639,978 | Sending http request in node.js | <p>I am trying to send a http request to a neo4j database using node.js. This is the code I am using:</p>
<pre><code>var options = {
host: 'localhost',
port: 7474,
path: '/db/data',
method: 'GET',
headers: {
accept: 'application/json'
}
};
console.log("Start");
var x = http.request(options,function(res){
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
</code></pre>
<p>I check out that the database is running (I connect to the administration web page and everything is working). I am afraid that the problem is not on the database side but on the node.js side. </p>
<p>I hope some could give some light about this issue. I want to learn how to send a http request in node.js, the answer does not have to be specific to the neo4j issue.</p>
<p>Thanks in advance</p> | 9,640,364 | 2 | 1 | null | 2012-03-09 19:41:22.873 UTC | 5 | 2021-05-29 12:53:06.263 UTC | null | null | null | null | 829,584 | null | 1 | 22 | http|node.js|request | 45,199 | <p>If it's a simple GET request, you should use <code>http.get()</code></p>
<p>Otherwise, <code>http.request()</code> needs to be closed.</p>
<pre><code>var options = {
host: 'localhost',
port: 7474,
path: '/db/data',
method: 'GET',
headers: {
accept: 'application/json'
}
};
console.log("Start");
var x = http.request(options,function(res){
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
x.end();
</code></pre> |
9,019,833 | How can I specify location of debug keystore for Android ant debug builds? | <p>Is it possible to specify the location of a self created debug keystore when creating debug <code>.apk</code>'s (<code><project-name>-debug.apk</code>) with <code>ant debug</code>? I only see the possibility to specify the location of the release keystore.</p>
<p>I would like to share the debug keystore over multiple PC's without copying them over the the one that is placed in the '.android' directory. The debug keystore could for example reside within the source code repository. But I need a way to tell ant where to find the debug keystore.</p> | 18,331,895 | 7 | 1 | null | 2012-01-26 14:44:45.053 UTC | 12 | 2017-08-10 22:45:23.8 UTC | 2013-01-09 20:02:19.087 UTC | null | 194,894 | null | 748,578 | null | 1 | 40 | android|debugging|ant|keystore | 39,996 | <p>You can remove the signature of the final apk and sign it again. It is just a debug build so the zipalign can be avoided (at least I have no problems in my build).</p>
<p>Copy your keystore to a file debug.keystore in the project and add the following in ant.properties</p>
<pre><code>debug.key.store.password=android
debug.key.alias.password=android
debug.key.store=../debug.keystore
debug.key.alias=androiddebugkey
</code></pre>
<p>And add the following in your build.xml</p>
<pre><code><target name="-post-build" if="${build.is.packaging.debug}">
<!-- Remove the signature of the debug build, and sign it again with our own debug keystore -->
<delete dir="tmp" includeemptydirs="true" failonerror="false" />
<mkdir dir="tmp" />
<unzip src="${out.final.file}" dest="tmp" />
<delete dir="tmp/META-INF" includeemptydirs="true" verbose="true" failonerror="true" />
<delete file="${out.final.file}" failonerror="true" />
<zip destfile="${out.final.file}" basedir="tmp" />
<delete dir="tmp" includeemptydirs="true" failonerror="false" />
<echo level="info">Signing final DEBUG apk with a common signature...
signapk
input="${out.final.file}"
output="${out.packaged.file}"
keystore="${debug.key.store}"
storepass="${debug.key.store.password}"
alias="${debug.key.alias}"
keypass="${debug.key.alias.password}"
</echo>
<signapk
input="${out.final.file}"
output="${out.packaged.file}"
keystore="${debug.key.store}"
storepass="${debug.key.store.password}"
alias="${debug.key.alias}"
keypass="${debug.key.alias.password}"/>
<delete file="${out.final.file}" failonerror="true" />
<move file="${out.packaged.file}" tofile="${out.final.file}" failonerror="true" />
</target>
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.