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
4,666,590
Remove outliers from correlation coefficient calculation
<p>Assume we have two numeric vectors <code>x</code> and <code>y</code>. The Pearson correlation coefficient between <code>x</code> and <code>y</code> is given by</p> <blockquote> <p>cor(x, y)</p> </blockquote> <p>How can I automatically consider only a subset of <code>x</code> and <code>y</code> in the calculation (say 90%) as to maximize the correlation coefficient?</p>
4,667,300
5
2
null
2011-01-12 08:20:33.197 UTC
11
2017-03-20 10:17:42.993 UTC
2011-01-12 12:26:29.927 UTC
null
415,690
null
488,719
null
1
10
r|statistics|correlation
25,222
<p>If you <em>really</em> want to do this (remove the largest (absolute) residuals), then we can employ the linear model to estimate the least squares solution and associated residuals and then select the middle n% of the data. Here is an example:</p> <p>Firstly, generate some dummy data:</p> <pre><code>require(MASS) ## for mvrnorm() set.seed(1) dat &lt;- mvrnorm(1000, mu = c(4,5), Sigma = matrix(c(1,0.8,1,0.8), ncol = 2)) dat &lt;- data.frame(dat) names(dat) &lt;- c("X","Y") plot(dat) </code></pre> <p>Next, we fit the linear model and extract the residuals:</p> <pre><code>res &lt;- resid(mod &lt;- lm(Y ~ X, data = dat)) </code></pre> <p>The <code>quantile()</code> function can give us the required quantiles of the residuals. You suggested retaining 90% of the data, so we want the upper and lower 0.05 quantiles:</p> <pre><code>res.qt &lt;- quantile(res, probs = c(0.05,0.95)) </code></pre> <p>Select those observations with residuals in the middle 90% of the data:</p> <pre><code>want &lt;- which(res &gt;= res.qt[1] &amp; res &lt;= res.qt[2]) </code></pre> <p>We can then visualise this, with the red points being those we will retain:</p> <pre><code>plot(dat, type = "n") points(dat[-want,], col = "black", pch = 21, bg = "black", cex = 0.8) points(dat[want,], col = "red", pch = 21, bg = "red", cex = 0.8) abline(mod, col = "blue", lwd = 2) </code></pre> <p><img src="https://i.stack.imgur.com/gaOp1.png" alt="The plot produced from the dummy data showing the selected points with the smallest residuals"></p> <p>The correlations for the full data and the selected subset are:</p> <pre><code>&gt; cor(dat) X Y X 1.0000000 0.8935235 Y 0.8935235 1.0000000 &gt; cor(dat[want,]) X Y X 1.0000000 0.9272109 Y 0.9272109 1.0000000 &gt; cor(dat[-want,]) X Y X 1.000000 0.739972 Y 0.739972 1.000000 </code></pre> <p>Be aware that here we might be throwing out perfectly good data, because we just choose the 5% with largest positive residuals and 5% with the largest negative. An alternative is to select the 90% with smallest <em>absolute</em> residuals:</p> <pre><code>ares &lt;- abs(res) absres.qt &lt;- quantile(ares, prob = c(.9)) abswant &lt;- which(ares &lt;= absres.qt) ## plot - virtually the same, but not quite plot(dat, type = "n") points(dat[-abswant,], col = "black", pch = 21, bg = "black", cex = 0.8) points(dat[abswant,], col = "red", pch = 21, bg = "red", cex = 0.8) abline(mod, col = "blue", lwd = 2) </code></pre> <p>With this slightly different subset, the correlation is slightly lower:</p> <pre><code>&gt; cor(dat[abswant,]) X Y X 1.0000000 0.9272032 Y 0.9272032 1.0000000 </code></pre> <p>Another point is that even then we are throwing out good data. You might want to look at Cook's distance as a measure of the strength of the outliers, and discard only those values above a certain threshold Cook's distance. <a href="http://en.wikipedia.org/wiki/Cook&#39;s_distance" rel="noreferrer">Wikipedia</a> has info on Cook's distance and proposed thresholds. The <code>cooks.distance()</code> function can be used to retrieve the values from <code>mod</code>:</p> <pre><code>&gt; head(cooks.distance(mod)) 1 2 3 4 5 6 7.738789e-04 6.056810e-04 6.375505e-04 4.338566e-04 1.163721e-05 1.740565e-03 </code></pre> <p>and if you compute the threshold(s) suggested on Wikipedia and remove only those that exceed the threshold. For these data:</p> <pre><code>&gt; any(cooks.distance(mod) &gt; 1) [1] FALSE &gt; any(cooks.distance(mod) &gt; (4 * nrow(dat))) [1] FALSE </code></pre> <p>none of the Cook's distances exceed the proposed thresholds (not surprising given the way I generated the data.)</p> <p>Having said all of this, why do you want to do this? If you are just trying to get rid of data to improve a correlation or generate a significant relationship, that sounds a bit fishy and bit like data dredging to me.</p>
4,827,622
Copy several byte arrays to one big byte array
<p>I have one big <code>byte[]</code> array and lot of small <code>byte</code> arrays ( length of big array is sum of lengths small arrays). Is there maybe some quick method to copy one array to another from starting position to ending, not to use for loop for every byte manually ?</p>
4,827,732
5
0
null
2011-01-28 11:19:30.693 UTC
6
2017-04-15 17:36:19.84 UTC
2011-01-28 14:47:01.393 UTC
null
342,852
null
486,578
null
1
35
java|arrays
64,729
<p>You can use a <a href="http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html" rel="noreferrer"><code>ByteBuffer</code></a>.</p> <pre><code>ByteBuffer target = ByteBuffer.wrap(bigByteArray); target.put(small1); target.put(small2); ...; </code></pre>
4,256,329
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>
<p>I have the code below:</p> <pre><code>List&lt;string&gt; aa = (from char c in source select new { Data = c.ToString() }).ToList(); </code></pre> <p>But what about </p> <pre><code>List&lt;string&gt; aa = (from char c1 in source from char c2 in source select new { Data = string.Concat(c1, ".", c2)).ToList&lt;string&gt;(); </code></pre> <p>While compile getting error</p> <blockquote> <p>Cannot implicitly convert type <code>'System.Collections.Generic.List&lt;AnonymousType#1&gt;'</code> to <code>'System.Collections.Generic.List&lt;string&gt;'</code></p> </blockquote> <p>Need help.</p>
4,256,387
5
2
null
2010-11-23 13:12:20.247 UTC
4
2016-06-08 05:36:44.217 UTC
2012-08-01 10:30:20.157 UTC
null
41,956
user372724
null
null
1
42
c#|.net|linq|compiler-errors
236,569
<pre><code>IEnumerable&lt;string&gt; e = (from char c in source select new { Data = c.ToString() }).Select(t = &gt; t.Data); // or IEnumerable&lt;string&gt; e = from char c in source select c.ToString(); // or IEnumerable&lt;string&gt; e = source.Select(c = &gt; c.ToString()); </code></pre> <hr> <p>Then you can call <code>ToList()</code>:</p> <pre><code>List&lt;string&gt; l = (from char c in source select new { Data = c.ToString() }).Select(t = &gt; t.Data).ToList(); // or List&lt;string&gt; l = (from char c in source select c.ToString()).ToList(); // or List&lt;string&gt; l = source.Select(c = &gt; c.ToString()).ToList(); </code></pre>
4,623,328
Select first occurring element after another element
<p>I've got the following HTML code on a page:</p> <pre><code>&lt;h4&gt;Some text&lt;/h4&gt; &lt;p&gt; Some more text! &lt;/p&gt; </code></pre> <p>In my <code>.css</code> I've got the following selector to style the <code>h4</code> element. The HTML code above is just a small part of the entire code; there are several <code>div</code>s more wrapped around belonging to a shadowbox:</p> <pre><code>#sb-wrapper #sb-wrapper-inner #sb-body #myDiv h4 { color : #614E43; margin-top : 5px; margin-left : 6px; } </code></pre> <p>So, I have the correct style for my <code>h4</code> element, but I also want to style the <code>p</code> tag in my HTML.</p> <p>Is this possible with CSS-selectors? And if yes, how can I do this?</p>
4,623,351
5
0
null
2011-01-07 07:17:54.947 UTC
14
2021-08-10 04:30:08.483 UTC
2019-01-04 21:33:45.717 UTC
null
3,345,644
null
291,293
null
1
149
html|css|css-selectors
166,673
<pre><code>#many .more.selectors h4 + p { ... } </code></pre> <p>This is called the <a href="http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors" rel="noreferrer">adjacent sibling selector</a>.</p>
4,494,404
Find large number of consecutive values fulfilling condition in a numpy array
<p>I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a a period in time.</p> <p>An extremely simple way to do this is something like this:</p> <pre><code>values = ''.join(("1" if (abs(x) &lt; SILENCE_THRESHOLD) else "0" for x in samples)) pattern = re.compile('1{%d,}'%int(MIN_SILENCE)) for match in pattern.finditer(values): # code goes here </code></pre> <p>The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.</p> <p>Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?</p>
4,495,197
8
0
null
2010-12-20 22:02:05.607 UTC
14
2021-01-31 22:46:58.237 UTC
null
null
null
null
458,320
null
1
25
python|search|numpy
15,279
<p>Here's a numpy-based solution.</p> <p>I think (?) it should be faster than the other options. Hopefully it's fairly clear.</p> <p>However, it does require a twice as much memory as the various generator-based solutions. As long as you can hold a single temporary copy of your data in memory (for the diff), and a boolean array of the same length as your data (1-bit-per-element), it should be pretty efficient...</p> <pre><code>import numpy as np def main(): # Generate some random data x = np.cumsum(np.random.random(1000) - 0.5) condition = np.abs(x) &lt; 1 # Print the start and stop indices of each region where the absolute # values of x are below 1, and the min and max of each of these regions for start, stop in contiguous_regions(condition): segment = x[start:stop] print start, stop print segment.min(), segment.max() def contiguous_regions(condition): &quot;&quot;&quot;Finds contiguous True regions of the boolean array &quot;condition&quot;. Returns a 2D array where the first column is the start index of the region and the second column is the end index.&quot;&quot;&quot; # Find the indicies of changes in &quot;condition&quot; d = np.diff(condition) idx, = d.nonzero() # We need to start things after the change in &quot;condition&quot;. Therefore, # we'll shift the index by 1 to the right. idx += 1 if condition[0]: # If the start of condition is True prepend a 0 idx = np.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = np.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) return idx main() </code></pre>
4,101,539
C# removing substring from end of string
<p>I have an array of strings:</p> <pre><code>string[] remove = { "a", "am", "p", "pm" }; </code></pre> <p>And I have a textbox that a user enters text into. If they type any string in the <code>remove</code> array at the end of the text in the textbox, it should be removed. What is the easiest way to do this?</p> <p><strong>EDIT</strong> To clarify, I'm making a time parser. When you give the function a string, it does its best to parse it into this format: <code>08:14pm</code> I have a textbox to test it. When the focus leaves the textbox, I need to get the text without the am/pm/a/p suffix so I can parse the number only segment.</p>
4,101,583
8
6
null
2010-11-04 21:23:26.1 UTC
1
2020-02-27 16:20:35.17 UTC
2020-02-27 16:20:35.17 UTC
null
953,496
null
481,702
null
1
56
c#|string|textbox
96,991
<pre><code>string[] remove = { "a", "am", "p", "pm" }; string inputText = "blalahpm"; foreach (string item in remove) if (inputText.EndsWith(item)) { inputText = inputText.Substring(0, inputText.LastIndexOf(item)); break; //only allow one match at most } </code></pre>
4,732,544
Why are only final variables accessible in anonymous class?
<ol> <li><p><code>a</code> can only be final here. Why? How can I reassign <code>a</code> in <code>onClick()</code> method without keeping it as private member?</p> <pre><code>private void f(Button b, final int a){ b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int b = a*5; } }); } </code></pre></li> <li><p>How can I return the <code>5 * a</code> when it clicked? I mean,</p> <pre><code>private void f(Button b, final int a){ b.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int b = a*5; return b; // but return type is void } }); } </code></pre></li> </ol>
4,732,617
15
8
null
2011-01-19 06:58:42.2 UTC
227
2021-03-16 20:41:58.64 UTC
2017-07-14 09:29:07.35 UTC
null
5,091,346
user467871
null
null
1
381
java|event-handling|anonymous-class
125,467
<p>As noted in comments, some of this becomes irrelevant in Java 8, where <code>final</code> can be implicit. Only an <em>effectively</em> final variable can be used in an anonymous inner class or lambda expression though.</p> <hr> <p>It's basically due to the way Java manages <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">closures</a>.</p> <p>When you create an instance of an anonymous inner class, any variables which are used within that class have their <em>values</em> copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)</p> <p>As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what <em>would</em> be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.</p> <p>Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the <em>parameters</em> of one method aren't seen by its caller, but changes made to the objects <em>referred to</em> by the parameters are seen.</p> <p>If you're interested in a more detailed comparison between Java and C# closures, I have an <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="noreferrer">article</a> which goes into it further. I wanted to focus on the Java side in this answer :)</p>
4,105,795
Pretty-Print JSON in Java
<p>I'm using <a href="/questions/tagged/json-simple" class="post-tag" title="show questions tagged &#39;json-simple&#39;" rel="tag">json-simple</a> and I need to pretty-print JSON data (make it more human readable).</p> <p>I haven't been able to find this functionality within that library. How is this commonly achieved?</p>
7,310,424
21
1
null
2010-11-05 12:24:08.397 UTC
55
2022-07-24 19:23:13.617 UTC
2015-09-11 14:35:33.077 UTC
null
3,453,226
null
328,681
null
1
273
java|json|pretty-print|json-simple
342,993
<p>Google's <a href="https://github.com/google/gson" rel="noreferrer">GSON</a> can do this in a nice way:</p> <pre><code>Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJsonString); String prettyJsonString = gson.toJson(je); </code></pre> <p>or since it is now recommended to use the static parse method from JsonParser you can also use this instead:</p> <pre><code>Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement je = JsonParser.parseString​(uglyJsonString); String prettyJsonString = gson.toJson(je); </code></pre> <p>Here is the import statement:</p> <pre><code>import com.google.gson.*; </code></pre> <p>Here is the Gradle dependency:</p> <pre><code>implementation 'com.google.code.gson:gson:2.8.7' </code></pre>
4,827,092
unable to install pg gem
<p>I tried using <code>gem install pg</code> but it doesn't seem to work.</p> <p><code>gem install pg</code> gives this error</p> <pre><code>Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... ERROR: Error installing pg: ERROR: Failed to build gem native extension. C:/Ruby/bin/ruby.exe extconf.rb checking for pg_config... no No pg_config... trying anyway. If building fails, please try again with --with-pg-config=/path/to/pg_config checking for libpq-fe.h... no Can't find the 'libpq-fe.h header *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=C:/Ruby/bin/ruby --with-pg --without-pg --with-pg-dir --without-pg-dir --with-pg-include --without-pg-include=${pg-dir}/include --with-pg-lib --without-pg-lib=${pg-dir}/lib --with-pg-config --without-pg-config --with-pg_config --without-pg_config Gem files will remain installed in C:/Ruby/lib/ruby/gems/1.8/gems/pg-0.10.1 for inspection. Results logged to C:/Ruby/lib/ruby/gems/1.8/gems/pg-0.10.1/ext/gem_make.out </code></pre>
4,827,229
23
4
null
2011-01-28 10:19:27.767 UTC
53
2022-03-17 23:13:31.24 UTC
2015-03-09 10:25:42.487 UTC
null
2,641,576
null
429,167
null
1
252
ruby-on-rails|ruby|rubygems|installation
162,157
<p>Answered here: <a href="https://stackoverflow.com/questions/4335750/cant-install-pg-gem-on-windows">Can&#39;t install pg gem on Windows</a></p> <blockquote> <p>There is no Windows native version of latest release of pg (0.10.0) released yesterday, but if you install 0.9.0 it should install binaries without issues.</p> </blockquote>
14,501,748
cannot open window service on computer '.' in window application
<p>I develop one window application and I also create one service. I start the service using coding in window application, but I am getting an error like cannot open window service on computer <code>'.'</code> </p> <p>I have used below code.</p> <pre><code>ServiceController controller = new ServiceController("SeoMozScheduleService"); if (controller.Status == ServiceControllerStatus.Stopped) { controller.Start(); } </code></pre> <p>If i right click on Application and click on Run as Administrator than it works fine for me...</p>
14,600,685
7
9
null
2013-01-24 12:48:21.483 UTC
3
2021-09-24 09:20:38.703 UTC
2013-05-15 19:56:00.483 UTC
null
58,074
null
1,253,970
null
1
21
c#|windows-services|windows-applications
48,630
<p>Go to <code>c://Program Files/ApplicationFolder/.exe</code> Right-click on .exe and go to <code>Properties</code> then go <code>Compatibility Tab</code> and check true to <code>Run this Program as an administrator Level</code>.</p>
14,608,250
How can I find the size of a type?
<p>I'm holding a <code>Type*</code> in my hand. How do I find out its size (the size objects of this type will occupy in memory) in bits / bytes? I see all kinds of methods allowing me to get "primitive" or "scalar" size, but that won't help me with aggregate types...</p>
14,608,251
2
1
null
2013-01-30 15:59:16.883 UTC
10
2018-04-08 15:08:11.017 UTC
null
null
null
null
242,762
null
1
26
llvm
10,391
<p>The size depends on the target (for several reasons, alignment being one of them).</p> <p>In LLVM versions 3.2 and above, you need to use <a href="http://llvm.org/docs/doxygen/html/classllvm_1_1DataLayout.html" rel="noreferrer">DataLayout</a>, in particular its <code>getTypeAllocSize</code> method. This returns the size in bytes, there's also a bit version named <code>getTypeAllocSizeInBits</code>. A <code>DataLayout</code> instance can be obtained by creating it from the current module: <code>DataLayout* TD = new DataLayout(M)</code>.</p> <p>With LLVM up to version 3.1 (including), use <code>TargetData</code> instead of <code>DataLayout</code>. It exposes the same <code>getTypeAllocSize</code> methods, though.</p>
14,365,725
Easiest/Lightest Replacement For Browser Detection jQuery 1.9?
<p>I had several clients complain yesterday that some code stopped working. Apparently it comes down to plug-ins using the now deprecated <code>jQuery.browser</code> which stopped working yesterday when jQuery 1.9 was released.</p> <p>I (quickly) looked at the 1.9 change docs and it <em>seems</em> like they want me to substitute some pretty heavy libraries just for that <strong>one</strong> function.</p> <p>Is there a recommended lightest weight plug-in or code snippet to restore that functionality?</p> <p>For what these sites need, it's very basic; I only need the most basic detection of IE vs FF vs everyone else.</p> <p>Suggestions?</p>
16,194,719
13
3
null
2013-01-16 19:01:02.293 UTC
11
2014-07-10 13:50:57.803 UTC
2013-02-11 22:14:38.673 UTC
null
237,917
null
1,332,527
null
1
64
jquery|browser-detection
63,696
<p>I've use the following code answered by Alexx Roche, but i wanted to detect MSIE so:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { if (navigator.userAgent.match(/msie/i) ){ alert('I am an old fashioned Internet Explorer'); } }); &lt;/script&gt; </code></pre> <p>hope it helps!</p>
14,622,421
How to change legend title in ggplot
<p>I have the following plot like below. It was created with this command:</p> <pre><code>library(ggplot2) df &lt;- data.frame(cond = factor(rep(c(&quot;A&quot;, &quot;B&quot;), each = 200)), rating = c(rnorm(200), rnorm(200, mean=.8))) ggplot(df, aes(x=rating, fill=cond)) + geom_density(alpha = .3) + xlab(&quot;NEW RATING TITLE&quot;) + ylab(&quot;NEW DENSITY TITLE&quot;) </code></pre> <p>Now, I want to modify the <em>legend title</em> from <strong>cond</strong> into <strong>NEW LEGEND TITLE</strong>.</p> <p>So, I just added the following line add the end of the above code:</p> <pre><code>+labs(colour=&quot;NEW LEGEND TITLE&quot;) </code></pre> <p>But it doesn't work. What's the right way to do it?</p> <p><img src="https://i.stack.imgur.com/sqpSU.png" alt="enter image description here" /></p>
14,622,513
13
7
null
2013-01-31 09:31:10.45 UTC
97
2022-01-05 21:31:01.18 UTC
2022-01-05 21:31:01.18 UTC
null
15,293,191
null
67,405
null
1
454
r|plot|ggplot2
998,721
<p>This should work:</p> <pre><code>p &lt;- ggplot(df, aes(x=rating, fill=cond)) + geom_density(alpha=.3) + xlab("NEW RATING TITLE") + ylab("NEW DENSITY TITLE") p &lt;- p + guides(fill=guide_legend(title="New Legend Title")) </code></pre> <p>(or alternatively)</p> <pre><code>p + scale_fill_discrete(name = "New Legend Title") </code></pre>
2,936,116
Autotools: how to cleanup files created by "./configure" in lighttpd project?
<p>I'm trying out <code>lighttpd</code> for an embedded Linux project. I got the latest source package and started writing a master Makefile encapsulating all configure, compile, install (for testing) etc stuff. </p> <p>And vice-versa, I want to cleanup every step. After the cleanup there should be no generated files anymore. This is important for repetitive testing.</p> <p>I wonder if there is a way to do a complete cleanup of what <code>./configure</code> generated? I'm not familiar with <code>autotools</code> in details.</p> <p>Any hints?</p>
2,937,092
2
2
null
2010-05-29 18:17:43.49 UTC
4
2016-04-03 13:52:18.527 UTC
2016-02-24 10:30:36.647 UTC
null
1,052,126
null
330,272
null
1
37
makefile|autotools|configure|lighttpd|undo
49,287
<p>I personally would really use the features of a source control software (you should use one) for this. This would cleanup make independent of your build process. See e.g. <a href="http://websvn.kde.org/*checkout*/trunk/KDE/kdesdk/scripts/svn-clean?pathrev=499176" rel="noreferrer"><code>svn-cleanup</code></a> or <code>git clean</code>.</p> <p>Nevertheless, automake allows some tweaking when to remove which files. This has (intentionally?) built-in limitations on what files generated by autotools can be remove this way though. Have a look at <a href="http://www.gnu.org/software/hello/manual/automake/Clean.html#Clean" rel="noreferrer">the definitions for MOSTLYCLEANFILES, CLEANFILES, DISTCLEANFILES, and MAINTAINERCLEANFILES</a> and adjust your <code>Makefile.am</code>'s. With them you can remove a lot of stuff with</p> <pre><code>make mostlyclean make clean make distclean make maintainer-clean </code></pre> <p>You won't be able to remove e.g. <code>Makefile</code> or <code>.deps/</code> this way.</p> <p>As for the reliability of <code>make clean</code> it should "work 100%" if you stick to cleanly specifying your files and stay away from manual intervention. Otherwise <a href="http://www.gnu.org/software/hello/manual/automake/Extending.html#Extending" rel="noreferrer">extend the cleanup rules</a>.</p>
53,682,247
How to point Go module dependency in go.mod to a latest commit in a repo?
<p>Starting with v1.11 Go added support for modules. Commands</p> <pre><code>go mod init &lt;package name&gt; go build </code></pre> <p>would generate <code>go.mod</code> and <code>go.sum</code> files that contain all found versions for the package dependencies. </p> <p>If a module does not have any releases, the latest commit of that module is used. If a module does have releases, the latest one is picked as a dependency.</p> <p>However sometimes I would need functionality that is not in a published release yet, but from a commit made after that release. How do I set <code>go.mod</code> to point not to a release of a module, but to a specific commit in the module's repository?</p> <p>It looks like I can do it by hand in go.mod with</p> <pre><code>module /my/module require ( ... github.com/someone/some_module v0.0.0-20181121201909-af044c0995fe ... ) </code></pre> <p>where <code>v0.0.0</code> does not correspond to the last published release tag, <code>20181121201909</code> would be a commit timestamp and <code>af044c0995fe</code> would be the commit hash? Should such information to be found and entered by hand, or there is a better way?</p>
53,682,399
6
0
null
2018-12-08 11:53:31.147 UTC
48
2021-11-26 07:52:12.38 UTC
null
null
null
null
23,080
null
1
195
git|go|module
197,876
<p>Just 'go get' at the commit hash you want:</p> <pre><code>go get github.com/someone/some_module@af044c0995fe </code></pre> <p>'go get' will correctly update the dependency files (go.mod, go.sum).</p> <p>More information: <a href="https://github.com/golang/go/wiki/Modules#how-to-upgrade-and-downgrade-dependencies" rel="noreferrer">https://github.com/golang/go/wiki/Modules#how-to-upgrade-and-downgrade-dependencies</a></p>
53,658,208
Custom AppBar Flutter
<p>Im trying to achieve something like the following, <a href="https://i.stack.imgur.com/xRIAc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xRIAc.png" alt="enter image description here"></a></p> <p>I'm very new to flutter so I couldn't figure it out. I need a custom AppBar with drawer and actions but arranged like the image.</p> <p>I tried a StackView in the title widget</p> <pre><code>appBar: AppBar( title: Stack( children: &lt;Widget&gt;[ Container( width: double.infinity, color: CustomColors.accentColor, ), Text( 'Title', style: TextStyle(fontSize: 22.0, color: CustomColors.primaryDark), ), ], ), ), </code></pre> <p>But I get something like this <a href="https://i.stack.imgur.com/UQW46.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UQW46.png" alt="enter image description here"></a></p> <p>Can someone help me out? Thank you.</p>
53,658,805
5
1
null
2018-12-06 19:15:42.353 UTC
21
2021-07-22 15:19:41.41 UTC
null
null
null
null
3,831,319
null
1
24
dart|flutter|flutter-layout
112,446
<p>As I mentioned in the comment , you can create a Custom widget like your Image attached, there are many ways to do it, this is just an example :</p> <pre><code> class CustomBarWidget extends StatelessWidget { GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = GlobalKey(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, body: Container( height: 160.0, child: Stack( children: &lt;Widget&gt;[ Container( color: Colors.red, width: MediaQuery.of(context).size.width, height: 100.0, child: Center( child: Text( "Home", style: TextStyle(color: Colors.white, fontSize: 18.0), ), ), ), Positioned( top: 80.0, left: 0.0, right: 0.0, child: Container( padding: EdgeInsets.symmetric(horizontal: 20.0), child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(1.0), border: Border.all( color: Colors.grey.withOpacity(0.5), width: 1.0), color: Colors.white), child: Row( children: [ IconButton( icon: Icon( Icons.menu, color: Colors.red, ), onPressed: () { print("your menu action here"); _scaffoldKey.currentState.openDrawer(); }, ), Expanded( child: TextField( decoration: InputDecoration( hintText: "Search", ), ), ), IconButton( icon: Icon( Icons.search, color: Colors.red, ), onPressed: () { print("your menu action here"); }, ), IconButton( icon: Icon( Icons.notifications, color: Colors.red, ), onPressed: () { print("your menu action here"); }, ), ], ), ), ), ) ], ), ), ); } } </code></pre> <p>For more information, I wrote an article about how we can customize the <code>AppBar</code> : <a href="https://medium.com/flutter-community/flutter-increase-the-power-of-your-appbar-sliverappbar-c4f67c4e076f" rel="noreferrer">https://medium.com/flutter-community/flutter-increase-the-power-of-your-appbar-sliverappbar-c4f67c4e076f</a></p>
30,642,894
Getting Flask to use Python3 (Apache/mod_wsgi)
<p>I've got a basic "hello world" Flask app running.</p> <p>I'm on Ubuntu 14.04, using Apache 2.4. I've installed mod_wsgi.</p> <p>I've created a <code>~/web/piFlask/venv/</code> to hold a virtualenv-created Python2 with flask installed.</p> <p>However, I wish to have my flaskapp import a Python3.x module I have written.</p> <p>What do I need to do to make this happen?</p> <p>I tried creating a <code>~/web/piFlask/venv3/</code> and modifying <code>~/web/piFlask/piFlask.wsgi</code>:</p> <pre><code>import os, sys PROJECT_DIR = '/home/pi/web/piFlask' activate_this = os.path.join(PROJECT_DIR, 'venv3/bin', 'activate_this.py') execfile(activate_this, dict(__file__=activate_this)) sys.path.insert(0, PROJECT_DIR) from piFlask import app as application application.debug = True </code></pre> <p>But I don't think this is sufficient. This .wsgi is in fact a Python file that will get executed by mod_wsgi, which I'm sure will use a Py2.x interpreter to do the execution.</p> <p>So if I'm understanding correctly, mod_wsgi fires up the system Python in order to execute this .wsgi, which will in turn fire up my <code>~/web/piFlask/venv/</code> interpreter to actually process the request.</p> <p>I think I could persuade mod_wsgi to use either a system Python3 or my own venv3/... by setting <code>WSGIPythonPath /home/pi/web/piFlask/venv3/lib/python3.4/site-packages</code> in /etc/apache2/mods-available/wsgi.conf</p> <p>But I found an instruction somewhere saying you have to compile mod_wsgi for Py3, and the bottom quickly falls out to this problem.</p>
30,643,902
4
0
null
2015-06-04 11:39:56.37 UTC
10
2018-03-13 22:44:23.35 UTC
null
null
null
null
435,129
null
1
14
python-3.x|flask|mod-wsgi
20,578
<p>Correct, mod_wsgi needs to be compiled for a specific Python version as it never actually executes 'python' executable. Instead the Python library is linked into mod_wsgi.</p> <p>The end result is you cannot mix Python 3 code within an application running using the Python 2 interpreter.</p> <p>You would have to consider making your code runnable under both Python 2 and 3 and then you could choose which of those you want to use and use a version of mod_wsgi compiled for the version you choose to use.</p>
44,533,319
How to assign more memory to docker container
<p>As the title reads, I'm trying to assign more memory to my container. I'm using an image from docker hub called "aallam/tomcat-mysql" in case that's relevant.</p> <p>When I start it normally without any special flags, there's a memory limit of 2GB (even though I read that memory is unbounded if not set)</p> <p>Here are my docker stats</p> <pre><code>CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS ba57d6c9e9d2 0.22% 145.6 MiB / 1.952 GiB 7.29% 508 B / 508 B 0 B / 6.91 MB 68 </code></pre> <p>I tried setting memory explicitly like so but with same results</p> <pre><code>docker run -d --memory=10g --memory-swap=-1 -e MYSQL_PASSWORD=password -p 3307:3306 -p 8081:8080 aallam/tomcat-mysql </code></pre> <p>I've read that perhaps the VM is what's restricting it. But then why does docker stats show that container size limit is 2GB?</p>
44,533,437
4
0
null
2017-06-13 23:59:34.483 UTC
27
2022-09-20 11:31:47.47 UTC
2018-10-04 03:58:16.667 UTC
null
4,671,027
null
1,007,922
null
1
183
docker|docker-container
236,485
<p>That <code>2GB</code> limit you see is the total memory of the VM (virtual machine) on which docker runs.</p> <p>If you are using <a href="https://docs.docker.com/desktop/" rel="nofollow noreferrer">Docker Desktop</a> you can easily increase it from the Whale icon in the task bar, then go to Preferences -&gt; Advanced:</p> <p><a href="https://i.stack.imgur.com/6iWiW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6iWiW.png" alt="Docker Preferences" /></a></p> <p>But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.</p> <p>See this for Mac:</p> <p><a href="https://docs.docker.com/desktop/settings/mac/#advanced" rel="nofollow noreferrer">https://docs.docker.com/desktop/settings/mac/#advanced</a></p> <blockquote> <p>MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.</p> </blockquote> <p>For Windows:</p> <p><a href="https://docs.docker.com/desktop/settings/windows/#advanced" rel="nofollow noreferrer">https://docs.docker.com/desktop/settings/windows/#advanced</a></p> <blockquote> <p>Memory - Change the amount of memory the Docker for Windows' Linux VM uses</p> </blockquote>
10,834,817
Xcode Simulator: how to remove older unneeded devices?
<p>I'm running Xcode 4.3.1 iOS-Simulator which originally only supports iOS 5.1.</p> <p>I need to test my code with iOS 4.3, so I used Xcode's "Install" feature to install it as described in <a href="https://apple.stackexchange.com/questions/47323">"Installing Xcode with iOS 4.3 device simulator?"</a></p> <p>Now I'm finished with testing but cannot find a way to uninstall the 4.3 portions ("iPhone 4.3 Simulator" and "iPad 4.3 Simulator"). I want to reduce the clutter in the Scheme menu.</p> <p>No one on Apple's Xcode listserv knew the answer!</p> <p>EDIT: note that much has changed since Xcode 4.3, so suggest anyone reading this look at all the answers. The newest ones such as Steve Moser's may be of more use to you!</p> <p>EDIT 10/2017: Posted on Twitter by Julio Carrettoni‏ </p> <blockquote> <p>If you are an iOS developer, execute this:<br> <code>$ xcrun simctl delete unavailable</code><br> It removes old simulators Xcode no longer use. For me it was 6Gb Did not try it myself...</p> </blockquote> <p>[Also, I just saw Russ Bishop mentioned this in a comment below already...]</p>
10,835,251
21
0
null
2012-05-31 13:40:49.83 UTC
90
2022-09-13 12:13:10.767 UTC
2018-01-09 11:49:27.803 UTC
null
3,397,217
null
1,633,251
null
1
257
ios|xcode|ios-simulator
165,796
<p>Did you try to just delete the 4.3 SDK from within the Xcode Package?</p> <blockquote> <p>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs</p> </blockquote> <p>please also delete the corresponding .dmg file in</p> <blockquote> <p>~/Library/Caches/com.apple.dt.Xcode/Downloads</p> </blockquote> <p>to <a href="https://stackoverflow.com/questions/11672945/xcode-4-4-simulator-how-to-remove-older-unneeded-devices/11790983#11790983">prevent Xcode from re-installing</a> the same package again.</p> <hr /> <p>for XCode &gt;= 6 see <a href="https://stackoverflow.com/a/30206853/529977"> @praveen-matanam 's answer</a></p>
34,580,662
What does "Stage Skipped" mean in Apache Spark web UI?
<p>From my Spark UI. What does it mean by skipped?</p> <p><a href="https://i.stack.imgur.com/cyvd1.png"><img src="https://i.stack.imgur.com/cyvd1.png" alt="enter image description here"></a></p>
34,581,152
2
0
null
2016-01-03 19:26:29.91 UTC
30
2021-02-05 07:59:55.47 UTC
2017-08-18 21:43:08.447 UTC
null
-1
null
127,320
null
1
106
apache-spark|rdd
31,724
<p>Typically it means that data has been fetched from cache and there was no need to re-execute given stage. It is consistent with your DAG which shows that the next stage requires shuffling (<code>reduceByKey</code>). Whenever there is shuffling involved Spark <a href="https://spark.apache.org/docs/1.5.0/programming-guide.html#performance-impact">automatically caches generated data</a>: </p> <blockquote> <p>Shuffle also generates a large number of intermediate files on disk. As of Spark 1.3, these files are preserved until the corresponding RDDs are no longer used and are garbage collected. This is done so the shuffle files don’t need to be re-created if the lineage is re-computed. </p> </blockquote>
34,490,599
C++11: How to set seed using <random>
<p>I am exercising the random library, new to C++11. I wrote the following minimal program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;random&gt; using namespace std; int main() { default_random_engine eng; uniform_real_distribution&lt;double&gt; urd(0, 1); cout &lt;&lt; "Uniform [0, 1): " &lt;&lt; urd(eng); } </code></pre> <p>When I run this repeatedly it gives the same output each time:</p> <pre><code>&gt;a Uniform [0, 1): 0.131538 &gt;a Uniform [0, 1): 0.131538 &gt;a Uniform [0, 1): 0.131538 </code></pre> <p>I would like to have the program set the seed differently each time it is called, so that a different random number is generated each time. I am aware that random provides a facility called seed_seq, but I find the explanation of it (at cplusplus.com) totally obscure:</p> <p><a href="http://www.cplusplus.com/reference/random/seed_seq/" rel="noreferrer">http://www.cplusplus.com/reference/random/seed_seq/</a></p> <p>I'd appreciate advice on how to have a program generate a new seed each time it is called: The simpler the better.</p> <p>My platform(s):</p> <ul> <li>Windows 7 : <a href="http://tdm-gcc.tdragon.net/" rel="noreferrer">TDM-GCC compiler</a></li> </ul>
34,493,057
2
0
null
2015-12-28 09:09:05.873 UTC
9
2015-12-29 20:01:59.9 UTC
2015-12-28 12:07:47.913 UTC
null
559,289
null
2,432,059
null
1
27
c++11|random
35,325
<p>The point of having a <code>seed_seq</code> is to increase the entropy of the generated sequence. If you have a random_device on your system, initializing with multiple numbers from that random device may arguably do that. On a system that has a pseudo-random number generator I don't think there is an increase in randomness, i.e. generated sequence entropy.</p> <p>Building on that your approach:</p> <p>If your system does provide a random device then you can use it like this:</p> <pre><code> std::random_device r; // std::seed_seq ssq{r()}; // and then passing it to the engine does the same default_random_engine eng{r()}; uniform_real_distribution&lt;double&gt; urd(0, 1); cout &lt;&lt; "Uniform [0, 1): " &lt;&lt; urd(eng); </code></pre> <p>If your system does not have a random device then you can use <code>time(0)</code> as a seed to the random_engine</p> <pre><code> default_random_engine eng{static_cast&lt;long unsigned int&gt;(time(0))}; uniform_real_distribution&lt;double&gt; urd(0, 1); cout &lt;&lt; "Uniform [0, 1): " &lt;&lt; urd(eng); </code></pre> <p>If you have multiple sources of randomness you can actually do this (e.g. 2)</p> <pre><code>std::seed_seq seed{ r1(), r2() }; default_random_engine eng{seed}; uniform_real_distribution&lt;double&gt; urd(0, 1); cout &lt;&lt; "Uniform [0, 1): " &lt;&lt; urd(eng); </code></pre> <p>where r1 , r2 are different random devices , e.g. a <em>thermal noise</em> or <em>quantum source</em> .</p> <p>Ofcourse you could mix and match</p> <pre><code>std::seed_seq seed{ r1(), static_cast&lt;long unsigned int&gt;(time(0)) }; default_random_engine eng{seed}; uniform_real_distribution&lt;double&gt; urd(0, 1); cout &lt;&lt; "Uniform [0, 1): " &lt;&lt; urd(eng); </code></pre> <p>Finally, I like to initialize with an one liner:</p> <pre><code> auto rand = std::bind(std::uniform_real_distribution&lt;double&gt;{0,1}, std::default_random_engine{std::random_device()()}); std::cout &lt;&lt; "Uniform [0,1): " &lt;&lt; rand(); </code></pre> <hr> <p>If you worry about the <code>time(0)</code> having second precision you can overcome this by playing with the <code>high_resolution_clock</code> either by requesting the time since epoch as designated firstly by <a href="https://stackoverflow.com/a/34490647/4345926">bames23 below</a>:</p> <pre><code>static_cast&lt;long unsigned int&gt;(std::chrono::high_resolution_clock::now().time_since_epoch().count()) </code></pre> <p>or maybe just play with CPU randomness</p> <pre><code>long unsigned int getseed(int const K) { typedef std::chrono::high_resolution_clock hiclock; auto gett= [](std::chrono::time_point&lt;hiclock&gt; t0) { auto tn = hiclock::now(); return static_cast&lt;long unsigned int&gt;(std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(tn-t0).count()); }; long unsigned int diffs[10]; diffs[0] = gett(hiclock::now()); for(int i=1; i!=10; i++) { auto last = hiclock::now(); for(int k=K; k!=0; k--) { diffs[i]= gett(last); } } return *std::max_element(&amp;diffs[1],&amp;diffs[9]); } </code></pre>
34,607,028
How to set Image resource to ImageView using DataBinding
<p>How can we use data binding in android to put image resource in an <code>ImageView</code>? </p> <pre><code> &lt;ImageView android:id="@+id/is_synced" android:src="@{model.pending ? @mipmap/pending: @mipmap/synced}" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; </code></pre> <p>I want an image if pending is true and another image if pending is false. But it's showing error.How can I achieve this functionality?</p>
37,570,135
9
1
null
2016-01-05 08:19:22.633 UTC
13
2020-05-01 21:42:32.077 UTC
2016-01-05 08:38:30.173 UTC
null
2,006,803
null
2,006,803
null
1
89
android|xml|android-databinding
84,224
<p>set image like this,</p> <pre><code> &lt;ImageView android:layout_width="28dp" android:layout_height="28dp" android:src="@{model.isActive ? @drawable/white_activated_icon :@drawable/activated_icon}" tools:src="@mipmap/white_activated_icon" /&gt; </code></pre>
26,157,620
Convert a simple one line string to RDD in Spark
<p>I have a simple line:</p> <pre><code>line = "Hello, world" </code></pre> <p>I would like to convert it to an RDD with only one element. I have tried </p> <pre><code>sc.parallelize(line) </code></pre> <p>But it get:</p> <pre><code>sc.parallelize(line).collect() ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] </code></pre> <p>Any ideas? </p>
26,158,173
3
0
null
2014-10-02 09:07:14.783 UTC
5
2020-11-20 14:54:56.94 UTC
2016-09-06 23:47:33.047 UTC
null
2,411,320
null
112,976
null
1
29
python|apache-spark|pyspark|distributed-computing|rdd
50,363
<p>try using List as parameter: </p> <pre><code>sc.parallelize(List(line)).collect() </code></pre> <p>it returns </p> <pre><code>res1: Array[String] = Array(hello,world) </code></pre>
38,892,270
DELETE_FAILED_INTERNAL_ERROR Error while Installing APK
<p><a href="https://i.stack.imgur.com/F2Isr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F2Isr.png" alt="enter image description here" /></a>I am using <strong>Android Studio 2.2</strong> Preview. I am facing the issue</p> <blockquote> <p>Failure: Install failed invalid apk</p> <p>Error: While installing apk,</p> </blockquote> <p>I have made changes in build.gradle but could not retrack it, please suggest me solution???</p>
43,734,320
32
8
null
2016-08-11 09:21:24.16 UTC
43
2020-07-28 12:48:04.74 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,301,371
null
1
203
android|android-studio|build.gradle
182,147
<p><strong>Android studio mac/windows/linux:</strong></p> <p><strong>Steps in together (mac):</strong> Android Studio > Preferences > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run</p> <p><strong>Steps in together (windows &amp; linux):</strong> File > Settings > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run</p> <p><strong>Steps in Detail :</strong></p> <p><strong>Steps 1:</strong> Studio > Preferences (for windows &amp; linux got to File > settings > Build, Execution, Deployment and then same as mac)</p> <p><a href="https://i.stack.imgur.com/Q9HIA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q9HIA.png" alt="enter image description here"></a></p> <p><strong>Steps 2:</strong> <em>Preferences > Build, Execution, Deployment</em></p> <p><a href="https://i.stack.imgur.com/LWMRM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LWMRM.png" alt="enter image description here"></a></p> <p><strong>Steps 3:</strong> <em>Build, Execution, Deployment > Instant Run</em></p> <p><a href="https://i.stack.imgur.com/2ks5G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2ks5G.png" alt="enter image description here"></a></p> <p><strong>Steps 4:</strong> <em>Instant Run > Uncheck : Enable Instant Run</em></p> <p><a href="https://i.stack.imgur.com/elAOO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/elAOO.png" alt="enter image description here"></a></p>
49,949,526
Laravel mysql migrate error
<p>I recently format my mac book pro, after cloning the proyect from github and install the things I need like MySql and Sequel Pro I tried to migrate the database information but I get this error:</p> <pre><code> Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER' (SQL: select * from information_schema.tables where table_schema = fisica and table_name = migrations) Exception trace: 1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'") </code></pre> <p>Versions: </p> <p>Mysql 8.0.11</p> <p>Laravel 5.6.12</p> <p>PHP 7.1.14 (cli)</p> <pre><code>DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=fisica DB_USERNAME=xxx DB_PASSWORD=xxx </code></pre> <p>I created the database from Sequel PRO GUI</p>
50,372,200
10
5
null
2018-04-20 20:49:24.193 UTC
16
2021-10-08 12:25:19.317 UTC
null
null
null
null
8,161,086
null
1
66
php|mysql|laravel|laravel-5.6
43,681
<p>I finally found the solutions a days ago and I remembered this post. In the <code>config/database.php</code> file in mysql tag, the sql modes should be added in order to skip this error. <a href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-full" rel="noreferrer">https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-full</a></p> <p>My MySQL array ended up like this:</p> <pre><code> 'mysql' =&gt; [ 'driver' =&gt; 'mysql', 'host' =&gt; env('DB_HOST', '127.0.0.1'), 'port' =&gt; env('DB_PORT', '3306'), 'database' =&gt; env('DB_DATABASE', 'forge'), 'username' =&gt; env('DB_USERNAME', 'forge'), 'password' =&gt; env('DB_PASSWORD', ''), 'unix_socket' =&gt; env('DB_SOCKET', ''), 'charset' =&gt; 'utf8mb4', 'collation' =&gt; 'utf8mb4_unicode_ci', 'prefix' =&gt; '', 'strict' =&gt; true, 'engine' =&gt; null, 'modes' =&gt; [ 'ONLY_FULL_GROUP_BY', 'STRICT_TRANS_TABLES', 'NO_ZERO_IN_DATE', 'NO_ZERO_DATE', 'ERROR_FOR_DIVISION_BY_ZERO', 'NO_ENGINE_SUBSTITUTION', ], ], </code></pre>
3,034,162
Plotting a cumulative graph of python datetimes
<p>Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.</p> <p>Is it possible in matplotlib to graph the frequency of this event occurring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), without preprocessing this list? (e.g. passing datetime objects directly to some wonderful matplotlib function)</p> <p>Or do I need to turn this list of datetimes into a list of dictionary items, such as:</p> <pre><code>{"year": 1998, "month": 12, "date": 15, "events": 92} </code></pre> <p>and then generate a graph from this list?</p>
3,034,217
3
0
null
2010-06-13 22:34:49.937 UTC
9
2017-07-24 06:30:05.62 UTC
2017-07-24 06:30:05.62 UTC
null
3,632,894
null
221,001
null
1
18
python|datetime|graph|matplotlib
11,395
<p>This should work for you:</p> <pre><code>counts = arange(0, len(list_of_dates)) plot(list_of_dates, counts) </code></pre> <p>You can of course give any of the usual options to the <code>plot</code> call to make the graph look the way you want it. (I'll point out that matplotlib is very adept at handling dates and times.)</p> <p>Another option would be the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html" rel="noreferrer">hist function</a> - it has an option 'cumulative=True' that might be useful. You can create a cumulative histogram showing the number of events that have occurred as of any given date something like this:</p> <pre><code>from pyplot import hist from matplotlib.dates import date2num hist(date2num(list_of_dates), cumulative=True) </code></pre> <p>But this produces a bar chart, which might not be quite what you're looking for, and in any case making the date labels on the horizontal axis display properly will probably require some fudging.</p> <p><em>EDIT</em>: I'm getting the sense that what you really want is one point (or bar) per date, with the corresponding y-value being the number of events that have occurred up to (and including?) that date. In that case, I'd suggest doing something like this:</p> <pre><code>grouped_dates = [[d, len(list(g))] for d,g in itertools.groupby(list_of_dates, lambda k: k.date())] dates, counts = grouped_dates.transpose() counts = counts.cumsum() step(dates, counts) </code></pre> <p>The <code>groupby</code> function from the <code>itertools</code> module will produce the kind of data you're looking for: only a single instance of each date, accompanied by a list (an iterator, actually) of all the <code>datetime</code> objects that have that date. As suggested by Jouni in the comments, the <code>step</code> function will give a graph that steps up at each day on which events occurred, so I'd suggest using that in place of <code>plot</code>.</p> <p>(Hat tip to EOL for reminding me about <code>cumsum</code>)</p> <p>If you want to have one point for every day, regardless of whether any events occurred on that day or not, you'll need to alter the above code a bit:</p> <pre><code>from matplotlib.dates import drange, num2date date_dict = dict((d, len(list(g))) for d,g in itertools.groupby(list_of_dates, lambda k: k.date())) dates = num2date(drange(min(list_of_dates).date(), max(list_of_dates).date() + timedelta(1), timedelta(1))) counts = asarray([date_dict.get(d.date(), 0) for d in dates]).cumsum() step(dates, counts) </code></pre> <p>I don't think it'll really make a difference for the plot produced by the <code>step</code> function though.</p>
2,714,507
jQuery ajax upload with progress bar - no flash
<p>I am looking for a file uploader similar to <a href="http://www.uploadify.com/" rel="noreferrer">uploadify</a> with progress bar that doesn't rely on flash, preferably using jQuery - is this possible?</p>
2,714,755
3
1
null
2010-04-26 15:05:31.38 UTC
13
2013-03-27 18:45:34.613 UTC
2010-04-26 15:14:05.693 UTC
null
94,278
null
94,278
null
1
20
jquery|ajax|post|upload
66,719
<p>Sure, it's possible. A couple sites with different code and tutorials are:</p> <ul> <li><a href="http://github.com/drogus/jquery-upload-progress" rel="noreferrer">http://github.com/drogus/jquery-upload-progress</a> (ninja'd by DrJokepu ;)</li> <li><a href="http://web.archive.org/web/20120414125425/http://t.wits.sg/2008/06/25/howto-php-and-jquery-upload-progress-bar" rel="noreferrer">http://t.wits.sg/2008/06/25/howto-php-and-jquery-upload-progress-bar/</a></li> </ul>
2,756,923
Javascript if (j === null) do nothing
<p>I'm using <a href="http://www.curvycorners.net/" rel="nofollow noreferrer">CurvyCorners</a> to make my corners curvy in IE, only thing is that when it reads the CSS it takes all the webkit properties and shows me an alert <code>curvyCorners.alert("No object with ID " + arg + " exists yet.\nCall curvyCorners(settings, obj) when it is created.");</code>.</p> <p>How can I just set this if statement to do nothing?</p> <pre><code>if (j === null) do nothing(); //but in real script </code></pre> <p>Thanks :)</p>
2,756,933
5
0
null
2010-05-03 08:37:01.65 UTC
1
2020-04-10 11:56:39.023 UTC
2010-05-03 08:48:01.11 UTC
null
58,635
null
287,047
null
1
5
javascript|html
38,112
<p>Do you have access to the code? If so, you can add this code to the start of the curvyCorners function definition:</p> <pre><code>if (!obj) return; </code></pre> <p>This will quit the curvyCorners function silently if the element doesn't exist.</p>
38,709,886
Call route from button click laravel
<p>I am using the Laravel framework and the blade templating engine for one of my projects, where I have a route which looks like </p> <pre><code>Route::get('/problems/{problem-id}/edit', 'AdminController@editProblem'); </code></pre> <p>I have <strong>editProblem</strong> method in <strong>AdminController</strong> which returns a view</p> <pre><code>public function editProblem(Problem $problem) { return view('admin.problem-edit', compact('problem')); } </code></pre> <p>and I have a button on a view which looks like</p> <pre><code>&lt;button class="btn btn-xs btn-info pull-right"&gt;Edit&lt;/button&gt; </code></pre> <p>Now I want to call this route with the <code>$problem-&gt;id</code> when the button will be clicked. I need to pass these value on the route.</p> <p>how can I do that?</p>
38,710,638
4
0
null
2016-08-02 00:11:26.13 UTC
5
2022-02-24 04:16:26.773 UTC
2018-01-18 07:59:58.85 UTC
null
4,426,099
null
4,426,099
null
1
13
php|laravel|laravel-5|routes|balde
112,148
<h3>In my opnion, you should use url() Laravel method</h3> <p>To call you route with the problem's id you can do:</p> <pre><code>&lt;a href=&quot;{{ url('/problems/' . $problem-&gt;id . '/edit') }}&quot; class=&quot;btn btn-xs btn-info pull-right&quot;&gt;Edit&lt;/a&gt; </code></pre> <p>I used an anchor tag, but it will be rendered like you button tag because I kept the same style class you have defined.</p> <h3>Why you should use url() method ?</h3> <p>The reason is simple, the url method will get the full url to your controller. If you don't use this, href link will get appended with current url.</p> <p>For example, supose you button is located inside a given page</p> <blockquote> <p>yourdomain.com/a-given-page/</p> </blockquote> <p>when someone click in your button, the result will be:</p> <blockquote> <p>yourdomain.com/a-given-page/problems/{problem-id}/edit</p> </blockquote> <p>when you would like to get this:</p> <blockquote> <p>yourdomain.com/problems/{problem-id}/edit</p> </blockquote> <h3>Some considerations about your editProblem method</h3> <p>Your route has the '$id', so you need to receive this '$id' in your method</p> <pre><code>public function editProblem($problem_id) { $problem = \App\Problem::find($problem_id); //If you have your model 'Problem' located in your App folder return view('admin.problem-edit', compact('problem')); } </code></pre>
54,101,923
1006 Connection closed abnormally error with python 3.7 websockets
<p>I'm having the same problem as this github issue with python websockets: <a href="https://github.com/aaugustin/websockets/issues/367" rel="noreferrer">https://github.com/aaugustin/websockets/issues/367</a></p> <p>The proposed solution isn't working for me though. The error I'm getting is:</p> <p>websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason</p> <p>This is my code:</p> <pre><code>async def get_order_book(symbol): with open('test.csv', 'a+') as csvfile: csvw = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) DT = Data(data=data, last_OB_id=ob_id, last_TR_id=tr_id, sz=10, csvw=csvw) while True: if not websocket.open: print('Reconnecting') websocket = await websockets.connect(ws_url) else: resp = await websocket.recv() update = ujson.loads(resp) DT.update_data(update) async def get_order_books(): r = requests.get(url='https://api.binance.com/api/v1/ticker/24hr') await asyncio.gather(*[get_order_book(data['symbol']) for data in r.json()]) if __name__ == '__main__': asyncio.run(get_order_books()) </code></pre> <p>The way I've been testing it is by closing my internet connection, but after a ten second delay it still returns the 1006 error.</p> <p>I'm running Python 3.7 and Websockets 7.0.</p> <p>Let me know what your thoughts are, thanks!</p>
54,660,106
6
0
null
2019-01-09 01:06:30.653 UTC
9
2021-08-12 00:25:06.003 UTC
null
null
null
null
4,696,535
null
1
18
python|python-3.x|websocket|python-asyncio
27,749
<p>So I found the solution:</p> <p>When the connection closes, it breaks out of the while loop for some reason. So in order to keep the websocket running you have to surround </p> <pre><code>resp = await websocket.recv() </code></pre> <p>with try ... except and have </p> <pre><code>print('Reconnecting') websocket = await websockets.connect(ws_url) </code></pre> <p>in the exception handling part.</p>
50,670,326
How to check if point is placed inside contour?
<p>I have drawn a contour around extreme points. Inside polygon figure I have others points. How to check if they are inside contour?</p>
50,670,359
1
0
null
2018-06-03 19:40:19.633 UTC
9
2022-08-15 11:43:30.757 UTC
2022-08-15 11:43:30.757 UTC
null
6,885,902
null
8,291,684
null
1
17
python|opencv|contour|opencv3.0
15,493
<p>You can use the <code>cv2.pointPolygonTest()</code> function available in OpenCV.</p> <p>For example:</p> <p><code>dist = cv2.pointPolygonTest(cnt,(50,50),True)</code></p> <p>In this example we are checking whether the coordinate <code>(50, 50)</code> is present withing the contour <code>cnt</code></p> <ol> <li><p><code>dist</code> returns one of the following three:</p> <ul> <li><strong>Positive</strong> value if the point is <strong>inside</strong> the contour</li> <li><strong>Negative</strong> value if the point is <strong>outside</strong> the contour</li> <li><strong>Zero</strong> if the point is <strong>on</strong> the contour</li> </ul> </li> <li><p>Within the function <code>cv2.pointPolygonTest()</code> the third parameter decides whether you want one of the following two :</p> <ul> <li>If it is <strong>True</strong>, <code>dist</code> returns either the positive or negative distance of the point, if it is either inside or outside the contour respectively.</li> <li>On the other hand, if it is set to <strong>False</strong>, it returns +1, -1 or 0 depending on the point lying inside, outside or on the contour respectively</li> </ul> </li> </ol> <p>See <a href="https://docs.opencv.org/3.1.0/d5/d45/tutorial_py_contours_more_functions.html" rel="nofollow noreferrer">THE DOCS</a> for more details</p> <h2><strong>Illustration:</strong></h2> <p>I added an example to show how it works. I considered the following image for which a contour was obtained:</p> <p><a href="https://i.stack.imgur.com/ZEMwF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZEMwF.jpg" alt="enter image description here" /></a></p> <p>I assumed the following points to be used as illustration:</p> <p><code>(50, 70), (170, 152), (152, 48)</code></p> <p><a href="https://i.stack.imgur.com/9YKpE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9YKpE.jpg" alt="enter image description here" /></a></p> <pre><code>dist1 = cv2.pointPolygonTest(contours[0], (50, 70), True) #green dist2 = cv2.pointPolygonTest(contours[0], (170, 152), True) #blue dist3 = cv2.pointPolygonTest(contours[0], (152, 48), True) #red print('dist1 : ', dist1) print('dist2 : ', dist2) print('dist3 : ', dist3) </code></pre> <p><strong>Output:</strong></p> <pre><code>('dist1 : ', -45.17742799230607) ('dist2 : ', 49.9799959983992) ('dist3 : ', -0.0) </code></pre>
49,377,231
When to use Rc vs Box?
<p>I have the following code which uses both <code>Rc</code> and <code>Box</code>; what is the difference between those? Which one is better?</p> <pre><code>use std::rc::Rc; fn main() { let a = Box::new(1); let a1 = &amp;a; let a2 = &amp;a; let b = Rc::new(1); let b1 = b.clone(); let b2 = b.clone(); println!(&quot;{} {}&quot;, a1, a2); //=&gt; 1 1 println!(&quot;{} {}&quot;, b1, b2); //=&gt; 1 1 } </code></pre> <p><a href="https://play.rust-lang.org/?gist=f969bf51c9ff678d7f7267794bf0218f&amp;version=stable" rel="noreferrer">playground link</a></p>
49,379,201
2
0
null
2018-03-20 05:59:06.893 UTC
10
2022-04-28 04:17:59.757 UTC
2022-04-28 04:17:59.757 UTC
null
8,776,746
null
1,125,621
null
1
32
rust|reference-counting
14,659
<p><a href="https://doc.rust-lang.org/std/rc/" rel="noreferrer"><code>Rc</code></a> provides shared ownership so by default its contents can't be mutated, while <a href="https://doc.rust-lang.org/std/boxed/" rel="noreferrer"><code>Box</code></a> provides exclusive ownership and thus mutation is allowed:</p> <pre><code>use std::rc::Rc; fn main() { let mut a = Box::new(1); let mut b = Rc::new(1); *a = 2; // works *b = 2; // doesn't } </code></pre> <p>In addition <code>Rc</code> cannot be sent between threads, because it doesn't implement <code>Send</code>.</p> <p>The bottom line is they are meant for different things: if you don't need shared access, use <code>Box</code>; otherwise, use <code>Rc</code> (or <code>Arc</code> for multi-threaded shared usage) and keep in mind you will be needing <code>Cell</code> or <code>RefCell</code> for internal mutability.</p>
35,280,479
Can I choose where my conda environment is stored?
<p>Can I change the path /Users/nolan/miniconda/envs/ to another one when creating a virtual environment ? I'd like it to be specific to my project directory. (As we can do with virtualenv)</p> <pre><code>$conda info -e Using Anaconda Cloud api site https://api.anaconda.org # conda environments: # _build /Users/nolan/miniconda/envs/_build myen3 /Users/nolan/miniconda/envs/myen3 nolanemirot /Users/nolan/miniconda/envs/nolanemirot root * /Users/nolan/miniconda </code></pre>
35,303,953
4
0
null
2016-02-08 22:20:46.217 UTC
17
2021-09-21 09:18:05.687 UTC
null
null
null
null
2,201,037
null
1
50
conda
51,057
<p>You can change the environments directory by editing your .condarc file found in your user directory. Add the following specifying the path to the directory you want:</p> <pre><code>envs_dirs: - /Users/nolan/newpath </code></pre>
53,461,830
Send message using Django Channels from outside Consumer class
<p>I am building an online game, which uses Django channels 2.1.5 for websockets.</p> <p>I am able to build the connection between the client and the server, and also able to send data between them only inside the consumer class:</p> <pre><code>from channels.generic.websocket import WebsocketConsumer import json from . import controller class GameConsumer(WebsocketConsumer): def connect(self): self.accept() print("Wohooo .. Connected to client!") self.render() controller.startTurn() def render(self, type="render", message=None): self.send(controller.renderMap(type, message)) def disconnect(self, close_code): print("WebSocket connection is lost...") def receive(self, text_data): text_data_json = json.loads(text_data) controller.handleRecieved(text_data) ... </code></pre> <p>Now, What I wish to do, is to call the function <strong>render</strong>, -which is inside the consumer class-, from another module</p> <p>I tried this:</p> <pre><code>from .. import consumer def sendDeployments(owner, armies): type = "renderDeployments" message = owner + " has " + str(armies) + " to deploy" dummyConsumer = consumer.GameConsumer() consumer.GameConsumer.render(type, message) </code></pre> <p>But failed because I can't use the "self" parameter from outside the class.</p> <p>Can anybody think of a way to achieve my goal?</p> <p>Ps: I don't care about synchronization at this occasion.</p>
53,495,618
3
0
null
2018-11-24 19:52:57.857 UTC
11
2019-11-18 18:09:42.957 UTC
2019-11-18 18:09:42.957 UTC
null
6,250,155
null
7,406,460
null
1
22
python|django|websocket|django-channels
13,168
<p>Firstly you need your consumer instance to subscribe to a group. </p> <pre><code>from asgiref.sync import async_to_sync class GameConsumer(WebsocketConsumer): def connect(self): self.accept() self.render() async_to_sync(self.add_group)('render_updates_group') controller.startTurn() ... </code></pre> <p>Then if you are outside of your consumer you will need to send a message to that group so that all the consumers that have registered onto the group get the message.</p> <pre><code>from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def sendDeployments(owner, armies): type = "renderDeployments" message = owner + " has " + str(armies) + " to deploy" channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'render_updates_group', {'type': 'render', 'message': message} ) </code></pre> <p>However, you also need to remember to remove your consumer from the group when it disconnects.</p> <pre><code>class GameConsumer(WebsocketConsumer): .... def disconnect(self, close_code): async_to_sync(self.group_name)('render_updates_group') </code></pre> <p>If you want to limit which open connections get this render message you need to build your group name accordingly. </p> <p>eg if you are thinking about some online game then maybe you include a <code>MATCH-ID</code> in the group name that is shared by all connections for the same match.</p> <p>A good reference for this is the <a href="https://channels.readthedocs.io/en/latest/topics/channel_layers.html" rel="noreferrer">channels Layers documentation</a> but do remember when running this in production you will need a messaging layer (normally Redis) set up.</p>
42,680,980
How to chain two Completable in RxJava2
<p>I have two Completable. I would like to do following scenario: If first Completable gets to onComplete , continue with second Completable. The final results would be onComplete of second Completable.</p> <p>This is how I do it when I have Single <strong>getUserIdAlreadySavedInDevice()</strong> and Completable <strong>login()</strong>:</p> <pre><code>@Override public Completable loginUserThatIsAlreadySavedInDevice(String password) { return getUserIdAlreadySavedInDevice() .flatMapCompletable(s -&gt; login(password, s)) } </code></pre>
42,684,401
5
0
null
2017-03-08 20:08:53.053 UTC
13
2021-11-10 17:12:27.777 UTC
2017-03-09 11:45:11.613 UTC
null
7,045,114
null
2,959,120
null
1
80
java|rx-java|rx-java2
42,007
<p>You are looking for <code>andThen</code> operator.</p> <blockquote> <p>Returns a Completable that first runs this Completable and then the other completable.</p> </blockquote> <pre><code>firstCompletable .andThen(secondCompletable) </code></pre> <p>In general, this operator is a "replacement" for a <code>flatMap</code> on <code>Completable</code>:</p> <pre><code>Completable andThen(CompletableSource next) &lt;T&gt; Maybe&lt;T&gt; andThen(MaybeSource&lt;T&gt; next) &lt;T&gt; Observable&lt;T&gt; andThen(ObservableSource&lt;T&gt; next) &lt;T&gt; Flowable&lt;T&gt; andThen(Publisher&lt;T&gt; next) &lt;T&gt; Single&lt;T&gt; andThen(SingleSource&lt;T&gt; next) </code></pre>
42,822,948
How should I handle events in Vuex?
<p>I am used to using a global event bus to handle cross-component methods. For example:</p> <pre><code>var bus = new Vue(); ... //Component A bus.$emit('DoSomethingInComponentB'); ... //Component B bus.$on('DoSomethingInComponentB', function(){ this.doSomething() }) </code></pre> <p>However, I am building a larger project, which requires global state management. Naturally, I want to use Vuex.</p> <p>While this bus pattern works with Vuex, it seems wrong. I have seen Vuex recommended as a <strong>replacement</strong> for this pattern.</p> <p>Is there a way to run methods in components from Vuex? How should I approach this?</p>
42,824,182
3
0
null
2017-03-15 23:57:52.36 UTC
12
2022-07-15 19:48:51.59 UTC
null
null
null
null
2,779,909
null
1
36
vue.js|vuejs2|vuex
36,149
<p><a href="https://vuex.vuejs.org/en" rel="nofollow noreferrer">Vuex</a> and <a href="https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication" rel="nofollow noreferrer">event bus</a> are two different things in the sense that vuex manages central state of your application while event bus is used to communicate between different components of your app.</p> <p>You can execute vuex mutation or actions from a component and also raise events from vuex's actions.</p> <p>As the <a href="https://vuex.vuejs.org/en/actions.html" rel="nofollow noreferrer">docs</a> says:</p> <blockquote> <p>Actions are similar to mutations, the difference being that:</p> <ul> <li>Instead of mutating the state, actions commit mutations.</li> <li>Actions can contain arbitrary asynchronous operations.</li> </ul> </blockquote> <p>So you can raise an event via bus from actions and you can call an action from any component method.</p>
32,133,836
remove shadow below AppBarLayout widget android
<p>When using <code>AppBarLayout</code> widget in design support library, a shadow appears on the bottom of the toolbar. How can I remove that shadow?</p>
32,325,432
10
0
null
2015-08-21 06:35:11.267 UTC
13
2022-03-07 07:17:10.533 UTC
2017-12-18 18:15:29.19 UTC
null
2,804,761
null
5,219,069
null
1
113
android|android-layout
40,289
<p>Simply use <code>app:elevation="0dp"</code> inside "AppBarLayout" to remove the shadow. It has always worked for me. Hope it works for you.</p>
28,099,441
Define a recursive function within a function in Go
<p>I am trying to define a recursive function within another function in Go but I am struggling to get the right syntax. I am looking for something like this:</p> <pre><code>func Function1(n) int { a := 10 Function2 := func(m int) int { if m &lt;= a { return a } return Function2(m-1) } return Function2(n) } </code></pre> <p>I'd like to keep Function2 inside the scope of Function1 as it is accessing some elements of its scope.</p> <p>How can I do this in Go?</p> <p>Many thanks</p>
28,099,510
2
0
null
2015-01-22 21:58:10.393 UTC
5
2018-10-05 19:00:26.767 UTC
2018-01-14 07:20:12.317 UTC
null
1,705,598
null
2,641,547
null
1
29
function|recursion|go
7,945
<p>You can't access <code>Function2</code> inside of it if it is in the line where you declare it. The reason is that you're not referring to a <em>function</em> but to a <em>variable</em> (whose type is a function) and it will be accessible only after the declaration.</p> <p>Quoting from <a href="https://golang.org/ref/spec#Declarations_and_scope" rel="noreferrer">Spec: Declarations and scope:</a></p> <blockquote> <p>The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.</p> </blockquote> <p>In your example <code>Function2</code> is a variable declaration, and the VarSpec is:</p> <pre><code>Function2 := func(m int) int { if m &lt;= a { return a } return Function2(m-1) } </code></pre> <p>And as the quote form the language spec describes, the variable identifier <code>Function2</code> will only be in scope after the declaration, so you can't refer to it inside the declaration itself. For details, see <a href="https://stackoverflow.com/questions/52503560/understanding-variable-scope-in-go/52506086#52506086">Understanding variable scope in Go</a>.</p> <p>Declare the <code>Function2</code> variable first, so you can refer to it from the <a href="https://golang.org/ref/spec#Function_literals" rel="noreferrer">function literal</a>:</p> <pre><code>func Function1(n int) int { a := 10 var Function2 func(m int) int Function2 = func(m int) int { if m &lt;= a { return a } return Function2(m - 1) } return Function2(n) } </code></pre> <p>Try it on <a href="http://play.golang.org/p/fD6fjED8oN" rel="noreferrer">Go Playground</a>.</p>
28,089,942
Difference between "fill" and "expand" options for tkinter pack method
<p>I know this is a too trivial question, but I am new to python, and I have just started using the <code>tkinter</code> module. I have actually looked up about it everywhere, and I am unable to find the satisfactory answer. I found the following: </p> <blockquote> <p><code>fill</code> option: it determines whether to use up more space or keep "one's own" dimensions.</p> <p><code>expand</code> option: it deals with the expansion of parent widget.</p> </blockquote> <p>The <strong>problem</strong> is that these two sound more or less <em>the same</em>. I even tried out a few examples by toggling between the 4 values of <code>fill</code> and 2 values of <code>expand</code> but received more or less the same output in 2 or 3 cases, because of which I have this query. Any help would be appreciated in this regards. Thanks in advance!</p>
28,090,362
3
0
null
2015-01-22 13:26:25.837 UTC
20
2022-02-07 23:12:22.173 UTC
2015-01-22 14:46:48.47 UTC
null
3,924,118
null
4,233,030
null
1
57
python|tkinter
100,978
<p>From <a href="https://web.archive.org/web/20201112024617/http://effbot.org/tkinterbook/pack.htm" rel="nofollow noreferrer">effbot</a>:</p> <blockquote> <p>The <strong>fill</strong> option tells the manager that the widget wants fill the entire space assigned to it. The value controls how to fill the space; <strong>BOTH</strong> means that the widget should expand both horizontally and vertically, <strong>X</strong> means that it should expand only horizontally, and <strong>Y</strong> means that it should expand only vertically.</p> <p>The <strong>expand</strong> option tells the manager to assign additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the <strong>expand</strong> option set to a non-zero value.</p> </blockquote> <p>So <code>fill</code> tells the widget to grow to as much space is available for it in the direction specified, <code>expand</code> tells the master to take any space that is not assigned to any widget and distribute it to all widgets that have a non-zero <code>expand</code> value.</p> <p>The difference becomes clear when running this example:</p> <pre><code>import Tkinter as tk root = tk.Tk() root.geometry('200x200+200+200') tk.Label(root, text='Label', bg='green').pack(expand=1, fill=tk.Y) tk.Label(root, text='Label2', bg='red').pack(fill=tk.BOTH) root.mainloop() </code></pre> <p>You can see that the label with <code>expand=1</code> gets assigned as much space as available for it, but only occupies it in the direction specified, Y. The label with <code>fill=tk.BOTH</code> expands in both directions, but has less space available.</p> <p><img src="https://i.stack.imgur.com/BOBMS.png" alt="Expand vs Fill" /></p>
22,579,666
error: out-of-line definition of 'test' does not match any declaration in 'B<dim>'
<p>I have a small problem that is killing me!! I don't know what seems to be wrong with the below code. I should be able to implement the function that is inherited from the super class, shouldn't I? but I get <code>error: out-of-line definition of 'test' does not match any declaration in 'B&lt;dim&gt;'</code> </p> <pre><code>template &lt;int dim&gt; class A { public: virtual double test() const ; }; template &lt;int dim&gt; class B : public A &lt;dim&gt; { }; template &lt;int dim&gt; double B&lt;dim&gt;::test () const { return 0; } </code></pre> <p>I am on a Mac using clang (Apple LLVM version 5.1).</p>
22,579,699
2
0
null
2014-03-22 15:35:52.207 UTC
3
2020-07-20 17:38:00.167 UTC
null
null
null
null
3,449,968
null
1
16
c++|macos|templates|inheritance|virtual
80,912
<p>Try </p> <pre><code>template &lt;int dim&gt; class B : public A &lt;dim&gt; { public: virtual double test () const; }; // Function definition template &lt;int dim&gt; double B&lt;dim&gt;::test () const { return 0; } </code></pre> <p>You still need to <em>define</em> the function declared the class declaration.</p>
46,441,893
connected component labeling in python
<p>How to implement connected component labeling in python with open cv? This is an image example:</p> <p><img src="https://i.stack.imgur.com/eGaIy.jpg" /></p> <p>I need connected component labeling to separate objects on a black and white image.</p>
46,442,154
2
0
null
2017-09-27 07:28:39.49 UTC
27
2020-02-18 20:56:01.697 UTC
2018-03-13 21:15:29.463 UTC
null
3,419,103
null
8,681,147
null
1
26
python-2.7|opencv|image-processing|connected-components
76,560
<p>The <a href="http://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#connectedcomponents" rel="noreferrer">OpenCV 3.0 docs for <code>connectedComponents()</code></a> don't mention Python but it actually is implemented. See for e.g. <a href="https://stackoverflow.com/questions/43547540/cv2-connectedcomponents-not-detecting-components">this SO question</a>. On OpenCV 3.4.0 and above, the docs do include the Python signatures, as can be seen on the <a href="https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#gaedef8c7340499ca391d459122e51bef5" rel="noreferrer">current master docs</a>.</p> <p>The function call is simple: <code>num_labels, labels_im = cv2.connectedComponents(img)</code> and you can specify a parameter <code>connectivity</code> to check for 4- or 8-way (default) connectivity. The difference is that 4-way connectivity just checks the top, bottom, left, and right pixels and sees if they connect; 8-way checks if any of the eight neighboring pixels connect. If you have diagonal connections (like you do here) you should specify <code>connectivity=8</code>. Note that it just numbers each component and gives them increasing integer labels starting at 0. So all the zeros are connected, all the ones are connected, etc. If you want to visualize them, you can map those numbers to specific colors. I like to map them to different hues, combine them into an HSV image, and then convert to BGR to display. Here's an example with your image:</p> <pre class="lang-py prettyprint-override"><code>import cv2 import numpy as np img = cv2.imread('eGaIy.jpg', 0) img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary num_labels, labels_im = cv2.connectedComponents(img) def imshow_components(labels): # Map component labels to hue val label_hue = np.uint8(179*labels/np.max(labels)) blank_ch = 255*np.ones_like(label_hue) labeled_img = cv2.merge([label_hue, blank_ch, blank_ch]) # cvt to BGR for display labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR) # set bg label to black labeled_img[label_hue==0] = 0 cv2.imshow('labeled.png', labeled_img) cv2.waitKey() imshow_components(labels_im) </code></pre> <p><a href="https://i.stack.imgur.com/gRWLH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gRWLH.png" alt="Labeled image"></a></p>
34,220,532
How to assign a value to a TensorFlow variable?
<p>I am trying to assign a new value to a tensorflow variable in python.</p> <pre><code>import tensorflow as tf import numpy as np x = tf.Variable(0) init = tf.initialize_all_variables() sess = tf.InteractiveSession() sess.run(init) print(x.eval()) x.assign(1) print(x.eval()) </code></pre> <p>But the output I get is</p> <pre><code>0 0 </code></pre> <p>So the value has not changed. What am I missing?</p>
34,220,750
8
0
null
2015-12-11 09:51:46.307 UTC
20
2019-12-13 18:33:53.317 UTC
2018-01-29 11:24:11.747 UTC
null
5,096,199
null
3,537,687
null
1
87
python|tensorflow|neural-network|deep-learning|variable-assignment
112,147
<p>In TF1, the statement <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/Variable#assign" rel="noreferrer"><code>x.assign(1)</code></a> does not actually assign the value <code>1</code> to <code>x</code>, but rather creates a <a href="https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/Operation" rel="noreferrer"><code>tf.Operation</code></a> that you have to explicitly <em>run</em> to update the variable.* A call to <a href="https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/Operation#run" rel="noreferrer"><code>Operation.run()</code></a> or <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session#run" rel="noreferrer"><code>Session.run()</code></a> can be used to run the operation:</p> <pre><code>assign_op = x.assign(1) sess.run(assign_op) # or `assign_op.op.run()` print(x.eval()) # ==&gt; 1 </code></pre> <p>(* In fact, it returns a <code>tf.Tensor</code>, corresponding to the updated value of the variable, to make it easier to chain assignments.)</p> <p>However, in TF2 <a href="https://www.tensorflow.org/api_docs/python/tf/Variable#assign" rel="noreferrer"><code>x.assign(1)</code></a> will now assign the value eagerly:</p> <pre><code>x.assign(1) print(x.numpy()) # ==&gt; 1 </code></pre>
47,077,210
Using styled-components with props and TypeScript
<p>I'm trying to integrate TypeScript into our project and so far I stumbled upon one issue with <a href="https://www.styled-components.com/" rel="noreferrer">styled-components</a> library.</p> <p>Consider this component</p> <pre><code>import * as React from &quot;react&quot;; import styled from &quot;styled-components/native&quot;; import { TouchableOpacity } from &quot;react-native&quot;; // -- types ----------------------------------------------------------------- // export interface Props { onPress: any; src: any; width: string; height: string; } // -- styling --------------------------------------------------------------- // const Icon = styled.Image` width: ${(p: Props) =&gt; p.width}; height: ${(p: Props) =&gt; p.height}; `; class TouchableIcon extends React.Component&lt;Props&gt; { // -- default props ------------------------------------------------------- // static defaultProps: Partial&lt;Props&gt; = { src: null, width: &quot;20px&quot;, height: &quot;20px&quot; }; // -- render -------------------------------------------------------------- // render() { const { onPress, src, width, height } = this.props; return ( &lt;TouchableOpacity onPress={onPress}&gt; &lt;Icon source={src} width={width} height={height} /&gt; &lt;/TouchableOpacity&gt; ); } } export default TouchableIcon; </code></pre> <p>Following line throws 3 errors, that are same in nature <code>&lt;Icon source={src} width={width} height={height} /&gt;</code></p> <blockquote> <p>Type {source: any; width: string; height: string;} is not assignable to type IntrinsicAttributes ... Property 'onPress' is missing in type {source: any; width: string; height: string;}</p> </blockquote> <p>Not entirely sure what this is and how to fix it, do I somehow need to declare these on <code>Icon</code> or something of this sort?</p> <p><strong>EDIT:</strong> typescript <code>v2.6.1</code>, styled-components <code>v2.2.3</code></p>
47,222,056
8
0
null
2017-11-02 14:02:06.36 UTC
21
2022-03-31 12:58:45.703 UTC
2021-08-21 08:16:18.96 UTC
null
6,904,888
null
911,930
null
1
79
javascript|reactjs|typescript|jsx|styled-components
99,201
<p><strong>This answer is outdated, the most current answer is here: <a href="https://stackoverflow.com/a/52045733/1053772">https://stackoverflow.com/a/52045733/1053772</a></strong></p> <p>As far as I can tell there is no official way (yet?) to do this, but you can solve it with a bit of trickery. First, create a <code>withProps.ts</code> file with the following content:</p> <pre><code>import * as React from 'react' import { ThemedStyledFunction } from 'styled-components' const withProps = &lt;U&gt;() =&gt; &lt;P, T, O&gt;(fn: ThemedStyledFunction&lt;P, T, O&gt;) =&gt; fn as ThemedStyledFunction&lt;P &amp; U, T, O &amp; U&gt; export { withProps } </code></pre> <p>Now, inside your <code>.tsx</code> files, use it like this:</p> <pre><code>// ... your other imports import { withProps } from './withProps' export interface IconProps { onPress: any; src: any; width: string; height: string; } const Icon = withProps&lt;IconProps&gt;()(styled.Image)` width: ${(p: IconProps) =&gt; p.width}; height: ${(p: IconProps) =&gt; p.height}; `; </code></pre> <p>And you should be good to go. It's definitely <em>not</em> ideal and hopefully there will be a way to provide generics to template literals soon in TS, but I guess that for now this is your best option.</p> <p>Credit is given where credit is due: I copypasted this from <a href="https://github.com/styled-components/styled-components/issues/630" rel="noreferrer">here</a></p>
32,429,076
Develop and Debug Atom Package
<p>I have just began working on <a href="https://atom.io/docs/">Atom.io</a> Package development, and based on <a href="https://atom.io/docs/v1.0.11/hacking-atom-package-word-count">this tutorial</a>, have learnt from how to create package development skelton file to how to publish your package.</p> <p>However, I do not know how to check/debug/develop your package. I know I can use Jasmine via <code>alt-cmd-I</code> or Developer Console (for Atom is based on Chromium), still if you want to check the behavior of your package, do I have to re-publish or install your package manually every time?</p>
32,435,735
2
0
null
2015-09-06 22:57:05.447 UTC
16
2017-03-26 17:37:57.98 UTC
null
null
null
null
2,775,013
null
1
31
atom-editor
8,250
<p>When working on packages locally, here's the recommended workflow:</p> <ul> <li>Clone your package from GitHub using <code>apm develop &lt;package-name&gt;</code>. This will clone the package's repo to your local <code>~/.atom/dev/packages/&lt;package-name&gt;</code></li> <li><code>cd</code> into this directory</li> <li>Start Atom in this directory using <code>atom -d .</code></li> </ul> <p>Now you can work on the package, make changes, etc. Once you're ready to reload, you can use <code>View &gt; Developer &gt; Reload Window</code> to restart Atom with the changed package.</p> <p>If you have your package sources locally on your machine, you can skip the first step (<code>apm develop</code>) and simply create a symbolic link from your sources to <code>~/.atom/dev/packages/&lt;package-name</code>.</p>
31,595,750
How to use Cordova-plugin-purchase to do in-app purchase with ionic framework?
<p>I have been struggling with the implementation of in-app purchase for both iOS and Andriod in ionic. I came across tutorials regarding both the <a href="https://github.com/j3k0/cordova-plugin-purchase">cordova-plugin-purchase</a> and the <a href="https://github.com/AlexDisler/ng-storekit">ng-storekit</a>, but seems like the tutorials were based on the <a href="https://github.com/j3k0/cordova-plugin-purchase/tree/v3.4.1">version 3.4.1</a> of cordova-plugin-purchase, and the latest version now has undergone huge modification that the code is no longer applicable. I tried following the demo and API guide on Cordova-plugin-purchase, but no luck. Even <code>window.store</code> or <code>window.storekit</code> returns false.</p> <p>Has anyone work with the latest version of Cordova-plugin-purchase in Ionic and successfully implement IAP? Any working examples demonstrating the initialisation and the purchase flow? Thank you very much.</p>
35,741,779
2
0
null
2015-07-23 18:49:19.587 UTC
8
2016-05-13 05:09:39.427 UTC
2015-07-23 19:03:29.643 UTC
null
4,198,060
null
4,198,060
null
1
16
cordova|in-app-purchase|ionic-framework
6,624
<p>Maybe this brand new plugin (iOS/Android supported) could help you:</p> <p><a href="https://github.com/AlexDisler/cordova-plugin-inapppurchase">https://github.com/AlexDisler/cordova-plugin-inapppurchase</a></p> <p>The author has written a recent post on his blog:</p> <p><a href="https://alexdisler.com/2016/02/29/in-app-purchases-ionic-cordova/">Add In App Purchases To Your Ionic Cordova App - Step By Step Guide With An Example App</a></p> <p>and there is also a complete Ionic demo app on his Github repo:</p> <p><a href="https://github.com/AlexDisler/cordova-inapppurchases-app">https://github.com/AlexDisler/cordova-inapppurchases-app</a></p>
6,254,447
Using pHash from .NET
<p>I am trying to use <a href="http://phash.org" rel="nofollow noreferrer">pHash</a> from .NET</p> <p>First thing I tried was to register (regsvr32) <code>phash.dll</code> and asked <a href="https://stackoverflow.com/questions/6233343/how-to-add-unmanaged-dll-to-show-up-in-add-references-com-tab">here</a> Second of all, i was trying to import using <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx" rel="nofollow noreferrer">DllImport</a> as shown below.</p> <pre><code> [DllImport(@".\Com\pHash.dll")] public static extern int ph_dct_imagehash( [MarshalAs(UnmanagedType.LPStr)] string file, UInt64 hash); </code></pre> <p>But when i try to access the method above during run-time, following error message shows up.<br /></p> <pre><code> Unable to find an entry point named 'ph_dct_imagehash' in DLL '.\Com\pHash.dll'. </code></pre> <p>What does "entry point" means and why am I getting the error?</p> <p>Thank you.</p> <p><strong>FYI</strong> - Here is the full source code</p> <pre><code>using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; namespace DetectSimilarImages { public partial class MainWindow : Window { [DllImport(@".\Com\pHash.dll")] public static extern int ph_dct_imagehash( [MarshalAs(UnmanagedType.LPStr)] string file, UInt64 hash); public MainWindow() { InitializeComponent(); Loaded += MainWindow_Loaded; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { try { UInt64 hash1 = 0, hash2 = 0; string firstImage = @"C:\Users\dance2die\Pictures\2011-01-23\177.JPG"; string secondImage = @"C:\Users\dance2die\Pictures\2011-01-23\176.JPG"; ph_dct_imagehash(firstImage, hash1); ph_dct_imagehash(secondImage, hash2); Debug.WriteLine(hash1); Debug.WriteLine(hash2); } catch (Exception ex) { } } } } </code></pre>
6,268,367
1
9
null
2011-06-06 15:36:43.163 UTC
9
2013-03-25 14:48:02.917 UTC
2017-05-23 12:02:27.96 UTC
null
-1
null
4,035
null
1
9
c#|.net|c++|dllimport
6,268
<p>The current Windows source code project (as of 7/2011) on <a href="http://msdn.microsoft.com/en-us/library/c1h23y6c%28v=vs.71%29.aspx" rel="nofollow noreferrer">phash.org</a> does not seem to export the ph_ API calls from the DLL. You will need to add these yourself by __declspec(dllexport) at the beginning of the line in pHash.h like so:</p> <pre><code>__declspec(dllexport) int ph_dct_imagehash(const char* file,ulong64 &amp;hash); </code></pre> <p>You should then see the export show up in the DLL using <a href="http://msdn.microsoft.com/en-us/library/c1h23y6c%28v=vs.71%29.aspx" rel="nofollow noreferrer">dumpbin</a></p> <pre><code>dumpbin /EXPORTS pHash.dll ... Dump of file pHash.dll ... 1 0 00047A14 closedir = @ILT+2575(_closedir) 2 1 00047398 opendir = @ILT+915(_opendir) 3 2 00047A4B ph_dct_imagehash = @ILT+2630(_ph_dct_imagehash) 4 3 000477B2 readdir = @ILT+1965(_readdir) 5 4 00047A00 rewinddir = @ILT+2555(_rewinddir) 6 5 000477AD seekdir = @ILT+1960(_seekdir) 7 6 00047AFA telldir = @ILT+2805(_telldir) </code></pre> <p>You should now be able to use this call from C#.</p> <p>however...</p> <p>I am getting a crash in the CImg code when I try to call this, so it seems there is some <a href="https://stackoverflow.com/questions/4001816/loading-pngs-with-cimg">more work to do here</a>...</p>
5,941,583
UIDatePicker in UIActionSheet on iPad
<p>In the iPhone version of my app, I have a <code>UIDatePicker</code> in a <code>UIActionSheet</code>. It appears correctly. I am now setting up the iPad version of the app, and the same <code>UIActionSheet</code> when viewed on the iPad appears as a blank blank box. </p> <p>Here is the code I am using:</p> <pre><code>UIDatePicker *datePickerView = [[UIDatePicker alloc] init]; datePickerView.datePickerMode = UIDatePickerModeDate; self.dateActionSheet = [[UIActionSheet alloc] initWithTitle:@"Choose a Follow-up Date" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Done", nil]; [self.dateActionSheet showInView:self.view]; [self.dateActionSheet addSubview:datePickerView]; [self.dateActionSheet sendSubviewToBack:datePickerView]; [self.dateActionSheet setBounds:CGRectMake(0,0,320, 500)]; CGRect pickerRect = datePickerView.bounds; pickerRect.origin.y = -95; datePickerView.bounds = pickerRect; </code></pre>
5,952,179
1
5
null
2011-05-09 19:34:53.763 UTC
9
2011-12-13 14:31:53.107 UTC
2011-05-09 22:02:36.933 UTC
null
300,129
null
300,129
null
1
15
iphone|ipad|uidatepicker|uiactionsheet
11,414
<p>I ended up creating a separate segment of code for the iPad Popover:</p> <pre><code>//build our custom popover view UIViewController* popoverContent = [[UIViewController alloc] init]; UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 344)]; popoverView.backgroundColor = [UIColor whiteColor]; datePicker.frame = CGRectMake(0, 44, 320, 300); [popoverView addSubview:toolbar]; [popoverView addSubview:datePicker]; popoverContent.view = popoverView; //resize the popover view shown //in the current view to the view's size popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 244); //create a popover controller UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent]; //present the popover view non-modal with a //refrence to the button pressed within the current view [popoverController presentPopoverFromBarButtonItem:self.navigationItem.leftBarButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; //release the popover content [popoverView release]; [popoverContent release]; </code></pre>
5,636,580
Force gfortran to stop program at first NaN
<p>To debug my application (fortran 90) I want to turn all NaNs to signalling NaN. </p> <p>With default settings my program works without any signals and just outputs NaN data in file. I want find the point, where NaN is generated. If I can recompile program with signalling NaN, I will get an <code>SIGFPE</code> signal at first point where first wrong floating operation reside.</p>
5,636,881
1
0
null
2011-04-12 14:09:53.797 UTC
9
2015-11-03 12:08:00.973 UTC
2013-10-29 14:46:58.443 UTC
null
196,561
null
196,561
null
1
18
gcc|fortran|nan|gfortran
11,592
<p>The flag you're looking for is <code>-ffpe-trap=invalid</code>; I usually add <code>,zero,overflow</code> to check for related floating point exceptions. </p> <pre><code>program nantest real :: a, b, c a = 1. b = 2. c = a/b print *, c,a,b a = 0. b = 0. c = a/b print *, c,a,b a = 2. b = 1. c = a/b print *,c,a,b end program nantest </code></pre> <p>Then compiling it and running it in a debugger gives:</p> <pre><code>$ gfortran -o nantest nantest.f90 -ffpe-trap=invalid,zero,overflow -g -static $ gdb nantest [...] (gdb) run Starting program: /scratch/ljdursi/Testing/fortran/nantest 0.50000000 1.0000000 2.0000000 Program received signal SIGFPE, Arithmetic exception. 0x0000000000400384 in nantest () at nantest.f90:13 13 c = a/b Current language: auto; currently fortran </code></pre> <p>With the intel fortran compiler (ifort), using the option <code>-fpe0</code> will do the same thing.</p> <p>It's a little tricker with C/C++ code; we have to actually insert a call to <code>feenableexcept()</code>, which enables floating point exceptions, and is defined in <code>fenv.h</code>;</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;fenv.h&gt; int main(int argc, char **argv) { float a, b, c; feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); a = 1.; b = 2.; c = a/b; printf("%f %f %f\n", a, b, c); a = 0.; b = 0.; c = a/b; printf("%f %f %f\n", a, b, c); a = 2.; b = 1.; c = a/b; printf("%f %f %f\n", a, b, c); return 0; } </code></pre> <p>but the effect is the same:</p> <pre><code>$ gcc -o nantest nantest.c -lm -g $ gdb ./nantest [...] (gdb) run Starting program: /scratch/s/scinet/ljdursi/Testing/exception/nantest 1.000000 2.000000 0.500000 Program received signal SIGFPE, Arithmetic exception. 0x00000000004005d0 in main (argc=1, argv=0x7fffffffe4b8) at nantest.c:17 17 c = a/b; </code></pre> <p>either way, you have a much better handle on where the errors are occuring.</p>
25,815,032
Finding Overlaps between interval sets / Efficient Overlap Joins
<h2>Overview:</h2> <p>I need to join two tables:</p> <p><code>ref</code> contains the time intervals (from <code>t1</code> to <code>t2</code>) along with an <code>id</code> for each interval and a <code>space</code> where this interval occurs.</p> <p><code>map</code> contains time intervals (<code>t1</code> to <code>t2</code>) each with a result <code>res</code> and its corresponding <code>space</code>.</p> <p>I wish to obtain/join all intervals (and their score) of <code>map</code> that fall within the intervals in <code>ref</code> onto <code>ref</code>.</p> <h2>example:</h2> <pre><code>ref &lt;- data.table(space=rep('nI',3),t1=c(100,300,500),t2=c(150,400,600),id=letters[1:3]) map &lt;- data.table(space=rep('nI',241),t1=seq(0,1200,by=5),t2=seq(5,1205,by=5),res=rnorm(241)) </code></pre> <p>they look like:</p> <pre><code>&gt; ref space t1 t2 id 1: nI 100 150 a 2: nI 300 400 b 3: nI 500 600 c &gt; map space t1 t2 res 1: nI 0 5 -0.7082922 2: nI 5 10 1.8251041 3: nI 10 15 0.2076552 4: nI 15 20 0.8047347 5: nI 20 25 2.3388920 --- 237: nI 1180 1185 1.0229284 238: nI 1185 1190 -0.3657815 239: nI 1190 1195 0.3013489 240: nI 1195 1200 1.2947271 241: nI 1200 1205 -1.5050221 </code></pre> <h2>(UPDATE) Solution</h2> <ul> <li><code>?data.table::foverlaps</code> is the key here. </li> </ul> <p>I need to join all the <code>map</code> intervals that occur <code>"within"</code> the intervals of <code>ref</code> and I am not interested in intervals that do not match this key so use <code>nomatch=0L</code>.</p> <pre><code>setkey(ref,space,t1,t2) foverlaps(map,ref,type="within",nomatch=0L) </code></pre> <p>which gives: </p> <pre><code>space t1 t2 id i.t1 i.t2 res 1: nI 100 150 a 100 105 -0.85202726 2: nI 100 150 a 105 110 0.79748876 3: nI 100 150 a 110 115 1.49894097 4: nI 100 150 a 115 120 0.47719957 5: nI 100 150 a 120 125 -0.95767896 6: nI 100 150 a 125 130 -0.51054673 7: nI 100 150 a 130 135 -0.08478700 8: nI 100 150 a 135 140 -0.69526566 9: nI 100 150 a 140 145 2.14917623 10: nI 100 150 a 145 150 -0.05348163 11: nI 300 400 b 300 305 0.28834548 12: nI 300 400 b 305 310 0.32449616 13: nI 300 400 b 310 315 1.16107248 14: nI 300 400 b 315 320 1.08550676 15: nI 300 400 b 320 325 0.84640788 16: nI 300 400 b 325 330 -2.15485447 17: nI 300 400 b 330 335 1.59115714 18: nI 300 400 b 335 340 -0.57588128 19: nI 300 400 b 340 345 0.23957563 20: nI 300 400 b 345 350 -0.60824259 21: nI 300 400 b 350 355 -0.84828189 22: nI 300 400 b 355 360 -0.43528701 23: nI 300 400 b 360 365 -0.80026281 24: nI 300 400 b 365 370 -0.62914234 25: nI 300 400 b 370 375 -0.83485164 26: nI 300 400 b 375 380 1.46922713 27: nI 300 400 b 380 385 -0.53965310 28: nI 300 400 b 385 390 0.98728765 29: nI 300 400 b 390 395 -0.66328893 30: nI 300 400 b 395 400 -0.08182384 31: nI 500 600 c 500 505 0.72566100 32: nI 500 600 c 505 510 2.27878366 33: nI 500 600 c 510 515 0.72974139 34: nI 500 600 c 515 520 -0.35358019 35: nI 500 600 c 520 525 -1.20697646 36: nI 500 600 c 525 530 -0.01719057 37: nI 500 600 c 530 535 0.06686472 38: nI 500 600 c 535 540 -0.40866088 39: nI 500 600 c 540 545 -1.02697573 40: nI 500 600 c 545 550 2.19822065 41: nI 500 600 c 550 555 0.57075648 42: nI 500 600 c 555 560 -0.52009726 43: nI 500 600 c 560 565 -1.82999177 44: nI 500 600 c 565 570 2.53776578 45: nI 500 600 c 570 575 0.85626293 46: nI 500 600 c 575 580 -0.34245708 47: nI 500 600 c 580 585 1.21679869 48: nI 500 600 c 585 590 1.87587020 49: nI 500 600 c 590 595 -0.23325264 50: nI 500 600 c 595 600 0.18845022 space t1 t2 id i.t1 i.t2 res </code></pre>
25,818,856
1
0
null
2014-09-12 18:59:39.76 UTC
10
2015-10-03 18:08:23.437 UTC
2014-09-13 01:41:37.47 UTC
null
3,566,491
null
3,566,491
null
1
25
r|data.table|dplyr
6,974
<p>Ha, nice timing :). Just a few days back, overlap joins (or interval joins) was implemented. in data.table The function is <code>foverlaps()</code> and is available from the <a href="https://github.com/Rdatatable/data.table">github project page</a>. Make sure to have a look at <code>?foverlaps</code>.</p> <pre><code>setkey(ref, space, t1, t2) foverlaps(map, ref, type="within", nomatch=0L) </code></pre> <p>I think this is what you're after. This'll result in the join result only where there's a match, and it'll check for <code>t1,t2</code> overlaps between <code>ref</code> and <code>map</code> within <code>space</code> identifier.. If you don't want that, just remove <code>space</code> from the key column. And if you want all matches, remove <code>nomatch=0L</code> - the default is <code>nomatch=NA</code> which returns all.</p> <p>The function is new (but has been rigorously tested) and is therefore not feature complete. If you've any suggestions for improvement or come across any issues, please feel free to file an issue.</p>
25,546,417
Where can I download mysql jdbc jar from?
<p>I installed and tried to use jasper report studio. The first brick wall you hit when you try to create a datasource for your reports is </p> <pre><code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver </code></pre> <p>The forums say I need to install a jar on the classpath. I have no idea how to do this, so the first hurdle is how to get the jar. The only place I can find is this: </p> <p><a href="http://dev.mysql.com/downloads/connector/j/" rel="noreferrer">http://dev.mysql.com/downloads/connector/j/</a> </p> <p>but this unfortunately gives you an msi installer, not a jar. I don't want to install stuff, just get the jar.</p> <p>I have mysql DB installed, had have trawled through the install dir in program files, but can't find the jar.</p> <p>Anyone know the official (not malware site) way to get hold of the mysql jar? It seems bizarre that its so hard to find.</p> <p>I have windows 8 64 bit and mysql 5.6.</p>
25,548,704
3
0
null
2014-08-28 10:21:25.743 UTC
7
2017-09-06 06:41:31.127 UTC
2014-08-28 19:11:12.413 UTC
null
466,862
null
1,072,187
null
1
58
mysql|jdbc|jar
187,229
<p>Go to <a href="http://dev.mysql.com/downloads/connector/j" rel="noreferrer">http://dev.mysql.com/downloads/connector/j</a> and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.</p> <p>Download zip file and extract it, with in that you will find <code>mysql-connector-XXX.jar</code> file</p> <p>If you are using maven then you can add the dependency from the link <a href="http://mvnrepository.com/artifact/mysql/mysql-connector-java" rel="noreferrer">http://mvnrepository.com/artifact/mysql/mysql-connector-java</a></p> <p>Select the version you want to use and add the dependency in your <code>pom.xml</code> file</p>
28,478,945
React.js can't change checkbox state
<p>I created this simple TODO list, and when I want to check the checkbox I can't.</p> <pre><code>import React from 'react'; const TodoItem = React.createClass({ render() { return ( &lt;div&gt; &lt;span&gt;{this.props.todo}&lt;/span&gt; &lt;input type="checkbox" checked={this.props.done} /&gt; &lt;/div&gt; ); } }); export default TodoItem; </code></pre> <p>The parent:</p> <pre><code>import React from 'react'; import TodoItem from './TodoItem'; import AddTodo from './AddTodo'; const TodoList = React.createClass({ getInitialState() { return { todos: [{ todo: 'some text', done:false },{ todo: 'some text2', done:false }, { todo: 'some text3', done:true }] }; }, addTodo (childComponent) { var todoText = childComponent.refs.todoText.getDOMNode().value; var todo = { todo: todoText, done:false }; var todos = this.state.todos.concat([todo]); this.setState({ todos:todos }); childComponent.refs.todoText.getDOMNode().value = ''; }, render() { var Todos = this.state.todos.map(function(todo) { return ( &lt;TodoItem todo={todo.todo} done={todo.done} /&gt; ) }); return ( &lt;div&gt; {Todos} &lt;AddTodo addTodo={this.addTodo}/&gt; &lt;/div&gt; ); } }); export default TodoList; </code></pre>
28,479,290
3
0
null
2015-02-12 13:40:40.39 UTC
2
2020-02-03 17:43:13.84 UTC
2016-04-14 00:03:00.357 UTC
null
140,448
null
4,159,572
null
1
39
javascript|reactjs
73,174
<p>When you haven't specified an <code>onChange</code> handler on your inputs React will render the input field as read-only.</p> <pre><code>getInitialState() { return { done: false }; } </code></pre> <p>and</p> <pre><code>&lt;input type="checkbox" checked={this.state.done || this.props.done } onChange={this.onChange} /&gt; </code></pre>
52,628,473
How to add multiple policies in action using Authorize attribute using identity 2.0?
<p>I am identity 2.1.2 with asp.net core 2.0, I have application claim table which have claim type and claim value i.e Assets ,Assets Edit,Assets, Assets View, where claim types are same with distinct claim values and I am creating policies using claim type name which is working fine for me no clue about how to add multiple policies in one action. Below code is being used in startup file to create policies.</p> <pre><code>services.AddAuthorization(options =&gt; { var dbContext = SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder&lt;MyDBContext&gt;(), Configuration.GetConnectionString(&quot;TestIdentityClaimAuth&quot;)).Options; var dbCon = new MyDBContext(dbContext); //Getting the list of application claims. var applicationClaims = dbCon.ApplicationClaims.ToList(); var strClaimValues = string.Empty; List&lt;ClaimVM&gt; lstClaimTypeVM = new List&lt;ClaimVM&gt;(); IEnumerable&lt;string&gt; lstClaimValueVM = null;// new IEnumerable&lt;string&gt;(); lstClaimTypeVM = (from dbAppClaim in dbCon.ApplicationClaims select new ClaimVM { ClaimType = dbAppClaim.ClaimType }).Distinct().ToList(); foreach (ClaimVM objClaimType in lstClaimTypeVM) { lstClaimValueVM = (from dbClaimValues in dbCon.ApplicationClaims where dbClaimValues.ClaimType == objClaimType.ClaimType select dbClaimValues.ClaimValue).ToList(); options.AddPolicy(objClaimType.ClaimType, policy =&gt; policy.RequireClaim(objClaimType.ClaimType, lstClaimValueVM)); lstClaimValueVM = null; } }); </code></pre> <p>And in my controller using the Autherize attribute like this.</p> <pre><code>[Authorize(Policy = &quot;Assets Edit&quot;)] </code></pre> <p>Please shade some light on it thanks in advance.</p>
52,639,938
3
1
null
2018-10-03 13:44:28.987 UTC
11
2021-02-27 13:21:53.997 UTC
2020-08-26 20:43:27.49 UTC
null
6,844,481
null
4,046,078
null
1
14
c#|asp.net-core|claims-based-identity
13,314
<p>For multiple policys, you could implement your own <code>AuthorizeAttribute</code>. </p> <ul> <li><p><code>MultiplePolicysAuthorizeAttribute</code> </p> <pre><code>public class MultiplePolicysAuthorizeAttribute : TypeFilterAttribute { public MultiplePolicysAuthorizeAttribute(string policys, bool isAnd = false) : base(typeof(MultiplePolicysAuthorizeFilter)) { Arguments = new object[] { policys, isAnd }; } } </code></pre></li> <li><p>MultiplePolicysAuthorizeFilter </p> <pre><code>public class MultiplePolicysAuthorizeFilter : IAsyncAuthorizationFilter { private readonly IAuthorizationService _authorization; public string Policys { get; private set; } public bool IsAnd { get; private set; } public MultiplePolicysAuthorizeFilter(string policys, bool isAnd, IAuthorizationService authorization) { Policys = policys; IsAnd = isAnd; _authorization = authorization; } public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var policys = Policys.Split(";").ToList(); if (IsAnd) { foreach (var policy in policys) { var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy); if (!authorized.Succeeded) { context.Result = new ForbidResult(); return; } } } else { foreach (var policy in policys) { var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy); if (authorized.Succeeded) { return; } } context.Result = new ForbidResult(); return; } } } </code></pre></li> <li><p>only require one of the policy</p> <pre><code>[MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete")] </code></pre></li> <li><p>only require all the policys</p> <pre><code>[MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete", true)] </code></pre></li> </ul>
49,104,247
In Redux, where does the state actually get stored?
<p>I searched a bit about this question but found very vague answers. In redux, we know that the state is stored as an object. But where is this state stored actually? Is it somehow saved as a file which can be accessed by us later on? What I know is that it does not store it in a cookie format or in the browser's local storage.</p>
49,104,335
2
0
null
2018-03-05 05:52:31.103 UTC
7
2020-11-19 10:59:34.98 UTC
2018-04-26 02:00:56.373 UTC
null
3,928,341
null
5,864,426
null
1
36
javascript|reactjs|redux
17,832
<p>The state in Redux is stored in memory, <a href="https://github.com/reduxjs/redux/blob/master/src/createStore.ts#L61" rel="noreferrer">in the Redux store</a>.</p> <p>This means that, if you refresh the page, that state gets wiped out.</p> <p>You can imagine that store looking something like this:</p> <pre><code>function createStore(reducer, initialState) { let state = initialState // &lt;-- state is just stored in a variable that lives in memory function getState() { return state } function dispatch(action) { state = reducer(state, action) // &lt;-- state gets updated using the returned value from the reducer return action } return { getState, dispatch } } </code></pre> <p>The state in redux is just a variable that persists in memory because it is referenced (via <a href="https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1">closure</a>) by all redux functions.</p> <p>Here's a simplified example of what is going on:</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 example() { let variableAvailableViaClosure = 0 function incrementTheClosureVariable() { variableAvailableViaClosure += 1 } function getTheClosureVariable() { return variableAvailableViaClosure } return { incrementTheClosureVariable, getTheClosureVariable } } let data = example() // at this point example is finished // but the functions it returned // still have access to the (internal) variable via closure console.log( data.getTheClosureVariable() // 0 ) data.incrementTheClosureVariable() console.log( data.getTheClosureVariable() // 1 )</code></pre> </div> </div> </p> <p>Furthermore, the statement</p> <blockquote> <p>In redux, we know that the state is stored as an object.</p> </blockquote> <p>isn't correct. State in redux can be any valid javascript value, not just an object. It just usually makes the most sense for it to be an object (or a special object like an array) because that allows for a more flexible data structure (but you could make the state just be a number for example, if you wanted to).</p> <p>Check out the actual Redux <a href="https://github.com/reactjs/redux/blob/master/src/createStore.ts" rel="noreferrer">implementation</a> for more details.</p> <p>If you want the state to persist in a cookie or localStorage, you would <a href="https://redux.js.org/understanding/thinking-in-redux/glossary#store-enhancer" rel="noreferrer">enhance the store</a> such that, on top of updating the state in memory, it will save to your desired storage as well (and load from that storage when the store is initialized)</p>
526,890
Best OpenId API for ASP.NET MVC application
<p>I am developing an ASP.NET MVC application and I want to use OpenId.</p> <p>What is the best option? </p> <ul> <li>DotNetOpenId</li> <li>RPX</li> <li>Other???</li> </ul> <p>Does anyone know what StackOverflow uses? Is the Login UI custom-developed, or provided by an API/service?</p>
526,897
2
3
null
2009-02-09 01:35:11.203 UTC
36
2010-12-20 04:06:20.387 UTC
2010-08-02 13:39:17.5 UTC
null
24,874
Jedi Master Spooky
1,154
null
1
46
asp.net-mvc|openid
7,567
<p>We use the excellent DotNetOpenId library here on Stack Overflow:</p> <blockquote> <p><a href="http://code.google.com/p/dotnetopenid/" rel="noreferrer">http://code.google.com/p/dotnetopenid/</a></p> </blockquote> <p>now moved to:</p> <blockquote> <p><a href="http://www.dotnetopenauth.net/" rel="noreferrer">http://www.dotnetopenauth.net/</a></p> </blockquote> <p>Our <em>original</em> login UI was provided by <a href="http://www.idselector.com/" rel="noreferrer">ID Selector</a>, but we've since rolled our own minimalist version.</p>
3,094,126
Best Practice / Standard for storing an Address in a SQL Database
<p>I am wondering if there is some sort of "standard" for storing US addresses in a database? It seems this is a common task, and there should be some sort of a standard. </p> <p>What I am looking for is a <strong>specific</strong> schema of how the database tables should work and interact, already in third normal form, including data types (MySQL). A good UML document would work. </p> <p>Maybe I'm just being lazy, but this is a very common task, and I am sure someone has published an efficient way to do this somewhere. I just don't know where to look and Google isn't helping. Please point me to the resource. Thanks.</p> <p>EDIT</p> <hr> <p>Although this is more of a general question, I would like to clarify my specific needs.</p> <p>Addresses will be used to specify road addresses of locations of events. These addresses will need to be in a format that can be best broken down and searched, and also used by any third-party applications I may end up linking my data source to.</p> <p>ALSO. Data will be geo-coded (long, lat) on entry and stored separately, so it must fit the (yet undecided) protocol of whatever geocoder / application / library does that. </p>
3,433,390
6
2
null
2010-06-22 14:30:12.843 UTC
13
2021-12-09 13:00:02.407 UTC
2010-08-08 08:55:22.99 UTC
null
233,999
null
233,999
null
1
23
mysql|street-address
47,786
<p>For international addresses, refer to the <a href="https://www.upu.int/en-us" rel="nofollow noreferrer">Universal Postal Union</a>'s <a href="https://www.upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions#postal-addressing-systems-(pas)" rel="nofollow noreferrer">Postal Addressing Systems database</a>.</p> <p>For U.S. addresses, refer to <a href="https://pe.usps.com/text/pub28/" rel="nofollow noreferrer">USPS Publication 28 &quot;Postal Addressing Standards&quot;</a>.</p> <p>The USPS wants the following unpunctuated address components concatenated on a single line:</p> <ul> <li>house number</li> <li>predirectional (<code>N</code>, <code>SE</code>, etc.)</li> <li>street</li> <li>suffix (<code>AVE</code>, <code>BLVD</code>, etc.)</li> <li>postdirectional (<code>SW</code>, <code>E</code>, etc.)</li> <li>unit (<code>APT</code>, <code>STE</code>, etc.)</li> <li>apartment/suite number</li> </ul> <p>E.g. <code>102 N MAIN ST SE APT B</code></p> <p>If you keep the entire address line as a single field in your database, input and editing is easy, but searches can be more difficult (eg, in the case <code>SOUTH EAST LANE</code> is the street <code>EAST</code> as in <code>S EAST LN</code> or is it <code>LANE</code> as in <code>SE LANE ST</code>?).</p> <p>If you keep the address parsed into separate fields, searches for components like street name or apartments become easier, but you have to append everything together for output, you need <a href="https://postalpro.usps.com/certifications/cass" rel="nofollow noreferrer">CASS software</a> to parse correctly, and PO boxes, rural route addresses, and APO/FPO addresses have special parsings.</p> <p>A physical location with multiple addresses at that location is either a multiunit building, in which case letters/numbers after units like <code>APT</code> and <code>STE</code> designate the address, or it's a Commercial Mail Receiving Agency (eg, UPS store) and a maildrop/private mailbox number is appended (like <code>100 MAIN ST STE B PMB 102</code>), or it's a business with one USPS delivery point and mail is routed after USPS delivery (which usually requires a separate mailstop field which the company might need but the USPS won't want on the address line).</p> <p>A contact with more than one physical address is usually a business or person with a street address and a PO box. Note that it's common for each address to have a different ZIP code.</p> <p>It's quite typical that one business transaction might have a shipping address and a billing address (again, with different ZIP codes). The information I keep for EACH address is:</p> <ul> <li>name prefix (<code>DR</code>, <code>MS</code>, etc)</li> <li>first name and initial</li> <li>last name</li> <li>name suffix (<code>III</code>, <code>PHD</code>, etc)</li> <li>mail stop</li> <li>company name</li> <li>address (one line only per Pub 28 for USA)</li> <li>city</li> <li>state/province</li> <li>ZIP/postal code</li> <li>country</li> </ul> <p>I typically print mail stops somewhere between the person's name and company because the country contains the state/ZIP which contains the city which contains the address which contains the company which contains the mail stop which contains the person. I use CASS software to validate and standardize addresses when entered or edited.</p>
2,842,540
Is there a brief syntax for executing a block n times in Scala?
<p>I find myself writing code like this when I want to repeat some execution n times:</p> <pre><code>for (i &lt;- 1 to n) { doSomething() } </code></pre> <p>I'm looking for a shorter syntax like this:</p> <pre><code>n.times(doSomething()) </code></pre> <p>Does something like this exist in Scala already?</p> <p><strong>EDIT</strong></p> <p>I thought about using Range's foreach() method, but then the block needs to take a parameter which it never uses.</p> <pre><code>(1 to n).foreach(ignored =&gt; doSomething()) </code></pre>
2,842,640
6
5
null
2010-05-16 03:56:36.397 UTC
12
2019-10-28 08:02:12.25 UTC
2010-05-16 15:40:33.833 UTC
null
23,572
null
23,572
null
1
56
scala
26,650
<p>You could easily define one using Pimp My Library pattern.</p> <pre><code>scala&gt; implicit def intWithTimes(n: Int) = new { | def times(f: =&gt; Unit) = 1 to n foreach {_ =&gt; f} | } intWithTimes: (n: Int)java.lang.Object{def times(f: =&gt; Unit): Unit} scala&gt; 5 times { | println("Hello World") | } Hello World Hello World Hello World Hello World Hello World </code></pre>
2,972,077
Multiline text as the button label in Windows Forms
<p>Basically, I am creating a button in an oval shape. But my button label is too long to display in one line, so I wanted to split it into multiple lines so that the oval button looks good.</p> <p>How do I enable word wrap on a button?</p>
2,972,371
7
0
null
2010-06-04 06:57:52.323 UTC
2
2018-07-30 10:27:24.603 UTC
2014-01-21 12:33:26.163 UTC
null
63,550
null
321,959
null
1
15
c#|winforms|button|word-wrap|shapes
58,253
<p>Set the label text on form load and add Environment.Newline as the newline string, like this:</p> <pre><code>btnOK.Text = "OK" + Environment.NewLine + "true"; </code></pre>
2,692,340
MySQL - How to count all rows per table in one query
<p>Is there a way to query the DB to find out how many rows there are in all the tables?</p> <p>i.e.</p> <pre><code>table1 1234 table2 222 table3 7888 </code></pre> <p>Hope you can advise</p>
2,692,395
9
1
null
2010-04-22 15:50:10.72 UTC
30
2020-09-22 11:21:01.65 UTC
2017-08-30 14:02:20.557 UTC
null
4,519,059
null
99,877
null
1
73
sql|mysql|count
72,229
<pre><code>SELECT TABLE_NAME, TABLE_ROWS FROM `information_schema`.`tables` WHERE `table_schema` = 'YOUR_DB_NAME'; </code></pre>
2,519,933
GIT clone repo across local file system in windows
<p>I am a complete Noob when it comes to GIT. I have been just taking my first steps over the last few days. I setup a repo on my laptop, pulled down the Trunk from an SVN project (had some issues with branches, not got them working), but all seems ok there.</p> <p>I now want to be able to pull or push from the laptop to my main desktop. The reason being the laptop is handy on the train as I spend 2 hours a day travelling and can get some good work done. But my main machine at home is great for development. So I want to be able to push / pull from the laptop to the main computer when I get home. I thought the most simple way of doing this would be to just have the code folder shared out across the LAN and do:</p> <pre><code>git clone file://192.168.10.51/code </code></pre> <p>unfortunately this doesn't seem to be working for me:</p> <p>so I open a git bash cmd and type the above command, I am in C:\code (the shared folder for both machines) this is what I get back:</p> <pre><code>Initialized empty Git repository in C:/code/code/.git/ fatal: 'C:/Program Files (x86)/Git/code' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>How can I share the repository between the two machines in the most simple of ways.</p> <p>There will be other locations that will be official storage points and places where the other devs and CI server etc will pull from, this is just so that I can work on the same repo across two machines.</p> <p>As per Sebastian's suggestion I get the following:</p> <pre><code>C:\code&gt;git clone --no-hardlinks file://192.168.10.51/code Initialized empty Git repository in C:/code/code/.git/ fatal: 'C:/Program Files (x86)/Git/code' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>**EDIT - ANSWER **</p> <p>Thanks to all that helped. I tried the mapping a drive and that worked so thought I would go back and retry without mapping. The final result was:</p> <pre><code>git clone file://\\\\192.168.0.51\code </code></pre> <p>This worked great.</p> <p>Thanks</p>
2,520,121
9
6
null
2010-03-25 22:34:47.117 UTC
90
2019-11-22 12:54:01.607 UTC
2014-11-09 09:16:38.583 UTC
null
1,143,013
null
6,486
null
1
208
windows|git|git-clone
207,142
<p>You can specify the remote’s URL by applying the <a href="http://msdn.microsoft.com/en-us/library/gg465305.aspx" rel="noreferrer" title="Universal Naming Convention">UNC</a> path to the file protocol. This requires you to use four slashes:</p> <pre><code>git clone file:////&lt;host&gt;/&lt;share&gt;/&lt;path&gt; </code></pre> <p>For example, if your main machine has the IP <em>192.168.10.51</em> and the computer name <code>main</code>, and it has a share named <code>code</code> which itself is a git repository, then both of the following commands should work equally:</p> <pre><code>git clone file:////main/code git clone file:////192.168.10.51/code </code></pre> <p>If the Git repository is in a subdirectory, simply append the path:</p> <pre><code>git clone file:////main/code/project-repository git clone file:////192.168.10.51/code/project-repository </code></pre>
3,100,319
Event on a disabled input
<p>Apparently a disabled <code>&lt;input&gt;</code> is not handled by any event</p> <p>Is there a way to work around this issue ?</p> <pre><code>&lt;input type="text" disabled="disabled" name="test" value="test" /&gt; </code></pre> <pre class="lang-javascript prettyprint-override"><code>$(':input').click(function () { $(this).removeAttr('disabled'); }) </code></pre> <p>Here, I need to click on the input to enable it. But if I don't activate it, the input should not be posted.</p>
3,100,395
12
3
null
2010-06-23 09:09:26.457 UTC
54
2021-10-30 00:12:01.73 UTC
2019-11-10 03:44:08.317 UTC
null
667,810
null
305,189
null
1
266
javascript|jquery|html
281,634
<p>Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.</p> <p>I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:</p> <pre><code>&lt;div style="display:inline-block; position:relative;"&gt; &lt;input type="text" disabled /&gt; &lt;div style="position:absolute; left:0; right:0; top:0; bottom:0;"&gt;&lt;/div&gt; &lt;/div&gt;​ </code></pre> <p>jq:</p> <pre><code>$("div &gt; div").click(function (evt) { $(this).hide().prev("input[disabled]").prop("disabled", false).focus(); });​ </code></pre> <p>Example: <a href="http://jsfiddle.net/RXqAm/170/" rel="noreferrer">http://jsfiddle.net/RXqAm/170/</a> (updated to use jQuery 1.7 with <code>prop</code> instead of <code>attr</code>).</p>
2,801,882
Generating a PNG with matplotlib when DISPLAY is undefined
<p>I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?</p> <pre><code>#!/usr/bin/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig("/var/www/node.png") Traceback (most recent call last): File "graph.py", line 13, in &lt;module&gt; nx.draw(G) File "/usr/lib/pymodules/python2.5/networkx/drawing/nx_pylab.py", line 124, in draw cf=pylab.gcf() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf return figure() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure **kwargs) File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager window = Tk.Tk() File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable </code></pre> <hr> <p>I get a different error now:</p> <pre><code>#!/usr/bin/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt matplotlib.use('Agg') G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig("/var/www/node.png") </code></pre> <hr> <pre><code>/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. if warn: warnings.warn(_use_error_msg) Traceback (most recent call last): File "graph.py", line 15, in &lt;module&gt; nx.draw(G) File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw cf=pylab.gcf() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf return figure() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure **kwargs) File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager window = Tk.Tk() File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable </code></pre> <hr> <p>I get a different error now:</p> <pre><code>#!/usr/bin/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt matplotlib.use('Agg') G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig("/var/www/node.png") </code></pre> <hr> <pre><code>/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. if warn: warnings.warn(_use_error_msg) Traceback (most recent call last): File "graph.py", line 15, in &lt;module&gt; nx.draw(G) File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw cf=pylab.gcf() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf return figure() File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure **kwargs) File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager window = Tk.Tk() File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable </code></pre>
3,054,314
13
3
null
2010-05-10 10:22:33.093 UTC
113
2022-03-29 17:30:52.143 UTC
2016-08-08 23:37:26.403 UTC
null
2,966,723
null
3,836,677
null
1
331
python|matplotlib|graph
180,462
<p>The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read <em>before</em> any other pylab/matplotlib/<strong>pyplot</strong> import:</p> <pre><code>import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') </code></pre> <p>The alternative is to set it in your .matplotlibrc</p>
25,306,519
Shiny saving URL state subpages and tabs
<p>I would like to have a shiny website that keeps the dynamic choices in the URL as output, so you can copy and share the URL. I took this code as an example: <a href="https://gist.github.com/amackey/6841cf03e54d021175f0" rel="noreferrer">https://gist.github.com/amackey/6841cf03e54d021175f0</a></p> <p>And modified it to my case, which is a webpage with a <code>navbarPage</code> and multiple tabs per element in the bar.</p> <p>What I would like is the URL to direct the user to the right element in the first level tabPanel, and the right tab in the second level tabPanel.</p> <p>This is, if the user has navigated to "Delta Foxtrot" and then to "Hotel", then changed the parameters to <code>#beverage=Tea;milk=TRUE;sugarLumps=3;customer=mycustomer</code>, I would like the URL to send the user to "Delta Foxtrot" -> "Hotel", instead of starting at the first tab of the first panel element.</p> <p>Ideally I would like a working example, since everything I tried so far hasn't worked.</p> <p>Any ideas?</p> <p><img src="https://i.stack.imgur.com/KtnQc.jpg" alt="enter image description here"></p> <pre><code># ui.R library(shiny) hashProxy &lt;- function(inputoutputID) { div(id=inputoutputID,class=inputoutputID,tag("div","")); } # Define UI for shiny d3 chatter application shinyUI(navbarPage('URLtests', id="page", collapsable=TRUE, inverse=FALSE, tabPanel("Alfa Bravo", tabsetPanel( tabPanel("Charlie", tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab") ) ) ) ,tabPanel("Delta Foxtrot", tabsetPanel( tabPanel("Golf", tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab") ) ,tabPanel("Hotel", tags$p("This widget is a demonstration of how to preserve input state across sessions, using the URL hash."), selectInput("beverage", "Choose a beverage:", choices = c("Tea", "Coffee", "Cocoa")), checkboxInput("milk", "Milk"), sliderInput("sugarLumps", "Sugar Lumps:", min=0, max=10, value=3), textInput("customer", "Your Name:"), includeHTML("URL.js"), h3(textOutput("order")), hashProxy("hash") ) ) ) )) # server.R library(shiny) url_fields_to_sync &lt;- c("beverage","milk","sugarLumps","customer"); # Define server logic required to respond to d3 requests shinyServer(function(input, output, clientData) { # Generate a plot of the requested variable against mpg and only # include outliers if requested output$order &lt;- reactiveText(function() { paste(input$beverage, if(input$milk) "with milk" else ", black", "and", if (input$sugarLumps == 0) "no" else input$sugarLumps, "sugar lumps", "for", if (input$customer == "") "next customer" else input$customer) }) firstTime &lt;- TRUE output$hash &lt;- reactiveText(function() { newHash = paste(collapse=";", Map(function(field) { paste(sep="=", field, input[[field]]) }, url_fields_to_sync)) # the VERY FIRST time we pass the input hash up. return( if (!firstTime) { newHash } else { if (is.null(input$hash)) { NULL } else { firstTime&lt;&lt;-F; isolate(input$hash) } } ) }) }) # URL.js &lt;script type="text/javascript"&gt; (function(){ this.countValue=0; var changeInputsFromHash = function(newHash) { // get hash OUTPUT var hashVal = $(newHash).data().shinyInputBinding.getValue($(newHash)) if (hashVal == "") return // get values encoded in hash var keyVals = hashVal.substring(1).split(";").map(function(x){return x.split("=")}) // find input bindings corresponding to them keyVals.map(function(x) { var el=$("#"+x[0]) if (el.length &gt; 0 &amp;&amp; el.val() != x[1]) { console.log("Attempting to update input " + x[0] + " with value " + x[1]); if (el.attr("type") == "checkbox") { el.prop('checked',x[1]=="TRUE") el.change() } else if(el.attr("type") == "radio") { console.log("I don't know how to update radios") } else if(el.attr("type") == "slider") { // This case should be setValue but it's not implemented in shiny el.slider("value",x[1]) //el.change() } else { el.data().shinyInputBinding.setValue(el[0],x[1]) el.change() } } }) } var HashOutputBinding = new Shiny.OutputBinding(); $.extend(HashOutputBinding, { find: function(scope) { return $(scope).find(".hash"); }, renderError: function(el,error) { console.log("Shiny app failed to calculate new hash"); }, renderValue: function(el,data) { console.log("Updated hash"); document.location.hash=data; changeInputsFromHash(el); } }); Shiny.outputBindings.register(HashOutputBinding); var HashInputBinding = new Shiny.InputBinding(); $.extend(HashInputBinding, { find: function(scope) { return $(scope).find(".hash"); }, getValue: function(el) { return document.location.hash; }, subscribe: function(el, callback) { window.addEventListener("hashchange", function(e) { changeInputsFromHash(el); callback(); } , false); } }); Shiny.inputBindings.register(HashInputBinding); })() &lt;/script&gt; </code></pre> <p>EDITED: I ran the example code in the answer, but couldn't get it to work. See screenshot.</p> <p><img src="https://i.stack.imgur.com/FnhzZ.jpg" alt="enter image description here"></p>
25,385,474
2
0
null
2014-08-14 11:05:24.263 UTC
10
2016-09-15 12:41:54.513 UTC
2014-08-19 08:38:59.427 UTC
null
719,016
null
719,016
null
1
21
r|shiny
6,142
<h1>UPDATE</h1> <p>Shiny .14 now available on CRAN supports saving app state in a URL. See <a href="http://shiny.rstudio.com/articles/bookmarking-state.html" rel="noreferrer">this article</a></p> <hr> <p>This answer is a more in-depth answer than my first that uses the entire sample code provided by OP. I've decided to add it as a new answer in light of the bounty. My original answer used a simplified version of this so that someone else coming to the answer wouldn't have to read through any extraneous code to find what they're looking for. Hopefully, this extended version will clear up any difficulties you're having. Parts I've added to your R code are surrounded with <code>### ... ###</code>.</p> <h3>server.r</h3> <pre><code># server.R library(shiny) url_fields_to_sync &lt;- c("beverage","milk","sugarLumps","customer"); # Define server logic required to respond to d3 requests shinyServer(function(input, output, session) { # session is the common name for this variable, not clientData # Generate a plot of the requested variable against mpg and only # include outliers if requested output$order &lt;- reactiveText(function() { paste(input$beverage, if(input$milk) "with milk" else ", black", "and", if (input$sugarLumps == 0) "no" else input$sugarLumps, "sugar lumps", "for", if (input$customer == "") "next customer" else input$customer) }) firstTime &lt;- TRUE output$hash &lt;- reactiveText(function() { newHash = paste(collapse=";", Map(function(field) { paste(sep="=", field, input[[field]]) }, url_fields_to_sync)) # the VERY FIRST time we pass the input hash up. return( if (!firstTime) { newHash } else { if (is.null(input$hash)) { NULL } else { firstTime&lt;&lt;-F; isolate(input$hash) } } ) }) ### # whenever your input values change, including the navbar and tabpanels, send # a message to the client to update the URL with the input variables. # setURL is defined in url_handler.js observe({ reactlist &lt;- reactiveValuesToList(input) reactvals &lt;- grep("^ss-|^shiny-", names(reactlist), value=TRUE, invert=TRUE) # strip shiny related URL parameters reactstr &lt;- lapply(reactlist[reactvals], as.character) # handle conversion of special data types session$sendCustomMessage(type='setURL', reactstr) }) observe({ # this observer executes once, when the page loads # data is a list when an entry for each variable specified # in the URL. We'll assume the possibility of the following # variables, which may or may not be present: # nav= The navbar tab desired (either Alfa Bravo or Delta Foxtrot) # tab= The desired tab within the specified nav bar tab, e.g., Golf or Hotel # beverage= The desired beverage selection # sugar= The desired number of sugar lumps # # If any of these variables aren't specified, they won't be used, and # the tabs and inputs will remain at their default value. data &lt;- parseQueryString(session$clientData$url_search) # the navbar tab and tabpanel variables are two variables # we have to pass to the client for the update to take place # if nav is defined, send a message to the client to set the nav tab if (! is.null(data$page)) { session$sendCustomMessage(type='setNavbar', data) } # if the tab variable is defined, send a message to client to update the tab if (any(sapply(data[c('alfa_bravo_tabs', 'delta_foxtrot_tabs')], Negate(is.null)))) { session$sendCustomMessage(type='setTab', data) } # the rest of the variables can be set with shiny's update* methods if (! is.null(data$beverage)) { # if a variable isn't specified, it will be NULL updateSelectInput(session, 'beverage', selected=data$beverage) } if (! is.null(data$sugarLumps)) { sugar &lt;- as.numeric(data$sugarLumps) # variables come in as character, update to numeric updateNumericInput(session, 'sugarLumps', value=sugar) } }) ### }) </code></pre> <h3>ui.r</h3> <pre><code>library(shiny) hashProxy &lt;- function(inputoutputID) { div(id=inputoutputID,class=inputoutputID,tag("div","")); } # Define UI for shiny d3 chatter application shinyUI(navbarPage('URLtests', id="page", collapsable=TRUE, inverse=FALSE, tabPanel("Alfa Bravo", tabsetPanel( ### id='alfa_bravo_tabs', # you need to set an ID for your tabpanels ### tabPanel("Charlie", tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab") ) ) ) ,tabPanel("Delta Foxtrot", tabsetPanel( ### id='delta_foxtrot_tabs', # you need to set an ID for your tabpanels ### tabPanel("Golf", tags$p("Nothing to see here. Everything is in the 'Delta Foxtrot' 'Hotel' tab") ) ,tabPanel("Hotel", id='hotel', tags$p("This widget is a demonstration of how to preserve input state across sessions, using the URL hash."), selectInput("beverage", "Choose a beverage:", choices = c("Tea", "Coffee", "Cocoa")), checkboxInput("milk", "Milk"), sliderInput("sugarLumps", "Sugar Lumps:", min=0, max=10, value=3), textInput("customer", "Your Name:"), #includeHTML("URL.js"), ### includeHTML('url_handler.js'), # include the new script ### h3(textOutput("order")), hashProxy("hash") ) ) ) )) </code></pre> <h3>url_handler.js</h3> <pre><code>&lt;script&gt; Shiny.addCustomMessageHandler('setNavbar', function(data) { // create a reference to the desired navbar tab. page is the // id of the navbarPage. a:contains says look for // the subelement that contains the contents of data.nav var nav_ref = '#page a:contains(\"' + data.page + '\")'; $(nav_ref).tab('show'); } ) Shiny.addCustomMessageHandler('setTab', function(data) { // pick the right tabpanel ID based on the value of data.nav if (data.page == 'Alfa Bravo') { var tabpanel_id = 'alfa_bravo_tabs'; } else { var tabpanel_id = 'delta_foxtrot_tabs'; } // combine this with a reference to the desired tab itself. var tab_ref = '#' + tabpanel_id + ' a:contains(\"' + data[tabpanel_id] + '\")'; $(tab_ref).tab('show'); } ) Shiny.addCustomMessageHandler('setURL', function(data) { // make each key and value URL safe (replacing spaces, etc.), then join // them and put them in the URL var search_terms = []; for (var key in data) { search_terms.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); } window.history.pushState('object or string', 'Title', '/?' + search_terms.join('&amp;')); } ); &lt;/script&gt; </code></pre> <p>To test this, call <code>runApp(port=5678)</code> in the directory with your source files. By default, no parameters are specified in the URL, so this will default to the first navbar item and the first tab within that item. To test it with URL parameters, point your browser to: <code>http://127.0.0.1:5678/?nav=Delta%20Foxtrot&amp;tab=Hotel&amp;beverage=Coffee</code>. This should point you to the second navbar tab and the second tab in that navbar item with coffee as the selected beverage.</p>
45,625,844
Is it advisable to use LinearLayout inside ConstraintLayout in Android?
<p>I am new to <code>ConstraintLayout</code> in Android and newbie to Android too. I have a question. Is it advisable to use <code>LinearLayout</code> inside <code>ConstraintLayout</code>? For example:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" app:srcCompat="@drawable/landing_screen" android:layout_height="match_parent" tools:context="com.braigolabs.braigo.landing.LandingActivity"&gt; &lt;ImageView android:id="@+id/imageView" android:layout_width="0dp" android:layout_height="0dp" android:scaleType="centerCrop" app:srcCompat="@drawable/landing_screen" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintVertical_bias="1.0" app:layout_constraintHorizontal_bias="1.0" tools:layout_constraintTop_creator="1" tools:layout_constraintRight_creator="1" tools:layout_constraintBottom_creator="1" tools:layout_constraintLeft_creator="1"/&gt; &lt;LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="horizontal" tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="51dp"&gt; &lt;TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="66dp" android:layout_marginStart="66dp" android:gravity="center" android:text="@string/login_welcome_braigolabs" android:textAppearance="@style/TextAppearance.AppCompat.Large" tools:layout_editor_absoluteX="93dp" tools:layout_editor_absoluteY="403dp"/&gt; &lt;Button android:id="@+id/login_button" style="@style/Widget.AppCompat.Button.Colored" android:layout_width="match_parent" android:layout_height="wrap_content" android:elevation="2dp" android:text="@string/login_login_button_title" android:textAllCaps="false" tools:layout_editor_absoluteX="116dp" tools:layout_editor_absoluteY="543dp"/&gt; &lt;/LinearLayout&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>Also curious to know how popular is the <code>ConstraintLayout</code> among the developers?</p>
45,626,000
2
1
null
2017-08-11 02:03:34.873 UTC
2
2022-09-18 08:37:23.013 UTC
2017-11-27 17:05:30.98 UTC
null
1,708,390
null
357,166
null
1
38
android|android-constraintlayout
27,657
<blockquote> <p>Is it advisable to use LinearLayout inside ConstraintLayout?</p> </blockquote> <p>No... usually.</p> <p>In general, the idea behind <code>ConstraintLayout</code> is that it allows you to position all of your children without having to nest any other <code>ViewGroup</code>s inside the <code>ConstraintLayout</code>. As such, I would say that it is not <em>advisable</em>.</p> <p>However, there <em>are</em> some things that a <code>LinearLayout</code> can do that a <code>ConstraintLayout</code> can't (mostly revolving around weighted spacing of views), and so if you need these particular corner cases in your layout, you won't have any option other than falling back to a <code>LinearLayout</code>.</p> <blockquote> <p>how popular is the ConstraintLayout among the developers?</p> </blockquote> <p><code>ConstraintLayout</code> is relatively new, but it is quite powerful and certainly something that you ought to familiarize yourself with. It won't always be the perfect tool for the job at hand, but it will often allow you to easily create layouts you would otherwise spend hours on.</p> <p>I can't speak to widespread adoption statistics, but I can say that I've seen tons of questions on this site about the correct usage of <code>ConstraintLayout</code>, so clearly devs around the world are starting to work with it.</p>
10,365,523
Adding a page loader using jQuery
<p>I need a little help. I do not know where to start. I need to add a page loader to my website. I first submit a form it then uses SimpleXML to call an exterior XML Sheet with expedia... It takes a minute to load, so I would like to add the image loader to this page. But how do I go about doing this? I have looked on Google and could not find any useful info.</p> <p>I need it to show the loader until the COMPLETE page has loaded.</p>
10,365,835
3
0
null
2012-04-28 16:45:09.497 UTC
4
2020-06-22 09:36:19.027 UTC
2020-06-22 09:36:19.027 UTC
null
4,217,744
null
1,094,309
null
1
4
jquery|pageload|page-loading-message
64,874
<p>This has many solutions, but a simple one is to:</p> <p>1- Create an overlay DIV with your loader stuff and prepend to BODY;<br> 2- Add an event listener for <code>window.load</code> or <code>document.ready</code> event that hides this DIV.</p> <pre><code>// On the first line inside BODY tag &lt;script type="text/javascript"&gt; jQuery("body").prepend('&lt;div id="preloader"&gt;Loading...&lt;/div&gt;'); jQuery(document).ready(function() { jQuery("#preloader").remove(); }); &lt;/script&gt; </code></pre> <p><em>(code typos fixed)</em></p>
10,543,325
Can't connect to server on SQL Server Management Studio 2008
<p>When I open the Management Studio and try to connect using the [PCNAME]/SQLEXPRESS it shows this error:</p> <blockquote> <p>"Cannot connect to [PCNAME]\SQLEXPRESS"</p> </blockquote> <hr> <p>ADDITIONAL INFORMATION:</p> <p>Error Message:</p> <blockquote> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) (Microsoft SQL Server, Error: -1)</p> <p>For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=-1&amp;LinkId=20476" rel="nofollow">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=-1&amp;LinkId=20476</a>"</p> </blockquote> <p>I've also tried "localhost", "local" and "." in the place for [PCNAME] but to no avail.</p>
10,543,353
3
0
null
2012-05-10 23:05:01.877 UTC
2
2021-05-19 20:43:45.147 UTC
2017-01-14 21:31:16.91 UTC
null
13,302
null
1,200,185
null
1
8
sql-server-2008|sql-server-2008-express
38,680
<p>Make sure SQL Server (SQL Express) service is running.</p> <p>in powershell prompt type:</p> <pre><code>Get-Service -Name 'MSSQL$SQLEXPRESS' </code></pre> <p>service "status" property should be reported as "Running"</p> <p>If it is not, type (you need to be in elevated prompt, i.e. "Run as Administrator"):</p> <p>Start-Service -Name 'MSSQL$SQLEXPRESS'</p> <p>OR</p> <p>click start > type cmd and type</p> <pre><code>sc query MSSQL$SQLEXPRESS </code></pre> <p>State should be reported as "Running"</p> <p>If it is not, type (you need to be in elevated prompt, i.e. "Run as Administrator"):</p> <pre><code>sc start MSSQL$SQLEXPRESS </code></pre> <p>If you get an error that the service cannot be found: Open SQL server Configuration Manager and make sure you have SQL server express installed: <img src="https://i.stack.imgur.com/RJVeN.png" alt="enter image description here"></p>
5,833,642
python: APNs SSLError
<p>I am trying to send push notifications to iPhone via python as described <a href="http://leenux.org.uk/2009/07/14/push-on-the-iphone/" rel="noreferrer">here</a> but I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/home/omat/CA/server/ca/models.py", line 193, in push c.connect((host_name, 2195)) File "/usr/lib/python2.6/ssl.py", line 307, in connect self.ca_certs) SSLError: [Errno 336265225] _ssl.c:337: error:140B0009:SSL routines: SSL_CTX_use_PrivateKey_file:PEM lib </code></pre> <p>The error is raised from within the python ssl module as the traceback says but the message doesn't sing to me. Any ideas on what might be wrong?</p> <p>Thanks,</p> <p>oMat</p> <p><strong>edit:</strong></p> <p>The certificate used is created from the certificate and the private key as follows:</p> <pre><code>openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12 openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12 cat apns-dev-cert.pem apns-dev-key.pem &gt; apns-dev.pem </code></pre>
5,855,800
2
2
null
2011-04-29 14:52:15.417 UTC
16
2014-03-19 13:41:55.157 UTC
2011-04-29 15:37:13.867 UTC
null
287,923
null
287,923
null
1
18
python|ssl|apple-push-notifications
12,462
<p>Here is how I get it working:</p> <p>From within KeyChain export the following both in <code>p12</code> format, without giving password:</p> <ul> <li><code>Apple Development Push Services</code> certificate as <code>cert.p12</code></li> <li><code>primary key</code> under <code>Apple Development Push Services</code> as <code>pkey.p12</code></li> </ul> <p>In terminal go to the directory where you have exported the certificates and convert the <code>p12</code> files to <code>pem</code> format and concatenate them as follows:</p> <pre><code>$ openssl pkcs12 -in pkey.p12 -out pkey.pem -nodes -clcerts $ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts $ cat cert.pem pkey.pem &gt; iphone_ck.pem </code></pre> <p><code>iphone_ck.pem</code> is the certificate you need.</p>
6,084,743
Rails ActiveRecord: building queries dynamically
<p>I'm trying to put together a series of classes that can use ActiveRecord to create and execute complex queries dynamically. I feel very comfortable with the whole practice of doing:</p> <pre><code>MyModel.select("id, name, floober").join(:creator).where(:is_active =&gt; true) </code></pre> <p>What I'm struggling with is using these things to build up a query w/o being able to determine how many there will be of each possible method (number of joins, number or where clauses, limit, group, etc) ahead of time. I might have 2 joins, or no joins depending upon where it's called from.</p> <p>Due to the nature of how I'm getting these things--a list of joins, a list of columns, a list of where clauses, etc--I can blindly chain them together. I have to join the columns together, arrange the joins, chain the where clauses, so I can't loop through the various lists.</p> <p>I'm trying to avoid writing any raw SQL.</p> <p>One thing I tried was building up the ruby statement as a string then evaling it at the end, and when I got done I felt dirty like I needed a bath. What I'm looking for is a way to cache the state of my query until all the parts have been accumulated, then execute them.</p> <p>Have I wandered "off the Rails"?</p> <p>thanks in advance...</p>
6,085,124
2
0
null
2011-05-21 22:07:00.7 UTC
9
2012-12-14 13:34:29.4 UTC
null
null
null
null
483,040
null
1
29
ruby-on-rails|ruby-on-rails-3|activerecord
16,279
<p>I think I figured it out. I was fairly off base on my understanding of the AR query methods. It turns out that ActiveRecord doesn't actually execute the query until you actually try to use the results. As a result it's possible to do things like:</p> <pre><code>model_query = MyModel.select("column12, column32") model_query = model_query.joins(:user) model_query = model_query.where(:column12 =&gt; true) </code></pre> <p>then after everything is built up you can do</p> <pre><code>model_query.each do |record| ... end </code></pre> <p>The query isn't actually executed until you call each (or whatever method you use that demands the results of the query).</p> <p>I got this by watching Railscasts <a href="http://railscasts.com/episodes/202-active-record-queries-in-rails-3" rel="noreferrer">202</a> and <a href="http://railscasts.com/episodes/215-advanced-queries-in-rails-3" rel="noreferrer">215</a>. I love Ryan Bates.</p>
31,343,299
MySQL Improperly Configured Reason: unsafe use of relative path
<p>I'm using Django, and when I run <code>python manage.py runserver</code> I receive the following error: </p> <pre><code>ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: unsafe use of relative rpath libmysqlclient.18.dylib in /Library/Python/2.7/site-packages/_mysql.so with restricted binary </code></pre> <p>I'm not entirely sure how to fix this. I have installed MySQL-python via pip. And I followed <a href="https://stackoverflow.com/q/2952187/3990714">this</a> step earlier. </p> <p>I want to also point out this is with El Capitan Beta 3.</p>
31,821,332
2
2
null
2015-07-10 14:26:27.13 UTC
15
2016-10-22 07:26:01.883 UTC
2017-05-23 11:47:11.08 UTC
null
-1
null
3,990,714
null
1
27
python|mysql|django|dynamic-linking|osx-elcapitan
11,881
<p>In OS X El Capitan (10.11), Apple added <a href="https://support.apple.com/en-us/HT204899" rel="noreferrer">System Integrity Protection</a>.</p> <p>This prevents programs in protected locations like <code>/usr</code> from calling a shared library that uses a relative reference to another shared library. In the case of <code>_mysql.so</code>, it contains a relative reference to the shared library <code>libmysqlclient.18.dylib</code>. </p> <p>In the future, the shared library <code>_mysql.so</code> may be updated. Until then, you can force it to use an absolute reference via the <code>install_name_tool</code> utility.</p> <p>Assuming that <code>libmysqlclient.18.dylib</code> is in /usr/local/mysql/lib/, then run the command:</p> <pre><code>sudo install_name_tool -change libmysqlclient.18.dylib \ /usr/local/mysql/lib/libmysqlclient.18.dylib \ /Library/Python/2.7/site-packages/_mysql.so </code></pre>
23,188,932
how do I clean up my docker host machine
<p>As I create/debug a docker image/container docker seems to be leaving all sorts of artifacts on my system. (at one point there was a 48 image limit) But the last time I looked there were 20-25 images; <code>docker images</code>.</p> <p>So the overarching questions are:</p> <ul> <li>how does one properly cleanup?</li> <li>as I was manually deleting images more started to arrive. huh?</li> <li>how much disk space should I really allocate to the host?</li> <li>will running daemons really restart after the next reboot?</li> </ul> <p>and the meta question... what questions have I not asked that need to be?</p>
32,464,728
6
0
null
2014-04-21 00:00:37.24 UTC
18
2017-10-02 16:00:31.137 UTC
null
null
null
null
99,542
null
1
30
docker|coreos
19,671
<p>It can also be helpful to remove "dangling" images</p> <p><code>docker rmi $(docker images -f "dangling=true" -q)</code></p>
33,059,933
package org.apache.http.client does not exist
<p>I am trying to check log in credentials , But I am getting these errors again and again , I have tried everything. I am new to android Any kind of help will be appreciated. If there is other good way to implement same , want to know how to imply</p> <p>Error</p> <pre><code>Error:(19, 30) error: package org.apache.http.client does not exist Error:(15, 23) error: package org.apache.http does not exist Error:(16, 23) error: package org.apache.http does not exist Error:(17, 23) error: package org.apache.http does not exist Error:(18, 30) error: package org.apache.http.client does not exist Error:(20, 37) error: package org.apache.http.client.entity does not exist Error:(21, 38) error: package org.apache.http.client.methods does not exist Error:(22, 35) error: package org.apache.http.impl.client does not exist Error:(23, 31) error: package org.apache.http.message does not exist Error:(79, 22) error: cannot find symbol class NameValuePair Error:(85, 49) error: cannot find symbol class DefaultHttpClient Error:(86, 21) error: cannot find symbol class HttpPost Error:(86, 45) error: cannot find symbol class HttpPost Error:(88, 44) error: cannot find symbol class UrlEncodedFormEntity Error:(90, 21) error: cannot find symbol class HttpResponse Error:(92, 21) error: cannot find symbol class HttpEntity Error:(105, 26) error: cannot find symbol class ClientProtocolException Error:Execution failed for task ':app:compileDebugJavaWithJavac'. &gt; Compilation failed; see the compiler error output for details. Error:(85, 21) error: cannot find symbol class HttpClient Error:(81, 40) error: cannot find symbol class BasicNameValuePair Error:(80, 40) error: cannot find symbol class BasicNameValuePair Error:(79, 68) error: cannot find symbol class NameValuePair </code></pre> <p>MainActivity.java</p> <pre><code>package com.tarun.proxy_maar; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private EditText editTextUserName; private EditText editTextPassword; public static final String USER_NAME = "USERNAME"; String username; String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextUserName = (EditText) findViewById(R.id.editTextUserName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); } public void invokeLogin(View view){ username = editTextUserName.getText().toString(); password = editTextPassword.getText().toString(); login(username,password); } private void login(final String username, String password) { class LoginAsync extends AsyncTask&lt;String, Void, String&gt;{ private Dialog loadingDialog; @Override protected void onPreExecute() { super.onPreExecute(); loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading..."); } @Override protected String doInBackground(String... params) { String uname = params[0]; String pass = params[1]; InputStream is = null; List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(); nameValuePairs.add(new BasicNameValuePair("username", uname)); nameValuePairs.add(new BasicNameValuePair("password", pass)); String result = null; try{ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "http://shaadi.web44.net/hello.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result){ String s = result.trim(); loadingDialog.dismiss(); if(s.equalsIgnoreCase("success")){ Intent intent = new Intent(MainActivity.this, UserProfile.class); intent.putExtra(USER_NAME, username); finish(); startActivity(intent); }else { Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show(); } } } LoginAsync la = new LoginAsync(); la.execute(username, password); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre>
33,059,990
2
0
null
2015-10-10 23:13:17.837 UTC
4
2015-10-11 01:34:25.633 UTC
null
null
null
null
4,974,092
null
1
14
java|android|http|android-studio
67,779
<p>Add that to your build.gradle:</p> <pre><code>android { useLibrary 'org.apache.http.legacy' } </code></pre> <p>Or you use the <code>HttpURLConnection class</code> instead.</p>
21,565,738
Using toastr in the AngularJS way
<p>Currently, I just call <code>toastr.success('my message')</code> within a controller where required. This work fine, but it feels a bit dirty to me. </p> <p>Is there a 'best practice' or recommended 'angularjs' way of using the <a href="https://github.com/CodeSeven/toastr">toastr.js library</a>?</p>
21,565,779
1
0
null
2014-02-04 23:29:13.203 UTC
3
2017-11-14 10:56:10.977 UTC
2015-05-21 13:15:52.28 UTC
null
2,874,896
null
1,248,716
null
1
29
javascript|angularjs|toastr
23,468
<p>Yes. Pretty simply:</p> <pre><code>app.factory('notificationFactory', function () { return { success: function (text) { toastr.success(text,"Success"); }, error: function (text) { toastr.error(text, "Error"); } }; }); </code></pre> <p>Resolve factory in controller. Customize messages, notifications/etc in factory.</p> <p>Despite the idea that code adds another abstraction, it's really effective.</p>
25,931,716
Add new lines in VBA email
<p>I'm trying to send an email automatically through Excel, but the new line commands aren't working! I've tried <code>&lt;br/&gt;</code>, <code>vbCrLf</code> and <code>vbNewLine</code></p> <pre><code>.HTMLbody = "Hello" &amp; vbNewLine &amp; "Please find attached the above invoices and backup" &amp; vbNewLine &amp; _ "Any queries please let me know" &amp; vbNewLine &amp; "Regards" &amp; vbNewLine &amp; Signature </code></pre> <p>It keeps just giving <code>Hello Please find attached the above invoices and backup Any queries please let me know Regards</code> as one line!</p>
25,931,889
4
0
null
2014-09-19 10:23:54.133 UTC
1
2022-02-18 13:23:02.253 UTC
null
null
null
null
4,043,074
null
1
11
vba|excel|excel-2007|html-email
121,238
<p>May be you can try this instead: Use</p> <pre><code>.HTMLbody = "Hello" &amp; "&lt;br&gt;" &amp; "Please find attached the above invoices and backup" &amp; "&lt;br&gt;" </code></pre> <p>instead of vbnewline</p>
8,944,860
How to create an IP alias on Windows
<p>I need to create an alias for my network interface such that it can be accessed locally with either 127.0.0.1 or 33.33.33.33.</p> <p>In *nix I would do this:</p> <pre><code>sudo ifconfig en1 inet 33.33.33.33/32 alias </code></pre> <p>It appears that the <code>netsh</code> tool may be able to do the same thing. If so, how? I've seen some examples that seem close, but I don't understand the options provided.</p> <p>The motivation for this is to run two instances of JBossAS on the same machine without port offsets. Thus, they would need to use the same port numbers without conflicting.</p>
8,944,928
7
0
null
2012-01-20 16:46:03.273 UTC
7
2022-04-28 17:52:37.4 UTC
null
null
null
null
63,308
null
1
16
windows|ip|netsh
92,502
<p>You'd be correct. Also, you can add multiple addresses without touching the command line using the advanced interface properties screen.</p> <pre><code>netsh interface ip add address "Local Area Connection" 33.33.33.33 255.255.255.255 </code></pre> <p><img src="https://i.stack.imgur.com/nA5wA.png" alt="Windows Advanced TCP/IP Settings"></p>
8,905,662
How to change all occurrences of a word in all files in a directory
<p>I was in the process of creating a <code>User</code> class where one of the methods was <code>get_privileges();</code>.</p> <p>After hours of slamming my head into the keyboard, I finally discovered that the previous coder who I inherited this particular database spelled the word "<strong>privileges</strong>" as "<strong>privelages</strong>" in the MySQL database, and thus also everywhere in the hundreds of files that access these "<strong>privelages</strong>" it is spelled that way.</p> <p>Is there a way in Linux (<em>Ubuntu Server</em>) that I can go through every place in the <code>/var/www</code> folder and replace "<strong>privelages</strong>" with "<strong>privileges</strong>", so that I don't have to deal with this typo and code around it?</p>
8,905,787
3
0
null
2012-01-18 05:37:27.723 UTC
15
2020-12-15 23:16:04.947 UTC
2018-07-16 23:25:38.157 UTC
null
5,377,495
null
714,178
null
1
42
linux|ubuntu|replace
49,352
<p>A variation that takes into account subdirectories (untested):</p> <pre><code>find /var/www -type f -exec sed -i 's/privelages/privileges/g' {} \; </code></pre> <p>This will <code>find</code> all files (not directories, specified by <code>-type f</code>) under <code>/var/www</code>, and perform a <code>sed</code> command to replace "privelages" with "privileges" on each file it finds.</p>
55,269,763
Return a Pandas DataFrame as a data_table from a callback with Plotly Dash for Python
<p>I would like to read a .csv file and return a groupby function as a callback to be displayed as a simple data table with "dash_table" library. @Lawliet's helpful answer shows how to do that with "dash_table_experiments" library. Here is where I’m stuck:</p> <pre><code>import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html import dash_table from dash.dependencies import Input, Output, State df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') app = dash.Dash() application = app.server app.layout = html.Div([ dash_table.DataTable( id = 'datatable', ), html.Div([ html.Button(id='submit-button', children='Submit' ) ]), ]) @app.callback(Output('datatable','data'), [Input('submit-button','n_clicks')], [State('submit-button','n_clicks')]) def update_datatable(n_clicks,csv_file): if n_clicks: dfgb = df.groupby(['state']).sum() return dfgb.to_dict('rows') if __name__ == '__main__': application.run(debug=False, port=8080) </code></pre>
55,305,812
2
0
null
2019-03-20 20:37:25.623 UTC
10
2019-11-26 10:25:51.38 UTC
2019-11-26 10:25:51.38 UTC
null
11,733,759
null
5,405,782
null
1
7
python|pandas|plotly-dash
24,538
<p>When you are trying to register the callback <code>Output</code> component as a <code>DataTable</code>, all the required / mandatory attributes for the <code>DataTable</code> component should be updated in the callback and returned. In your code, you are updating just <code>DataTable.data</code> and not <code>DataTable.column</code>, one easy way is to return the whole <code>Datatable</code> component which is prepopulated with all the required attribute values. </p> <p>Here is an example,</p> <pre><code>import dash_html_components as html import dash_core_components as dcc import dash import dash_table import pandas as pd import dash_table_experiments as dt app = dash.Dash(__name__) #data to be loaded data = [['Alex',10],['Bob',12],['Clarke',13],['Alex',100]] df = pd.DataFrame(data,columns=['Name','Mark']) app.layout = html.Div([ dt.DataTable( rows=df.to_dict('records'), columns=df.columns, row_selectable=True, filterable=True, sortable=True, selected_row_indices=list(df.index), # all rows selected by default id='2' ), html.Button('Submit', id='button'), html.Div(id="div-1"), ]) @app.callback( dash.dependencies.Output('div-1', 'children'), [dash.dependencies.Input('button', 'n_clicks')]) def update_output(n_clicks): df_chart = df.groupby('Name').sum() return [ dt.DataTable( rows=df_chart.to_dict('rows'), columns=df_chart.columns, row_selectable=True, filterable=True, sortable=True, selected_row_indices=list(df_chart.index), # all rows selected by default id='3' ) ] if __name__ == '__main__': app.run_server(debug=True) </code></pre> <p>Looks like <code>dash-table-experiments</code> is deprecated.</p> <p>Edit 1: Here is one way of how it can be achieved using <code>dash_tables</code></p> <pre><code>import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html import dash_table as dt from dash.dependencies import Input, Output, State df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') app = dash.Dash() application = app.server app.layout = html.Div([ dt.DataTable( id = 'dt1', columns = [{"name": i, "id": i,} for i in (df.columns)], ), html.Div([ html.Button(id='submit-button', children='Submit' ) ]), ]) @app.callback(Output('dt1','data'), [Input('submit-button','n_clicks')], [State('submit-button','n_clicks')]) def update_datatable(n_clicks,csv_file): if n_clicks: dfgb = df.groupby(['state']).sum() data_1 = df.to_dict('rows') return data_1 if __name__ == '__main__': application.run(debug=False, port=8080) </code></pre> <p>Another way: return the whole <code>DataTable</code></p> <pre><code>import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html import dash_table as dt from dash.dependencies import Input, Output, State df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') app = dash.Dash() application = app.server app.layout = html.Div([ html.Div(id="table1"), html.Div([ html.Button(id='submit-button', children='Submit' ) ]), ]) @app.callback(Output('table1','children'), [Input('submit-button','n_clicks')], [State('submit-button','n_clicks')]) def update_datatable(n_clicks,csv_file): if n_clicks: dfgb = df.groupby(['state']).sum() data = df.to_dict('rows') columns = [{"name": i, "id": i,} for i in (df.columns)] return dt.DataTable(data=data, columns=columns) if __name__ == '__main__': application.run(debug=False, port=8080) </code></pre> <p>I referred to this example: <a href="https://github.com/plotly/dash-table/blob/master/tests/cypress/dash/v_copy_paste.py#L33" rel="noreferrer">https://github.com/plotly/dash-table/blob/master/tests/cypress/dash/v_copy_paste.py#L33</a></p>
43,581,127
What are the benefits of Apache Beam over Spark/Flink for batch processing?
<p><a href="https://beam.apache.org/documentation/" rel="noreferrer">Apache Beam</a> supports multiple runner backends, including Apache Spark and Flink. I'm familiar with Spark/Flink and I'm trying to see the pros/cons of Beam for batch processing.</p> <p>Looking at the <a href="https://beam.apache.org/get-started/wordcount-example/" rel="noreferrer">Beam word count example</a>, it feels it is very similar to the native Spark/Flink equivalents, maybe with a slightly more verbose syntax.</p> <p>I currently don't see a big benefit of choosing Beam over Spark/Flink for such a task. The only observations I can make so far:</p> <ul> <li>Pro: Abstraction over different execution backends.</li> <li>Con: This abstraction comes at the price of having less control over what exactly is executed in Spark/Flink.</li> </ul> <p>Are there better examples that highlight other pros/cons of the Beam model? Is there any information on how the loss of control affects performance?</p> <p>Note that I'm not asking for differences in the streaming aspects, which are partly covered in <a href="https://stackoverflow.com/questions/35264441/what-is-apache-beam">this question</a> and summarized in <a href="https://cloud.google.com/dataflow/blog/dataflow-beam-and-spark-comparison" rel="noreferrer">this article</a> (outdated due to Spark 1.X).</p>
43,672,838
3
0
null
2017-04-24 06:26:45.41 UTC
34
2022-09-03 07:38:16.233 UTC
2017-05-23 12:09:56.457 UTC
null
-1
null
1,804,173
null
1
107
apache-spark|apache-flink|apache-beam
39,373
<p>There's a few things that Beam adds over many of the existing engines.</p> <ul> <li><p><strong>Unifying batch and streaming.</strong> Many systems can handle both batch and streaming, but they often do so via separate APIs. But in Beam, batch and streaming are just two points on a spectrum of latency, completeness, and cost. There's no learning/rewriting cliff from batch to streaming. So if you write a batch pipeline today but tomorrow your latency needs change, it's incredibly easy to adjust. You can see this kind of journey in the <a href="https://beam.apache.org/get-started/mobile-gaming-example/" rel="noreferrer">Mobile Gaming examples</a>.</p></li> <li><p><strong>APIs that raise the level of abstraction</strong>: Beam's APIs focus on capturing properties of your data and your logic, instead of letting details of the underlying runtime leak through. This is both key for portability (see next paragraph) and can also give runtimes a lot of flexibility in how they execute. Something like ParDo fusion (aka function composition) is a pretty basic optimization that the vast majority of runners already do. Other optimizations are still being implemented for some runners. For example, Beam's <a href="https://beam.apache.org/blog/2016/05/18/splitAtFraction-method.html" rel="noreferrer">Source APIs</a> are specifically built to avoid overspecification the sharding within a pipeline. Instead, they give runners the right hooks to dynamically rebalance work across available machines. This can make a huge difference in performance by essentially eliminating straggler shards. In general, the more smarts we can build into the runners, the better off we'll be. Even the most careful hand tuning will fail as data, code, and environments shift.</p></li> <li><p><strong>Portability across runtimes.</strong>: Because data shapes and runtime requirements are neatly separated, the same pipeline can be run in multiple ways. And that means that you don't end up rewriting code when you have to move from on-prem to the cloud or from a tried and true system to something on the cutting edge. You can very easily compare options to find the mix of environment and performance that works best for your current needs. And that might be a mix of things -- processing sensitive data on premise with an open source runner and processing other data on a managed service in the cloud. </p></li> </ul> <p>Designing the Beam model to be a useful abstraction over many, different engines is tricky. Beam is neither the intersection of the functionality of all the engines (too limited!) nor the union (too much of a kitchen sink!). Instead, Beam tries to be at the forefront of where data processing is going, both pushing functionality into and pulling patterns out of the runtime engines.</p> <ul> <li><a href="https://beam.apache.org/blog/2017/02/13/stateful-processing.html" rel="noreferrer">Keyed State</a> is a great example of functionality that existed in various engines and enabled interesting and common use cases, but wasn't originally expressible in Beam. We recently expanded the Beam model to include a version of this functionality according to Beam's <a href="https://beam.apache.org/contribute/design-principles/" rel="noreferrer">design principles</a>.</li> <li>And vice versa, we hope that Beam will influence the roadmaps of various engines as well. For example, the semantics of Flink's DataStreams were <a href="http://www.zdnet.com/article/going-with-the-stream-unbounded-data-processing-with-apache-flink/" rel="noreferrer">influenced</a> by the Beam (née Dataflow) model. </li> <li>This also means that the capabilities will not always be exactly the same across different Beam runners at a given point in time. So that's why we're using <a href="https://beam.apache.org/documentation/runners/capability-matrix/" rel="noreferrer">capability matrix</a> to try to clearly communicate the state of things. </li> </ul>
1,270,018
Explain the FFT to me
<p>I want to take audio PCM data and find peaks in it. Specifically, I want to return the frequency and time at which a peak occurs.</p> <p>My understanding of this is that I have to take the PCM data and dump it into an array, setting it as the real values with the complex parts set to 0. I then take the FFT, and I get an array back. If each number in the array is a magnitude value, how do I get the frequency associated with each one? Also, do I take the magnitude of the real &amp; complex part or just discard the complex values?</p> <p>Finally, if I wanted to find the peaks in a single song, do I just set a small window to FFT and slide it across all of the audio? Any suggestions on how large that window should be?</p>
1,274,663
3
1
null
2009-08-13 04:22:41.827 UTC
14
2009-12-18 19:42:59.403 UTC
null
null
null
null
143,879
null
1
15
audio|signals|frequency|fft
8,329
<p>You may actually be looking for a <em><a href="http://en.wikipedia.org/wiki/Spectrogram" rel="nofollow noreferrer">spectrogram</a></em>, which is basically an FFT of the data in a small window that's slid along the time axis. If you have software that implements this, it might save you some effort. It's what's commonly used for analysing time varying acoustic signals, and is a very useful way to look at sounds. Also, there are some tricks, for example, with windowing data for FFTs, that the spectrogram will probably get right, but will be harder (though not very hard) for you to do correctly.</p>
1,043,378
Print full call stack on printStackTrace()?
<p>I need to write small a log analyzer application to process some log files generated by a 3rd party closed source library (having custom logger inside) used in my project. </p> <p>In case of an exception entry in the log I need to collect aggregated information about the methods involved along the stack trace from the top to the actual place of the exception.</p> <p>Unfortunately, by default Java printStackTrace() does not print every method in the call stack but up to a certain number and the rest is just referenced as <code>16 more...</code>.</p> <p>If I could catch the exception myself I would use the getStackTrace() and print it myself but the root cause is never included in the exception this library throws.</p> <p><em>Is there a way to ask Java to print the entire call stack in the stacktrace?</em></p> <p><em>Apart from my situation do common logging frameworks have option for this?</em></p> <p><strong>Edit:</strong> The program runs on Sun's JVM with JDK 1.5.0_09. No option to change that.</p>
1,043,484
3
1
null
2009-06-25 11:19:30.19 UTC
7
2013-01-03 20:13:40.227 UTC
2009-06-25 11:50:58.783 UTC
null
61,158
null
61,158
null
1
48
java|logging|stack-trace
64,777
<p><a href="https://stackoverflow.com/questions/437756/how-do-i-stop-stacktraces-truncating-in-logs">here is an explanation</a> of the 'caused by' and '... <em>n</em> more' lines in the printed trace. see also the <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace%28%29" rel="noreferrer">JavaDoc for printStackTrace</a>. you might not have any work to do.</p> <blockquote> <p>Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught.</p> </blockquote>
35,311,318
Opening Shiny App directly in the default browser
<p>Normally the shiny app opens through the inbuilt browser within R-Studio. Is it possible to open the app directly in the web browser, say Google Chrome, without going through the R-Studio.</p>
35,312,401
4
2
null
2016-02-10 09:33:01.013 UTC
8
2022-08-04 14:55:43.07 UTC
2022-08-04 14:55:43.07 UTC
null
5,221,626
null
4,246,716
null
1
34
r|shiny
30,248
<p>To run it using different approach to @Batanichek you can locate the executables of each of your browsers and then specify it in options which to point to, as so:</p> <p><strong>Edit:</strong> You can find the <code>options</code> and its arguments in the R environment (I used RStudio) e.g. <code>options(browser = )</code></p> <p><strong>Step 1: Locate where your .exe files are installed for all you browsers, then add the following:</strong></p> <p>For Chrome</p> <pre><code>options(browser = "C:/Program Files/Google/Chrome/Application/chrome.exe") </code></pre> <p>For Firefox</p> <pre><code>options(browser = "C:/Program Files/Mozilla Firefox/firefox.exe") </code></pre> <p>For IE</p> <pre><code>options(browser = "C:/Program Files/Internet Explorer/iexplore.exe") </code></pre> <p><strong>Step 2: Run the app as always</strong></p> <pre><code>runApp(list(ui = ui, server = server),host="192.168.xx.xx",port=5013, launch.browser = TRUE) </code></pre>
28,677,638
ngChange-like functionality for the entire form
<p>I would like to do an equivalent of <code>ng-change</code> for the entire form whenever there is a change in one of its input fields.</p> <p>I know that since AngularJS 1.3 I have the debounce option but it applies only for a single input.</p> <p>I'm looking for a "debounce"/"on change" functionality that will apply for the entire form.</p>
28,678,545
4
1
null
2015-02-23 15:49:16.983 UTC
9
2018-08-10 12:26:20.83 UTC
2017-06-02 21:03:31.47 UTC
null
1,264,804
null
1,846,993
null
1
42
angularjs|onchange|forms
38,499
<p>There isn't a built-in way to do <code>ng-change</code> for a form.</p> <p>It may not even be needed, because if you organized your view model properly, then your form inputs are likely bound to a certain scope-exposed property:</p> <pre><code>$scope.formData = {}; </code></pre> <p>and in the View:</p> <pre><code>&lt;form name="form1"&gt; &lt;input ng-model="formData.a"&gt; &lt;input ng-model="formData.b"&gt; &lt;/form&gt; </code></pre> <p>Then you could deep-watch (with <code>$watch</code>) for model changes (and apply whatever debounce option on elements that you need):</p> <pre><code>$scope.$watch("formData", function(){ console.log("something has changed"); }, true); </code></pre> <p><strong>Then problem is</strong>, of course, that this is a deep-watch and it is expensive. Also, it reacts not only to changes in the Form, but also to a change in <code>formData</code> from any source.</p> <p>So, as an alternative, you could create your own directive to compliment the form and react to form's change events.</p> <pre><code>.directive("formOnChange", function($parse){ return { require: "form", link: function(scope, element, attrs){ var cb = $parse(attrs.formOnChange); element.on("change", function(){ cb(scope); }); } } }); </code></pre> <p>and the usage is:</p> <pre><code>&lt;form name="form1" form-on-change="doSomething()"&gt; &lt;input ng-model="formData.a"&gt; &lt;input ng-model="formData.b"&gt; &lt;/form&gt; </code></pre> <p><a href="http://plnkr.co/edit/el1Z5z37geFsAc76toFv?p=preview">plunker</a> for illustration.</p> <p>Note, that the "change" event is fired only on blur for a text input, as per <a href="http://api.jquery.com/change/">jQuery documentation:</a></p> <blockquote> <p>The <code>change</code> event is sent to an element when its value changes. This event is limited to <code>&lt;input&gt;</code> elements, <code>&lt;textarea&gt;</code> boxes and <code>&lt;select&gt;</code> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.</p> </blockquote>
28,742,018
Swift Increase font size of the UITextview,how?
<p>I am trying to add two buttons to my app to set the font size of a UITextview,and i found this function</p> <pre><code>textview.font.increaseSize(...) //and decreaseSize(...) </code></pre> <p>But i don't understand what I have to put inside the parentheses,i want to increase and decrease the font size by one point</p> <p>Thanks for the answers</p>
28,742,178
5
1
null
2015-02-26 12:05:50.07 UTC
8
2020-06-05 07:00:30.457 UTC
null
null
null
null
4,561,398
null
1
29
ios|swift|fonts|uitextview
43,923
<p>I don't think there's a method named <code>increaseSize()</code>. May be you've find some <code>UIFont</code> or <code>UITextView</code> category.</p> <p>The <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIFont_Class/">official <code>UIFont</code></a> class document doesn't reveal any such method.</p> <p>Additionally you can increase the font like this:</p> <pre><code>textview.font = UIFont(name: textview.font.fontName, size: 18) </code></pre> <p>The above statement will simply set the existing font size to 18, change it to whatever you want.</p> <p>However if you want some method like you've posted, you can introduce your own category like this:</p> <pre><code>extension UITextView { func increaseFontSize () { self.font = UIFont(name: self.font.fontName, size: self.font. pointSize+1)! } } </code></pre> <p><strong>Swift 2 &amp; 3:</strong></p> <pre><code>import UIKit extension UITextView { func increaseFontSize () { self.font = UIFont(name: (self.font?.fontName)!, size: (self.font?.pointSize)!+1)! } } </code></pre> <p>and simply import this to wherever you want to use like this:</p> <pre><code>textview.increaseFontSize() </code></pre> <p>it'll increase the font by 1 every time you call it..</p>
56,435,054
Xcode Canvas for SwiftUI previews does not show up
<p>I´m trying to get the new Canvas feature from Xcode 11 running, but the Canvas won´t show up. What am I doing wrong?</p> <p>This new Xcode feature should show a live preview of my SwiftUI views without running the app.</p> <blockquote> <p>When you create a custom View with SwiftUI, Xcode can display a preview of the view’s content that stays up to date as you make changes to the view’s code. You define a structure that conforms to the PreviewProvider protocol to tell Xcode what to display. Xcode shows the preview in a canvas beside your code.</p> <p><a href="https://developer.apple.com/documentation/swiftui/previews-in-xcode" rel="nofollow noreferrer">https://developer.apple.com/documentation/swiftui/previews-in-xcode</a></p> </blockquote> <p>I just created a new default project (single view app), compiled it and activated 'Editor &gt; Editor and Canvas'. I can navigate to each file in the project, nothing shows up.</p> <p>What else does need to be done?</p>
56,435,175
18
1
null
2019-06-03 22:00:20.857 UTC
4
2022-09-16 10:12:48.603 UTC
2022-04-21 19:02:35.423 UTC
null
1,265,393
null
727,742
null
1
45
ios|swift|xcode|swiftui|xcode11
35,003
<p>You need to be on <strong>Catalina</strong> macOS version (10.15), as stated in <a href="https://developer.apple.com/tutorials/swiftui/creating-and-combining-views" rel="noreferrer">official tutorial</a></p> <p>Be warned: Catalina doesn't support 32-bit applications, some old apps will stop working after update.</p>
24,034,588
Static Html Website - Bootstrap - Multi language Support
<p>To begin with I want to state that I am newbie in Web Development.</p> <p>I was asked to build a static website (for a small - size hotel), and I bought <a href="http://themeforest.net/item/sunshine-responsive-hotel-template/5635208?WT.ac=search_item&amp;WT.seg_1=search_item&amp;WT.z_author=aveothemes">this</a> responsive html5 - CSS3 template. It consists of pure html5 - css3 , and some JavaScript for slideshows etc and uses the bootstrap framework.</p> <p>I have already build the website, and now I was asked to add multilanguage support to it. Can I accomplish this via bootstrap? Can it even be done with CSS? </p> <p>If not, should I have a copy of all my .html files in a subfolder (e.g "website"/en/"content" ) and redirect the user via a link at the top of the page, or should I use JavaScript to decide the language?</p> <p>Briefly, I would like a user that visits my website from another country to get the English version of the site, while all others get the default language. I want as fast development as possible (that's why I bought a template) to get up and running asap (summer season has already started). I have a reasonable background in programming, but I am totally new in Web Development.</p>
24,035,422
7
0
null
2014-06-04 10:07:35.027 UTC
19
2021-09-27 05:46:47.903 UTC
2015-12-19 03:54:55.903 UTC
null
1,045,902
null
2,254,704
null
1
30
javascript|html|css|twitter-bootstrap-3|multilingual
66,184
<p>You can do this within a single file without using any server-side programming languages. You should check out <a href="http://i18next.com">i18next</a> for a proper <strong>javascript solution</strong>. </p> <p>You can also use pure <strong>CSS</strong> to translate a homepage. Try something like </p> <pre><code>.en, .de, .it { display:none; } /* hide all elements with a language class */ .en:lang(en), .de:lang(de), .it:lang(it) { display:block; } /* show those elements that match their language class */ </code></pre> <p>When you set a proper lang attribute on your html tag (e.g. by javascript) you can translate your page very easy:</p> <pre><code>&lt;div class="en"&gt;Good morning&lt;/div&gt; &lt;div class="de"&gt;Guten Morgen&lt;/div&gt; &lt;div class="it"&gt;Ciao&lt;/div&gt; </code></pre>
42,889,699
Smooth drawing with Apple Pencil
<p>I am developing a diagraming app for Apple Pencil using Qt-5.8/PyQt5 and am trying to get the pencil strokes as smooth as some of the other apps that I am seeing, namely Notability and PDF Expert. I patched Qt-5.8 to provide fast access to the floating-point coalesced and predicted UITouch data provided by Apple and my app code is fast and responsive, but the lines are still jittery (see screenshots):</p> <p><a href="https://i.stack.imgur.com/PlqpI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PlqpI.jpg" alt="My Current Code"></a> <a href="https://i.stack.imgur.com/3QPPH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3QPPH.jpg" alt="enter image description here"></a></p> <p>Notability and PDF Expert both produce lines that maintain their sharpness at various levels of zoon, which suggests to me that they may be vectorized.</p> <p>Anyone have a suggestion for smoothing out my painting? I am already painting at retina resolution and using the same 250Hz Apple Pencil data as they are. Is there a mathematical technique for smoothing a series of points, or some other trick out there?</p>
42,891,040
2
1
null
2017-03-19 17:25:31.513 UTC
9
2019-08-08 10:52:08.993 UTC
2017-03-19 19:26:23.937 UTC
null
1,271,826
null
414,605
null
1
2
ios|qt|uikit
2,756
<p>Note taking apps tend to actually store and paint the drawings as vectors, which is why they are smooth. It also enables several cool features, like being able to select and move text around, change its color and style, it is also very efficient for storage and can be zoomed in or out without loss of resolution, compared to raster painting. </p> <p>In some applications there is even a two step process, there is an initial smoothing taking place while drawing a specific glyph and another pass which takes place after you lift the pen and the glyph is considered finished.</p> <p>Your code on the other hand looks very raster-y. There is a number of ways to simplify the input points, ranging from very simple to incredibly complex.</p> <p>In your case what you could try is rather simple, and should work fine for the kind of usage you are aiming at.</p> <p>You need to keep processing each stroke / glyph as the pen moves, and instead of adding every intermediate position to the stroke control points, you only add points that deviate from the current angle / direction above a certain threshold. It is conceptually a lot like the <a href="https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm" rel="noreferrer">Ramer–Douglas–Peucker algorithm</a>, but you don't apply it on pre-existing data points, but rather while the points are created, which is more efficient and better for user experience.</p> <p>Your first data point is created when you put down the pen on the screen. Then you start moving the pen. You now have a second point, so you add that, but also calculate the angle of the line which the two points form, or the direction the pen is going. Then, as you move the pen further, you have a third point, which you check against the second point, and if the angle difference is not above the threshold, instead adding the third point you modify to extend the second point to that position effectively eliminating a redundant point. So you only end up creating points with deviate enough to form the rough shape of the line, and skip all the tiny little variances which create your jittery lines.</p> <p>This is only the first step, this will leave you with a simplified, but faceted line. If you draw it directly, it will not look like a smooth curve, but like a series of line segments. The second step is point interpolation, probably regular old <a href="http://blog.ivank.net/interpolation-with-cubic-splines.html" rel="noreferrer">cubic interpolation</a> will do just fine. You then get each actual position by interpolating between each set of 3 points, and draw the brush stroke at every brush spacing threshold. When interpolating the position, you also interpolate the brush pressure between the two points defining the currently drawn segment, which you must store along with each curve defining point. The pressure interpolation itself can be as simple as linear.</p>
42,952,979
go version command shows old version number after update to 1.8
<p>Pretty much the title. I downloaded/installed Go 1.8 for OS X, but when I go</p> <pre><code>$ go version go version go1.7.5 darwin/amd64 </code></pre> <p>My .bashrc look like the following</p> <pre><code># some exports omitted NPM_PACKAGES=/Users/&lt;me&gt;/.npm-packages NODE_PATH="$NPM_PACKAGES/lib/node_modules:$NODE_PATH" export PATH=~/Library/Python/3.4/bin:$PATH export GOPATH=$HOME/Go export PATH=$PATH:/usr/local/go/bin </code></pre> <p>My workspace is in a directory called "Go" in my home folder. </p> <p>What I have checked so far:</p> <ul> <li><p>I've checked the files in /usr/local/go/bin, and the VERSION file states "1.8", so I know the installation was successful.</p></li> <li><p>I have also renewed my terminal session, I even rebooted my pc to make sure no other processes were interfering with it.</p></li> <li><p>I use Webstorm as my IDE, and it correctly recognized 1.8 as the working version</p></li> <li><p>It's not a bug in the version number itself, as I can't use the "NextResultSet()" sql functionality, introduced in version 1.8</p></li> </ul> <p>I believe the culprit might be a wrong configuration in the .bashrc file above, as only the terminal is stuck on the old version, but I can't figure out what is wrong with it.</p>
42,953,523
6
2
null
2017-03-22 13:24:52.82 UTC
9
2022-05-13 10:39:01.25 UTC
null
null
null
null
1,400,741
null
1
46
macos|go|upgrade
88,719
<p>You obviously have an old version of Go installed, else you couldn't see <code>go version go1.7.5 darwin/amd64</code> as the output of <code>go version</code>.</p> <p>IDEs might have more advanced method of detecting Go installations other that simply scanning <code>PATH</code> and <code>GOROOT</code> (and that's why your IDE found and suggested the newer Go 1.8).</p> <p>Execute <code>which go</code>, and you'll see where your old Go resides. Remove it (and references to it).</p> <p>Note that in your <code>.bashrc</code> you're appending the proper Go <code>bin</code> folder to the <em>end</em> of <code>PATH</code>:</p> <pre><code>export PATH=$PATH:/usr/local/go/bin </code></pre> <p>Which means if <code>PATH</code> contains the <code>bin</code> folder of the old Go installation (very likely), that is used to execute the <code>go</code> command.</p>
36,200,749
How do you add more property values to a custom object
<p>If I do this</p> <pre><code>$account = New-Object -TypeName psobject -Property @{User="Jimbo"; Password="1234"} </code></pre> <p>How do I add <strong>additional</strong> User and Password values to <code>$account</code> without overwriting the existing one?</p> <p>I cannot pre-populate <code>$account</code> from a hashtable. I don't know all the users and passwords at runtime.</p>
36,200,906
2
2
null
2016-03-24 12:57:02.983 UTC
4
2018-06-11 08:06:08.543 UTC
2016-03-24 13:24:32.373 UTC
null
1,630,171
null
5,233,104
null
1
18
powershell|object
54,666
<p>If you want to use <code>$account</code> to store user + pwd credentials, you should declare it as an <code>array</code> and add items when you want:</p> <pre><code>$account = @() $account += New-Object -TypeName psobject -Property @{User="Jimbo"; Password="1234"} $account += New-Object -TypeName psobject -Property @{User="Jimbo2"; Password="abcd"} $account += New-Object -TypeName psobject -Property @{User="Jimbo3"; Password="idontusepwds"} </code></pre> <p>Output of <code>$account</code>:</p> <pre><code>User Password ---- -------- Jimbo 1234 Jimbo2 abcd Jimbo3 idontusepwds </code></pre>
5,739,140
MediaScannerConnection produces android.app.ServiceConnectionLeaked
<p>I'm using the MediaScannerConnection example code from the <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/content/ExternalStorage.html" rel="nofollow noreferrer">API Demos</a></p> <p>The snippet I'm using is:</p> <pre><code>MediaScannerConnection.scanFile( context, new String[] { permFile.getAbsolutePath() }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { android.util.Log.i("ExternalStorage", "Scanned " + path + ":"); android.util.Log.i("ExternalStorage", "-&gt; uri=" + uri); } }); </code></pre> <p>When I run this code, I get an FC dialog with the following from the <a href="https://sites.google.com/site/androidhowto/how-to-1/save-logcat-to-a-text-file" rel="nofollow noreferrer">LogCat</a>:</p> <pre><code>4-20 23:17:45.988: ERROR/ActivityThread(3015): Activity com.my.package.name has leaked ServiceConnection android.media.MediaScannerConnection@40715c70 that was originally bound here 04-20 23:17:45.988: ERROR/ActivityThread(3015): android.app.ServiceConnectionLeaked: Activity com.my.package.name has leaked ServiceConnection android.media.MediaScannerConnection@40715c70 that was originally bound here </code></pre> <p>What am I doing wrong?</p> <p>FYI, I'm running this from a background thread using AsyncTask.</p>
12,821,924
3
3
null
2011-04-21 03:22:30.08 UTC
6
2019-11-07 09:06:22.1 UTC
2019-11-07 08:54:57.333 UTC
null
63,550
null
341,390
null
1
29
android|sample
7,104
<p>I noticed the same kind of error message using the code snippet provided with the documentation of <a href="http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory%28java.lang.String%29" rel="nofollow noreferrer">Environment.getExternalStoragePublicDirectory</a>.</p> <p>The code works fine as expected and makes a <strong>new file visible in the device gallery</strong>, but at the same time prints the error about the <code>leaked ServiceConnection</code>.</p> <p>Looking at the internal Android code of the <code>MediaScannerConnection</code> it seems some kind of mechanism exists to stop the service after the last file. Maybe it doesn't work when given only one file?</p> <p>I ended up using an entirely different solution by informing the MediaScanner via Intent. This works fine too and it is not producing any warnings:</p> <pre><code>Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri fileContentUri = Uri.fromFile(permFile); // With 'permFile' being the File object mediaScannerIntent.setData(fileContentUri); this.sendBroadcast(mediaScannerIntent); // With 'this' being the context, e.g. the activity </code></pre> <p>It seems this is the preferred way, and it is mentioned in the <a href="http://developer.android.com/training/camera/photobasics.html#TaskGallery" rel="nofollow noreferrer">Android Training about Taking Photos</a> too.</p>
5,832,208
WPF Attached Property Data Binding
<p>I try to use binding with an attached property. But can't get it working.</p> <pre><code>public class Attached { public static DependencyProperty TestProperty = DependencyProperty.RegisterAttached("TestProperty", typeof(bool), typeof(Attached), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Inherits)); public static bool GetTest(DependencyObject obj) { return (bool)obj.GetValue(TestProperty); } public static void SetTest(DependencyObject obj, bool value) { obj.SetValue(TestProperty, value); } } </code></pre> <p>The XAML Code:</p> <pre><code>&lt;Window ...&gt; &lt;StackPanel local:Attached.Test="true" x:Name="f"&gt; &lt;CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}" /&gt; &lt;CheckBox local:Attached.Test="true" IsChecked="{Binding (local:Attached.Test), Mode=TwoWay}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>And the Binding Error:</p> <pre><code>System.Windows.Data Error: 40 : BindingExpression path error: '(local:Attached.Test)' property not found on 'object' ''StackPanel' (Name='f')'. BindingExpression:Path=(local:Attached.Test); DataItem='StackPanel' (Name='f'); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1') </code></pre>
5,832,247
3
0
null
2011-04-29 12:45:30.63 UTC
21
2019-01-10 07:32:33.317 UTC
2018-11-13 18:34:40.78 UTC
null
1,644,522
null
613,320
null
1
80
wpf|xaml|binding|attached-properties
43,253
<p>Believe it or not, just add <code>Path=</code> and use parenthesis when binding to an attached property:</p> <pre><code>IsChecked="{Binding Path=(local:Attached.Test), Mode=TwoWay, RelativeSource={RelativeSource Self}}" </code></pre> <p>In addition, your call to <code>RegisterAttached</code> should pass in "Test" as the property name, not "TestProperty".</p>
2,200,250
How to "automatically" remove unused units from uses clause?
<p>Does anyone know about a utility, that can automatically detect and remove unrequired units from the <code>uses</code> clause? </p> <p>Preferably it .. </p> <ul> <li>can be run against a unit and/or a project</li> <li>is free and works with Delphi 2010</li> </ul> <p>Thanks in advance.</p>
2,200,324
2
3
null
2010-02-04 14:16:02.137 UTC
13
2019-12-13 08:15:41.843 UTC
2018-10-25 17:09:36.36 UTC
null
9,818,506
null
266,256
null
1
27
delphi|delphi-2010
12,244
<p>Try using the "Uses Unit Cleaner" Wizard from <a href="http://www.cnpack.org/index.php?lang=en" rel="nofollow noreferrer">CnPack</a> you can download from <a href="http://www.cnpack.org/showdetail.php?id=669&amp;lang=en" rel="nofollow noreferrer">here</a></p> <p><a href="https://i.stack.imgur.com/fXzV7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXzV7.png" alt="alt text"></a> </p> <p>Another option is use <a href="http://www.peganza.com/download.htm" rel="nofollow noreferrer">ICARUS</a>.</p> <blockquote> <p>ICARUS is a small subset of Pascal Analyzer. It parses Delphi or Borland Pascal source code and generates a list of unneeded unit references in your uses lists</p> </blockquote>
1,495,636
Can I have an Action<> or Func<> with an out param?
<p>I have a method with an <code>out</code> parameter, and I'd like to point an <code>Action</code> or <code>Func</code> (or other kind of delegate) at it.</p> <p>This works fine:</p> <pre><code>static void Func(int a, int b) { } Action&lt;int,int&gt; action = Func; </code></pre> <p>However this doesn't</p> <pre><code>static void OutFunc(out int a, out int b) { a = b = 0; } Action&lt;out int, out int&gt; action = OutFunc; // loads of compile errors </code></pre> <p>This is probably a duplicate, but searching for 'out parameter' isn't particularly fruitful.</p>
1,495,657
2
1
null
2009-09-30 00:47:24.247 UTC
6
2013-01-23 17:51:51.167 UTC
null
null
null
null
234
null
1
40
c#|delegates
21,101
<p>Action and Func specifically do not take out or ref parameters. However, they are just delegates.</p> <p>You can make a custom delegate type that does take an out parameter, and use it, though.</p> <p>For example, the following works:</p> <pre><code>class Program { static void OutFunc(out int a, out int b) { a = b = 0; } public delegate void OutAction&lt;T1,T2&gt;(out T1 a, out T2 b); static void Main(string[] args) { OutAction&lt;int, int&gt; action = OutFunc; int a = 3, b = 5; Console.WriteLine("{0}/{1}",a,b); action(out a, out b); Console.WriteLine("{0}/{1}", a, b); Console.ReadKey(); } } </code></pre> <p>This prints out:</p> <pre><code>3/5 0/0 </code></pre>
1,655,361
how to clone an old git-commit (and some more questions about git)
<p>I have a git-repository of my project with about 20 commits. I know how to clone the actual commit with <code>git clone</code>, </p> <ul> <li>but how can I "clone" an old commit? </li> <li>is there a really good git-GUI (imho <code>qgit</code> is not a good GUI)? </li> <li>what exactly are "branches"?</li> <li>when I want to release 0.1, 0.2 and so on, what is the best way to mark these commits in git?</li> <li>what are the big differences to svn?</li> </ul>
1,655,666
2
0
null
2009-10-31 19:32:05.96 UTC
32
2016-02-26 13:45:39.36 UTC
null
null
null
null
150,667
null
1
84
git
105,878
<p>A git repository contains the all history at all time.<br> So when you are cloning a repository, you are cloning it with its full history, and <em>then</em>, you can make a branch from whatever commit you want:</p> <pre><code> $ git checkout -b aNewBranch SHA1 </code></pre> <p>with SHA1 representing the commit id from which you want to proceed.</p> <hr> <p>Branches in Git are just a way to keep track of one path of a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph" rel="noreferrer">DAG (Directed Acyclic Graph)</a> which is the set of commits representing the history of a Git repository.<br> It is a mere pointer you assign to one of those commits, and it will keep moving along with each new commits.</p> <p><img src="https://i.stack.imgur.com/2HRWl.png" alt="branches"></p> <p>See <a href="http://git-scm.com/book/en/Git-Branching-What-a-Branch-Is" rel="noreferrer"><strong>Pro Git</strong></a> book for more.</p> <hr> <p>You can mark a specific commit with <a href="http://git-scm.com/book/ch2-6.html" rel="noreferrer">a tag</a>, which, like a branch, is a mere pointer, but an immutable one (it wont move when you make new commit).<br> You will use preferably <strong>annotated</strong> tags, which are stored as full objects in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG).</p> <hr> <p>The "Graphical Interfaces" section of <a href="https://git.wiki.kernel.org/index.php/InterfacesFrontendsAndTools" rel="noreferrer">InterfacesFrontendsAndTools</a> page on Git Wiki lists the various GUI for Git at the moment. </p> <hr> <p>You will see many questions about the difference between Git and SVN: see <a href="https://stackoverflow.com/questions/885213/in-short-what-are-the-advantages-of-git-and-mercurial-over-subversion/885272#885272">my answer</a> (or <a href="https://stackoverflow.com/questions/995636/popularity-of-git-mercurial-bazaar-vs-which-to-recommend/995799#995799">this one</a>) for example.<br> My most complete answer about the fundamental differences between Git and SVN is here:<br> <a href="https://stackoverflow.com/a/2549128/6309">"which of the two is better:git or SVN"</a>.</p>
32,291,026
Latex table multiple row and multiple column
<p>I'm trying to create a table in Latex but without success. I tried different solutions but no one solves my problem. I would like create a table like the picture below:</p> <p><a href="https://i.stack.imgur.com/xZnUZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xZnUZ.png" alt="enter image description here" /></a></p> <p>Can anyone show how to do this in Latex please?</p>
32,291,618
2
2
null
2015-08-29 21:53:26.563 UTC
12
2021-02-04 22:40:07.387 UTC
2021-02-04 22:40:07.387 UTC
null
3,543,233
null
1,037,475
null
1
25
latex|multiple-columns|tabular|multirow
126,339
<p>One first sketch may be the following:</p> <pre class="lang-latex prettyprint-override"><code>\documentclass{article} \usepackage{multirow} \begin{document} \begin{tabular}{|c|c|c|c|c|c|} \hline \multirow{3}{*}{A} &amp; \multicolumn{2}{c|}{User B} &amp; % \multicolumn{2}{c|}{User C} &amp; \multirow{3}{*}{D}\\ \cline{2-5} &amp; \multicolumn{2}{c|}{Value} &amp; \multicolumn{2}{c|}{Value} &amp; \\ \cline{2-5} &amp; B1 &amp; B2 &amp; C1 &amp; C2 &amp; \\ \hline &amp; &amp; &amp; &amp; &amp; \\ \hline &amp; &amp; &amp; &amp; &amp; \\ \hline % etc. ... \end{tabular} \end{document} </code></pre> <p>It produces:</p> <p><a href="https://i.stack.imgur.com/90z5h.png" rel="noreferrer"><img src="https://i.stack.imgur.com/90z5h.png" alt="screenshot of output"></a></p> <p><strong>Addendum:</strong></p> <pre class="lang-latex prettyprint-override"><code>\documentclass{article} \usepackage{multirow} \begin{document} {\sffamily % \begin{tabular}{|c|c|c|c|c|c|c|}% seven columns now, not six... \hline \multirow{3}{*}{A} &amp; \multicolumn{2}{c|}{User B} &amp; \multirow{3}{*}{X} &amp; % \multicolumn{2}{c|}{User C} &amp; \multirow{3}{*}{D}\\ \cline{2-3}\cline{5-6} &amp; \multicolumn{2}{c|}{Value} &amp; &amp; \multicolumn{2}{c|}{Value} &amp; \\ \cline{2-3}\cline{5-6} &amp; B1 &amp; B2 &amp; &amp; C1 &amp; C2 &amp; \\ \hline &amp; &amp; &amp; &amp; &amp; &amp; \\ \hline &amp; &amp; &amp; &amp; &amp; &amp; \\ \hline % etc. ... \end{tabular} }% \end{document} </code></pre> <p>produces:</p> <p><a href="https://i.stack.imgur.com/IMfUw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IMfUw.png" alt="enter image description here"></a></p> <p>Please, <em>critically</em> check all the differences between the original code and this latter.</p> <p>Don't forget that several LaTeX packages can help you improving style, dimensions and spacing of your table: among these, I advise you to have a look at <a href="https://www.ctan.org/pkg/bigstrut" rel="noreferrer"><code>bigstrut</code></a>.</p> <p>Also:</p> <pre class="lang-latex prettyprint-override"><code>\documentclass{article} \usepackage{multirow} \begin{document} \begin{tabular}{|c|c|c|c|c|c|c|} \hline \multirow{3}{*}{A} &amp; \multirow{3}{*}{X} &amp; \multicolumn{2}{c|}{User B} &amp; \multicolumn{2}{c|}{User C} &amp; \multirow{3}{*}{D}\\ \cline{3-6} &amp; &amp; \multicolumn{2}{c|}{Value} &amp; \multicolumn{2}{c|}{Value} &amp; \\ \cline{3-6} &amp; &amp; B1 &amp; B2 &amp; C1 &amp; C2 &amp; \\ \hline &amp; &amp; &amp; &amp; &amp; &amp; \\ \hline \end{tabular} \end{document} </code></pre> <p>You should now be able to operate on your own further changes to the model of table.</p>
6,309,725
Newtonsoft ignore attributes?
<p>I am currently using the same C# DTOs to pull data out of CouchDB, via LoveSeat which I am going to return JSON via an ASP MVC controller.</p> <p>I am using the NewtonSoft library to seralise my DTOs before sending them down through the controller. </p> <p>However, as CouchDB also uses NewtonSoft it is also respecting the property level NewtonSoft attributes such as </p> <pre><code>[JsonIgnore] [JsonProperty("foo")] </code></pre> <p>Is there anyway to tell the newtonsoft library to ignore these attributes explicitly? LoveSeat allows me to provide my own implementation of IObjectSerializer, which gives me full control over netwonsofts JsonSerializerSettings. So, can I ignore the attributes by using those settings ? </p> <p>I ask as the only alternative I can see at this point, is to dupe my DTOs. While not that's not terrible, it isn't great either. </p> <p>The only other way I can see is to bring in my own version of the Newtonsoft.Json source into my project, with a different assembly name etc etc. But this way madness definitely lies and I will just dupe the DTOs before I go down this road.</p>
6,315,258
5
0
null
2011-06-10 17:04:02.823 UTC
9
2019-10-04 00:46:01.78 UTC
2019-04-04 09:49:51.677 UTC
null
9,267,987
null
208,754
null
1
83
c#|asp.net-mvc|couchdb|json.net
111,269
<p>I ended up making all properties I needed to only add attributes to virtual, and overriding them alone in another class, with the relevant newtonsoft attributes.</p> <p>This allows me to have different serialisation behavior when de-serialising from CouchDB and serialising for a GET, without too much dupe. It is fine, and a bonus, that the two are coupled; any changes in the base i would want anyway.</p> <p>It would still be nice to know if my original question is possible?</p>
5,735,592
Determine Keys from Functional Dependencies
<p>I'm taking a database theory course, and it's not clear to me after doing the reading how I can infer keys, given a set of functional dependencies.</p> <p>I have an example problem:</p> <p>Find all keys of the relation R(ABCDEFG) with functional dependencies</p> <pre><code>AB → C CD → E EF → G FG → E DE → C BC → A </code></pre> <p>Demonstrate your knowledge by identifying which of the following is a key.</p> <pre><code>a. BCDEF b. ADFG c. BDFG d. BCDE </code></pre> <p>Can someone walk me through how I should decompose the functional dependencies to conclude that some combination of attributes is a key? I expect I'll face a number of these types of problems and I need to understand how to approach it.</p>
5,736,174
6
2
null
2011-04-20 19:26:53.523 UTC
23
2019-08-04 17:48:16.5 UTC
2012-10-02 16:12:26.81 UTC
null
992,687
null
641,455
null
1
45
database|functional-dependencies
79,557
<p>Take an FD, e.g. AB→C</p> <p>Augment until all attributes are mentioned, e.g. ABDEFG → CDEFG (note that this is equivalent to ABDEFG → ABCDEFG because it is trivially true that A->A and B->B).</p> <p>This tells you that ABDEFG is a superkey.</p> <p>Check the other FDs in which the LHS is a subset of your superkey, and that on its RHS contains some other attribute of your superkey.</p> <p>There are two. EF→G and FG→E. Remove the attributes of the RHS of these from your superkey. Doing so gives you two keys, that are certainly superkeys, but not necessarily irreducible ones: ABDEF and ABDFG.</p> <p>However, from AB→C and CD→E we can also derive that ABD→E. Hence we can also remove the E from our ABDEF key. The nasty thing here is that when I said "Check the other FDs", that apparently means that you should also check any FD that appears in the closure of your set of FDs (i.e. any FD that is derivable from your given set of FDs)... And that's a bit impractical to do by hand ...</p> <p>A useful site for verifying whether your results are correct:</p> <p><a href="http://raymondcho.net/RelationalDatabaseTools/RelationalDatabaseTools" rel="nofollow noreferrer">http://raymondcho.net/RelationalDatabaseTools/RelationalDatabaseTools</a></p> <p>You should now be able to determine that option c is a key.</p>
5,687,341
iPhone:Programmatically compressing recorded video to share?
<p>I have implemented an overlay view when calling camera view before recording the video.</p> <pre><code>pickerController.cameraOverlayView =myOverlay; </code></pre> <p>Video recording and saving the video into Album after recording the video and sharing via email etc. all works fine.</p> <p>If i use video quality as "High quality", then the recorded video has become huge size. For example, if i record video for 30 seconds with high quality, recorded video has become around 30 - 40 mb.</p> <pre><code>pickerController.videoQuality = UIImagePickerControllerQualityTypeHigh; </code></pre> <p>How do i program to compress the high quality recorded video before sharing it, like how Apple does with built-in Video recorder?</p> <p>Please guide me to resolve this.</p> <p>Thanks!</p> <p><strong>UPDATED:</strong></p> <p>This is what i'm trying recently, but still no success: I want to compress the recorded video taken which comes to didFinishPickingMediaWithInfo and store in same photo album actual video path itself, not anywhere else. I tested the same video is compressed to very small size when i pick from photo library, but the same video taken from camera and came via didFinishPickingMediaWithInfo is not compressed, though i used the AVAssetExportSession code below.</p> <pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) { NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSString *urlPath = [videoURL path]; if ([[urlPath lastPathComponent] isEqualToString:@"capturedvideo.MOV"]) { if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (urlPath)) { [self copyTempVideoToMediaLibrary :urlPath]; } else { NSLog(@"Video Capture Error: Captured video cannot be saved...didFinishPickingMediaWithInfo()"); } } else { NSLog(@"Processing soon to saved photos album...else loop of lastPathComponent..didFinishPickingMediaWithInfo()"); } } [self dismissModalViewControllerAnimated:YES]; } - (void)copyTempVideoToMediaLibrary :(NSString *)videoURL { dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(mainQueue, ^{ ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease]; ALAssetsLibraryWriteVideoCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) { NSLog(@"Saved URL: %@", assetURL); NSLog(@"Error: %@", error); if (assetURL != nil) { AVURLAsset *theAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:videoURL] options:nil]; NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:theAsset]; AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:theAsset presetName:AVAssetExportPresetLowQuality]; [exportSession setOutputURL:[NSURL URLWithString:videoURL]]; [exportSession setOutputFileType:AVFileTypeQuickTimeMovie]; [exportSession exportAsynchronouslyWithCompletionHandler:^ { switch ([exportSession status]) { case AVAssetExportSessionStatusFailed: NSLog(@"Export session faied with error: %@", [exportSession error]); break; default: //[self mediaIsReady]; break; } }]; } }; [library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoURL] completionBlock:completionBlock]; }); } </code></pre>
5,853,354
7
1
null
2011-04-16 14:58:25.43 UTC
47
2022-08-11 13:07:23.75 UTC
2012-03-14 08:40:46.493 UTC
null
125,099
null
187,532
null
1
45
iphone
50,802
<p>If you want to compress the video for remote sharing and keep the original quality for local storage on the iPhone, you should look into <a href="http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAssetExportSession_Class/Reference/Reference.html#//apple_ref/occ/cl/AVAssetExportSession">AVAssetExportSession</a> or <a href="http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAssetWriter_Class/Reference/Reference.html#//apple_ref/occ/cl/AVAssetWriter">AVAssetWriter</a>.</p> <p>Also read up on how iOS manages <a href="http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/01_UsingAssets.html#//apple_ref/doc/uid/TP40010188-CH7-SW1">Assets</a>.</p> <pre><code>- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL handler:(void (^)(AVAssetExportSession*))handler { [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil]; AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil]; AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality]; exportSession.outputURL = outputURL; exportSession.outputFileType = AVFileTypeQuickTimeMovie; [exportSession exportAsynchronouslyWithCompletionHandler:^(void) { handler(exportSession); [exportSession release]; }]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSURL *outputURL = [NSURL fileURLWithPath:@"/Users/josh/Desktop/output.mov"]; [self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession) { if (exportSession.status == AVAssetExportSessionStatusCompleted) { printf("completed\n"); } else { printf("error\n"); } }]; } </code></pre>
5,757,101
Change Input to Upper Case
<p>JS: </p> <pre><code>&lt;script type="text/css"&gt; $(function() { $('#upper').keyup(function() { this.value = this.value.toUpperCase(); }); }); &lt;/script&gt; </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="search"&gt; &lt;input type="radio" name="table" class="table" value="professor" tabindex="1" /&gt; Professor &lt;input type="radio" name="table" class="table" value="department" tabindex="2" /&gt; Department &lt;input type="radio" name="table" id="upper" class="table" value="course" tabindex="3" /&gt; Course &lt;input type="text" name="search" class="keywords" value="Select an option..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?':this.value;" tabindex="4" /&gt; &lt;div id="content"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Why is this still not working?? Just trying to call div ".keywords" from JS.</p>
5,757,133
15
2
null
2011-04-22 15:41:38.88 UTC
15
2020-04-25 16:06:27.6 UTC
2011-04-22 17:08:38.66 UTC
null
700,070
null
700,070
null
1
83
javascript|jquery
245,376
<p>I think the most elegant way is without any javascript but with css. You can use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform" rel="noreferrer"><code>text-transform: uppercase</code></a> (this is inline just for the idea):</p> <pre><code>&lt;input id="yourid" style="text-transform: uppercase" type="text" /&gt; </code></pre> <p><strong>Edit:</strong></p> <p>So, in your case, if you want keywords to be uppercase change: <code>keywords: $(".keywords").val(),</code> to <code>$(".keywords").val().toUpperCase(),</code></p>
6,001,654
How to render a DateTime in a specific format in ASP.NET MVC 3?
<p>If I have in my model class a property of type <code>DateTime</code> how can I render it in a specific format - for example in the format which <code>ToLongDateString()</code> returns?</p> <p>I have tried this...</p> <pre><code>@Html.DisplayFor(modelItem =&gt; item.MyDateTime.ToLongDateString()) </code></pre> <p>...which throws an exception because the expression must point to a property or field. And this...</p> <pre><code>@{var val = item.MyDateTime.ToLongDateString(); Html.DisplayFor(modelItem =&gt; val); } </code></pre> <p>...which doesn't throw an exception, but the rendered output is empty (although <code>val</code> contains the expected value, as I could see in the debugger).</p> <p>Thanks for tips in advance!</p> <p><strong>Edit</strong></p> <p><code>ToLongDateString</code> is only an example. What I actually want to use instead of <code>ToLongDateString</code> is a custom extension method of <code>DateTime</code> and <code>DateTime?</code>:</p> <pre><code>public static string FormatDateTimeHideMidNight(this DateTime dateTime) { if (dateTime.TimeOfDay == TimeSpan.Zero) return dateTime.ToString("d"); else return dateTime.ToString("g"); } public static string FormatDateTimeHideMidNight(this DateTime? dateTime) { if (dateTime.HasValue) return dateTime.Value.FormatDateTimeHideMidNight(); else return ""; } </code></pre> <p>So, I think I cannot use the <code>DisplayFormat</code> attribute and <code>DataFormatString</code> parameter on the ViewModel properties.</p>
6,001,836
15
0
null
2011-05-14 11:56:01.523 UTC
28
2017-12-28 11:41:02.133 UTC
2011-05-14 12:57:28.6 UTC
null
270,591
null
270,591
null
1
119
asp.net|asp.net-mvc|asp.net-mvc-3
218,759
<p>If all you want to do is display the date with a specific format, just call:</p> <pre><code>@String.Format(myFormat, Model.MyDateTime) </code></pre> <p>Using <code>@Html.DisplayFor(...)</code> is just extra work unless you are specifying a template, or need to use something that is built on templates, like iterating an <code>IEnumerable&lt;T&gt;</code>. Creating a template is simple enough, and can provide a lot of flexibility too. Create a folder in your views folder for the current controller (or shared views folder) called <code>DisplayTemplates</code>. Inside that folder, add a partial view with the model type you want to build the template for. In this case I added <code>/Views/Shared/DisplayTemplates</code> and added a partial view called <code>ShortDateTime.cshtml</code>.</p> <pre><code>@model System.DateTime @Model.ToShortDateString() </code></pre> <p>And now you can call that template with the following line:</p> <pre><code>@Html.DisplayFor(m =&gt; m.MyDateTime, "ShortDateTime") </code></pre>
55,802,212
Error related to resources_ap after upgrading to Android Studio 3.4
<p>I upgraded Android Studio 3.4 today. I am no longer able to run the the app. I have cleaned the project, restarted Android studio many times. I have also invalidated cache to no avail. I am getting the following error when installing the app:</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformDexWithInstantRunSlicesApkForDebug'. &gt; java.lang.RuntimeException: java.io.FileNotFoundException: E:\...\app\build\intermediates\instant_run_split_apk_resources\debug\instantRunSplitApkResourcesDebug\out\slice_1\resources_ap </code></pre> <p>Could anyone offer a tip on how to remedy this?</p> <p><strong>Edit:</strong> I have two projects with different behaviors related to this issue:</p> <ol> <li>Project A initially had this issue. I disabled Instant Run per the answer, the problem was solved. I enabled Instant Run later, and Project A is still working fine.</li> <li>Project B also had this problem that has been remedied by turning of Instant Run. However, its problem will occur as soon as Instant Run is turned on. I do not what difference between these two projects results in this. One suspect is library C project. Library C is a part of Project A (i.e. its source code, resources are in Project A). However, Project B uses the aar of Library C as a module. </li> </ol>
55,824,989
10
3
null
2019-04-22 23:10:36.937 UTC
7
2019-08-09 14:13:58.123 UTC
2019-04-30 01:43:59.477 UTC
null
355,456
null
355,456
null
1
79
android-studio|android-studio-3.4
23,800
<p>Switching off Instant Run as a workaround (File/Settings/Instant Run) seems to eliminate the problem.</p> <p>According to OP it is possible to turn Instant Run back on without the problem recurring for some projects.</p>
39,142,778
How to determine the language of a piece of text?
<p>I want to get this:</p> <pre class="lang-none prettyprint-override"><code>Input text: &quot;ру́сский язы́к&quot; Output text: &quot;Russian&quot; Input text: &quot;中文&quot; Output text: &quot;Chinese&quot; Input text: &quot;にほんご&quot; Output text: &quot;Japanese&quot; Input text: &quot;العَرَبِيَّة&quot; Output text: &quot;Arabic&quot; </code></pre> <p>How can I do it in python?</p>
39,143,059
15
3
null
2016-08-25 10:26:00.44 UTC
86
2022-09-19 08:41:41.32 UTC
2022-06-13 15:59:31.613 UTC
null
68,587
null
6,680,564
null
1
162
python|nlp
136,964
<p>Have you had a look at <a href="https://pypi.python.org/pypi/langdetect?" rel="noreferrer">langdetect</a>?</p> <pre><code>from langdetect import detect lang = detect("Ein, zwei, drei, vier") print lang #output: de </code></pre>
4,985,093
jQuery - Send a form asynchronously
<p>I have a form such as :</p> <pre><code>&lt;form action='???' method='post' name='contact'&gt; &lt;input type="text" class="inputContact" name="mittente" /&gt; &lt;textarea class="textContact" name="smex"&gt;&lt;/textarea&gt; &lt;input type="submit" value="Send" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I'd like to send these data asynchronously, trought jQuery function <code>$.ajax</code>.</p> <p><strong>EDIT :with solution :</strong></p> <pre><code>&lt;form name='contactForm'&gt; &lt;input type="text" class="inputContact" name="mittente" /&gt; &lt;textarea class="textContact" name="smex"&gt;&lt;/textarea&gt; &lt;input type="submit" value="Send" /&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('form[name=contactForm]').submit(function(e){ e.preventDefault(); $.ajax({ type: 'POST', cache: false, url: './ajax/header_ajax.php', data: 'id=header_contact_send&amp;'+$(this).serialize(), success: function(msg) { $("#boxContentId").html(msg); } }); }); }); &lt;/script&gt; </code></pre>
4,985,112
1
3
null
2011-02-13 15:44:55.737 UTC
12
2021-04-22 09:09:47.16 UTC
2011-02-13 16:48:47.893 UTC
null
365,251
null
365,251
null
1
34
jquery|ajax|forms
33,610
<pre><code>$('form[name=contact]').submit(function(){ // Maybe show a loading indicator... $.post($(this).attr('action'), $(this).serialize(), function(res){ // Do something with the response `res` console.log(res); // Don't forget to hide the loading indicator! }); return false; // prevent default action }); </code></pre> <p>See:</p> <ul> <li><a href="http://api.jquery.com/jQuery.post" rel="noreferrer">jQuery docs: post</a></li> <li><a href="http://api.jquery.com/serialize" rel="noreferrer">jQuery docs: serialize</a></li> </ul>