id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
11,641,356
Circular plot in ggplot2 with line segments connected in r
<p>I am trying to create a circular plot and am stuck at a point:</p> <pre><code>dat1 &lt;- data.frame (xvar = 1:10, y = 6, ymin = 4, ymax = 4.5) </code></pre> <p>Using this data, I can produce a circular ribbon plot in ggplot2 </p> <pre><code>require(ggplot2) ggplot(dat1, aes(x=xvar, y=y)) + geom_ribbon(aes(ymin=ymin, ymax=ymax), col = "blue", fill = "blue2") + ylim (c(0,6)) + coord_polar() </code></pre> <p><img src="https://i.stack.imgur.com/GNfkP.jpg" alt=""></p> <p>However I want more. </p> <p>I want to fill the segment of the ribbon with different colors and labels using the following data. </p> <pre><code> filld &lt;- data.frame (start = c(1, 4, 6, 7.5, 8, 9), end = c(4, 6, 7.5, 8, 9, 10), label = c("A", "B", "C", "A", "C", "D")) filld ## start end label ## 1 1.0 4.0 A ## 2 4.0 6.0 B ## 3 6.0 7.5 C ## 4 7.5 8.0 A ## 5 8.0 9.0 C ## 6 9.0 10.0 D </code></pre> <p>The ribbon will be filled with different color by label variable. For example, the segment A will start from 1 and end at 4. Then segment B will start and end at 6 and filled with different color. Segments with same label (such as A and C) will be connected by line. </p> <p>The resulting plot will look like this: <img src="https://i.stack.imgur.com/LHFVz.png" alt=""></p>
11,641,943
3
1
null
2012-07-25 01:06:22.773 UTC
9
2018-12-21 13:39:00.803 UTC
2018-12-21 13:34:41.073 UTC
null
4,076,315
null
1,368,828
null
1
15
r|ggplot2
5,055
<p>Here is an example:</p> <pre><code>filld$p &lt;- rowMeans(subset(filld, select = c(start, end))) ggplot(filld, aes(xmin = start, xmax = end, ymin = 4, ymax = 5, fill = label)) + geom_rect() + geom_segment(data = subset(filld, label %in% label[duplicated(label)]), aes(x = p, y = 0, xend = p, yend = 4, colour = label), size = 2, show_guide = FALSE) + geom_text(aes(x = p, y = 4.5, label = label), colour = "white", size = 10) + coord_polar() + scale_y_continuous(limits = c(0, 5)) </code></pre> <p><img src="https://i.stack.imgur.com/e1SxA.png" alt=""></p> <p><em>Updated</em></p> <p>I do not recommend but something like this:</p> <pre><code>filld &lt;- data.frame (start = c(1, 4, 6, 7.5, 8, 9), end = c(4, 6, 7.5, 8, 9, 10), label = c("A", "B", "C", "A", "C", "D")) filld$p &lt;- rowMeans(subset(filld, select = c(start, end))) filld &lt;- merge(filld, ddply(filld, .(label), summarize, p2 = mean(p))) lnd &lt;- subset(filld, label %in% label[duplicated(label)]) lnd &lt;- ddply(lnd, .(label), function(x) { x &lt;- seq(x$p[1], x$p[2], length = 100) y &lt;- 4.5 + ((x - mean(x))^2 - (x[1]-mean(x))^2) / (x[1]-mean(x))^2 * 3 + sin(x*3*pi) * 0.1 data.frame(x, y) }) p &lt;- ggplot(filld, aes(xmin = start, xmax = end, ymin = 4, ymax = 5, colour = label, fill = label)) + geom_line(aes(x, y, xmin = NULL, ymin = NULL, xmax = NULL, ymax = NULL), data = lnd, size = 2) + geom_rect() + geom_text(aes(x = p, y = 4.5, label = label), colour = "white", size = 10) + coord_polar() + scale_y_continuous(limits = c(0, 5)) p </code></pre> <p><img src="https://i.stack.imgur.com/4Xge2.png" alt=""></p> <p>Perhaps, what you want is beyond the scope of ggplot2.</p>
11,818,384
How to add pom.xml to existing Eclipse project?
<p>I'm new to Maven and use Eclipse Juno. I've installed Maven Integration for Eclipse. There are three options in File > New > Other > Maven: <br>1. Checkout Maven Projects from SCM<br>2. Maven Module<br>3. Maven Project <br><br>But I don't see Maven2 POM as described <a href="http://www.theserverside.com/news/1363817/Introduction-to-m2eclipse" rel="noreferrer">here</a>. I've read that adding pom.xml is the first thing to do when using Maven.</p> <p>I have an existing Dynamic Web Project so I'm not sure whether I need to create Maven Project just to use Maven.</p> <p><strong>How to use Maven with this existing project?</strong></p> <p>Further, when I try to add Maven Project and on step "Select an Archetype", then all shown archetypes have version "RELEASE". When I click Next on this step, Eclipse becomes Not Responding. It's used memory doesn't even increase.</p>
11,818,558
2
0
null
2012-08-05 17:09:00.11 UTC
5
2020-07-30 12:18:02.85 UTC
2013-02-22 01:36:40.253 UTC
null
1,332,264
null
841,064
null
1
26
java|eclipse|maven|m2eclipse|m2e
68,432
<p>Take a look here :</p> <ul> <li><a href="https://stackoverflow.com/questions/2449461/convert-existing-eclipse-project-to-maven-project">Convert Existing Eclipse Project to Maven Project</a></li> </ul> <p>In last version of eclipse (Juno included), there is a more convinient wizard :</p> <pre><code>Configure &gt; Convert to maven project </code></pre>
11,776,829
Android form validation UI library
<p>There is iOS <a href="https://github.com/ustwo/US2FormValidator" rel="noreferrer">US2FormValidator</a> library for user input validation (see the picture below). I think that library is better than the default of just popping an alert when something doesn't validate.</p> <p><img src="https://i.stack.imgur.com/G9Wx9.png" alt="US2FormValidator Preview"></p> <p>I'm looking for how to do such things on Android. Are there some Android analogs of <a href="https://github.com/ustwo/US2FormValidator" rel="noreferrer">US2FormValidator</a>?</p>
13,012,846
3
0
null
2012-08-02 11:52:15.65 UTC
9
2017-12-16 06:06:50.683 UTC
null
null
null
null
807,805
null
1
28
android|user-interface|validation
35,542
<p>The pop-up effect you have shown on your screenshot can be achieved using Android's built-in <code>setError(String)</code> method on <code>EditText</code> widgets.</p> <p>Also, you can leverage the power of annotations using the <a href="https://github.com/ragunathjawahar/android-saripaar" rel="noreferrer">Android Saripaar</a> library that I've authored.</p> <p>first add the library:</p> <pre><code>compile 'com.mobsandgeeks:android-saripaar:2.0.2' </code></pre> <p>The library is very simple to use. In your activity annotate the <code>View</code> references you would like to validate as in the following example.</p> <pre><code>@Order(1) private EditText fieldEditText; @Order(2) @Checked(message = "You must agree to the terms.") private CheckBox iAgreeCheckBox; @Order(3) @Length(min = 3, message = "Enter atleast 3 characters.") @Pattern(regex = "[A-Za-z]+", message = "Should contain only alphabets") private TextView regexTextView; @Order(4) @Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS) private EditText passwordEditText; @Order(5) @ConfirmPassword private EditText confirmPasswordEditText; </code></pre> <p>The <code>order</code> attribute specifies the order in which the fields have to be validated.</p> <p>In your <code>onCreate()</code> method instantiate a new <code>Validator</code> object. and call <code>validator.validate()</code> inside any of your event listeners.</p> <p>You'll receive callbacks on <code>onSuccess</code> and <code>onFailure</code> methods of the <code>ValidationListener</code>.</p> <p>If you want to show a pop-up as show in the image above then do the following,</p> <pre><code>public void onValidationFailed(View failedView, Rule&lt;?&gt; failedRule) { if (failedView instanceof Checkable) { Toast.makeText(this, failedRule.getFailureMessage(), Toast.LENGTH_SHORT).show(); } else if (failedView instanceof TextView) { TextView view = (TextView) failedView; view.requestFocus(); view.setError(failedRule.getFailureMessage()); } } </code></pre> <p>Hope that helps.</p>
11,856,983
Why is git AuthorDate different from CommitDate?
<p>I looked in my git logs and found that the AuthorDate and CommitDate is slightly different for some of my commits. From the <code>git log --pretty=fuller</code> output:</p> <pre><code>commit 3a5912f90dc5227f308e99f95152fbee2301c59a Author: &lt;hidden&gt; AuthorDate: Fri Jun 15 10:57:22 2012 +0800 Commit: &lt;hidden&gt; CommitDate: Fri Jun 15 11:14:37 2012 +0800 </code></pre> <p>The Author and Commit is the same (me).</p> <p>How does this happen? I have been puzzled for days.</p> <p>There are more - it happened in 17 out of 341 commits:</p> <pre><code>+------------------------------+-------------------------------+ | from_unixtime(authored_date) | from_unixtime(committed_date) | +------------------------------+-------------------------------+ | 2012-06-15 10:57:22 | 2012-06-15 11:14:37 | | 2012-06-15 14:39:54 | 2012-06-15 14:48:57 | | 2012-06-19 12:28:21 | 2012-06-19 12:29:41 | | 2012-06-21 18:16:25 | 2012-06-21 18:28:48 | | 2012-06-26 17:30:54 | 2012-06-26 17:33:55 | | 2012-07-13 11:41:43 | 2012-07-13 11:42:17 | | 2012-07-13 11:56:02 | 2012-07-13 12:13:22 | | 2012-07-13 12:05:09 | 2012-07-13 12:12:24 | | 2012-07-12 18:38:49 | 2012-07-13 12:26:35 | | 2012-07-13 11:00:47 | 2012-07-13 12:25:15 | | 2012-07-16 14:10:54 | 2012-07-16 14:15:01 | | 2012-07-13 12:56:51 | 2012-07-16 13:49:48 | | 2012-07-16 14:10:54 | 2012-07-16 14:19:46 | | 2012-07-24 16:05:05 | 2012-07-24 16:05:48 | | 2012-07-24 17:42:58 | 2012-07-24 17:43:33 | | 2012-07-24 17:42:58 | 2012-07-24 17:45:18 | | 2012-07-26 16:55:40 | 2012-07-26 16:55:53 | +------------------------------+-------------------------------+ </code></pre>
11,857,467
3
6
null
2012-08-08 02:50:43.137 UTC
39
2022-03-07 18:44:26.887 UTC
2022-03-07 18:44:26.887 UTC
null
157,957
null
547,578
null
1
144
git
45,405
<p>The <strong>author date</strong> notes when this commit was originally made (i.e. when you finished the <code>git commit</code>). According to the docs of <a href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html" rel="noreferrer"><code>git commit</code></a>, the author date could be overridden using the <code>--date</code> switch.</p> <p>The <strong>commit date</strong> gets changed every time the commit is being modified, for example when rebasing the branch where the commit is in on another branch (<a href="https://gist.github.com/x-yuri/ec13ea740f766e72430ed8b9a9a72884" rel="noreferrer">more</a>).</p> <p>Same could happen if you make your commit and send your patch to another one in order to apply the patch in another repo: the author date will be the date of your <code>git commit</code>, the commit date will be set to that date when the patch is applied in the other repo.</p> <p>If you send the patch to two colleagues, there will be one author date but two different commit dates.</p> <p>This is also mentioned in the <a href="http://git-scm.com/book/ch2-3.html" rel="noreferrer">Git Book</a>:</p> <blockquote> <p>You may be wondering what the difference is between <em>author</em> and <em>committer</em>. The <em>author</em> is the person who originally wrote the patch, whereas the <em>committer</em> is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit &mdash; you as the author and the core member as the committer</p> </blockquote>
3,857,038
Writing TXT File with PHP, Want to Add an Actual Line Break
<p>I am writing a TXT file using PHP. I want to insert actual line breaks into the TXT file wherever necessary. I have tried all combinations of \n \r \r\n \n\r ... but these are not causing any linebreaks to appear - in most cases, I am seeing the text "\n" appear in the TXT file, with no linebreak.</p> <p>I have also tried chr(13).</p> <p>Any other ideas would be appreciated.</p>
3,857,061
5
1
null
2010-10-04 16:13:22.13 UTC
3
2012-08-29 08:38:55.703 UTC
null
null
null
null
300,129
null
1
19
php|text-files|line-breaks
44,510
<p>Sounds to me like you might be using single quotes, i.e. <code>'\n'</code> rather than <code>"\n"</code>.</p> <p>If you wanted to continue with a single quotes bias (as you should!), two options:</p> <pre><code>file_put_contents('/path/to/file.txt', 'Hello friend! This will appear on a new line. As will this'); // or file_put_contents('/path/to/file.txt', 'Hello friend!'."\n".'This will appear on a new line.'."\n".'As will this'); </code></pre>
3,707,722
how to build arrays of objects in PHP without specifying an index number?
<p>Here is a weird question. I am building an array of objects manually, like this:</p> <pre><code>$pages_array[0]-&gt;slug = "index"; $pages_array[0]-&gt;title = "Site Index"; $pages_array[0]-&gt;template = "interior"; $pages_array[1]-&gt;slug = "a"; $pages_array[1]-&gt;title = "100% Wide (Layout A)"; $pages_array[1]-&gt;template = "interior"; $pages_array[2]-&gt;slug = "homepage"; $pages_array[2]-&gt;title = "Homepage"; $pages_array[2]-&gt;template = "homepage"; </code></pre> <p>I like how clearcut this is, but because I have to specify the index number, I can't rearrange them easily. How can I do this without the index number? Related, what is a better way to do this?</p> <p>I also tried writing this by making a class, and having each spot on the array be instances of that class. But since this is a configuration file, it was hard to read and know what argument went with what parameter. That's why I chose this old-school method above.</p> <p>Any thoughts are much appreciated!</p>
3,707,800
6
2
null
2010-09-14 09:42:36.163 UTC
6
2021-03-22 12:28:41.25 UTC
null
null
null
null
447,186
null
1
29
php|arrays|object
86,746
<p>This code</p> <pre><code> $pages_array[1]-&gt;slug = "a"; </code></pre> <p>is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:</p> <pre><code> $pages_array[] = new MyObject('index', 'title'....) </code></pre> <p>or using a stdclass cast</p> <pre><code> $pages_array[] = (object) array('slug' =&gt; 'xxx', 'title' =&gt; 'etc') </code></pre>
4,010,158
Is it possible to get a list of files under a directory of a website? How?
<p>Say I have a website <code>www.example.com</code>. Under the website directory there is a page <code>secret.html</code>. It can be accessed directly like <code>www.example.com/secret.html</code>, but there are no pages that link to it. Is it possible to discover this page, or will it remain hidden from outside world?</p>
4,010,177
6
2
null
2010-10-24 20:00:59.733 UTC
18
2021-11-06 08:48:20.3 UTC
2021-11-06 08:47:58.423 UTC
null
1,145,388
null
147,530
null
1
75
html|url|webserver|hidden
581,110
<p>If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.</p> <p>That said, I've seen hacking scripts attempt to &quot;guess&quot; a whole bunch of these common names. <code>secret.html</code> would probably be in such a guess list.</p> <p>The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.</p>
3,621,067
Why is the range of bytes -128 to 127 in Java?
<p>I don't understand why the lowest value a byte can take is <code>-128</code>. I can see that the highest value is <code>127</code>, because it's <code>01111111</code> in binary, but how does one represent <code>-128</code> with only 8 bits, one of which is used for the sign? Positive 128 would already be 8-bit, i.e. <code>10000000</code>, and then you would need a 9th bit to represent the negative sign. </p> <p>Could someone please help explain this to me.</p>
3,621,099
8
3
null
2010-09-01 18:33:37.56 UTC
34
2019-03-07 21:01:42.407 UTC
2012-05-02 06:52:50.027 UTC
null
1,268,895
null
243,500
null
1
83
java|byte
84,728
<p>The answer is <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">two's complement</a>.</p> <p>In short, Java (and most modern languages) do not represent signed integers using signed-magnitude representation. In other words, an 8-bit integer is not a sign bit followed by a 7-bit unsigned integer. </p> <p>Instead, negative integers are represented in a system called two's complement, which allows easier arithmetic processing in hardware, and also eliminates the potential ambiguity of having positive zero and negative zero. A side effect of eliminating negative zero is that there is always one extra negative number available at the bottom of the range. </p> <p>Another interesting property of two's complement systems is that the first bit does <em>effectively</em> function as a sign indicator (i.e. all numbers beginning with the bit 1 are negative), but the next seven bits are not to be interpreted on their own as an unsigned number to which the sign bit is applied.</p> <p>Two's complement isn't terribly complicated, but getting an initial good grip on what two's complement is and how and why it works is probably beyond the scope of an SO answer. Start with the Wikipedia article, or google the term for more resources.</p> <p>To try to briefly address your query about -128, the fundamental idea behind generating a two's complement number is to take the unsigned form of the number, invert all of the bits and add one. So unsigned 128 is 10000000. Inverted, it's 01111111, and adding one gets 10000000 again. So in a two's complement system, 10000000 is unambiguously -128 and not +128. Numbers greater than or equal to +128 simply cannot be represented in 8 bits using a two's complement system because they would be ambiguous with the forms of negative numbers.</p>
3,435,581
How to count lines of Java code using IntelliJ IDEA?
<p>How to count lines of Java code using IntelliJ IDEA?</p>
4,341,885
9
1
null
2010-08-08 18:45:55.607 UTC
37
2021-01-09 00:08:08.55 UTC
2020-02-12 12:15:27.51 UTC
null
1,788,806
null
52,563
null
1
338
java|intellij-idea|metrics
185,974
<p>The <a href="https://plugins.jetbrains.com/idea/search?correctionAllowed=true&amp;search=statistic" rel="noreferrer">Statistic</a> plugin worked for me.</p> <p>To install it from Intellij:</p> <blockquote> <p>File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.</p> </blockquote> <p>Access the 'statistic' toolbar via tabs in bottom left of project <a href="https://i.stack.imgur.com/CQ7LY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CQ7LY.png" alt="screen capture of statistic toolbar, bottom left" /></a></p> <p>OLDER VERSIONS: Open statistics window from:</p> <blockquote> <p>View -&gt; Tool Windows -&gt; Statistic</p> </blockquote>
3,586,207
Validate HTML on local machine
<p>I'm currently trying to learn HTML and Java EE Servlet programming. I have an application server running on my local machine (Orion Application Server) and I'm connecting to web pages I've deployed on this server using a browser running on the same machine, directed to <a href="http://localhost/mypage.htm" rel="noreferrer">http://localhost/mypage.htm</a> (for example).</p> <p>I know W3C has a site you can go to that will validate an HTML page (and count how many errors are found for a given doctype), but that has to be a publicly available URL. How do you validate HTML on a locally running setup like I've described above?</p>
3,586,244
10
1
null
2010-08-27 16:21:26.07 UTC
7
2021-12-16 14:53:55.783 UTC
2016-10-21 04:10:54.027 UTC
null
441,757
null
348,408
null
1
39
html|validation|localhost|w3c-validation
50,290
<p>many options:</p> <p>see installation of w3c validation service:</p> <p><a href="http://validator.w3.org/docs/install.html" rel="noreferrer">http://validator.w3.org/docs/install.html</a></p> <p>Firefox addons:</p> <p><a href="https://stackoverflow.com/questions/918419/firefox-addon-or-other-tool-to-locally-validate-html-pages">Firefox addon or other tool to locally validate HTML pages</a></p> <p><a href="https://addons.mozilla.org/en-US/firefox/addon/249/" rel="noreferrer">https://addons.mozilla.org/en-US/firefox/addon/249/</a></p> <p>Offline validator: </p> <p><a href="http://htmlhelp.com/tools/validator/offline/index.html.en" rel="noreferrer">http://htmlhelp.com/tools/validator/offline/index.html.en</a></p>
7,742,143
How are scrollbars in new Google Docs UI styled (esp. the arrow buttons)?
<p>The new Google Docs UI features cool gray scrollbars.</p> <p><img src="https://i.stack.imgur.com/UtLjS.png" alt="Screenshot of the Google Docs UI"></p> <p>These appear to be regular scrollbars styled with selectors like <code>::-webkit-scrollbar-thumb</code>. Which is nice and accessible.</p> <p>However, I can't get arrow buttons to appear (circled on the screenshot). Inspector shows no corresponding DOM elements or any special CSS. So the question is, <strong>how these custom scrollbars are made, including the arrow buttons?</strong></p> <p>Please check out <a href="http://jsfiddle.net/9hMXL/2/" rel="noreferrer">this fiddle</a>.</p> <p>Edit:</p> <p>So it seems that just not all css rules appear in the Inspector.</p> <p>In particular, you'd need <code>::-webkit-scrollbar-button:vertical:decrement</code> and <code>::-webkit-scrollbar-button:vertical:increment</code>, and their <code>horizontal</code> equivalents.</p> <p>Please see <a href="http://jsfiddle.net/9hMXL/199/" rel="noreferrer"><strong>new fiddle</strong></a> (updated 27 Apr. 2012).</p>
7,742,387
4
1
null
2011-10-12 15:00:11.213 UTC
8
2017-07-24 15:17:59.11 UTC
2012-04-27 12:21:07.507 UTC
null
247,441
null
247,441
null
1
24
css|scrollbar|styling|google-docs
14,377
<p>It looks like the css tags for the handles don't show up in Chrome's dev tools. You have to examine the source of the sample to see what is really going on.</p> <p><a href="http://www.webkit.org/blog/363/styling-scrollbars/">http://www.webkit.org/blog/363/styling-scrollbars/</a></p>
7,714,868
multiprocessing: How can I ʀᴇʟɪᴀʙʟʏ redirect stdout from a child process?
<p>NB. I have seen <a href="https://stackoverflow.com/questions/1501651/log-output-of-multiprocessing-process">Log output of multiprocessing.Process</a> - unfortunately, it doesn't answer this question.</p> <p>I am creating a child process (on windows) via multiprocessing. I want <em>all</em> of the child process's stdout and stderr output to be redirected to a log file, rather than appearing at the console. The only suggestion I have seen is for the child process to set sys.stdout to a file. However, this does not effectively redirect all stdout output, due to the behaviour of stdout redirection on Windows. </p> <p>To illustrate the problem, build a Windows DLL with the following code</p> <pre><code>#include &lt;iostream&gt; extern "C" { __declspec(dllexport) void writeToStdOut() { std::cout &lt;&lt; "Writing to STDOUT from test DLL" &lt;&lt; std::endl; } } </code></pre> <p>Then create and run a python script like the following, which imports this DLL and calls the function:</p> <pre><code>from ctypes import * import sys print print "Writing to STDOUT from python, before redirect" print sys.stdout = open("stdout_redirect_log.txt", "w") print "Writing to STDOUT from python, after redirect" testdll = CDLL("Release/stdout_test.dll") testdll.writeToStdOut() </code></pre> <p>In order to see the same behaviour as me, it is probably necessary for the DLL to be built against a different C runtime than than the one Python uses. In my case, python is built with Visual Studio 2010, but my DLL is built with VS 2005.</p> <p>The behaviour I see is that the console shows:</p> <pre><code>&gt; stdout_test.py Writing to STDOUT from python, before redirect Writing to STDOUT from test DLL </code></pre> <p>While the file stdout_redirect_log.txt ends up containing:</p> <pre><code>Writing to STDOUT from python, after redirect </code></pre> <p>In other words, setting sys.stdout failed to redirect the stdout output generated by the DLL. This is unsurprising given the nature of the underlying APIs for stdout redirection in Windows. I have encountered this problem at the native/C++ level before and never found a way to reliably redirect stdout from within a process. It has to be done externally.</p> <p>This is actually the very reason I am launching a child process - it's so that I can connect externally to its pipes and thus guarantee that I am intercepting all of its output. I can definitely do this by launching the process manually with pywin32, but I would very much like to be able to use the facilities of multiprocessing, in particular the ability to communicate with the child process via a multiprocessing Pipe object, in order to get progress updates. The question is whether there is any way to both use multiprocessing for its IPC facilities <strong>and</strong> to reliably redirect all of the child's stdout and stderr output to a file.</p> <p><strong>UPDATE:</strong> Looking at the source code for multiprocessing.Processs, it has a static member, _Popen, which looks like it can be used to override the class used to create the process. If it's set to None (default), it uses a multiprocessing.forking._Popen, but it looks like by saying</p> <pre><code>multiprocessing.Process._Popen = MyPopenClass </code></pre> <p>I could override the process creation. However, although I could derive this from multiprocessing.forking._Popen, it looks like I would have to copy a bunch of internal stuff into my implementation, which sounds flaky and not very future-proof. If that's the only choice I think I'd probably plump for doing the whole thing manually with pywin32 instead.</p>
11,779,039
6
5
null
2011-10-10 15:10:49.687 UTC
9
2022-03-10 16:16:48.443 UTC
2021-05-20 01:45:17.117 UTC
null
355,230
null
457,139
null
1
36
python|windows|stdout|multiprocessing|stderr
25,065
<p>The solution you suggest is a good one: create your processes manually such that you have explicit access to their stdout/stderr file handles. You can then create a socket to communicate with the sub-process and use multiprocessing.connection over that socket (multiprocessing.Pipe creates the same type of connection object, so this should give you all the same IPC functionality).</p> <p>Here's a two-file example.</p> <p><strong>master.py:</strong></p> <pre><code>import multiprocessing.connection import subprocess import socket import sys, os ## Listen for connection from remote process (and find free port number) port = 10000 while True: try: l = multiprocessing.connection.Listener(('localhost', int(port)), authkey="secret") break except socket.error as ex: if ex.errno != 98: raise port += 1 ## if errno==98, then port is not available. proc = subprocess.Popen((sys.executable, "subproc.py", str(port)), stdout=subprocess.PIPE, stderr=subprocess.PIPE) ## open connection for remote process conn = l.accept() conn.send([1, "asd", None]) print(proc.stdout.readline()) </code></pre> <p><strong>subproc.py:</strong></p> <pre><code>import multiprocessing.connection import subprocess import sys, os, time port = int(sys.argv[1]) conn = multiprocessing.connection.Client(('localhost', port), authkey="secret") while True: try: obj = conn.recv() print("received: %s\n" % str(obj)) sys.stdout.flush() except EOFError: ## connection closed break </code></pre> <p>You may also want to see the first answer to <a href="https://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python">this question</a> to get non-blocking reads from the subprocess.</p>
7,742,148
How to convert text to SVG paths?
<p>I have a font in ttf file and want to generate SVG with text turned into paths. I don't need image (so using imagettftext or Image Magick font rendering capabilities is not enough), I need shape, that can be scaled up and down and I want to lose information about font used and don't want to reference it in SVG file (so font-face declarations can't be used here). Is it possible?</p>
9,558,337
6
0
null
2011-10-12 15:00:33.707 UTC
28
2020-05-12 10:48:29.657 UTC
null
null
null
null
179,482
null
1
50
php|text|svg|truetype
51,584
<p>I have created my own class to process SVG font file and to turn text into glyphs. Example of using:</p> <pre><code>include "SVGFont.php"; $svgFont = new SVGFont(); $svgFont-&gt;load("/path/to/font.svg"); $result = $svgFont-&gt;textToPaths("Simple text", 20); </code></pre> <p>Example result:</p> <pre><code>&lt;g transform="scale(0.009765625) translate(0, 0)"&gt;&lt;path transform="translate(0,0) rotate(180) scale(-1, 1)" d="M92 471l183 16q13 -110 60.5 -180.5t147.5 -114t225 -43.5q111 0 196 33t126.5 90.5t41.5 125.5q0 69 -40 120.5t-132 86.5q-59 23 -261 71.5t-283 91.5q-105 55 -156.5 136.5t-51.5 182.5q0 111 63 207.5t184 146.5t269 50q163 0 287.5 -52.5t191.5 -154.5t72 -231 l-186 -14q-15 139 -101.5 210t-255.5 71q-176 0 -256.5 -64.5t-80.5 -155.5q0 -79 57 -130q56 -51 292.5 -104.5t324.5 -93.5q128 -59 189 -149.5t61 -208.5q0 -117 -67 -220.5t-192.5 -161t-282.5 -57.5q-199 0 -333.5 58t-211 174.5t-80.5 263.5z" /&gt;&lt;path transform="translate(1366,0) rotate(180) scale(-1, 1)" d="M136 0v1062h180v-1062h-180zM136 1259v207h180v-207h-180z" /&gt;&lt;path transform="translate(1821,0) rotate(180) scale(-1, 1)" d="M135 0v1062h161v-149q50 78 133 125.5t189 47.5q118 0 193.5 -49t106.5 -137q126 186 328 186q158 0 243 -87.5t85 -269.5v-729h-179v669q0 108 -17.5 155.5t-63.5 76.5t-108 29q-112 0 -186 -74.5t-74 -238.5v-617h-180v690q0 120 -44 180t-144 60q-76 0 -140.5 -40 t-93.5 -117t-29 -222v-551h-180z" /&gt;&lt;path transform="translate(3527,0) rotate(180) scale(-1, 1)" d="M135 -407v1469h164v-138q58 81 131 121.5t177 40.5q136 0 240 -70t157 -197.5t53 -279.5q0 -163 -58.5 -293.5t-170 -200t-234.5 -69.5q-90 0 -161.5 38t-117.5 96v-517h-180zM298 525q0 -205 83 -303t201 -98q120 0 205.5 101.5t85.5 314.5q0 203 -83.5 304t-199.5 101 q-115 0 -203.5 -107.5t-88.5 -312.5z" /&gt;&lt;path transform="translate(4666,0) rotate(180) scale(-1, 1)" d="M131 0v1466h180v-1466h-180z" /&gt;&lt;path transform="translate(5121,0) rotate(180) scale(-1, 1)" d="M75 522q0 268 138 416t358 148q213 0 348 -145t135 -408q0 -16 -1 -48h-792q10 -175 99 -268t222 -93q99 0 169 52t111 166l186 -23q-44 -163 -163 -253t-304 -90q-233 0 -369.5 143.5t-136.5 402.5zM271 633h593q-12 134 -68 201q-86 104 -223 104q-124 0 -208.5 -83 t-93.5 -222z" /&gt;&lt;path transform="translate(6260,0) rotate(180) scale(-1, 1)" d="" /&gt;&lt;path transform="translate(6829,0) rotate(180) scale(-1, 1)" d="M36 922v140h132v263l179 108v-371h181v-140h-181v-621q0 -77 9.5 -99t31 -35t61.5 -13q30 0 79 7l26 -159q-76 -16 -136 -16q-98 0 -152 31t-76 81.5t-22 212.5v611h-132z" /&gt;&lt;path transform="translate(7398,0) rotate(180) scale(-1, 1)" d="M75 522q0 268 138 416t358 148q213 0 348 -145t135 -408q0 -16 -1 -48h-792q10 -175 99 -268t222 -93q99 0 169 52t111 166l186 -23q-44 -163 -163 -253t-304 -90q-233 0 -369.5 143.5t-136.5 402.5zM271 633h593q-12 134 -68 201q-86 104 -223 104q-124 0 -208.5 -83 t-93.5 -222z" /&gt;&lt;path transform="translate(8537,0) rotate(180) scale(-1, 1)" d="M15 0l388 552l-359 510h225l163 -249q46 -71 74 -119q44 66 81 117l179 251h215l-367 -500l395 -562h-221l-218 330l-58 89l-279 -419h-218z" /&gt;&lt;path transform="translate(9561,0) rotate(180) scale(-1, 1)" d="M36 922v140h132v263l179 108v-371h181v-140h-181v-621q0 -77 9.5 -99t31 -35t61.5 -13q30 0 79 7l26 -159q-76 -16 -136 -16q-98 0 -152 31t-76 81.5t-22 212.5v611h-132z" /&gt;&lt;/g&gt; </code></pre> <p>Code for my class:</p> <pre><code>&lt;?php /** * This class represents SVG pa * @author Łukasz Ledóchowski [email protected] * @version 0.1 */ class SVGFont { protected $id = ''; protected $horizAdvX = 0; protected $unitsPerEm = 0; protected $ascent = 0; protected $descent = 0; protected $glyphs = array(); /** * Function takes UTF-8 encoded string and returns unicode number for every character. * Copied somewhere from internet, thanks. */ function utf8ToUnicode( $str ) { $unicode = array(); $values = array(); $lookingFor = 1; for ($i = 0; $i &lt; strlen( $str ); $i++ ) { $thisValue = ord( $str[ $i ] ); if ( $thisValue &lt; 128 ) $unicode[] = $thisValue; else { if ( count( $values ) == 0 ) $lookingFor = ( $thisValue &lt; 224 ) ? 2 : 3; $values[] = $thisValue; if ( count( $values ) == $lookingFor ) { $number = ( $lookingFor == 3 ) ? ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ): ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 ); $unicode[] = $number; $values = array(); $lookingFor = 1; } } } return $unicode; } /** * Function takes path to SVG font (local path) and processes its xml * to get path representation of every character and additional * font parameters */ public function load($filename) { $this-&gt;glyphs = array(); $z = new XMLReader; $z-&gt;open($filename); // move to the first &lt;product /&gt; node while ($z-&gt;read()) { $name = $z-&gt;name; if ($z-&gt;nodeType == XMLReader::ELEMENT) { if ($name == 'font') { $this-&gt;id = $z-&gt;getAttribute('id'); $this-&gt;horizAdvX = $z-&gt;getAttribute('horiz-adv-x'); } if ($name == 'font-face') { $this-&gt;unitsPerEm = $z-&gt;getAttribute('units-per-em'); $this-&gt;ascent = $z-&gt;getAttribute('ascent'); $this-&gt;descent = $z-&gt;getAttribute('descent'); } if ($name == 'glyph') { $unicode = $z-&gt;getAttribute('unicode'); $unicode = $this-&gt;utf8ToUnicode($unicode); $unicode = $unicode[0]; $this-&gt;glyphs[$unicode] = new stdClass(); $this-&gt;glyphs[$unicode]-&gt;horizAdvX = $z-&gt;getAttribute('horiz-adv-x'); if (empty($this-&gt;glyphs[$unicode]-&gt;horizAdvX)) { $this-&gt;glyphs[$unicode]-&gt;horizAdvX = $this-&gt;horizAdvX; } $this-&gt;glyphs[$unicode]-&gt;d = $z-&gt;getAttribute('d'); } } } } /** * Function takes UTF-8 encoded string and size, returns xml for SVG paths representing this string. * @param string $text UTF-8 encoded text * @param int $asize size of requested text * @return string xml for text converted into SVG paths */ public function textToPaths($text, $asize) { $lines = explode("\n", $text); $result = ""; $horizAdvY = 0; foreach($lines as $text) { $text = $this-&gt;utf8ToUnicode($text); $size = ((float)$asize) / $this-&gt;unitsPerEm; $result .= "&lt;g transform=\"scale({$size}) translate(0, {$horizAdvY})\"&gt;"; $horizAdvX = 0; for($i = 0; $i &lt; count($text); $i++) { $letter = $text[$i]; $result .= "&lt;path transform=\"translate({$horizAdvX},{$horizAdvY}) rotate(180) scale(-1, 1)\" d=\"{$this-&gt;glyphs[$letter]-&gt;d}\" /&gt;"; $horizAdvX += $this-&gt;glyphs[$letter]-&gt;horizAdvX; } $result .= "&lt;/g&gt;"; $horizAdvY += $this-&gt;ascent + $this-&gt;descent; } return $result; } } </code></pre>
8,225,776
Why does sizeof(x++) not increment x?
<p>Here is the code compiled in dev c++ windows:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int x = 5; printf("%d and ", sizeof(x++)); // note 1 printf("%d\n", x); // note 2 return 0; } </code></pre> <p>I expect <code>x</code> to be 6 after executing <strong>note 1</strong>. However, the output is:</p> <pre><code>4 and 5 </code></pre> <p>Can anyone explain why <code>x</code> does not increment after <strong>note 1</strong>?</p>
8,225,835
10
2
null
2011-11-22 11:07:16.623 UTC
122
2021-08-02 12:08:28.65 UTC
2011-11-24 15:16:53.87 UTC
null
27,615
null
559,397
null
1
523
c|sizeof
33,600
<p>From the <a href="http://www.open-std.org/JTC1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">C99 Standard</a> (the emphasis is mine)</p> <blockquote> <p>6.5.3.4/2</p> <p>The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, <strong>the operand is not evaluated</strong> and the result is an integer constant.</p> </blockquote>
4,259,128
How can I create a multilingual android application?
<p>I would like to create a multilingual android application.</p> <p>Is there a way to detect what language the user prefers?</p> <p>Is there a recommended way to manage multiple languages on Android or should I reinvent the wheel?</p>
4,259,200
3
0
null
2010-11-23 17:49:58.303 UTC
14
2019-01-31 11:15:17.18 UTC
2011-10-26 02:22:20.157 UTC
null
467,090
null
97,688
null
1
26
android|internationalization
47,180
<p>Yes, there is a recommended way to manage multiple languages</p> <blockquote> <p>Multilanguage support is easy done for android. Create a new values directory for the language with the suffix of the language code. For german: values-de or french: values-fr than copy your string.xml into that and translate each entry. Thats all you need.</p> <p><a href="https://stackoverflow.com/questions/3626976/do-android-support-multiple-languages">Do android support multiple languages?</a></p> </blockquote> <p>Providing you follow the recommendations, detecting which language the user prefers is automatic.</p> <p>Have a read of this:</p> <p><a href="http://developer.android.com/guide/topics/resources/localization.html" rel="noreferrer">http://developer.android.com/guide/topics/resources/localization.html</a></p>
4,709,369
How to declare a inline object with inline variables without a parent class
<p>I am trying to do something like:</p> <pre><code>Object [] x = new Object[2]; x[0]=new Object(){firstName="john";lastName="walter"}; x[1]=new Object(){brand="BMW"}; </code></pre> <p>I want to know if there is a way to achieve that inline declaration in C#</p>
4,709,392
3
0
null
2011-01-17 01:45:14.533 UTC
11
2018-06-19 22:50:50.173 UTC
2014-02-20 09:23:27.91 UTC
null
552,301
null
552,301
null
1
57
c#
119,362
<p>yes, there is:</p> <pre><code>object[] x = new object[2]; x[0] = new { firstName = "john", lastName = "walter" }; x[1] = new { brand = "BMW" }; </code></pre> <p>you were practically there, just the <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx">declaration of the anonymous types</a> was a little off.</p>
4,509,912
Is it possible to use BitmapFactory.decodeFile method to decode a image from http location?
<p>I would like to know if it is possible to use BitmapFactory.decodeFile method to decode a image from http location? </p> <p>For eg. </p> <pre><code>ImageView imageview = new ImageView(context); Bitmap bmp = BitmapFactory.decodeFile("http://&lt;my IP&gt;/test/abc.jpg"); imageview.setImageBitmap(bmp); </code></pre> <p>But bmp is always returning null. </p> <p>Is there any other way to achieve this scenario, where i have a set of images in my server PC, and i am loading the images to my gallery application via an xml? </p> <p>Thanks,<br> Sen</p>
4,516,150
5
4
null
2010-12-22 14:02:16.28 UTC
9
2015-05-12 15:04:03.667 UTC
null
null
null
null
449,378
null
1
11
android|http|bitmap
21,947
<p>@Amir &amp; @Sankar : Thanks for your valuable suggestions.</p> <p>I solved the above problem by doing the following code snippet : </p> <pre><code>ImageView iv = new ImageView(context); try{ String url1 = "http://&lt;my IP&gt;/test/abc.jpg"; URL ulrn = new URL(url1); HttpURLConnection con = (HttpURLConnection)ulrn.openConnection(); InputStream is = con.getInputStream(); Bitmap bmp = BitmapFactory.decodeStream(is); if (null != bmp) iv.setImageBitmap(bmp); else System.out.println("The Bitmap is NULL"); } catch(Exception e) { } </code></pre> <p>Thanks,<br> Sen</p>
4,505,718
How to replace part of an input value in jQuery?
<p>I've been trying to figure out a way to replace part of a string in an <em>input</em> value, but haven't been able to get it working.</p> <p>The <em>input field</em> looks like this:</p> <pre><code>&lt;input type="text" value="20,54,26,99" name="ids" /&gt; </code></pre> <p>I've tried:</p> <pre><code>$('input[name=ids]').val().replace("54,",""); </code></pre> <p>and</p> <pre><code>var replit = $('input[name=ids]').val(); replit.replace("54,",""); $('input[name=ids]').val(replit); </code></pre> <p>but neither worked?</p>
4,505,751
5
0
null
2010-12-22 02:37:31.57 UTC
3
2019-11-11 11:13:42.267 UTC
2019-11-11 11:13:42.267 UTC
null
814,702
null
550,623
null
1
12
jquery|replace
47,206
<pre><code>$('input[name=ids]').val(function(index, value) { return value.replace('54,', ''); }); </code></pre>
4,589,622
Simplifying const Overloading?
<p>I've been teaching a C++ programming class for many years now and one of the trickiest things to explain to students is const overloading. I commonly use the example of a vector-like class and its <code>operator[]</code> function:</p> <pre><code>template &lt;typename T&gt; class Vector { public: T&amp; operator[] (size_t index); const T&amp; operator[] (size_t index) const; }; </code></pre> <p>I have little to no trouble explaining why it is that two versions of the <code>operator[]</code> function are needed, but in trying to explain how to unify the two implementations together I often find myself wasting a lot of time with language arcana. The problem is that the only good, reliable way that I know how to implement one of these functions in terms of the other is with the <code>const_cast</code>/<code>static_cast</code> trick:</p> <pre><code>template &lt;typename T&gt; const T&amp; Vector&lt;T&gt;::operator[] (size_t index) const { /* ... your implementation here ... */ } template &lt;typename T&gt; T&amp; Vector&lt;T&gt;::operator[] (size_t index) { return const_cast&lt;T&amp;&gt;(static_cast&lt;const Vector&amp;&gt;(*this)[index]); } </code></pre> <p>The problem with this setup is that it's extremely tricky to explain and not at all intuitively obvious. When you explain it as "cast to const, then call the const version, then strip off constness" it's a little easier to understand, but the actual syntax is frightening,. Explaining what <code>const_cast</code> is, why it's appropriate here, and why it's almost universally inappropriate elsewhere usually takes me five to ten minutes of lecture time, and making sense of this whole expression often requires more effort than the difference between <code>const T*</code> and <code>T* const</code>. I feel that students need to know about const-overloading and how to do it without needlessly duplicating the code in the two functions, but this trick seems a bit excessive in an introductory C++ programming course.</p> <p>My question is this - is there a simpler way to implement <code>const</code>-overloaded functions in terms of one another? Or is there a simpler way of explaining this existing trick to students?</p>
4,589,659
7
16
null
2011-01-04 00:20:41.823 UTC
8
2012-12-01 23:19:16.733 UTC
2012-12-01 23:19:16.733 UTC
null
128,421
null
501,557
null
1
43
c++|constants|overloading
4,534
<p>How about simply breaking it down into smaller steps?</p> <pre><code>const Vector&lt;T&gt;&amp; const_this = *this; const T&amp; const_elem = const_this[index]; T&amp; mutable_elem = const_cast&lt;T&amp;&gt;(const_elem); return mutable_elem; </code></pre> <p>You can even eliminate the <code>static_cast</code> this way, although you could leave it in if you think it would be clearer.</p>
14,449,118
PHP + Ajax Login
<p>Just having a few issues submitting a login form via ajax, I am primarily a PHP developer, I don't use Jquery + Ajax all that often with PHP.</p> <p>At the moment If i check the firebug POST data after the form has been submit it does appear to get the username and password that have been added to the form, however the page just reloads regardless of whether an incorrect username and password are added or if they are correct and no session is created.</p> <p>This is the form:</p> <pre><code> &lt;form id="loginform" method="post"&gt; Username: &lt;input type="text" name="username" id="username" value=""&gt; Password: &lt;input type="password" name="password" id="password" value=""&gt; &lt;input type="submit" name="loginsub" id="loginsub" value="Login"&gt; &lt;/form&gt; </code></pre> <p>This is the Ajax/Jquery:</p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#loginform').submit(function() { $.ajax({ type: "POST", url: '/class/login.php', data: { username: $("#username").val(), password: $("#password").val() }, success: function(data) { if (data === 'Login') { window.location.replace('/user-page.php'); } else { alert('Invalid Credentials'); } } }); }); }); &lt;/script&gt; </code></pre> <p>And this is the PHP:</p> <pre><code> class Users { public $username = null; public $password = null; public function __construct( $data = array() ) { if( isset( $data['username'] ) ) $this-&gt;username = stripslashes( strip_tags( $data['username'] ) ); if( isset( $data['password'] ) ) $this-&gt;password = stripslashes( strip_tags( $data['password'] ) ); } public function storeFormValues( $params ) { $this-&gt;__construct( $params ); } public function Login() { $success = false; try{ $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $con-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1"; $user = username; $stmt = $con-&gt;prepare( $sql ); $stmt-&gt;bindValue( "username", $this-&gt;username, PDO::PARAM_STR ); $stmt-&gt;bindValue( "password", md5($this-&gt;password), PDO::PARAM_STR ); $stmt-&gt;execute(); $valid = $stmt-&gt;fetchColumn(); if( $valid ) { $success = true; session_start(); session_regenerate_id(); $_SESSION['user'] = $user['user']; session_write_close(); echo ('Login'); exit(); } $con = null; return $success; }catch (PDOException $e) { echo $e-&gt;getMessage(); return $success; } } </code></pre> <p>I guess it is not working because I am not calling the class and function, but I am not sure how to succesfully do so. I tried creating a controller page in between the 2 that would initiate the php class and function but to no avail.</p> <p>Just to edit, the login does work correctly if I remove the ajax and just call the php page via the login form action.</p> <p>Any ideas?</p>
14,449,231
3
7
null
2013-01-21 23:33:45.377 UTC
5
2019-01-23 16:42:07.483 UTC
2013-01-22 00:21:08.663 UTC
null
443
null
1,852,170
null
1
9
php|jquery|ajax
64,364
<p>whole issue is in jquery use this instead</p> <pre><code>$(document).ready(function() { $('#loginform').submit(function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '/class/login.php', data: $(this).serialize(), success: function(data) { if (data === 'Login') { window.location = '/user-page.php'; } else { alert('Invalid Credentials'); } } }); }); }); </code></pre>
14,637,150
View the file system of iPad/iPhone to verify saved files
<p>I would like to be able to view the file system of my actual iPad/iPhone to verify that files are being written correctly. I can do this using the simulator by navigating to Users/<em>me</em>/Library/Application Support/iPhone Simulator/6.0/Applications/<em>specific app</em>/Documents. Here I can see all of the files and data I have written from within my app.</p> <p>I would be really helpful if anyone knows of an app or some way of viewing the file system of my apps <strong>WITHOUT JAIL BREAKING</strong> </p> <p>Thanks in advance</p>
14,637,311
4
0
null
2013-01-31 23:36:11.897 UTC
2
2022-06-10 18:39:46.257 UTC
null
null
null
null
329,900
null
1
12
ios|filesystems|sandbox
66,462
<p>Take a look at iExplorer: <a href="http://www.macroplant.com/iexplorer/" rel="nofollow noreferrer">http://www.macroplant.com/iexplorer/</a></p> <p>Also, look at this question: <a href="https://apple.stackexchange.com/questions/54682/easiest-way-to-browse-iphone-filesystem">https://apple.stackexchange.com/questions/54682/easiest-way-to-browse-iphone-filesystem</a></p>
14,735,762
Load HTML page dynamically into div with jQuery
<p>I'm trying to make it so when I click on a link in a HTML page, it dynamically loads the requested page into a div with jQuery.</p> <p>How can I do that?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; // what can I do for load any url clicked? &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;a href="page1.html"&gt;Page 1&lt;/a&gt;&lt;br /&gt; &lt;a href="page2.html"&gt;Page 2&lt;/a&gt;&lt;br /&gt; &lt;a href="page3.html"&gt;Page 3&lt;/a&gt;&lt;br /&gt; &lt;a href="page4.html"&gt;Page 4&lt;/a&gt;&lt;br /&gt; &lt;a href="page5.html"&gt;Page 5&lt;/a&gt;&lt;br /&gt; &lt;a href="page6.html"&gt;Page 6&lt;/a&gt;&lt;br /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
14,742,452
7
1
null
2013-02-06 18:01:34.877 UTC
16
2015-12-03 16:07:20.267 UTC
2013-09-29 12:06:12.733 UTC
null
1,746,298
null
1,746,298
null
1
16
javascript|jquery|html|css
140,213
<p>There's a jQuery plugin out there called <a href="https://github.com/defunkt/jquery-pjax">pjax</a> it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."</p> <p>The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.</p> <p>What pjax does is that it listens on specified page elements such as <code>&lt;a&gt;</code>. Then when the <code>&lt;a href=""&gt;&lt;/a&gt;</code> element is invoked, the target page is fetched with either the <code>X-PJAX</code> header, or a specified fragment.</p> <p>Example:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).pjax('a', '#pjax-container'); &lt;/script&gt; </code></pre> <p>Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.</p> <p>(meaning you want to replace <code>#pjax-container</code> on the current page with <code>#pjax-container</code> from the remote page)</p> <p>When <code>&lt;a&gt;</code> is invoked, it will fetch the link with the request header <code>X-PJAX</code> and will look for the contents of <code>#pjax-container</code> in the result. If the result is <code>#pjax-container</code>, the container on the current page will be replaced with the new result.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.pjax.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).pjax('a', '#pjax-container'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;My Site&lt;/h1&gt; &lt;div class="container" id="pjax-container"&gt; Go to &lt;a href="/page2"&gt;next page&lt;/a&gt;. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If <code>#pjax-container</code> is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send <code>#pjax-container</code>.</p> <p>Example server side code of <code>page2</code>:</p> <pre><code>//if header X-PJAX == true in request headers, send &lt;div class="container" id="pjax-container"&gt; Go to &lt;a href="/page1"&gt;next page&lt;/a&gt;. &lt;/div&gt; //else send full page </code></pre> <p>If you can't change server-side code, then the fragment option is an alternative.</p> <pre><code>$(document).pjax('a', '#pjax-container', { fragment: '#pjax-container' }); </code></pre> <p>Note that <code>fragment</code> is an older pjax option and appears to fetch the child element of requested element.</p>
14,821,329
Freemarker and hashmap. How do I get key-value
<p>I have a hash map as below</p> <pre><code>HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); map.put("one", "1"); map.put("two", "2"); map.put("three", "3"); Map root = new HashMap(); root.put("hello", map); </code></pre> <p>My Freemarker template is:</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;#list hello?keys as key&gt; ${key} = ${hello[key]} &lt;/#list&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>The goal is to display key-value pair in the HTML that I'm generating. Please help me to do it. Thanks!</p>
14,821,487
4
1
null
2013-02-11 21:38:31.733 UTC
6
2022-01-23 00:37:45.03 UTC
2014-03-09 22:58:39.483 UTC
null
179,850
null
1,629,109
null
1
25
java|html|freemarker
78,788
<p><strong>Code:</strong></p> <pre><code>Map root = new HashMap(); HashMap&lt;String, String&gt; test1 = new HashMap&lt;String, String&gt;(); test1.put(&quot;one&quot;, &quot;1&quot;); test1.put(&quot;two&quot;, &quot;2&quot;); test1.put(&quot;three&quot;, &quot;3&quot;); root.put(&quot;hello&quot;, test1); Configuration cfg = new Configuration(); // Create configuration Template template = cfg.getTemplate(&quot;test.ftl&quot;); // Filename of your template StringWriter sw = new StringWriter(); // So you can use the output as String template.process(root, sw); // process the template to output System.out.println(sw); // eg. output your result </code></pre> <p><strong>Template:</strong></p> <pre><code>&lt;body&gt; &lt;#list hello?keys as key&gt; ${key} = ${hello[key]} &lt;/#list&gt; &lt;/body&gt; </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;body&gt; two = 2 one = 1 three = 3 &lt;/body&gt; </code></pre>
14,507,310
What's the difference between "var" and "out" parameters?
<p>What's the difference between parameters declared with <code>var</code> and those declared with <code>out</code>? How does the compiler treat them differently (e.g., by generating different code, or by changing which diagnostics it issues)? Or do the different modifiers merely allow the programmer to document intended use of the parameters? What effect do the <em>types</em> of the parameters have on the matter?</p>
14,507,363
4
11
null
2013-01-24 17:34:59.15 UTC
12
2022-08-11 09:51:13.793 UTC
null
null
null
null
33,732
null
1
59
delphi|parameters|pass-by-reference
22,637
<p>A <code>var</code> parameter will be passed by reference, and that's it.</p> <p>An <code>out</code> parameter is also passed by reference, but it's assumed that the input value is irrelevant. For managed types, (strings, Interfaces, etc,) the compiler will enforce this, by clearing the variable before the routine begins, equivalent to writing <code>param := nil</code>. For unmanaged types, the compiler implements <code>out</code> identically to <code>var</code>.</p> <p>Note that the clearing of a managed parameter is performed at the call-site and so the code generated for the function does not vary with <code>out</code> or <code>var</code> parameters.</p>
17,830,333
Start Raspberry Pi without login
<p>I would like to ask you if there is any way to start raspberry pi (using Raspbian) without login and password and to move directly to the GUI. Like Windows for example. </p>
17,830,633
1
2
null
2013-07-24 09:39:32.573 UTC
9
2019-05-21 19:41:30.603 UTC
2019-05-21 19:36:46.703 UTC
null
147,407
null
576,998
null
1
23
raspberry-pi|raspbian
54,084
<h1>Raspbian Wheezy:</h1> <p>Following was taken from <a href="http://elinux.org" rel="nofollow noreferrer">eLinux.org</a> <a href="http://elinux.org/RPi_Debian_Auto_Login" rel="nofollow noreferrer">RPi Debian Auto Login</a> page:</p> <p><strong>Auto Login:</strong></p> <p>In Terminal:</p> <pre><code>sudo nano /etc/inittab </code></pre> <p>Scroll down to:</p> <pre><code>1:2345:respawn:/sbin/getty 115200 tty1 </code></pre> <p>and change to</p> <pre><code>#1:2345:respawn:/sbin/getty 115200 tty1 </code></pre> <p>Under that line add:</p> <pre><code>1:2345:respawn:/bin/login -f pi tty1 &lt;/dev/tty1 &gt;/dev/tty1 2&gt;&amp;1 </code></pre> <p>Ctrl+X to exit, Y to save followed by enter twice</p> <p><strong>Auto StartX (Run LXDE)</strong>:</p> <p>In Terminal:</p> <pre><code>sudo nano /etc/rc.local </code></pre> <p>Scroll to the bottom and add the following above exit 0:</p> <pre><code>su -l pi -c startx </code></pre> <h1>Raspbian Jessie:</h1> <p>Use <code>raspi-config</code>. If, for some magic reason this tool is not present on your system, install it:</p> <pre><code>sudo apt-get install raspi-config </code></pre> <p><strong>Hard way:</strong></p> <p><a href="https://raspberrypi.stackexchange.com/a/43419/427">Link</a>. <a href="https://raspberrypi.stackexchange.com/questions/3873/auto-login-with-gui-disabled-in-raspbian">Link</a>.</p> <hr> <h1>UPDATE 2019.05</h1> <p>In recent distro there's a simpler way to fix this:</p> <p>At command prompt, type <code>sudo raspi-config</code>, then:</p> <ul> <li>select option 3 in menu (Boot Options)</li> <li>select option B1 (Desktopp/CLI)</li> <li>select option B2 (Console Autologin)</li> </ul> <p>Hit OK, exit all the way and restart.</p> <p><em>Update 2019.05</em> credit belongs to <em>Hasan A Yousef</em>.</p>
42,921,854
How to check if a particular cell in pandas DataFrame isnull?
<p>I have the following <code>df</code> in pandas.</p> <pre><code>0 A B C 1 2 NaN 8 </code></pre> <p>How can I check if <code>df.iloc[1]['B']</code> is NaN?</p> <p>I tried using <code>df.isnan()</code> and I get a table like this:</p> <pre><code>0 A B C 1 false true false </code></pre> <p>but I am not sure how to index the table and if this is an efficient way of performing the job at all?</p>
42,921,875
3
0
null
2017-03-21 08:32:09.673 UTC
3
2019-01-09 10:49:25.21 UTC
null
null
null
null
1,803,908
null
1
20
python|pandas|dataframe
100,605
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.isnull.html" rel="noreferrer"><code>pd.isnull</code></a>, for select use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><code>loc</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="noreferrer"><code>iloc</code></a>:</p> <pre><code>print (df) 0 A B C 0 1 2 NaN 8 print (df.loc[0, 'B']) nan a = pd.isnull(df.loc[0, 'B']) print (a) True print (df['B'].iloc[0]) nan a = pd.isnull(df['B'].iloc[0]) print (a) True </code></pre>
41,684,463
Flask - Active Directory Authentication
<p>I made a small Flask application and I would like users to be able to authenticate with their Windows NT IDs. I am not a part of the IT team, so I have limited insight into this area and my IT team is not experienced with Python.</p> <p>How easy would it be to configure this? I tried to do some Googling and I saw LDAP modules and Flask-Security. I am hoping for a quick guide or to be pointed into a specific direction.</p> <ul> <li>There is an existing Active Directory and a lot of our internal websites use NT authentication</li> <li>I made a Flask app that I will be porting to our internal network</li> <li>I want users to be able to login to the site with their NT ID</li> <li>I need to know what information I need (an LDAP server and port?) or what I need to do with IT to get this configured properly without breaking any security protocols</li> </ul> <p>Thanks!</p>
42,296,880
2
0
null
2017-01-16 20:26:21.003 UTC
12
2019-04-18 16:26:20.28 UTC
null
null
null
null
3,966,601
null
1
38
flask
37,820
<p>It is quite easy to work with Flask as it is a lightweight and plugin-based Python web framework.</p> <blockquote> <p>Things you will need for LDAP Configuration</p> </blockquote> <ul> <li>LDAP Host</li> <li>LDAP Domain</li> <li>LDAP Profile Key</li> </ul> <blockquote> <p>You need to install Flask-LDAP plugin</p> </blockquote> <pre><code>pip install Flask-LDAP </code></pre> <p>and here is a basic example to get you started:</p> <pre><code>from flask import Flask from flask.ext.ldap import LDAP, login_required app = Flask(__name__) app.debug = True app.config['LDAP_HOST'] = 'ldap.example.com' app.config['LDAP_DOMAIN'] = 'example.com' app.config['LDAP_SEARCH_BASE'] = 'OU=Domain Users,DC=example,DC=com' ldap = LDAP(app) app.secret_key = "welfhwdlhwdlfhwelfhwlehfwlehfelwehflwefwlehflwefhlwefhlewjfhwelfjhweflhweflhwel" app.add_url_rule('/login', 'login', ldap.login, methods=['GET', 'POST']) @app.route('/') @ldap.login_required def index(): pass # @app.route('/login', methods=['GET', 'POST']) # def login(): # pass if __name__ == '__main__': app.run(debug=True, host="0.0.0.0") </code></pre> <p>More details can be found <a href="http://flask-ldap.readthedocs.io/en/latest/installation.html" rel="noreferrer">here</a></p>
50,186,904
PathLib recursively remove directory?
<p>Is there any way to remove a directory and it’s contents in the PathLib module? With <code>path.unlink()</code> it only removes a file, with <code>path.rmdir()</code> the directory has to be empty. Is there no way to do it in one function call? </p>
50,187,147
7
0
null
2018-05-05 07:29:39.557 UTC
7
2022-09-14 18:59:47.837 UTC
null
null
null
null
4,556,675
null
1
113
python|directory|pathlib
57,410
<p>As you already know, the only two <code>Path</code> methods for removing files/directories are <code>.unlink()</code> and <code>.rmdir()</code> and neither does what you want.</p> <p>Pathlib is a module that provides object oriented paths across different OS's, it isn't meant to have lots of diverse methods.</p> <blockquote> <p>The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.</p> </blockquote> <p>The &quot;uncommon&quot; file system alterations, such as recursively removing a directory, is stored in different modules. If you want to recursively remove a directory, you should use the <code>shutil</code> module. (It works with <code>Path</code> instances too!)</p> <pre class="lang-py prettyprint-override"><code>import shutil import pathlib import os # for checking results print(os.listdir()) # [&quot;a_directory&quot;, &quot;foo.py&quot;, ...] path = pathlib.Path(&quot;a_directory&quot;) shutil.rmtree(path) print(os.listdir()) # [&quot;foo.py&quot;, ...] </code></pre>
40,336,502
Want to know the diff among pd.factorize, pd.get_dummies, sklearn.preprocessing.LableEncoder and OneHotEncoder
<p>All four functions seem really similar to me. In some situations some of them might give the same result, some not. Any help will be thankfully appreciated!</p> <p>Now I know and I assume that internally, <code>factorize</code> and <code>LabelEncoder</code> work the same way and having no big differences in terms of results. I am not sure whether they will take up similar time with large magnitudes of data.</p> <p><code>get_dummies</code> and <code>OneHotEncoder</code> will yield the same result but <code>OneHotEncoder</code> can only handle numbers but <code>get_dummies</code> will take all kinds of input. <code>get_dummies</code> will generate new column names automatically for each column input, but <code>OneHotEncoder</code> will not (it rather will assign new column names 1,2,3....). So <code>get_dummies</code> is better in all respectives.</p> <p>Please correct me if I am wrong! Thank you!</p>
40,338,956
1
0
null
2016-10-31 04:15:11.273 UTC
12
2018-11-28 18:22:48.68 UTC
2017-07-02 14:06:16.903 UTC
null
7,117,003
null
7,086,135
null
1
24
python|pandas|encoding|machine-learning|scikit-learn
8,677
<p>These four encoders can be split in two categories:</p> <ul> <li>Encode <strong>labels into categorical variables</strong>: Pandas <code>factorize</code> and scikit-learn <code>LabelEncoder</code>. The result will have 1 dimension.</li> <li>Encode <strong>categorical variable into dummy/indicator (binary) variables</strong>: Pandas <code>get_dummies</code> and scikit-learn <code>OneHotEncoder</code>. The result will have n dimensions, one by distinct value of the encoded categorical variable.</li> </ul> <p>The main difference between pandas and scikit-learn encoders is that scikit-learn encoders are made to be used in <strong>scikit-learn pipelines</strong> with <code>fit</code> and <code>transform</code> methods.</p> <h2>Encode labels into categorical variables</h2> <p>Pandas <code>factorize</code> and scikit-learn <code>LabelEncoder</code> belong to the first category. They can be used to create categorical variables for example to transform characters into numbers.</p> <pre><code>from sklearn import preprocessing # Test data df = DataFrame(['A', 'B', 'B', 'C'], columns=['Col']) df['Fact'] = pd.factorize(df['Col'])[0] le = preprocessing.LabelEncoder() df['Lab'] = le.fit_transform(df['Col']) print(df) # Col Fact Lab # 0 A 0 0 # 1 B 1 1 # 2 B 1 1 # 3 C 2 2 </code></pre> <h2>Encode categorical variable into dummy/indicator (binary) variables</h2> <p>Pandas <code>get_dummies</code> and scikit-learn <code>OneHotEncoder</code> belong to the second category. They can be used to create binary variables. <code>OneHotEncoder</code> can only be used with categorical integers while <code>get_dummies</code> can be used with other type of variables.</p> <pre><code>df = DataFrame(['A', 'B', 'B', 'C'], columns=['Col']) df = pd.get_dummies(df) print(df) # Col_A Col_B Col_C # 0 1.0 0.0 0.0 # 1 0.0 1.0 0.0 # 2 0.0 1.0 0.0 # 3 0.0 0.0 1.0 from sklearn.preprocessing import OneHotEncoder, LabelEncoder df = DataFrame(['A', 'B', 'B', 'C'], columns=['Col']) # We need to transform first character into integer in order to use the OneHotEncoder le = preprocessing.LabelEncoder() df['Col'] = le.fit_transform(df['Col']) enc = OneHotEncoder() df = DataFrame(enc.fit_transform(df).toarray()) print(df) # 0 1 2 # 0 1.0 0.0 0.0 # 1 0.0 1.0 0.0 # 2 0.0 1.0 0.0 # 3 0.0 0.0 1.0 </code></pre> <p><em>I've also written a more detailed <a href="https://www.back2code.me/2017/09/numeric-and-binary-encoders-in-python" rel="noreferrer">post</a> based on this answer.</em></p>
50,668,487
using the new keyword in flutter
<p>Recently started following the flutter <a href="https://classroom.udacity.com/courses/ud905" rel="noreferrer">udacity course</a> and while experimenting with creating basic apps I came across something that was unclear to me. When adding widgets, I have noted that doing both <code>new Widget()</code> and <code>Widget()</code> <em>[where Widget is any widget being added to the tree]</em> give the same result. Is there a specific time when you should use <code>new Widget()</code> and a time when you should omit the <code>new</code> keyword?</p> <p>For example:</p> <pre><code>return MaterialApp( debugShowCheckedModeBanner: false, home: new Scaffold( appBar: new AppBar( title: Text('My app name') ), ) </code></pre> <p><code>Text('My app name')</code> works, but <code>new Text('My app name')</code> also works. Any chance I could get some pointers and guidelines on best practices with this?</p>
50,668,527
1
0
null
2018-06-03 16:22:31.857 UTC
5
2019-05-08 12:41:21.873 UTC
2019-04-03 08:06:20.77 UTC
null
7,090,955
null
7,090,955
null
1
46
dart|flutter
12,861
<p><code>new</code> was made optional beginning with Dart 2.0, this is why some examples or tutorial still use <code>new</code> and newer or updated ones don't. </p> <p>You can just always omit it.</p> <p><code>const</code> can be omitted when the context requires <code>const</code></p>
29,923,531
How to set Java heap size (Xms/Xmx) inside Docker container?
<p>As of raising this question, Docker looks to be new enough to not have answers to this question on the net. The only place I found is <a href="http://blog.takipi.com/ignore-the-hype-5-docker-misconceptions-java-developers-should-consider/">this article</a> in which the author is saying it is hard, and that's it.</p>
29,926,938
6
0
null
2015-04-28 15:25:52.997 UTC
11
2020-12-16 16:59:44.623 UTC
2015-04-28 15:31:48.677 UTC
null
1,402,390
null
1,402,390
null
1
51
java|docker|heap-memory
107,268
<p>I agree that it depends on what container you're using. If you are using the official <a href="https://registry.hub.docker.com/_/tomcat/" rel="noreferrer">Tomcat image</a>, it looks like it's simple enough, you will need to pass the <code>JAVA_OPTS</code> environment variable with your heap settings:</p> <pre><code>docker run --rm -e JAVA_OPTS='-Xmx1g' tomcat </code></pre> <p>See <a href="https://github.com/docker-library/tomcat/issues/8" rel="noreferrer">How to set JVM parameters?</a></p>
28,100,220
Jekyll display collection by category
<p>I'm having trouble figuring out how to sort the content of a collection by category. I've found a very similar question on how to sort posts by category but it doesn't seem to work with collections <a href="https://stackoverflow.com/questions/20872861/jekyll-display-posts-by-category">Jekyll display posts by category</a>.</p> <p>Let's say I have a collection called 'cars' with two categories: 'old' and 'new'. How can I display only cars with the category 'old'?</p>
28,105,741
1
0
null
2015-01-22 23:00:34.313 UTC
12
2015-01-23 08:24:47.847 UTC
null
null
null
null
2,556,370
null
1
14
jekyll
5,478
<p>You can sort, group or filter collection like any other object like page or posts.</p> <p><strong>_my_collection/mustang.md</strong></p> <pre><code>--- category: 'old' abbrev: tang --- mustang content </code></pre> <p><strong>_my_collection/corvette.md</strong></p> <pre><code>--- category: 'new' abbrev: vet --- corvette content </code></pre> <h3>Filtering</h3> <pre><code>{% assign newcars = site.my_collection | where: "category", "new" %} </code></pre> <h3>Sorting</h3> <pre><code>{% assign allcarssorted = site.my_collection | sort: "category" %} </code></pre> <h3>Grouping</h3> <pre><code>{% assign groups = site.my_collection | group_by: "category" | sort: "name" %} </code></pre> <p>This groups your cars and then sort groups by name that is the category.</p> <pre><code>{% for group in groups %} {{ group.name }} {% for item in group.items %} {{item.abbrev}} {%endfor%} {%endfor%} </code></pre>
3,000,131
Android NDK r4 san-angeles problem
<p>I'm starting to learn the android NDK and I've instantly come up against a problem.</p> <p>I'e built the tool chain (which took a LOT longer than I was expecting!!) and I've compiled the C++ code with no problems and now I'm trying to build the java code.</p> <p>Instantly I come up against a problem. There is a file "main.xml"</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World, DemoActivity" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>and I get the following errors:</p> <pre><code>Description Resource Path Location Type error: Error: String types not allowed (at 'layout_height' with value 'match_parent'). main.xml /DemoActivity/res/layout line 2 Android AAPT Problem error: Error: String types not allowed (at 'layout_height' with value 'match_parent'). main.xml /DemoActivity/res/layout line 2 Android AAPT Problem error: Error: String types not allowed (at 'layout_width' with value 'match_parent'). main.xml /DemoActivity/res/layout line 2 Android AAPT Problem error: Error: String types not allowed (at 'layout_width' with value 'match_parent'). main.xml /DemoActivity/res/layout line 7 Android AAPT Problem error: Error: String types not allowed (at 'layout_width' with value 'match_parent'). main.xml /DemoActivity/res/layout line 7 Android AAPT Problem </code></pre> <p>So I can see the problem lies in the fact that these "match_parent" strings are in there. Anyone know how to fix this?</p>
3,000,156
1
1
null
2010-06-08 18:25:11.057 UTC
3
2012-09-20 07:19:29.183 UTC
2012-09-20 07:19:29.183 UTC
null
192,373
null
131,140
null
1
43
java|android|xml
25,972
<p>Check what <a href="http://developer.android.com/guide/appendix/api-levels.html" rel="noreferrer">API Level</a> you are using.</p> <p><code>FILL_PARENT</code> was renamed to <code>MATCH_PARENT</code> in API Level 8 (Android 2.2).</p>
2,736,087
eval-after-load vs. mode hook
<p>Is there a difference between setting things for a mode using <code>eval-after-load</code> and using the mode hook?</p> <p>I've seen some code where <code>define-key</code> is used inside a major mode hook, and some other code where <code>define-key</code> is used in <code>eval-after-load</code> form.</p> <hr> <p>Update:</p> <p>For better understanding, here is an example of using eval-after-load and mode hooks with org-mode. The code can run <strong>before</strong> <code>(load "org")</code> or <code>(require 'org)</code> or <code>(package-initialize)</code>.</p> <pre><code>;; The following two lines of code set some org-mode options. ;; Usually, these can be outside (eval-after-load ...) and work. ;; In cases that doesn't work, try using setq-default or set-variable ;; and putting them in (eval-after-load ...), if the ;; doc for the variables don't say what to do. ;; Or use Customize interface. (setq org-hide-leading-stars t) (setq org-return-follows-link t) ;; "org" because C-h f org-mode RET says that org-mode is defined in org.el (eval-after-load "org" '(progn ;; Establishing your own keybindings for org-mode. ;; Variable org-mode-map is available only after org.el or org.elc is loaded. (define-key org-mode-map (kbd "&lt;C-M-return&gt;") 'org-insert-heading-respect-content) (define-key org-mode-map (kbd "&lt;M-right&gt;") nil) ; erasing a keybinding. (define-key org-mode-map (kbd "&lt;M-left&gt;") nil) ; erasing a keybinding. (defun my-org-mode-hook () ;; The following two lines of code is run from the mode hook. ;; These are for buffer-specific things. ;; In this setup, you want to enable flyspell-mode ;; and run org-reveal for every org buffer. (flyspell-mode 1) (org-reveal)) (add-hook 'org-mode-hook 'my-org-mode-hook))) </code></pre>
2,736,153
1
1
null
2010-04-29 09:20:27.05 UTC
32
2012-02-05 14:39:36.157 UTC
2012-02-05 14:39:36.157 UTC
null
37,664
null
37,664
null
1
80
emacs|elisp
17,659
<p>Code wrapped in <code>eval-after-load</code> will be executed only once, so it is typically used to perform one-time setup such as setting default global values and behaviour. An example might be setting up a default keymap for a particular mode. In <code>eval-after-load</code> code, there's no notion of the "current buffer".</p> <p>Mode hooks execute once for every buffer in which the mode is enabled, so they're used for per-buffer configuration. Mode hooks are therefore run later than <code>eval-after-load</code> code; this lets them take actions based upon such information as whether other modes are enabled in the current buffer.</p>
34,265,416
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in ubuntu 14.04
<p>I have installed LAMP on my Ubuntu machine.</p> <p>Where Apache2 and PHP5 have been installed properly as when I run <code>apache2 -v</code> and <code>php5 -v</code> I am getting their installed versions.</p> <p>But I am not sure how do I check If <code>My-SQL</code> is properly installed or not.</p> <p>Because when I run <code>mysql -u root -p</code> command, I am getting the below error.</p> <blockquote> <p>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)</p> </blockquote> <p>Please help!</p>
34,265,783
7
0
null
2015-12-14 11:04:55.687 UTC
7
2019-03-28 06:23:16.123 UTC
null
null
null
null
2,615,428
null
1
9
mysql|sockets|ubuntu-14.04|lamp
110,175
<p>you could try starting your mysql first</p> <pre><code>&gt; ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock &gt; &gt; service mysql start or service mysql start </code></pre>
38,636,254
How to convert Json to Java object using Gson
<p>Suppose I have json string </p> <pre><code>{"userId":"1","userName":"Yasir"} </code></pre> <p>now I have a class User</p> <pre><code>class User{ int userId; String userName; //setters and getters } </code></pre> <p>Now How can I convert above json string to user class object</p>
38,636,376
4
2
null
2016-07-28 12:22:35.63 UTC
3
2022-06-13 20:55:10.6 UTC
null
null
null
user6160039
null
null
1
25
java|json|gson
74,746
<p>Try this:</p> <pre><code>Gson gson = new Gson(); String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}"; User user= gson.fromJson(jsonInString, User.class); </code></pre>
31,582,378
ios 8 Swift - TableView with embedded CollectionView
<p>I am relatively new to iOS programming and have tried a few things but to no avail.</p> <p>I would like to put a <code>CollectionView</code> inside a <code>TableViewCell</code>. I can code each individually, but dont understand how to set and reference each <code>CollectionView</code> within a <code>TableViewCell</code>.</p> <p>I have found this tutorial, <a href="http://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell/" rel="noreferrer">http://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell/</a> which shows how it can be done in Objective-C but I have always struggled with Obj-C.</p> <p>Does anyone know of a Swift Tutorial or can assist? I am in the process of creating a simple project/code which I will post shortly to try and assist.</p> <p>EDIT 1</p> <p>I have just found the swift version of the above link. I am working through this now, but seems over complicated, modifying the AppDelegate.</p> <p><a href="https://github.com/DahanHu/DHCollectionTableView" rel="noreferrer">https://github.com/DahanHu/DHCollectionTableView</a></p> <p>Many thanks Rob</p>
31,584,653
3
0
null
2015-07-23 08:45:45.427 UTC
20
2019-04-19 01:58:22.34 UTC
2015-07-23 10:25:46.977 UTC
null
5,146,932
null
5,146,932
null
1
17
ios|swift|uitableview|uicollectionview
53,931
<p>Create a usual UITableView and in your UITableViewCell create the UICollectionView. Your collectionView delegate and datasource should conform to that UITableViewCell.</p> <p>Just go through this</p> <p>In your ViewController</p> <pre><code>// Global Variable var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: self.view.bounds) tableView.delegate = self tableView.dataSource = self self.view.addSubview(tableView) tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "TableViewCell") tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "NormalCell") } func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { if indexPath.row == 3 { var cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("TableViewCell", forIndexPath: indexPath) as! TableViewCell cell.backgroundColor = UIColor.groupTableViewBackgroundColor() return cell } else { var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("NormalCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = "cell: \(indexPath.row)" return cell } } </code></pre> <p>As you can see I've created two different cells, a custom TableViewCell which is returned only when the row index is 3 and a basic UITableViewCell in other indices.</p> <p>The custom "TableViewCell" will have our UICollectionView. So Create a UITableViewCell subclass and write down the below code.</p> <pre><code>import UIKit class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate { var collectionView: UICollectionView! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell") collectionView.backgroundColor = UIColor.clearColor() self.addSubview(collectionView) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -&gt; Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell { let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! UICollectionViewCell if indexPath.row%2 == 0 { cell.backgroundColor = UIColor.redColor() } else { cell.backgroundColor = UIColor.yellowColor() } return cell } } </code></pre> <p>Hope it helps.</p>
25,363,977
What is the advantage of strand in boost asio?
<p>Studying boost asio and find out a class called "strand", as far as I understand. If there are only one io_service associated to a specific strand and post the handle by the strand.</p> <p>example(from <a href="http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting-started-with-boostasio/?pg=5">here</a>)</p> <pre><code>boost::shared_ptr&lt; boost::asio::io_service &gt; io_service( new boost::asio::io_service ); boost::shared_ptr&lt; boost::asio::io_service::work &gt; work( new boost::asio::io_service::work( *io_service ) ); boost::asio::io_service::strand strand( *io_service ); boost::thread_group worker_threads; for( int x = 0; x &lt; 2; ++x ) { worker_threads.create_thread( boost::bind( &amp;WorkerThread, io_service ) ); } boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) ); strand.post( boost::bind( &amp;PrintNum, 1 ) ); strand.post( boost::bind( &amp;PrintNum, 2 ) ); strand.post( boost::bind( &amp;PrintNum, 3 ) ); strand.post( boost::bind( &amp;PrintNum, 4 ) ); strand.post( boost::bind( &amp;PrintNum, 5 ) ); </code></pre> <p>Then the strand will serialized handler execution for us.But what is the benefits of doing this?Why don't we just create a single thread(ex : make x = 1 in the for loop) if we want the tasks become serialized?</p>
25,364,185
2
0
null
2014-08-18 13:02:42.563 UTC
11
2021-11-26 21:49:35.72 UTC
2019-01-31 12:00:38.833 UTC
null
10,576,494
null
1,281,264
null
1
27
c++|boost|boost-asio
19,044
<p>Think of a system where a single <code>io_service</code> manages sockets for hundreds of network connections. To be able to parallelize workload, the system maintains a pool of worker threads that call <code>io_service::run</code>.</p> <p>Now most of the operations in such a system can just run in parallel. But some will have to be serialized. For example, you probably would not want multiple write operations on the same socket to happen concurrently. You would then use one strand per socket to synchronize writes: Writes on distinct sockets can still happen at the same time, while writes to same sockets will be serialized. The worker threads do not have to care about synchronization or different sockets, they just grab whatever <code>io_service::run</code> hands them.</p> <p>One might ask: Why can't we just use mutex instead for synchronization? The advantage of strand is that a worker thread will not get scheduled in the first place if the strand is already being worked on. With a mutex, the worker thread would get the callback and then would block on the lock attempt, preventing the thread from doing any useful work until the mutex becomes available.</p>
43,406,887
Spark Dataframe :How to add a index Column : Aka Distributed Data Index
<p>I read data from a csv file ,but don't have index.</p> <p>I want to add a column from 1 to row's number.</p> <p>What should I do,Thanks (scala)</p>
43,408,058
7
0
null
2017-04-14 07:09:50.98 UTC
16
2020-11-16 08:06:12.237 UTC
2019-05-13 14:54:09.67 UTC
null
647,053
null
7,859,743
null
1
42
scala|apache-spark|dataframe|apache-spark-sql
119,854
<p>With Scala you can use:</p> <pre><code>import org.apache.spark.sql.functions._ df.withColumn("id",monotonicallyIncreasingId) </code></pre> <p>You can refer to this <a href="https://hadoopist.wordpress.com/2016/05/24/generate-unique-ids-for-each-rows-in-a-spark-dataframe/" rel="noreferrer">exemple</a> and scala <a href="https://spark.apache.org/docs/1.6.2/api/java/org/apache/spark/sql/functions.html#monotonically_increasing_id()" rel="noreferrer">docs</a>.</p> <p>With Pyspark you can use: </p> <pre><code>from pyspark.sql.functions import monotonically_increasing_id df_index = df.select("*").withColumn("id", monotonically_increasing_id()) </code></pre>
2,991,490
Bad text rendering using DrawString on top of transparent pixels
<p>When rendering text into a bitmap, I find that text looks very bad when rendered on top of an area with non-opaque alpha. The problem is progressively worse as the underlying pixels become more transparent. If I had to guess I'd say that when underlying pixels are transparent, the text renderer draws any anti-aliased 'gray' pixels as solid black.</p> <p>Here are some screenshots:</p> <p><strong>Text drawn on top of transparent pixels:</strong></p> <p><img src="https://i.stack.imgur.com/AS1zC.png" alt="alt text"></p> <p><strong>Text drawn on top of semi-transparent pixels:</strong></p> <p><img src="https://i.stack.imgur.com/fv0HK.png" alt="alt text"></p> <p><strong>Text drawn on opaque pixels:</strong></p> <p><img src="https://i.stack.imgur.com/tDvXj.png" alt="alt text"></p> <p>Here is the code used to render the text:</p> <pre><code>g.SmoothingMode = SmoothingMode.HighQuality; g.DrawString("Press the spacebar", Font, Brushes.Black, textLeft, textTop); </code></pre>
7,078,925
4
4
null
2010-06-07 16:56:10.537 UTC
8
2019-05-14 09:37:39.317 UTC
2019-05-14 09:37:39.317 UTC
null
8,967,612
null
25,457
null
1
33
c#|winforms|gdi+|system.drawing|drawstring
25,277
<p>The option I used to workaround this problem was:</p> <pre><code>Graphics graphics = new Graphics(); graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; </code></pre> <p>There are some others useful options in TextRenderingHint</p> <p>Hope it helps</p>
37,985,581
How to dynamically remove fields from serializer output
<p>I'm developing an API with Django Rest framework, and I would like to dynamically remove the fields from a serializer. The problem is that I need to remove them depending on the value of another field. How could I do that? I have a serializer like:</p> <pre><code>class DynamicSerliazer(serializers.ModelSerializer): type = serializers.SerializerMethodField() url = serializers.SerializerMethodField() title = serializers.SerializerMethodField() elements = serializers.SerializerMethodField() def __init__(self, *args, **kwargs): super(DynamicSerliazer, self).__init__(*args, **kwargs) if self.fields and is_mobile_platform(self.context.get('request', None)) and "url" in self.fields: self.fields.pop("url") </code></pre> <p>As you can see, I'm already removing the field "url" depending whether the request has been done from a mobile platform. But, I would like to remove the "elements" field depending on the "type" value. How should I do that?</p> <p>Thanks in advance</p>
37,997,364
4
0
null
2016-06-23 08:03:58.443 UTC
5
2022-05-04 21:57:07.36 UTC
2016-06-24 14:39:49.343 UTC
null
4,921,103
null
4,989,926
null
1
30
django-rest-framework|django-serializer
20,703
<p>You <strong>can <a href="http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior" rel="noreferrer">customize the serialization behavior</a> by overriding the <code>to_representation()</code> method</strong> in your serializer.</p> <pre><code>class DynamicSerliazer(serializers.ModelSerializer): def to_representation(self, obj): # get the original representation ret = super(DynamicSerializer, self).to_representation(obj) # remove 'url' field if mobile request if is_mobile_platform(self.context.get('request', None)): ret.pop('url') # here write the logic to check whether `elements` field is to be removed # pop 'elements' from 'ret' if condition is True # return the modified representation return ret </code></pre>
36,494,529
Convert a simple string to JSON String in swift
<p>I know there is a question with same title <a href="https://stackoverflow.com/questions/30825755/convert-string-to-json-string-in-swift">here</a>. But in that question, he is trying to convert a dictionary into JSON. But I have a simple sting like this: "garden"</p> <p>And I have to send it as JSON. I have tried SwiftyJSON but still I am unable to convert this into JSON. </p> <p>Here is my code: </p> <pre><code>func jsonStringFromString(str:NSString)-&gt;NSString{ let strData = str.dataUsingEncoding(NSUTF8StringEncoding) let json = JSON(data: strData!) let jsonString = json.string return jsonString! } </code></pre> <p>My code crashes at the last line:</p> <pre><code>fatal error: unexpectedly found nil while unwrapping an Optional value </code></pre> <p>Am I doing something wrong? </p>
36,494,656
2
0
null
2016-04-08 08:04:03.63 UTC
4
2018-03-01 06:40:25.987 UTC
2017-05-23 12:34:17.677 UTC
null
-1
null
3,081,929
null
1
10
json|swift|swifty-json
40,446
<p><a href="http://www.json.org/" rel="noreferrer">JSON has to be an array or a dictionary</a>, it can't be only a String.</p> <p>I suggest you create an array with your String in it:</p> <pre><code>let array = ["garden"] </code></pre> <p>Then you create a JSON object from this array:</p> <pre><code>if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { // here `json` is your JSON data } </code></pre> <p>If you need this JSON as a String instead of data you can use this:</p> <pre><code>if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { // here `json` is your JSON data, an array containing the String // if you need a JSON string instead of data, then do this: if let content = String(data: json, encoding: NSUTF8StringEncoding) { // here `content` is the JSON data decoded as a String print(content) } } </code></pre> <p>Prints:</p> <blockquote> <p>["garden"]</p> </blockquote> <p>If you prefer having a dictionary rather than an array, follow the same idea: create the dictionary then convert it.</p> <pre><code>let dict = ["location": "garden"] if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) { if let content = String(data: json, encoding: NSUTF8StringEncoding) { // here `content` is the JSON dictionary containing the String print(content) } } </code></pre> <p>Prints:</p> <blockquote> <p>{"location":"garden"}</p> </blockquote>
779,414
Java generics Pair<String, String> stored in HashMap not retrieving key->value properly
<p>Here's Pair.java</p> <pre><code>import java.lang.*; import java.util.*; public class Pair&lt;TYPEA, TYPEB&gt; implements Comparable&lt; Pair&lt;TYPEA, TYPEB&gt; &gt; { protected final TYPEA Key_; protected final TYPEB Value_; public Pair(TYPEA key, TYPEB value) { Key_ = key; Value_ = value; } public TYPEA getKey() { return Key_; } public TYPEB getValue() { return Value_; } public String toString() { System.out.println("in toString()"); StringBuffer buff = new StringBuffer(); buff.append("Key: "); buff.append(Key_); buff.append("\tValue: "); buff.append(Value_); return(buff.toString() ); } public int compareTo( Pair&lt;TYPEA, TYPEB&gt; p1 ) { System.out.println("in compareTo()"); if ( null != p1 ) { if ( p1.equals(this) ) { return 0; } else if ( p1.hashCode() &gt; this.hashCode() ) { return 1; } else if ( p1.hashCode() &lt; this.hashCode() ) { return -1; } } return(-1); } public boolean equals( Pair&lt;TYPEA, TYPEB&gt; p1 ) { System.out.println("in equals()"); if ( null != p1 ) { if ( p1.Key_.equals( this.Key_ ) &amp;&amp; p1.Value_.equals( this.Value_ ) ) { return(true); } } return(false); } public int hashCode() { int hashCode = Key_.hashCode() + (31 * Value_.hashCode()); System.out.println("in hashCode() [" + Integer.toString(hashCode) + "]"); return(hashCode); } } </code></pre> <p>Here's the testcase: </p> <pre><code>import java.lang.*; import java.util.*; import junit.framework.*; public class PairTest extends TestCase { public void testPair() { String key = new String("key"); String value = new String("asdf"); Pair&lt;String, String&gt; pair = new Pair&lt;String, String&gt;( key, value ); assertTrue( pair.getKey().equals( key ) ); assertTrue( pair.getValue().equals( value ) ); assertTrue( pair.equals( new Pair&lt;String, String&gt;(key, value)) ); } public void testPairCollection() { HashMap&lt; Pair&lt;String, String&gt;, String&gt; hm1 = new HashMap&lt;Pair&lt;String,String&gt;, String&gt;(); Pair&lt;String, String&gt; p1 = new Pair&lt;String, String&gt;("Test1", "Value1"); hm1.put(p1, "ONE"); Pair&lt;String, String&gt; p2 = new Pair&lt;String, String&gt;("Test1", "Value2"); hm1.put(p2, "TWO"); Pair&lt;String, String&gt; p3 = new Pair&lt;String, String&gt;("Test2", "Value1"); hm1.put(p3, "THREE"); Pair&lt;String, String&gt; p4 = new Pair&lt;String, String&gt;("Test2", "Value2"); hm1.put(p4, "FOUR"); Pair&lt;String, String&gt; p5 = new Pair&lt;String, String&gt;("Test3", "Value1"); hm1.put(p5, "FIVE"); Pair&lt;String, String&gt; p6 = new Pair&lt;String, String&gt;("Test3", "Value2"); hm1.put(p6, "SIX"); Pair&lt;String, String&gt; p7 = new Pair&lt;String, String&gt;("Test3", "Value3"); hm1.put(p7, "SEVEN"); assertTrue( hm1.size() == 7 ); Pair&lt;String, String&gt; pSrch = new Pair&lt;String, String&gt;("Test3", "Value3"); assertTrue( p7.equals(pSrch) ); assertTrue( pSrch.equals(p7) ); assertTrue( p7.hashCode() == pSrch.hashCode() ); assertTrue( 0 == p7.compareTo( pSrch ) ); assertTrue( 0 == pSrch.compareTo(p7) ); System.out.println("starting containsKey search"); assertTrue( hm1.containsKey( p7 ) ); System.out.println("starting containsKey search2"); assertTrue( hm1.containsKey( pSrch ) ); System.out.println("finishing containsKey search"); String result = hm1.get( pSrch ); assertTrue( null != result ); assertTrue( 0 == result.compareTo("SEVEN")); } } </code></pre> <p>Here's my problem, the last hm1.containsKey call should (I naively expect) return the value stored where Pair&lt;"Three", "Three"> is true - I should get a String with a value of "SEVEN". Here is the output: </p> <pre><code>Running in equals() in hashCode() [1976956095] in hashCode() [1976956126] in hashCode() [1976956096] in hashCode() [1976956127] in hashCode() [1976956097] in hashCode() [1976956128] in hashCode() [1976956159] in equals() in equals() in hashCode() [1976956159] in hashCode() [1976956159] in compareTo() in equals() in compareTo() in equals() starting containsKey search in hashCode() [1976956159] starting containsKey search2 in hashCode() [1976956159] &lt;--- Bug here? Never reaches String result = hm1.get( pSrch ); </code></pre> <p>So is both p7.hashCode() and pSrch.hashCode() are equal and p7.equals(pSrch) and pSrch.equals(p7), and hm1.containsValue(p7) == true, I would expect hm1.containsValue(pSrch) would also return true, but it does not. What am I missing? </p>
779,466
2
0
null
2009-04-22 21:54:46.047 UTC
null
2009-04-22 22:15:59.677 UTC
2009-04-22 21:56:59.537 UTC
null
68,507
null
51,789
null
1
3
java|string|generics|hashmap
45,838
<p>You need to <em>override</em> the <code>equals</code> method from the <code>java.lang.Object</code> class.</p> <p>Instead, you've <em>overloaded</em> the method with an additional version that takes a <code>Pair</code>. Totally different method that never gets called. Replace your <code>equals</code> with something like this:</p> <pre><code>@Override public boolean equals(Object o) { System.out.println("in equals()"); if (o instanceof Pair) { Pair&lt;?, ?&gt; p1 = (Pair&lt;?, ?&gt;) o; if ( p1.Key_.equals( this.Key_ ) &amp;&amp; p1.Value_.equals( this.Value_ ) ) { return(true); } } return(false); } </code></pre> <p>To avoid this kind of mistake, use the <code>@Override</code> annotation on methods you intend to act as overrides. You'll get a compile time error when they don't.</p>
680,788
How to get the default printer name with network path
<p>I want to get the default printer name with the network path. Because i am using the network printer as a default printer. So i need this in VB.NET or C#.Net. Kind help needed. Thanks in advance</p> <p>Sivakumar.P</p>
681,276
2
0
null
2009-03-25 09:11:04.183 UTC
4
2011-10-10 23:21:14.753 UTC
null
null
null
sivakumar
82,380
null
1
10
c#|vb.net
38,071
<p>Try enumerating <code>System.Drawing.Printing.PrinterSettings.InstalledPrinters</code>.</p> <pre><code>using System.Drawing.Printing; string GetDefaultPrinter() { PrinterSettings settings = new PrinterSettings(); foreach (string printer in PrinterSettings.InstalledPrinters) { settings.PrinterName = printer; if (settings.IsDefaultPrinter) return printer; } return string.Empty; } </code></pre>
995,766
Comparison of collection datatypes in C#
<p>Does anyone know of a good overview of the different C# collection types? I am looking for something showing which basic operations such as <code>Add</code>, <code>Remove</code>, <code>RemoveLast</code> etc. are supported, and giving the relative performance. </p> <p>It would be particularly interesting for the various generic classes - and even better if it showed eg. if there is a difference in performance between a <code>List&lt;T&gt;</code> where <code>T</code> is a class and one where <code>T</code> is a struct.</p> <p>A start would be a nice cheat-sheet for the abstract data structures, comparing Linked Lists, Hash Tables etc. etc. Thanks!</p>
2,658,857
2
1
null
2009-06-15 12:10:00.183 UTC
14
2019-03-14 10:32:22.537 UTC
2013-10-19 11:17:16 UTC
null
100,297
null
6,091
null
1
18
c#|data-structures
16,308
<p>The following content was originally taken from MSDN <a href="http://xbox.create.msdn.com/downloads/?id=123&amp;filename=DataStructures_CheatSheet.doc" rel="noreferrer">http://xbox.create.msdn.com/downloads/?id=123&amp;filename=DataStructures_CheatSheet.doc</a> (but the link has since died).</p> <p><a href="https://i.stack.imgur.com/nkdKP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nkdKP.png" alt="Complexity table"></a></p> <p>As in the image above, the content was originally provided as a table (which StackOverflow doesn't support).</p> <p>Given an image isn't easily indexed below is a somewhat crude programmatic conversion of the information to lists:</p> <h1>Array</h1> <ul> <li><strong>add to end:</strong> <code>O(n)</code></li> <li><strong>remove from end:</strong> <code>O(n)</code></li> <li><strong>insert at middle:</strong> <code>O(n)</code></li> <li><strong>remove from middle:</strong> <code>O(n)</code></li> <li><strong>Random Access:</strong> <code>O(1)</code></li> <li><strong>In-order Access:</strong> <code>O(1)</code></li> <li><strong>Search for specific element:</strong> <code>O(n)</code></li> <li><strong>Notes:</strong> Most efficient use of memory; use in cases where data size is fixed.</li> </ul> <h1>List</h1> <ul> <li><strong>add to end:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>O(n)</code></li> <li><strong>remove from middle:</strong> <code>O(n)</code></li> <li><strong>Random Access:</strong> <code>O(1)</code></li> <li><strong>In-order Access:</strong> <code>O(1)</code></li> <li><strong>Search for specific element:</strong> <code>O(n)</code></li> <li><strong>Notes:</strong> Implementation is optimized for speed. In many cases, List will be the best choice.</li> </ul> <h1>Collection</h1> <ul> <li><strong>add to end:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>O(n)</code></li> <li><strong>remove from middle:</strong> <code>O(n)</code></li> <li><strong>Random Access:</strong> <code>O(1)</code></li> <li><strong>In-order Access:</strong> <code>O(1)</code></li> <li><strong>Search for specific element:</strong> <code>O(n)</code></li> <li><strong>Notes:</strong> List is a better choice, unless publicly exposed as API.</li> </ul> <h1>LinkedList</h1> <ul> <li><strong>add to end:</strong> <code>O(1)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>O(1)</code></li> <li><strong>remove from middle:</strong> <code>O(1)</code></li> <li><strong>Random Access:</strong> <code>O(n)</code></li> <li><strong>In-order Access:</strong> <code>O(1)</code></li> <li><strong>Search for specific element:</strong> <code>O(n)</code></li> <li><strong>Notes:</strong> Many operations are fast, but watch out for cache coherency.</li> </ul> <h1>Stack</h1> <ul> <li><strong>add to end:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>N/A</code></li> <li><strong>remove from middle:</strong> <code>N/A</code></li> <li><strong>Random Access:</strong> <code>N/A</code></li> <li><strong>In-order Access:</strong> <code>N/A</code></li> <li><strong>Search for specific element:</strong> <code>N/A</code></li> <li><strong>Notes:</strong> Shouldn't be selected for performance reasons, but algorithmic ones.</li> </ul> <h1>Queue</h1> <ul> <li><strong>add to end:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>N/A</code></li> <li><strong>remove from middle:</strong> <code>N/A</code></li> <li><strong>Random Access:</strong> <code>N/A</code></li> <li><strong>In-order Access:</strong> <code>N/A</code></li> <li><strong>Search for specific element:</strong> <code>N/A</code></li> <li><strong>Notes:</strong> Shouldn't be selected for performance reasons, but algorithmic ones.</li> </ul> <h1>Dictionary</h1> <ul> <li><strong>add to end:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from end:</strong> <code>O(1)</code></li> <li><strong>insert at middle:</strong> <code>best case O(1); worst case O(n)</code></li> <li><strong>remove from middle:</strong> <code>O(1)</code></li> <li><strong>Random Access:</strong> <code>O(1)*</code></li> <li><strong>In-order Access:</strong> <code>O(1)*</code></li> <li><strong>Search for specific element:</strong> <code>O(1)</code></li> <li><strong>Notes:</strong> Although in-order access time is constant time, it is usually slower than other structures due to the over-head of looking up the key.</li> </ul>
2,578,052
Printing contents of another page
<p>In the following link</p> <pre><code>&lt;a href=\"#\" onclick=javascript:print(\"\") style=\"color:blue;\"&gt;Print&lt;/a&gt;" &lt;script&gt; function print() { //How to print the contents of another page } </code></pre>
2,578,075
6
0
null
2010-04-05 11:19:38.62 UTC
5
2020-04-03 21:28:54.65 UTC
2020-04-03 21:28:54.65 UTC
null
4,370,109
null
221,149
null
1
12
javascript|html|printing|dom-events
42,441
<p><a href="http://www.javascriptkit.com/howto/newtech2.shtml" rel="nofollow noreferrer">I think you can print the contents of the current page not external page.</a></p>
2,756,100
Testing performance of queries in mysql
<p>I am trying to setup a script that would test performance of queries on a development mysql server. Here are more details:</p> <ul> <li>I have root access</li> <li>I am the only user accessing the server</li> <li>Mostly interested in InnoDB performance</li> <li>The queries I am optimizing are mostly search queries (<code>SELECT ... LIKE '%xy%'</code>)</li> </ul> <p>What I want to do is to create reliable testing environment for measuring the speed of a single query, free from dependencies on other variables.</p> <p>Till now I have been using <a href="http://dev.mysql.com/doc/refman/5.1/en/select.html" rel="noreferrer">SQL_NO_CACHE</a>, but sometimes the results of such tests also show caching behaviour - taking much longer to execute on the first run and taking less time on subsequent runs.</p> <p>If someone can explain this behaviour in full detail I might stick to using <code>SQL_NO_CACHE</code>; I do believe that it might be due to file system cache and/or caching of indexes used to execute the query, as <a href="http://www.mysqlperformanceblog.com/2007/09/12/query-profiling-with-mysql-bypassing-caches/" rel="noreferrer">this</a> post explains. It is not clear to me when Buffer Pool and Key Buffer get invalidated or how they might interfere with testing.</p> <p>So, short of restarting mysql server, how would you recommend to setup an environment that would be reliable in determining if one query performs better then the other?</p>
2,782,791
6
2
null
2010-05-03 04:23:45.597 UTC
28
2011-09-18 09:52:46.117 UTC
2011-09-18 09:52:46.117 UTC
null
99,256
null
207,036
null
1
31
performance|testing|mysql
50,936
<p>Assuming that you can not optimize the LIKE operation itself, you should try to optimize the base query without them minimizing number of rows that should be checked.</p> <p>Some things that might be useful for that:</p> <p><code>rows</code> column in EXPLAIN SELECT ... result. Then, </p> <pre><code>mysql&gt; set profiling=1; mysql&gt; select sql_no_cache * from mytable; ... mysql&gt; show profile; +--------------------+----------+ | Status | Duration | +--------------------+----------+ | starting | 0.000063 | | Opening tables | 0.000009 | | System lock | 0.000002 | | Table lock | 0.000005 | | init | 0.000012 | | optimizing | 0.000002 | | statistics | 0.000007 | | preparing | 0.000005 | | executing | 0.000001 | | Sending data | 0.001309 | | end | 0.000003 | | query end | 0.000001 | | freeing items | 0.000016 | | logging slow query | 0.000001 | | cleaning up | 0.000001 | +--------------------+----------+ 15 rows in set (0.00 sec) </code></pre> <p>Then,</p> <pre><code>mysql&gt; FLUSH STATUS; mysql&gt; select sql_no_cache * from mytable; ... mysql&gt; SHOW SESSION STATUS LIKE 'Select%'; +------------------------+-------+ | Variable_name | Value | +------------------------+-------+ | Select_full_join | 0 | | Select_full_range_join | 0 | | Select_range | 0 | | Select_range_check | 0 | | Select_scan | 1 | +------------------------+-------+ 5 rows in set (0.00 sec) </code></pre> <p>And another interesting value is <code>last_query_cost</code>, which shows how expensive the optimizer estimated the query (the value is the number of random page reads):</p> <pre><code>mysql&gt; SHOW STATUS LIKE 'last_query_cost'; +-----------------+-------------+ | Variable_name | Value | +-----------------+-------------+ | Last_query_cost | 2635.399000 | +-----------------+-------------+ 1 row in set (0.00 sec) </code></pre> <p>MySQL documentation is your friend.</p>
2,661,399
Why do I get instruments - "Target failed to run"?
<blockquote> <p>Target failed to run: Remote exception encountered: Faild to get task for pid 3103</p> </blockquote> <p><a href="https://i.stack.imgur.com/WGHGD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WGHGD.png" alt="Target failed to run"></a></p> <p>I'm running iPhone OS 3.1.3 on the device and I can run my App in debug mode on the device. </p> <p>I downloaded and installed the xcode_3.2.2_and_iphone_sdk_3.2_final.dmg twice, without any luck.</p>
2,661,473
6
0
null
2010-04-18 06:55:47.37 UTC
4
2017-04-19 19:08:09.137 UTC
2017-04-19 19:08:09.137 UTC
null
5,292,302
null
198
null
1
36
ios|iphone|ios-simulator|instruments
14,929
<p>To answer my own question:</p> <p>I have two applications installed on my device with the <strong>same name</strong> resp. the <strong>same Bundle display name</strong>: Doublemill. Since they have different bundle identifiers, the debugger can deal with that, however Instruments seems to be confused. </p>
2,356,830
What browsers currently support JavaScript's 'let' keyword?
<p>I'm developing an app and don't have to ever worry about Internet&nbsp;Explorer and was looking into some of the features present in A+ grade browsers that aren't in Internet&nbsp;Explorer1.</p> <p>One of these features I wanted to play around with is <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7#let_definitions" rel="noreferrer" title="New in JavaScript 1.7 - MDC">JavaScript's let keyword</a></p> <p>I can't seem to get any of their 'let' examples to work in Firefox 3.6 (<a href="https://en.wikipedia.org/wiki/User_agent#Use_in_HTTP" rel="noreferrer">User-Agent</a> string: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)). I get <code>SyntaxError: missing ; before statement</code> when executing <code>let foo = "bar"</code>.</p> <p>So, what browsers support the let keyword? (Or am I doing something wrong?)</p>
2,356,926
7
6
null
2010-03-01 15:26:50.867 UTC
13
2019-11-28 12:21:00.057 UTC
2016-05-11 14:18:33.81 UTC
null
63,550
null
160,173
null
1
89
javascript|firefox|firefox3.6
60,868
<p><strong>EDIT</strong>: <code>let</code> and <code>const</code> are supported by all modern browsers and are part of the <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations" rel="noreferrer">ECMAScript 2015 (ES6)</a> specification.</p> <p>Basically if you don't need to support anything below IE11, <code>let</code> and <code>const</code> are safe to use nowadays.</p> <p>On <em>IE11</em> there's a small quirk with <code>let</code> when used with <code>for</code> loops, the variable is not bound to the <code>for</code> block as you would expect, it behaves as <code>var</code> did... </p> <p>See also: <a href="https://caniuse.com/#feat=let" rel="noreferrer">let</a> and <a href="https://caniuse.com/#feat=const" rel="noreferrer">const</a> support.</p> <hr> <p><strong>Old and outdated answer from 2010:</strong> Those extensions are not ECMA-Standard, they are supported only by the Mozilla implementation.</p> <p>On browser environments you should include the JavaScript <em>version number</em> in your <code>script</code> tag to use it:</p> <pre><code>&lt;script type="application/javascript;version=1.7"&gt; var x = 5; var y = 0; let (x = x+10, y = 12) { alert(x+y + "\n"); } alert((x + y) + "\n"); &lt;/script&gt; </code></pre>
2,399,112
Print all items in a list with a delimiter
<p>Consider this Python code for printing a list of comma separated values</p> <pre><code>for element in list: print element + &quot;,&quot;, </code></pre> <p>What is the preferred method for printing such that a comma does not appear if <code>element</code> is the final element in the list.</p> <p>ex</p> <pre><code>a = [1, 2, 3] for element in a print str(element) +&quot;,&quot;, output 1,2,3, desired 1,2,3 </code></pre>
2,399,122
8
1
null
2010-03-08 03:25:03.45 UTC
12
2022-07-20 06:52:14.193 UTC
2022-07-20 06:52:14.193 UTC
null
6,862,601
null
357,024
null
1
47
python|string|printing
81,571
<pre><code>&gt;&gt;&gt; ','.join(map(str,a)) '1,2,3' </code></pre>
2,795,313
Devise: Disable password confirmation during sign-up
<p>I am using Devise for Rails. In the default registration process, Devise requires users to type the password twice for validation and authentication. How can I disable it?</p>
13,587,139
9
4
null
2010-05-08 19:20:21.157 UTC
11
2022-03-03 15:32:01.713 UTC
2019-05-04 11:28:29.11 UTC
null
278,842
null
314,325
null
1
45
ruby-on-rails|registration|devise
18,470
<p>To disable password confirmation <strong>you can simply remove the <code>password_confirmation</code> field from the registration form.</strong> This disables the need to confirm the password entirely!</p> <ol> <li>Generate devise views if you haven't: <code>rails g devise:views</code></li> <li>Remove the <code>password_confirmation</code> section in <code>app\views\devise\registrations\new.html.erb</code></li> </ol> <hr /> <p>The reason why this works lies in <code>lib/devise/models/validatable.rb</code> in the Devise source:</p> <pre><code>module Devise module Models module Validatable def self.included(base) base.class_eval do #....SNIP... validates_confirmation_of :password, :if =&gt; :password_required? end end #...SNIP... def password_required? !persisted? || !password.nil? || !password_confirmation.nil? end end end end </code></pre> <p>Note that the validation is only triggered if <code>password_required?</code> returns <code>true</code>, and <code>password_required?</code> will return <code>false</code> if the <code>password_confirmation</code> field is <code>nil</code>.</p> <p>Because where the <code>password_confirmation</code> field is present in the form, it will always be included in the parameters hash , as an empty string if it is left blank, the validation is triggered. However, if you remove the input from the form, the <code>password_confirmation</code> in the params will be <code>nil</code>, and therefore the validation will not be triggered.</p>
2,618,403
How to kill all subprocesses of shell?
<p>I'm writing a bash script, which does several things.</p> <p>In the beginning it starts several monitor scripts, each of them runs some other tools.</p> <p>At the end of my main script, I would like to kill all things that were spawned from my shell.</p> <p>So, it might looks like this:</p> <pre><code>#!/bin/bash some_monitor1.sh &amp; some_monitor2.sh &amp; some_monitor3.sh &amp; do_some_work ... kill_subprocesses </code></pre> <p>The thing is that most of these monitors spawn their own subprocesses, so doing (for example): <code>killall some_monitor1.sh</code> will not always help.</p> <p>Any other way to handle this situation?</p>
2,618,421
9
1
null
2010-04-11 19:34:23.723 UTC
13
2022-04-28 02:54:48.243 UTC
2018-03-24 05:20:25.047 UTC
null
6,862,601
user80168
null
null
1
59
bash|shell|process|fork|kill
69,951
<p>After starting each child process, you can get its id with</p> <pre><code>ID=$! </code></pre> <p>Then you can use the stored PIDs to find and kill all grandchild etc. processes as described <a href="http://www.askdavetaylor.com/how_do_i_find_all_child_processes_in_unix.html" rel="noreferrer">here</a> or <a href="http://www.unix.com/unix-dummies-questions-answers/5245-script-kill-all-child-process-given-pid.html" rel="noreferrer">here</a>.</p>
39,931,781
git diff --stat exclude certain files
<p>Trying to adapt the answers from <a href="https://stackoverflow.com/q/10415100/281545">Want to exclude file from &quot;git diff&quot;</a> for the <code>--stat</code> flag and failing - the <a href="https://stackoverflow.com/a/10421385/281545">accepted answer</a> (create a driver) seems unix only (redirect to /bin/true, whatever this means) plus it creates a driver and assigns it to the file kind of permanently, while I am looking for a switch to temporarily disable the diff for a file (or rather some files). </p> <p>The scripting <a href="https://stackoverflow.com/a/10421413/281545">solution</a>:</p> <pre><code>git diff `git status -s |grep -v ^\ D |grep -v file/to/exclude.txt |cut -b4-` </code></pre> <p>actually calls git status and edits its output - while what I want is to instruct git diff itself to ignore some files while calculating the (simple) --stat (just lines changed). I went through <a href="https://git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> docs but can't seem to find such an option. Anyone give me a hand ?</p> <pre><code>$ git --version git version 2.6.1.windows.1 </code></pre>
39,937,070
1
0
null
2016-10-08 11:25:31.813 UTC
11
2019-08-21 16:18:32.557 UTC
2017-05-23 12:26:23.92 UTC
null
-1
null
281,545
null
1
29
git|git-diff
14,741
<p>The exclude pathspec trick, described in <a href="https://stackoverflow.com/q/5685007/1256452">Making &#39;git log&#39; ignore changes for certain paths</a>, works here:</p> <pre><code>git diff --stat -- . ':(exclude)file/to/exclude.txt' </code></pre> <p>or, if you are in a subdirectory:</p> <pre><code>git diff --stat -- :/ ':(exclude,top)file/to/exclude.txt' </code></pre> <p>The latter can be spelled in various ways. For instance, this also works:</p> <pre><code>git diff --stat ':(top)' :!/file/to/exclude.txt </code></pre> <p>as does:</p> <pre><code>git diff --stat :/: :!/:file/to/exclude.txt </code></pre> <p>These are described in <a href="https://www.kernel.org/pub/software/scm/git/docs/gitglossary.html" rel="noreferrer">the <code>gitglossary</code> documentation</a> under the "pathspec" section. Note that the exclude feature is new in Git version 1.9 (and slightly broken until 1.9.2). The leading <code>/</code> is an alias for <code>top</code> and the <code>!</code> is an alias for <code>exclude</code>, with the long forms requiring the parentheses. The trailing colon before the actual pathname is optional when using the single-character aliases but forbidden when using the parentheses (this rule trips me up every time—I keep wanting to use <code>:(exclude):...</code> rather than <code>:(exclude)...</code>). The single quotes around the <code>(top)</code> and <code>(exclude)</code> pathspec components above are to protect the parentheses from being interpreted by the (Unix/Linux) shells; the Windows shell may have different ideas about which characters need protection.</p>
10,544,456
Dynamically Adding Labels to User Form = Blank UserForm
<p>I'm trying to dynamically add buttons to the userform, but the userform just comes up blank. Ive simplified the essence of the code as much as possible for error checking (not that it's helped me)</p> <pre><code>Sub addLabel() UserForm2.Show Dim theLabel As Label Dim labelCounter As Integer For labelCounter = 1 To 3 Set Label = UserForm2.Controls.Add("Forms.Label.1", "Test" &amp; labelCounter, True) With theLabel .Caption = "Test" &amp; labelCounter .Left = 10 .Width = 50 .Top = 10 End With End Sub </code></pre> <p>Is there any way of checking if the buttons have been added but are invisible? Or why they are not being added. Any help greatly appreciated.</p>
10,545,127
3
0
null
2012-05-11 02:01:12.557 UTC
4
2020-07-05 07:56:12.787 UTC
2020-07-05 07:56:12.787 UTC
null
8,422,953
null
788,910
null
1
15
excel|vba
59,020
<p>A few things:</p> <ol> <li>You need to show your UserForm as <code>vbModeless</code> - else the code stops on <code>UserForm2.Show</code></li> <li>You are creating an object called <code>Label</code> then using <code>With</code> on <code>theLabel</code></li> <li><p>You will then need to increment the position of your three labels to avoid overlap (which I have done using <code>Top</code>).</p> <pre><code>Sub addLabel() UserForm2.Show vbModeless Dim theLabel As Object Dim labelCounter As Long For labelCounter = 1 To 3 Set theLabel = UserForm2.Controls.Add("Forms.Label.1", "Test" &amp; labelCounter, True) With theLabel .Caption = "Test" &amp; labelCounter .Left = 10 .Width = 50 .Top = 10 * labelCounter End With Next End Sub </code></pre></li> </ol>
10,741,165
PHP mail function 'from' address
<p>I'm not even sure this is possible, however what I'm trying to do is as follows. I have an HTML form that generates and email using a <code>PHP</code> script. What I want is to recieve emails from this form to <code>[email protected]</code>, then I want the <code>from</code> address to appear as one of the fields in the form.</p> <p>I have had a look around and found some useful information on this <a href="http://www.w3schools.com/php/php_ref_mail.asp" rel="noreferrer">site</a>. I'm not sure whether <code>sendmail_from</code> can be used in this situation, or if it does what I'm asking.</p> <p>Is this possible, if so how?</p>
10,741,228
3
0
null
2012-05-24 16:03:34.443 UTC
4
2012-05-24 16:12:50.073 UTC
null
null
null
user843337
null
null
1
20
email|php
41,513
<p>See this page on the same site (example 2): <a href="http://www.w3schools.com/php/func_mail_mail.asp" rel="noreferrer">http://www.w3schools.com/php/func_mail_mail.asp</a></p> <p>You will have to set the headers of the message to include the From and other stuff like CC or BCC:</p> <pre><code>&lt;?php $to = "[email protected]"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: [email protected]\r\n"; mail($to,$subject,$txt,$headers); ?&gt; </code></pre> <p>Note that you have to separate the headers with a newline sequence <code>"\r\n"</code>.</p>
10,477,085
Oracle 'Partition By' and 'Row_Number' keyword
<p>I have a SQL query written by someone else and I'm trying to figure out what it does. Can someone please explain what the <code>Partition By</code> and <code>Row_Number</code> keywords does here and give a simple example of it in action, as well as why one would want to use it?</p> <p>An example of partition by:</p> <pre><code>(SELECT cdt.*, ROW_NUMBER () OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency ORDER BY cdt.country_code, cdt.account, cdt.currency) seq_no FROM CUSTOMER_DETAILS cdt); </code></pre> <p>I've seen some examples online, they are in bit too depth.</p> <p>Thanks in advance!</p>
10,477,672
4
0
null
2012-05-07 05:28:00.2 UTC
30
2018-04-05 05:40:28.73 UTC
2018-04-05 05:40:28.73 UTC
null
3,876,565
null
889,475
null
1
52
sql|oracle|partition|row-number|analytic-functions
307,044
<p><code>PARTITION BY</code> segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.</p> <p>In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER</p> <p>But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of <code>cdt.country_code, cdt.account, cdt.currency</code> </p> <p><code>newid()</code> produces GUID, so what shall you expect by this expression? </p> <pre><code>select hi,ho, row_number() over(partition by newid() order by hi,ho) from tbl; </code></pre> <p>...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1</p> <p>Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1</p> <p>An example, this is your data:</p> <pre><code>create table tbl(hi varchar, ho varchar); insert into tbl values ('A','X'), ('A','Y'), ('A','Z'), ('B','W'), ('B','W'), ('C','L'), ('C','L'); </code></pre> <p>Then this is analogous to your query:</p> <pre><code>select hi,ho, row_number() over(partition by hi,ho order by hi,ho) from tbl; </code></pre> <p>What will be the output of that?</p> <pre><code>HI HO COLUMN_2 A X 1 A Y 1 A Z 1 B W 1 B W 2 C L 1 C L 2 </code></pre> <p>You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.</p> <p>Now, why is the <code>ORDER BY</code> needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:</p> <pre><code>select hi,ho, row_number() over(partition by hi,ho) from tbl; </code></pre> <p>But alas, Oracle(and Sql Server too) doesn't allow partition with no <code>ORDER BY</code>; whereas in Postgresql, <code>ORDER BY</code> on PARTITION is optional: <a href="http://www.sqlfiddle.com/#!1/27821/1" rel="noreferrer">http://www.sqlfiddle.com/#!1/27821/1</a></p> <pre><code>select hi,ho, row_number() over(partition by hi,ho) from tbl; </code></pre> <p>Your <code>ORDER BY</code> on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow <code>PARTITION</code> with no <code>ORDER BY</code>, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:</p> <pre><code>SELECT cdt.*, ROW_NUMBER () OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency ORDER BY newid()) seq_no FROM CUSTOMER_DETAILS cdt </code></pre> <p>You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the <strong>same values</strong> anyway. You can use GUID for example(you use <code>newid()</code> for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow <code>PARTITION</code> with no <code>ORDER BY</code></p> <p>Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: <a href="https://stackoverflow.com/questions/6645746/how-to-get-one-unique-record-from-the-same-list-of-records-from-table-no-unique">How to get one unique record from the same list of records from table? No Unique constraint in the table</a></p> <p>It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.</p> <p>Live test: <a href="http://www.sqlfiddle.com/#!3/27821/6" rel="noreferrer">http://www.sqlfiddle.com/#!3/27821/6</a></p> <hr/> <p>But as dbaseman have noticed also, it's useless to partition and order on same columns.</p> <p>You have a set of data like this:</p> <pre><code>create table tbl(hi varchar, ho varchar); insert into tbl values ('A','X'), ('A','X'), ('A','X'), ('B','Y'), ('B','Y'), ('C','Z'), ('C','Z'); </code></pre> <p>Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) <a href="http://www.sqlfiddle.com/#!3/29ab8/3" rel="noreferrer">http://www.sqlfiddle.com/#!3/29ab8/3</a></p> <pre><code>select hi,ho, row_number() over(partition by hi,ho order by hi,ho) as nr from tbl; </code></pre> <p>Output:</p> <pre><code>HI HO ROW_QUERY_A A X 1 A X 2 A X 3 B Y 1 B Y 2 C Z 1 C Z 2 </code></pre> <p>See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)</p> <hr/> <p>You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s <em>unique</em>-ing column. Example will make it more clear:</p> <pre><code>create table tbl(hi varchar, ho varchar); insert into tbl values ('A','D'), ('A','E'), ('A','F'), ('B','F'), ('B','E'), ('C','E'), ('C','D'); select hi,ho, row_number() over(partition by hi order by ho) as nr from tbl; </code></pre> <p><code>PARTITION BY hi</code> operates on non unique column, then on each partitioned column, you order on its unique column(ho), <code>ORDER BY ho</code></p> <p>Output:</p> <pre><code>HI HO NR A D 1 A E 2 A F 3 B E 1 B F 2 C D 1 C E 2 </code></pre> <p>That data set makes more sense</p> <p>Live test: <a href="http://www.sqlfiddle.com/#!3/d0b44/1" rel="noreferrer">http://www.sqlfiddle.com/#!3/d0b44/1</a></p> <p>And this is similar to your query with same columns on both PARTITION BY and ORDER BY: </p> <pre><code>select hi,ho, row_number() over(partition by hi,ho order by hi,ho) as nr from tbl; </code></pre> <p>And this is the ouput:</p> <pre><code>HI HO NR A D 1 A E 1 A F 1 B E 1 B F 1 C D 1 C E 1 </code></pre> <p>See? no sense?</p> <p>Live test: <a href="http://www.sqlfiddle.com/#!3/d0b44/3" rel="noreferrer">http://www.sqlfiddle.com/#!3/d0b44/3</a></p> <hr/> <p>Finally this might be the right query:</p> <pre><code>SELECT cdt.*, ROW_NUMBER () OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency ORDER BY -- removed: cdt.country_code, cdt.account, cdt.currency) -- keep seq_no FROM CUSTOMER_DETAILS cdt </code></pre>
5,827,804
Logback native VS Logback via SLF4J
<p>I have gone through the following article regarding the logging frameworks available for Java: <a href="http://michaelandrews.typepad.com/the_technical_times/2011/04/java-logging-reconsidered.html" rel="noreferrer">http://michaelandrews.typepad.com/the_technical_times/2011/04/java-logging-reconsidered.html</a></p> <p>The author has mentioned using SLF4J with Logback. How is that different from using Logback directly. Wouldn't it be better if one uses Logback directly rather than going for SLF4J, since Logback is built on top of SLF4J.</p>
5,847,865
2
2
null
2011-04-29 04:19:17.683 UTC
4
2014-01-13 20:40:43.99 UTC
2011-08-02 17:56:20.047 UTC
null
31,493
null
709,168
null
1
28
java|logging|slf4j|logback
9,572
<p>SLF4J is adding zero overhead to Logback since it is simply the interface that is implemented by Logback without any additional layer.</p> <p>You should use SLF4J simply because...</p> <ol> <li>It enables you to switch away from Logback if you ever need to</li> <li>It does not cost you anything, even the imports are smaller ;)</li> <li>Other people will love you for using SLF4J and hate you for using a specific logging framework directly if you ever release your code into the wild.</li> </ol> <p>The only place where you'd access Logback directly would be while (re)configuring your logging manually in an application. The need for this arises occasionally but even in that case, working with Logback would be restricted to a single class or even method.</p> <p>As a rule of thumb: libraries should always use a logging abstraction while applications define the logging they are using, optionally accessing it directly.</p>
6,074,481
Setting the value of a Label?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4902464/how-to-add-text-to-a-wpf-label-in-code">How to add text to a WPF Label in code?</a> </p> </blockquote> <p>I need set the value of a Label like this:</p> <pre><code>messagelb = "Generating file..." </code></pre> <p>I try with <code>messagelb.Text</code> and <code>messagelb.TextIput</code></p> <p>but not work.</p> <p>how can I do this? </p>
6,074,891
2
3
null
2011-05-20 15:53:53.587 UTC
1
2016-05-12 09:39:55.36 UTC
2017-05-23 12:18:03.07 UTC
null
-1
null
708,095
null
1
-3
c#|wpf|label
44,643
<p>in wpf </p> <pre><code>messagelb.Content = "Generating file..."; </code></pre>
33,305,352
Can I mix UIKit and TVMLKit within one app?
<p>I'm exploring <code>tvOS</code> and I found that Apple offers nice set of <a href="https://developer.apple.com/library/prerelease/tvos/samplecode/TVMLCatalog/Introduction/Intro.html">templates</a> written using <code>TVML</code>. I'd like to know if a <code>tvOS</code> app that utilises <code>TVML</code> templates can also use <code>UIKit</code>.</p> <p><strong>Can I mix UIKit and TVMLKit within one app?</strong></p> <p>I found a thread on <a href="https://forums.developer.apple.com/thread/19055">Apple Developer Forum</a> but it does not fully answer this question and I am going through documentation to find an answer.</p>
33,531,442
4
0
null
2015-10-23 14:52:10.337 UTC
12
2018-05-04 21:35:28.563 UTC
2015-11-05 06:08:56.753 UTC
null
3,366,741
null
348,796
null
1
18
uikit|tvos|apple-tv|tvml
4,588
<p>Yes, you can. Displaying TVML templates requires you to use an object that controls the JavaScript Context: <strong>TVApplicationController</strong>.</p> <pre><code>var appController: TVApplicationController? </code></pre> <p>This object has a <strong>UINavigationController</strong> property associated with it. So whenever you see fit, you can call:</p> <pre><code>let myViewController = UIViewController() self.appController?.navigationController.pushViewController(myViewController, animated: true) </code></pre> <p>This allows you to push a Custom UIKit viewcontroller onto the navigation stack. If you want to go back to TVML Templates, just pop the viewController off of the navigation stack.</p> <p>If what you would like to know is how to communicate between JavaScript and Swift, here is a method that creates a javascript function called <strong>pushMyView()</strong></p> <pre><code>func createPushMyView(){ //allows us to access the javascript context appController?.evaluateInJavaScriptContext({(evaluation: JSContext) -&gt; Void in //this is the block that will be called when javascript calls pushMyView() let pushMyViewBlock : @convention(block) () -&gt; Void = { () -&gt; Void in //pushes a UIKit view controller onto the navigation stack let myViewController = UIViewController() self.appController?.navigationController.pushViewController(myViewController, animated: true) } //this creates a function in the javascript context called "pushMyView". //calling pushMyView() in javascript will call the block we created above. evaluation.setObject(unsafeBitCast(pushMyViewBlock, AnyObject.self), forKeyedSubscript: "pushMyView") }, completion: {(Bool) -&gt; Void in //done running the script }) } </code></pre> <p>Once you call <strong>createPushMyView()</strong> in Swift, you are free to call <strong>pushMyView()</strong> in your javascript code and it will push a view controller onto the stack.</p> <p><strong>SWIFT 4.1 UPDATE</strong></p> <p>Just a few simple changes to method names and casting:</p> <pre><code>appController?.evaluate(inJavaScriptContext: {(evaluation: JSContext) -&gt; Void in </code></pre> <p>and</p> <pre><code>evaluation.setObject(unsafeBitCast(pushMyViewBlock, to: AnyObject.self), forKeyedSubscript: "pushMyView" as NSString) </code></pre>
23,062,154
AspNetSynchronizationContext and await continuations in ASP.NET
<p>I noticed an unexpected (and I'd say, a redundant) thread switch after <code>await</code> inside asynchronous ASP.NET Web API controller method.</p> <p>For example, below I'd expect to see the same <code>ManagedThreadId</code> at locations #2 and 3#, but most often I see a different thread at #3:</p> <pre><code>public class TestController : ApiController { public async Task&lt;string&gt; GetData() { Debug.WriteLine(new { where = "1) before await", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); await Task.Delay(100).ContinueWith(t =&gt; { Debug.WriteLine(new { where = "2) inside ContinueWith", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); }, TaskContinuationOptions.ExecuteSynchronously); //.ConfigureAwait(false); Debug.WriteLine(new { where = "3) after await", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); return "OK"; } } </code></pre> <p>I've looked at the implementation of <a href="http://referencesource.microsoft.com/#System.Web/xsp/system/Web/AspNetSynchronizationContext.cs#5257a8565ead9af4" rel="noreferrer"><code>AspNetSynchronizationContext.Post</code></a>, essentially it comes down to this:</p> <pre><code>Task newTask = _lastScheduledTask.ContinueWith(_ =&gt; SafeWrapCallback(action)); _lastScheduledTask = newTask; </code></pre> <p>Thus, <strong>the continuation is scheduled on <code>ThreadPool</code>, rather than gets inlined.</strong> Here, <code>ContinueWith</code> uses <code>TaskScheduler.Current</code>, which in my experience is always an instance of <code>ThreadPoolTaskScheduler</code> inside ASP.NET (but it doesn't have to be that, see below).</p> <p>I could eliminate a redundant thread switch like this with <code>ConfigureAwait(false)</code> or a custom awaiter, but that would take away the automatic flow of the HTTP request's state properties like <code>HttpContext.Current</code>. </p> <p>There's another side effect of the current implementation of <code>AspNetSynchronizationContext.Post</code>. <strong>It results in a deadlock in the following case:</strong></p> <pre><code>await Task.Factory.StartNew( async () =&gt; { return await Task.Factory.StartNew( () =&gt; Type.Missing, CancellationToken.None, TaskCreationOptions.None, scheduler: TaskScheduler.FromCurrentSynchronizationContext()); }, CancellationToken.None, TaskCreationOptions.None, scheduler: TaskScheduler.FromCurrentSynchronizationContext()).Unwrap(); </code></pre> <p>This example, albeit a bit contrived, shows what may happen if <code>TaskScheduler.Current</code> is <code>TaskScheduler.FromCurrentSynchronizationContext()</code>, i.e., made from <code>AspNetSynchronizationContext</code>. It doesn't use any blocking code and would have been executed smoothly in WinForms or WPF.</p> <p>This behavior of <code>AspNetSynchronizationContext</code> is different from the v4.0 implementation (which is still there as <a href="http://referencesource.microsoft.com/#System.Web/xsp/system/Web/LegacyAspNetSynchronizationContext.cs#ec2b39df91472600" rel="noreferrer"><code>LegacyAspNetSynchronizationContext</code></a>).</p> <p><strong>So, what is the reason for such change?</strong> I thought, the idea behind this might be to reduce the gap for deadlocks, but deadlock are still possible with the current implementation, when using <code>Task.Wait()</code> or <code>Task.Result</code>. </p> <p>IMO, it'd more appropriate to put it like this:</p> <pre><code>Task newTask = _lastScheduledTask.ContinueWith(_ =&gt; SafeWrapCallback(action), TaskContinuationOptions.ExecuteSynchronously); _lastScheduledTask = newTask; </code></pre> <p>Or, at least, I'd expect it to use <code>TaskScheduler.Default</code> rather than <code>TaskScheduler.Current</code>.</p> <p>If I enable <code>LegacyAspNetSynchronizationContext</code> with <code>&lt;add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" /&gt;</code> in <code>web.config</code>, it works as desired: the synchronization context gets installed on the thread where the awaited task has ended, and the continuation is synchronously executed there.</p>
23,076,876
2
0
null
2014-04-14 13:59:56.233 UTC
9
2014-04-18 08:41:26.287 UTC
2014-04-18 08:39:03.183 UTC
null
1,768,303
null
1,768,303
null
1
12
c#|asp.net|.net|task-parallel-library|async-await
3,720
<p>Now my guess is, they have implemented <code>AspNetSynchronizationContext.Post</code> this way to avoid a possibility of infinite recursion which might lead to stack overflow. That might happen if <code>Post</code> is called from the callback passed to <code>Post</code> itself.</p> <p>Still, I think an extra thread switch might be too expensive for this. It could have been possibly avoided like this:</p> <pre><code>var sameStackFrame = true try { //TODO: also use TaskScheduler.Default rather than TaskScheduler.Current Task newTask = _lastScheduledTask.ContinueWith(completedTask =&gt; { if (sameStackFrame) // avoid potential recursion return completedTask.ContinueWith(_ =&gt; SafeWrapCallback(action)); else { SafeWrapCallback(action); return completedTask; } }, TaskContinuationOptions.ExecuteSynchronously).Unwrap(); _lastScheduledTask = newTask; } finally { sameStackFrame = false; } </code></pre> <p>Based on this idea, I've created a custom awaiter which gives me the desired behavior:</p> <pre><code>await task.ConfigureContinue(synchronously: true); </code></pre> <p>It uses <code>SynchronizationContext.Post</code> if operation completed synchronously on the same stack frame, and <code>SynchronizationContext.Send</code> if it did on a different stack frame (it could even be the same thread, asynchronously reused by <code>ThreadPool</code> after some cycles): </p> <pre><code>using System; using System.Diagnostics; using System.Runtime.Remoting.Messaging; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace TestApp.Controllers { /// &lt;summary&gt; /// TestController /// &lt;/summary&gt; public class TestController : ApiController { public async Task&lt;string&gt; GetData() { Debug.WriteLine(String.Empty); Debug.WriteLine(new { where = "before await", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); // add some state to flow HttpContext.Current.Items.Add("_context_key", "_contextValue"); CallContext.LogicalSetData("_key", "_value"); var task = Task.Delay(100).ContinueWith(t =&gt; { Debug.WriteLine(new { where = "inside ContinueWith", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); // return something as we only have the generic awaiter so far return Type.Missing; }, TaskContinuationOptions.ExecuteSynchronously); await task.ConfigureContinue(synchronously: true); Debug.WriteLine(new { logicalData = CallContext.LogicalGetData("_key"), contextData = HttpContext.Current.Items["_context_key"], where = "after await", thread = Thread.CurrentThread.ManagedThreadId, context = SynchronizationContext.Current }); return "OK"; } } /// &lt;summary&gt; /// TaskExt /// &lt;/summary&gt; public static class TaskExt { /// &lt;summary&gt; /// ConfigureContinue - http://stackoverflow.com/q/23062154/1768303 /// &lt;/summary&gt; public static ContextAwaiter&lt;TResult&gt; ConfigureContinue&lt;TResult&gt;(this Task&lt;TResult&gt; @this, bool synchronously = true) { return new ContextAwaiter&lt;TResult&gt;(@this, synchronously); } /// &lt;summary&gt; /// ContextAwaiter /// TODO: non-generic version /// &lt;/summary&gt; public class ContextAwaiter&lt;TResult&gt; : System.Runtime.CompilerServices.ICriticalNotifyCompletion { readonly bool _synchronously; readonly Task&lt;TResult&gt; _task; public ContextAwaiter(Task&lt;TResult&gt; task, bool synchronously) { _task = task; _synchronously = synchronously; } // awaiter methods public ContextAwaiter&lt;TResult&gt; GetAwaiter() { return this; } public bool IsCompleted { get { return _task.IsCompleted; } } public TResult GetResult() { return _task.Result; } // ICriticalNotifyCompletion public void OnCompleted(Action continuation) { UnsafeOnCompleted(continuation); } // Why UnsafeOnCompleted? http://blogs.msdn.com/b/pfxteam/archive/2012/02/29/10274035.aspx public void UnsafeOnCompleted(Action continuation) { var syncContext = SynchronizationContext.Current; var sameStackFrame = true; try { _task.ContinueWith(_ =&gt; { if (null != syncContext) { // async if the same stack frame if (sameStackFrame) syncContext.Post(__ =&gt; continuation(), null); else syncContext.Send(__ =&gt; continuation(), null); } else { continuation(); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } finally { sameStackFrame = false; } } } } } </code></pre>
19,737,653
What is the equivalent of Regex-replace-with-function-evaluation in Java 7?
<p>I'm looking for a <em>very simple</em> way of getting the equivalent of something like the following JavaScript code. That is, for each match I would like to call a certain transformation function and use the result as the replacement value.</p> <pre><code>var res = "Hello World!".replace(/\S+/, function (word) { // Since this function represents a transformation, // replacing literal strings (as with replaceAll) are not a viable solution. return "" + word.length; }) // res =&gt; "5 6" </code></pre> <p>Only .. in Java. And, preferably as a "single method" or "template" that can be reused.</p>
19,737,857
4
0
null
2013-11-02 00:38:24.413 UTC
7
2020-03-31 11:59:24.637 UTC
2017-03-22 16:46:29.343 UTC
null
2,864,740
null
2,864,740
null
1
29
java|regex|function|replace|matchevaluator
10,218
<p>Your answer is in the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement%28java.lang.StringBuffer,%20java.lang.String%29" rel="noreferrer">Matcher#appendReplacement</a> documentation. Just put your function call in the while loop.</p> <blockquote> <p>[The appendReplacement method] is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:</p> </blockquote> <pre><code>Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toString()); </code></pre>
55,596,789
Deploying GitLab pages for different branches
<p>I am deploying my React app using GitLab Pages, and it works well.</p> <p>Here is my <code>gitlab-ci.yml</code>:</p> <pre class="lang-yaml prettyprint-override"><code># Using the node alpine image to build the React app image: node:alpine # Announce the URL as per CRA docs # https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#advanced-configuration variables: PUBLIC_URL: / # Cache node modules - speeds up future builds cache: paths: - client/node_modules # Name the stages involved in the pipeline stages: - deploy # Job name for gitlab to recognise this results in assets for Gitlab Pages # https://docs.gitlab.com/ee/user/project/pages/introduction.html#gitlab-pages-requirements pages: stage: deploy script: - cd client - npm install # Install all dependencies - npm run build --prod # Build for prod - cp public/index.html public/404.html # Not necessary, but helps with https://medium.com/@pshrmn/demystifying-single-page-applications-3068d0555d46 - mv public _public # CRA and gitlab pages both use the public folder. Only do this in a build pipeline. - mv build ../public # Move build files to public dir for Gitlab Pages artifacts: paths: - public # The built files for Gitlab Pages to serve only: - master # Only run on master branch </code></pre> <p>Now, I just created a dev version, based on my branch <code>develop</code></p> <p>I would like to have 2 versions of my React app with 2 different URLs. How can I do that?</p> <p>For example right now, I have:</p> <p><code>my-react-app.com</code> linked to <code>master</code> branch</p> <p>How should I have</p> <p><code>dev.my-react-app.com</code> or even <code>my-react-app.gitlab.io</code> linked to <code>develop</code> branch?&lt;</p>
58,402,821
3
1
null
2019-04-09 15:54:49.317 UTC
14
2022-06-04 09:44:39.26 UTC
2022-06-04 09:44:39.26 UTC
null
2,249,995
null
1,956,558
null
1
34
git|gitlab|gitlab-pages
18,068
<p>I've had success using the browsable artifacts for this purpose. In your example, you would create a job for your develop branch and set the <code>PUBLIC_URL</code> to the path on <code>gitlab.io</code> where the job's artifacts are published:</p> <pre class="lang-yaml prettyprint-override"><code>develop: artifacts: paths: - public environment: name: Develop url: "https://$CI_PROJECT_NAMESPACE.gitlab.io/-/$CI_PROJECT_NAME/-/jobs/$CI_JOB_ID/artifacts/public/index.html" script: | # whatever stage: deploy variables: PUBLIC_URL: "/-/$CI_PROJECT_NAME/-/jobs/$CI_JOB_ID/artifacts/public" </code></pre> <p>Setting the <code>environment</code> as indicated produces a »Review app« link in relevant merge requests, allowing you to get to the artifacts with a single click.</p> <p><strong>Note</strong>: if your repository is in a <a href="https://docs.gitlab.com/ee/user/group/subgroups/index.html" rel="noreferrer">subgroup</a>, you need to insert the subgroup name in two places above above between <code>/-/</code> and <code>$CI_PROJECT_NAME</code> for the resulting URLs to work.</p>
35,526,532
How to add an elasticsearch index during docker build
<p>I use the official elasticsearch docker image and wonder how can I include also during building a custom index, so that the index is already there when I start the container. </p> <p>My attempt was to add the following line to my dockerfile:</p> <pre><code>RUN curl -XPUT 'http://127.0.0.1:9200/myindex' -d @index.json </code></pre> <p>I get the following error: </p> <pre><code>0curl: (7) Failed to connect to 127.0.0.1 port 9200: Connection refused </code></pre> <p>Can I reach elasticsearch during build with such an API call or is there a complete different way to implement that? </p>
39,873,112
3
0
null
2016-02-20 17:23:05.097 UTC
7
2019-12-09 06:05:47.347 UTC
null
null
null
null
985,881
null
1
39
elasticsearch|docker
19,858
<p>I've had a similar problem.</p> <p>I wanted to create a docker container with preloaded data (via some scripts and json files in the repo). The data inside elasticsearch was not going to change during the execution and I wanted as few build steps as possible (ideally only <code>docker-compose up -d</code>).</p> <p>One option would be to do it manually once, and store the elasticsearch data folder (with a docker volume) in the repository. But then I would have had duplicate data and I would have to check in manually a new version of the data folder every time the data changes.</p> <h2>The solution</h2> <ol> <li>Make elasticsearch write data to a folder that is not declared as a volume in elasticsearchs' official dockerfile.</li> </ol> <p><code>RUN mkdir /data &amp;&amp; chown -R elasticsearch:elasticsearch /data &amp;&amp; echo 'es.path.data: /data' &gt;&gt; config/elasticsearch.yml &amp;&amp; echo 'path.data: /data' &gt;&gt; config/elasticsearch.yml </code></p> <p>(the folder needs to be created with the right permissions)</p> <ol start="2"> <li>Download <a href="https://github.com/vishnubob/wait-for-it" rel="noreferrer">wait-for-it</a></li> </ol> <p><code>ADD https://raw.githubusercontent.com/vishnubob/wait-for-it/e1f115e4ca285c3c24e847c4dd4be955e0ed51c2/wait-for-it.sh /utils/wait-for-it.sh</code></p> <p>This script will wait until elasticsearch is up to run our insert commands.</p> <ol start="3"> <li>Insert data into elasticsearch</li> </ol> <p><code>RUN /docker-entrypoint.sh elasticsearch -p /tmp/epid &amp; /bin/bash /utils/wait-for-it.sh -t 0 localhost:9200 -- path/to/insert/script.sh; kill $(cat /tmp/epid) &amp;&amp; wait $(cat /tmp/epid); exit 0; </code></p> <p>This command starts elasticsearch during the build process, inserts data and takes it down in one RUN command. The container is left as it was except for elasticsearch's data folder which has been properly initialized now.</p> <h2>Summary</h2> <pre><code>FROM elasticsearch RUN mkdir /data &amp;&amp; chown -R elasticsearch:elasticsearch /data &amp;&amp; echo 'es.path.data: /data' &gt;&gt; config/elasticsearch.yml &amp;&amp; echo 'path.data: /data' &gt;&gt; config/elasticsearch.yml ADD https://raw.githubusercontent.com/vishnubob/wait-for-it/e1f115e4ca285c3c24e847c4dd4be955e0ed51c2/wait-for-it.sh /utils/wait-for-it.sh # Copy the files you may need and your insert script RUN /docker-entrypoint.sh elasticsearch -p /tmp/epid &amp; /bin/bash /utils/wait-for-it.sh -t 0 localhost:9200 -- path/to/insert/script.sh; kill $(cat /tmp/epid) &amp;&amp; wait $(cat /tmp/epid); exit 0; </code></pre> <p>And that's it! When you run this image, the database will have preloaded data, indexes, etc...</p>
19,022,702
how to change the color of route in google maps v3
<p>I am using this <a href="https://developers.google.com/maps/documentation/javascript/examples/directions-simple">code</a> to get directions between two points. Is it possible to change the color of the route from blue? I am not using polyline in my code.</p> <p>Thanx in advance :)</p>
19,023,573
2
0
null
2013-09-26 08:09:28.913 UTC
7
2018-06-11 09:08:10.097 UTC
2013-09-26 09:55:26.177 UTC
null
2,809,895
null
2,809,895
null
1
31
google-maps|google-maps-api-3|stroke
49,790
<p>You can specify the color of the line when you create the DirectionsRenderer, using the optional <a href="https://developers.google.com/maps/documentation/javascript/reference?csw=1#DirectionsRendererOptions" rel="noreferrer">DirectionsRendererOptions</a> struct.</p> <p>This works for me, simply changing the line where the DirectionsRenderer object is created:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="initial-scale=1.0, user-scalable=no"&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Directions service&lt;/title&gt; &lt;link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet"&gt; &lt;script src="https://maps.googleapis.com/maps/api/js?v=3"&gt;&lt;/script&gt; &lt;script&gt; var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "red" } }); var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: {lat: 41.850033, lng: -87.6500523} } map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); directionsDisplay.setMap(map); } function calcRoute() { var start = document.getElementById('start').value; var end = document.getElementById('end').value; var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } google.maps.event.addDomListener(window, 'load', initialize); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="panel"&gt; &lt;b&gt;Start: &lt;/b&gt; &lt;select id="start" onchange="calcRoute();"&gt; &lt;option value="chicago, il"&gt;Chicago&lt;/option&gt; &lt;option value="st louis, mo"&gt;St Louis&lt;/option&gt; &lt;option value="joplin, mo"&gt;Joplin, MO&lt;/option&gt; &lt;option value="oklahoma city, ok"&gt;Oklahoma City&lt;/option&gt; &lt;option value="amarillo, tx"&gt;Amarillo&lt;/option&gt; &lt;option value="gallup, nm"&gt;Gallup, NM&lt;/option&gt; &lt;option value="flagstaff, az"&gt;Flagstaff, AZ&lt;/option&gt; &lt;option value="winona, az"&gt;Winona&lt;/option&gt; &lt;option value="kingman, az"&gt;Kingman&lt;/option&gt; &lt;option value="barstow, ca"&gt;Barstow&lt;/option&gt; &lt;option value="san bernardino, ca"&gt;San Bernardino&lt;/option&gt; &lt;option value="los angeles, ca"&gt;Los Angeles&lt;/option&gt; &lt;/select&gt; &lt;b&gt;End: &lt;/b&gt; &lt;select id="end" onchange="calcRoute();"&gt; &lt;option value="chicago, il"&gt;Chicago&lt;/option&gt; &lt;option value="st louis, mo"&gt;St Louis&lt;/option&gt; &lt;option value="joplin, mo"&gt;Joplin, MO&lt;/option&gt; &lt;option value="oklahoma city, ok"&gt;Oklahoma City&lt;/option&gt; &lt;option value="amarillo, tx"&gt;Amarillo&lt;/option&gt; &lt;option value="gallup, nm"&gt;Gallup, NM&lt;/option&gt; &lt;option value="flagstaff, az"&gt;Flagstaff, AZ&lt;/option&gt; &lt;option value="winona, az"&gt;Winona&lt;/option&gt; &lt;option value="kingman, az"&gt;Kingman&lt;/option&gt; &lt;option value="barstow, ca"&gt;Barstow&lt;/option&gt; &lt;option value="san bernardino, ca"&gt;San Bernardino&lt;/option&gt; &lt;option value="los angeles, ca"&gt;Los Angeles&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="map-canvas"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
46,802,099
How can I set the field unique in django?
<p>I have a model class:</p> <pre><code>class PysicalServer(models.Model): serial_number = models.CharField(max_length=64) # I want to add the unique name = models.CharField(max_length=16) </code></pre> <p>I know use the primary_key can set unique, but the serial_number is not my id field, I can not use the primary_key, is there other property I can set field unique?</p>
46,802,144
4
0
null
2017-10-18 02:55:18.26 UTC
6
2022-08-18 04:29:39.553 UTC
2022-08-18 04:29:39.553 UTC
null
17,562,044
null
7,693,832
null
1
31
python|django|django-models
37,059
<p>Just add <code>unique=True</code> in the field, so:</p> <pre class="lang-py prettyprint-override"><code>serial_number = models.CharField(max_length=64, unique=True) </code></pre> <p>Refer <a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#unique" rel="nofollow noreferrer">docs</a> for more information.</p>
28,046,506
Bootstrap responsive Table -> change Rows with Column
<p>I have a problem creating a timetable for my school using Bootstrap. The timetable should be responsive for mobile devices and tablets.</p> <p>The view for larger screens works perfectly, but when it switches to the mobile View, it changes the rows with columns ..</p> <p>Tabletview: <a href="http://imgur.com/U3ger2a,6ThcH1l" rel="noreferrer">http://imgur.com/U3ger2a,6ThcH1l</a> <img src="https://i.stack.imgur.com/nvQJM.png" alt="enter image description here"></p> <p>Mobileview: <a href="http://imgur.com/U3ger2a,6ThcH1l#1" rel="noreferrer">http://imgur.com/U3ger2a,6ThcH1l#1</a> <img src="https://i.stack.imgur.com/plksa.png" alt="enter image description here"></p> <p>The main html File:</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>@media only screen and (max-width: 800px) { /* Force table to not be like tables anymore */ #no-more-tables table, #no-more-tables thead, #no-more-tables tbody, #no-more-tables th, #no-more-tables td, #no-more-tables tr { display: block; } /* Hide table headers (but not display: none;, for accessibility) */ #no-more-tables thead tr { position: absolute; top: -9999px; left: -9999px; } #no-more-tables tr { border: 1px solid #ccc; } #no-more-tables td { /* Behave like a "row" */ border: none; border-bottom: 1px solid #eee; position: relative; padding-left: 50%; white-space: normal; text-align:left; } #no-more-tables td:before { /* Now like a table header */ position: absolute; /* Top/left values mimic padding */ top: 6px; left: 6px; width: 45%; padding-right: 10px; white-space: nowrap; text-align:left; font-weight: bold; } /* Label the data */ #no-more-tables td:before { content: attr(data-title); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Timetable&lt;/title&gt; &lt;link href="css/bootstrap.min.css" rel="stylesheet"&gt; &lt;link href="js/bootstrap.js" rel="stylesheet"&gt; &lt;!-- &lt;link src="styles.css" rel="stylesheet"&gt; --&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- jQuery (necessary for Bootstrap's JavaScript plugins) --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Include all compiled plugins (below), or include individual files as needed --&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="styles.css" rel="stylesheet"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-12"&gt; &lt;h2 class="text-center"&gt; Timetable &lt;/h2&gt; &lt;/div&gt; &lt;div id="no-more-tables"&gt; &lt;table class="col-sm-12 table-bordered table-striped table-condensed cf"&gt; &lt;thead class="cf"&gt; &lt;tr&gt; &lt;th&gt; &lt;/th&gt; &lt;th&gt;Monday&lt;/th&gt; &lt;th&gt;Tuesday&lt;/th&gt; &lt;th&gt;Wednesday&lt;/th&gt; &lt;th&gt;Thursday&lt;/th&gt; &lt;th&gt;Friday&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td data-title=" "&gt;07:45 |1| 08:35&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;08:35 |2| 09:25&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;09:30 |3| 10:20&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;10:35 |4| 11:25&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;11:30 |5| 12:20&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;12:20 |6| 13:10&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;13:10 |7| 14:00&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;14:00 |8| 14:50&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;15:00 |9| 15:50&lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;15:55 |10| 16:45 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;16:50 |11| 17:40 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;17:40 |12| 18:30 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;18:55 |13| 19:40 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;19:40 |14| 20:25 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;20:30 |15| 21:15 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-title=" "&gt;21:15 |16| 22:00 &lt;/td&gt; &lt;td data-title="Monday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Tuesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Wednesday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Thursday"&gt;Lesson&lt;/td&gt; &lt;td data-title="Friday"&gt;Lesson&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Did anyone know, how to solve this problem?</p>
28,126,196
1
0
null
2015-01-20 13:26:22.543 UTC
15
2017-10-12 11:37:07.683 UTC
2017-02-01 09:49:56.237 UTC
null
4,370,109
null
4,183,627
null
1
20
html|twitter-bootstrap|css|html-table
71,372
<p>Replace your html code lines</p> <p><code>&lt;div id="no-more-tables"&gt;</code> with <code>&lt;div class="table-responsive"&gt;</code></p> <p>and</p> <p><code>&lt;table class="col-sm-12 table-bordered table-striped table-condensed cf"&gt;</code> with <code>&lt;table class="table col-sm-12 table-bordered table-striped table-condensed cf"&gt;</code></p> <p>See working <a href="http://jsfiddle.net/rxbaoj1r/">example</a></p>
8,532,929
What does two asterisks together in file path mean?
<p>What does the following file path mean? </p> <pre><code>$(Services_Jobs_Drop_Path)\**\*.config </code></pre> <p>The variable just holds some path, nothing interesting. I'm a lot more concerned, what the hell the <code>**</code> mean. Any ideas?</p> <p>P.S. The following path is used in msbuild scripts, if it helps.</p>
8,532,962
1
0
null
2011-12-16 10:36:45.527 UTC
19
2022-02-27 15:13:34.457 UTC
2022-02-27 15:13:34.457 UTC
null
1,063,716
null
476,756
null
1
86
windows|msbuild|filepath
44,412
<p><code>\**\</code> This pattern is often used in <a href="http://msdn.microsoft.com/en-us/library/3e54c37h.aspx">Copy Task</a> for recursive folder tree traversal. Basically it means that all files with extension <code>config</code> would be processed from the all subdirectories of <code>$(Services_Jobs_Drop_Path)</code> path.</p> <p>MSDN, <a href="http://msdn.microsoft.com/en-us/library/ms171453.aspx">Using Wildcards to Specify Items</a>:</p> <blockquote> <p>You can use the **, *, and ? wildcard characters to specify a group of files as inputs for a build instead of listing each file separately.</p> <ul> <li>The ? wildcard character matches a single character.</li> <li>The * wildcard character matches zero or more characters.</li> <li>The ** wildcard character sequence matches a partial path.</li> </ul> </blockquote> <p>MSDN, <a href="http://msdn.microsoft.com/en-us/library/ms171454.aspx">Specifying Inputs with Wildcards</a></p> <blockquote> <p>To include all .jpg files in the Images directory and subdirectories Use the following Include attribute:</p> <p>Include="Images\**\*.jpg"</p> </blockquote>
30,305,069
Numpy concatenate 2D arrays with 1D array
<p>I am trying to concatenate 4 arrays, one 1D array of shape (78427,) and 3 2D array of shape (78427, 375/81/103). Basically this are 4 arrays with features for 78427 images, in which the 1D array only has 1 value for each image.</p> <p>I tried concatenating the arrays as follows:</p> <pre><code>&gt;&gt;&gt; print X_Cscores.shape (78427, 375) &gt;&gt;&gt; print X_Mscores.shape (78427, 81) &gt;&gt;&gt; print X_Tscores.shape (78427, 103) &gt;&gt;&gt; print X_Yscores.shape (78427,) &gt;&gt;&gt; np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1) </code></pre> <p>This results in the following error: </p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in ValueError: all the input arrays must have same number of dimensions</p> </blockquote> <p>The problem seems to be the 1D array, but I can't really see why (it also has 78427 values). I tried to transpose the 1D array before concatenating it, but that also didn't work. </p> <p>Any help on what's the right method to concatenate these arrays would be appreciated!</p>
30,305,148
3
0
null
2015-05-18 13:52:37.483 UTC
6
2020-04-08 07:36:15.513 UTC
null
null
null
null
4,809,610
null
1
35
python|arrays|numpy|concatenation
36,578
<p>Try concatenating <code>X_Yscores[:, None]</code> (or <code>X_Yscores[:, np.newaxis]</code> as imaluengo suggests). This creates a 2D array out of a 1D array.</p> <p>Example:</p> <pre><code>A = np.array([1, 2, 3]) print A.shape print A[:, None].shape </code></pre> <p>Output:</p> <pre><code>(3,) (3,1) </code></pre>
30,413,488
Apache Spark application deployment best practices
<p>I have a couple of use cases for Apache Spark applications/scripts, generally of the following form:</p> <p><strong>General ETL use case</strong> - more specifically a transformation of a Cassandra column family containing many events (think event sourcing) into various aggregated column families.</p> <p><strong>Streaming use case</strong> - realtime analysis of the events as they arrive in the system.</p> <p>For <strong>(1)</strong>, I'll need to kick off the Spark application periodically.</p> <p>For <strong>(2)</strong>, just kick off the long running Spark Streaming process at boot time and let it go.</p> <p><em>(Note - I'm using Spark Standalone as the cluster manager, so no yarn or mesos)</em></p> <p>I'm trying to figure out the most common / best practice deployment strategies for Spark applications. </p> <p>So far the options I can see are:</p> <ol> <li><p><strong>Deploying my program as a jar</strong>, and running the various tasks with spark-submit - which seems to be the way recommended in the spark docs. Some thoughts about this strategy:</p> <ul> <li>how do you start/stop tasks - just using simple bash scripts?</li> <li>how is scheduling managed? - simply use cron?</li> <li>any resilience? (e.g. Who schedules the jobs to run if the driver server dies?)</li> </ul></li> <li><p><strong>Creating a separate webapp</strong> as the driver program.</p> <ul> <li>creates a spark context programmatically to talk to the spark cluster</li> <li>allowing users to kick off tasks through the http interface</li> <li>using Quartz (for example) to manage scheduling</li> <li>could use cluster with zookeeper election for resilience</li> </ul></li> <li><p><strong>Spark job server</strong> (<a href="https://github.com/ooyala/spark-jobserver">https://github.com/ooyala/spark-jobserver</a>)</p> <ul> <li>I don't think there's much benefit over (2) for me, as I don't (yet) have many teams and projects talking to Spark, and would still need some app to talk to job server anyway</li> <li>no scheduling built in as far as I can see</li> </ul></li> </ol> <p>I'd like to understand the general consensus w.r.t a simple but robust deployment strategy - I haven't been able to determine one by trawling the web, as of yet.</p> <p>Thanks very much!</p>
30,422,862
1
0
null
2015-05-23 13:50:49.507 UTC
11
2015-05-25 07:05:17.207 UTC
null
null
null
null
395,079
null
1
21
apache-spark|spark-streaming
2,793
<p>Even though you are not using Mesos for Spark, you could have a look at </p> <p>-<a href="https://github.com/mesos/chronos">Chronos </a> offering a distributed and fault tolerant cron</p> <p>-<a href="https://github.com/mesosphere/marathon">Marathon</a> a Mesos framework for long running applications</p> <p>Note that this doesn't mean you have to move your spark deployment to mesos, e.g. you could just use chronos to trigger the spark -submit.</p> <p>I hope I understood your problem correctly and this helps you a bit!</p>
43,719,789
C++17 Variadic Template Folding
<p>I don't understand why this doesn't work. Could someone who understands templates and variadic expression folding explain what is going on and give a solution that does work?</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; template &lt;typename... Args&gt; void print(Args... args) { std::string sep = " "; std::string end = "\n"; (std::cout &lt;&lt; ... &lt;&lt; sep &lt;&lt; args) &lt;&lt; end; } int main() { print(1, 2, 3); } </code></pre> <p>It should print out each of the args with a space in between and a newline at the end. It works if you remove the <code>sep &lt;&lt;</code> but then there is no space between each argument when it is printed.</p>
43,719,934
7
0
null
2017-05-01 13:22:13.027 UTC
11
2019-05-10 21:07:33.217 UTC
2018-01-31 16:22:19.727 UTC
null
2,069,064
null
4,705,242
null
1
26
c++|variadic-templates|fold|c++17
8,846
<p>The grammar for binary <a href="http://en.cppreference.com/w/cpp/language/fold" rel="noreferrer">fold-expressions</a> must be one of:</p> <pre><code>(pack op ... op init) (init op ... op pack) </code></pre> <p>What you have is <code>(std::cout &lt;&lt; ... &lt;&lt; sep &lt;&lt; args)</code>, which doesn't fit either form. You need something like <code>(cout &lt;&lt; ... &lt;&lt; pack)</code>, which is why removing <code>sep</code> works. </p> <p>Instead, you can either fold over a comma:</p> <pre><code>((std::cout &lt;&lt; sep &lt;&lt; args), ...); </code></pre> <p>or use recursion:</p> <pre><code>template &lt;class A, class... Args&gt; void print(A arg, Args... args) { std::cout &lt;&lt; arg; if constexpr (sizeof...(Args) &gt; 0) { std::cout &lt;&lt; sep; print(args...); } } </code></pre>
43,852,562
Round corner for BottomSheetDialogFragment
<p>I have a custom BttomSheetDialogFragment and I want to have round corners in top of Bottom View</p> <p>This is my Custom class that inflates my layout that I want to appear from bottom</p> <pre class="lang-java prettyprint-override"><code>View mView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.charge_layout, container, false); initChargeLayoutViews(); return mView; } </code></pre> <p>and also I have this XML resource file as background:</p> <pre class="lang-xml prettyprint-override"><code>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:shape=&quot;rectangle&quot; &gt; &lt;corners android:topRightRadius=&quot;35dp&quot; android:topLeftRadius=&quot;35dp&quot; /&gt; &lt;solid android:color=&quot;@color/white&quot;/&gt; &lt;padding android:top=&quot;10dp&quot; android:bottom=&quot;10dp&quot; android:right=&quot;16dp&quot; android:left=&quot;16dp&quot;/&gt; &lt;/shape&gt; </code></pre> <p>The problem is, when I set this resource file as background of my Layout's root element, the corners still are not rounded.</p> <p>I can't use below code:</p> <pre class="lang-java prettyprint-override"><code>this.getDialog().getWindow().setBackgroundDrawableResource(R.drawable.charge_layout_background); </code></pre> <p>Because it overrides the default background of BottomSheetDialog and there won't be any semi-transparent gray color above my Bottom View.</p>
50,929,873
28
1
null
2017-05-08 16:18:56.887 UTC
55
2022-09-20 04:51:04.353 UTC
2021-02-17 16:30:34.523 UTC
null
466,862
null
4,061,352
null
1
199
android|material-design|bottom-sheet|material-components-android|material-components
128,003
<p>Create a custom drawable <code>rounded_dialog.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"&gt; &lt;solid android:color="@android:color/white"/&gt; &lt;corners android:topLeftRadius="16dp" android:topRightRadius="16dp"/&gt; &lt;/shape&gt; </code></pre> <p>Then override <code>bottomSheetDialogTheme</code> on <code>styles.xml</code> using the drawable as background:</p> <pre><code>&lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="bottomSheetDialogTheme"&gt;@style/AppBottomSheetDialogTheme&lt;/item&gt; &lt;/style&gt; &lt;style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog"&gt; &lt;item name="bottomSheetStyle"&gt;@style/AppModalStyle&lt;/item&gt; &lt;/style&gt; &lt;style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal"&gt; &lt;item name="android:background"&gt;@drawable/rounded_dialog&lt;/item&gt; &lt;/style&gt; </code></pre> <p>This will change all the BottomSheetDialogs of your app.</p>
39,611,520
__init__ vs __enter__ in context managers
<p>As far as I understand, <code>__init__()</code> and <code>__enter__()</code> methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. What is the purpose of separating them into two methods, and what should I put into each?</p> <p>Edit: sorry, wasn't paying attention to the docs.</p> <p>Edit 2: actually, the reason I got confused is because I was thinking of <code>@contextmanager</code> decorator. A context manager created using <code>@contextmananger</code> can only be used once (the generator will be exhausted after the first use), so often they are written with the constructor call inside <code>with</code> statement; and if that was the only way to use <code>with</code> statement, my question would have made sense. Of course, in reality, context managers are more general than what <code>@contextmanager</code> can create; in particular context managers can, in general, be reused. I hope I got it right this time?</p>
39,611,597
2
1
null
2016-09-21 08:40:39.3 UTC
7
2018-01-23 12:05:14.51 UTC
2016-09-21 09:18:01.087 UTC
null
336,527
null
336,527
null
1
50
python|python-3.x|contextmanager
28,705
<blockquote> <p>As far as I understand, <code>__init__()</code> and <code>__enter__()</code> methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between.</p> </blockquote> <p>And your understanding is incorrect. <code>__init__</code> is called when the object is created, <code>__enter__</code> when it is entered with <code>with</code> statement, and these are 2 quite distinct things. Often it is so that the constructor is directly called in <code>with</code> initialization, with no intervening code, but this doesn't have to be the case.</p> <p>Consider this example:</p> <pre><code>class Foo: def __init__(self): print('__init__ called') def __enter__(self): print('__enter__ called') return self def __exit__(self, *a): print('__exit__ called') myobj = Foo() print('\nabout to enter with 1') with myobj: print('in with 1') print('\nabout to enter with 2') with myobj: print('in with 2') </code></pre> <p><code>myobj</code> can be initialized separately and entered in multiple <code>with</code> blocks:</p> <p>Output:</p> <pre><code>__init__ called about to enter with 1 __enter__ called in with 1 __exit__ called about to enter with 2 __enter__ called in with 2 __exit__ called </code></pre> <p>Furthermore if <code>__init__</code> and <code>__enter__</code> weren't separated, it wouldn't be possible to even use the following:</p> <pre><code>def open_etc_file(name): return open(os.path.join('/etc', name)) with open_etc_file('passwd'): ... </code></pre> <p>since the initialization (within <code>open</code>) is clearly separate from <code>with</code> entry.</p> <hr> <p>The managers created by <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="noreferrer"><code>contextlib.manager</code></a> are single-entrant, but they again can be constructed outside the <code>with</code> block. Take the example:</p> <pre><code>from contextlib import contextmanager @contextmanager def tag(name): print("&lt;%s&gt;" % name) yield print("&lt;/%s&gt;" % name) </code></pre> <p>you can use this as:</p> <pre><code>def heading(level=1): return tag('h{}'.format(level)) my_heading = heading() print('Below be my heading') with my_heading: print('Here be dragons') </code></pre> <p>output:</p> <pre><code>Below be my heading &lt;h1&gt; Here be dragons &lt;/h1&gt; </code></pre> <p>However, if you try to reuse <code>my_heading</code> (and, consequently, <code>tag</code>), you will get</p> <pre><code>RuntimeError: generator didn't yield </code></pre>
67,044,273
Rxjs toPromise() deprecated
<p>I have read that <code>toPromise()</code> is being deprecated in RxJS 7 and will be removed in RxJS 8. I have often used it with async await syntax in angular to handle http calls. Is it considered an anti pattern? I understand the concept of streams but an http call only emit a single value. I don't get the point of observable for a simple http call. What should I use next? should I fully embrace reactive programming?</p>
67,044,352
3
1
null
2021-04-11 11:11:55.847 UTC
3
2022-08-29 02:23:18.743 UTC
null
null
null
null
14,296,512
null
1
37
javascript|angular|typescript|rxjs
31,017
<p><em><strong>Why is this happening?</strong></em></p> <p>As mentioned <a href="https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated#why-is-this-happening-to-me" rel="noreferrer">here</a>, these are the main reasons why <code>toPromise</code> is being deprecated:</p> <blockquote> <ol> <li><p>One goal was to remove it from the <code>Observable</code> prototype and turn it into a standalone util function.</p> </li> <li><p>The naming of <code>toPromise</code> is not the best. Especially when used in combination with <code>await</code> it does not read very well: <code>await categories$.toPromise()</code> vs <code>await lastValueFrom(categories$)</code></p> </li> <li><p>The type information of <code>toPromise</code> is wrong. When the source <code>Observable</code> completed without ever emitting a single value - it resolved with <code>undefined</code>. It should reject in that case. A <code>Promise</code> is a &quot;promise&quot; that when it resolves a value will be there - and be it <code>undefined</code>. But when the stream completes without ever emitting a value you can't differentiate between a stream that a emitted <code>undefined</code> on purpose and a stream that completed without ever emitting anymore</p> </li> </ol> </blockquote> <p><em><strong>What should you use next?</strong></em></p> <p>If you really insist doing it the promise way, <code>lastValueFrom</code>/<code>firstValueFrom</code>. Otherwise switching to reactive programming would be the way to go.</p> <p>Using <code>toPromise</code> ( deprecated ) -</p> <pre><code>public async loadCategories() { this.categories = await this.inventoryService .getCategories() .toPromise() } </code></pre> <p>Using <code>lastValueFrom</code> ( new ) -</p> <pre><code>import { lastValueFrom } from 'rxjs'; public async loadCategories() { const categories$ = this.inventoryService.getCategories(); this.categories = await lastValueFrom(categories$); } </code></pre> <p>This link should help -</p> <p><a href="https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated" rel="noreferrer">https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated</a></p>
6,781,535
Special Login with Spring Security
<p>The company where i am currently working has a special kind of authentication process. </p> <p>Indeed, several users can have the same login and password. So, to identify them, in a second time, the user has to give his email. But again, in a few cases, several users can be concerned and then, the user has to give his company id to be full authenticated.</p> <p>So, my problem is that in some cases, the authentication process <strong>cannot be done in one step</strong>, which is the default behaviour of most applications that Spring Security handles out of the box.</p> <p>So my question is : what is the simpliest way to implement with Spring Security this <strong>special login process</strong> ?</p> <p>Thanks in advance.</p>
6,783,402
1
0
null
2011-07-21 19:22:39.187 UTC
15
2011-07-23 09:15:08.573 UTC
2011-07-23 09:15:08.573 UTC
null
856,672
null
856,672
null
1
17
java|spring-mvc|spring-security
7,049
<p>I had to do a similar two-step authentication process. It sounds simple, but finding the right places to inject and the right methods to override was not easy. The basic idea is to provide another role for the intermediate authentication (the email check), then grant full access after the email is confirmed.</p> <p>Hopefully the code below provides some good hints on how it could be solved for your scenario.</p> <p>Create a custom UserDetailsChecker to handle post-authentication checks. This is where the user's role is determined.</p> <pre><code>public class CustomPostAuthenticationChecks implements UserDetailsChecker { public void check(UserDetails userDetails) { CustomUser customUser = (CustomUser) userDetails; if (customUser.needsEmailAuthentication()) { // Get rid of any authorities the user currently has userDetails.getAuthorities().clear(); // Set the new authority, only allowing access to the // email authentication page. userDetails.getAuthorities().add(new GrantedAuthorityImpl("ROLE_NEEDS_EMAIL_AUTH")); } else { userDetails.getAuthorities().add(new GrantedAuthorityImpl("ROLE_AUTHORIZED_USER")); } } </code></pre> <p>Create a custom AuthenticationSuccessHandler. This class sends the user to the correct URL based on their role.</p> <pre><code>public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) { String targetUrl = null; SecurityContext securityContext = SecurityContextHolder.getContext(); Collection&lt;GrantedAuthority&gt; authorities = securityContext.getAuthentication().getAuthorities(); if (authorities.contains(new GrantedAuthorityImpl("ROLE_NEEDS_EMAIL_AUTH"))) { targetUrl = "/authenticate"; } else if (authorities.contains(new GrantedAuthorityImpl("ROLE_AUTHORIZED_USER"))) { targetUrl = "/authorized_user_url"; } else { targetUrl = super.determineTargetUrl(request, response); } return targetUrl; } </code></pre> <p>After the user's email address is authenticated, you will need to grant the user full access to the application:</p> <pre><code>public void grantUserAccess(User user) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication auth = securityContext.getAuthentication(); user.getAuthorities().clear(); user.getAuthorities().add(new GrantedAuthorityImpl("ROLE_AUTHORIZED_USER")); Authentication newAuth = new UsernamePasswordAuthenticationToken(user, auth.getCredentials(), user.getAuthorities()); securityContext.setAuthentication(newAuth); } </code></pre> <p>Define a custom authentication provider to register your CustomPostAuthenticationChecks:</p> <pre><code>&lt;security:authentication-manager&gt; &lt;security:authentication-provider ref="customAuthenticationProvider" /&gt; &lt;/security:authentication-manager&gt; &lt;bean id="customAuthenticationProvider" class="YourAuthenticationProvider"&gt; &lt;property name="postAuthenticationChecks"&gt; &lt;bean class="CustomPostAuthenticationChecks"/&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>If you're using the standard form-login tag, you can easily define your custom AuthenticationSuccessHandler:</p> <pre><code>&lt;security:form-login authentication-success-handler-ref="customAuthenticationSuccessHandler"&gt; ... &lt;bean id="customAuthenticationSuccessHandler" class="CustomAuthenticationSuccessHandler"/&gt; </code></pre> <p>Add a new role intercept rule for the <strong>/authenticate</strong> URL, so only users who need more authentication can access that page.</p> <pre><code>&lt;security:intercept-url pattern="/authenticate/**" access="hasRole('ROLE_NEEDS_EMAIL_AUTH')" /&gt; &lt;security:intercept-url pattern="/authorized_user_url/**" access="hasRole('ROLE_AUTHORIZED_USER')" /&gt; </code></pre>
56,191,415
Why is `git push --force-with-lease` failing with "rejected ... stale info" even when my local repo is up to date with remote?
<p>I'm trying to force push a rebase of a feature branch to a remote repository. To be a bit safer, I'm trying to use <code>--force-with-lease</code> to make sure no other changes have happened in the branch since I last fetched it.</p> <p>This is failing for reasons I don't understand:</p> <pre><code>$ git branch * my-branch master $ git push --force-with-lease origin my-branch -u To gitlab.com:example/my-project.git ! [rejected] my-branch -&gt; my-branch (stale info) error: failed to push some refs to '[email protected]:example/my-project.git' </code></pre> <p>I tried a fetch to see if my local cache had somehow gotten out of sync:</p> <pre><code>$ git fetch $ git push --force-with-lease origin my-branch -u To gitlab.com:example/my-project.git ! [rejected] my-branch -&gt; my-branch (stale info) error: failed to push some refs to '[email protected]:example/my-project.git' </code></pre> <p>I tried simplifying the push command a bit:</p> <pre><code>$ git push --force-with-lease To gitlab.com:example/my-project.git ! [rejected] my-branch -&gt; my-branch (stale info) error: failed to push some refs to '[email protected]:example/my-project.git' </code></pre> <p>I tried limiting the check to my branch:</p> <pre><code>$ git push --force-with-lease=my-branch:origin/my-branch To gitlab.com:example/my-project.git ! [rejected] my-branch -&gt; my-branch (stale info) error: failed to push some refs to '[email protected]:example/my-project.git' </code></pre> <p>As you can see, it fails the same way every time.</p> <p>Why is my push failing, and how do I fix it?</p>
56,191,884
4
2
null
2019-05-17 17:57:36.467 UTC
null
2022-04-27 17:11:30.763 UTC
null
null
null
null
90,848
null
1
42
git|git-push
20,673
<p>In this case it turned out that the problem was that the remote branch had been deleted, but there was still a copy of it in my local repo. Fetch doesn't delete local copies by default, which is why it had no effect.</p> <p>Adding the <code>--prune</code> option to my initial <code>git pull</code> (before doing my rebase) corrects this problem.</p>
24,068,866
Perform POST request in Swift
<p>I am trying to do something like this:</p> <pre><code>NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; request.HTTPMethod = @"POST"; NSString *stringData = @"some data"; NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = requestBodyData; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; </code></pre> <p>This is what I have so far:</p> <pre><code>var url = NSURL(string: "some url") var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" var dataString = "some data" var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData request.HTTPBody = requestBodyData var connection = NSURLConnection(request: request, delegate: self, startImmediately: false) println("sending request...") connection.start() </code></pre> <p>However, the var requestBodyData: line throws the first stone with "Cannot convert the expression's type NSData to type NSData"</p> <p>Anyone care to weigh in?</p>
24,068,960
2
0
null
2014-06-05 19:40:59.19 UTC
9
2016-06-22 08:19:38.67 UTC
2014-06-05 20:47:22.703 UTC
null
1,226,963
null
3,111,379
null
1
16
ios|post|nsurlconnection|swift
23,244
<p><code>stringByAddingPercentEscapesUsingEncoding</code> returns a string instead of an NSData object. According to <a href="https://stackoverflow.com/questions/24039868/creating-nsdata-from-nsstring-in-swift">this</a> answer, you need to use this to convert to an NSData instance:</p> <pre><code>let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding) </code></pre>
42,632,767
CSS Animation - Grow from center (Zoom from center dot to full container)
<p>I'm working on a game and I want to animate some boxes.</p> <p>I want a box to start from small and then grow outwards, with all edges growing at the same time in an effect that looks like it is growing outwards from the center.</p> <p>The best animation I have so far is the following: it grows the height and the width of the box as I want, but starts from the left and top. I would like it to start from a center point.</p> <p>I looked at the animation properties on W3 and nothing seems to fit the boat.</p> <pre><code> .box_2_gen{ animation-duration: 0.25s; animation-name: createBox; position: relative; background: #FFEDAD; border: black solid; border-width: 1px; border-radius: 15px; width: 98px; height: 98px; margin: 10px; float: left; } @keyframes createBox{ from{ height:0px; width: 0px; } to{ height: 98px; width: 98px; } } </code></pre> <p>EDIT: My question may seem like another similar one, but I just wanted to know how to do it using only keyframes.</p> <p>Thanks,</p>
42,632,850
2
2
null
2017-03-06 18:17:08.01 UTC
10
2022-02-09 04:34:45.473 UTC
2022-02-09 04:34:45.473 UTC
null
5,161,626
null
5,161,626
null
1
25
css|animation|css-transforms
64,274
<p>You should use <code>transform</code> in the animation for better performance and more control. Then you won't have to repeat the static <code>px</code> values, and you can use <code>transform-origin</code> to control where the transform happens. <code>scale()</code> will scale from the center by default. </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>div { background: red; animation: createBox .25s; width: 98px; height: 98px; } @keyframes createBox { from { transform: scale(0); } to { transform: scale(1); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
36,182,743
How to prevent a flex box from growing with content
<p>In the code and jsfiddle below, flexbox proportions changes with content. I am feeling I do not understand the real purpose of flexbox here. If we are giving <code>flex-grow</code> properties for the proportions we desire, why do the boxes grow with content?</p> <p>Notice when <code>dataDiv</code> has new span content in it, proportions are broken with the content. You can observe how it is the expected proportions when you delete the <code>span</code> inside <code>dataDiv</code>. Why does this occur?</p> <p><a href="https://jsfiddle.net/4shaz5oy/" rel="noreferrer">https://jsfiddle.net/4shaz5oy/</a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: flex; flex-flow: row wrap; height: 100vh; } .mapBox { flex: 2; background-color: red; } .controlBox { flex: 1; display: flex; flex-direction: column; background-color: green; } .controlPanel { flex: 1; max-height: 33%; background-color: yellow; padding: 5px; text-align: center; } .dataPanel { flex: 2; max-height: 66%; background-color: blue; padding: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="mapBox"&gt;&lt;/div&gt; &lt;div class="controlBox"&gt; &lt;div class="controlPanel"&gt; &lt;div class="buttonDiv"&gt;&lt;/div&gt; &lt;div class="buttonDiv"&gt;&lt;/div&gt; &lt;div class="buttonDiv"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="dataPanel"&gt; &lt;div class="dataDiv"&gt; &lt;span&gt;yoyoyoyasdasdadsadasdasdasdasdasdasdasdadada&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
36,182,821
2
1
null
2016-03-23 15:48:15.693 UTC
8
2018-09-20 20:51:17.54 UTC
2018-09-20 20:51:17.54 UTC
null
2,827,823
null
1,407,527
null
1
22
html|css|flexbox
67,542
<p>The <code>flex-grow</code> defines how the remaining space should be distributed amongst the flex items, not the items themselves.</p> <p>For their size you use <code>flex-basis</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { margin: 0; } .container { display: flex; flex-flow: row wrap; height: 100vh; } .mapBox { flex: 2; flex-basis: 66%; background-color: red; } .controlBox { flex: 1; flex-basis: 33%; display: flex; flex-direction:column; background-color:green; } .controlPanel { flex: 1; max-height: 33%; background-color: yellow; padding: 5px; text-align: center; } .dataPanel { flex: 2; max-height: 66%; background-color: blue; padding: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="mapBox"&gt; &lt;/div&gt; &lt;div class="controlBox"&gt; &lt;div class="controlPanel"&gt; &lt;div class="buttonDiv"&gt; &lt;/div&gt; &lt;div class="buttonDiv"&gt; &lt;/div&gt; &lt;div class="buttonDiv"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="dataPanel"&gt; &lt;div class="dataDiv"&gt; &lt;span&gt;yoyoyoy as da sd ad sa da sd as da sd as da sd as da sd ad ada&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>Based on comments, here is a simplified sample of how to keep size</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body{ margin: 0; } .flex, .left, .right { display: flex; } .left, .right { flex: 1; flex-direction: column; } .left { background: red; flex-basis: 66.66%; } .right { flex-basis: 33.33%; } .item1 { background: yellow; overflow: auto; height: 33.33vh; } .item2 { background: lightblue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex"&gt; &lt;div class="left"&gt; Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 Bla 0 &lt;br&gt; Bla 0&lt;br&gt; Bla 0&lt;br&gt; Bla 0&lt;br&gt; Bla 0&lt;br&gt; &lt;/div&gt; &lt;div class="right"&gt; &lt;div class="item1"&gt; Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 Bla 1 &lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; Bla 1&lt;br&gt; &lt;/div&gt; &lt;div class="item2"&gt; Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 Bla 2 &lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; Bla 2&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
5,685,471
Error: Jump to case label in switch statement
<p>I wrote a program which involves use of switch statements, however on compilation it shows:</p> <blockquote> <p>Error: Jump to case label.</p> </blockquote> <p>Why does it do that?</p> <pre><code>#include &lt;iostream&gt; int main() { int choice; std::cin &gt;&gt; choice; switch(choice) { case 1: int i=0; break; case 2: // error here } } </code></pre>
5,685,578
4
2
null
2011-04-16 09:05:21.703 UTC
63
2021-10-03 21:27:55.263 UTC
2021-10-03 21:27:55.263 UTC
null
8,372,853
null
646,248
null
1
303
c++|switch-statement
396,232
<p>The problem is that variables declared in one <code>case</code> are still visible in the subsequent <code>case</code>s unless an explicit <code>{ }</code> block is used, <em>but they will not be initialized</em> because the initialization code belongs to another <code>case</code>.</p> <p>In the following code, if <code>foo</code> equals 1, everything is ok, but if it equals 2, we'll accidentally use the <code>i</code> variable which does exist but probably contains garbage.</p> <pre><code>switch(foo) { case 1: int i = 42; // i exists all the way to the end of the switch dostuff(i); break; case 2: dostuff(i*2); // i is *also* in scope here, but is not initialized! } </code></pre> <p>Wrapping the case in an explicit block solves the problem:</p> <pre><code>switch(foo) { case 1: { int i = 42; // i only exists within the { } dostuff(i); break; } case 2: dostuff(123); // Now you cannot use i accidentally } </code></pre> <h2>Edit</h2> <p>To further elaborate, <code>switch</code> statements are just a particularly fancy kind of a <code>goto</code>. Here's an analoguous piece of code exhibiting the same issue but using a <code>goto</code> instead of a <code>switch</code>:</p> <pre><code>int main() { if(rand() % 2) // Toss a coin goto end; int i = 42; end: // We either skipped the declaration of i or not, // but either way the variable i exists here, because // variable scopes are resolved at compile time. // Whether the *initialization* code was run, though, // depends on whether rand returned 0 or 1. std::cout &lt;&lt; i; } </code></pre>
6,151,417
Complete reconstruction of TCP Session (HTML pages) from WireShark pcaps, any tools for this?
<p>I wonder if there is a way in wireshark to reconstruct a complete TCP Session (HTML page(s)) if we have wireshark pcaps, can wireshark do the reconstruction? or is there any tool around that can do the reconstruction? Data streamed from a source could be compressed(Gzip) or uncompressed and the end result of reconstruction should be a valid complete HTML page with all of its contents.</p>
12,186,996
5
7
null
2011-05-27 11:12:15.857 UTC
9
2015-06-13 13:19:03.01 UTC
2012-03-22 11:14:26.88 UTC
user349026
null
user349026
null
null
1
11
html|wireshark|pcap
31,153
<p>Use <a href="http://justniffer.sourceforge.net/#!/justniffer_grab_http_traffic" rel="nofollow">justniffer-grab-http-traffic</a> .It is based on justniffer and it is an excellent tool for rebuilding tcp streams.</p>
1,686,157
C# constructor in interface
<p>I know that you can't have a constructor in an interface, but here is what I want to do:</p> <pre><code> interface ISomething { void FillWithDataRow(DataRow) } class FooClass&lt;T&gt; where T : ISomething , new() { void BarMethod(DataRow row) { T t = new T() t.FillWithDataRow(row); } } </code></pre> <p>I would really like to replace <code>ISomething</code>'s <code>FillWithDataRow</code> method with a constructor somehow.</p> <p>That way, my member class could implement the interface and still be readonly (it can't with the <code>FillWithDataRow</code> method).</p> <p>Does anyone have a pattern that will do what I want?</p>
1,686,189
2
3
null
2009-11-06 08:17:10.653 UTC
1
2022-08-25 14:46:34.18 UTC
2017-10-26 13:23:13.117 UTC
null
5,894,241
null
111,992
null
1
9
c#|interface|generics
44,792
<p>(I should have checked first, but I'm tired - this is mostly a <a href="https://stackoverflow.com/questions/1682310">duplicate</a>.)</p> <p>Either have a factory interface, or pass a <code>Func&lt;DataRow, T&gt;</code> into your constructor. (They're mostly equivalent, really. The interface is probably better for Dependency Injection whereas the delegate is less fussy.)</p> <p>For example:</p> <pre><code>interface ISomething { // Normal stuff - I assume you still need the interface } class Something : ISomething { internal Something(DataRow row) { // ... } } class FooClass&lt;T&gt; where T : ISomething , new() { private readonly Func&lt;DataRow, T&gt; factory; internal FooClass(Func&lt;DataRow, T&gt; factory) { this.factory = factory; } void BarMethod(DataRow row) { T t = factory(row); } } ... FooClass&lt;Something&gt; x = new FooClass&lt;Something&gt;(row =&gt; new Something(row)); </code></pre>
1,379,455
showing percentage in .net console application
<p>I have a console app that performs a lengthy process.</p> <p>I am printing out the percent complete on a new line, <strong>for every 1% complete</strong>.</p> <p>How can I make the program print out the percent complete in the same location in the console window?</p>
1,379,461
2
2
null
2009-09-04 13:59:24.313 UTC
4
2009-09-04 14:21:24.693 UTC
null
null
null
null
64,334
null
1
33
c#|.net|console-application
22,858
<p>Print <code>\r</code> to get back to the start of the line (but don't print a newline!)</p> <p>For example:</p> <pre><code>using System; using System.Threading; class Test { static void Main() { for (int i=0; i &lt;= 100; i++) { Console.Write("\r{0}%", i); Thread.Sleep(50); } } } </code></pre>
1,881,905
Call function with array of arguments
<p>Can I call a function with array of arguments in a convenient way in JavaScript?</p> <p>Example:</p> <pre><code>var fn = function() { console.log(arguments); } var args = [1,2,3]; fn(args); </code></pre> <p>I need <code>arguments</code> to be <code>[1,2,3]</code>, just like my array.</p>
1,881,925
2
0
null
2009-12-10 15:49:38.453 UTC
9
2022-03-30 12:08:15.77 UTC
2016-01-24 16:24:28.3 UTC
null
3,853,934
null
210,578
null
1
41
javascript|arrays|arguments
33,688
<p>Since the introduction of ES6, you can sue the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer"><em>spread syntax</em></a> in the function call:</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>const args = [1,2,3]; fn(...args); function fn() { console.log(arguments); }</code></pre> </div> </div> </p> <p>Before ES6, you needed to use <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Function:apply" rel="noreferrer"><code>apply</code></a>.</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 args = [1,2,3]; fn.apply(null, args); function fn() { console.log(arguments); }</code></pre> </div> </div> </p> <p>Both will produce the equivalent function call:</p> <pre><code>fn(1,2,3); </code></pre> <p>Notice that I used <code>null</code> as the first argument of the <code>apply</code> example, which will set the <code>this</code> keyword to the global object (<code>window</code>) inside <code>fn</code> or <code>undefined</code> under strict mode.</p> <p>Also, you should know that the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments" rel="noreferrer"><code>arguments</code></a> object is not an array, it's an array-like object, that contains numeric indexes corresponding to the arguments that were used to call your function, a <code>length</code> property that gives you the number of arguments used.</p> <p>In ES6, if you want to access a variable number of arguments as an array, you can also use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters" rel="noreferrer"><em>rest syntax</em></a> in the function parameter list:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function fn(...args) { args.forEach(arg =&gt; console.log(arg)) } fn(1,2,3)</code></pre> </div> </div> </p> <p>Before ES6, if you wanted to make an array from your <code>arguments</code> object, you commonly used the <code>Array.prototype.slice</code> method.</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>function fn() { var args = Array.prototype.slice.call(arguments); console.log(args); } fn(1,2,3);</code></pre> </div> </div> </p> <p><strong>Edit:</strong> In response to your comment, yes, you could use the <code>shift</code> method and set its returned value as the context (the <code>this</code> keyword) on your function:</p> <pre><code>fn.apply(args.shift(), args); </code></pre> <p>But remember that <code>shift</code> will remove the first element from the original array, and your function will be called without that first argument.</p> <p>If you still need to call your function with all your other arguments, you can:</p> <pre><code>fn.apply(args[0], args); </code></pre> <p>And if you don't want to change the context, you could extract the first argument inside your function:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function fn(firstArg, ...args) { console.log(args, firstArg); } fn(1, 2, 3, 4)</code></pre> </div> </div> </p> <p>In ES5, that would be a little more verbose.</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>function fn() { var args = Array.prototype.slice.call(arguments), firstArg = args.shift(); console.log(args, firstArg); } fn(1, 2, 3, 4);</code></pre> </div> </div> </p>
53,681,522
Share variable in multi-stage Dockerfile: ARG before FROM not substituted
<p>I'm writing a multi-stage Dockerfile for the <a href="https://www.mcs.anl.gov/research/projects/darshan/" rel="noreferrer">darshan utils</a>:</p> <pre><code>ARG DARSHAN_VER=3.1.6 FROM fedora:29 as build RUN dnf install -y \ gcc \ make \ bzip2 bzip2-devel zlib zlib-devel RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" \ &amp;&amp; tar ... FROM fedora:29 COPY --from=build "/usr/local/darshan-${DARSHAN_VER}" "/usr/local/darshan-${DARSHAN_VER}" ... </code></pre> <p>I build it with <code>docker build -t darshan-util:3.6.1 .</code> and the error I get is:</p> <pre><code>Step 5/10 : RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" &amp;&amp; tar ... ---&gt; Running in 9943cce1669c % Total % Received % Xferd Average Speed Time Time Time Current ... curl: (78) RETR response: 550 The command '/bin/sh -c curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" &amp;&amp; tar ...' returned a non-zero code: 78 </code></pre> <p>I'd like to reuse the same ARG in both stages, so that I can define a default build variable just once. If I duplicate ARG in both stages, just below the two FROMs, it builds correctly.</p> <p>What is the correct way to define a "global" multi-stage ARG variable with a default?</p>
53,682,110
2
2
null
2018-12-08 10:19:27.39 UTC
10
2021-04-16 21:53:37.79 UTC
2021-04-16 21:53:37.79 UTC
null
5,810,105
null
5,810,105
null
1
88
docker|dockerfile|docker-multi-stage-build
28,167
<p>ARGs only last for the build phase of a single image. For the multistage, renew the ARG by simply stating:</p> <pre><code>ARG DARSHAN_VER </code></pre> <p>after your FROM instructions.</p> <p>cf. <a href="https://docs.docker.com/engine/reference/builder/#arg" rel="noreferrer">https://docs.docker.com/engine/reference/builder/#arg</a></p> <pre><code>ARG DARSHAN_VER=3.1.6 FROM fedora:29 as build ARG DARSHAN_VER RUN dnf install -y \ gcc \ make \ bzip2 bzip2-devel zlib zlib-devel RUN curl -O "ftp://ftp.mcs.anl.gov/pub/darshan/releases/darshan-${DARSHAN_VER}.tar.gz" \ &amp;&amp; tar ... FROM fedora:29 ARG DARSHAN_VER COPY --from=build "/usr/local/darshan-${DARSHAN_VER}" "/usr/local/darshan-${DARSHAN_VER}" ... </code></pre>
28,991,835
Firefox: navigator.getUserMedia is not a function
<p>I'm playing with browser and audio.</p> <p>I'm doing this</p> <pre><code> var session = { audio: true, video: false }; var recordRTC = null; navigator.getUserMedia(session, initializeRecorder, onError); </code></pre> <p>But, using latest FF available I got a javascript error, saying that</p> <blockquote> <p>navigator.getUserMedia is not a function</p> </blockquote> <p>I copied this code from this blog post: <a href="https://blog.groupbuddies.com/posts/39-tutorial-html-audio-capture-streaming-to-nodejs-no-browser-extensions" rel="noreferrer">https://blog.groupbuddies.com/posts/39-tutorial-html-audio-capture-streaming-to-nodejs-no-browser-extensions</a></p> <p>And similar on latest Chrome:</p> <blockquote> <p>Uncaught TypeError: undefined is not a function</p> </blockquote> <p>But I know that this api is supported from both browser</p> <p>What am I doing wrong?</p>
57,086,999
5
2
null
2015-03-11 16:14:08.66 UTC
3
2021-09-27 13:47:25.653 UTC
null
null
null
null
1,055,279
null
1
18
javascript|firefox|html5-audio
45,168
<p>Navigator.getUserMedia() is deprecated, advised to use MediaDevices.getUserMedia() </p> <pre><code>async function getMedia(pc) { let stream = null; try { stream = await navigator.mediaDevices.getUserMedia(constraints); /* use the stream */ } catch(err) { /* handle the error */ } } </code></pre>
6,029,804
What does a lock statement do under the hood?
<p>I see that for using objects which are not thread safe we wrap the code with a lock like this:</p> <pre><code>private static readonly Object obj = new Object(); lock (obj) { // thread unsafe code } </code></pre> <p>So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?</p> <p>What is the performance impact because of using locks?</p>
6,029,829
9
1
null
2011-05-17 10:55:13.383 UTC
133
2022-05-08 05:47:56.243 UTC
2021-03-08 03:33:26.423 UTC
null
3,739,391
null
250,524
null
1
625
c#|.net|synchronization|locking|thread-safety
403,105
<p>The <code>lock</code> statement is translated by C# 3.0 to the following:</p> <pre><code>var temp = obj; Monitor.Enter(temp); try { // body } finally { Monitor.Exit(temp); } </code></pre> <p>In C# 4.0 <a href="https://ericlippert.com/2009/03/06/locks-and-exceptions-do-not-mix/" rel="noreferrer">this has changed</a> and it is now generated as follows:</p> <pre><code>bool lockWasTaken = false; var temp = obj; try { Monitor.Enter(temp, ref lockWasTaken); // body } finally { if (lockWasTaken) { Monitor.Exit(temp); } } </code></pre> <p>You can find more info about what <code>Monitor.Enter</code> does <a href="https://docs.microsoft.com/dotnet/api/system.threading.monitor.enter#System_Threading_Monitor_Enter_System_Object_" rel="noreferrer">here</a>. To quote MSDN:</p> <blockquote> <p>Use <code>Enter</code> to acquire the Monitor on the object passed as the parameter. If another thread has executed an <code>Enter</code> on the object but has not yet executed the corresponding <code>Exit</code>, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke <code>Enter</code> more than once without it blocking; however, an equal number of <code>Exit</code> calls must be invoked before other threads waiting on the object will unblock.</p> </blockquote> <p>The <code>Monitor.Enter</code> method will wait infinitely; it will <em>not</em> time out.</p>
5,608,222
How to apply box-shadow on all four sides?
<p>I'm trying to apply a <code>box-shadow</code> on all four sides. I could only get it on 2 sides:</p> <p><img src="https://i.stack.imgur.com/X83rz.png" alt=""> </p>
5,608,237
14
1
null
2011-04-09 22:01:30.85 UTC
18
2022-04-07 11:07:02.247 UTC
2017-02-24 14:14:00.56 UTC
null
6,887,672
null
629,305
null
1
109
css|box-shadow
243,666
<p>It's because of x and y offset. Try this:</p> <pre><code>-webkit-box-shadow: 0 0 10px #fff; box-shadow: 0 0 10px #fff; </code></pre> <p>edit (year later..): Made the answer more cross-browser, as requested in comments :)</p> <p>btw: there are many css3 generator nowadays.. <a href="http://www.css3.me/">css3.me</a>, <a href="http://www.css3maker.com/box-shadow.html">css3maker</a>, <a href="http://css3generator.com/">css3generator</a> etc...</p>
46,284,405
How can I use ESLint no-unused-vars for a block of code?
<p>I need to disable some variable checks in <code>ESLint</code>.</p> <p>Currently, I am using this code, but am not getting the desired result:</p> <pre class="lang-js prettyprint-override"><code>/* eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "Hey" }] */ export type Hey = { a: string, b: object } </code></pre> <p>Two questions:</p> <ul> <li>Is there a variant which can enable <code>no-unused-vars</code> for a block of code?</li> </ul> <p>Something like...</p> <pre class="lang-js prettyprint-override"><code>/* eslint rule disable"*/ // I want to place my block of code, here /* eslint rule disable"*/ </code></pre> <ul> <li>Or could I make <code>Hey</code> a global variable so that it can be ignored everywhere?</li> </ul>
46,284,508
7
2
null
2017-09-18 16:45:25.71 UTC
7
2022-08-30 10:23:34.197 UTC
2020-03-16 15:49:56.78 UTC
null
10,312,071
null
6,426,229
null
1
68
javascript|eslint
66,830
<p>To disable the <code>@typescript-eslint/no-unused-vars</code> warning:</p> <ul> <li><h5>For the current line:</h5> </li> </ul> <pre><code>const unusedVar = 1; // eslint-disable-line @typescript-eslint/no-unused-vars </code></pre> <ul> <li><h5>For the next line:</h5> </li> </ul> <pre><code>// eslint-disable-next-line @typescript-eslint/no-unused-vars const unusedVar = 1; </code></pre> <ul> <li><h5>For a block:</h5> </li> </ul> <pre class="lang-js prettyprint-override"><code>/* eslint-disable @typescript-eslint/no-unused-vars */ const unusedVar1 = 1; const unusedVar2 = 2; /* eslint-enable @typescript-eslint/no-unused-vars */ </code></pre> <h1>Original answer</h1> <p>Just use pair of lines:</p> <pre><code>/* eslint-disable no-unused-vars */ // ... your code here with unused vars... /* eslint-enable no-unused-vars */ </code></pre>
5,095,077
Ruby convert array to nested hash
<p>I have the following:</p> <pre><code>value = 42 array = ["this","is","a","test"] </code></pre> <p>how can I convert that to get this</p> <pre><code>{ "this" =&gt; { "is" =&gt; { "a" =&gt; { "test" =&gt; 42 } } } } </code></pre> <p>the array is always flat. </p> <p>Thank you!</p>
5,095,149
1
3
null
2011-02-23 18:10:18.717 UTC
18
2021-05-06 20:17:16.09 UTC
null
null
null
null
63,383
null
1
30
ruby
7,154
<p>Try this:</p> <pre class="lang-rb prettyprint-override"><code>array.reverse.inject(value) { |assigned_value, key| { key =&gt; assigned_value } } #=&gt; {&quot;this&quot;=&gt;{&quot;is&quot;=&gt;{&quot;a&quot;=&gt;{&quot;test&quot;=&gt;42}}}} </code></pre>
44,638,867
VBA + Excel + Try Catch
<p>In VBA, I'm doing a simple script that records a version of a spreadsheet being used.</p> <pre><code>Private Sub Workbook_Open() version = "1.0" Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") URL = "&lt;WEB SERVICE&gt;" objHTTP.Open "POST", URL, False objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded" objHTTP.send ("version=" + version) End Sub </code></pre> <p>The process works fine, but...</p> <p>I'm trying to do a try catch so if the web host is offline, instead of showing a run time error I catch it and suppress.</p> <p>What is the best way to try catch in VBA so there is no error message shown?</p>
44,638,899
2
1
null
2017-06-19 19:55:39.983 UTC
5
2019-12-20 14:52:46.713 UTC
2019-12-20 14:52:46.713 UTC
null
7,478,530
null
6,859,373
null
1
36
excel|vba
131,689
<pre><code>Private Sub Workbook_Open() on error goto Oops version = "1.0" Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") URL = "&lt;WEB SERVICE&gt;" objHTTP.Open "POST", URL, False objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded" objHTTP.send ("version=" + version) exit sub Oops: 'handle error here End Sub </code></pre> <p>If you wanted to, for example, change the URL because of the error, you can do this</p> <pre><code>Private Sub Workbook_Open() on error goto Oops version = "1.0" Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") URL = "&lt;WEB SERVICE&gt;" Send: objHTTP.Open "POST", URL, False objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded" objHTTP.send ("version=" + version) exit sub Oops: 'handle error here URL="new URL" resume Send 'risk of endless loop if the new URL is also bad End Sub </code></pre> <p>Also, if your feeling really try/catchy, you can emulate that like this.</p> <pre><code>Private Sub Workbook_Open() version = "1.0" Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") URL = "&lt;WEB SERVICE&gt;" on error resume next 'be very careful with this, it ignores all errors objHTTP.Open "POST", URL, False objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded" objHTTP.send ("version=" + version) if err &lt;&gt; 0 then 'not 0 means it errored, handle it here err.clear 'keep in mind this doesn't reset the error handler, any code after this will still ignore errors end if End Sub </code></pre> <p>So extending this to be really hard core...</p> <pre><code>Private Sub Workbook_Open() version = "1.0" on error resume next Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1") if err &lt;&gt; 0 then 'unable to create object, give up err.clear exit sub end if URL = "&lt;WEB SERVICE&gt;" objHTTP.Open "POST", URL, False if err &lt;&gt; 0 then 'unable to open request, give up err.clear exit sub end if objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded" objHTTP.send ("version=" + version) if err &lt;&gt; 0 then 'unable to send request, give up err.clear exit sub end if End Sub </code></pre> <p>Also worth noting that any errors that happen in an <code>on error goto</code> style will not be handled, so if you did this</p> <pre><code>private sub MakeError() dim iTemp as integer on error goto Oops iTemp = 5 / 0 'divide by 0 error exit sub Oops: itemp = 4 / 0 'unhandled exception, divide by 0 error end sub </code></pre> <p>Will cause an unhandled exception, however</p> <pre><code>private sub MakeError() dim iTemp as integer on error resume next iTemp = 5 / 0 'divide by 0 error if err &lt;&gt; 0 then err.clear iTemp = 4 / 0 'divide by 0 error, but still ignored if err &lt;&gt; 0 then 'another error end if end if end sub </code></pre> <p>Will not cause any exceptions, since VBA ignored them all.</p>
51,160,076
Spring 5 WebFlux Mono and Flux
<p>In Spring 5 I just know Spring WebFlux Handler method handles the request and returns <strong>Mono</strong> or <strong>Flux</strong> as response.</p> <pre><code>@Component public class HelloWorldHandler { public Mono&lt;ServerResponse&gt; helloWorld(ServerRequest request) { return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromObject("Hello World")); } } </code></pre> <p>But I have no idea what means <strong>Mono</strong> and <strong>Flux</strong> and how it works with the WebFlux Handler.</p> <p>Can any one simply explain</p> <p>1.What means <strong>Mono</strong> and <strong>Flux</strong>.</p> <p>2.How it works with the <strong>WebFlux Handler</strong>.</p> <p>Thanks in advance.</p>
51,167,661
1
2
null
2018-07-03 17:28:02.907 UTC
13
2018-07-04 07:55:52.427 UTC
null
null
null
null
5,267,773
null
1
21
spring|spring-boot|java-8|spring-webflux
14,947
<p>Webflux is all about reactive programming, which in summary means that business logic is only executed as soon as the data to process it is available (reactive).</p> <p>This means you no longer can return simple POJO's, but you have to return something else, something that can provide the result when it's available. Within the <a href="http://www.reactive-streams.org/" rel="noreferrer">reactive streams</a> initiative, this is called a <a href="http://www.reactive-streams.org/reactive-streams-1.0.2-javadoc/org/reactivestreams/Publisher.html" rel="noreferrer"><code>Publisher</code></a>. A <code>Publisher</code> has a <code>subcribe()</code> method that will allow the consumer to get the POJO when it's available.</p> <p>A <code>Publisher</code> (for example <code>Publisher&lt;Foo&gt;</code>) can return zero or multiple, possibly infinite, results. To make it more clear how many results you can expect, <a href="http://projectreactor.io/" rel="noreferrer">Project Reactor</a> (the reactive streams implementation of Pivotal) introduced two implementations of <code>Publisher</code>:</p> <ul> <li>A <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html" rel="noreferrer"><code>Mono</code></a>, which will complete after emitting a single result. </li> <li>A <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html" rel="noreferrer"><code>Flux</code></a>, which will emit zero or multiple, possibly infinite, results and then completes.</li> </ul> <p>So, basically you can see <code>Mono&lt;Foo&gt;</code> as the reactive counterpart of returning <code>Foo</code> and <code>Flux&lt;Foo&gt;</code> as the reactive counterpart of <code>Collection&lt;Foo&gt;</code>.</p> <p>For example:</p> <pre class="lang-java prettyprint-override"><code>Flux .just(1, 2, 3, 4) .map(nr -&gt; nr * 2) .subscribe(System.out::println); </code></pre> <p>Even though the numbers are already available (you can see them), you should realize that since it's a <code>Flux</code>, they're emitted one by one. In other cases, the numbers might come from an external API and in that case they won't be immediately available. The next phase (the <code>map</code> operator), will multiply the number as soon as it retrieves one, this means that it also does this mapping one by one and then emit the new value.</p> <p>Eventually, there's a subscriber (there should always be one, but it could be the Spring framework itself that's subscribing), and in this case it will print each value it obtains and print it to the console, also, one by one.</p> <p>You should also realize that there's no particular order when processing these items. It could be that the first number has already been printed on the console, while the third item is hasn't been multiplied by two yet.</p> <p>So, in your case, you have a <code>Mono&lt;ServerResponse&gt;</code>, which means that as soon as the <code>ServerResponse</code> is available, the WebFlux framework can utilize it. Since there is only one <code>ServerResponse</code> expected, it's a <code>Mono</code> and not a <code>Flux</code>.</p>
32,758,000
java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
<p>I am trying to write a standalone executable jar (fat jar) . I am using spring boot gradle plugin and writing a SpringBoot App to do this. </p> <p>Here is my Application.java file</p> <pre><code>@Configuration @EnableAutoConfiguration @EnableRabbit @EntityScan("persistence.domain") @EnableJpaRepositories("persistence.repository") @ComponentScan(basePackages = {"common","service"}) public class Application { public static void main(final String[] args) { final SpringApplicationBuilder appBuilder = new SpringApplicationBuilder( Application.class); appBuilder.profiles("common", "common_db").run(args); } @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } } </code></pre> <p>I have specified properties in yml files. For ex application-common etc . While running Application.java I am getting error :</p> <pre><code>[2015-09-24 14:40:22.304] boot - 32791 INFO [main] ---AnnotationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@51a282af: startup date [Thu Sep 24 14:40:22 IST 2015]; root of context hierarchy [2015-09-24 14:40:23.194] boot - 32791 WARN [main] --- AnnotationConfigEmbeddedWebApplicationContext: Exception encountered during context initialization - cancelling refresh attempt org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: ; nested exception is java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:392) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:165) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691) at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142) at storm.Application.main(Application.java:28) Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:58) at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:92) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:190) at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:435) at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:389) ... 12 more Caused by: java.lang.NullPointerException at org.springframework.boot.autoconfigure.condition.OnPropertyCondition.getMatchOutcome(OnPropertyCondition.java:61) at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:45) ... 16 more </code></pre> <p>Here is my build.gradle </p> <pre><code>def projects= [ ":common", ":persistence", ":adapter" ] buildscript { repositories { mavenCentral() maven { url 'http://repo.spring.io/snapshot' } maven { url 'http://repo.spring.io/milestone' } } dependencies { classpath group: 'org.springframework.boot', name: 'spring-boot-gradle-plugin', version: springBootVersion } </code></pre> <p>}</p> <pre><code>apply plugin: 'spring-boot' apply plugin: 'maven-publish' apply from: "${rootDir}/deployTasks.gradle" springBoot { mainClass = "storm.Application" } dependencies { compile project(':common') compile project(':adapter') compile project(':persistence') compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.1.8.RELEASE' compile group : 'org.springframework.boot',name: 'spring-boot-autoconfigure', version : '1.1.8.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.1.8.RELEASE' </code></pre> <p>}</p> <p>Database specification as in application-common_db.yml</p> <pre><code>database: host: localhost port: 3306 schema: subscriptions username: root password: root autoconnect: maxReconnects: 3 initialTimeout: 2 timeout: connectTimeout: 0 socketTimeout: 0 failover: host: localhost port: 3306 queriesBeforeRetryMaster: 50 secondsBeforeRetryMaster: 30 spring: datasource: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://${database.host}:${database.port},${database.failover.host}:${database.failover.port}/${database.schema}?${database.properties} username: ${database.username} password: ${database.password} continueOnError: true initialize: false initialSize: 0 timeBetweenEvictionRunsMillis: 5000 minEvictableIdleTimeMillis: 5000 removeAbandonedTimeout: 60 removeAbandoned: true minIdle: 0 </code></pre> <p>I am not sure how to resolve this error . Can nybody suggest what is going wrong here and why am i getting nullPointerException. </p> <p>Help is appreciated .</p> <p>Thanks</p>
32,761,482
5
1
null
2015-09-24 09:33:21.673 UTC
5
2021-08-18 11:49:52.12 UTC
2018-02-14 14:53:19.647 UTC
null
7,162,168
null
2,156,718
null
1
24
spring|gradle|spring-boot|build.gradle
188,557
<p><strong>This is caused by non-matching Spring Boot dependencies.</strong> Check your classpath to find the offending resources. You have explicitly included version <em>1.1.8.RELEASE</em>, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.</p>
9,224,927
How to set EditText box height and width programmatically in Android
<p>I want to manage the height and width of an <code>EditText</code> box programmatically in Android. I tried <code>edittext.setWidth(32);</code> and <code>edittext.setEms(50);</code>, but both are not working. See my below code, as I am using it to create dynamic <code>EditText</code>s in Android.</p> <pre><code>private EditText createEditText() { final LayoutParams lparams = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); final EditText edittext = new EditText(this); edittext.setLayoutParams(lparams); edittext.setWidth(32); edittext.setEms(50); return edittext; } </code></pre>
9,225,177
6
0
null
2012-02-10 08:36:21.873 UTC
5
2019-01-19 06:04:47.15 UTC
2019-01-19 06:04:47.15 UTC
null
6,214,491
null
1,218,762
null
1
23
android|android-edittext
53,608
<pre><code>private EditText createEditText() { final LayoutParams lparams = new LayoutParams(50,30); // Width , height final EditText edittext = new EditText(this); edittext.setLayoutParams(lparams); return edittext; } </code></pre> <p>Try this.</p>
9,104,268
Can't convert value type array to params object[]
<p>If C# can cast an int to an object, why not an int[] to an object[]?</p> <h2>Simple Program Example:</h2> <pre><code>void Main() { var a = new String[]{"0", "1"}; var b = new int[]{0, 1}; AssertMoreThan1(a); // No Exception AssertMoreThan1(b); // Exception } static void AssertMoreThan1(params object[] v){ if(v.Length == 1){ throw new Exception("Too Few Parameters"); } } </code></pre>
9,104,534
2
0
null
2012-02-01 22:22:46.893 UTC
13
2012-02-02 16:35:50.497 UTC
null
null
null
null
227,436
null
1
26
c#|.net
11,175
<blockquote> <p>If C# can cast an int to an object, why not an int[] to an object[]?</p> </blockquote> <p>Your question could be also stated as "what are the <em>covariance</em> rules for array conversions in C#?"</p> <p>They are a bit tricky, and broken in several interesting and unfortunate ways.</p> <p>First off, we should clearly state what we mean by "covariance". Covariance is the property that a <em>mapping</em> preserves a <em>relationship</em>. The mapping here is "T goes to array of T". The <em>relationship</em> is "can be implicitly converted". For example:</p> <p><code>Giraffe</code> can be implicitly converted to <code>Mammal</code>. </p> <p>That's a relationship between two types. Now apply the mapping to both sides of the relationship:</p> <p><code>Giraffe[]</code> can be converted to <code>Mammal[]</code>. </p> <p>If the truth of the first statement always entails the truth of the second statement -- that is, if the mapping <em>preserves</em> the truth of the relationship -- then the mapping is said to be "covariant". </p> <p>As a shorthand, instead of saying "the mapping from T to array of T is a covariant mapping over the implicit conversion relation", we just say "arrays are covariant" and hope that the rest of that is understood from context.</p> <p>OK, now that we have the definition down: Arrays <em>with reference type elements</em> are covariant in C#. Tragically, this is broken covariance:</p> <pre><code>class Mammal {} class Giraffe : Mammal {} class Tiger : Mammal {} ... Mammal[] mammals = new Giraffe[1]; </code></pre> <p>This is perfectly legal because arrays of reference type elements are covariant in C#. But then this crashes at runtime:</p> <pre><code>mammals[0] = new Tiger(); </code></pre> <p>because mammals is <em>really an array of Giraffes</em>.</p> <p>This means that every time you <em>write</em> to an array whose elements are <em>unsealed reference types</em>, the runtime performs a type check <em>and might crash if the type check fails</em>.</p> <p>This is my candidate for "worst feature of C#", but it does in fact <em>work</em>.</p> <p>Your question is "why does array covariance not work when the source array is an array of value type and the target array is an array of reference type?"</p> <p>Because <em>those two things have a different form at runtime</em>. Suppose you have a <code>byte[]</code> with ten elements. The actual storage reserved for the array elements is ten bytes long. Suppose you are on a 64 bit machine and you have an <code>object[]</code> with ten elements. The storage is eight times bigger!</p> <p>Clearly you cannot convert <em>via reference conversion</em> a reference to storage for ten bytes to storage for ten eight-byte references to bytes. The extra seventy bytes don't come out of nowhere; someone has to allocate them.</p> <p>Moreover: <em>who does the boxing</em>? If you have an array of ten objects and each object is a byte, each one of those bytes is <em>boxed</em>. But bytes in a byte array are not boxed. So when you do the conversion, who does the boxing?</p> <p>In general in C#, <em>covariant conversions always preserve representation</em>. The representation of a "reference to Animal" is exactly the same as the representation of "reference to Giraffe". But the representations of "int" and "reference to object" are completely different.</p> <p>One expects that casting one array type to another does not <em>allocate and copy a huge array</em>. But we cannot have <em>referential identity</em> between an array of ten bytes and an array of eighty bytes containing ten references, and therefore the entire thing is simply made illegal.</p> <p>Now, you might then say, well, what happens when the representations <em>are the same</em> for value types? In fact, this is illegal in C#:</p> <pre><code>int[] x = new uint[10]; </code></pre> <p>because in C# the rule is that only covariant array conversions involving only reference types are legal. But if you force it to be done by the runtime:</p> <pre><code>int[] x = (int[])(object) new uint[10]; </code></pre> <p>Then the runtime allows it because a four byte int and a four byte uint have the same representation.</p> <p>If you want to understand this better then you should probably read my entire series of articles on how covariance and contravariance works in C#:</p> <ul> <li><p><a href="http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/" rel="noreferrer">The whole series</a></p></li> <li><p><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx" rel="noreferrer">The specifics of unsafe reference-element array covariance</a></p></li> <li><p><a href="http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx" rel="noreferrer">More about value-element array covariance</a></p></li> </ul>
9,489,384
initializing a Guava ImmutableMap
<p>Guava offers a nice shortcut for initializing a map. However I get the following compiler error (Eclipse Indigo) when my map initializes to nine entries. </p> <p>The method <code>of(K, V, K, V, K, V, K, V, K, V)</code> in the type <code>ImmutableMap</code> is not applicable for the arguments <code>(String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String)</code></p> <pre><code>ImmutableMap&lt;String,String&gt; myMap = ImmutableMap.of( "key1", "value1", "key2", "value2", "key3", "value3", "key4", "value4", "key5", "value5", "key6", "value6", "key7", "value7", "key8", "value8", "key9", "value9" ); </code></pre> <p>The message appears to say that </p> <blockquote> <p>An ImmutableMap has a maximum size of four pairs of key,value.</p> </blockquote> <p>Obviously, this cannot be the case but I can't figure out what to do to increase the size of my initializer.</p> <p>Can someone tell me what is missing?</p>
9,489,463
3
0
null
2012-02-28 20:42:33.99 UTC
28
2021-10-27 15:03:42.357 UTC
2017-03-07 11:45:59.053 UTC
user1752532
null
null
903,724
null
1
167
java|dictionary|guava
132,626
<p>Notice that your error message only contains five <code>K, V</code> pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different <code>of()</code> methods, accepting between zero and five key-value pairings. There is not an <code>of(...)</code> overload accepting a varags parameter because <code>K</code> and <code>V</code> can be different types.</p> <p>You want an <code>ImmutableMap.Builder</code>:</p> <pre><code>ImmutableMap&lt;String,String&gt; myMap = ImmutableMap.&lt;String, String&gt;builder() .put("key1", "value1") .put("key2", "value2") .put("key3", "value3") .put("key4", "value4") .put("key5", "value5") .put("key6", "value6") .put("key7", "value7") .put("key8", "value8") .put("key9", "value9") .build(); </code></pre>
10,636,134
iOS FFT Accerelate.framework draw spectrum during playback
<p>UPDATE 2016-03-15</p> <h2>Please take a look at this project: <a href="https://github.com/ooper-shlab/aurioTouch2.0-Swift" rel="nofollow noreferrer">https://github.com/ooper-shlab/aurioTouch2.0-Swift</a>. It has been ported to Swift and contains every answer you're looking for, if you cam here.</h2> <hr> <p>I did a lot of research and learned a lot about FFT and the Accelerate Framework. But after days of experiments I'm kind of frustrated.</p> <p>I want to display the frequency spectrum of an audio file during playback in a diagram. For every time interval it should show the magnitude in db on the Y-axis (displayed by a red bar) for every frequency (in my case 512 values) calculated by a FFT on the X-Axis. </p> <p>The output should look like this: <img src="https://i.stack.imgur.com/mytPj.png" alt="enter image description here"></p> <p>I fill a buffer with 1024 samples extracting only the left channel for the beginning. Then I do all this FFT stuff.</p> <p>Here is my code so far:</p> <p>Setting up some variables</p> <pre><code>- (void)setupVars { maxSamples = 1024; log2n = log2f(maxSamples); n = 1 &lt;&lt; log2n; stride = 1; nOver2 = maxSamples/2; A.realp = (float *) malloc(nOver2 * sizeof(float)); A.imagp = (float *) malloc(nOver2 * sizeof(float)); memset(A.imagp, 0, nOver2 * sizeof(float)); obtainedReal = (float *) malloc(n * sizeof(float)); originalReal = (float *) malloc(n * sizeof(float)); setupReal = vDSP_create_fftsetup(log2n, FFT_RADIX2); } </code></pre> <p>Doing the FFT. FrequencyArray is just a data structure that holds 512 float values.</p> <pre><code>- (FrequencyArry)performFastFourierTransformForSampleData:(SInt16*)sampleData andSampleRate:(UInt16)sampleRate { NSLog(@"log2n %i n %i, nOver2 %i", log2n, n, nOver2); // n = 1024 // log2n 10 // nOver2 = 512 for (int i = 0; i &lt; n; i++) { originalReal[i] = (float) sampleData[i]; } vDSP_ctoz((COMPLEX *) originalReal, 2, &amp;A, 1, nOver2); vDSP_fft_zrip(setupReal, &amp;A, stride, log2n, FFT_FORWARD); float scale = (float) 1.0 / (2 * n); vDSP_vsmul(A.realp, 1, &amp;scale, A.realp, 1, nOver2); vDSP_vsmul(A.imagp, 1, &amp;scale, A.imagp, 1, nOver2); vDSP_ztoc(&amp;A, 1, (COMPLEX *) obtainedReal, 2, nOver2); FrequencyArry frequencyArray; for (int i = 0; i &lt; nOver2; i++) { frequencyArray.frequency[i] = log10f(obtainedReal[i]); // Magnitude in db??? } return frequencyArray; } </code></pre> <p>The output looks always kind of weird although it some how seems to move according to the music.</p> <p>I'm happy that I came so far thanks to some very good posts here like this: <a href="https://stackoverflow.com/questions/3398753/using-the-apple-fft-and-accelerate-framework">Using the apple FFT and accelerate Framework</a></p> <p>But now I don't know what to do. What am I missing?</p>
10,636,698
1
1
null
2012-05-17 12:55:11.1 UTC
16
2016-03-15 11:21:04.47 UTC
2017-05-23 12:01:20.547 UTC
null
-1
null
392,137
null
1
14
ios|fft|frequency|spectrum
7,312
<p>Firstly you're not applying a <a href="http://en.wikipedia.org/wiki/Window_function">window function</a> prior to the FFT - this will result in smearing of the spectrum due to <a href="http://en.wikipedia.org/wiki/Spectral_leakage">spectral leakage</a>.</p> <p>Secondly, you're just using the real component of the FFT output bins to calculate dB magnitude - you need to use the complex magnitude:</p> <pre><code>magnitude_dB = 10 * log10(re * re + im * im); </code></pre>
22,968,427
Check if string variable is null or empty, or full of white spaces
<p>How can I check if a string variable is null or empty, or full with space characters in Twig? (Shortest possible, maybe an equivalent to CSharp's <code>String.IsNullOrWhiteSpace()</code> method)</p>
22,981,532
4
1
null
2014-04-09 16:21:41.45 UTC
4
2021-11-29 15:53:46.2 UTC
2014-09-12 13:51:19.34 UTC
null
806,975
null
806,975
null
1
45
string|twig|isnullorempty
94,574
<p>There are already good answers, but I give my 2 cents too:</p> <pre><code>{% if foo|length %} </code></pre> <p>I was inspired by @GuillermoGutiérrez's filter trick.</p> <p>But I think <code>|length</code> is safer as the <code>"0"|trim</code> expression will evaluates to false.</p> <p>References :</p> <ul> <li><a href="http://twig.sensiolabs.org/doc/filters/length.html">length</a></li> <li><a href="http://codepad.org/XrjyBSCT">codepad</a></li> <li><a href="http://www.php.net/manual/en/function.boolval.php">boolval</a></li> </ul>
37,970,187
Elasticsearch cluster 'master_not_discovered_exception'
<p>i have installed elasticsearch 2.2.3 and configured in cluster of 2 nodes</p> <p>Node 1 (elasticsearch.yml)</p> <pre><code>cluster.name: my-cluster node.name: node1 bootstrap.mlockall: true discovery.zen.ping.unicast.hosts: ["ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com", "ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com"] discovery.zen.minimum_master_nodes: 1 discovery.zen.ping.multicast.enabled: false indices.fielddata.cache.size: "30%" indices.cache.filter.size: "30%" node.master: true node.data: true http.cors.enabled: true script.inline: false script.indexed: false network.bind_host: 0.0.0.0 </code></pre> <p>Node 2 (elasticsearch.yml)</p> <pre><code>cluster.name: my-cluster node.name: node2 bootstrap.mlockall: true discovery.zen.ping.unicast.hosts: ["ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com", "ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com"] discovery.zen.minimum_master_nodes: 1 discovery.zen.ping.multicast.enabled: false indices.fielddata.cache.size: "30%" indices.cache.filter.size: "30%" node.master: false node.data: true http.cors.enabled: true script.inline: false script.indexed: false network.bind_host: 0.0.0.0 </code></pre> <p>If i get <code>curl -XGET 'http://localhost:9200/_cluster/state?pretty'</code> i have:</p> <pre><code>{ "error" : { "root_cause" : [ { "type" : "master_not_discovered_exception", "reason" : null } ], "type" : "master_not_discovered_exception", "reason" : null }, "status" : 503 } </code></pre> <p>Into log of node 1 have:</p> <pre><code>[2016-06-22 13:33:56,167][INFO ][cluster.service ] [node1] new_master {node1}{Vwj4gI3STr6saeTxKkSqEw}{127.0.0.1}{127.0.0.1:9300}{master=true}, reason: zen-disco-join(elected_as_master, [0] joins received) [2016-06-22 13:33:56,210][INFO ][http ] [node1] publish_address {127.0.0.1:9200}, bound_addresses {[::]:9200} [2016-06-22 13:33:56,210][INFO ][node ] [node1] started [2016-06-22 13:33:56,221][INFO ][gateway ] [-node1] recovered [0] indices into cluster_state </code></pre> <p>Into log of node 2 instead:</p> <pre><code>[2016-06-22 13:34:38,419][INFO ][discovery.zen ] [node2] failed to send join request to master [{node1}{Vwj4gI3STr6saeTxKkSqEw}{127.0.0.1}{127.0.0.1:9300}{master=true}], reason [RemoteTransportException[[node2][127.0.0.1:9300][internal:discovery/zen/join]]; nested: IllegalStateException[Node [{node2}{_YUbBNx9RUuw854PKFe1CA}{127.0.0.1}{127.0.0.1:9300}{master=false}] not master for join request]; ] </code></pre> <p>Where the error?</p>
37,972,630
9
1
null
2016-06-22 13:54:28.61 UTC
4
2021-09-29 03:37:19.447 UTC
null
null
null
null
2,385,354
null
1
20
elasticsearch
80,481
<p>I resolved with this line:</p> <p><code>network.publish_host: ec2-xx-xx-xx-xx.eu-west-1.compute.amazonaws.com</code></p> <p>every <code>elasticsearch.yml</code> config file must have this line with your hostname</p>
36,927,169
(ML) Modules vs (Haskell) Type Classes
<p>According to Harper (<a href="https://existentialtype.wordpress.com/2011/04/16/modules-matter-most/" rel="noreferrer">https://existentialtype.wordpress.com/2011/04/16/modules-matter-most/</a>), it seems that Type Classes simply do not offer the same level of abstraction that Modules offer and I'm having a hard time exactly figuring out why. And there are no examples in that link, so it's hard for me to see the key differences. There are also other papers on how to translate between Modules and Type Classes (<a href="http://www.cse.unsw.edu.au/~chak/papers/modules-classes.pdf" rel="noreferrer">http://www.cse.unsw.edu.au/~chak/papers/modules-classes.pdf</a>), but this doesn't really have anything to do with the implementation in the programmer's perspective (it just says that there isn't something one can do that the other can't emulate).</p> <p>Specifically, in the <a href="https://existentialtype.wordpress.com/2011/04/16/modules-matter-most/" rel="noreferrer">first link</a>:</p> <blockquote> <p>The first is that they insist that a type can implement a type class in exactly one way. For example, according to the philosophy of type classes, the integers can be ordered in precisely one way (the usual ordering), but obviously there are many orderings (say, by divisibility) of interest. The second is that they confound two separate issues: specifying how a type implements a type class and specifying when such a specification should be used during type inference.</p> </blockquote> <p>I don't understand either. A type can implement a type class in more than 1 way in ML? How would you have the integers ordered by divisibility by example without creating a new type? In Haskell, you would have to do something like use data and have the <code>instance Ord</code> to offer an alternative ordering.</p> <p>And the second one, aren't the two are distinct in Haskell? Specifying "when such a specification should be used during type inference" can be done by something like this:</p> <pre><code>blah :: BlahType b =&gt; ... </code></pre> <p>where BlahType is the class being used during the type inference and NOT the implementing class. Whereas, "how a type implements a type class" is done using <code>instance</code>.</p> <p>Can some one explain what the link is really trying to say? I'm just not quite understanding why Modules would be less restrictive than Type Classes.</p>
36,927,542
1
2
null
2016-04-28 23:33:23.543 UTC
10
2022-04-12 21:05:25.98 UTC
2016-04-29 09:24:56.8 UTC
null
477,476
null
3,953,988
null
1
27
haskell|sml|ml
4,798
<p>To understand what the article is saying, take a moment to consider the <code>Monoid</code> typeclass in Haskell. A monoid is any type, <code>T</code>, which has a function <code>mappend :: T -&gt; T -&gt; T</code> and identity element <code>mempty :: T</code> for which the following holds.</p> <pre><code>a `mappend` (b `mappend` c) == (a `mappend` b) `mappend` c a `mappend` mempty == mempty `mappend` a == a </code></pre> <p>There are many Haskell types which fit this definition. One example that springs immediately to mind are the integers, for which we can define the following.</p> <pre><code>instance Monoid Integer where mappend = (+) mempty = 0 </code></pre> <p>You can confirm that all of the requirements hold.</p> <pre><code>a + (b + c) == (a + b) + c a + 0 == 0 + a == a </code></pre> <p>Indeed, the those conditions hold for all numbers over addition, so we can define the following as well.</p> <pre><code>instance Num a =&gt; Monoid a where mappend = (+) mempty = 0 </code></pre> <p>So now, in GHCi, we can do the following.</p> <pre><code>&gt; mappend 3 5 8 &gt; mempty 0 </code></pre> <p>Particularly observant readers (or those with a background in mathemetics) will probably have noticed by now that we can also define a <code>Monoid</code> instance for numbers over <em>multiplication</em>.</p> <pre><code>instance Num a =&gt; Monoid a where mappend = (*) mempty = 1 a * (b * c) == (a * b) * c a * 1 == 1 * a == a </code></pre> <p>But now the compiler encounters a problem. Which definiton of <code>mappend</code> should it use for numbers? Does <code>mappend 3 5</code> equal <code>8</code> or <code>15</code>? There is no way for it to decide. This is why Haskell does not allow multiple instances of a single typeclass. However, the issue still stands. Which <code>Monoid</code> instance of <code>Num</code> should we use? Both are perfectly valid and make sense for certain circumstances. The solution is to use neither. If you look <code>Monoid</code> in Hackage, you will see that there is no <code>Monoid</code> instance of <code>Num</code>, or <code>Integer</code>, <code>Int</code>, <code>Float</code>, or <code>Double</code> for that matter. Instead, there are <code>Monoid</code> instances of <code>Sum</code> and <code>Product</code>. <code>Sum</code> and <code>Product</code> are defined as follows.</p> <pre><code>newtype Sum a = Sum { getSum :: a } newtype Product a = Product { getProduct :: a } instance Num a =&gt; Monoid (Sum a) where mappend (Sum a) (Sum b) = Sum $ a + b mempty = Sum 0 instance Num a =&gt; Monoid (Product a) where mappend (Product a) (Product b) = Product $ a * b mempty = Product 1 </code></pre> <p>Now, if you want to use a number as a <code>Monoid</code> you have to wrap it in either a <code>Sum</code> or <code>Product</code> type. Which type you use determines which <code>Monoid</code> instance is used. This is the essence of what the article was trying to describe. There is no system built into Haskell's typeclass system which allows you to choose between multiple intances. Instead you have to jump through hoops by wrapping and unwrapping them in skeleton types. Now whether or not you consider this a problem is a large part of what determines whether you prefer Haskell or ML.</p> <p>ML gets around this by allowing multiple &quot;instances&quot; of the same class and type to be defined in different modules. Then, which module you import determines which &quot;instance&quot; you use. (Strictly speaking, ML doesn't have classes and instances, but it does have signatures and structures, which can act almost the same. For amore in depth comparison, read <a href="https://www.cse.unsw.edu.au/%7Echak/papers/modules-classes.pdf" rel="nofollow noreferrer">this paper</a>).</p>
17,988,099
How do I trivially linearize my git history?
<h1>Question</h1> <p>Given that I have a commit like the following:</p> <pre><code>A - B - C - D - G - H \ / - E - F - </code></pre> <p>How do I get a perfectly linear history following only the first parents?</p> <p>Eg, I want to get:</p> <pre><code>A - B - C - D - G'- H' </code></pre> <p>It is expected that the sha1's of G and H will change, as noted above. (For obvious reasons). If the sha1's for A, B, C, and D change as well, then I want to know why.</p> <h1>Background</h1> <p>The intention is to avoid potential merge commits that would arise when doing a naive git rebase -i.</p> <p>The real point is to hopefully gain additional insight in order to determine which commits are in a particular branch, eg, if we have the following graph:</p> <pre><code>I - J - K - L - M \ / / / - N - O - P - </code></pre> <p>Where N was merged into K, but O was merged with --strategy=ours into L, and P was merged into M.</p> <p>I want to be able to linearlize my history so that such problematic commits can be identified, and inspected. I want to have a tree where can identify that O was not put into the upstream branch, even if I potentially identify N and P as being potentially missing from the upstream branch as well, by using git cherry, however any suggestions here would be appreciated.</p>
17,994,534
2
2
null
2013-08-01 07:50:54.78 UTC
13
2016-02-08 14:46:01.057 UTC
2013-08-01 07:57:35.023 UTC
null
52,273
null
52,273
null
1
25
git
3,650
<p>As you said, the following command works:</p> <pre><code>git filter-branch --parent-filter 'cut -f 2,3 -d " "' </code></pre> <p>Why?</p> <p>The problem you pose is solved by transforming each merge commit with a simple commit: this will simply remove the feature branches that were merged, since they will become orphan.</p> <p>Each commit has one or more parent commits. Merge commit are the one which get more than one. Git stores this in each commit object of the history.</p> <p>The <code>git filter-branch</code> command, with the <code>--parent-filter</code> option, allows to rewrite every commit's parent, passed to the filter as <code>-p SHA1</code>, repeated if there are more than one parent. Our filter cuts the parent and forces every commit to have a single parent. </p> <p>For bonus, here's how to do it manually on a precise commit, by re-creating a new commit:</p> <ul> <li><p>get the commit tree and the first parent</p> <pre><code>tree=`git show -s --format=%T SHA1` parent=`git show -s --format=%P SHA1 | cut -d " " -f1` </code></pre></li> <li><p>make a new commit with the same tree, same message, and keep only the first parent as ancestor</p> <pre><code>git show -s --format=%B SHA1 | git commit-tree $tree -p $parent </code></pre></li> </ul>