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
1,667,630
How do I convert a String object into a Hash object?
<p>I have a string which looks like a hash:</p> <pre><code>"{ :key_a =&gt; { :key_1a =&gt; 'value_1a', :key_2a =&gt; 'value_2a' }, :key_b =&gt; { :key_1b =&gt; 'value_1b' } }" </code></pre> <p>How do I get a Hash out of it? like:</p> <pre><code>{ :key_a =&gt; { :key_1a =&gt; 'value_1a', :key_2a =&gt; 'value_2a' }, :key_b =&gt; { :key_1b =&gt; 'value_1b' } } </code></pre> <p>The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.</p>
1,667,683
16
2
null
2009-11-03 14:24:21.49 UTC
41
2022-05-17 18:44:59.953 UTC
null
null
null
null
100,466
null
1
162
ruby
232,447
<p>The string created by calling <code>Hash#inspect</code> can be turned back into a hash by calling <code>eval</code> on it. However, this requires the same to be true of all of the objects in the hash.</p> <p>If I start with the hash <code>{:a =&gt; Object.new}</code>, then its string representation is <code>"{:a=&gt;#&lt;Object:0x7f66b65cf4d0&gt;}"</code>, and I can't use <code>eval</code> to turn it back into a hash because <code>#&lt;Object:0x7f66b65cf4d0&gt;</code> isn't valid Ruby syntax.</p> <p>However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.</p>
1,646,580
Get Visual Studio to run a T4 Template on every build
<p>How do I get a T4 template to generate its output on every build? As it is now, it only regenerates it when I make a change to the template.</p> <p>I have found other questions similar to this:</p> <p><a href="https://stackoverflow.com/questions/1293320/t4-transformation-and-build-order-in-visual-studio">T4 transformation and build order in Visual Studio</a> (unanswered)</p> <p><a href="https://stackoverflow.com/questions/405560/how-to-get-t4-files-to-build-in-visual-studio">How to get t4 files to build in visual studio?</a> (answers are not detailed enough [while still being plenty complicated] and don't even make total sense)</p> <p>There has got to be a simpler way to do this!</p>
3,041,089
22
5
null
2009-10-29 21:14:03.517 UTC
78
2022-03-18 16:57:05.75 UTC
2017-12-12 22:58:44.5 UTC
null
41,956
null
16,012
null
1
181
visual-studio|tfs|msbuild|t4
71,145
<p>I used JoelFan's answer to come up w/ this. I like it better because you don't have to remember to modify the pre-build event every time you add a new .tt file to the project.</p> <ul> <li>add TextTransform.exe to your <code>%PATH%</code></li> <li>created a batch file named transform_all.bat (see below)</li> <li>create a pre-build event "<code>transform_all ..\..</code>"</li> </ul> <p><strong>transform_all.bat</strong></p> <pre><code>@echo off SETLOCAL ENABLEDELAYEDEXPANSION :: set the working dir (default to current dir) set wdir=%cd% if not (%1)==() set wdir=%1 :: set the file extension (default to vb) set extension=vb if not (%2)==() set extension=%2 echo executing transform_all from %wdir% :: create a list of all the T4 templates in the working dir dir %wdir%\*.tt /b /s &gt; t4list.txt echo the following T4 templates will be transformed: type t4list.txt :: transform all the templates for /f %%d in (t4list.txt) do ( set file_name=%%d set file_name=!file_name:~0,-3!.%extension% echo: \--^&gt; !file_name! TextTransform.exe -out !file_name! %%d ) echo transformation complete </code></pre>
8,808,794
Get hash key and convert into string ruby
<p>Example Hash</p> <pre><code>hash = {:key =&gt; ["val1", "val2]} </code></pre> <p>When I did this on rails 3.0.7, it was fine.</p> <pre><code>&gt; hash.keys.to_s =&gt; "key" &gt; hash[hash.keys.to_s] =&gt; ["val1", "val2"] </code></pre> <p>But if I do this with rails 3.1.3, it isn't.</p> <pre><code>&gt; hash.keys.to_s =&gt; [\"key\"] &gt; hash[hash.keys.to_s] =&gt; nil </code></pre> <p><strong>Is this was because of the Rails version changed?</strong> and <strong>Is there any other way to turn hash key into a string that works with both version (or with rails 2 too)?</strong></p>
8,809,180
2
2
null
2012-01-10 18:50:50.657 UTC
3
2012-01-10 19:29:09.07 UTC
null
null
null
null
760,363
null
1
15
ruby-on-rails-3
42,541
<p>Did you upgrade Ruby as well as Rails? I think this is a change between 1.8 and 1.9</p> <p>Try <code>hash.keys.first.to_s</code> (if there's always only one key) or <code>hash.keys.join</code></p>
18,083,239
What happened to "Always refresh from server" in IE11 developer tools?
<p>Do the F12 developer tools in Internet Explorer 11 also have the "Always refresh from server" feature of the developer tools in IE 8-10?</p> <p>I see the "Clear browser cache... (Ctrl + R)" button on the <a href="http://msdn.microsoft.com/en-us/library/ie/dn255004.aspx" rel="noreferrer">Network tool</a>, but clicking on it appears to do nothing (the Temporary Internet Files folder still has files in it afterward). I also have the "Check for newer versions of stored pages:" setting set to "Every time I visit the webpage", but this does not appear to always refresh external assets.</p> <p>Can the cache be completely disabled in IE 11 for development?</p> <p>For now I am just holding down the Ctrl key and clicking on the refresh button (per <a href="http://en.wikipedia.org/wiki/Wikipedia:Bypass_your_cache#Internet_Explorer" rel="noreferrer">Wikipedia's instructions to bypass the cache</a>), but this is easy to forget to do.</p>
18,723,232
5
0
null
2013-08-06 14:39:21.477 UTC
8
2016-03-12 20:23:06.393 UTC
2013-08-06 17:01:41.58 UTC
null
168,868
null
196,844
null
1
102
internet-explorer|ie-developer-tools|internet-explorer-11|ie11-developer-tools
79,732
<p><img src="https://i.stack.imgur.com/92Rof.png" alt="Refresh from Server button"></p> <p>It seems they have added the "Always Refresh from Server" button in the RTM version of IE11 that ships with Windows 8.1</p> <p>It is found in the Network tab of the developer tools, 3rd button from the left.</p>
17,755,859
how do i call dictionary values from within a list of dictionaries ?
<p>i am trying to learn python with codeacademy. the assignment was make 3 dictionaries (for each student) and then make a list of the 3 dictionaries. then, i am supposed to print out all the data in the list. </p> <p>i tried to call out the values the same way i used for a dictionary by itself (lloyd[values]), but then it says that values is not defined o_O. I have also tried to 'print names' but then the error message is that i didn't print out one of the values. </p> <p>i'd appreciate your help very much. </p> <pre><code> lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } students = [lloyd, alice, tyler] for names in students: print lloyd[values] </code></pre>
17,756,026
6
1
null
2013-07-19 21:33:04.87 UTC
3
2016-09-04 17:22:38.867 UTC
null
null
null
null
1,476,390
null
1
0
python|list|dictionary
39,328
<p>If you want to print all the information for each student, you have to loop over the students and the values stored in the dictionaries:</p> <pre><code>students = [lloyd, alice, tyler] for student in students: for value in student: print value, "is", student[value] </code></pre> <p>Note, however, that dictionaries are not ordered, so the order of the values might not be the way you want it. In this case, print them individually, using the name of the value as a string as key:</p> <pre><code>for student in students: print "Name is", student["name"] print "Homework is", student["homework"] # same for 'quizzes' and 'tests' </code></pre> <p>Finally, you could also use the <code>pprint</code> module for "pretty-printing" the student dictionaries:</p> <pre><code>import pprint for student in students: pprint.pprint(student) </code></pre>
17,973,970
How can I solve "java.lang.NoClassDefFoundError"?
<p>I've tried both the examples in Oracle's <a href="http://docs.oracle.com/javase/tutorial" rel="noreferrer">Java Tutorials</a>. They both compile fine, but at run time, both come up with this error:</p> <pre class="lang-none prettyprint-override"><code>Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: graphics/shapes/Square at Main.main(Main.java:7) Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more </code></pre> <p>I think I might have the <code>Main.java</code> file in the wrong folder.</p> <p>Here is the directory hierarchy:</p> <pre class="lang-none prettyprint-override"><code>graphics ├ Main.java ├ shapes | ├ Square.java | ├ Triangle.java ├ linepoint | ├ Line.java | ├ Point.java ├ spaceobjects | ├ Cube.java | ├ RectPrism.java </code></pre> <p>And here is <code>Main.java</code>:</p> <pre><code>import graphics.shapes.*; import graphics.linepoint.* import graphics.spaceobjects.*; public class Main { public static void main(String args[]) { Square s = new Square(2, 3, 15); Line l = new Line(1, 5, 2, 3); Cube c = new Cube(13, 32, 22); } } </code></pre> <p>What am I doing wrong here?</p> <p><strong>UPDATE</strong></p> <p>After I put put the <code>Main</code> class into the <code>graphics</code> package (I added <code>package graphics;</code> to it), set the classpath to &quot;_test&quot; (folder containing graphics), compiled it, and ran it using <code>java graphics.Main</code> (from the command line), it worked.</p> <p><strong>Really late UPDATE #2</strong></p> <p>I wasn't using <a href="https://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> (just <a href="https://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and <a href="https://en.wikipedia.org/wiki/IntelliJ_IDEA" rel="noreferrer">IntelliJ IDEA</a>, but they have similar concepts.</p>
17,974,068
34
11
null
2013-07-31 15:00:27.523 UTC
77
2022-08-19 04:44:28.88 UTC
2021-05-26 09:58:26.967 UTC
null
63,550
null
2,397,327
null
1
269
java|exception|package|noclassdeffounderror
1,471,076
<p>After you compile your code, you end up with <code>.class</code> files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The <code>NoClassDefFoundError</code> indicates that the classloader (in this case <code>java.net.URLClassLoader</code>), which is responsible for dynamically loading classes, cannot find the <code>.class</code> file for the class that you're trying to use.</p> <p>Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically <code>java.net.URLClassLoader</code>) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. <code>NoClassDefFoundError</code> can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.</p> <p>For example, if you had a class <code>com.example.Foo</code>, after compiling you would have a class file <code>Foo.class</code>. Say for example your working directory is <code>.../project/</code>. That class file must be placed in <code>.../project/com/example</code>, and you would set your classpath to <code>.../project/</code>.</p> <p>Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, <a href="http://en.wikipedia.org/wiki/Classpath_%28Java%29" rel="noreferrer">this link</a> explains how to set the classpath when you execute on the command line.</p>
44,532,077
switch with var/null strange behavior
<p>Given the following code:</p> <pre><code>string someString = null; switch (someString) { case string s: Console.WriteLine("string s"); break; case var o: Console.WriteLine("var o"); break; default: Console.WriteLine("default"); break; } </code></pre> <p>Why is the switch statement matching on <code>case var o</code>?</p> <p>It is my understanding that <code>case string s</code> does not match when <code>s == null</code> because (effectively) <code>(null as string) != null</code> evaluates to false. IntelliSense on VS Code tells me that <code>o</code> is a <code>string</code> as well. Any thoughts?</p> <hr> <p>Similiar to: <a href="https://stackoverflow.com/questions/42950833/c-sharp-7-switch-case-with-null-checks">C# 7 switch case with null checks</a></p>
44,532,658
3
9
null
2017-06-13 21:44:30.933 UTC
14
2017-12-26 14:58:21.983 UTC
2017-06-23 15:31:14.913 UTC
null
1,159,478
null
4,607,317
null
1
91
c#|null|switch-statement|var|c#-7.0
4,188
<p>Inside a pattern matching <code>switch</code> statement using a <code>case</code> for an explicit type is asking if the value in question is of that specific type, or a derived type. It's the exact equivalent of <code>is</code> </p> <pre><code>switch (someString) { case string s: } if (someString is string) </code></pre> <p>The value <code>null</code> does not have a type and hence does not satisfy either of the above conditions. The static type of <code>someString</code> doesn't come into play in either example. </p> <p>The <code>var</code> type though in pattern matching acts as a wild card and will match any value including <code>null</code>. </p> <p>The <code>default</code> case here is dead code. The <code>case var o</code> will match any value, null or non-null. A non-default case always wins over a default one hence <code>default</code> will never be hit. If you look at the IL you'll see it's not even emitted. </p> <p>At a glance it may seem odd that this compiles without any warning (definitely threw me off). But this is matching with C# behavior that goes back to 1.0. The compiler allows <code>default</code> cases even when it can trivially prove that it will never be hit. Consider as an example the following:</p> <pre><code>bool b = ...; switch (b) { case true: ... case false: ... default: ... } </code></pre> <p>Here <code>default</code> will never be hit (even for <code>bool</code> that have a value that isn't 1 or 0). Yet C# has allowed this since 1.0 without warning. Pattern matching is just falling in line with this behavior here. </p>
6,983,589
Target first element of DIV using CSS
<p>I have a WYSIWYG editor inside of a table that is placed within a div, as such...</p> <pre><code>&lt;div class="mydiv"&gt; &lt;li&gt; &lt;table&gt;My WYSIWYG&lt;/table&gt; &lt;/li&gt; &lt;/table&gt; </code></pre> <p>Inside my WYSIWYG there are more tables however I only want to target the first table, I understand I could assign a class to the table but thats not what I want. </p> <p>I've tried using the following only it doesn't seem to work...</p> <pre><code>.mydiv li + table {width:100%;} </code></pre>
6,983,615
4
4
null
2011-08-08 14:23:25.367 UTC
2
2013-01-29 21:08:01.35 UTC
null
null
null
null
766,532
null
1
5
css|html
43,869
<p>You need <code>.mydiv li table:first-child</code>.</p> <p><a href="http://www.w3.org/TR/css3-selectors/#first-child-pseudo" rel="noreferrer">More information</a>.</p> <p><code>:first-child</code> works in IE7+ and all modern browsers.</p> <p><a href="http://jsfiddle.net/74eSh/" rel="noreferrer">An example.</a> </p> <hr> <p><code>.mydiv li + table</code> isn't working for you because that matches something like this:</p> <pre><code>&lt;div class="mydiv"&gt; &lt;li&gt;&lt;/li&gt; &lt;table&gt;My WYSIWYG&lt;/table&gt; &lt;/div&gt; </code></pre> <hr> <p>Also note that there are few things wrong with your HTML:</p> <pre><code>&lt;div class="mydiv"&gt; &lt;li&gt; &lt;table&gt;My WYSIWYG&lt;/table&gt; &lt;/li&gt; &lt;/table&gt; </code></pre> <ul> <li><code>&lt;/table&gt;</code> at the end should be <code>&lt;/div&gt;</code>.</li> <li>The <code>div</code> should be a <code>ul</code>, because <code>li</code> is not a valid child of <code>div</code>.</li> </ul> <p>I've fixed these things in the demo above.</p>
6,336,441
How to scroll WPF ScrollViewer's content to specific location
<p>I am writing my custom WPF ItemsControl to display a list of item. The items are shown embedded inside a ScrollViewer:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Style TargetType="MyCustomItemsControl"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="MyCustomItemsControl"&gt; &lt;ScrollViewer x:Name="PART_MyScrollViewer" &gt; &lt;ItemsPresenter/&gt; &lt;/ScrollViewer&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>I want to make sure that when I move the mouse into the control, a particular item (marked as selected) will be scrolled into the mouse position. In my OnMouseEnter method I am able to find the item but I don't know what to do next. Does anyone have any idea?</p> <pre><code>protected override void OnMouseEnter(MouseEventArgs e) { for (int i = 0; i &lt; Items.Count; i++) { ContentPresenter uiElement = (ContentPresenter)ItemContainerGenerator.ContainerFromIndex(i); var item = uiElement.Content as MyCustomObject; if (item.IsSelected) { // How to scroll the uiElement to the mouse position? break; } } } </code></pre>
6,336,745
4
0
null
2011-06-13 21:13:48.923 UTC
4
2019-07-02 09:23:24.15 UTC
2014-03-06 07:11:16.083 UTC
null
546,730
null
449,056
null
1
22
wpf|mouse|position|scrollviewer
40,664
<p>Something like the following:</p> <pre><code>var sv = (ScrollViewer)Template.FindName("PART_MyScrollViewer", this); // If you do not already have a reference to it somewhere. var ip = (ItemsPresenter)sv.Content; var point = item.TranslatePoint(new Point() - (Vector)e.GetPosition(sv), ip); sv.ScrollToVerticalOffset(point.Y + (item.ActualHeight / 2)); </code></pre>
23,611,688
keytool error: java.lang.Exception: Failed to establish chain from reply
<p>Generate keystore:</p> <pre><code>keytool -genkey -alias tomcat -keyalg RSA -keystore my.keystore -keysize 2048 </code></pre> <p>Generate certificate signing request (CSR):</p> <pre><code>keytool -certreq -alias tomcat -keyalg RSA -file my.csr -keystore my.keystore </code></pre> <p>I then go off to my hosting provider and get some certificates. These i installed as follows:</p> <pre><code>keytool -import -alias root -keystore my.keystore -trustcacerts -file gd_bundle-g2-g1.crt keytool -import -alias intermed -keystore my.keystore -trustcacerts -file gdig2.crt keytool -import -alias tomcat -keystore my.keystore -trustcacerts -file my.crt </code></pre> <p>When I installed the final certificate (my.crt) I got the following error:</p> <pre><code>keytool error: java.lang.Exception: Failed to establish chain from reply </code></pre> <p>I believe i have imported the chain and in the correct order so I'm very confused by this message. Can anyone see what I'm doing wrong?</p>
23,612,624
6
2
null
2014-05-12 14:26:37.02 UTC
5
2017-12-13 15:12:50.787 UTC
2016-08-18 17:21:42.737 UTC
null
371,184
null
669,645
null
1
33
tomcat|ssl-certificate|keytool
115,157
<p>I've just discovered that the files godaddy supplied with my certificate are both intermediate certificates (in fact they seem to both be the same intermediate certificate).</p> <p>I got the correct root and intermediate certificates by double clicking on my certificate and looking at the certificate path... from here I could also download each of these certificates and use the steps used in the question to import them</p> <p><img src="https://i.stack.imgur.com/bEVJh.png" alt="enter image description here"></p>
18,609,397
What's the difference between sockaddr, sockaddr_in, and sockaddr_in6?
<p>I know that sockaddr_in is for IPv4, and sockaddr_in6 for IPv6. The confusion to me is the difference between sockaddr and sockaddr_in[6]. </p> <p>Some functions accept <code>sockaddr</code> and some functions accept <code>sockaddr_in</code> or <code>sockaddr_in6</code>, so:</p> <ul> <li>what's the rule? </li> <li>And why is there a need for two different structures?</li> </ul> <p>And because the <code>sizeof(sockaddr_in6) &gt; sizeof(sockaddr) == sizeof(sockaddr_in)</code>.</p> <ul> <li>Does that mean we should always use sockaddr_in6 to allocate memory in stack and cast to sockaddr and sockaddr_in if we need to support ipv4 and ipv6?</li> </ul> <p>One example is: we have a socket, and we want to get the string ip address of it (it can be ipv4 or ipv6).</p> <p>We first call <code>getsockname</code> to get an <code>addr</code> and then call <code>inet_ntop</code> based on the <code>addr.sa_family</code>.</p> <p>Is there anything wrong with this code snippet?</p> <pre><code>char ipStr[256]; sockaddr_in6 addr_inv6; sockaddr* addr = (sockaddr*)&amp;addr_inv6; sockaddr_in* addr_in = (sockaddr_in*)&amp;addr_inv6; socklen_t len = sizeof(addr_inv6); getsockname(_socket, addr, &amp;len); if (addr-&gt;sa_family == AF_INET6) { inet_ntop(addr_inv6.sin6_family, &amp;addr_inv6.sin6_addr, ipStr, sizeof(ipStr)); // &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;IS THIS LINE VALID, getsockname expected a sockaddr, but we use // it output parameter as sockaddr_in6. } else { inet_ntop(addr_in-&gt;sin_family, &amp;addr_in-&gt;sin_addr, ipStr, sizeof(ipStr)); } </code></pre>
18,626,969
2
1
null
2013-09-04 08:54:03.617 UTC
26
2019-04-24 07:01:07.643 UTC
2019-04-24 07:01:07.643 UTC
null
1,564,946
null
2,428,052
null
1
53
c++|c|api|network-programming
45,492
<p>I don't want to answer my question. But to give more information here which might be useful to other people, I decide to answer my question.</p> <p>After dig into the source code of <code>linux</code>. Following is my finding, there are possible multiple protocol which all implement the <code>getsockname</code>. And each have themself underling address data structure, for example, for IPv4 it is <code>sockaddr_in</code>, and IPV6 <code>sockaddr_in6</code>, and <code>sockaddr_un</code> for <code>AF_UNIX</code> socket. <code>sockaddr</code> are used as the common data strut in the signature of those APIs. </p> <p>Those API will copy the socketaddr_in or sockaddr_in6 or sockaddr_un to sockaddr base on another parameter <code>length</code> by memcpy.</p> <p>And all of the data structure begin with same type field sa_family.</p> <p>Base on those reason, the code snippet is valid, because both <code>sockaddr_in</code> and <code>sockaddr_in6</code> have <code>sa_family</code> and then we can cast it to the correct data structure for usage after check <code>sa_family</code>.</p> <p>BTY, I'm not sure why the <code>sizeof(sockaddr_in6) &gt; sizeof(sockaddr)</code>, which cause allocate memory base on size of sockaddr is not enough for ipv6( that is error-prone), but I guess it is because of history reason.</p>
34,238,399
Function to extract remaining string after last backslash
<p>I need an Excel function that can extract a string after last <code>\</code> from a path and if no <code>\</code> found then take the whole string. For example:</p> <pre><code>D:\testing\rbc.xls output will be rbc.xls D:\home\testing\test1\script1.sql output will be script.sql script 3.txt output will be script 3.txt </code></pre>
34,239,186
1
5
null
2015-12-12 09:40:14.16 UTC
3
2020-06-29 19:11:54.983 UTC
2020-06-29 19:11:54.983 UTC
null
8,422,953
null
664,481
null
1
9
excel|vba|replace|excel-formula|find-replace
45,514
<p>1.Change all the "\" to spaces, the number of spaces is determined by the number of characters in the cell </p> <p>2.Use the right function to extract the right of the string based on the number of characters in the cell. </p> <p>3.Use the trim function to remove the spaces.</p> <p><a href="https://i.stack.imgur.com/G8FrU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/G8FrU.jpg" alt="enter image description here"></a></p> <p>Your results will be.</p> <p><a href="https://i.stack.imgur.com/jc8rT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/jc8rT.jpg" alt="enter image description here"></a></p> <p><code>=TRIM(RIGHT(SUBSTITUTE(A1,"\",REPT(" ",LEN(A1))),LEN(A1)))</code></p> <p>As suggested, one way to do this without formulas or vba would be to use "Find/Replace". Hit Ctrl &amp; "H" keys and do the following.</p> <p>Find what *\ and replace with nothing</p> <p><a href="https://i.stack.imgur.com/Rih9D.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Rih9D.jpg" alt="enter image description here"></a></p> <p>The VBA code for that would be</p> <pre><code>Sub ReplaceIt() Columns("A").Replace What:="*\", Replacement:="", SearchOrder:=xlByColumns, MatchCase:=True End Sub </code></pre>
51,116,381
Convert Firebase Firestore Timestamp to Date (Swift)?
<p>I have a date saved in a Firestore field as a timestamp that I want to convert to a Date in Swift:</p> <p><code>June 19,2018 at 7:20:21 PM UTC-4</code></p> <p>I tried the following but I get an error:</p> <p><code>let date = Date(timeIntervalSince1970: postTimestamp as! TimeInterval)</code></p> <p>Error:</p> <p><code>Could not cast value of type 'FIRTimestamp' (0x104fa8b98) to 'NSNumber'</code></p> <p>The reason why I want to convert to Date is so that I can use this Date extension to mimic timestamps you see on Instagram posts:</p> <pre><code>extension Date { func timeAgoDisplay() -&gt; String { let secondsAgo = Int(Date().timeIntervalSince(self)) let minute = 60 let hour = 60 * minute let day = 24 * hour let week = 7 * day if secondsAgo &lt; minute { return "\(secondsAgo) seconds ago" } else if secondsAgo &lt; hour { return "\(secondsAgo / minute) minutes ago" } else if secondsAgo &lt; day { return "\(secondsAgo / hour) hours ago" } else if secondsAgo &lt; week { return "\(secondsAgo / day) days ago" } return "\(secondsAgo / week) weeks ago" } } </code></pre>
51,116,425
1
3
null
2018-06-30 15:53:29.7 UTC
11
2018-06-30 15:59:57.017 UTC
null
null
null
null
2,089,684
null
1
36
swift|firebase|google-cloud-firestore
20,926
<p>Either do:</p> <pre><code>let date = postTimestamp.dateValue() </code></pre> <p>or you could do:</p> <pre><code>let date = Date(timeIntervalSince1970: postTimestamp.seconds) </code></pre> <p>See the <a href="https://firebase.google.com/docs/reference/swift/firebasefirestore/api/reference/Classes/Timestamp" rel="noreferrer">Timestamp reference documentation</a>.</p>
41,197,546
Typescript Select Ids from object
<p>I am new to Typescript. I want to select ids from observable</p> <p>This is my observable</p> <pre><code>let myObj = [{ "id": 1, "text": "Mary" }, { "id": 2, "text": "Nancy" }, { "id": 3, "text": "Paul" }, { "id": 4, "text": "Cheryl" }, { "id": 5, "text": "Frances" }] </code></pre> <p>Expected Result :</p> <pre><code>let selectedIds = [1,2,3,4,5]; </code></pre> <p>Can I do this without creating an array and pushing the ids in a for loop. </p>
41,197,583
2
3
null
2016-12-17 10:18:48.197 UTC
3
2016-12-17 13:40:41.773 UTC
2016-12-17 10:22:02.513 UTC
null
3,001,761
null
4,728,339
null
1
25
arrays|angular|typescript|rxjs|rxjs5
68,703
<p>Use <code>Array#map</code> to map one array to another:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const myObj = [{"id":1,"text":"Mary"},{"id":2,"text":"Nancy"},{"id":3,"text":"Paul"},{"id":4,"text":"Cheryl"},{"id":5,"text":"Frances"}]; const selectedIds = myObj.map(({ id }) =&gt; id); console.log(selectedIds);</code></pre> </div> </div> </p>
16,363,292
Label width in tkinter
<p>I'm writing an app with tkinter and I am trying to put several labels in a frame... Unfortunately,</p> <pre><code>windowTitle=Label(... width=100) </code></pre> <p>and</p> <pre><code>windowFrame=Frame(... width=100) </code></pre> <p>are very different widths...</p> <p>So far, I use this code:</p> <pre><code>windowFrame=Frame(root,borderwidth=3,relief=SOLID,width=xres/2,height=yres/2) windowFrame.place(x=xres/2-160,y=yres/2-80) windowTitle=Label(windowFrame,background="#ffa0a0",text=title) windowTitle.place(x=0,y=0) windowContent=Label(windowFrame,text=content,justify="left") windowContent.place(x=8,y=32) ... #xres is screen width #yres is screen height </code></pre> <p>For some reason, setting label width doesn't set width correctly, or doesn't use pixels as measurement units... So, is there a way to place <code>windowTitle</code> widget in such way that it adapts to the lenght of the frame, or to set label width in pixels?</p>
16,363,832
1
12
null
2013-05-03 16:10:22.94 UTC
2
2015-08-13 23:31:18.867 UTC
null
null
null
null
1,901,114
null
1
8
python|tkinter|width|label|frame
47,093
<p><code>height</code> and <code>width</code> define the size of the label in <strong>text units</strong> when it contains text. Follow @Elchonon Edelson's advice and set size of frame + one small trick:</p> <pre><code>from tkinter import * root = Tk() def make_label(master, x, y, h, w, *args, **kwargs): f = Frame(master, height=h, width=w) f.pack_propagate(0) # don't shrink f.place(x=x, y=y) label = Label(f, *args, **kwargs) label.pack(fill=BOTH, expand=1) return label make_label(root, 10, 10, 10, 40, text='xxx', background='red') make_label(root, 30, 40, 10, 30, text='xxx', background='blue') root.mainloop() </code></pre>
1,243,201
Is Macro Better Than UIColor for Setting RGB Color?
<p>I have this macro in my header file:</p> <pre><code>#define UIColorFromRGB(rgbValue) \ [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \ blue:((float)(rgbValue & 0xFF))/255.0 \ alpha:1.0]</code></pre> <p>And I am using this as something like this in my .m file:</p> <pre><code>cell.textColor = UIColorFromRGB(0x663333);</code></pre> <p>So I want to ask everyone is this better or should I use this approach:</p> <pre><code>cell.textColor = [UIColor colorWithRed:66/255.0 green:33/255.0 blue:33/255.0 alpha:1.0];</code></pre> <p>Which one is the better approach?</p>
1,243,280
7
1
null
2009-08-07 06:26:18.09 UTC
9
2011-09-09 16:16:31.493 UTC
2009-08-07 06:41:39.527 UTC
null
104,200
null
83,905
null
1
5
objective-c|iphone|xcode|macros|uicolor
19,714
<p>A middle ground might be your best option. You could define either a regular C or objective-C function to do what your macro is doing now:</p> <pre><code>// As a C function: UIColor* UIColorFromRGB(NSInteger rgbValue) { return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]; } // As an Objective-C function: - (UIColor *)UIColorFromRGB:(NSInteger)rgbValue { return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]; }</code></pre> <p>If you decide to stick with the macro, though, you should put parentheses around <code>rgbValue</code> wherever it appears. If I decide to call your macro with:</p> <pre><code>UIColorFromRGB(0xFF0000 + 0x00CC00 + 0x000099);</code></pre> <p>you may run into trouble.</p> <p>The last bit of code is certainly the most readable, but probably the least portable - you can't call it simply from anywhere in your program.</p> <p>All in all, I'd suggest refactoring your macro into a function and leaving it at that.</p>
457,207
Cropping pages of a .pdf file
<p>I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size.</p> <p>After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a page object the results were not what I had expected and appeared to be quite random.</p> <p>Has anyone had any experience with this? Code examples would be well appreciated, preferably in python.</p>
465,901
7
1
null
2009-01-19 10:43:23.267 UTC
20
2022-06-03 20:39:17.033 UTC
2022-05-14 11:31:47.287 UTC
null
562,769
null
367,099
null
1
23
python|pdf|pypdf2|pypdf
43,199
<p><a href="https://pypi.org/project/pyPdf/" rel="noreferrer">pyPdf</a> does what I expect in this area. Using the following script:</p> <pre><code>#!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader with open(&quot;in.pdf&quot;, &quot;rb&quot;) as in_f: input1 = PdfFileReader(in_f) output = PdfFileWriter() numPages = input1.getNumPages() print &quot;document has %s pages.&quot; % numPages for i in range(numPages): page = input1.getPage(i) print page.mediaBox.getUpperRight_x(), page.mediaBox.getUpperRight_y() page.trimBox.lowerLeft = (25, 25) page.trimBox.upperRight = (225, 225) page.cropBox.lowerLeft = (50, 50) page.cropBox.upperRight = (200, 200) output.addPage(page) with open(&quot;out.pdf&quot;, &quot;wb&quot;) as out_f: output.write(out_f) </code></pre> <p>The resulting document has a trim box that is 200x200 points and starts at 25,25 points inside the media box. The crop box is 25 points inside the trim box.</p> <p>Here is how my sample document looks in acrobat professional after processing with the above code: <a href="https://i.stack.imgur.com/vM7e6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vM7e6.png" alt="crop pages screenshot" /></a></p> <p>This document will appear blank when loaded in acrobat reader.</p>
623,618
What is the definition of "accessor method"?
<p>I've been having an argument about the usage of the word "accessor" (the context is Java programming). I tend to think of accessors as implicitly being "property accessors" -- that is, the term implies that it's more or less there to provide direct access to the object's internal state. The other party insists that any method that touches the object's state in any way is an accessor.</p> <p>I know you guys can't win the argument for me, but I'm curious to know how you would define the term. :)</p>
623,631
8
0
null
2009-03-08 14:02:56.183 UTC
1
2015-06-16 01:17:44.993 UTC
null
null
null
Rytmis
266
null
1
15
java|definition|accessor
77,328
<p>By accessors, I tend to think of getters and setters.</p> <p>By insisting that all methods that touch the object's internal state are accessors, it seems that any instance method that actually uses the state of the object would be an accessor, and that just doesn't seem right. What kind of instance method won't use the state of the object? In other words, <em>an instance method that doesn't use the object's state in some way shouldn't be an instance method to begin with -- it should be a class method</em>.</p> <p>For example, should the <a href="http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#add(java.math.BigDecimal)" rel="noreferrer"><code>BigDecimal.add</code></a> method be considered an accessor? It is a method that will read the value of the instance that the <code>add</code> method was called on, then return the result after adding the value of another <code>BigInteger</code>. It seems fairly straight forward that the <code>add</code> instance method is not a getter nor a setter.</p>
1,208,077
Optimal number of connections in connection pool
<p>Currently we are using 4 cpu windows box with 8gb RAM with MySQL 5.x installed on same box. We are using Weblogic application server for our application. We are targeting for 200 concurrent users for our application (Obviously not for same module/screen). So what is optimal number of connections should we configured in connection pool (min and max number) (We are using weblogic AS' connection pooling mechanism) ?</p>
2,669,936
8
5
null
2009-07-30 17:25:01.243 UTC
21
2021-01-09 15:33:56.313 UTC
null
null
null
null
87,582
null
1
40
java|mysql|performance|weblogic|connection-pooling
51,056
<p>There is a very simple answer to this question: </p> <p><strong>The number of connections in the connection pool should be equal the number of the exec threads configured in WebLogic</strong>. </p> <p>The rationale is very simple: If the number of the connections is less than the number of threads, some of the thread maybe waiting for a connection thus making the connection pool a bottleneck. So, it should be equal at least the number the exec threads (thread pool size). </p>
1,023,146
Is it good style to explicitly return in Ruby?
<p>Coming from a Python background, where there is always a "right way to do it" (a "Pythonic" way) when it comes to style, I'm wondering if the same exists for Ruby. I've been using my own style guidelines but I'm thinking about releasing my source code, and I'd like it to adhere to any unwritten rules that might exist.</p> <p>Is it "The Ruby Way" to explicitly type out <code>return</code> in methods? I've seen it done with and without, but is there a right way to do it? Is there maybe a right <em>time</em> to do it? For example:</p> <pre><code>def some_func(arg1, arg2, etc) # Do some stuff... return value # &lt;-- Is the 'return' needed here? end </code></pre>
13,635,060
8
2
null
2009-06-21 03:38:11.813 UTC
34
2019-12-05 09:29:44.97 UTC
2015-05-15 19:30:36.94 UTC
null
104,184
null
104,184
null
1
168
ruby|coding-style|return-value
82,657
<p>Old (and "answered") question, but I'll toss in my two cents as an answer.</p> <p>TL;DR - You don't have to, but it can make your code a lot more clear in some cases.</p> <p>Though not using an explicit return may be "the Ruby way", it's confusing to programmers working with unfamiliar code, or unfamiliar with this feature of Ruby.</p> <p>It's a somewhat contrived example, but imagine having a little function like this, which adds one to the number passed, and assigns it to an instance variable. </p> <pre><code>def plus_one_to_y(x) @y = x + 1 end </code></pre> <p>Was this meant to be a function that returned a value, or not? It's really hard to say what the developer meant, as it both assigns the instance variable, AND returns the value assigned as well.</p> <p>Suppose much later, another programmer (perhaps not that familiar with how Ruby does returns based on last line of code executed) comes along and wants to put in some print statements for logging, and the function becomes this...</p> <pre><code>def plus_one_to_y(x) @y = x + 1 puts "In plus_one_to_y" end </code></pre> <p>Now the function is broken <em>if anything expects a returned value</em>. If nothing expects a returned value, it's fine. Clearly if somewhere further down the code chain, something calling this is expecting a returned value, it's going to fail as it's not getting back what it expects.</p> <p>The real question now is this: did anything really expect a returned value? Did this break something or not? Will it break something in the future? Who knows! Only a full code review of all calls will let you know.</p> <p>So for me at least, the best practice approach is to either be very explicit that you are returning something if it matters, or return nothing at all when it doesn't.</p> <p>So in the case of our little demo function, assuming we wanted it to return a value, it would be written like this...</p> <pre><code>def plus_one_to_y(x) @y = x + 1 puts "In plus_one_to_y" return @y end </code></pre> <p>And it would be very clear to any programmer that it does return a value, and much harder for them to break it without realizing it.</p> <p>Alternatively, one could write it like this and leave out the return statement...</p> <pre><code>def plus_one_to_y(x) @y = x + 1 puts "In plus_one_to_y" @y end </code></pre> <p>But why bother leaving out the word return? Why not just put it in there and make it 100% clear what's happening? It will literally have no impact on your code's ability to perform.</p>
249,392
Binary Search in Array
<p>How would I implement a binary search using just an array? </p>
249,404
9
2
null
2008-10-30 06:01:43.993 UTC
9
2022-06-18 13:37:12.307 UTC
null
null
null
Claudiu
15,055
null
1
16
algorithm|arrays|language-agnostic|search|binary-search
47,929
<p>Ensure that your array is sorted since this is the crux of a binary search. </p> <p>Any indexed/random-access data structure can be binary searched. So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on. </p> <p>You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from <a href="http://en.wikipedia.org/wiki/Binary_search" rel="noreferrer">Wikipedia: Binary Search Algorithm</a>:</p> <p>Recursive: </p> <pre><code>BinarySearch(A[0..N-1], value, low, high) { if (high &lt; low) return -1 // not found mid = low + ((high - low) / 2) if (A[mid] &gt; value) return BinarySearch(A, value, low, mid-1) else if (A[mid] &lt; value) return BinarySearch(A, value, mid+1, high) else return mid // found } </code></pre> <p>Iterative:</p> <pre><code> BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low &lt;= high) { mid = low + ((high - low) / 2) if (A[mid] &gt; value) high = mid - 1 else if (A[mid] &lt; value) low = mid + 1 else return mid // found } return -1 // not found } </code></pre>
277,514
Delphi: How do you auto-update your applications?
<p>I've been thinking of rolling my own code for enabling my Delphi application to update seamlessly as I'll be going for "release often, release early" mentality furthermore. There are various Delphi solutions (both freeware and paid) out there and I'd like to ask if you've been using any of them or simply went on with your own solutions in this area. Any comments on the auto-update topic are welcome.</p>
277,789
10
0
null
2008-11-10 10:15:58.31 UTC
37
2013-01-11 20:47:47.847 UTC
2011-08-03 19:04:30.037 UTC
Barry Kelly
496,830
utku karatas
14,716
null
1
42
delphi|auto-update
38,761
<p>Years ago I wrote a simple tool which is started instead of the real program, checks for updates, loads and installs them (if any are available), and finally starts the real application.</p> <p>There are however problems with that approach if your program works in a properly administered environment, where users normally don't have write access to the program directories. You can no longer simply update your own program in such environments. That's why a lot of programs these days come with their own updater tool, which can be installed to run with elevated permissions, so that program updates can be applied even though only standard users do ever log on to the system.</p> <p>You have to decide whether your target audience can be assumed to run on power user or administrator accounts, or whether you will have to deal with above-mentioned problems. With Vista things got considerably harder already.</p> <p>With all these problems (net access over proxies, missing write permissions for installation directories, the need to update files that the updater itself is using - just to name a few) I wouldn't try again to code this on my own. Much better to check if any one of the available solutions does all you need it to.</p>
238,535
C++ performance of accessing member variables versus local variables
<p>Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive data, perform calculations on it, then pass it off to other classes. Performance-wise, would it make more sense to have a list of member variables that the method populates as it receives data? Or just declare local variables each time the callback method is called?</p> <p>Assume this method would be called hundreds of times a second...</p> <p>In case I'm not being clear, here's some quick examples:</p> <pre><code>// use local variables class thisClass { public: void callback( msg&amp; msg ) { int varA; double varB; std::string varC; varA = msg.getInt(); varB = msg.getDouble(); varC = msg.getString(); // do a bunch of calculations } }; // use member variables class thisClass { public: void callback( msg&amp; msg ) { m_varA = msg.getInt(); m_varB = msg.getDouble(); m_varC = msg.getString(); // do a bunch of calculations } private: int m_varA; double m_varB; std::string m_varC; }; </code></pre>
238,568
11
1
null
2008-10-26 20:08:15.673 UTC
12
2012-05-26 13:08:15.307 UTC
null
null
null
moleary
null
null
1
39
c++|performance
22,747
<p>Executive summary: In virtually all scenarios, it doesn't matter, but there is a slight advantage for local variables.</p> <p>Warning: You are micro-optimizing. You will end up spending hours trying to understand code that is supposed to win a nanosecond.</p> <p>Warning: In your scenario, performance shouldn't be the question, but the role of the variables - are they temporary, or state of thisClass?</p> <p>Warning: First, second and last rule of optimization: measure!</p> <hr> <p>First of all, look at the typical assembly generated for x86 (your platform may vary):</p> <pre><code>// stack variable: load into eax mov eax, [esp+10] // member variable: load into eax mov ecx, [adress of object] mov eax, [ecx+4] </code></pre> <p>Once the address of the object is loaded, int a register, the instructions are identical. Loading the object address can usually be paired with an earlier instruction and doesn't hit execution time.</p> <p>But this means the ecx register isn't available for other optimizations. <em>However</em>, modern CPUs do some intense trickery to make that less of an issue. </p> <p>Also, when accessing many objects this may cost you extra. <em>However</em>, this is less than one cycle average, and there are often more opprtunities for pairing instructions.</p> <p>Memory locality: here's a chance for the stack to win big time. Top of stack is virtually always in the L1 cache, so the load takes one cycle. The object is more likely to be pushed back to L2 cache (rule of thumb, 10 cycles) or main memory (100 cycles). </p> <p><em>However</em>, you pay this only for the first access. if all you have is a single access, the 10 or 100 cycles are unnoticable. if you have thousands of accesses, the object data will be in L1 cache, too.</p> <p>In summary, the gain is so small that it virtually never makes sense to copy member variables into locals to achieve better performance. </p>
680,541
Quick Sort Vs Merge Sort
<p>Why might quick sort be better than merge sort ?</p>
680,559
11
2
null
2009-03-25 07:26:23.45 UTC
55
2020-12-18 08:33:43.243 UTC
2009-03-25 07:41:19.483 UTC
qrdl
28,494
null
43,502
null
1
120
algorithm|sorting
255,770
<p>See <a href="http://en.wikipedia.org/wiki/Quicksort" rel="noreferrer">Quicksort on wikipedia</a>:</p> <blockquote> <p>Typically, quicksort is significantly faster in practice than other Θ(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.</p> </blockquote> <p>Note that the very low memory requirement is a big plus as well.</p>
1,207,457
Convert a Unicode string to a string in Python (containing extra symbols)
<p>How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?</p>
1,207,479
12
13
null
2009-07-30 15:41:11.657 UTC
181
2022-06-30 12:38:29.267 UTC
2016-03-22 17:05:28.957 UTC
null
4,279
null
47,013
null
1
534
python|string|unicode|type-conversion
1,096,529
<p>See <a href="https://docs.python.org/library/unicodedata.html#unicodedata.normalize" rel="noreferrer"><code>unicodedata.normalize</code></a></p> <pre><code>title = u"Klüft skräms inför på fédéral électoral große" import unicodedata unicodedata.normalize('NFKD', title).encode('ascii', 'ignore') 'Kluft skrams infor pa federal electoral groe' </code></pre>
118,633
What's so wrong about using GC.Collect()?
<p>Although I do understand the serious implications of playing with this function (or at least that's what I think), I fail to see why it's becoming one of these things that respectable programmers wouldn't ever use, even those who don't even know what it is for.</p> <p>Let's say I'm developing an application where memory usage varies extremely depending on what the user is doing. The application life cycle can be divided into two main stages: editing and real-time processing. During the editing stage, suppose that billions or even trillions of objects are created; some of them small and some of them not, some may have finalizers and some may not, and suppose their lifetimes vary from a very few milliseconds to long hours. Next, the user decides to switch to the real-time stage. At this point, suppose that performance plays a fundamental role and the slightest alteration in the program's flow could bring catastrophic consequences. Object creation is then reduced to the minimum possible by using object pools and the such but then, the GC chimes in unexpectedly and throws it all away, and someone dies.</p> <p>The question: In this case, wouldn't it be wise to call GC.Collect() before entering the second stage?</p> <p>After all, these two stages never overlap in time with each other and all the optimization and statistics the GC could have gathered would be of little use here...</p> <p>Note: As some of you have pointed out, .NET might not be the best platform for an application like this, but that's beyond the scope of this question. The intent is to clarify whether a GC.Collect() call can improve an application's overall behaviour/performance or not. We all agree that the circumstances under which you would do such a thing are extremely rare but then again, the GC tries to guess and does it perfectly well most of the time, but it's still about guessing.</p> <p>Thanks.</p>
118,776
20
3
2008-09-25 13:12:13.293 UTC
2008-09-23 01:30:12.357 UTC
31
2020-09-25 11:15:34.777 UTC
2008-10-20 00:36:45.923 UTC
null
7,839
Trap
7,839
null
1
110
.net|performance|memory-management|garbage-collection
68,441
<p><a href="https://docs.microsoft.com/en-us/archive/blogs/ricom/when-to-call-gc-collect" rel="nofollow noreferrer">From Rico's Blog...</a></p> <blockquote> <p><strong>Rule #1</strong></p> <p>Don't.</p> <p>This is really the most important rule. It's fair to say that most usages of GC.Collect() are a bad idea and I went into that in some detail in the orginal posting so I won't repeat all that here. So let's move on to...</p> <p><strong>Rule #2</strong></p> <p>Consider calling GC.Collect() if some non-recurring event has just happened and this event is highly likely to have caused a lot of old objects to die.</p> <p>A classic example of this is if you're writing a client application and you display a very large and complicated form that has a lot of data associated with it. Your user has just interacted with this form potentially creating some large objects... things like XML documents, or a large DataSet or two. When the form closes these objects are dead and so GC.Collect() will reclaim the memory associated with them...</p> </blockquote> <p>So it sounds like this situation may fall under Rule #2, you know that there's a moment in time where a lot of old objects have died, and it's non-recurring. However, don't forget Rico's parting words.</p> <blockquote> <p>Rule #1 should trump Rule #2 without strong evidence.</p> </blockquote> <p>Measure, measure, measure.</p>
988,403
How to prevent auto-closing of console after the execution of batch file
<p>What command can I put at the end of a batch file to prevent auto-closing of the console after the execution of the file?</p>
988,423
21
2
null
2009-06-12 18:57:37.503 UTC
104
2022-08-17 04:04:05.043 UTC
2018-11-18 14:10:04.647 UTC
null
4,518,341
null
5,653
null
1
624
windows|command-line|batch-file
862,922
<p>In Windows/DOS batch files:</p> <pre><code>pause </code></pre> <p>This prints a nice <code>"Press any key to continue . . . "</code> message</p> <p>Or, if you don't want the <code>"Press any key to continue . . ."</code> message, do this instead:</p> <pre><code>pause &gt;nul </code></pre>
901,712
How do I check whether a checkbox is checked in jQuery?
<p>I need to check the <code>checked</code> property of a checkbox and perform an action based on the checked property using jQuery.</p> <p>For example, if the <code>age</code> checkbox is checked, then I need to show a textbox to enter <code>age</code>, else hide the textbox.</p> <p>But the following code returns <code>false</code> by default:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if ($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="checkbox" id="isAgeSelected"/&gt; &lt;div id="txtAge" style="display:none"&gt; Age is selected &lt;/div&gt;</code></pre> </div> </div> </p> <p>How do I successfully query the <code>checked</code> property?</p>
903,152
66
3
2013-09-29 15:45:05.537 UTC
2009-05-23 15:16:39.917 UTC
687
2022-07-24 23:16:41.883 UTC
2021-02-20 00:03:33.407 UTC
null
8,384,089
null
111,435
null
1
5,054
javascript|jquery|html|checkbox
4,619,941
<p>This worked for me:</p> <pre><code>$get("isAgeSelected ").checked == true </code></pre> <p>Where <code>isAgeSelected</code> is the id of the control.</p> <p>Also, @karim79's <a href="https://stackoverflow.com/questions/901712/check-checkbox-checked-property-using-jquery/901727#901727">answer</a> works fine. I am not sure what I missed at the time I tested it.</p> <p><strong>Note, this is answer uses Microsoft Ajax, not jQuery</strong></p>
34,749,806
Using moviepy, scipy and numpy in amazon lambda
<p>I'd like to generate video using <code>AWS Lambda</code> feature.</p> <p>I've followed instructions found <a href="http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python">here</a> and <a href="http://www.perrygeo.com/running-python-with-compiled-code-on-aws-lambda.html">here</a>.</p> <p>And I now have the following process to build my <code>Lambda</code> function:</p> <h2>Step 1</h2> <p>Fire a <code>Amazon Linux EC2</code> instance and run this as root on it:</p> <pre class="lang-sh prettyprint-override"><code>#! /usr/bin/env bash # Install the SciPy stack on Amazon Linux and prepare it for AWS Lambda yum -y update yum -y groupinstall "Development Tools" yum -y install blas --enablerepo=epel yum -y install lapack --enablerepo=epel yum -y install atlas-sse3-devel --enablerepo=epel yum -y install Cython --enablerepo=epel yum -y install python27 yum -y install python27-numpy.x86_64 yum -y install python27-numpy-f2py.x86_64 yum -y install python27-scipy.x86_64 /usr/local/bin/pip install --upgrade pip mkdir -p /home/ec2-user/stack /usr/local/bin/pip install moviepy -t /home/ec2-user/stack cp -R /usr/lib64/python2.7/dist-packages/numpy /home/ec2-user/stack/numpy cp -R /usr/lib64/python2.7/dist-packages/scipy /home/ec2-user/stack/scipy tar -czvf stack.tgz /home/ec2-user/stack/* </code></pre> <h2>Step 2</h2> <p>I scp the resulting tarball to my laptop. And then run this script to build a zip archive.</p> <pre class="lang-sh prettyprint-override"><code>#! /usr/bin/env bash mkdir tmp rm lambda.zip tar -xzf stack.tgz -C tmp zip -9 lambda.zip process_movie.py zip -r9 lambda.zip *.ttf cd tmp/home/ec2-user/stack/ zip -r9 ../../../../lambda.zip * </code></pre> <p><code>process_movie.py</code> script is at the moment only a test to see if the stack is ok:</p> <pre class="lang-py prettyprint-override"><code>def make_movie(event, context): import os print(os.listdir('.')) print(os.listdir('numpy')) try: import scipy except ImportError: print('can not import scipy') try: import numpy except ImportError: print('can not import numpy') try: import moviepy except ImportError: print('can not import moviepy') </code></pre> <h2>Step 3</h2> <p>Then I upload the resulting archive to S3 to be the source of my <code>lambda</code> function. When I test the function I get the following <code>callstack</code>:</p> <pre><code>START RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca Version: $LATEST ['tqdm', 'imageio-1.4.egg-info', 'decorator.pyc', 'process_movie.py', 'decorator-4.0.6.dist-info', 'imageio', 'moviepy', 'tqdm-3.4.0.dist-info', 'scipy', 'numpy', 'OpenSans-Regular.ttf', 'decorator.py', 'moviepy-0.2.2.11.egg-info'] ['add_newdocs.pyo', 'numarray', '__init__.py', '__config__.pyc', '_import_tools.py', 'setup.pyo', '_import_tools.pyc', 'doc', 'setupscons.py', '__init__.pyc', 'setup.py', 'version.py', 'add_newdocs.py', 'random', 'dual.pyo', 'version.pyo', 'ctypeslib.pyc', 'version.pyc', 'testing', 'dual.pyc', 'polynomial', '__config__.pyo', 'f2py', 'core', 'linalg', 'distutils', 'matlib.pyo', 'tests', 'matlib.pyc', 'setupscons.pyc', 'setup.pyc', 'ctypeslib.py', 'numpy', '__config__.py', 'matrixlib', 'dual.py', 'lib', 'ma', '_import_tools.pyo', 'ctypeslib.pyo', 'add_newdocs.pyc', 'fft', 'matlib.py', 'setupscons.pyo', '__init__.pyo', 'oldnumeric', 'compat'] can not import scipy 'module' object has no attribute 'core': AttributeError Traceback (most recent call last): File "/var/task/process_movie.py", line 91, in make_movie import numpy File "/var/task/numpy/__init__.py", line 122, in &lt;module&gt; from numpy.__config__ import show as show_config File "/var/task/numpy/numpy/__init__.py", line 137, in &lt;module&gt; import add_newdocs File "/var/task/numpy/numpy/add_newdocs.py", line 9, in &lt;module&gt; from numpy.lib import add_newdoc File "/var/task/numpy/lib/__init__.py", line 13, in &lt;module&gt; from polynomial import * File "/var/task/numpy/lib/polynomial.py", line 11, in &lt;module&gt; import numpy.core.numeric as NX AttributeError: 'module' object has no attribute 'core' END RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca REPORT RequestId: 36c62b93-b94f-11e5-9da7-83f24fc4b7ca Duration: 112.49 ms Billed Duration: 200 ms Memory Size: 1536 MB Max Memory Used: 14 MB </code></pre> <p>I cant understand why python does not found the core directory that is present in the folder structure.</p> <p>EDIT:</p> <p>Following @jarmod advice I've reduced the <code>lambda</code>function to:</p> <pre class="lang-py prettyprint-override"><code>def make_movie(event, context): print('running make movie') import numpy </code></pre> <p>I now have the following error:</p> <pre><code>START RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 Version: $LATEST running make movie Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python intepreter from there.: ImportError Traceback (most recent call last): File "/var/task/process_movie.py", line 3, in make_movie import numpy File "/var/task/numpy/__init__.py", line 127, in &lt;module&gt; raise ImportError(msg) ImportError: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python intepreter from there. END RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 REPORT RequestId: 6abd7ef6-b9de-11e5-8aee-918ac0a06113 Duration: 105.95 ms Billed Duration: 200 ms Memory Size: 1536 MB Max Memory Used: 14 MB </code></pre>
34,930,400
11
5
null
2016-01-12 17:12:06.523 UTC
44
2021-10-07 08:11:04.98 UTC
2016-01-13 10:14:48.16 UTC
null
4,730,638
null
4,730,638
null
1
69
python|amazon-web-services|numpy|aws-lambda
32,958
<p>With the help of all posts in this thread here is a solution for the records:</p> <p>To get this to work you'll need to:</p> <ol> <li><p>start a <code>EC2</code> instance with at least 2GO RAM (to be able to compile <code>NumPy</code> &amp; <code>SciPy</code>)</p></li> <li><p>Install the needed dependencies</p> <pre><code>sudo yum -y update sudo yum -y upgrade sudo yum -y groupinstall "Development Tools" sudo yum -y install blas --enablerepo=epel sudo yum -y install lapack --enablerepo=epel sudo yum -y install Cython --enablerepo=epel sudo yum install python27-devel python27-pip gcc virtualenv ~/env source ~/env/bin/activate pip install scipy pip install numpy pip install moviepy </code></pre></li> <li><p>Copy to your locale machine all the content of the directories (except _markerlib, pip*, pkg_resources, setuptools* and easyinstall*) in a <code>stack</code> folder:</p> <ul> <li><code>home/ec2-user/env/lib/python2.7/dist-packages</code></li> <li><code>home/ec2-user/env/lib64/python2.7/dist-packages</code></li> </ul></li> <li><p>get all required shared libraries from you <code>EC2</code>instance:</p> <ul> <li><code>libatlas.so.3</code> </li> <li><code>libf77blas.so.3</code> </li> <li><code>liblapack.so.3</code> </li> <li><code>libptf77blas.so.3</code></li> <li><code>libcblas.so.3</code> </li> <li><code>libgfortran.so.3</code> </li> <li><code>libptcblas.so.3</code> </li> <li><code>libquadmath.so.0</code></li> </ul></li> <li><p>Put them in a <code>lib</code> subfolder of the <code>stack</code> folder</p></li> <li><p><code>imageio</code> is a dependency of <code>moviepy</code>, you'll need to download some binary version of its dependencies: <code>libfreeimage</code> and of <code>ffmpeg</code>; they can be found <a href="https://github.com/imageio/imageio-binaries/">here</a>. Put them at the root of your stack folder and rename <code>libfreeimage-3.16.0-linux64.so</code>to <code>libfreeimage.so</code></p></li> <li><p>You should now have a <code>stack</code> folder containing:</p> <ul> <li>all python dependencies at root</li> <li>all shared libraries in a <code>lib</code> subfolder</li> <li><code>ffmpeg</code> binary at root</li> <li><code>libfreeimage.so</code> at root</li> </ul></li> <li><p>Zip this folder: <code>zip -r9 stack.zip . -x ".*" -x "*/.*"</code></p></li> <li><p>Use the following <code>lambda_function.py</code> as an entry point for your <code>lambda</code> </p> <pre><code>from __future__ import print_function import os import subprocess SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) LIB_DIR = os.path.join(SCRIPT_DIR, 'lib') FFMPEG_BINARY = os.path.join(SCRIPT_DIR, 'ffmpeg') def lambda_handler(event, context): command = 'LD_LIBRARY_PATH={} IMAGEIO_FFMPEG_EXE={} python movie_maker.py'.format( LIB_DIR, FFMPEG_BINARY, ) try: output = subprocess.check_output(command, shell=True) print(output) except subprocess.CalledProcessError as e: print(e.output) </code></pre></li> <li><p>write a <code>movie_maker.py</code>script that depends on <code>moviepy</code>, <code>numpy</code>, ...</p></li> <li><p>add those to script to your stack.zip file <code>zip -r9 lambda.zip *.py</code></p></li> <li><p>upload the zip to <code>S3</code> and use it as a source for your <code>lambda</code></p></li> </ol> <p>You can also download the <code>stack.zip</code> <a href="http://dvmobile.fr/stackoverflow/lambda-moviepy-stack.zip">here</a>.</p>
6,487,839
Reading data from DataGridView in C#
<p>How can I read data from <code>DataGridView</code> in C#? I want to read the data appear in Table. How do I navigate through lines?</p>
6,488,000
5
0
null
2011-06-27 01:23:52.717 UTC
6
2019-05-20 00:06:36.48 UTC
2014-08-15 21:10:09.383 UTC
null
1,489,823
null
780,303
null
1
22
c#|winforms|datagridview
162,127
<p>something like</p> <pre><code>for (int rows = 0; rows &lt; dataGrid.Rows.Count; rows++) { for (int col= 0; col &lt; dataGrid.Rows[rows].Cells.Count; col++) { string value = dataGrid.Rows[rows].Cells[col].Value.ToString(); } } </code></pre> <p>example without using index</p> <pre><code>foreach (DataGridViewRow row in dataGrid.Rows) { foreach (DataGridViewCell cell in row.Cells) { string value = cell.Value.ToString(); } } </code></pre>
6,408,186
Infinite streams in Scala
<p>Say I have a function, for example the old favourite</p> <pre><code>def factorial(n:Int) = (BigInt(1) /: (1 to n)) (_*_) </code></pre> <p>Now I want to find the biggest value of <code>n</code> for which <code>factorial(n)</code> fits in a Long. I could do </p> <pre><code>(1 to 100) takeWhile (factorial(_) &lt;= Long.MaxValue) last </code></pre> <p>This works, but the 100 is an arbitrary large number; what I really want on the left hand side is an infinite stream that keeps generating higher numbers until the <code>takeWhile</code> condition is met.</p> <p>I've come up with </p> <pre><code>val s = Stream.continually(1).zipWithIndex.map(p =&gt; p._1 + p._2) </code></pre> <p>but is there a better way?</p> <p>(I'm also aware I could get a solution recursively but that's not what I'm looking for.)</p>
6,408,262
5
0
null
2011-06-20 07:46:59.69 UTC
6
2019-05-20 19:48:16.633 UTC
null
null
null
null
770,361
null
1
51
scala|stream
32,730
<pre><code>Stream.from(1) </code></pre> <p>creates a stream starting from 1 and incrementing by 1. It's all in the <a href="https://www.scala-lang.org/files/archive/api/2.12.8/scala/collection/immutable/Stream$.html" rel="noreferrer">API docs</a>.</p>
6,507,475
Job queue as SQL table with multiple consumers (PostgreSQL)
<p>I have a typical producer-consumer problem:</p> <p>Multiple producer applications write job requests to a job-table on a PostgreSQL database.</p> <p>The job requests have a state field that starts contains QUEUED on creation.</p> <p>There are <strong>multiple</strong> consumer applications that are notified by a rule when a producer inserts a new record:</p> <pre><code>CREATE OR REPLACE RULE &quot;jobrecord.added&quot; AS ON INSERT TO jobrecord DO NOTIFY &quot;jobrecordAdded&quot;; </code></pre> <p>They will try to reserve a new record by setting its state to RESERVED. Of course, only one consumer should succeed. All other consumers should not be able to reserve the same record. They should instead reserve other records with state=QUEUED.</p> <p>Example: some producer added the following records to table <em>jobrecord</em>:</p> <pre><code>id state owner payload ------------------------ 1 QUEUED null &lt;data&gt; 2 QUEUED null &lt;data&gt; 3 QUEUED null &lt;data&gt; 4 QUEUED null &lt;data&gt; </code></pre> <p>now, two consumers <em>A</em>, <em>B</em> want to process them. They start running at the same time. One should reserve id 1, the other one should reserve id 2, then the first one who finishes should reserve id 3 and so on..</p> <p>In a pure multithreaded world, I would use a mutex to control access to the job queue, but the consumers are different processes that may run on different machines. They only access the same database, so all synchronization must happen through the database.</p> <p>I read a lot of documentation about concurrent access and locking in PostgreSQL, e.g. <a href="http://www.postgresql.org/docs/9.0/interactive/explicit-locking.html" rel="nofollow noreferrer">http://www.postgresql.org/docs/9.0/interactive/explicit-locking.html</a> <a href="https://stackoverflow.com/questions/389541/select-unlocked-row-in-postgresql/5616714#5616714">Select unlocked row in Postgresql</a> <a href="https://stackoverflow.com/questions/5636006/postgresql-and-locking/5638753#5638753">PostgreSQL and locking</a></p> <p>From these topics, I learned, that the following SQL statement should do what I need:</p> <pre><code>UPDATE jobrecord SET owner= :owner, state = :reserved WHERE id = ( SELECT id from jobrecord WHERE state = :queued ORDER BY id LIMIT 1 ) RETURNING id; // will only return an id when they reserved it successfully </code></pre> <p>Unfortunately, when I run this in multiple consumer processes, in about 50% of the time, they still reserve the same record, both processing it and one overwriting the changes of the other.</p> <p>What am I missing? How do I have to write the SQL statement so that multiple consumers will not reserve the same record?</p>
6,510,889
7
5
null
2011-06-28 13:48:27.273 UTC
25
2021-04-30 03:09:06.49 UTC
2021-04-30 02:40:32.87 UTC
null
32,688
null
819,214
null
1
42
sql|postgresql|queue|producer-consumer
25,166
<p>Read my post here:</p> <p><a href="https://stackoverflow.com/a/6500830/32688">https://stackoverflow.com/a/6500830/32688</a></p> <p>If you use transaction and LOCK TABLE you will have no problems.</p>
6,802,573
Interfaces — What's the point?
<p>The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).</p> <p>All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).</p> <p>In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.</p> <p>easy example (taken from a different stack overflow contribution)</p> <pre><code>public interface IPizza { public void Order(); } public class PepperoniPizza : IPizza { public void Order() { //Order Pepperoni pizza } } public class HawaiiPizza : IPizza { public void Order() { //Order HawaiiPizza } } </code></pre>
6,802,596
32
7
null
2011-07-23 18:56:53.567 UTC
156
2022-04-20 07:07:40.92 UTC
2019-02-27 17:22:59.42 UTC
null
107,625
null
785,021
null
1
319
c#|.net|interface
159,813
<p>The point is that the interface represents a <em>contract</em>. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.</p> <p>You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an <code>IPizza</code> you can use <code>IPizza</code> wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from <code>IPizza</code> is guaranteed to be orderable, as it has an <code>Order()</code> method.</p> <p>Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an <code>Order()</code> method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random <code>object</code> the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the <code>dynamic</code> keyword, but that's going a bit far right now, I guess.)</p> <p>Also note that an interface in the usual sense does not necessarily have to be a C# <code>interface</code>, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, <code>interface</code> suffices).</p>
41,330,707
How can I format PHP files with HTML markup in Visual Studio Code?
<p>I'm using Laravel so all the views are <code>.blade.php</code> files. Visual Studio Code won't format the HTML because of the PHP extension. I removed the "blade" part of the filename, but it still isn't formatting the files properly (via <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd>).</p> <p>I also tried about five extensions, but none of them do the reformatting.</p> <p>How can I format <code>.blade.php</code> files in Visual Studio Code?</p>
46,855,721
9
2
null
2016-12-26 11:40:07.29 UTC
14
2021-02-15 22:11:14.547 UTC
2020-06-13 14:10:29.537 UTC
null
63,550
null
4,843,624
null
1
32
php|laravel|visual-studio-code|code-formatting
58,566
<p>The extension <a href="https://marketplace.visualstudio.com/items?itemName=HookyQR.beautify" rel="noreferrer">Beautify</a> (from HookyQR) just does it very well. Either add PHP, and any other file extension type, to the configuration. As <a href="https://stackoverflow.com/questions/41330707/how-to-format-php-files-with-html-markup-in-visual-studio-code/41522834#41522834">said by Nico</a>, here is an example:</p> <ol> <li><p>Go to user settings (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> → <em>User settings</em> (UI) or <kbd>Ctrl</kbd> + <kbd>,</kbd> (comma)</p> </li> <li><p>Search for Beautify in the field above. And click on <em>&quot;Edit in settings.json&quot;</em> for <em>&quot;Beautify: Config&quot;</em>.</p> </li> <li><p>For the <em>&quot;html&quot;</em> section, add <em>&quot;php&quot;</em> and <em>&quot;blade&quot;</em>.</p> <p><a href="https://i.stack.imgur.com/5aBtU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5aBtU.png" alt="Enter image description here" /></a> <a href="https://i.stack.imgur.com/q22IB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q22IB.png" alt="Enter image description here" /></a></p> </li> </ol> <p>###Usage</p> <p>You can invoke it directly. Press <kbd>F1</kbd>, and then write <strong>Beautify</strong>. The <strong>auto completion</strong> gives you two choices, <em>&quot;Beautify file&quot;</em> and <em>&quot;Beautify selection&quot;</em>. <strong>Choose the one you need</strong>, and it will do the job. That's a <strong>straightforward direct way</strong>.</p> <p><a href="https://i.stack.imgur.com/lBf57.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lBf57.png" alt="Enter image description here" /></a></p> <p><strong>You can also</strong> add a <strong>keybinding</strong> to have a <strong>keyboard shortcut</strong>. Here is how to do it:</p> <ol> <li><p>Open keybindings.json (go to menu <em>File</em> → <em>Preferences</em> → <em>Keyboard Shortcuts</em>)</p> </li> <li><p>Click in the above. Open and edit file <strong>keybindings.json</strong></p> </li> <li><p>Add the following into the closed brackets, []</p> <pre><code>{ &quot;key&quot;: &quot;alt+b&quot;, &quot;command&quot;: &quot;HookyQR.beautify&quot;, &quot;when&quot;: &quot;editorFocus&quot; } </code></pre> <p>Choose any key you want, and make sure you don't override an existing one. Search first in the left side if it exists or not.</p> <p><a href="https://i.stack.imgur.com/kOKKU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kOKKU.png" alt="Enter image description here" /></a></p> </li> </ol> <p>Note that all of those things are well documented in the description of the extension.</p> <h2>Extra: Note about blade</h2> <p>(suite to @Peter Mortensen clarification pinpoint)</p> <h3>blade or blade.php</h3> <p>If you are confused if it's <code>blade</code> or <code>blade.php</code> for the setting! I'll clear it up for you! It's <code>blade</code>! That's vscode keyword for the language!</p> <p><strong>How do you know ?</strong></p> <p>First if you open the list of languages as by the image bellow:</p> <p><a href="https://i.stack.imgur.com/H8QQE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H8QQE.png" alt="enter image description here" /></a></p> <p>Write blade</p> <p><a href="https://i.stack.imgur.com/ZkFN7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZkFN7.png" alt="enter image description here" /></a></p> <p>You can see <code>Laravel Blade (blade)</code>! The language keyword is in the paratheses! <strong>blade</strong>!</p> <p>Well but how to check!</p> <p>Try with <code>blade.php</code> in the settings!</p> <p><a href="https://i.stack.imgur.com/gpspv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gpspv.png" alt="enter image description here" /></a></p> <p>Try to beautify</p> <p><a href="https://i.stack.imgur.com/kWLc9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kWLc9.png" alt="enter image description here" /></a></p> <p>You'll get an asking context menu for what language (html, css, js)!</p> <p><a href="https://i.stack.imgur.com/R3SMn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/R3SMn.png" alt="enter image description here" /></a></p> <p>So it doesn't works!</p> <p>To really know ! Put back <code>blade</code>! And it will work and beautify directly!</p> <h3>How well it works with blade</h3> <p>The awesome answer to that! Is try it, and see for yourself!</p> <p>But if you ask me! I'll say it does work as with html! It can be too handy! And you may need to fix some lines! Depending on your expectations and your style!</p> <p>Here an illustration! I screwed the indentation in purpose</p> <p><a href="https://i.stack.imgur.com/P0WFY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P0WFY.png" alt="enter image description here" /></a></p> <p>And here the beautification result:</p> <p><a href="https://i.stack.imgur.com/xfXIl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xfXIl.png" alt="enter image description here" /></a></p>
15,706,188
Get list of files from FTP server
<p>I'm trying to get a list of all the files we have on a server ( specifically every pdf file we have there ). I've tried using total commander and search for the files. It worked to some extent, as in, i got a list of every pdf we had there, but no way of exporting the results ( we have 100.000+ files there )</p> <p>I've tried using a bash script to get the information, but i'm not very experienced with linux, and i don't really know what i'm doing.</p> <p>My script looks like this : </p> <pre><code>#!/bin/bash hostname="&lt;host&gt;" ftp -i -nv $hostname &lt;&lt; EOF user &lt;username&gt; &lt;password&gt; ls -R EOF </code></pre> <p>Running the above script i get</p> <pre><code>?Invalid command 501 Illegal PORT command ftp: bind: Address already in use 221 Goodbye </code></pre> <p>Any help or pointing me on what to search would be greatly appreciated.</p>
15,706,312
6
0
null
2013-03-29 15:22:59.537 UTC
8
2020-06-30 13:44:52.707 UTC
2015-01-27 20:29:04.52 UTC
null
832,230
null
207,614
null
1
21
bash|ftp
95,967
<p>Try to configure <code>ftp</code> to use the PASV (passive) mode for data transfers. This done with the <code>-p</code> switch.</p> <p>I'm not sure if you will be able to do a recursive file listing with this ftp-client. <code>ls -R</code> in my case just gave the list of files and directories in the current working dir. Maybe <a href="https://stackoverflow.com/questions/2614319/recursive-ftp-directory-listing-in-shell-bash-with-a-single-session-using-curl">Recursive FTP directory listing in shell/bash with a single session (using cURL or ftp)</a> will help you.</p>
16,005,672
Running multiple Selenium tests at the same time
<p>I would like to run multiple Selenium Tests (on a Jenkins server) at the same time.</p> <p>It currently runs only a single test at a time cause ChromeDriver seems to communicate over a special port. So somehow I guess I have to pass some kind of port settings via Selenium to the ChromeDriver to start up multiple tests.</p> <p>The Selenium website unfortunately is empty for that topic: <a href="http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#parallelizing-your-test-runs" rel="noreferrer">http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#parallelizing-your-test-runs</a></p> <p>From my point of view it makes no difference if the Test runs locally or on Jenkins, the problem is the same. We need to somehow configure ChromeDriver. The question is just how.</p> <p>Anybody has some ideas or pointers where to look at and what files are involved to get this done?</p>
16,005,992
4
1
null
2013-04-14 23:47:05.073 UTC
12
2016-06-17 17:30:18.017 UTC
null
null
null
null
1,448,704
null
1
22
testing|selenium|selenium-chromedriver
65,605
<p>What you are looking for is <a href="https://github.com/SeleniumHQ/selenium/wiki/Grid2" rel="nofollow noreferrer">Selenium Grid 2</a>.</p> <p>Grid allows you to :</p> <ul> <li>scale by distributing tests on several machines ( parallel execution )</li> <li>manage multiple environments from a central point, making it easy to run the tests against a vast combination of browsers / OS.</li> <li>minimize the maintenance time for the grid by allowing you to implement custom hooks to leverage virtual infrastructure for instance.</li> </ul>
15,555,042
Doctrine 2 delete with query builder
<p>I have two Entities with relation OneToMany, <code>Project</code> and <code>Services</code>. Now i want to remove all the services by project_id.</p> <p>First attempt:</p> <pre><code>$qb = $em-&gt;createQueryBuilder(); $qb-&gt;delete('Services','s'); $qb-&gt;andWhere($qb-&gt;expr()-&gt;eq('s.project_id', ':id')); $qb-&gt;setParameter(':id',$project-&gt;getId()); </code></pre> <p>This attempt fails with the Exception <code>Entity Service does not have property project_id</code>. And it's true, that property does not exists, it's only in database table as foreign key.</p> <p>Second attempt:</p> <pre><code>$qb = $em-&gt;createQueryBuilder(); $qb-&gt;delete('Services','s')-&gt;innerJoin('s.project','p'); $qb-&gt;andWhere($qb-&gt;expr()-&gt;eq('p.id', ':id')); $qb-&gt;setParameter(':id',$project-&gt;getId()); </code></pre> <p>This one generetate a non valid DQL query too.</p> <p>Any ideas and examples will be welcome.</p>
15,555,495
2
0
null
2013-03-21 18:13:07.927 UTC
3
2017-10-30 09:02:36.69 UTC
2014-10-26 20:21:33.833 UTC
null
759,866
null
338,526
null
1
36
php|doctrine-orm
79,409
<p>You're working with DQL, not SQL, so don't reference the IDs in your condition, reference the object instead.</p> <p>So your first example would be altered to:</p> <pre><code>$qb = $em-&gt;createQueryBuilder(); $qb-&gt;delete('Services', 's'); $qb-&gt;where('s.project = :project'); $qb-&gt;setParameter('project', $project); </code></pre>
15,523,514
Find by key deep in a nested array
<p>Let's say I have an object:</p> <pre><code>[ { 'title': "some title" 'channel_id':'123we' 'options': [ { 'channel_id':'abc' 'image':'http://asdasd.com/all-inclusive-block-img.jpg' 'title':'All-Inclusive' 'options':[ { 'channel_id':'dsa2' 'title':'Some Recommends' 'options':[ { 'image':'http://www.asdasd.com' 'title':'Sandals' 'id':'1' 'content':{ ... </code></pre> <p>I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore's <code>_.filter</code> method, but I would have to start at the top and filter down.</p>
15,524,326
21
0
null
2013-03-20 12:25:41.78 UTC
41
2022-09-20 09:54:40.36 UTC
2020-01-06 17:04:54.897 UTC
null
123,671
null
228,660
null
1
103
javascript|underscore.js
231,196
<p>Recursion is your friend. I updated the function to account for property arrays:</p> <pre><code>function getObject(theObject) { var result = null; if(theObject instanceof Array) { for(var i = 0; i &lt; theObject.length; i++) { result = getObject(theObject[i]); if (result) { break; } } } else { for(var prop in theObject) { console.log(prop + ': ' + theObject[prop]); if(prop == 'id') { if(theObject[prop] == 1) { return theObject; } } if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) { result = getObject(theObject[prop]); if (result) { break; } } } } return result; } </code></pre> <p>updated jsFiddle: <a href="http://jsfiddle.net/FM3qu/7/">http://jsfiddle.net/FM3qu/7/</a></p>
10,749,010
If an Int can't be null, what does null.asInstanceOf[Int] mean?
<p>As a test, I wrote this code:</p> <pre><code>object Ambig extends App { def f( x:Int ) { println("Int" ) } def f( x:String ) { println("String") } f( null.asInstanceOf[Int ] ) f( null.asInstanceOf[String] ) f(null) } </code></pre> <p>I was expecting to get an error on that last invocation of f(), saying that it was ambiguous. The compiler accepted it, and produced this output:</p> <pre><code>Int String String </code></pre> <p>Now I'm guessing that this has to do with the fact that Int is not an AnyRef, so the only version of f that works for f(null) is f(x:String). But then, if an Int can't be null, what does null.asInstanceOf[Int] mean? The repl says it's of type Int:</p> <pre><code>scala&gt; :type null.asInstanceOf[Int] Int </code></pre> <p>but I don't really see how that works. After all, if I try to cast a String to an Int, all hell breaks loose:</p> <pre><code>scala&gt; "foo".asInstanceOf[Int] java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source) ... </code></pre> <p>Of course that's to be expected -- "foo" can't be made into an Int. But neither can null, so why does casting null to an Int work? Presumably boxing in some form, but the type is still Int, which can't be null...</p> <p>What am I missing?</p>
10,750,800
4
4
null
2012-05-25 05:39:06.763 UTC
6
2015-09-26 19:47:56.187 UTC
null
null
null
null
464,309
null
1
36
scala|null
14,616
<p>The behaviour of casting <code>null</code> to an <code>Int</code> depends on the context in which it is done.</p> <p>First of all, if you cast a <code>null</code> to an <code>Int</code>, it actually means a boxed integer, whose value is <code>null</code>. If you put the expression in a context where the expected type is <code>Any</code> (which is translated to <code>Object</code> behind the scene, because in the JVM bytecode, there is no way to refer to a primitive type and a reference type with the same reference), then this value is not converted further - that is why <code>println(null.asInstanceOf[Int])</code> prints <code>null</code>.</p> <p>However, if you use this same boxed integer value in a context where a primitive <code>Int</code> (Java <code>int</code>) is expected, it will be converted to a primitive, and <code>null</code> is (as a default value for reference types) converted to <code>0</code> (a default value for primitive types).</p> <p>If a generic method does this cast, then, naturally, you get a <code>null</code> back.</p> <p>However, if this method is specialized, then its return type is <code>Int</code> (which is a primitive integer in this case), so the <code>null: Any</code> value has to be converted to a primitive, as before.</p> <p>Hence, running:</p> <pre><code>object Test extends App { println(null.asInstanceOf[Int]) def printit(x: Int) = println(x) printit(null.asInstanceOf[Int]) def nullint[T] = null.asInstanceOf[T] println(nullint[Int]) def nullspecint[@specialized(Int) T] = null.asInstanceOf[T] println(nullspecint[Int]) } </code></pre> <p>produces:</p> <pre><code>null 0 null 0 </code></pre>
10,397,736
RestSharp - Ignore SSL errors
<p>Is there any whay that I can get RestSharp to ignore errors in SSL certificates? I have a test client, and the service I connect to does not yet have a valid cetificate.</p> <p>When I make a request now I get the error:</p> <pre><code>The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. </code></pre>
17,234,955
3
6
null
2012-05-01 12:38:48.18 UTC
17
2022-05-11 18:29:21.57 UTC
2020-10-26 08:46:44.473 UTC
null
563,532
null
1,358,305
null
1
91
https|restsharp
64,838
<p>As John suggested:</p> <pre class="lang-cs prettyprint-override"><code>ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =&gt; true; </code></pre>
46,600,498
Initialize all the elements of an array to the same number
<p>Some time ago my old teacher posted this code saying that it is another way to initialize an array to the same number (other than zero of course).</p> <p>Three in this case.</p> <p>He said that this way is slightly better than the <code>for</code> loop. Why do I need the left shift operator? Why do I need another array of long? I don't understand anything what's happening here.</p> <pre><code>int main() { short int A[100]; long int v = 3; v = (v &lt;&lt; 16) + 3; v = (v &lt;&lt; 16) + 3; v = (v &lt;&lt; 16) + 3; long *B = (long*)A; for(int i=0; i&lt;25; i++) B[i] = v; cout &lt;&lt; endl; print(A,100); } </code></pre>
46,600,831
7
21
null
2017-10-06 07:29:30.003 UTC
5
2017-10-19 09:25:18.13 UTC
2017-10-06 18:15:45.763 UTC
null
63,550
null
6,212,793
null
1
59
c++|arrays|for-loop
6,317
<p>He assumes that <code>long</code> is four times longer than <code>short</code> (that is not guaranteed; he should use int16_t and int64_t).</p> <p>He takes that longer memory space (64 bits) and fills it with four short (16 bits) values. He is setting up the values by shifting bits by 16 spaces.</p> <p>Then he wants to treat an array of shorts as an array of longs, so he can set up 100 16-bit values by doing only 25 loop iteration instead of 100.</p> <p>That's the way your teacher thinks, but as others said this cast is undefined behavior.</p>
50,585,456
How can I Interleave / merge async iterables?
<p>Suppose I have some async iterable objects like this:</p> <pre><code>const a = { [Symbol.asyncIterator]: async function * () { yield 'a'; await sleep(1000); yield 'b'; await sleep(2000); yield 'c'; }, }; const b = { [Symbol.asyncIterator]: async function * () { await sleep(6000); yield 'i'; yield 'j'; await sleep(2000); yield 'k'; }, }; const c = { [Symbol.asyncIterator]: async function * () { yield 'x'; await sleep(2000); yield 'y'; await sleep(8000); yield 'z'; await sleep(10000); throw new Error('You have gone too far! '); }, }; </code></pre> <p>And for completeness:</p> <pre><code>// Promisified sleep function const sleep = ms =&gt; new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; resolve(ms), ms); }); </code></pre> <p>Now, suppose I can concat them like this:</p> <pre><code>const abcs = async function * () { yield * a; yield * b; yield * c; }; </code></pre> <p>The (first 9) items yielded will be:</p> <pre><code>(async () =&gt; { const limit = 9; let i = 0; const xs = []; for await (const x of abcs()) { xs.push(x); i++; if (i === limit) { break; } } console.log(xs); })().catch(error =&gt; console.error(error)); // [ 'a', 'b', 'c', 'i', 'j', 'k', 'x', 'y', 'z' ] </code></pre> <p>But imagine that I <em>do not care about the order</em>, that <code>a</code>, <code>b</code> and <code>c</code> yield at different speeds, and that I want to <em>yield as quickly as possible.</em></p> <p>How can I rewrite this loop so that <code>x</code>s are yielded as soon as possible, ignoring order?</p> <hr /> <p>It is also possible that <code>a</code>, <code>b</code> or <code>c</code> are infinite sequences, so the solution must not require all elements to be buffered into an array.</p>
50,586,391
7
9
null
2018-05-29 13:19:21.997 UTC
9
2021-11-16 07:16:27.027 UTC
2021-04-21 08:42:53.493 UTC
null
1,256,041
null
1,256,041
null
1
29
javascript|promise|iterator|async-await
4,989
<p>There is no way to write this with a loop statement. <code>async</code>/<code>await</code> code always executes sequentially, to do things concurrently you need to use promise combinators directly. For plain promises, there's <code>Promise.all</code>, for async iterators there is nothing (yet) so we need to write it on our own:</p> <pre><code>async function* combine(iterable) { const asyncIterators = Array.from(iterable, o =&gt; o[Symbol.asyncIterator]()); const results = []; let count = asyncIterators.length; const never = new Promise(() =&gt; {}); function getNext(asyncIterator, index) { return asyncIterator.next().then(result =&gt; ({ index, result, })); } const nextPromises = asyncIterators.map(getNext); try { while (count) { const {index, result} = await Promise.race(nextPromises); if (result.done) { nextPromises[index] = never; results[index] = result.value; count--; } else { nextPromises[index] = getNext(asyncIterators[index], index); yield result.value; } } } finally { for (const [index, iterator] of asyncIterators.entries()) if (nextPromises[index] != never &amp;&amp; iterator.return != null) iterator.return(); // no await here - see https://github.com/tc39/proposal-async-iteration/issues/126 } return results; } </code></pre> <p>Notice that <code>combine</code> does not support passing values into <code>next</code> or cancellation through <code>.throw</code> or <code>.return</code>.</p> <p>You can call it like</p> <pre><code>(async () =&gt; { for await (const x of combine([a, b, c])) { console.log(x); } })().catch(console.error); </code></pre>
10,620,862
Use different center than the prime meridian in plotting a world map
<p>I am overlaying a world map from the <code>maps</code> package onto a <code>ggplot2</code> raster geometry. However, this raster is not centered on the prime meridian (0 deg), but on 180 deg (roughly the Bering Sea and the Pacific). The following code gets the map and recenters the map on 180 degree:</p> <pre><code>require(maps) world_map = data.frame(map(plot=FALSE)[c("x","y")]) names(world_map) = c("lon","lat") world_map = within(world_map, { lon = ifelse(lon &lt; 0, lon + 360, lon) }) ggplot(aes(x = lon, y = lat), data = world_map) + geom_path() </code></pre> <p>which yields the following output:</p> <p><img src="https://i.stack.imgur.com/DlVSm.png" alt="enter image description here"></p> <p>Quite obviously there are the lines draw between polygons that are on one end or the other of the prime meridian. My current solution is to replace points close to the prime meridian by NA, replacing the <code>within</code> call above by:</p> <pre><code>world_map = within(world_map, { lon = ifelse(lon &lt; 0, lon + 360, lon) lon = ifelse((lon &lt; 1) | (lon &gt; 359), NA, lon) }) ggplot(aes(x = lon, y = lat), data = world_map) + geom_path() </code></pre> <p>Which leads to the correct image. I now have a number of question:</p> <ol> <li>There must be a better way of centering the map on another meridian. I tried using the <code>orientation</code> parameter in <code>map</code>, but setting this to <code>orientation = c(0,180,0)</code> did not yield the correct result, in fact it did not change anything to the result object (<code>all.equal</code> yielded <code>TRUE</code>).</li> <li>Getting rid of the horizontal stripes should be possible without deleting some of the polygons. It might be that solving point 1. also solves this point.</li> </ol>
10,749,877
3
8
null
2012-05-16 14:37:19.09 UTC
16
2017-07-17 16:54:47.02 UTC
2012-05-25 16:27:14.647 UTC
null
980,833
null
1,033,808
null
1
32
r|ggplot2
7,477
<p>Here's a different approach. It works by:</p> <ol> <li>Converting the world map from the <code>maps</code> package into a <code>SpatialLines</code> object with a geographical (lat-long) CRS.</li> <li>Projecting the <code>SpatialLines</code> map into the Plate Carée (aka Equidistant Cylindrical) projection centered on the Prime Meridian. (This projection is very similar to a geographical mapping).</li> <li>Cutting in two segments that would otherwise be clipped by left and right edges of the map. (This is done using topological functions from the <code>rgeos</code> package.)</li> <li>Reprojecting to a Plate Carée projection centered on the desired meridian (<code>lon_0</code> in terminology taken from the <code>PROJ_4</code> program used by <code>spTransform()</code> in the <code>rgdal</code> package).</li> <li>Identifying (and removing) any remaining 'streaks'. I automated this by searching for lines that cross g.e. two of three widely separated meridians. (This also uses topological functions from the <code>rgeos</code> package.)</li> </ol> <p>This is obviously a lot of work, but leaves one with maps that are minimally truncated, and can be easily reprojected using <code>spTransform()</code>. To overlay these on top of raster images with <code>base</code> or <code>lattice</code> graphics, I first reproject the rasters, also using <code>spTransform()</code>. If you need them, grid lines and labels can likewise be projected to match the <code>SpatialLines</code> map.</p> <hr> <pre><code>library(sp) library(maps) library(maptools) ## map2SpatialLines(), pruneMap() library(rgdal) ## CRS(), spTransform() library(rgeos) ## readWKT(), gIntersects(), gBuffer(), gDifference() ## Convert a "maps" map to a "SpatialLines" map makeSLmap &lt;- function() { llCRS &lt;- CRS("+proj=longlat +ellps=WGS84") wrld &lt;- map("world", interior = FALSE, plot=FALSE, xlim = c(-179, 179), ylim = c(-89, 89)) wrld_p &lt;- pruneMap(wrld, xlim = c(-179, 179)) map2SpatialLines(wrld_p, proj4string = llCRS) } ## Clip SpatialLines neatly along the antipodal meridian sliceAtAntipodes &lt;- function(SLmap, lon_0) { ## Preliminaries long_180 &lt;- (lon_0 %% 360) - 180 llCRS &lt;- CRS("+proj=longlat +ellps=WGS84") ## CRS of 'maps' objects eqcCRS &lt;- CRS("+proj=eqc") ## Reproject the map into Equidistant Cylindrical/Plate Caree projection SLmap &lt;- spTransform(SLmap, eqcCRS) ## Make a narrow SpatialPolygon along the meridian opposite lon_0 L &lt;- Lines(Line(cbind(long_180, c(-89, 89))), ID="cutter") SL &lt;- SpatialLines(list(L), proj4string = llCRS) SP &lt;- gBuffer(spTransform(SL, eqcCRS), 10, byid = TRUE) ## Use it to clip any SpatialLines segments that it crosses ii &lt;- which(gIntersects(SLmap, SP, byid=TRUE)) # Replace offending lines with split versions # (but skip when there are no intersections (as, e.g., when lon_0 = 0)) if(length(ii)) { SPii &lt;- gDifference(SLmap[ii], SP, byid=TRUE) SLmap &lt;- rbind(SLmap[-ii], SPii) } return(SLmap) } ## re-center, and clean up remaining streaks recenterAndClean &lt;- function(SLmap, lon_0) { llCRS &lt;- CRS("+proj=longlat +ellps=WGS84") ## map package's CRS newCRS &lt;- CRS(paste("+proj=eqc +lon_0=", lon_0, sep="")) ## Recenter SLmap &lt;- spTransform(SLmap, newCRS) ## identify remaining 'scratch-lines' by searching for lines that ## cross 2 of 3 lines of longitude, spaced 120 degrees apart v1 &lt;-spTransform(readWKT("LINESTRING(-62 -89, -62 89)", p4s=llCRS), newCRS) v2 &lt;-spTransform(readWKT("LINESTRING(58 -89, 58 89)", p4s=llCRS), newCRS) v3 &lt;-spTransform(readWKT("LINESTRING(178 -89, 178 89)", p4s=llCRS), newCRS) ii &lt;- which((gIntersects(v1, SLmap, byid=TRUE) + gIntersects(v2, SLmap, byid=TRUE) + gIntersects(v3, SLmap, byid=TRUE)) &gt;= 2) SLmap[-ii] } ## Put it all together: Recenter &lt;- function(lon_0 = -100, grid=FALSE, ...) { SLmap &lt;- makeSLmap() SLmap2 &lt;- sliceAtAntipodes(SLmap, lon_0) recenterAndClean(SLmap2, lon_0) } ## Try it out par(mfrow=c(2,2), mar=rep(1, 4)) plot(Recenter(-90), col="grey40"); box() ## Centered on 90w plot(Recenter(0), col="grey40"); box() ## Centered on prime meridian plot(Recenter(90), col="grey40"); box() ## Centered on 90e plot(Recenter(180), col="grey40"); box() ## Centered on International Date Line </code></pre> <p><img src="https://i.stack.imgur.com/7pUAD.png" alt="enter image description here"></p>
56,476,007
SwiftUI TextField max length
<p>Is it possible to set a maximum length for <code>TextField</code>? I was thinking of handling it using <code>onEditingChanged</code> event but it is only called when the user begins/finishes editing and not called while user is typing. I've also read the docs but haven't found anything yet. Is there any workaround?</p> <pre><code>TextField($text, placeholder: Text("Username"), onEditingChanged: { _ in print(self.$text) }) { print("Finished editing") } </code></pre>
58,364,685
15
3
null
2019-06-06 10:46:23.517 UTC
16
2022-08-02 10:42:50.3 UTC
2019-06-06 11:03:49.69 UTC
null
3,815,069
null
3,815,069
null
1
62
ios|swift|swiftui
32,893
<p>A slightly shorter version of Paulw11's answer would be:</p> <pre><code>class TextBindingManager: ObservableObject { @Published var text = &quot;&quot; { didSet { if text.count &gt; characterLimit &amp;&amp; oldValue.count &lt;= characterLimit { text = oldValue } } } let characterLimit: Int init(limit: Int = 5){ characterLimit = limit } } struct ContentView: View { @ObservedObject var textBindingManager = TextBindingManager(limit: 5) var body: some View { TextField(&quot;Placeholder&quot;, text: $textBindingManager.text) } } </code></pre> <p>All you need is an <code>ObservableObject</code> wrapper for the TextField string. Think of it as an interpreter that gets notified every time there's a change and is able to send modifications back to the TextField. However, there's no need to create the <code>PassthroughSubject</code>, using the <code>@Published</code> modifier will have the same result, in less code.</p> <p>One mention, you need to use <code>didSet</code>, and not <code>willSet</code> or you can end up in a recursive loop.</p>
33,800,344
Java private constructors visibility
<p>I try to understand why there is a difference between accessibility of class members when speaking about constructors.</p> <p>Consider the following example:</p> <pre><code>class A { static class B { private B(String s) {} private void foo() {} } static class C extends B { public C(String s) { super(s); // call B(String), which is private, and obviously accessible } void bar() { foo(); // compilation error (symbol unknown), as B.foo() is private } } } </code></pre> <p>Private members of <code>A</code>, as being private, should not be accessible from <code>B</code>. For fields and methods, it is the case, but it seems that constructors are not following the same rule.</p> <p>From the JLS-8 (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.1" rel="noreferrer">6.6.1. Determining Accessibility</a>), we can read:</p> <blockquote> <p>[...]</p> <p>A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:</p> <ul> <li><p>[...]</p> </li> <li><p>Otherwise, the member or constructor is declared <code>private</code>, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.</p> </li> </ul> </blockquote> <p>Can anyone explain me why the constructor is accessible from <code>C</code>, even while being declared <code>private</code>?</p>
33,800,659
3
11
null
2015-11-19 09:50:01.333 UTC
null
2015-11-19 14:13:32.557 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,649,158
null
1
31
java|constructor|private
1,674
<p>The method <code>foo()</code> is private, so you don't inherit it and can't call it directly from the <code>C</code> class. </p> <p>However, you can see private methods and constructor from <code>B</code> since everything is declared in the same containing class, and access them with <code>super</code>, which is why <code>super()</code> works. In the same way, you can access <code>foo</code> with <code>super.foo()</code>.</p> <p>Note that you can redefine a new foo method in <code>C</code>, but this method will not override <code>B.foo()</code>.</p>
22,515,908
Using straight Lua, how do I expose an existing C++ class objec for use in a Lua script?
<p>I've been furthering my experience in embedding Lua scripting in C++, and I could use a hand, here.</p> <p>Consider the following two classes:</p> <pre class="lang-cpp prettyprint-override"><code>// Person.hpp #pragma once #include &lt;string&gt; class Person { private: std::string p_Name; int p_Age; public: Person(const std::string &amp; strName, const int &amp; intAge) : p_Name(strName), p_Age(intAge) { } Person() : p_Name(""), p_Age(0) { } std::string getName() const { return p_Name; } int getAge() const { return p_Age; } void setName(const std::string &amp; strName) { p_Name = strName; } void setAge(const int &amp; intAge) { p_Age = intAge; } }; </code></pre> <p>... and ...</p> <pre class="lang-cpp prettyprint-override"><code>// PersonManager.hpp #pragma once #include "Person.hpp" #include &lt;vector&gt; class PersonManager { // Assume that this class is a singleton, and therefore // has no public constructor, but a static function that returns the // singleton instance. private: std::vector&lt;Person *&gt; pm_People; public: bool personExists(const std::string &amp; strName) { /* ... */ } bool addPerson(const std::string &amp; strName, const int &amp; intAge) { /* ... */ } Person * getPerson(const std::string &amp; strName) { /* ... */ } void removePerson(const std::string &amp; strName) { /* ... */ } void removeAllPeople() { /* ... */ } }; </code></pre> <p>... where <code>getPerson</code> checks the <code>pm_People</code> vector to see if the person with the specified name exists, using <code>personExists</code>.</p> <p>Now, consider the following function that gets a <code>Person</code> object from Lua and returns its age.</p> <pre class="lang-cpp prettyprint-override"><code>// Lua_Person.cpp #include "Lua_Person.hpp" // "Lua_Person.hpp" declares the function called to expose the "Person" functions to Lua. #include "PersonManager.hpp" #include "Person.hpp" int lua_GetPersonAge(lua_State * LS) { // Validate the userdata. luaL_checktype(LS, 1, LUA_TUSERDATA); // Get the "Person" userdata. Person * luaPerson = reinterpret_cast&lt;Person *&gt;(lua_touserdata(LS, 1)); // Check to see if the Person pointer is not null. if(luaPerson == nullptr) luaL_error(LS, "lua_GetPersonAge: You gave me a null pointer!"); // Push the person's age onto the Lua stack. lua_pushnumber(LS, luaPerson-&gt;getAge()); // Return that age integer. return 1; } </code></pre> <p>What I want to do is to get an already-instantiated and existing <code>Person</code> object from the <code>PersonManager</code> singleton, using <code>getPerson</code>, and expose that object to Lua, so I can do something like this:</p> <pre class="lang-lua prettyprint-override"><code>local testPerson = People.get("Stack Overflower") print(testPerson:getAge()) </code></pre> <p>I tried something like the code block below, to no avail:</p> <pre class="lang-cpp prettyprint-override"><code>int lua_GetPerson(lua_State * LS) { // Validate the argument passed in. luaL_checktype(LS, 1, LUA_TSTRING); // Get the string. std::string personName = lua_tostring(LS, 1); // Verify that the person exists. if(PersonManager::getInstance().personExists(personName) == false) luaL_error(LS, "lua_GetPerson: No one exists with this ID: %s", personName.c_str()); // Put a new userdata into a double pointer, and assign it to the already existing "Person" object requested. Person ** p = static_cast&lt;Person **&gt;(lua_newuserdata(LS, sizeof(Person *))); // &lt;Userdata&gt; *p = PersonManager::getInstance().getPerson(personName); // Put that person object into the "Meta_Person" metatable. // Assume that metatable is created during the registration of the Person/Person Manager functions with Lua. luaL_getmetatable(LS, "Meta_Person"); // &lt;Metatable&gt;, &lt;Userdata&gt; lua_setmetatable(LS, -2); // &lt;Metatable&gt; // Return that metatable. return 1; } </code></pre> <p>Can anybody lend a helping hand here, or at least point me in the right direction? I am not using any lua wrapper libraries, just straight Lua.</p> <p>Thank you.</p> <p>EDIT: The functions that I use to expose my <code>Person</code> and <code>PersonManager</code> functions are as follows:</p> <pre class="lang-cpp prettyprint-override"><code>void exposePerson(lua_State * LS) { static const luaL_reg person_functions[] = { { "getAge", lua_getPersonAge }, { nullptr, nullptr } }; luaL_newmetatable(LS, "Meta_Person"); lua_pushstring(LS, "__index"); lua_pushvalue(LS, -2); lua_settable(LS, -3); luaL_openlib(LS, nullptr, person_functions, 0); } void exposePersonManager(lua_State * LS) { static const luaL_reg pman_functions[] = { { "get", lua_getPerson }, { nullptr, nullptr } }; luaL_openlib(LS, "People", pman_functions, 0); lua_pop(LS, 1); } </code></pre>
22,558,439
2
2
null
2014-03-19 19:11:44.517 UTC
9
2014-03-21 16:30:07.347 UTC
2014-03-19 20:10:07.597 UTC
null
2,868,302
null
2,868,302
null
1
9
c++|lua
6,483
<p>Let's start off the top, that is by registering <code>PersonManager</code> in Lua. Since it's a singleton, we'll register it as a global.</p> <pre><code>void registerPersonManager(lua_State *lua) { //First, we create a userdata instance, that will hold pointer to our singleton PersonManager **pmPtr = (PersonManager**)lua_newuserdata( lua, sizeof(PersonManager*)); *pmPtr = PersonManager::getInstance(); //Assuming that's the function that //returns our singleton instance //Now we create metatable for that object luaL_newmetatable(lua, "PersonManagerMetaTable"); //You should normally check, if the table is newly created or not, but //since it's a singleton, I won't bother. //The table is now on the top of the stack. //Since we want Lua to look for methods of PersonManager within the metatable, //we must pass reference to it as "__index" metamethod lua_pushvalue(lua, -1); lua_setfield(lua, -2, "__index"); //lua_setfield pops the value off the top of the stack and assigns it to our //field. Hence lua_pushvalue, which simply copies our table again on top of the stack. //When we invoke lua_setfield, Lua pops our first reference to the table and //stores it as "__index" field in our table, which is also on the second //topmost position of the stack. //This part is crucial, as without the "__index" field, Lua won't know where //to look for methods of PersonManager luaL_Reg personManagerFunctions[] = { 'get', lua_PersonManager_getPerson, nullptr, nullptr }; luaL_register(lua, 0, personManagerFunctions); lua_setmetatable(lua, -2); lua_setglobal(lua, "PersonManager"); } </code></pre> <p>Now we handle <code>PersonManager</code>'s <code>get</code> method:</p> <pre><code>int lua_PersonManager_getPerson(lua_State *lua) { //Remember that first arbument should be userdata with your PersonManager //instance, as in Lua you would call PersonManager:getPerson("Stack Overflower"); //Normally I would first check, if first parameter is userdata with metatable //called PersonManagerMetaTable, for safety reasons PersonManager **pmPtr = (PersonManager**)luaL_checkudata( lua, 1, "PersonManagerMetaTable"); std::string personName = luaL_checkstring(lua, 2); Person *person = (*pmPtr)-&gt;getPerson(personName); if (person) registerPerson(lua, person); //Function that registers person. After //the function is called, the newly created instance of Person //object is on top of the stack else lua_pushnil(lua); return 1; } void registerPerson(lua_State *lua, Person *person) { //We assume that the person is a valid pointer Person **pptr = (Person**)lua_newuserdata(lua, sizeof(Person*)); *pptr = person; //Store the pointer in userdata. You must take care to ensure //the pointer is valid entire time Lua has access to it. if (luaL_newmetatable(lua, "PersonMetaTable")) //This is important. Since you //may invoke it many times, you should check, whether the table is newly //created or it already exists { //The table is newly created, so we register its functions lua_pushvalue(lua, -1); lua_setfield(lua, -2, "__index"); luaL_Reg personFunctions[] = { "getAge", lua_Person_getAge, nullptr, nullptr }; luaL_register(lua, 0, personFunctions); } lua_setmetatable(lua, -2); } </code></pre> <p>And finally handling <code>Person</code>'s <code>getAge</code>.</p> <pre><code>int lua_Person_getAge(lua_State *lua) { Person **pptr = (Person**)lua_checkudata(lua, 1, "PersonMetaTable"); lua_pushnumber(lua, (*pptr)-&gt;getAge()); return 1; } </code></pre> <p>You should now call <code>registerPersonManager</code> before executing your Lua code, best just after you create new Lua state and open needed libraries.</p> <p>Now within Lua, you should be able to do that:</p> <pre><code>local person = PersonManager:getPerson("Stack Overflower"); print(person:getAge()); </code></pre> <p>I don't have access to either Lua or C++ at the moment to test it, but that should get you started. Please be careful with lifetime of the <code>Person</code> pointer you give Lua access to.</p>
22,834,379
CSS3 -ms-max-content in IE11
<p>We can set in CSS3 <code>-moz-max-content</code> (for Firefox) and <code>-webkit-max-content</code> (for Chrome, Safari) as <code>width</code>, but it seems <code>-ms-max-content</code> is not working in Internet Explorer (IE11).</p> <p><strong>Update:</strong> Here is a sample code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.button { background: #d1d1d1; margin: 2px; cursor: pointer; width: -moz-max-content; width: -webkit-max-content; width: -o-max-content; width: -ms-max-content; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div class="button"&gt; Short t. &lt;/div&gt; &lt;div class="button"&gt; Looooooong text &lt;/div&gt; &lt;div class="button"&gt; Medium text &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
22,835,556
4
2
null
2014-04-03 10:09:34.5 UTC
4
2020-06-02 10:00:13.48 UTC
2019-12-22 03:29:30.1 UTC
null
3,448,527
null
2,857,638
null
1
24
html|css|internet-explorer|internet-explorer-11
61,032
<p><code>-max-content</code> it is not supported by IE, according to <a href="http://caniuse.com/#feat=intrinsic-width" rel="noreferrer">CanIuse</a>.</p> <p>So I created a fallback for IE that might help you, by setting <code>.button</code> to <code>display:inline-block</code>:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.button { background: #d1d1d1; margin: 2px; cursor: pointer; width: -moz-max-content; width: -webkit-max-content; width: -o-max-content; /* width: -ms-max-content;*/ } /* fallback for IE*/ .button { display: inline-block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div class="button"&gt;Short t.&lt;/div&gt; &lt;div class="button"&gt;Looooooong text&lt;/div&gt; &lt;div class="button"&gt;Medium text&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p><strong>UPDATE: (Based on OP comment)</strong></p> <blockquote> <p>It's working, but I don't want to display the elements inline.</p> </blockquote> <p>here is the final answer:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.button { background: #d1d1d1; margin: 2px; cursor: pointer; width: -moz-max-content; width: -webkit-max-content; width: -o-max-content /* width: -ms-max-content;*/ } /* fallback for IE*/ .width { width:100% } .button { display: inline-block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div class="width"&gt; &lt;div class="button"&gt;Short t.&lt;/div&gt; &lt;/div&gt; &lt;div class="width"&gt; &lt;div class="button"&gt;Looooooong text&lt;/div&gt; &lt;/div&gt; &lt;div class="width"&gt; &lt;div class="button"&gt;Medium text&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <h2>NEW UPDATE</h2> <p>Nowadays and for awhile there is a cleaner approach to this issue, by simply setting the parent as <code>display: flex</code>, and you even won't need the <code>*-max-content</code> value in <code>width</code> property</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.button { background: #d1d1d1; margin: 2px; cursor: pointer; } /* the fix */ section { display: flex }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;section&gt; &lt;div class="button"&gt;Short t.&lt;/div&gt; &lt;div class="button"&gt;Looooooong text&lt;/div&gt; &lt;div class="button"&gt;Medium text&lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
13,658,756
Example of tm use
<p>Can you give an example of use of <code>tm</code> (I don't know how to initialize that <code>struct</code>) where the current date is written in this format <code>y/m/d</code>?</p>
13,658,903
1
1
null
2012-12-01 11:01:14.823 UTC
4
2012-12-01 11:25:27.063 UTC
2012-12-01 11:25:27.063 UTC
null
851,432
null
1,833,274
null
1
8
c|tm
40,592
<h3>How to use <code>tm</code> structure</h3> <ol> <li>call <code>time()</code> to get current date/time as number of seconds since 1 Jan 1970.</li> <li><p>call <code>localtime()</code> to get <code>struct tm</code> pointer. If you want GMT them call <code>gmtime()</code> instead of <code>localtime()</code>.</p></li> <li><p>Use <code>sprintf()</code> or <code>strftime()</code> to convert the struct tm to a string in any format you want.</p></li> </ol> <h3>Example</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main () { time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &amp;rawtime ); timeinfo = localtime ( &amp;rawtime ); strftime (buffer,80,"Now it's %y/%m/%d.",timeinfo); puts (buffer); return 0; } </code></pre> <h3>Example Output</h3> <pre><code>Now it's 12/10/24 </code></pre> <h3>References:</h3> <ul> <li><a href="http://www.daniweb.com/software-development/c/threads/335282/struct-tm" rel="noreferrer">struct tm</a></li> <li><a href="http://www.cplusplus.com/reference/ctime/strftime/" rel="noreferrer">strftime</a></li> </ul>
13,229,111
C char array concatenation
<p>What I have:</p> <pre><code>char cmd[50] = "some text here"; char v[] = {'a','s','d','c','b'}; </code></pre> <p>So I want to concatenate <code>cmd</code> by adding a letter from <code>v</code>.</p> <p>Obviously: </p> <pre><code>strcat(cmd, v[3]); </code></pre> <p>doesn't work because <code>strcat</code> doesn't accept the <code>v[n]</code> parameter <code>n = int</code>.</p>
13,229,171
7
0
null
2012-11-05 09:21:20.297 UTC
2
2014-05-27 12:21:53.63 UTC
2014-05-27 12:21:53.63 UTC
null
1,772,805
null
1,713,797
null
1
11
c|arrays|char|concatenation
64,860
<p>Problems with your approach.</p> <ul> <li><p>C strings must end in 0 byte, in other words <code>'\0'</code> character. Using <code>""</code> adds that automatically, but otherwise you have to add it yourself, and all string functions depend on that 0 being there.</p></li> <li><p>Your v array contains characters, not strings, and <code>strcat</code> takes strings.</p></li> </ul> <p>One solution:</p> <pre><code>char cmd[50] = "some text here"; char *v[] = {"a","s","d","c","b"}; strcat(cmd,v[3]); </code></pre> <p>This turns your char array into array of pointers to C strings.</p> <p>Also, it's your responsibility to take care that, <code>cmd[]</code> contains enough space to hold whatever you add to it with strcat (here it does). It's usually best to use <code>snprintf</code> to do string concatenation, as it takes total size of the target array <em>including</em> terminating null, and adds that null there always, so it's harder to mess up. Example with your original char array:</p> <pre><code>char cmd[50] = "some text here"; char buf[50]; char v[] = {'a','s','d','c','b'}; snprintf(buf, sizeof buf, "%s%c", cmd, v[3]); </code></pre> <p>Notes: sizeof like this works only when <code>buf</code> really is an array, declared with <code>[]</code> like here. Also with snprintf, using same buffer both as destination and format argument may yield unexpected results, so I added a new destination buffer variable.</p> <p>One more snprintf example, with your original two arrays only, appending to end of current contents of cmd:</p> <pre><code>snprintf(cmd + strlen(cmd), (sizeof cmd) - strlen(cmd), "%c", v[3]); </code></pre> <p>So clearly, in this particular case, the <code>strncat(cmd, &amp;v[3], 1)</code> suggested in other answers to add 1 character is much nicer, but benefit of snprintf is, you can add all datatype supported by printf, not chars.</p>
13,656,921
Fastest way to find the index of a child node in parent
<p>I want to find the index of the child div that has the id <code>'whereami'</code>.</p> <pre><code>&lt;div id="parent"&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div id="whereami"&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Currently I am using this function to find the index of the child.</p> <pre><code>function findRow(node){ var i=1; while(node.previousSibling){ node = node.previousSibling; if(node.nodeType === 1){ i++; } } return i; //Returns 3 } var node = document.getElementById('whereami'); //div node to find var index = findRow(node); </code></pre> <p>fiddle: <a href="http://jsfiddle.net/grantk/F7JpH/2/">http://jsfiddle.net/grantk/F7JpH/2/</a></p> <p><strong>The Problem</strong><br> When there are a thousands of div nodes, the while loop has to traverse through each div to count them. Which can take a while.</p> <p>Is there any faster way to tackle this?</p> <p>*Note that the id will change to different divs node, so it will need to be able to re-calculate.</p>
13,657,635
9
11
null
2012-12-01 06:05:27.757 UTC
12
2020-07-21 18:23:16.133 UTC
2012-12-01 06:55:27.79 UTC
null
1,845,423
null
1,845,423
null
1
34
javascript|html|dom
32,404
<p>Out of curiosity I ran your code against both jQuery's <a href="http://api.jquery.com/index/" rel="noreferrer"><code>.index()</code></a> and my below code:</p> <pre><code>function findRow3(node) { var i = 1; while (node = node.previousSibling) { if (node.nodeType === 1) { ++i } } return i; } </code></pre> <p><a href="http://jsperf.com/sibling-index/9" rel="noreferrer"><strong>Jump to jsperf results</strong></a></p> <p>It turns out that jQuery is roughly 50% slower than your implementation (on Chrome/Mac) and mine arguably topped it by 1%.</p> <p><strong>Edit</strong></p> <p>Couldn't quite let this one go, so I've added two more approaches:</p> <p><em>Using Array.indexOf</em></p> <pre><code>[].indexOf.call(node.parentNode.children, node); </code></pre> <p>Improvement on my earlier experimental code, as seen in <a href="https://stackoverflow.com/a/13657458/1338292">HBP's answer</a>, the <code>DOMNodeList</code> is treated like an array and it uses <code>Array.indexOf()</code> to determine the position within its <code>.parentNode.children</code> which are all elements. My first attempt was using <code>.parentNode.childNodes</code> but that gives incorrect results due to text nodes.</p> <p><em>Using previousElementSibling</em></p> <p>Inspired by <a href="https://stackoverflow.com/a/13660565/1338292">user1689607's answer</a>, recent browsers have another property besides <code>.previousSibling</code> called .<code>previousElementSibling</code>, which does both original statements in one. IE &lt;= 8 doesn't have this property, but <code>.previousSibling</code> already acts as such, therefore a <a href="https://gist.github.com/1393418" rel="noreferrer">feature detection</a> would work.</p> <pre><code>(function() { // feature detection // use previousElementSibling where available, IE &lt;=8 can safely use previousSibling var prop = document.body.previousElementSibling ? 'previousElementSibling' : 'previousSibling'; getElementIndex = function(node) { var i = 1; while (node = node[prop]) { ++i } return i; } </code></pre> <p><strong>Conclusion</strong> </p> <p>Using <code>Array.indexOf()</code> is not supported on IE &lt;= 8 browsers, and the emulation is simply not fast enough; however, it does give 20% performance improvement.</p> <p>Using feature detection and <code>.previousElementSibling</code> yields a 7x improvement (on Chrome), I have yet to test it on IE8.</p>
51,725,339
How to manage signing keystore in Gitlab CI for android
<p>Dear stackoverflow community, once more I turn to you :)</p> <p>I've recently come across the wonder of Gitlab and their very nice bundled CI/CD solution. It works gallantly however, we all need to sign our binaries don't we and I've found no way to upload a key as I would to a Jenkins server for doing this.</p> <p>So, how can I, without checking in my keys and secrets sign my android (actually flutter) application when building a release?</p> <p>From what I see, most people define the build job with signing settings referring to a non-committed key.properties file specifying a local keystore.jks. This works fine when building APKs locally but if I would like to build and archive them as a part of the CI/CD job, how do I?</p> <p>For secret keys, for example the passwords to the keystore itself, I've found that I can simply store them as protected variables but the actual keystore file itself. What can I do about that?</p> <p>Any ideas, suggestions are dearly welcome. Cheers</p> <p>Edit: I apologise for never marking a right answer here and as @IvanP proposed the solution of writing individual values to a file was what I used for a long time. But as @VonC added later, Gitlab now has the capability to data as actual files which simplifies this so I am marking that as the correct answer.</p>
72,341,650
5
3
null
2018-08-07 11:10:36.427 UTC
7
2022-06-20 15:08:30.307 UTC
2022-05-24 00:24:31.177 UTC
null
479,632
null
479,632
null
1
29
android|gitlab|flutter|code-signing|continuous-deployment
12,797
<p>From <a href="https://stackoverflow.com/users/1407267/ivanp">IvanP</a>'s <a href="https://stackoverflow.com/a/53434270">answer</a>:</p> <blockquote> <p>Usually I store keystore file (as base64 string), alias and passwords to Gitlab's secrets variables.</p> </blockquote> <p>That should be easier with <a href="https://about.gitlab.com/releases/2022/05/22/gitlab-15-0-released/#project-level-secure-files-in-open-beta" rel="nofollow noreferrer">GitLab 15.0</a> (May 2022)</p> <blockquote> <h2>Project-level Secure Files in open beta</h2> <p>Previously, it was difficult to use binary files in your CI/CD pipelines because CI/CD variables could only contain text values. This made it difficult to make use of profiles, certificates, keystores, and other secure information, which are important for teams building mobile apps.</p> <p>Today we are releasing Project-level Secure Files in <a href="/handbook/product/gitlab-the-product/#open-beta">open beta</a>. Now you can upload binary files to projects in GitLab, and include those files in CI/CD jobs to be used in the build and release processes as needed. Secure Files are stored outside of version control and are not part of the project repository.</p> <p>Please leave us your feedback about your experience with this feature in the <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/362407" rel="nofollow noreferrer">feedback issue</a>.</p> <p>See <a href="https://docs.gitlab.com/ee/ci/secure_files/" rel="nofollow noreferrer">Documentation</a> and <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/346290" rel="nofollow noreferrer">Issue</a>.</p> </blockquote>
20,797,158
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method
<p>I am trying to convert one application to EntityFrameWork codefirst. My present code is</p> <pre><code> string sFrom ="26/12/2013"; select * FROM Trans where CONVERT(datetime, Date, 105) &gt;= CONVERT(datetime,'" + sFrom + "',105) </code></pre> <p>And i tried </p> <pre><code> DateTime dtFrom = Convert.ToDateTime(sFrom ); TransRepository.Entities.Where(x =&gt;Convert.ToDateTime(x.Date) &gt;= dtFrom) </code></pre> <p>But I got an error like this</p> <blockquote> <p>LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method</p> </blockquote> <p>Please help Thanks in advance</p>
20,797,182
4
2
null
2013-12-27 08:07:09.693 UTC
5
2019-03-14 18:20:26.193 UTC
2014-09-17 11:42:02.973 UTC
null
3,089,494
null
3,089,494
null
1
6
c#|entity-framework|linq-to-entities
42,823
<p>when you do this:</p> <pre><code>TransRepository.Entities.Where(x =&gt;Convert.ToDateTime(x.Date) &gt;= dtFrom) </code></pre> <p>LINQ to Entities cannot translate most .NET Date methods (including the casting you used) into SQL since there is no equivalent SQL. What you need to do is to do below:</p> <pre><code> DateTime dtFrom = Convert.ToDateTime(sFrom ); TransRepository .Entities.ToList()//forces execution .Where(x =&gt;Convert.ToDateTime(x.Date) &gt;= dtFrom) </code></pre> <p>but wait the above query will fetch <strong>entire data</strong>, and perform <code>.Where</code> on it, definitely you don't want that, </p> <p>simple soultion would be <a href="https://stackoverflow.com/questions/7740693/big-issue-in-converting-string-to-datetime-using-linq-to-entities">this</a>, personally, I would have made my Entity field as <code>DateTime</code> and db column as <code>DateTime</code></p> <p>but since, your db/Entity <code>Date</code> field is string, you don't have any other option, other than to change your field in the entity and db to <code>DateTime</code> and then do the comparison</p>
20,800,933
Running karma after installation results in 'karma' is not recognized as an internal or external command
<p>I'm trying to run karma as part as an <em>angular-seed</em> project, after installing karma using</p> <pre><code>npm install -g karma </code></pre> <p>I get:</p> <pre><code>'karma' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>when i'm trying to run test.bat from angular-client\scripts, the content of this file is:</p> <blockquote> <p>set BASE_DIR=%~dp0</p> <p>karma start &quot;%BASE_DIR%..\config\karma.conf.js&quot; %*</p> </blockquote> <p>I also tried to navigate to &quot;\AppData\Roaming\npm\node_modules\karma\bin&quot; and saw karma file, when I'm trying to run it I get again:</p> <blockquote> <p>'karma' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>Any suggestions? If not please suggest how to use jasmine without karma.</p> <p>Thanks.</p>
22,329,409
8
3
null
2013-12-27 12:42:37.73 UTC
15
2017-10-13 02:53:00.677 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
345,944
null
1
110
node.js|terminal|karma-runner
55,651
<p>The command line interface is in a separate package.</p> <p>To install this use: </p> <blockquote> <p>npm install -g karma-cli</p> </blockquote>
3,995,949
How to write Objective-C Blocks inline?
<p>I am trying to implement a binary search using objective-c blocks. I am using the function <code>indexOfObject:inSortedRange:options:usingComparator:</code>. Here is an example.</p> <pre><code>// A pile of data. NSUInteger amount = 900000; // A number to search for. NSNumber* number = [NSNumber numberWithInt:724242]; // Create some array. NSMutableArray* array = [NSMutableArray arrayWithCapacity:amount]; for (NSUInteger i = 0; i &lt; amount; ++i) {; [array addObject:[NSNumber numberWithUnsignedInteger:i]]; } NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate]; // Run binary search. int index1 = [array indexOfObject:number inSortedRange:NSMakeRange(0, [array count]) options:NSBinarySearchingFirstEqual usingComparator:^(id lhs, id rhs) { if ([lhs intValue] &lt; [rhs intValue]) { return (NSComparisonResult)NSOrderedAscending; } else if([lhs intValue] &gt; [rhs intValue]) { return (NSComparisonResult)NSOrderedDescending; } return (NSComparisonResult)NSOrderedSame; }]; NSTimeInterval stop1 = [NSDate timeIntervalSinceReferenceDate]; NSLog(@"Binary: Found index position: %d in %f seconds.", index1, stop1 - start); // Run normal search. int index2 = [array indexOfObject:number]; NSTimeInterval stop2 = [NSDate timeIntervalSinceReferenceDate]; NSLog(@"Normal: Found index position: %d in %f seconds.", index2, stop2 - start); </code></pre> <p>I wonder how I can use an externally defined objective-c block with the aforementioned function. Here are two compare functions.</p> <pre><code>NSComparisonResult compareNSNumber(id lhs, id rhs) { return [lhs intValue] &lt; [rhs intValue] ? NSOrderedAscending : [lhs intValue] &gt; [rhs intValue] ? NSOrderedDescending : NSOrderedSame; } NSComparisonResult compareInt(int lhs, int rhs) { return lhs &lt; rhs ? NSOrderedAscending : lhs &gt; rhs ? NSOrderedDescending : NSOrderedSame; } </code></pre> <p>Those are written in reference to the following declarations which can be found in <code>NSObjCRuntime.h</code>.</p> <pre><code>enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending}; typedef NSInteger NSComparisonResult; typedef NSComparisonResult (^NSComparator)(id obj1, id obj2); </code></pre>
4,709,829
2
0
null
2010-10-22 10:30:47.283 UTC
10
2011-10-10 14:27:34.363 UTC
null
null
null
null
356,895
null
1
7
objective-c|compare|binary-search|objective-c-blocks
9,836
<p>You can define a block as a global variable to get an effect similar to functions.</p> <pre><code>NSComparisonResult (^globalBlock)(id,id) = ^(id lhs, id rhs) { if([lhs intValue] &lt; [rhs intValue]) { return (NSComparisonResult)NSOrderedAscending; } else if([lhs intValue] &gt; [rhs intValue]) { return (NSComparisonResult)NSOrderedDescending; } return (NSComparisonResult)NSOrderedSame; }; </code></pre> <p>Then, in the method doing the comparison:</p> <pre><code>int index1 = [array indexOfObject:number inSortedRange:NSMakeRange(0, [array count]) options:NSBinarySearchingFirstEqual usingComparator:globalBlock]; </code></pre> <p>To put the block in a header, for external use:</p> <pre><code>NSComparisonResult (^globalBlock)(id,id); </code></pre>
3,545,057
Numpy for R user?
<p>long-time R and Python user here. I use R for my daily data analysis and Python for tasks heavier on text processing and shell-scripting. I am working with increasingly large data sets, and these files are often in binary or text files when I get them. The type of things I do normally is to apply statistical/machine learning algorithms and create statistical graphics in most cases. I use R with SQLite sometimes and write C for iteration-intensive tasks; before looking into Hadoop, I am considering investing some time in NumPy/Scipy because I've heard it has better memory management [and the transition to Numpy/Scipy for one with my background seems not that big] - I wonder if anyone has experience using the two and could comment on the improvements in this area, and if there are idioms in Numpy that deal with this issue. (I'm also aware of Rpy2 but wondering if Numpy/Scipy can handle most of my needs). Thanks -</p>
3,548,160
2
1
null
2010-08-23 06:01:55.673 UTC
9
2013-05-12 21:42:59.287 UTC
2013-05-12 21:42:59.287 UTC
null
832,621
null
143,476
null
1
10
python|r|numpy|scipy
17,967
<p>R's strength when looking for an environment to do machine learning and statistics is most certainly the diversity of its libraries. To my knowledge, SciPy + SciKits cannot be a replacement for CRAN.</p> <p>Regarding memory usage, R is using a pass-by-value paradigm while Python is using pass-by-reference. Pass-by-value can lead to more "intuitive" code, pass-by-reference can help optimize memory usage. Numpy also allows to have "views" on arrays (kind of subarrays without a copy being made).</p> <p>Regarding speed, pure Python is faster than pure R for accessing individual elements in an array, but this advantage disappears when dealing with numpy arrays (<a href="http://rpy.sourceforge.net/rpy2/doc-2.2/html/performances.html#a-simple-benchmark" rel="noreferrer">benchmark</a>). Fortunately, Cython lets one get serious speed improvements easily.</p> <p>If working with Big Data, I find the support for storage-based arrays better with Python (HDF5).</p> <p>I am not sure you should ditch one for the other but rpy2 can help you explore your options about a possible transition (arrays can be shuttled between R and Numpy without a copy being made).</p>
3,748,592
What are "n+k patterns" and why are they banned from Haskell 2010?
<p>When reading <a href="http://en.wikipedia.org/wiki/Haskell_(programming_language)#Haskell_2010" rel="noreferrer">Wikipedia's entry on Haskell 2010</a> I stumbled across this:</p> <pre><code>-- using only prefix notation and n+k-patterns (no longer allowed in Haskell 2010) factorial 0 = 1 factorial (n+1) = (*) (n+1) (factorial n) </code></pre> <p>What do they mean by "n+k patterns"? I guess it's the second line, but I don't get what might be wrong with it. Could anyone explain what is the issue there? Why isn't these n + k patterns more allowed in Haskell 2010?</p>
3,748,700
2
2
null
2010-09-20 03:44:42.933 UTC
16
2017-03-21 16:52:56.163 UTC
2017-03-21 16:52:56.163 UTC
null
3,924,118
null
130,758
null
1
67
haskell|functional-programming
10,153
<p>What are n+k patterns? Take a gander at this:</p> <pre><code>$ ghci GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Prelude&gt; let f 0 = 0 ; f (n+5) = n Prelude&gt; :t f f :: (Integral t) =&gt; t -&gt; t Prelude&gt; f 0 0 Prelude&gt; f 1 *** Exception: &lt;interactive&gt;:1:4-24: Non-exhaustive patterns in function f Prelude&gt; f 2 *** Exception: &lt;interactive&gt;:1:4-24: Non-exhaustive patterns in function f Prelude&gt; f 3 *** Exception: &lt;interactive&gt;:1:4-24: Non-exhaustive patterns in function f Prelude&gt; f 4 *** Exception: &lt;interactive&gt;:1:4-24: Non-exhaustive patterns in function f Prelude&gt; f 5 0 Prelude&gt; f 6 1 </code></pre> <p>They're basically an extremely special case on pattern matching which only work on numbers and which do ... well, let's just be polite and call it "unexpected things" to those numbers.</p> <p>Here I have a function <code>f</code> which has two clauses. The first clause matches <code>0</code> and only <code>0</code>. The second clause matches any value of type Integral whose value is 5 or greater. The bound name (<code>n</code>, in this case) has a value equal to the number you passed in minus 5. As to why they've been removed from Haskell 2010, I hope you can see the reason now with just a bit of thinking. (Hint: consider the "principle of least surprise" and how it may or may not apply here.)</p> <hr> <p><em>Edited to add:</em></p> <p>A natural question to arise now that these constructs are forbidden is "what do you use to replace them?"</p> <pre><code>$ ghci GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Prelude&gt; let f 0 = 0 ; f n | n &gt;= 5 = n - 5 Prelude&gt; :t f f :: (Num t, Ord t) =&gt; t -&gt; t Prelude&gt; f 0 0 Prelude&gt; f 1 *** Exception: &lt;interactive&gt;:1:4-33: Non-exhaustive patterns in function f Prelude&gt; f 2 *** Exception: &lt;interactive&gt;:1:4-33: Non-exhaustive patterns in function f Prelude&gt; f 3 *** Exception: &lt;interactive&gt;:1:4-33: Non-exhaustive patterns in function f Prelude&gt; f 4 *** Exception: &lt;interactive&gt;:1:4-33: Non-exhaustive patterns in function f Prelude&gt; f 5 0 Prelude&gt; f 6 1 </code></pre> <p>You'll notice from the type statements that these are not precisely equal, but the use of a guard is "equal enough". The use of the <code>n-5</code> in the expression could get tedious and error-prone in any code that uses it in more than one place. The answer would be to use a <code>where</code> clause along the lines of this:</p> <pre><code>Prelude&gt; let f 0 = 0 ; f n | n &gt;= 5 = n' where n' = n - 5 Prelude&gt; :t f f :: (Num t, Ord t) =&gt; t -&gt; t Prelude&gt; f 0 0 Prelude&gt; f 5 0 Prelude&gt; f 6 1 </code></pre> <p>The <code>where</code> clause lets you use the calculated expression in multiple places without risk of mistyping. There is still the annoyance of having to edit the border value (5 in this case) in two separate locations in the function definition, but personally I feel this is a small price to pay for the increase in cognitive comprehension.</p> <hr> <p><em>Further edited to add:</em></p> <p>If you prefer <code>let</code> expressions over <code>where</code> clauses, this is an alternative:</p> <pre><code>Prelude&gt; let f 0 = 0 ; f n | n &gt;= 5 = let n' = n - 5 in n' Prelude&gt; :t f f :: (Num t, Ord t) =&gt; t -&gt; t Prelude&gt; f 0 0 Prelude&gt; f 5 0 </code></pre> <p>And that's it. I'm really done now.</p>
16,214,517
Installing MariaDB - Unmet dependencies, mariadb-server-5.5
<p>I'm attempting to install MariaDB on Ubuntu 12.04 LTS.</p> <p>I've followed the instructions provided at <a href="https://askubuntu.com/questions/64772/how-to-install-mariadb">https://askubuntu.com/questions/64772/how-to-install-mariadb</a> and from MariaDB.org that appear when you choose the download.</p> <p>The last step is <code>sudo apt-get install mariadb-server</code> which returns:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: mariadb-server : Depends: mariadb-server-5.5 but it is not going to be installed E: Unable to correct problems, you have held broken packages. </code></pre> <p>The dependency issue is an acknowledge issue (<a href="https://mariadb.atlassian.net/browse/MDEV-3882" rel="noreferrer">https://mariadb.atlassian.net/browse/MDEV-3882</a>) but I believe the broken package prevents me from working around this.</p> <p>If I try to install libmariadbclient18 I get the following:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libmariadbclient18 : Depends: libmysqlclient18 (= 5.5.30-mariadb1~precise) but 5.5.31-0ubuntu0.12.04.1 is to be installed E: Unable to correct problems, you have held broken packages. </code></pre> <p>I've tried to correct the broken package using <code>sudo apt-get install -f</code>, but I still can't install mariadb-server or libmariadbclient18.</p>
16,232,587
8
1
null
2013-04-25 12:16:49.28 UTC
9
2016-07-12 05:25:06.153 UTC
2017-04-13 12:22:39.283 UTC
null
-1
null
2,045,006
null
1
29
ubuntu|apt-get|mariadb
32,428
<pre><code>sudo apt-get install libmysqlclient18=5.5.30-mariadb1~precise mysql-common=5.5.30-mariadb1~precise sudo apt-get install mariadb-server </code></pre> <p>The first one reverts the two mysql libs that were bumped ubuntu side to the older mariadb ones. The second one can then proceed normally.</p> <p>Packages got removed because something like <code>apt-get dist-upgrade</code> was run. The GUI actually warns you that something's amiss.</p> <p>To prevent this issue from cropping up again, tell apt to <a href="https://kb.askmonty.org/en/installing-mariadb-deb-files/#pinning-the-mariadb-repository" rel="noreferrer">favor the MariaDB repo via pinning</a> by creating a file in <code>/etc/apt/preferences.d</code>:</p> <pre><code>$ cat /etc/apt/preferences.d/MariaDB.pref Package: * Pin: origin &lt;mirror-domain&gt; Pin-Priority: 1000 </code></pre> <p>Also, be sure to install <code>libmariadbclient-dev</code> if you need to compile anything (like Ruby gems).</p>
16,568,986
What happens when you call data() on a std::vector<bool>?
<p>C++11 has implemented <code>data()</code> member function on <code>std::vector</code>, which gives you a pointer to the memory array. Does this mean the template specialization <code>std::vector&lt;bool&gt;</code> have this member as well? Since this specialization doesn't store the data in terms of <code>bool *</code>, what kind of behavior can you expect from calling <code>data()</code> ?</p>
16,569,085
4
0
null
2013-05-15 15:20:37.103 UTC
2
2013-05-15 21:40:07.93 UTC
null
null
null
null
1,821,831
null
1
38
c++|c++11|stl
5,072
<p>This <a href="http://www.cplusplus.com/reference/vector/vector-bool/">page</a> documenting the class explicitely indicates that the specialization does not provide this method.</p> <blockquote> <p>The specialization has the same member functions as the unspecialized vector, except data, emplace, and emplace_back, that are not present in this specialization.</p> </blockquote> <p>This <a href="http://en.cppreference.com/w/cpp/container/vector_bool">other page</a> as well as §23.3.7 of the <a href="https://github.com/cplusplus/draft/blob/master/papers/N3376.pdf">C++ specifications</a> do confirm it. </p>
16,047,344
Can a web browser use MQTT?
<p>We are looking at using MQTT as the messaging protocol on a new device we're building. We'd also like a web interface for the device. Does anyone know if you can implement a browser client app (without additional plugins) that talks MQTT?</p>
16,048,668
8
4
null
2013-04-16 21:22:11.31 UTC
15
2017-09-13 13:34:53.883 UTC
null
null
null
null
258,526
null
1
39
mqtt
54,181
<p>Yes, as mentioned in Steve-o's comment MQTT via websockets is very possible.</p> <p>There are 2 options at the moment</p> <ol> <li>IBM's MQ 7.5 comes with websockets support, you can find details <a href="http://www-01.ibm.com/software/websphere/subscriptionandsupport/compare-mq-versions.html" rel="noreferrer">here</a>.</li> <li>The Mosquitto broker has a javascript client with an example running <a href="http://test.mosquitto.org/ws.html" rel="noreferrer">here</a>.</li> </ol> <p>To answer your second question lighttpd has a websockets module that can be used to do forwarding to an existing broker with details <a href="https://github.com/nori0428/mod_websocket" rel="noreferrer">here</a>.</p> <p>I've not been able to find anything for Apache that doesn't need you to write your own library to do the forwarding.</p>
55,384,102
AWS Lambda Timezone
<p>I've been searching for a while and can't find a definitive answer on that or any oficial documentation from AWS.</p> <p>I have a Lambda function on which I need to get the current date according to my timezone, but I'm unsure on which premisses I may rely to do that, and as this is a critical app, I can't simply rely on a single test or empirical result.</p> <p>I would expect that lambda functions follow the timezone of the AWS region that they are hosted in OR a unique timezone for any GMT 0, but couldn't confirm it anywhere.</p> <p>Could anyone please clarify how this works and if possible also point to any official documentation about that? Also, any special concerns related to daylight saving time?</p> <p>My Lambda function is written on NodeJS and what I've been doing locally (on my machine) to retrieve the current date time is using <code>new Date()</code>.</p>
55,384,379
2
4
null
2019-03-27 18:20:54.003 UTC
1
2022-08-03 06:24:39.62 UTC
null
null
null
null
6,481,438
null
1
25
node.js|amazon-web-services|aws-lambda
39,242
<p>Lambda time using the date object will <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html" rel="noreferrer">return a date in UTC unix time</a></p> <blockquote> <p>TZ – The environment's time zone (UTC).</p> </blockquote> <p>To get a time in a specific timezone you can use <a href="https://www.npmjs.com/package/moment-timezone" rel="noreferrer">moment-timezone</a>.</p> <p>Using Javascript Date().now():</p> <pre><code>var moment = require(&quot;moment-timezone&quot;); moment(Date().now()).tz(&quot;America/Los_Angeles&quot;).format(&quot;DD-MM-YYYY&quot;); </code></pre> <p>or using new Date():</p> <pre><code>var moment = require(&quot;moment-timezone&quot;); var date = new Date(); moment(date.getTime()).tz(&quot;America/Los_Angeles&quot;).format(&quot;DD-MM-YYYY&quot;); </code></pre> <p>You can <a href="https://momentjs.com/docs/" rel="noreferrer">change the moment .js format to whatever you require</a></p> <p>Regarding daylight savings time, it is possible to detect it using <a href="https://stackoverflow.com/a/21918576/6481438">isDST() method</a>.</p>
15,234,879
handle "Another version of this product is already installed. Installation of this version cannot continue..."
<p>I have 32-bit and 64-bit versions of my installer which have (nearly) the exact same code &amp; custom action sequence (there are only minor differences which are not relevant to this issue)</p> <p>I want my installer to detect whether it has already been previously installed and in this case run my own code instead of showing the default Windows Installer error:</p> <blockquote> <p>Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.</p> </blockquote> <p>My 32-bit installer works perfectly fine in that it runs my custom code if I run the installer when the product is already installed, but the same code &amp; custom action in my 64-bit installer does NOT work correctly and always shows the unwanted error msg.</p> <p>CheckPreviousVersion is the first function called as a Custom Action during the UI sequence, I've tried putting it in different spots like after InstallValidate but nothing works.</p> <p>I've examined the verbose log file but I can't find anything that might explain this behavior, here is a part of the log:</p> <pre><code>=== Verbose logging started: 05/03/2013 16:27:20 Build type: SHIP UNICODE 5.00.7601.00 Calling process: C:\Windows\system32\msiexec.exe === MSI (c) (0C:94) [16:27:20:331]: Machine policy value 'Debug' is 0 MSI (c) (0C:94) [16:27:20:331]: ******* RunEngine: ******* Product: foo.msi ******* Action: ******* CommandLine: ********** MSI (c) (0C:94) [16:27:21:546]: Machine policy value 'DisableUserInstalls' is 0 MSI (c) (0C:94) [16:27:21:557]: SOFTWARE RESTRICTION POLICY: Verifying package --&gt; 'C:\Builds\.msi' against software restriction policy MSI (c) (0C:94) [16:27:21:557]: Note: 1: 2262 2: DigitalSignature 3: -2147287038 MSI (c) (0C:94) [16:27:21:557]: SOFTWARE RESTRICTION POLICY: C:\Builds\.msi is not digitally signed MSI (c) (0C:94) [16:27:21:558]: SOFTWARE RESTRICTION POLICY: C:\Builds.msi is permitted to run at the 'unrestricted' authorization level. MSI (c) (0C:94) [16:27:21:584]: Cloaking enabled. MSI (c) (0C:94) [16:27:21:584]: Attempting to enable all disabled privileges before calling Install on Server MSI (c) (0C:94) [16:27:21:586]: End dialog not enabled MSI (c) (0C:94) [16:27:21:586]: Original package ==&gt; C:\Builds\....msi MSI (c) (0C:94) [16:27:21:586]: Package we're running from ==&gt; C:\Builds\.....msi MSI (c) (0C:94) [16:27:21:589]: APPCOMPAT: Uninstall Flags override found. MSI (c) (0C:94) [16:27:21:589]: APPCOMPAT: Uninstall VersionNT override found. MSI (c) (0C:94) [16:27:21:589]: APPCOMPAT: Uninstall ServicePackLevel override found. MSI (c) (0C:94) [16:27:21:589]: APPCOMPAT: looking for appcompat database entry with ProductCode '{B8CBA92E-2140-48AB-B4EA-A4C3FF10295B}'. MSI (c) (0C:94) [16:27:21:589]: APPCOMPAT: no matching ProductCode found in database. MSI (c) (0C:94) [16:27:21:599]: MSCOREE not loaded loading copy from system32 MSI (c) (0C:94) [16:27:21:608]: Machine policy value 'DisablePatch' is 0 MSI (c) (0C:94) [16:27:21:608]: Machine policy value 'AllowLockdownPatch' is 0 MSI (c) (0C:94) [16:27:21:608]: Machine policy value 'DisableLUAPatching' is 0 MSI (c) (0C:94) [16:27:21:608]: Machine policy value 'DisableFlyWeightPatching' is 0 MSI (c) (0C:94) [16:27:21:609]: APPCOMPAT: looking for appcompat database entry with ProductCode '{}'. MSI (c) (0C:94) [16:27:21:609]: APPCOMPAT: no matching ProductCode found in database. MSI (c) (0C:94) [16:27:21:609]: Transforms are not secure. MSI (c) (0C:94) [16:27:21:609]: PROPERTY CHANGE: Adding MsiLogFileLocation property. Its value is 'C:\Builds\Angoss\Products\Workstation\single-exec\INSTALL64.LOG'. MSI (c) (0C:94) [16:27:21:609]: Command Line: CURRENTDIRECTORY=C:\Builds\Angoss\Products\Workstation\single-exec CLIENTUILEVEL=0 CLIENTPROCESSID=7948 MSI (c) (0C:94) [16:27:21:609]: PROPERTY CHANGE: Adding PackageCode property. Its value is '{}'. MSI (c) (0C:94) [16:27:21:609]: Product Code passed to Engine.Initialize: '' MSI (c) (0C:94) [16:27:21:609]: Product Code from property table before transforms: '{}' MSI (c) (0C:94) [16:27:21:609]: Product Code from property table after transforms: '{}' MSI (c) (0C:94) [16:27:21:609]: Product registered: entering maintenance mode MSI (c) (0C:94) [16:27:21:609]: Determined that existing product (either this product or the product being upgraded with a patch) is installed per-machine. MSI (c) (0C:94) [16:27:21:609]: PROPERTY CHANGE: Adding ProductState property. Its value is '5'. MSI (c) (0C:94) [16:27:21:609]: PROPERTY CHANGE: Adding ProductToBeRegistered property. Its value is '1'. MSI (c) (0C:94) [16:27:21:609]: Entering CMsiConfigurationManager::SetLastUsedSource. MSI (c) (0C:94) [16:27:21:609]: Specifed source is already in a list. MSI (c) (0C:94) [16:27:21:609]: User policy value 'SearchOrder' is 'nmu' MSI (c) (0C:94) [16:27:21:609]: Machine policy value 'DisableBrowse' is 0 MSI (c) (0C:94) [16:27:21:609]: Machine policy value 'AllowLockdownBrowse' is 0 MSI (c) (0C:94) [16:27:21:609]: Adding new sources is allowed. MSI (c) (0C:94) [16:27:21:609]: PROPERTY CHANGE: Adding PackagecodeChanging property. Its value is '1'. Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel. </code></pre>
15,246,453
2
0
null
2013-03-05 21:52:37.953 UTC
null
2017-10-22 18:48:51.9 UTC
null
null
null
null
1,944,239
null
1
6
installation|windows-installer|installshield|installshield-2011
48,167
<p>This message usually appears only during development phases, not on the end-user machine. The message appears because you modify only the resources from the package and rebuild it, <strong>without increasing the version number</strong>, so Windows Installer sees there is a package with the same product code and name on the machine, but with a different package code.</p> <p>Your users will never get this message because I assume you will increase the version number when releasing the package. This is also based on the name of your function i.e. "CheckPreviousVersion".</p> <p>If you want a custom message to appear if you found an older version on the machine make sure you first have the old version installed, you currently have the latest version installed, but using another previously built package (i.e. different package code).</p>
15,305,527
Javascript - User input through HTML input tag to set a Javascript variable?
<p>I want there to be a textbox on my screen(like the one i'm typing in now) that you can type in then click a submit button and it sends whatever you typed in the box to javascript and javascript prints it out.Here is my code This is the part that works.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;input type="text" id="userInput"=&gt;give me input&lt;/input&gt; &lt;button onclick="test()"&gt;Submit&lt;/button&gt; &lt;script&gt; function test() { var userInput = document.getElementById("userInput").value; document.write(userInput); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>OK so that's nice, but lets say I want input from that textbox and button while I'm already in a function and don't want to restart the function?</p> <p>Thanks, Jake</p>
15,305,675
4
5
null
2013-03-09 00:09:42.313 UTC
7
2019-01-15 14:28:07.483 UTC
2013-03-09 00:20:14.23 UTC
null
850,833
null
1,836,262
null
1
7
javascript|html|input|user-input
133,124
<p>When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:</p> <ul> <li>Use <code>var foo = prompt("Give me input");</code>, which will give you the string that the user enters into a popup box (or <code>null</code> if they cancel it)</li> <li>Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.</li> </ul>
17,544,371
Provide Print functionality in ASP.NET MVC 4
<p>I have a view with HTML tables, filled with information that I want to print in ASP.NET MVC 4 and C#.</p> <p>I don't know the actual code that prints the document, any help will be appreciated</p>
17,544,549
1
1
null
2013-07-09 09:13:44.443 UTC
2
2020-07-08 14:09:24.26 UTC
2020-07-08 14:09:24.26 UTC
null
442,624
null
2,553,267
null
1
8
c#|asp.net-mvc-4
57,696
<p>Well you have two choices </p> <ol> <li><p>Either use JS</p> <p><code>&lt;a href="javascript:window.print()"&gt;Click to Print This Page&lt;/a&gt;</code></p></li> <li><p><a href="https://www.simple-talk.com/dotnet/asp.net/asp.net-mvc-action-results-and-pdf-content/">Or print to a PDF using Action Result in MVC</a></p></li> </ol> <p>For the JS option you will want to build a <a href="http://www.webcredible.co.uk/user-friendly-resources/css/print-stylesheet.shtml">print css</a> file so as to best render the page during printing, also hide some element that you don't need to appear - menus for example.</p>
17,396,870
actionbar menu item onclick?
<p>I have an action bar that puts everything in a menu in the top right, which the user clicks and the menu options open up. </p> <p>I inflate the action bar menu with this on each activity I use it:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main2, menu); return true; } </code></pre> <p>And my xml for main2.xml is:</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_searchHome" android:orderInCategory="100" android:showAsAction="never" android:title="Seach"/&gt; &lt;/menu&gt; </code></pre> <p>My question is do I put an onclick in the item in the xml and if so where do I put the onclick method it calls? Do I need to put it in every activity I launch this action bar in?</p>
17,396,896
2
2
null
2013-07-01 02:56:15.247 UTC
4
2016-10-18 00:10:46.927 UTC
null
null
null
null
1,637,374
null
1
12
android|android-activity|android-actionbar
46,465
<p>If you add an onClick attribute on your menu item like this:</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_searchHome" android:orderInCategory="100" android:showAsAction="never" android:onClick="doThis" android:title="Seach"/&gt; &lt;/menu&gt; </code></pre> <p>Then in your activity:</p> <pre><code>public void doThis(MenuItem item){ Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show(); } </code></pre> <p><strong>Note:</strong></p> <p>ActionBarSherlock is <strong>deprecated</strong>. Unless you are developing an app for Android 4.0 or older, please don't use it. But if you are using the library, you will have to import</p> <p><code>import com.actionbarsherlock.view.MenuItem;</code> </p> <p><em>and not</em> </p> <p><code>import com.android.view.MenuItem;</code></p> <p>In addition, you could do something like this: <a href="https://stackoverflow.com/questions/10472443/actionbar-sherlock-menu-item-onclick">ActionBar Sherlock Menu Item OnClick</a></p> <p>which @adneal mentions.</p>
37,529,040
How do I solve a "view not found" exception in asp.net core mvc project
<p>I'm trying to create a ASP.NET Core MVC test app running on OSX using VS Code. I'm getting a 'view not found' exception when accessing the default Home/index (or any other views I tried). </p> <p>This is the Startup configuration</p> <pre><code> public void Configure(IApplicationBuilder app) { // use for development app.UseDeveloperExceptionPage(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc( routes =&gt; { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}" ); }); } </code></pre> <p>And I have the view defined in <code>Views/Home/index.cshtml</code>, and I have the following packages included on project.json</p> <pre><code>"dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0-rc2-3002702", "type": "platform" }, "Microsoft.AspNetCore.Razor.Tools" : "1.0.0-preview1-final", "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final", "Microsoft.AspNetCore.Routing": "1.0.0-rc2-final" }, </code></pre> <p>And finally, this is the exception I get.</p> <pre><code>System.InvalidOperationException: The view 'Index' was not found. The following locations were searched: /Views/Home/Index.cshtml /Views/Shared/Index.cshtml at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations) at Microsoft.AspNetCore.Mvc.ViewResult.&lt;ExecuteResultAsync&gt;d__26.MoveNext() --- End of stack trace from previous location where exception was thrown --- ... </code></pre> <p>Any suggestions of what I might be missing ?</p>
37,530,670
25
3
null
2016-05-30 15:16:49.91 UTC
7
2022-07-08 07:14:27.023 UTC
2021-10-16 21:57:45.02 UTC
null
819,887
null
1,779,348
null
1
51
c#|asp.net-core
82,240
<p>I found this missing piece. I ended up creating a ASP.NET Core project in VS2015 and then compare for differences. It turns out I was missing <code>.UseContentRoot(Directory.GetCurrentDirectory())</code> from <code>WebHostBuilder</code> in main.</p> <p>After adding this:</p> <pre><code>public static void Main(string[] args) { new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup&lt;Startup&gt;() .Build() .Run(); } </code></pre> <p>I then got an exception regarding missing <code>preserveCompilationContext</code>. Once added in project.json my view shows correct.</p> <pre><code>"buildOptions": { "preserveCompilationContext": true, "emitEntryPoint": true }, </code></pre>
27,146,966
Xcode shows warning after adding App Groups (Add the "App Groups" entitlement to your App ID)
<p>After I added an App Group in Xcode it shows a warning:</p> <blockquote> <p>Add the "App Groups" entitlement to your App ID<br> Add the "App Groups containers" entitlement to your App ID </p> </blockquote> <p>Before the warning there was a loading spinner like this:</p> <p><img src="https://i.stack.imgur.com/Qa0Zb.png" alt="Adding the &quot;App Groups&quot; entitlement to your App ID..."></p> <p>after it finished the loading I got the following warnings:</p> <p><img src="https://i.stack.imgur.com/7zd1P.png" alt="remaining warnings"></p> <p>What can I do to correct the two wrong steps? If I'm right it is already added to my App ID.</p>
27,149,502
6
7
null
2014-11-26 10:39:19.587 UTC
5
2019-07-10 01:27:12.333 UTC
2019-07-10 01:27:12.333 UTC
null
1,265,393
null
1,894,953
null
1
37
ios|xcode|ios-app-group
28,184
<p>I faced the same issue, and in my case my apple id did not have the permission to add the "App Group".</p> <p>If your account's type is "Member", not "Agent", then you need your Agent/Admin who has the main development account to add the "App Group" for you.</p>
17,583,439
"bin/rails: No such file or directory" w/ Ruby 2 & Rails 4 on Heroku
<p>While following the Rails 4 <strong>Beta</strong> version of Michael Hartl's <em><a href="http://ruby.railstutorial.org/ruby-on-rails-tutorial-book?version=4.0#top" rel="noreferrer">Ruby on Rails Tutorial</a></em>, my app fails to start on Heroku, but runs fine locally with <code>bundle exec rails server</code>. Checking <code>heroku logs -t</code> reveals the following error:</p> <pre><code>$ heroku[web.1]: State changed from crashed to starting $ heroku[web.1]: Starting process with command `bin/rails server -p 33847 -e $RAILS_ENV` $ app[web.1]: bash: bin/rails: No such file or directory $ heroku[web.1]: Process exited with status 127 $ heroku[web.1]: State changed from starting to crashed $ heroku[web.1]: Error R99 (Platform error) -&gt; Failed to launch the dyno within 10 seconds $ heroku[web.1]: Stopping process with SIGKILL </code></pre> <p>If I <code>heroku run bash</code> and check the <code>bin</code> directory, I can see that there is <strong>not</strong> a <code>rails</code> executable:</p> <pre><code>~$ ls bin erb gem irb node rdoc ri ruby testrb </code></pre> <p>What have I done wrong? I followed the tutorial exactly.</p>
17,583,440
8
0
null
2013-07-11 01:04:07.103 UTC
14
2021-12-15 05:54:02.057 UTC
null
null
null
null
311,304
null
1
59
ruby-on-rails|ruby|heroku|ruby-on-rails-4|ruby-2.0
31,358
<p>After struggling with this for a bit, I noticed that my Rails 4 project had a <code>/bin</code> directory, unlike some older Rails 3 projects I had cloned. <code>/bin</code> contains 3 files, <code>bundle</code>, <code>rails</code>, and <code>rake</code>, but these weren't making it to Heroku because I had <code>bin</code> in my global <code>.gitignore</code> file. </p> <p>This is a pretty common ignore rule if you work with Git and other languages (Java, etc.), so to fix this:</p> <ol> <li>Remove <code>bin</code> from <code>~/.gitignore</code></li> <li>Run <code>bundle install</code></li> <li>Commit your changes with <code>git add .</code> and <code>git commit -m "Add bin back"</code></li> <li>Push your changes to Heroku with <code>git push heroku master</code></li> </ol>
17,633,422
psql: FATAL: database "<user>" does not exist
<p>I'm using the PostgreSql app for mac (<a href="http://postgresapp.com/" rel="noreferrer">http://postgresapp.com/</a>). I've used it in the past on other machines but it's giving me some trouble when installing on my macbook. I've installed the application and I ran:</p> <pre><code>psql -h localhost </code></pre> <p>It returns:</p> <pre><code>psql: FATAL: database "&lt;user&gt;" does not exist </code></pre> <p>It seems I can't even run the console to create the database that it's attempting to find. The same thing happens when I just run:</p> <pre><code>psql </code></pre> <p>or if I launch psql from the application drop down menu:</p> <p>Machine stats:</p> <ul> <li><p>OSX 10.8.4</p></li> <li><p>psql (PostgreSQL) 9.2.4</p></li> </ul> <p>Any help is appreciated. </p> <p>I've also attempted to install PostgreSql via homebrew and I'm getting the same issue. I've also read the applications documentation page that states: </p> <blockquote> <p>When Postgres.app first starts up, it creates the $USER database, which is the default database for psql when none is specified. The default user is $USER, with no password.</p> </blockquote> <p>So it would seem the application is not creating $USER however I've installed->uninstalled-reinstalled several times now so it must be something with my machine.</p> <p>I found the answer but I'm not sure exactly how it works as the user who answered on this thread -> <a href="https://stackoverflow.com/questions/13515834/getting-postgresql-running-in-mac-database-postgres-does-not-exist">Getting Postgresql Running In Mac: Database &quot;postgres&quot; does not exist</a> didn't follow up. I used the following command to get psql to open: </p> <pre><code>psql -d template1 </code></pre> <p><em>I'll leave this one unanswered until someone can provide an explanation for why this works.</em></p>
17,936,043
23
5
null
2013-07-13 19:18:24.4 UTC
277
2022-05-18 08:34:53.103 UTC
2017-05-23 12:34:53.63 UTC
null
-1
null
1,254,737
null
1
934
postgresql|psql
526,216
<p>It appears that your package manager failed to create the database named $user for you. The reason that</p> <pre><code>psql -d template1 </code></pre> <p>works for you is that template1 is a database created by postgres itself, and is present on all installations. You are apparently able to log in to template1, so you must have some rights assigned to you by the database. Try this at a shell prompt:</p> <pre><code>createdb </code></pre> <p>and then see if you can log in again with </p> <pre><code>psql -h localhost </code></pre> <p>This will simply create a database for your login user, which I think is what you are looking for. If createdb fails, then you don't have enough rights to make your own database, and you will have to figure out how to fix the homebrew package.</p>
30,323,439
Raising elements of a list to a power
<p>How can I raise the numbers in list to a certain power?</p>
30,323,523
9
3
null
2015-05-19 10:45:59.317 UTC
2
2021-06-09 07:00:27.363 UTC
2015-05-19 11:01:15.39 UTC
null
4,908,068
null
4,908,068
null
1
14
python|list|python-3.x
45,724
<p>Use list comprehension:</p> <pre><code>def power(my_list): return [ x**3 for x in my_list ] </code></pre> <p><a href="https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions</a></p>
36,801,831
ASP.Net Core MVC Dependency Injection not working
<p>I am trying to inject a interface into to my HomeController and I am getting this error:</p> <blockquote> <p>InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate </p> </blockquote> <p>My Startup class is as follows:</p> <pre><code>public Startup(IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddEnvironmentVariables() .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddEntityFramework() .AddSqlServer() .AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options .UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;() .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;() .AddDefaultTokenProviders(); services.AddMvc(); services.AddSingleton(provider =&gt; Configuration); // Add application services. services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;(); services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;(); } public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); try { using (var serviceScope = app.ApplicationServices .GetRequiredService&lt;IServiceScopeFactory&gt;() .CreateScope()) { serviceScope.ServiceProvider .GetService&lt;ApplicationDbContext&gt;() .Database.Migrate(); } } catch { } } app.UseIISPlatformHandler(options =&gt; options.AuthenticationDescriptions.Clear()); app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes =&gt; { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run((async (context) =&gt; { await context.Response.WriteAsync("Error"); })); } </code></pre> <p>and my HomeController constructor is:</p> <pre><code>public HomeController(IConfiguration configuration, IEmailSender mailService) { _mailService = mailService; _to = configuration["emailAddress.Support"]; } </code></pre> <p>Please tell me where I am mistaken.</p> <blockquote> <p>Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)</p> </blockquote>
36,801,893
3
2
null
2016-04-22 19:24:43.547 UTC
9
2018-08-29 10:55:20.24 UTC
2018-08-29 10:55:20.24 UTC
null
2,869,093
null
5,197,739
null
1
23
asp.net-mvc|dependency-injection|asp.net-core
35,307
<p>Try injecting it as an <code>IConfigurationRoot</code> instead of <code>IConfiguration</code>:</p> <pre><code> public HomeController(IConfigurationRoot configuration , IEmailSender mailService) { _mailService = mailService; _to = configuration["emailAddress.Support"]; } </code></pre> <p>In this case, the line</p> <pre><code>services.AddSingleton(provider =&gt; Configuration); </code></pre> <p>is equivalent to </p> <pre><code>services.AddSingleton&lt;IConfigurationRoot&gt;(provider =&gt; Configuration); </code></pre> <p>because the <code>Configuration</code> property on the class is declared as such, and injection will be done by matching whatever type it was registered as. We can replicate this pretty easily, which might make it clearer:</p> <pre><code>public interface IParent { } public interface IChild : IParent { } public class ConfigurationTester : IChild { } </code></pre> <pre><code>public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); IChild example = new ConfigurationTester(); services.AddSingleton(provider =&gt; example); } </code></pre> <pre><code>public class HomeController : Controller { public HomeController(IParent configuration) { // this will blow up } } </code></pre> <h2>However</h2> <p>As stephen.vakil mentioned in the comments, it would be better to load your configuration file into a class, and then inject that class into controllers as needed. That would look something like this:</p> <pre><code>services.Configure&lt;AppSettings&gt;(Configuration.GetSection("AppSettings")); </code></pre> <p>You can grab these configurations with the <code>IOptions</code> interface:</p> <pre><code>public HomeController(IOptions&lt;AppSettings&gt; appSettings) </code></pre>
18,503,607
Best practice to select data using Spring JdbcTemplate
<p>I want to know what is the best practice to select records from a table. I mentioned two methods below from that I want to know which one is best practice to select the data from a table using Spring <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html" rel="noreferrer">JdbcTemplate</a>.</p> <h2>First example</h2> <pre><code>try { String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'"; long id = jdbcTemplate.queryForObject(sql, Long.class); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e); } } </code></pre> <p>This throws the following exception:</p> <blockquote> <p>Expected 1 actual 0 like</p> </blockquote> <p>when table doesn't contain any data. My friend told this is not the best practice to select the data. He suggested that the below mentioned code is the only best practice to select data.</p> <h2>Second example</h2> <pre><code>try { String countQuery = "SELECT COUNT(id) FROM tableName"; int count = jdbcTemplate.queryForInt(countQuery); if (count &gt; 0) { String sql = "SELECT id FROM tableName WHERE column_name = '" + coulmn value + "'"; long id = jdbcTemplate.queryForObject(sql, Long.class); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e); } } </code></pre> <p><br> I'm eager to know the right one or any other best practice.</p>
18,503,994
4
0
null
2013-08-29 06:21:34.777 UTC
12
2019-04-26 18:50:54.113 UTC
2017-08-07 14:39:08.113 UTC
null
814,702
null
2,314,379
null
1
35
java|spring|jdbctemplate
114,020
<p>Definitely the first way is the best practice, because in the second way you are hitting the database twice where you should actually hit it only once. This can cause performance issues.</p> <p>What you need to do is catch the exception <code>EmptyResultDataAccessException</code> and then return null back. Spring JDBC templates throws back an <a href="http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/dao/EmptyResultDataAccessException.html" rel="noreferrer">EmptyResultDataAccessException</a> exception if it doesn't find the data in the database.</p> <p>Your code should look like this. </p> <pre><code>try { sql = "SELECT id FROM tableNmae WHERE column_name ='"+ coulmn value+ "'"; id= jdbcTemplate.queryForObject(sql, Long.class); } catch (EmptyResultDataAccessException e) { if(log.isDebugEnabled()){ log.debug(e); } return null } </code></pre>
26,140,050
Why is 'font-family' not inherited in '<button>' tags automatically?
<p>I have noticed that in case of <code>&lt;button&gt;</code> tags, <strong>font-family</strong> is not inherited automatically; either I must specify it explicitly like:</p> <pre><code>&lt;button style="font-family: some_style;"&gt;Button&lt;/button&gt; </code></pre> <p>or use <strong>inherit</strong> property like this:</p> <pre><code>&lt;button style="font-family: inherit;"&gt;Button&lt;/button&gt; </code></pre> <p>However, the <em>font-family</em> is automatically inherited in case of other tags, the <code>&lt;a&gt;</code> tag for example.</p> <p>Why do we have this issue with the <code>&lt;button&gt;</code> tags?</p> <p>Here's a <strong><a href="http://jsfiddle.net/svkq54L9/" rel="noreferrer">DEMO</a></strong>.</p>
26,140,154
4
3
null
2014-10-01 11:14:16.257 UTC
6
2021-03-10 15:40:38.38 UTC
2014-10-01 18:49:49.793 UTC
null
3,622,940
null
3,765,126
null
1
50
html|css|fonts
18,578
<p>Form elements don't inherit font settings, you have to set these properties manually.</p> <p>If you use font declaration for eg. body, </p> <pre><code>body {font-family: arial, sans-serif} </code></pre> <p>use just</p> <pre><code>body, input, textarea, button {font-family: arial, sans-serif} </code></pre> <p>or</p> <pre><code>input, textarea, button {font-family: inherit} </code></pre>
26,151,648
Bottom layout guide length issue with tabbar after pushing
<p>So my problem is related to auto-layout and the bottom layout guide.</p> <p>Here's the design of the app:</p> <blockquote> <p>UITabBarController</p> <blockquote> <p>^-- Tab1: NavigationController with VC1 as root</p> <blockquote> <p>^-- VC2 is pushed and hides the tab bar (full screen, top layout is situated under the nav bar, bottom layout should be the lowest pixel).</p> </blockquote> </blockquote> </blockquote> <p>When VC2 is pushed, the bottom layout guide is 49 points length during a small amount of time and then it's 0.</p> <p>During this time, my subviews which are constrained to this bottom guide are positioned incorrectly. </p> <p>When the guide is then correctly set to 0 (by the navigation controller itself, there's no code from me regarding this), the subviews positions are then perfect.</p> <p><img src="https://i.imgur.com/2pdQCCz.gif" alt="cast"></p> <p>This does not happen on iOS 7.x (the app supports 7.0+)... I'm pretty sure that's a iOS 8 bug and I was looking for a workaround, but I could not find something that fixes this.</p> <p>I tried to solve the issue forcing the navigation controllers'view to layout in view(Will/Did)LayoutSubviews, but it did not help. </p> <p>I saw <a href="https://stackoverflow.com/questions/21850831/constraint-to-bottom-layout-guide-with-tabbar-issue">this post</a> is related but the suggested solution does not work. Presenting the VC2 modally solves the issue but that's not acceptable.</p> <ul> <li><a href="http://youtu.be/jk-q2jO9Rio" rel="nofollow noreferrer">Here's a video showing the issue</a></li> <li>And I created a <a href="https://github.com/RomainBoulay/iOS8-BottomLayoutGuideIssue" rel="nofollow noreferrer">small project here</a> that contains this bug.</li> </ul> <p>Thanks in advance for your help, let me know if you need more explanations</p>
26,219,272
3
3
null
2014-10-01 22:21:06.257 UTC
12
2016-09-07 01:47:17.217 UTC
2017-05-23 12:19:42.593 UTC
null
-1
null
459,676
null
1
15
ios|ios8|autolayout
5,114
<p>I'm having a similar issue like this with a UIPageViewController. After some initial research it does appears to be a bug. The only way I have managed to resolve this is to pin the subview to the superview instead of the bottom layout guide like so.</p> <p><img src="https://i.stack.imgur.com/T60Cv.png" alt="Pin to superview image"></p> <p>The constraint does seem to be respected once the subview is pinned to the superview.</p> <p>Hope this helps.</p>
5,049,315
Is there any jQuery plugin for Hijri calendars?
<p>I wonder if there is any jQuery DatePicker plugin for Hijri calendars?</p>
5,049,366
3
0
null
2011-02-19 06:40:04.497 UTC
12
2016-11-02 20:10:08.04 UTC
2015-12-20 11:55:10.267 UTC
null
3,530,081
null
14,118
null
1
21
jquery|jquery-ui|jquery-plugins|calendar|hijri
18,529
<p>You can use from <a href="http://keith-wood.name/calendars.html" rel="noreferrer">jQuery Calendars</a> by Keith Wood or <a href="http://keith-wood.name/js/jquery.calendars-ar-DZ.js" rel="noreferrer">Algerian Hijri Calendar</a> specifically.</p>
5,041,664
T must be contravariantly valid
<p>What is wrong with this?</p> <pre><code>interface IRepository&lt;out T&gt; where T : IBusinessEntity { IQueryable&lt;T&gt; GetAll(); void Save(T t); void Delete(T t); } </code></pre> <p>It says:</p> <blockquote> <p>Invalid variance: The type parameter 'T' must be contravariantly valid on 'MyNamespace.IRepository.Delete(T)'. 'T' is covariant.</p> </blockquote>
5,043,054
3
2
null
2011-02-18 13:10:59.84 UTC
7
2022-07-12 12:26:00.79 UTC
2022-07-12 12:26:00.79 UTC
null
3,195,477
null
129,960
null
1
42
c#|.net|generics|covariance|contravariance
14,130
<p>Consider what would happen if the compiler allowed that:</p> <pre><code>interface IR&lt;out T&gt; { void D(T t); } class C : IR&lt;Mammal&gt; { public void D(Mammal m) { m.GrowHair(); } } ... IR&lt;Animal&gt; x = new C(); // legal because T is covariant and Mammal is convertible to Animal x.D(new Fish()); // legal because IR&lt;Animal&gt;.D takes an Animal </code></pre> <p>And you just tried to grow hair on a fish. </p> <p>The "out" means "T is only used in output positions". You are using it in an input position.</p>
4,957,224
Getting Last Day of Previous Month in Oracle Function
<p>I need a function in <code>Oracle</code> like this.</p> <p>When i giving a parameter a simple date. Then function should getting me last day of the previous month.</p> <p>Example: </p> <pre><code>FunctionName(10.02.2011) Result should be 31.01.2011 FunctionName(21.03.2011) Result should be 28.02.2011 FunctionName(31.07.2011) Result should be 30.06.2011 (Even date is last day of month) </code></pre> <p>How can i do that? By the way, i never use <code>Oracle</code> .</p>
4,957,269
4
0
null
2011-02-10 12:43:31.64 UTC
null
2020-08-02 16:53:38.307 UTC
2011-06-30 20:17:29.427 UTC
null
236,247
null
447,156
null
1
9
database|oracle|function|date-arithmetic
74,429
<pre><code>SELECT LAST_DAY(ADD_MONTHS(yourdate,-1)) </code></pre>
43,193,049
App.settings - the Angular way?
<p>I want to add an <code>App Settings</code> section into my App where It will contain some consts and pre defined values.</p> <p>I've already read <a href="https://stackoverflow.com/a/40287063/859154"><em>this answer</em></a> which uses <code>OpaqueToken</code> But it is deprecated in Angular. This <a href="https://blog.thoughtram.io/angular/2016/05/23/opaque-tokens-in-angular-2.html" rel="noreferrer"><em>article</em></a> explains the differences but it didn't provide a full example , and my attempts were unsuccessful.</p> <p>Here is what I've tried ( I don't know if it's the right way) : </p> <pre><code>//ServiceAppSettings.ts import {InjectionToken, OpaqueToken} from "@angular/core"; const CONFIG = { apiUrl: 'http://my.api.com', theme: 'suicid-squad', title: 'My awesome app' }; const FEATURE_ENABLED = true; const API_URL = new InjectionToken&lt;string&gt;('apiUrl'); </code></pre> <p>And this is the component where I want to use those consts : </p> <pre><code>//MainPage.ts import {...} from '@angular/core' import {ServiceTest} from "./ServiceTest" @Component({ selector: 'my-app', template: ` &lt;span&gt;Hi&lt;/span&gt; ` , providers: [ { provide: ServiceTest, useFactory: ( apiUrl) =&gt; { // create data service }, deps: [ new Inject(API_URL) ] } ] }) export class MainPage { } </code></pre> <p>But it doesn't work and I get errors. </p> <p><strong>Question:</strong></p> <p>How can I consume "app.settings" values the Angular way?</p> <p><a href="https://plnkr.co/edit/2YMZk5mhP1B4jTgA37B8?p=preview" rel="noreferrer"><strong>plunker</strong></a></p> <p>NB Sure I can create Injectable service and put it in the provider of the NgModule , But as I said I want to do it with <code>InjectionToken</code> , the Angular way.</p>
43,193,574
11
5
null
2017-04-03 19:45:56.097 UTC
67
2022-08-17 21:34:29.043 UTC
2018-03-26 10:43:26.653 UTC
null
859,154
null
859,154
null
1
125
javascript|angular
145,022
<p>I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI you can use the environment files found in <code>/environments</code> for static application wide settings like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using <code>InjectionToken</code>'s can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial HTTP request data, subdomain, etc.</p> <p><strong>Injection Tokens Example</strong></p> <p><strong>/app/app-config.module.ts</strong></p> <pre><code>import { NgModule, InjectionToken } from '@angular/core'; import { environment } from '../environments/environment'; export let APP_CONFIG = new InjectionToken&lt;AppConfig&gt;('app.config'); export class AppConfig { apiEndpoint: string; } export const APP_DI_CONFIG: AppConfig = { apiEndpoint: environment.apiEndpoint }; @NgModule({ providers: [{ provide: APP_CONFIG, useValue: APP_DI_CONFIG }] }) export class AppConfigModule { } </code></pre> <p><strong>/app/app.module.ts</strong></p> <pre><code>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppConfigModule } from './app-config.module'; @NgModule({ declarations: [ // ... ], imports: [ // ... AppConfigModule ], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p>Now you can just DI it into any component, service, etc:</p> <p><strong>/app/core/auth.service.ts</strong></p> <pre><code>import { Injectable, Inject } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { APP_CONFIG, AppConfig } from '../app-config.module'; import { AuthHttp } from 'angular2-jwt'; @Injectable() export class AuthService { constructor( private http: Http, private router: Router, private authHttp: AuthHttp, @Inject(APP_CONFIG) private config: AppConfig ) { } /** * Logs a user into the application. * @param payload */ public login(payload: { username: string, password: string }) { return this.http .post(`${this.config.apiEndpoint}/login`, payload) .map((response: Response) =&gt; { const token = response.json().token; sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor return this.handleResponse(response); // TODO: unset token shouldn't return the token to login }) .catch(this.handleError); } // ... } </code></pre> <p>You can then also type check the config using the exported AppConfig.</p>
9,199,216
Strings written to file do not preserve line breaks
<p>I am trying to write a <code>String</code>(lengthy but wrapped), which is from <code>JTextArea</code>. When the string printed to console, formatting is same as it was in <code>Text Area</code>, but when I write them to file using BufferedWriter, it is writing that <code>String</code> in single line.</p> <p>Following snippet can reproduce it:</p> <pre><code>public class BufferedWriterTest { public static void main(String[] args) throws IOException { String string = "This is lengthy string that contains many words. So\nI am wrapping it."; System.out.println(string); File file = new File("C:/Users/User/Desktop/text.txt"); FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(string); bufferedWriter.close(); } } </code></pre> <p>What went wrong? How to resolve this? Thanks for any help!</p>
9,199,636
5
3
null
2012-02-08 18:25:49.993 UTC
4
2018-06-26 13:48:58.48 UTC
2015-01-03 10:56:10.933 UTC
null
545,127
null
953,140
null
1
19
java|string|file|newline
57,635
<p>Text from a <code>JTextArea</code> will have <code>\n</code> characters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is <code>\r\n</code>, as others have mentioned).</p> <p>I think the best way to do that is to wrap the text into a <code>BufferedReader</code>, which can be used to iterate over the lines, and then use a <code>PrintWriter</code> to write each line out to a file using the platform-specific newline. There is a shorter solution involving <code>string.replace(...)</code> (see comment by Unbeli), but it is slower and requires more memory.</p> <p>Here is my solution - now made even simpler thanks to new features in Java 8:</p> <pre><code>public static void main(String[] args) throws IOException { String string = "This is lengthy string that contains many words. So\nI am wrapping it."; System.out.println(string); File file = new File("C:/Users/User/Desktop/text.txt"); writeToFile(string, file); } private static void writeToFile(String string, File file) throws IOException { try ( BufferedReader reader = new BufferedReader(new StringReader(string)); PrintWriter writer = new PrintWriter(new FileWriter(file)); ) { reader.lines().forEach(line -&gt; writer.println(line)); } } </code></pre>
9,384,446
How to pass sqlparameter to IN()?
<p>For some reason the Sqlparameter for my IN() clause is not working. The code compiles fine, and the query works if I substitute the parameter with the actual values</p> <pre><code>StringBuilder sb = new StringBuilder(); foreach (User user in UserList) { sb.Append(user.UserId + ","); } string userIds = sb.ToString(); userIds = userIds.TrimEnd(new char[] { ',' }); SELECT userId, username FROM Users WHERE userId IN (@UserIds) </code></pre>
9,384,566
4
3
null
2012-02-21 20:11:35.197 UTC
17
2021-03-02 20:49:09.59 UTC
null
null
null
null
173,432
null
1
46
c#|sql-server|ado.net
95,951
<p>You have to create one parameter for each value that you want in the <code>IN</code> clause.</p> <p>The SQL needs to look like this:</p> <pre><code>SELECT userId, username FROM Users WHERE userId IN (@UserId1, @UserId2, @UserId3, ...) </code></pre> <p>So you need to create the parameters <strong>and</strong> the <code>IN</code> clause in the <code>foreach</code> loop.<br> Something like this (out of my head, untested):</p> <pre><code>StringBuilder sb = new StringBuilder(); int i = 1; foreach (User user in UserList) { // IN clause sb.Append("@UserId" + i.ToString() + ","); // parameter YourCommand.Parameters.AddWithValue("@UserId" + i.ToString(), user.UserId); i++; } </code></pre>
9,629,710
What is the proper way to detect shell exit code when errexit option is set?
<p>I prefer to <strong>write solid shell</strong> code, so the errexit &amp; nounset is always set.</p> <p>The following code will stop at bad_command line</p> <pre><code>#!/bin/bash set -o errexit set -o nounset bad_command # stop here good_command </code></pre> <p>I want to capture it, here is my method</p> <pre><code>#!/bin/bash set -o errexit set -o nounset rc=1 bad_command &amp;&amp; rc=0 # stop here [ $rc -ne 0 ] &amp;&amp; do_err_handle good_command </code></pre> <p>Is there any better or cleaner method</p> <p>My Answer:</p> <pre><code>#!/bin/bash set -o errexit set -o nounset if ! bad_command ; then # error handle here fi good_command </code></pre>
15,844,901
14
5
null
2012-03-09 06:10:37.453 UTC
18
2021-09-19 16:58:19.787 UTC
2021-09-19 16:58:19.787 UTC
null
294,317
null
730,346
null
1
55
bash|shell
29,337
<p>How about this? If you want the actual exit code ...</p> <pre><code>#!/bin/sh set -e cat /tmp/doesnotexist &amp;&amp; rc=$? || rc=$? echo exitcode: $rc cat /dev/null &amp;&amp; rc=$? || rc=$? echo exitcode: $rc </code></pre> <p>Output:</p> <pre><code>cat: /tmp/doesnotexist: No such file or directory exitcode: 1 exitcode: 0 </code></pre>
18,686,884
Get live NFL scores/stats to read and manipulate?
<p>I need some sort of database or feed to access live scores(and possibly player stats) for the NFL. I want to be able to display the scores on my site for my pickem league and show the users if their pick is winning or not. </p> <p>I'm not sure how to go about this. Can someone point me in the right direction?</p> <p>Also, it needs to be free.</p>
18,756,406
7
4
null
2013-09-08 17:59:22.25 UTC
10
2021-09-13 02:30:07.717 UTC
2013-09-08 18:48:59.643 UTC
null
2,759,392
null
2,759,392
null
1
15
php|statistics|feed
30,141
<p>Disclaimer: I'm the author of the tools I'm about to promote.</p> <p>Over the past year, I've written a couple Python libraries that will do what you want. The first is <a href="https://github.com/BurntSushi/nflgame" rel="noreferrer">nflgame</a>, which gathers game data (including play-by-play) from NFL.com's GameCenter JSON feed. This includes active games where data is updated roughly every 15 seconds. nflgame <a href="https://github.com/BurntSushi/nflgame/wiki" rel="noreferrer">has a wiki</a> with some tips on getting started.</p> <p>I released nflgame last year, and used it throughout last season. I think it is reasonably stable.</p> <p>Over this past summer, I've worked on its more mature brother, <a href="https://github.com/BurntSushi/nfldb" rel="noreferrer">nfldb</a>. nfldb provides access to the same kind of data nflgame does, except it keeps everything stored in a relational database. nfldb <a href="https://github.com/BurntSushi/nfldb/wiki" rel="noreferrer">also has a wiki</a>, although it isn't entirely complete yet.</p> <p>For example, this will output all current games and their scores:</p> <pre><code>import nfldb db = nfldb.connect() phase, year, week = nfldb.current(db) q = nfldb.Query(db).game(season_year=year, season_type=phase, week=week) for g in q.as_games(): print '%s (%d) at %s (%d)' % (g.home_team, g.home_score, g.away_team, g.away_score) </code></pre> <p>Since no games are being played, that outputs all games for next week with <code>0</code> scores. This is the output with <code>week=1</code>: (of the 2013 season)</p> <pre><code>CLE (10) at MIA (23) DET (34) at MIN (24) NYJ (18) at TB (17) BUF (21) at NE (23) SD (28) at HOU (31) STL (27) at ARI (24) SF (34) at GB (28) DAL (36) at NYG (31) WAS (27) at PHI (33) DEN (49) at BAL (27) CHI (24) at CIN (21) IND (21) at OAK (17) JAC (2) at KC (28) PIT (9) at TEN (16) NO (23) at ATL (17) CAR (7) at SEA (12) </code></pre> <p>Both are licensed under the WTFPL and are free to use for any purpose.</p> <p>N.B. I realized you tagged this as PHP, but perhaps this will point you in the right direction. In particular, you could use <code>nfldb</code> to maintain a PostgreSQL database and query it with your PHP program.</p>
14,957,541
Sitecore MVC Rendering type clarification
<p>Could someone help me clarify when to use the following (they all look similar to me and confusing):</p> <ol> <li>Item Rendering</li> <li>View Rendering</li> <li>Controller Rendering</li> <li>Method rendering</li> <li>XSLT Rendering</li> <li>Rendering parameter</li> <li>Any others</li> </ol>
14,979,574
2
0
null
2013-02-19 12:30:42.017 UTC
8
2016-03-11 16:20:50.493 UTC
2016-03-11 16:20:50.493 UTC
null
3,474,146
null
656,348
null
1
10
asp.net-mvc|sitecore|sitecore6|sitecore-mvc
3,483
<p><strong>Item Rendering</strong></p> <p>This is a way to ask a piece of content (an item) to render itself. The content carries information about how it should render.</p> <p>To the best of my knowledge this is not widely used and not well documented - but I believe the feature itself to pre-date Sitecore MVC.</p> <p>See more here: <a href="http://www.sitecore.net/unitedkingdom/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/06/MVC-Item-Renderings-in-the-Sitecore-ASPNET-CMS.aspx">http://www.sitecore.net/unitedkingdom/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/06/MVC-Item-Renderings-in-the-Sitecore-ASPNET-CMS.aspx</a></p> <p><strong>View Rendering</strong></p> <p>Basically this is a Razor view. Sitecore provides a default controller and model for the view. The model can be customised by changing the mvc.getModel pipeline.</p> <p>Use this when you want to render item content that does not require any significant business or presentation logic.</p> <p><strong>Controller Rendering</strong></p> <p>With a controller rendering you supply controller, model and view. On your rendering definition item you specify what action Sitecore should use to render the component.</p> <p>Use this when you need to render content that relies on external data and/or requires significant business or presentation logic. Anything to do with form submission would probably also fall in this category.</p> <p><strong>Method Rendering</strong></p> <p>Will output the return value of a call to a static method.</p> <p>To the best of my knowledge this is not widely used and not well documented - I suppose it could be used for integrating legacy content.</p> <p>See more here: <a href="http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/03/More-Than-Anyone-Ever-Wanted-to-Know-About-Method-Renderings-in-the-Sitecore-ASPNET-CMS.aspx">http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/03/More-Than-Anyone-Ever-Wanted-to-Know-About-Method-Renderings-in-the-Sitecore-ASPNET-CMS.aspx</a></p> <p><strong>XSLT Rendering</strong></p> <p>Renders a Sitecore XSLT on a Sitecore MVC page. This rendering type fills the same space as the View Rendering just using XSLT as the template engine (rather than Razor).</p> <p>Use this if you have a library of existing Sitecore XSLT components that you don't want to rewrite. Personally I think View Renderings for doing no/low logic components are more appropriate if starting from scratch.</p> <p><strong>Url Rendering</strong></p> <p>Renders the response of a HTTP GET request onto the current page.</p> <p>Use this if you need to screen scrape HTML of another system. Again this could be used as a transition tool when migrating a legacy site. Can be used in some cases to avoid the embarrassing iframe syndrome.</p> <p>See more here: <a href="http://www.sitecore.net/unitedkingdom/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/03/All-About-URL-Renderings-in-the-Sitecore-ASPNET-CMS.aspx">http://www.sitecore.net/unitedkingdom/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/03/All-About-URL-Renderings-in-the-Sitecore-ASPNET-CMS.aspx</a></p> <p><strong>Rendering Parameter</strong></p> <p>This is not a rendering type and does not provide a facility for rendering anything on its own. Rendering Parameters are used to control the behaviour of renderings. Applies to all of the above rendering types.</p>
15,239,859
Gem install hangs indefinitely
<p>Background: I'm a designer that works well with HTML, CSS, and JS. But when it comes to setting up my environment is where I fall short.</p> <p>I recently purchased a home computer. I want to set up <a href="http://middlemanapp.com/getting-started/" rel="noreferrer">Middleman</a> to use in a project. I already installed rvm and all its requirements. I am on ruby-2.0.0-p0, which from what I understand is the latest stable release.</p> <p>When I attempt to install Middleman, or any other gem for that matter, nothing happens. The cursor just moves to the next line. <img src="https://i.stack.imgur.com/iYtLz.png" alt="Screenshot"></p> <p>Some guidance, or troubleshooting steps, would be greatly appreciated!</p> <p>Thank you, </p> <p>Ricardo</p>
22,696,412
4
1
null
2013-03-06 05:46:05.443 UTC
3
2021-08-25 19:02:42.04 UTC
null
null
null
null
1,024,332
null
1
32
ruby|gem|installation|rvm
25,084
<p>If <code>gem install</code> is hanging, it's most likely a network, proxy, or firewall issue on your end.</p> <p>You can investigate by issuing your gem install command in verbose mode with <code>-V</code>. It'll show you what URLs it's communicating with to download the gem, and you can hopefully see what it's doing and where it's hanging:</p> <pre><code>&gt; gem install -V middleman HEAD https://rubygems.org/latest_specs.4.8.gz 302 Moved Temporarily HEAD https://s3.amazonaws.com/production.s3.rubygems.org/latest_specs.4.8.gz 200 OK GET https://rubygems.org/latest_specs.4.8.gz 302 Moved Temporarily GET https://s3.amazonaws.com/production.s3.rubygems.org/latest_specs.4.8.gz ... </code></pre> <p>You can also check <a href="http://status.rubygems.org/" rel="noreferrer">status.rubygems.org</a> where they'll alert you in case the gem/spec servers do have problems (see screenshot below):</p> <p><a href="http://status.rubygems.org/" rel="noreferrer"><img src="https://i.stack.imgur.com/rXiwL.jpg" alt="RubyGem.org status screenshot"></a></p>
15,117,379
HttpContext.Current not Resolving in MVC 4 Project
<p>I am wanting to use ImageResizer (from ImageResizing dot net). I installed ImageResizer for MVC via NuGet. But when I go to use the following code from the example:</p> <pre><code>//Loop through each uploaded file foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; if (file.ContentLength &lt;= 0) continue; //Skip unused file controls. //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details. //Destination paths can have variables like &lt;guid&gt; and &lt;ext&gt;, or //even a santizied version of the original filename, like &lt;filename:A-Za-z0-9&gt; ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, "~/uploads/&lt;guid&gt;.&lt;ext&gt;", new ImageResizer.ResizeSettings( "width=2000;height=2000;format=jpg;mode=max")); i.CreateParentDirectory = true; //Auto-create the uploads directory. i.Build(); } </code></pre> <p>The "HttpContext.Current.Request.Files.Keys" in the foreach is not resolving? I have my usings correct and Visual Studio offers no "Resolve" options.</p>
21,529,654
3
4
null
2013-02-27 16:37:31.47 UTC
6
2021-12-02 10:09:46.807 UTC
2018-02-02 22:33:25.163 UTC
null
41,956
null
566,295
null
1
38
c#|asp.net|asp.net-mvc|asp.net-mvc-4|httpcontext
53,074
<p>The problem is that the <code>Controller</code> class has a public property called <code>HttpContext</code> (see <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpcontext.aspx">http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpcontext.aspx</a>).</p> <p>This means that when you attempt to use it without any qualification in the controller it resolves to the local property and not <code>System.Web.HttpContext</code>. The type of the property is <code>HttpContextBase</code> which does have a <code>Request</code> property that would do what you want (though note that it isn't the same class as you would get from <code>System.Web.HttpContext</code>.</p>
15,191,511
Disable etag Header in Express Node.js
<p>We have a need to remove the <code>etag</code> header from all HTTP responses in our Node.js Express application. We have a web services API written in Express where unexpected results are seen at the client when we send etags and the client sends back the <code>if-none-match</code> header.</p> <p>We've tried <code>app.disable('etag')</code> and <code>res.removeHeader('etag')</code>, but neither work; the app sends the header regardless. </p> <p>Is there any other means of disabling this header in all responses?</p>
19,922,801
6
0
null
2013-03-03 22:10:06.877 UTC
5
2018-11-13 20:13:00.013 UTC
null
null
null
null
262,677
null
1
40
node.js|express
34,956
<p><code>app.disable('etag')</code> should work now, there has been a pull request merged to deal with this:</p> <p><a href="https://github.com/visionmedia/express/commit/610e172fcf9306bd5812bb2bae8904c23e0e8043" rel="noreferrer">https://github.com/visionmedia/express/commit/610e172fcf9306bd5812bb2bae8904c23e0e8043</a></p> <p><strong>UPDATE</strong>: as Bigood pointed out in the comments the new way of doing things is the following</p> <pre><code>app.set('etag', false); // turn off </code></pre> <p>Change occured with version 3.9.0: <a href="https://github.com/strongloop/express/releases/tag/3.9.0" rel="noreferrer">https://github.com/strongloop/express/releases/tag/3.9.0</a></p> <p>For more options on setting the etag check the 4.x docs here: <a href="http://expressjs.com/4x/api.html#app.set" rel="noreferrer">http://expressjs.com/4x/api.html#app.set</a></p>
15,334,220
Encode/Decode base64
<p>here is my code and i don't understand why the decode function doesn't work.</p> <p>Little insight would be great please.</p> <pre><code>func EncodeB64(message string) (retour string) { base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(message))) base64.StdEncoding.Encode(base64Text, []byte(message)) return string(base64Text) } func DecodeB64(message string) (retour string) { base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message))) base64.StdEncoding.Decode(base64Text, []byte(message)) fmt.Printf("base64: %s\n", base64Text) return string(base64Text) } </code></pre> <p>It gaves me : [Decode error - output not utf-8][Decode error - output not utf-8]</p>
15,334,435
5
0
null
2013-03-11 08:39:24.2 UTC
4
2022-05-31 01:56:59.437 UTC
2016-01-07 00:38:23.913 UTC
null
1,090,562
null
462,794
null
1
54
base64|go
75,407
<p><code>DecodedLen</code> returns the <strong>maximal</strong> length. </p> <p>This length is useful for sizing your buffer but part of the buffer won't be written and thus won't be valid UTF-8.</p> <p>You have to use only the real written length returned by the <code>Decode</code> function.</p> <pre><code>l, _ := base64.StdEncoding.Decode(base64Text, []byte(message)) log.Printf("base64: %s\n", base64Text[:l]) </code></pre>
15,154,644
GROUP BY to combine/concat a column
<p>I have a table as follow:</p> <pre><code>ID User Activity PageURL 1 Me act1 ab 2 Me act1 cd 3 You act2 xy 4 You act2 st </code></pre> <p>I want to group by User and Activity such that I end up with something like:</p> <pre><code>User Activity PageURL Me act1 ab, cd You act2 xy, st </code></pre> <p>As you can see, the column PageURL is combined together separated by a comma based on the group by.</p> <p>Would really appreciate any pointers and advice.</p>
15,154,723
2
4
null
2013-03-01 09:42:15.667 UTC
47
2015-06-16 07:38:19.93 UTC
2015-06-16 07:38:19.93 UTC
null
76,337
null
1,383,348
null
1
127
sql|sql-server|sql-server-2008|group-by
251,905
<pre><code>SELECT [User], Activity, STUFF( (SELECT DISTINCT ',' + PageURL FROM TableName WHERE [User] = a.[User] AND Activity = a.Activity FOR XML PATH ('')) , 1, 1, '') AS URLList FROM TableName AS a GROUP BY [User], Activity </code></pre> <ul> <li><a href="http://sqlfiddle.com/#!3/467bd/4">SQLFiddle Demo</a></li> </ul>
28,272,285
Why cgo's performance is so slow? is there something wrong with my testing code?
<p>I'm doing a test: compare excecution times of cgo and pure Go functions run 100 million times each. The cgo function takes longer time compared to the Golang function, and I am confused with this result. My testing code is:</p> <pre><code>package main import ( "fmt" "time" ) /* #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; void show() { } */ // #cgo LDFLAGS: -lstdc++ import "C" //import "fmt" func show() { } func main() { now := time.Now() for i := 0; i &lt; 100000000; i = i + 1 { C.show() } end_time := time.Now() var dur_time time.Duration = end_time.Sub(now) var elapsed_min float64 = dur_time.Minutes() var elapsed_sec float64 = dur_time.Seconds() var elapsed_nano int64 = dur_time.Nanoseconds() fmt.Printf("cgo show function elasped %f minutes or \nelapsed %f seconds or \nelapsed %d nanoseconds\n", elapsed_min, elapsed_sec, elapsed_nano) now = time.Now() for i := 0; i &lt; 100000000; i = i + 1 { show() } end_time = time.Now() dur_time = end_time.Sub(now) elapsed_min = dur_time.Minutes() elapsed_sec = dur_time.Seconds() elapsed_nano = dur_time.Nanoseconds() fmt.Printf("go show function elasped %f minutes or \nelapsed %f seconds or \nelapsed %d nanoseconds\n", elapsed_min, elapsed_sec, elapsed_nano) var input string fmt.Scanln(&amp;input) } </code></pre> <p>and result is:</p> <pre><code>cgo show function elasped 0.368096 minutes or elapsed 22.085756 seconds or elapsed 22085755775 nanoseconds go show function elasped 0.000654 minutes or elapsed 0.039257 seconds or elapsed 39257120 nanoseconds </code></pre> <p>The results show that invoking the C function is slower than the Go function. Is there something wrong with my testing code?</p> <p>My system is : mac OS X 10.9.4 (13E28)</p>
28,272,990
4
3
null
2015-02-02 06:35:13.087 UTC
13
2022-07-09 05:47:08.413 UTC
2016-08-03 04:44:58.487 UTC
user6169399
null
null
4,407,799
null
1
20
c|performance|go|cgo
12,422
<p>As you've discovered, there is fairly high overhead in calling C/C++ code via CGo. So in general, you are best off trying to minimise the number of CGo calls you make. For the above example, rather than calling a CGo function repeatedly in a loop it might make sense to move the loop down to C.</p> <p>There are a number of aspects of how the Go runtime sets up its threads that can break the expectations of many pieces of C code:</p> <ol> <li>Goroutines run on a relatively small stack, handling stack growth through segmented stacks (old versions) or by copying (new versions).</li> <li>Threads created by the Go runtime may not interact properly with <code>libpthread</code>'s thread local storage implementation.</li> <li>The Go runtime's UNIX signal handler may interfere with traditional C or C++ code.</li> <li>Go reuses OS threads to run multiple Goroutines. If the C code called a blocking system call or otherwise monopolised the thread, it could be detrimental to other goroutines.</li> </ol> <p>For these reasons, CGo picks the safe approach of running the C code in a separate thread set up with a traditional stack.</p> <p>If you are coming from languages like Python where it isn't uncommon to rewrite code hotspots in C as a way to speed up a program you will be disappointed. But at the same time, there is a much smaller gap in performance between equivalent C and Go code.</p> <p>In general I reserve CGo for interfacing with existing libraries, possibly with small C wrapper functions that can reduce the number of calls I need to make from Go.</p>
7,956,448
How to Access Sharepoint 2007/2010/2013 _layouts folder
<p>I'm trying to insert some data in the location mysiteurl/_layouts/</p> <p>'cause I had to use a third part software which uses data stored in that folder... I'm admin of the machine (Sharepoint 2010 on Windows server 2008R2) but the Sharepoint said I cannot access directly to that folder...</p> <p>Is there any trick to insert data in that specific folder?</p>
11,220,384
2
3
null
2011-10-31 16:16:33.68 UTC
6
2017-12-13 14:50:14.173 UTC
2017-03-02 17:24:50.07 UTC
null
2,680,216
null
530,384
null
1
24
sharepoint|layout|insert
83,691
<p>If you're using SP 2007 the folder path is:</p> <pre><code>C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\ </code></pre> <p>Sharepoint 2010 layouts folder path is:</p> <pre><code>C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\ </code></pre> <p>If you're using SP 2013 the folder path is:</p> <pre><code>C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\ </code></pre> <p>If you're using SP 2016 the folder path is:</p> <pre><code>C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\TEMPLATE\ </code></pre>
7,805,274
pause git clone and resume later?
<p>Is there a way to pause git clone and resume it later? I'm cloning a really big repo (around 2GB) and my PC's been turned on for more than 40 hours. I have school to catch later, I don't want to leave it like this. Anybody got an idea? It's already at 67% btw. :(</p>
7,805,382
2
0
null
2011-10-18 09:43:44.763 UTC
6
2019-08-05 18:47:02.53 UTC
null
null
null
null
588,051
null
1
43
git|git-clone
30,444
<p>Assuming it's a normal <code>git clone</code>, I'm afraid that they're not resumable, as far as I know. To add support for resumable <code>git clone</code> / <code>git fetch</code> has been a suggested project for the Google Summer of Code in the past.</p> <p>One exception is if you're actually doing a <code>git svn clone</code>, then you can restart it by changing into the directory and running <code>git svn fetch</code>, but I assume that this is just a normal git repository you're cloning. For some other ideas of how to work around this, you might want to try the suggestions in the answers to this question:</p> <ul> <li><a href="https://stackoverflow.com/q/3954852/223092">How to complete a git clone for a big project on an unstable connection?</a></li> </ul>
8,563,299
Submit multiple forms with one submit button
<p>I have the following code, basically it is performing two operations. First one being submitting my form data to the google spreadsheet and the other operation is submitting my second form textbox value data to another page textbox value. How to do this?</p> <pre class="lang-html prettyprint-override"><code>&lt;script type=&quot;text/javascript&quot;&gt; &lt;!-- function copy_data(val){ var a = document.getElementById(val.id).value document.getElementById(&quot;copy_to&quot;).value=a } //--&gt; &lt;/SCRIPT&gt; &lt;style type=&quot;text/css&quot;&gt; &lt;!-- --&gt; &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script type=&quot;text/javascript&quot;&gt;var submitted=false;&lt;/script&gt; &lt;iframe name=&quot;response_iframe&quot; id=&quot;hidden_iframe&quot; style=&quot;display:none;&quot; onload=&quot;if(submitted){window.location='Thanks.asp';}&quot;/&gt; &lt;form action=&quot;https://docs.google.com/spreadsheet/formResponse?formkey=dGtzZnBaYTh4Q1JfanlOUVZhZkVVUVE6MQ&amp;ifq&quot; method=&quot;post&quot; target=&quot;response_iframe&quot; id=&quot;commentForm&quot; onSubmit=&quot;submitted=true;&quot;&gt; &lt;!-- #include virtual=&quot;/sts/include/header.asp&quot; --&gt; &lt;!-- ABove this Header YJC --&gt; &lt;table style=&quot;background-color: #FFC ;&quot; width=&quot;950&quot; align=&quot;center&quot; border=&quot;0&quot; summary=&quot;VanaBhojnaluBooking_Table&quot;&gt; &lt;tr&gt; &lt;td colspan=&quot;7&quot;&gt; &lt;p class=&quot;MsoNormal&quot; align=&quot;center&quot; style=&quot;text-align:center;&quot;&gt; &lt;strong&gt; &lt;span style=&quot;line-height:115%; font-family:'Arial Rounded MT Bold','sans-serif'; font-size:16.0pt; color:#76923C; &quot;&gt;Karthika Masa Vanabhojanalu &amp;ndash; Participation Booking&lt;/span&gt; &lt;/strong&gt; &lt;/p&gt; &lt;p class=&quot;MsoNormal&quot; align=&quot;center&quot; style=&quot;text-align:center;&quot;&gt; &lt;strong&gt; &lt;em&gt; &lt;span style=&quot;line-height:115%; font-size:20.0pt; color:#7030A0; &quot;&gt;13&lt;sup&gt;th&lt;/sup&gt; Nov 2011 - @ West Coast Park - Singapore&lt;/span&gt; &lt;/em&gt; &lt;/strong&gt; &lt;/p&gt; &lt;p class=&quot;MsoNormal&quot; align=&quot;center&quot; style=&quot;text-align:center;&quot;&gt; &lt;strong&gt; &lt;span style=&quot;color:#7030A0; &quot;&gt;Reserve your participation and avail &lt;/span&gt; &lt;span style=&quot;color:red; &quot;&gt; &lt;a target=&quot;_blank&quot; href=&quot;/STS/programs/VB_2011_info.asp&quot;&gt; DISCOUNT &lt;/a&gt; &lt;/span&gt; &lt;span style=&quot;color:#7030A0; &quot;&gt; on the ticket&lt;/span&gt; &lt;/strong&gt; &lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th width=&quot;37&quot; scope=&quot;col&quot;&gt;&amp;nbsp;&lt;/th&gt; &lt;th width=&quot;109&quot; rowspan=&quot;5&quot; valign=&quot;top&quot; class=&quot;YJCRED&quot; scope=&quot;col&quot;&gt; &lt;div align=&quot;left&quot;&gt; &lt;font size=&quot;2&quot;&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;* Required&lt;/font&gt; &lt;/div&gt; &lt;/th&gt; &lt;td width=&quot;68&quot; scope=&quot;col&quot;&gt; &lt;div align=&quot;right&quot;&gt; &lt;font size=&quot;2.5px&quot;&gt;Name&lt;/font&gt; &lt;span class=&quot;yj&quot;&gt; &lt;span class=&quot;yjcred&quot;&gt;*&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;th colspan=&quot;3&quot; scope=&quot;col&quot;&gt; &lt;label for=&quot;Name&quot;/&gt; &lt;div align=&quot;left&quot;&gt; &lt;input name=&quot;entry.0.single&quot; class=&quot;required&quot; style=&quot;width:487px; height:25px; vertical-align:middle;&quot; type=&quot;text&quot; id=&quot;entry_0&quot; title=&quot;Enter your name&quot;&gt; &lt;/div&gt; &lt;/th&gt; &lt;th width=&quot;223&quot; scope=&quot;col&quot;&gt;&amp;nbsp;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt; &lt;div align=&quot;right&quot;&gt; &lt;font size=&quot;2.5px&quot;&gt;Phone&lt;/font&gt; &lt;span class=&quot;yj&quot;&gt; &lt;span class=&quot;yjcred&quot;&gt;*&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td width=&quot;107&quot;&gt; &lt;input name=&quot;entry.1.single&quot; class=&quot;required&quot; title=&quot;Handphone Number with out +65&quot; maxlength=&quot;8&quot; style=&quot;width:100px;height:25px;&quot; type=&quot;text&quot; onkeyup=&quot;copy_data(this)&quot; onKeyPress=&quot;return numbersonly(this, event)&quot; id=&quot;entry_1&quot;/&gt; &lt;td width=&quot;170&quot;&gt; &lt;div align=&quot;right&quot;&gt; &lt;font size=&quot;2.5px&quot;&gt;Email&lt;/font&gt; &lt;span class=&quot;yj&quot;&gt; &lt;span class=&quot;yjcred1&quot;&gt;*&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td width=&quot;206&quot;&gt; &lt;input name=&quot;entry.2.single&quot; type=&quot;text&quot; style=&quot;width:190px;height:25px;&quot; id=&quot;required&quot; title=&quot;Enter your email address&quot; class=&quot;required email&quot;/&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt; &lt;div align=&quot;right&quot;&gt; &lt;font size=&quot;2.5px&quot;&gt;Home Phone&lt;/font&gt; &lt;/div&gt; &lt;/td&gt; &lt;td width=&quot;107&quot;&gt; &lt;input name=&quot;entry.1.single&quot; title=&quot;Handphone Number with out +65&quot; maxlength=&quot;8&quot; style=&quot;width:100px;height:25px;&quot; type=&quot;text&quot; onKeyPress=&quot;return numbersonly(this, event)&quot; id=&quot;entry_100&quot;/&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align=&quot;center&quot; colspan=&quot;7&quot;&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt; &lt;input type=&quot;submit&quot; name=&quot;submit&quot; onMouseOver=&quot;Window.status='You can not see anything';return true&quot; onMouseOut=&quot;window.status='Press SUBMIT only after proper inforatmion entering then you are Done'&quot; onClick=&quot;jQuery.Watermark.HideAll();&quot; value=&quot;Submit&quot;&gt; &lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;tr&gt; &lt;td colspan=&quot;25&quot;/&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;form method=&quot;Link&quot; Action=&quot;Sankranthi_Reserv2.asp&quot;&gt; &lt;input disabled name=&quot;copy of hp&quot; maxlength=&quot;8&quot; style=&quot;width:100px;height:25px;&quot; type=&quot;text&quot; id=&quot;copy_to&quot;&gt; &lt;/form&gt; &lt;p&gt; &lt;!-- #include virtual=&quot;/sts/include/footer.asp&quot; --&gt; &lt;input type=&quot;hidden&quot; name=&quot;pageNumber&quot; value=&quot;0&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;backupCache&quot; value=&quot;&quot;&gt; &lt;script type=&quot;text/javascript&quot;&gt; (function() { var divs = document.getElementById('ss-form').getElementsByTagName('div'); var numDivs = divs.length; for (var j = 0; j &lt; numDivs; j++) { if (divs[j].className=='errorbox-bad') { divs[j].lastChild.firstChild.lastChild.focus(); return; } } for (var i=0; i &lt; numDivs; i++) { var div = divs[i]; if (div.className=='ss-form-entry' &amp;&amp; div.firstChild &amp;&amp; div.firstChild.className=='ss-q-title') { div.lastChild.focus(); return; } } </code></pre> <p>As you can see from above, this is the first page and in the second page where I was referring to Sankranthi_Reserv2.asp in the second form. I want to pass the textbox value over there, so the problem is the first form is submitting to the google docs and storing the data, but the second form need to pass the handphone number textbox value to the nextpage textbox value, but there is only one SUBMIT button.</p>
8,563,735
3
3
null
2011-12-19 15:10:14.663 UTC
9
2022-03-16 13:06:45.3 UTC
2022-03-16 13:06:45.3 UTC
null
15,377,355
null
935,913
null
1
12
javascript|jquery|html
76,351
<p>For submitting two forms you will have to use Ajax. As after using form.submit() page will load action URL for that form. so you will have to do that asynchronously.</p> <p>So you can send both request asynchronously or send one request asynchronously and after its success submit second form.</p> <pre><code>function submitTwoForms() { var dataObject = {"form1 Data with name as key and value "}; $.ajax({ url: "test.html", data : dataObject, type : "GET", success: function(){ $("#form2").submit(); //assuming id of second form is form2 } }); return false; //to prevent submit } </code></pre> <p>You can bind this <code>submitTwoForms()</code> function on your that one submit button. Using </p> <pre><code>$('#form1').submit(function() { submitTwoForms(); return false; }); </code></pre> <p>But, if you do not want to do all this, you can use <a href="http://jquery.malsup.com/form/#getting-started" rel="noreferrer">Jquery form plugin</a> to submit form using Ajax.</p>
8,642,668
How to make submodule with detached HEAD to be attached to actual HEAD?
<p>When I add a Git submodule to a Git repository like this,</p> <pre><code>git submodule add ssh://server/proj1/ proj1 git submodule init git submodule update </code></pre> <p>the added submodule will be in <em>detached HEAD</em> mode. I don't know well what that is, but I know that the submodule will be linked to specific revision of the target repository.</p> <p>I don't know how it actually works, anyway it looks like a proxy branch exists there. I solved this by switching to master branch.</p> <pre><code>cd proj1 git checkout master </code></pre> <p>This will switch current branch actual master HEAD, but this does not update the linkage. So If you clone the whole repository again, it will still be linked to old revision.</p> <p>If I want to make it to be linked to most recent revision (HEAD) always, what should I do?</p>
8,644,339
1
3
null
2011-12-27 08:45:24.057 UTC
10
2016-07-18 13:11:25.05 UTC
2014-07-11 09:38:57.323 UTC
null
246,776
null
246,776
null
1
28
git|git-submodules
21,362
<p>Update March 2013</p> <p><a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.8.2.txt" rel="nofollow noreferrer">Git 1.8.2</a> added the possibility to track branches. </p> <blockquote> <p>"<code>git submodule</code>" started learning a new mode to <strong>integrate with the tip of the remote branch</strong> (as opposed to integrating with the commit recorded in the superproject's gitlink).</p> </blockquote> <pre><code># add submodule to track master branch git submodule add -b master [URL to Git repo]; # update your submodule git submodule update --remote </code></pre> <p>See also the <a href="http://www.vogella.com/tutorials/GitSubmodules/article.html" rel="nofollow noreferrer">Vogella's tutorial on submodules</a>.</p> <hr> <p>Original answer (December 2011)</p> <blockquote> <p>added submodule will be in detached HEAD mode</p> </blockquote> <p>Yes, a submodule is about referencing a specific commit, and not a branch.<br> So:</p> <ul> <li>If you checkout a commit SHA1 (or a tag), you are in a detached HEAD mode. </li> <li>If you checkout a branch (like you did with <code>master</code> branch of the submodule), you can create other commits on top of that branch (but you will have to go back to the parent repo in order to commit said parent as well, for you need to record the new submodule commit you created)</li> </ul> <p>See "<a href="https://stackoverflow.com/questions/1979167/git-submodule-update/1979194#1979194">True nature of submodules</a>" for more.</p> <p>If you always wanted the latest commit of another repo, the simplest way would be to merge them together (for instance with subtree merging).<br> See "<a href="https://stackoverflow.com/questions/8632540/merge-2-same-repository-git/8634609#8634609">Merge 2 same repository GIT</a>" for the details and references.</p>
8,788,057
How to initialize and print a std::wstring?
<p>I had the code:</p> <pre><code>std::string st = "SomeText"; ... std::cout &lt;&lt; st; </code></pre> <p>and that worked fine. But now my team wants to move to <code>wstring</code>. So I tried:</p> <pre><code>std::wstring st = "SomeText"; ... std::cout &lt;&lt; st; </code></pre> <p>but this gave me a compilation error:</p> <blockquote> <p>Error 1 error C2664: 'std::basic_string&lt;_Elem,_Traits,_Ax>::basic_string(const std::basic_string&lt;_Elem,_Traits,_Ax> &amp;)' : cannot convert parameter 1 from 'const char [8]' to 'const std::basic_string&lt;_Elem,_Traits,_Ax> &amp;' D:...\TestModule1.cpp 28 1 TestModule1</p> </blockquote> <p>After searching the web I read that I should define it as:</p> <pre><code>std::wstring st = L"SomeText"; // Notice the "L" ... std::cout &lt;&lt; st; </code></pre> <p>this compiled but prints <code>"0000000000012342"</code> instead of <code>"SomeText"</code>.</p> <p>What am I doing wrong ?</p>
8,788,095
6
4
null
2012-01-09 11:56:48.693 UTC
12
2022-04-19 18:06:24.503 UTC
2014-09-18 09:19:22.157 UTC
null
2,642,204
null
672,689
null
1
79
c++|c++-cli|wstring
101,521
<p>To display a wstring you also need a wide version of cout - wcout.</p> <pre><code>std::wstring st = L"SomeText"; ... std::wcout &lt;&lt; st; </code></pre>
5,031,162
plugin to separate tags (like the stackoverflow's input tags interface)
<p>I'm looking for a plugin or simple script that behaves like <a href="http://stackoverflow.com">Stack Overflow</a>'s <em>tags</em> input interface. </p> <p>In particular I need to separate the single words (tags) that people write. </p>
5,031,215
4
2
null
2011-02-17 15:45:29.633 UTC
20
2015-11-09 10:18:11.127 UTC
2014-08-04 04:50:07.61 UTC
null
31,671
null
536,926
null
1
28
javascript|jquery|jquery-plugins|autocomplete
8,604
<p>There are <strong>plenty</strong>:</p> <ol> <li><strike><a href="http://code.drewwilson.com/entry/autosuggest-jquery-plugin" rel="nofollow noreferrer">http://code.drewwilson.com/entry/autosuggest-jquery-plugin</a></strike> (<strong>broken link</strong> <a href="https://github.com/drewwilson/AutoSuggest" rel="nofollow noreferrer">github link</a>)</li> <li><a href="http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/" rel="nofollow noreferrer">http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/</a></li> <li><strike><a href="http://plugins.jquery.com/project/tag-it" rel="nofollow noreferrer">http://plugins.jquery.com/project/tag-it</a></strike> (<strong>broken link</strong> <a href="http://aehlke.github.io/tag-it/" rel="nofollow noreferrer">github link</a>)</li> <li><strike><a href="http://plugins.jquery.com/project/jquerytag" rel="nofollow noreferrer">http://plugins.jquery.com/project/jquerytag</a></strike> (<strong>broken link</strong>)</li> </ol> <p><strong>If you are looking for a styled and ready solution, I'd recommend the first option.</strong></p> <p>If you are looking for a more flexible and complete solution, the second solution is probably a good fit.</p>
5,334,465
Routes with Dash `-` Instead of Underscore `_` in Ruby on Rails
<p>I want my urls to use dash <code>-</code> instead of underscore <code>_</code> as word separators. For example <code>controller/my-action</code> instead of <code>controller/my_action</code>.</p> <p>I'm surprised about two things:</p> <ol> <li>Google et al. continue to distinguish them. </li> <li>That Ruby on Rails doesn't have a simple, global configuration parameter to map <code>-</code> to <code>_</code> in the routing. Or does it? </li> </ol> <p>The best solution I've is to use <code>:as</code> or a named route.</p> <p>My idea is to modify the Rails routing to check for that global config and change <code>-</code> to <code>_</code> before dispatching to a controller action.</p> <p>Is there a better way?</p>
7,798,131
4
3
null
2011-03-17 03:09:20.267 UTC
13
2019-10-31 09:14:36.48 UTC
2017-05-10 13:04:27.763 UTC
null
118,007
null
217,833
null
1
91
ruby-on-rails|routing|rails-routing
20,633
<p>With Rails 3 and later you can do like this:</p> <pre><code>resources :user_bundles, :path =&gt; '/user-bundles' </code></pre> <hr> <p>Another option is to modify Rails, via an initializer. I don't recommend this though, since it may break in future versions (edit: doesn't work in Rails 5).</p> <p>Using <code>:path</code> as shown above is better.</p> <pre><code># Using private APIs is not recommended and may break in future Rails versions. # https://github.com/rails/rails/blob/4-1-stable/actionpack/lib/action_dispatch/routing/mapper.rb#L1012 # # config/initializers/adjust-route-paths.rb module ActionDispatch module Routing class Mapper module Resources class Resource def path @path.dasherize end end end end end end </code></pre>
5,055,853
How do you modularize Node.JS w/Express
<p>I'm trying to modularize my node.js application (using express framework). The trouble I am having is when setting up my routes. </p> <p>I am no longer able to extract the data I send to the post. (req.body is undefined). This works okay if it is all in the same file. What am I doing wrong here, and what is the best way to modularize code in node.js?</p> <p>My app.js</p> <pre><code>require('./routes.js').setRoutes(app); </code></pre> <p>My route.js</p> <pre><code>exports.setRoutes = function(app){ app.post('/ask', function(req, res, next){ time = new Date(); var newQuestion = {title: req.body.title, time: time.getTime(), vote:1}; app.questions.push(newQuestion); res.render('index', { locals: { title: 'Questions', questions: app.questions } }); }); </code></pre>
6,684,417
5
0
null
2011-02-20 07:40:16.4 UTC
18
2014-06-02 02:45:47.967 UTC
null
null
null
null
261,555
null
1
13
javascript|node.js|express
10,865
<p>A better approach:</p> <p>Create a routes.js file that contains:</p> <pre><code>var index = require('./controllers/index'); module.exports = function(app) { app.all('/', index.index); } </code></pre> <p>Then, from within your server.js (or however you've started your server), you'd require it as such:</p> <pre><code>require('./routes')(app); </code></pre> <p>This way you aren't creating global variables that bring with them a whole slew of issues (testability, collision, etc.)</p>
4,858,131
RGB to CMYK and back algorithm
<p>I am trying to implement a solution for calculating the conversion between RGB and CMYK and vice versa. Here is what I have so far:</p> <pre><code> public static int[] rgbToCmyk(int red, int green, int blue) { int black = Math.min(Math.min(255 - red, 255 - green), 255 - blue); if (black!=255) { int cyan = (255-red-black)/(255-black); int magenta = (255-green-black)/(255-black); int yellow = (255-blue-black)/(255-black); return new int[] {cyan,magenta,yellow,black}; } else { int cyan = 255 - red; int magenta = 255 - green; int yellow = 255 - blue; return new int[] {cyan,magenta,yellow,black}; } } public static int[] cmykToRgb(int cyan, int magenta, int yellow, int black) { if (black!=255) { int R = ((255-cyan) * (255-black)) / 255; int G = ((255-magenta) * (255-black)) / 255; int B = ((255-yellow) * (255-black)) / 255; return new int[] {R,G,B}; } else { int R = 255 - cyan; int G = 255 - magenta; int B = 255 - yellow; return new int[] {R,G,B}; } } </code></pre>
4,861,877
6
2
null
2011-02-01 01:56:02.613 UTC
9
2018-08-16 10:53:55.913 UTC
2011-02-01 02:02:35.137 UTC
null
40,516
null
398,499
null
1
11
java|rgb|cmyk
34,486
<p>As Lea Verou said you should make use of color space information because there isn't an algorithm to map from RGB to CMYK. Adobe has some ICC color profiles available for download<a href="http://download.adobe.com/pub/adobe/...c_end-user.zip" rel="noreferrer">1</a>, but I'm not sure how they are licensed.</p> <p>Once you have the color profiles something like the following would do the job:</p> <pre><code>import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.io.IOException; import java.util.Arrays; public class ColorConv { final static String pathToCMYKProfile = "C:\\UncoatedFOGRA29.icc"; public static float[] rgbToCmyk(float... rgb) throws IOException { if (rgb.length != 3) { throw new IllegalArgumentException(); } ColorSpace instance = new ICC_ColorSpace(ICC_Profile.getInstance(pathToCMYKProfile)); float[] fromRGB = instance.fromRGB(rgb); return fromRGB; } public static float[] cmykToRgb(float... cmyk) throws IOException { if (cmyk.length != 4) { throw new IllegalArgumentException(); } ColorSpace instance = new ICC_ColorSpace(ICC_Profile.getInstance(pathToCMYKProfile)); float[] fromRGB = instance.toRGB(cmyk); return fromRGB; } public static void main(String... args) { try { float[] rgbToCmyk = rgbToCmyk(1.0f, 1.0f, 1.0f); System.out.println(Arrays.toString(rgbToCmyk)); System.out.println(Arrays.toString(cmykToRgb(rgbToCmyk[0], rgbToCmyk[1], rgbToCmyk[2], rgbToCmyk[3]))); } catch (IOException e) { e.printStackTrace(); } } } </code></pre>
4,962,416
Preferred way of getting the selected item of a JComboBox
<p>HI,</p> <p>Which is the correct way to get the value from a JComboBox as a String and why is it the correct way. Thanks.</p> <pre><code>String x = JComboBox.getSelectedItem().toString(); </code></pre> <p>or</p> <pre><code>String x = (String)JComboBox.getSelectedItem(); </code></pre>
4,962,444
6
1
null
2011-02-10 20:40:56.487 UTC
12
2017-03-11 22:23:27.2 UTC
2011-02-10 21:09:49.663 UTC
null
276,052
null
489,041
null
1
33
java|swing
137,298
<p>If you have only put (non-null) <code>String</code> references in the JComboBox, then either way is fine.</p> <p>However, the first solution would also allow for future modifications in which you insert <code>Integer</code>s, <code>Doubles</code>s, <code>LinkedList</code>s etc. as items in the combo box.</p> <p>To be robust against <code>null</code> values (still without casting) you may consider a third option:</p> <pre><code>String x = String.valueOf(JComboBox.getSelectedItem()); </code></pre>
5,217,601
when do you need .ascx files and how would you use them?
<p>When building a website, when would it be a good idea to use .ascx files? What exactly is the .ascx and what is it used for? Examples would help a lot thanks!</p>
5,217,627
7
0
null
2011-03-07 08:51:55.217 UTC
22
2022-09-22 16:49:03.967 UTC
null
null
null
null
372,519
null
1
106
c#|asp.net
129,623
<p>It's an extension for the <a href="http://msdn.microsoft.com/en-us/library/y6wb1a0e.aspx" rel="noreferrer"><strong>User Controls</strong></a> you have in your project.</p> <blockquote> <p>A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit. </p> </blockquote> <p>Simply, if you want to have some <strong>functionality</strong> that will be used on many pages in your project then you should create a User control or Composite control and use it in your pages. It just helps you to keep the same functionality and code in one place. And it makes it <strong>reusable</strong>.</p>
5,379,752
CSS: Style external links
<p>I want to style all external links in my website (Wordpress). I'm trying with:</p> <pre><code>.post p a[href^="http://"]:after </code></pre> <p>But Wordpress put the entire url in the links... So, how could I style all links that doesn't start with <a href="http://www.mywebsite.com" rel="noreferrer">http://www.mywebsite.com</a> ?</p> <p>Thank you.</p>
5,379,820
8
0
null
2011-03-21 15:23:20.517 UTC
17
2022-01-14 02:07:34.53 UTC
2012-04-04 13:38:23.51 UTC
null
106,224
null
669,669
null
1
41
css|url|css-selectors|uri|href
17,903
<h3>2021 Solution</h3> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a[href]:not(:where( /* exclude hash only links */ [href^="#"], /* exclude relative but not double slash only links */ [href^="/"]:not([href^="//"]), /* domains to exclude */ [href*="//stackoverflow.com"], /* subdomains to exclude */ [href*="//meta.stackoverflow.com"], )):after { content: '↗️'; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;strong&gt;Internal sites:&lt;/strong&gt; &lt;br&gt;Lorem &lt;a href="http://stackoverflow.com"&gt;http://stackoverflow.com&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="/a/5379820"&gt;/a/5379820&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="//stackoverflow.com/a/5379820"&gt;//stackoverflow.com/a/5379820&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="http://stackoverflow.com/a/5379820"&gt;http://stackoverflow.com/a/5379820&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="https://stackoverflow.com/a/5379820"&gt;https://stackoverflow.com/a/5379820&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="https://meta.stackoverflow.com/"&gt;https://meta.stackoverflow.com/&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="ftp://stackoverflow.com"&gt;ftp://stackoverflow.com&lt;/a&gt; ipsum &lt;br&gt;&lt;br&gt; &lt;strong&gt;External sites:&lt;/strong&gt; &lt;br&gt;Lorem &lt;a href="ftp://google.com"&gt;ftp://google.com&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="https://google.com"&gt;https://google.com&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="http://google.com"&gt;http://google.com&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="https://www.google.com/search?q=stackoverflow"&gt;https://www.google.com/search?q=stackoverflow&lt;/a&gt; &lt;br&gt;Lorem &lt;a href="//www.google.com/search?q=stackoverflow"&gt;//www.google.com/search?q=stackoverflow&lt;/a&gt; &lt;br&gt;&lt;br&gt; &lt;strong&gt;Other anchor types&lt;/strong&gt; &lt;br&gt;Lorem &lt;a&gt;no-href&lt;/a&gt; ipsum &lt;br&gt;Lorem &lt;a href="#hash"&gt;#hash&lt;/a&gt; ipsum</code></pre> </div> </div> </p> <h3>2014 Solution</h3> <p>Using some special CSS syntax you can easily do this. Here is one way that should work for both the HTTP and HTTPS protocols:</p> <pre><code>a[href^=&quot;http://&quot;]:not([href*=&quot;stackoverflow.com&quot;]):after, a[href^=&quot;https://&quot;]:not([href*=&quot;stackoverflow.com&quot;]):after { content: '↗️'; } </code></pre>