input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Can I convert a C# string value to an escaped string literal? <p>In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.</p> <p>If this code:</p> <pre><code>Console.WriteLine(someString); </code></pre> <p>produces:</p> <pre><code>Hello World! </code></pre> <p>I want this code:</p> <pre><code>Console.WriteLine(ToLiteral(someString)); </code></pre> <p>to produce:</p> <pre><code>\tHello\r\n\tWorld!\r\n </code></pre>
<p>There's a method for this in <a href="https://en.wikipedia.org/wiki/.NET_Compiler_Platform" rel="noreferrer">Roslyn</a>'s <a href="https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/" rel="noreferrer">Microsoft.CodeAnalysis.CSharp</a> package on NuGet:</p> <pre class="lang-cs prettyprint-override"><code>private static string ToLiteral(string valueTextForCompiler) { return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false); } </code></pre> <p>Obviously, this didn't exist at the time of the original question, but it might help people who end up here from Google Search.</p>
{ "question_id": 323640, "question_date": "2008-11-27T12:39:36.977Z", "question_score": 218, "tags": "c#|string|escaping", "answer_id": 58825732, "answer_date": "2019-11-12T19:50:58.523Z", "answer_score": 26 }
Please answer the following Stack Overflow question: Title: Plotting in a non-blocking way with Matplotlib <p>I am having problems trying to make matplotlib plot a function without blocking execution.</p> <p>I have tried using <code>show(block=False)</code> as some people suggest, but all I get is a frozen window. If I simply call <code>show()</code>, the result is plotted properly but execution is blocked until the window is closed. From other threads I've read, I suspect that whether <code>show(block=False)</code> works or not depends on the backend. Is this correct? My backend is Qt4Agg. Could you have a look at my code and tell me if you see something wrong? Here is my code.</p> <pre><code>from math import * from matplotlib import pyplot as plt print(plt.get_backend()) def main(): x = range(-50, 51, 1) for pow in range(1,5): # plot x^1, x^2, ..., x^4 y = [Xi**pow for Xi in x] print(y) plt.plot(x, y) plt.draw() #plt.show() #this plots correctly, but blocks execution. plt.show(block=False) #this creates an empty frozen window. _ = raw_input(&quot;Press [enter] to continue.&quot;) if __name__ == '__main__': main() </code></pre> <p>PS. I forgot to say that I would like to update the existing window every time I plot something, instead of creating a new one.</p>
<p>I spent a long time looking for solutions, and found <a href="https://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib">this answer</a>.</p> <p>It looks like, in order to get what you (and I) want, you need the combination of <code>plt.ion()</code>, <code>plt.show()</code> (not with <code>block=False</code>) and, most importantly, <code>plt.pause(.001)</code> (or whatever time you want). The <a href="http://nullege.com/codes/search/matplotlib.pyplot.pause" rel="noreferrer">pause</a> is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.</p> <p>Here's an implementation that works for me on python 3.5: </p> <pre><code>import numpy as np from matplotlib import pyplot as plt def main(): plt.axis([-50,50,0,10000]) plt.ion() plt.show() x = np.arange(-50, 51) for pow in range(1,5): # plot x^1, x^2, ..., x^4 y = [Xi**pow for Xi in x] plt.plot(x, y) plt.draw() plt.pause(0.001) input("Press [enter] to continue.") if __name__ == '__main__': main() </code></pre>
{ "question_id": 28269157, "question_date": "2015-02-01T23:23:00.960Z", "question_score": 218, "tags": "python|matplotlib|plot", "answer_id": 33050617, "answer_date": "2015-10-10T05:22:46.790Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: How to Use slideDown (or show) function on a table row? <p>I'm trying to add a row to a table and have that row slide into view, however the slidedown function seems to be adding a display:block style to the table row which messes up the layout.</p> <p>Any ideas how to work around this?</p> <p>Here's the code:</p> <pre><code>$.get('/some_url', { 'val1': id }, function (data) { var row = $('#detailed_edit_row'); row.hide(); row.html(data); row.slideDown(1000); } ); </code></pre>
<p>Animations are not supported on table rows.</p> <p>From "Learning jQuery" by Chaffer and Swedberg</p> <hr> <blockquote> <p>Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.</p> </blockquote> <hr> <p>You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.</p>
{ "question_id": 467336, "question_date": "2009-01-21T22:36:54.370Z", "question_score": 218, "tags": "jquery|animation|html-table|slidedown", "answer_id": 920480, "answer_date": "2009-05-28T11:49:53.397Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: How to find an available port? <p>I want to start a server which listen to a port. I can specify port explicitly and it works. But I would like to find a port in an automatic way. In this respect I have two questions.</p> <ol> <li><p>In which range of port numbers should I search for? (I used ports 12345, 12346, and 12347 and it was fine).</p></li> <li><p>How can I find out if a given port is not occupied by another software?</p></li> </ol>
<p>If you don't mind the port used, specify a port of 0 to the <a href="http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#ServerSocket%28int%29" rel="noreferrer">ServerSocket constructor</a> and it will listen on any free port.</p> <pre><code>ServerSocket s = new ServerSocket(0); System.out.println("listening on port: " + s.getLocalPort()); </code></pre> <p>If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:</p> <pre><code>public ServerSocket create(int[] ports) throws IOException { for (int port : ports) { try { return new ServerSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found"); } </code></pre> <p>Could be used like so:</p> <pre><code>try { ServerSocket s = create(new int[] { 3843, 4584, 4843 }); System.out.println("listening on port: " + s.getLocalPort()); } catch (IOException ex) { System.err.println("no available ports"); } </code></pre>
{ "question_id": 2675362, "question_date": "2010-04-20T13:16:08.847Z", "question_score": 218, "tags": "java|networking|sockets|port", "answer_id": 2675416, "answer_date": "2010-04-20T13:24:35.900Z", "answer_score": 311 }
Please answer the following Stack Overflow question: Title: How to check if any flags of a flag combination are set? <p>Let's say I have this enum:</p> <pre><code>[Flags] enum Letters { A = 1, B = 2, C = 4, AB = A | B, All = A | B | C, } </code></pre> <p>To check if for example <code>AB</code> is set I can do this:</p> <pre><code>if((letter &amp; Letters.AB) == Letters.AB) </code></pre> <p>Is there a simpler way to check if any of the flags of a combined flag constant are set than the following?</p> <pre><code>if((letter &amp; Letters.A) == Letters.A || (letter &amp; Letters.B) == Letters.B) </code></pre> <p>Could one for example swap the <code>&amp;</code> with something?</p>
<p>If you want to know if letter has any of the letters in AB you must use the <strong>AND</strong> <code>&amp;</code> operator. Something like:</p> <pre><code>if ((letter &amp; Letters.AB) != 0) { // Some flag (A,B or both) is enabled } else { // None of them are enabled } </code></pre>
{ "question_id": 1339976, "question_date": "2009-08-27T09:44:00.163Z", "question_score": 218, "tags": "c#|enums|flags", "answer_id": 1340003, "answer_date": "2009-08-27T09:48:58.437Z", "answer_score": 177 }
Please answer the following Stack Overflow question: Title: Match exact string <p>What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.</p> <p>For example, if I'm trying to match for <code>abc</code>, then <code>1abc1</code>, <code>1abc</code>, and <code>abc1</code> would not match.</p>
<p>Use the start and end delimiters: <code>^abc$</code></p>
{ "question_id": 6298566, "question_date": "2011-06-09T20:03:09.103Z", "question_score": 218, "tags": "javascript|regex", "answer_id": 6298587, "answer_date": "2011-06-09T20:04:31.333Z", "answer_score": 404 }
Please answer the following Stack Overflow question: Title: What does CultureInfo.InvariantCulture mean? <p>I have a string of text like so:</p> <pre><code>var foo = "FooBar"; </code></pre> <p>I want to declare a second string called <code>bar</code> and make this equal to first and fourth character of my first <code>foo</code>, so I do this like so:</p> <pre><code>var bar = foo[0].ToString() + foo[3].ToString(); </code></pre> <p>This works as expected, but <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> is advising me to put <code>Culture.InvariantCulture</code> inside my brackets, so this line ends up like so:</p> <pre><code>var bar = foo[0].ToString(CultureInfo.InvariantCulture) + foo[3].ToString(CultureInfo.InvariantCulture); </code></pre> <p>What does this mean, and will it affect how my program runs?</p>
<p>Not all cultures use the same format for dates and decimal / currency values.</p> <p>This will matter for you when you are converting input values <em>(read)</em> that are stored as strings to <code>DateTime</code>, <code>float</code>, <code>double</code> or <code>decimal</code>. It will also matter if you try to format the aforementioned data types to strings <em>(write)</em> for display or storage.</p> <p>If you know what specific culture that your dates and decimal / currency values will be in ahead of time, you can use that specific <code>CultureInfo</code> property (i.e. <code>CultureInfo("en-GB")</code>). For example if you expect a user input.</p> <p><strong>The <code>CultureInfo.InvariantCulture</code> property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.</strong></p> <p><em>The default value is <code>CultureInfo.InstalledUICulture</code> so the default CultureInfo is depending on the executing OS's settings. This is why you should always make sure the culture info fits your intention (see <a href="https://stackoverflow.com/a/14418644/2822719">Martin's answer</a> for a good guideline).</em></p> <ul> <li><a href="http://geekswithblogs.net/kobush/archive/2007/09/16/avoidcommonglobalizationerrors.aspx" rel="noreferrer">CultureInfo.InvariantCulture Example</a></li> <li><a href="https://stackoverflow.com/questions/2583362/how-to-convert-string-to-double-with-proper-cultureinfo">CultureInfo.InvariantCulture on StackOverflow</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/4c5zdc6a%28v=vs.100%29.aspx" rel="noreferrer">CultureInfo.InvariantCulture MSDN Article</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx" rel="noreferrer">Predefined CultureInfo Names</a></li> </ul>
{ "question_id": 9760237, "question_date": "2012-03-18T16:54:27.237Z", "question_score": 218, "tags": ".net|resharper", "answer_id": 9760339, "answer_date": "2012-03-18T17:10:29.647Z", "answer_score": 191 }
Please answer the following Stack Overflow question: Title: How can I make an entire HTML form "readonly"? <p>I have two pages with HTML forms. The first page has a submission form, and the second page has an acknowledgement form. The first form offers a choice of many controls, while the second page displays the data from the submission form again with a confirmation message. On this second form all fields must be static.</p> <p>From what I can see, some form controls can be <code>readonly</code> and all can be <code>disabled</code>, the difference being that you can still tab to a readonly field.</p> <p>Rather than doing this field by field is there any way to mark the whole form as readonly/disabled/static such that the user can't alter any of the controls?</p>
<p>Wrap the input fields and other stuff into a <code>&lt;fieldset&gt;</code> and give it the <code>disabled="disabled"</code> attribute.</p> <p>Example (<a href="http://jsfiddle.net/7qGHN/" rel="noreferrer">http://jsfiddle.net/7qGHN/</a>):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;fieldset disabled="disabled"&gt; &lt;input type="text" name="something" placeholder="enter some text" /&gt; &lt;select&gt; &lt;option value="0" disabled="disabled" selected="selected"&gt;select somethihng&lt;/option&gt; &lt;option value="1"&gt;woot&lt;/option&gt; &lt;option value="2"&gt;is&lt;/option&gt; &lt;option value="3"&gt;this&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
{ "question_id": 3507958, "question_date": "2010-08-18T00:08:33.607Z", "question_score": 218, "tags": "html", "answer_id": 17186342, "answer_date": "2013-06-19T08:24:17.550Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: How to set entire application in portrait mode only? <p>How do I set it so the application is running in portrait mode only? I want the landscape mode to be disabled while the application is running. How do I do it programmatically?</p>
<h3>For any Android version</h3> <em>From XML</em> <p>You can specify <code>android:screenOrientation="portrait"</code> for each activity in your manifest.xml file. You cannot specify this option on the <code>application</code> tag.</p> <em>From Java</em> <p>Other option is to do it programmatically, for example in an <code>Activity</code> base class:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } </code></pre> <h3>For Android 4+ (API 14+)</h3> <p>Last option is to do it with activity lifecycle listeners which is only available since Android 4.0 (API 14+). Everything happens in a custom <code>Application</code> class:</p> <pre><code>@Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() { @Override public void onActivityCreated(Activity a, Bundle savedInstanceState) { a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } }); } </code></pre> <p><code>ActivityLifecycleAdapter</code> is just a helper class you'll need to create which will be an empty implementation of <code>ActivityLifecycleCallbacks</code> (so you don't have to override each and every methods of that interface when you simply need one of them).</p>
{ "question_id": 6745797, "question_date": "2011-07-19T10:35:04.843Z", "question_score": 218, "tags": "android", "answer_id": 6745830, "answer_date": "2011-07-19T10:38:34.550Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: Electron require() is not defined <p>I'm creating an Electron app for my own purpose. My problem is when I'm using node functions inside my HTML page it throws an error of:</p> <blockquote> <p>'require()' is not defined.</p> </blockquote> <p>Is there any way to use Node functionalities in all my HTML pages? If it is possible please give me an example of how to do this or provide a link. Here are the variables I'm trying to use in my HTML page:</p> <pre><code> var app = require('electron').remote; var dialog = app.dialog; var fs = require('fs'); </code></pre> <p>and these are the values I'm using in all my HTML windows within Electron.</p>
<p>As of version 5, the default for <code>nodeIntegration</code> changed from true to false. You can enable it when creating the Browser Window:</p> <pre class="lang-js prettyprint-override"><code>app.on('ready', () =&gt; { mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false, } }); }); </code></pre>
{ "question_id": 44391448, "question_date": "2017-06-06T13:32:19.083Z", "question_score": 218, "tags": "javascript|html|node.js|electron", "answer_id": 55908510, "answer_date": "2019-04-29T17:53:37.923Z", "answer_score": 479 }
Please answer the following Stack Overflow question: Title: How to merge a transparent png image with another image using PIL <p>I have a transparent png image "foo.png" and I've opened another image with </p> <pre><code>im = Image.open("foo2.png"); </code></pre> <p>now what i need is to merge foo.png with foo2.png.</p> <p>( foo.png contains some text and I want to print that text on foo2.png )</p>
<pre><code>from PIL import Image background = Image.open(&quot;test1.png&quot;) foreground = Image.open(&quot;test2.png&quot;) background.paste(foreground, (0, 0), foreground) background.show() </code></pre> <p>First parameter to <code>.paste()</code> is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a <strong>mask</strong> that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.</p> <p>Check the <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.paste" rel="noreferrer">docs</a>.</p>
{ "question_id": 5324647, "question_date": "2011-03-16T11:33:59.700Z", "question_score": 218, "tags": "python|image|image-processing|python-imaging-library", "answer_id": 5324782, "answer_date": "2011-03-16T11:48:21.310Z", "answer_score": 422 }
Please answer the following Stack Overflow question: Title: Copy Notepad++ text with formatting? <p>I'm using Notepad++ to write code.</p> <p>How do I copy code in Notepad++ along with its formatting to paste into Microsoft Word? (i.e. syntax highlights, etc)</p>
<p>Here is an image from notepad++ when you select text to copy as html.</p> <p><img src="https://i.stack.imgur.com/fDsn4.png" alt="Notepad++ Plugin: Copy as HTML"></p> <p>and how the formatted text looks like after pasting it in OneNote (similar to any other app that supports "Paste Special"): <img src="https://i.stack.imgur.com/LjyGr.png" alt="How it looks like when importing it"></p>
{ "question_id": 3475790, "question_date": "2010-08-13T10:00:09.640Z", "question_score": 218, "tags": "notepad++|syntax-highlighting", "answer_id": 5106990, "answer_date": "2011-02-24T15:51:26.357Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: How to add MVC5 to Visual Studio 2013? <p>I'm starting a new project, and would like to give a try to MVC 5 (I have built a web app using MVC 4 before).</p> <p>In Visual Studio 2013, I click the New Project and navigate to Visual C# > Web > Visual Studio 2012 (even though I have installed VS 2013 it says 2012 in the menu) and on that list I only have MVC 4 application - not 5.</p> <p>The framework in the drop down menu is set to .NET Framework 4.5.1 - and still nothing.</p> <p>I've checked Tools > Extensions and Update and searched for MVC 5 - but it doesn't find anything official from Microsoft.</p> <p>How can I add MVC 5 to my Visual Studio 2013?</p> <p>Thank you</p>
<p>Visual Studio 2013 no longer has separate project types for different ASP.Net features.</p> <p>You must select .NET Framework 4.5 (or higher) in order to see the ASP.NET Web Application template (For ASP.NET One).<br> So just select Visual C# > Web > ASP.NET Web Application, then select the MVC checkbox in the next step.</p> <p><em>Note: Make sure not to select the C# > Web > <strong>Visual Studio 2012</strong> sub folder.</em> </p>
{ "question_id": 21096746, "question_date": "2014-01-13T16:47:54.333Z", "question_score": 218, "tags": "visual-studio-2013|asp.net-mvc-5", "answer_id": 21096806, "answer_date": "2014-01-13T16:50:41.917Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How to remove a virtualenv created by "pipenv run" <p>I am learning Python virtual environment. In one of my small projects I ran</p> <pre><code>pipenv run python myproject.py </code></pre> <p>and it created a virtualenv for me in <code>C:\Users\USERNAME\.virtualenvs</code></p> <p>I found it also created or modified some files under my project source code directory. I am just wondering how to cleanly delete this virtualenv and reverse my project back to a no-virtualenv state.</p> <p>I am using python 3.6.4, and PyCharm.</p>
<p>You can run the <code>pipenv</code> command with the <code>--rm</code> option as in:</p> <pre><code>pipenv --rm </code></pre> <p>This will remove the virtualenv created for you under ~/.virtualenvs</p> <p>See <a href="https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm" rel="noreferrer">https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm</a></p>
{ "question_id": 48256391, "question_date": "2018-01-15T02:58:16.267Z", "question_score": 218, "tags": "pipenv", "answer_id": 48431669, "answer_date": "2018-01-24T21:12:14.937Z", "answer_score": 475 }
Please answer the following Stack Overflow question: Title: make arrayList.toArray() return more specific types <p>So, normally <code>ArrayList.toArray()</code> would return a type of <code>Object[]</code>....but supposed it's an <code>Arraylist</code> of object <code>Custom</code>, how do I make <code>toArray()</code> to return a type of <code>Custom[]</code> rather than <code>Object[]</code>?</p>
<p>Like this:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(); String[] a = list.toArray(new String[0]); </code></pre> <p>Before Java6 it was recommended to write:</p> <pre><code>String[] a = list.toArray(new String[list.size()]); </code></pre> <p>because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see <a href="https://stackoverflow.com/questions/174093">.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?</a></p> <p>If your list is not properly typed you need to do a cast before calling toArray. Like this:</p> <pre><code> List l = new ArrayList&lt;String&gt;(); String[] a = ((List&lt;String&gt;)l).toArray(new String[l.size()]); </code></pre>
{ "question_id": 5061640, "question_date": "2011-02-21T02:07:10.953Z", "question_score": 218, "tags": "java|arrays|object|types|arraylist", "answer_id": 5061692, "answer_date": "2011-02-21T02:19:32.560Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: SQL Logic Operator Precedence: And and Or <p>Are the two statements below equivalent?</p> <pre><code>SELECT [...] FROM [...] WHERE some_col in (1,2,3,4,5) AND some_other_expr </code></pre> <p>and</p> <pre><code>SELECT [...] FROM [...] WHERE some_col in (1,2,3) or some_col in (4,5) AND some_other_expr </code></pre> <p>Is there some sort of truth table I could use to verify this?</p>
<p><code>And</code> has precedence over <code>Or</code>, so, even if <code>a &lt;=&gt; a1 Or a2</code></p> <pre><code>Where a And b </code></pre> <p>is not the same as</p> <pre><code>Where a1 Or a2 And b, </code></pre> <p>because that would be Executed as </p> <pre><code>Where a1 Or (a2 And b) </code></pre> <p>and what you want, to make them the same, is the following (using parentheses to override rules of precedence):</p> <pre><code> Where (a1 Or a2) And b </code></pre> <p>Here's an example to illustrate:</p> <pre><code>Declare @x tinyInt = 1 Declare @y tinyInt = 0 Declare @z tinyInt = 0 Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F </code></pre> <p>For those who like to consult references (in alphabetic order):</p> <ul> <li><a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql?view=sql-server-2017" rel="noreferrer">Microsoft Transact-SQL operator precedence</a> </li> <li><a href="https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html" rel="noreferrer">Oracle MySQL 9 operator precedence</a></li> <li><a href="https://docs.oracle.com/cd/B19306_01/server.102/b14200/conditions001.htm#i1034834" rel="noreferrer">Oracle 10g condition precedence</a></li> <li><a href="https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-PRECEDENCE" rel="noreferrer">PostgreSQL operator Precedence</a></li> <li><a href="https://www.sqlite.org/lang_expr.html" rel="noreferrer">SQL as understood by SQLite</a></li> </ul>
{ "question_id": 1241142, "question_date": "2009-08-06T20:15:22.597Z", "question_score": 218, "tags": "sql|logical-operators|operator-precedence", "answer_id": 1241158, "answer_date": "2009-08-06T20:19:50.497Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method <p>I have a simple actionmethod, that returns some json. It runs on ajax.example.com. I need to access this from another site someothersite.com.</p> <p>If I try to call it, I get the expected...:</p> <pre><code>Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin. </code></pre> <p>I know of two ways to get around this: <a href="https://stackoverflow.com/questions/5968682/jquery-ajax-json-cross-domain-request-and-asp-net-mvc">JSONP</a> and creating a <a href="http://tpeczek.blogspot.com/2010/09/httphandler-with-cross-origin-resource.html" rel="noreferrer">custom HttpHandler</a> to set the header.</p> <p>Is there no simpler way?</p> <p>Is it not possible for a simple action to either define a list of allowed origins - or simple allow everyone? Maybe an action filter?</p> <p>Optimal would be...:</p> <pre><code>return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe); </code></pre>
<h1>For plain ASP.NET MVC Controllers</h1> <h2>Create a new attribute</h2> <pre><code>public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*"); base.OnActionExecuting(filterContext); } } </code></pre> <h2>Tag your action:</h2> <pre><code>[AllowCrossSiteJson] public ActionResult YourMethod() { return Json("Works better?"); } </code></pre> <h1>For ASP.NET Web API</h1> <pre><code>using System; using System.Web.Http.Filters; public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); base.OnActionExecuted(actionExecutedContext); } } </code></pre> <h2>Tag a whole API controller:</h2> <pre><code>[AllowCrossSiteJson] public class ValuesController : ApiController { </code></pre> <h2>Or individual API calls:</h2> <pre><code>[AllowCrossSiteJson] public IEnumerable&lt;PartViewModel&gt; Get() { ... } </code></pre> <h1>For Internet Explorer &lt;= v9</h1> <p>IE &lt;= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).</p> <p>Download it using nuget <code>corsproxy</code> and follow the included instructions.</p> <p><a href="http://blog.gauffin.org/2014/04/how-to-use-cors-requests-in-internet-explorer-9-and-below/" rel="noreferrer">Blog post</a> | <a href="https://github.com/jgauffin/corsproxy" rel="noreferrer">Source code</a></p>
{ "question_id": 6290053, "question_date": "2011-06-09T08:29:18.883Z", "question_score": 218, "tags": "json|asp.net-mvc-3|cors|asp.net-ajax", "answer_id": 6290385, "answer_date": "2011-06-09T09:00:12.120Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: Visual Studio popup: "the operation could not be completed" <p>When I try to open a project, local or on a <a href="https://en.wikipedia.org/wiki/Team_Foundation_Server" rel="noreferrer">Team Foundation Server</a> (TFS), I get a modal window telling me that:</p> <blockquote> <p>The operation could not be completed: Unspecified error</p> </blockquote> <p>Or the same message, but with "Class not defined.." instead of "Unspecified error".</p> <p>These errors started happening earlier today when I tried to check in some of my work to the team foundation server. I have tried using Visual&nbsp;Studio&nbsp;2008 on the same computer, but I still get the same error. I've also googled for it but none of the solutions seems to help me.</p> <p>I have installed the latest updates from Windows Update as well.</p> <p>Any ideas?</p>
<p>Have you tried to <strong>delete the <code>Your_Solution_FileName.suo</code></strong> file? </p> <p>The <code>.suo</code> file should be in the same folder as your <code>.sln</code> file, or in the <code>.vs</code> folder for newer versions of Visual Studio. The <code>.vs</code> folder might be hidden.</p> <hr> <p><strong>Update for Visual Studio 2017</strong><br> In VS 2017 the <code>.suo</code> files are located in a different folder: you can find the <code>.suo</code> file in <strong><code>YourSolutionFolder\.vs\YourSolutionName\v15\.suo</code></strong> </p> <p>The <code>.vs</code> folder is hidden, and the <code>.suo</code> files is a file without name, with just the <code>.suo</code> extension. </p> <hr> <p> <br> <strong>Explanation</strong></p> <p>The <code>.suo</code> file contain various information like the opened files list, and some preferences that are not saved in the solution file (like the starting project) and other things.</p> <p>Normally you can delete the <code>.suo</code> file without problems. You might have to set the <code>StartUp Project</code> for your solution afterwards.</p> <p>Just to stay on the safe way, you can rename the <code>.suo</code> file, and then retry to start the solution, to see if this help.</p> <p>In my experience sometime VS crash on start because there is an error in some source code, and due to that error VS can't compile the code, and then crash because without compiled code it's unable to show form in design mode. In this case, deleting the <code>.suo</code> file will solve the situation because it reset the open files list, so the solution can start up without opening/showing any files.</p> <hr> <p><strong>When deleting the .suo file doesn't works</strong><br> Here's a list of other things you can try when deleting the <code>.suo</code> file doesn't resolve the issue:</p> <ul> <li>Restart the computer</li> <li>Clean Windows temp folder</li> <li>Clean the solution from the IDE (Menu\Build\Clean Solution)</li> <li>Clean the solution manually (delete the compiled DLL/EXE in the <code>/bin/</code> folder and empty the temporary files that VS create during the build process in the <code>/obj/</code> folder (each project that compose the solution has these folders, so clean them all))</li> <li>Try to open each single project that compose the solution 1-by-1 and build it, to understand which is the specific project that generate the issue</li> <li>Understand what is the change/edit/modification that triggered the error, and undo it (source control tool can help...)</li> <li>If you have custom controls: check the code in the constructor. The VS IDE will call the constructor of your custom controls even at design time, and weird things can happen (at design time some properties dont works, your connection string probably isn't populated...)</li> </ul> <p>As a last resort... </p> <ul> <li>Try to install any VS update</li> <li>Try to disable VS extensions (if you installed any...)</li> <li>Try to update any external DLL/Control referenced in your solution</li> <li>Try to update Windows</li> </ul>
{ "question_id": 9079466, "question_date": "2012-01-31T12:25:25.617Z", "question_score": 218, "tags": ".net|visual-studio|visual-studio-2015", "answer_id": 9130257, "answer_date": "2012-02-03T14:32:41.663Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: How can I force a long string without any blank to be wrapped? <p>I have a long string (a DNA sequence). It does not contain any whitespace character.</p> <p>For example:</p> <pre><code>ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA </code></pre> <p>What would be the CSS selector to force this text to be wrapped in a <code>html:textarea</code> or in a <code>xul:textbox</code>?</p>
<p>for block elements:</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-html lang-html prettyprint-override"><code>&lt;textarea style="width:100px; word-wrap:break-word;"&gt; ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC &lt;/textarea&gt;</code></pre> </div> </div> </p> <p>for inline elements:</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-html lang-html prettyprint-override"><code>&lt;span style="width:100px; word-wrap:break-word; display:inline-block;"&gt; ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC &lt;/span&gt;</code></pre> </div> </div> </p>
{ "question_id": 499137, "question_date": "2009-01-31T16:44:16.810Z", "question_score": 218, "tags": "html|css|string|xul|word-wrap", "answer_id": 499154, "answer_date": "2009-01-31T16:53:49.427Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: Illegal pattern character 'T' when parsing a date string to java.util.Date <p>I have a date string and I want to parse it to normal date use the java Date API,the following is my code:</p> <pre><code>public static void main(String[] args) { String date="2010-10-02T12:23:23Z"; String pattern="yyyy-MM-ddThh:mm:ssZ"; SimpleDateFormat sdf=new SimpleDateFormat(pattern); try { Date d=sdf.parse(date); System.out.println(d.getYear()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>However I got an exception: <code>java.lang.IllegalArgumentException: Illegal pattern character 'T'</code></p> <p>So I wonder if I have to split the string and parse it manually?</p> <p>BTW, I have tried to add a single quote character on either side of the T: </p> <pre><code>String pattern="yyyy-MM-dd'T'hh:mm:ssZ"; </code></pre> <p>It also does not work.</p>
<h3>Update for Java 8 and higher</h3> <p>You can now simply do <code>Instant.parse("2015-04-28T14:23:38.521Z")</code> and get the correct thing now, especially since you should be using <code>Instant</code> instead of the broken <code>java.util.Date</code> with the most recent versions of Java. </p> <p>You should be using <code>DateTimeFormatter</code> instead of <code>SimpleDateFormatter</code> as well.</p> <h3>Original Answer:</h3> <blockquote> <p>The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.</p> </blockquote> <h3>This works with the input with the trailing <code>Z</code> as demonstrated:</h3> <blockquote> <p>In the pattern the <code>T</code> is escaped with <code>'</code> on either side. </p> <p>The pattern for the <code>Z</code> at the end is actually <code>XXX</code> as documented in the JavaDoc for <code>SimpleDateFormat</code>, it is just not very clear on actually how to use it since <code>Z</code> is the marker for the old <code>TimeZone</code> information as well.</p> </blockquote> <h3><a href="https://github.com/jarrodhroberson/Stack-Overflow/blob/master/src/main/java/com/stackoverflow/Q2597083.java" rel="noreferrer">Q2597083.java</a></h3> <pre><code>import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; public class Q2597083 { /** * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone. */ public static final TimeZone UTC; /** * @see &lt;a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations"&gt;Combined Date and Time Representations&lt;/a&gt; */ public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; /** * 0001-01-01T00:00:00.000Z */ public static final Date BEGINNING_OF_TIME; /** * 292278994-08-17T07:12:55.807Z */ public static final Date END_OF_TIME; static { UTC = TimeZone.getTimeZone("UTC"); TimeZone.setDefault(UTC); final Calendar c = new GregorianCalendar(UTC); c.set(1, 0, 1, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); BEGINNING_OF_TIME = c.getTime(); c.setTime(new Date(Long.MAX_VALUE)); END_OF_TIME = c.getTime(); } public static void main(String[] args) throws Exception { final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT); sdf.setTimeZone(UTC); System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME)); System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME)); System.out.println("sdf.format(new Date()) = " + sdf.format(new Date())); System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z")); System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z")); System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z")); } } </code></pre> <h3>Produces the following output:</h3> <pre><code>sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z sdf.format(new Date()) = 2015-04-28T14:38:25.956Z sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015 sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1 sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994 </code></pre>
{ "question_id": 2597083, "question_date": "2010-04-08T02:00:06.777Z", "question_score": 218, "tags": "java|date|simpledateformat|iso8601", "answer_id": 2597111, "answer_date": "2010-04-08T02:08:27.113Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: Circle line-segment collision detection algorithm? <p>I have a line from A to B and a circle positioned at C with the radius R. </p> <p><img src="https://i.stack.imgur.com/QpgMZ.png" alt="Image"></p> <p>What is a good algorithm to use to check whether the line intersects the circle? And at what coordinate along the circles edge it occurred?</p>
<p>Taking</p> <ol> <li><strong>E</strong> is the starting point of the ray,</li> <li><strong>L</strong> is the end point of the ray,</li> <li><strong>C</strong> is the center of sphere you're testing against</li> <li><strong>r</strong> is the radius of that sphere</li> </ol> <p>Compute:<br /> <strong>d</strong> = L - E ( Direction vector of ray, from start to end )<br /> <strong>f</strong> = E - C ( Vector from center sphere to ray start )</p> <p>Then the intersection is found by..<br /> Plugging:<br /> <strong>P = E + t * d</strong><br /> This is a parametric equation:<br /> P<sub>x</sub> = E<sub>x</sub> + td<sub>x</sub><br /> P<sub>y</sub> = E<sub>y</sub> + td<sub>y</sub><br /> into<br /> <strong>(x - h)<sup>2</sup> + (y - k)<sup>2</sup> = r<sup>2</sup></strong><br /> (h,k) = center of circle.</p> <blockquote> <p>Note: We've simplified the problem to 2D here, the solution we get applies also in 3D</p> </blockquote> <p><strong>to get:</strong></p> <ol> <li><strong>Expand</strong> x<sup>2</sup> - 2xh + h<sup>2</sup> + y<sup>2</sup> - 2yk + k<sup>2</sup> - r<sup>2</sup> = 0</li> <li><strong>Plug</strong> x = e<sub>x</sub> + td<sub>x</sub><br /> y = e<sub>y</sub> + td<sub>y</sub><br /> ( e<sub>x</sub> + td<sub>x</sub> )<sup>2</sup> - 2( e<sub>x</sub> + td<sub>x</sub> )h + h<sup>2</sup> + ( e<sub>y</sub> + td<sub>y</sub> )<sup>2</sup> - 2( e<sub>y</sub> + td<sub>y</sub> )k + k<sup>2</sup> - r<sup>2</sup> = 0</li> <li><strong>Explode</strong> e<sub>x</sub><sup>2</sup> + 2e<sub>x</sub>td<sub>x</sub> + t<sup>2</sup>d<sub>x</sub><sup>2</sup> - 2e<sub>x</sub>h - 2td<sub>x</sub>h + h<sup>2</sup> + e<sub>y</sub><sup>2</sup> + 2e<sub>y</sub>td<sub>y</sub> + t<sup>2</sup>d<sub>y</sub><sup>2</sup> - 2e<sub>y</sub>k - 2td<sub>y</sub>k + k<sup>2</sup> - r<sup>2</sup> = 0</li> <li><strong>Group</strong> t<sup>2</sup>( d<sub>x</sub><sup>2</sup> + d<sub>y</sub><sup>2</sup> ) + 2t( e<sub>x</sub>d<sub>x</sub> + e<sub>y</sub>d<sub>y</sub> - d<sub>x</sub>h - d<sub>y</sub>k ) + e<sub>x</sub><sup>2</sup> + e<sub>y</sub><sup>2</sup> - 2e<sub>x</sub>h - 2e<sub>y</sub>k + h<sup>2</sup> + k<sup>2</sup> - r<sup>2</sup> = 0</li> <li><strong>Finally,</strong> t<sup>2</sup>( <strong>d</strong> · <strong>d</strong> ) + 2t( <strong>e</strong> · <strong>d</strong> - <strong>d</strong> · <strong>c</strong> ) + <strong>e</strong> · <strong>e</strong> - 2( <strong>e</strong> · <strong>c</strong> ) + <strong>c</strong> · <strong>c</strong> - r<sup>2</sup> = 0<br /> Where <strong>d</strong> is the vector d and · is the dot product.</li> <li><strong>And then,</strong> t<sup>2</sup>( <strong>d</strong> · <strong>d</strong> ) + 2t( <strong>d</strong> · ( <strong>e</strong> - <strong>c</strong> ) ) + ( <strong>e</strong> - <strong>c</strong> ) · ( <strong>e</strong> - <strong>c</strong> ) - r<sup>2</sup> = 0</li> <li><strong>Letting</strong> <strong>f</strong> = <strong>e</strong> - <strong>c</strong> t<sup>2</sup>( <strong>d</strong> · <strong>d</strong> ) + 2t( <strong>d</strong> · <strong>f</strong> ) + <strong>f</strong> · <strong>f</strong> - r<sup>2</sup> = 0</li> </ol> <p>So we get:<br /> t<sup>2</sup> * (<strong>d</strong> · <strong>d</strong>) + 2t*( <strong>f</strong> · <strong>d</strong> ) + ( <strong>f</strong> · <strong>f</strong> - r<sup>2</sup> ) = 0</p> <p>So solving the quadratic equation:</p> <pre><code>float a = d.Dot( d ) ; float b = 2*f.Dot( d ) ; float c = f.Dot( f ) - r*r ; float discriminant = b*b-4*a*c; if( discriminant &lt; 0 ) { // no intersection } else { // ray didn't totally miss sphere, // so there is a solution to // the equation. discriminant = sqrt( discriminant ); // either solution may be on or off the ray so need to test both // t1 is always the smaller value, because BOTH discriminant and // a are nonnegative. float t1 = (-b - discriminant)/(2*a); float t2 = (-b + discriminant)/(2*a); // 3x HIT cases: // -o-&gt; --|--&gt; | | --|-&gt; // Impale(t1 hit,t2 hit), Poke(t1 hit,t2&gt;1), ExitWound(t1&lt;0, t2 hit), // 3x MISS cases: // -&gt; o o -&gt; | -&gt; | // FallShort (t1&gt;1,t2&gt;1), Past (t1&lt;0,t2&lt;0), CompletelyInside(t1&lt;0, t2&gt;1) if( t1 &gt;= 0 &amp;&amp; t1 &lt;= 1 ) { // t1 is the intersection, and it's closer than t2 // (since t1 uses -b - discriminant) // Impale, Poke return true ; } // here t1 didn't intersect so we are either started // inside the sphere or completely past it if( t2 &gt;= 0 &amp;&amp; t2 &lt;= 1 ) { // ExitWound return true ; } // no intn: FallShort, Past, CompletelyInside return false ; } </code></pre>
{ "question_id": 1073336, "question_date": "2009-07-02T09:15:10.203Z", "question_score": 218, "tags": "algorithm|math|line|collision-detection|geometry", "answer_id": 1084899, "answer_date": "2009-07-05T21:54:39.927Z", "answer_score": 223 }
Please answer the following Stack Overflow question: Title: How do you produce a .d.ts "typings" definition file from an existing JavaScript library? <p>I'm using a lot of libraries both my own and 3rd party. I see the "typings" directory contains some for Jquery and WinRT... but how are they created?</p>
<p>There are a few options available for you depending on the library in question, how it's written, and what level of accuracy you're looking for. Let's review the options, in roughly descending order of desirability.</p> <h2>Maybe It Exists Already</h2> <p>Always check DefinitelyTyped (<a href="https://github.com/DefinitelyTyped/DefinitelyTyped" rel="noreferrer">https://github.com/DefinitelyTyped/DefinitelyTyped</a>) first. This is a community repo full of literally thousands of .d.ts files and it's very likely the thing you're using is already there. You should also check TypeSearch (<a href="https://microsoft.github.io/TypeSearch/" rel="noreferrer">https://microsoft.github.io/TypeSearch/</a>) which is a search engine for NPM-published .d.ts files; this will have slightly more definitions than DefinitelyTyped. A few modules are also shipping their own definitions as part of their NPM distribution, so also see if that's the case before trying to write your own.</p> <h2>Maybe You Don't Need One</h2> <p>TypeScript now supports the <code>--allowJs</code> flag and will make more JS-based inferences in .js files. You can try including the .js file in your compilation along with the <code>--allowJs</code> setting to see if this gives you good enough type information. TypeScript will recognize things like ES5-style classes and JSDoc comments in these files, but may get tripped up if the library initializes itself in a weird way.</p> <h2>Get Started With <code>--allowJs</code></h2> <p>If <code>--allowJs</code> gave you decent results and you want to write a better definition file yourself, you can combine <code>--allowJs</code> with <code>--declaration</code> to see TypeScript's "best guess" at the types of the library. This will give you a decent starting point, and may be as good as a hand-authored file if the JSDoc comments are well-written and the compiler was able to find them.</p> <h2>Get Started with dts-gen</h2> <p>If <code>--allowJs</code> didn't work, you might want to use dts-gen (<a href="https://github.com/Microsoft/dts-gen" rel="noreferrer">https://github.com/Microsoft/dts-gen</a>) to get a starting point. This tool uses the runtime shape of the object to accurately enumerate all available properties. On the plus side this tends to be very accurate, but the tool does not yet support scraping the JSDoc comments to populate additional types. You run this like so:</p> <pre><code>npm install -g dts-gen dts-gen -m &lt;your-module&gt; </code></pre> <p>This will generate <code>your-module.d.ts</code> in the current folder.</p> <h2>Hit the Snooze Button</h2> <p>If you just want to do it all later and go without types for a while, in TypeScript 2.0 you can now write</p> <pre><code>declare module "foo"; </code></pre> <p>which will let you <code>import</code> the <code>"foo"</code> module with type <code>any</code>. If you have a global you want to deal with later, just write</p> <pre><code>declare const foo: any; </code></pre> <p>which will give you a <code>foo</code> variable.</p>
{ "question_id": 12687779, "question_date": "2012-10-02T09:29:02.867Z", "question_score": 218, "tags": "typescript|tsc", "answer_id": 12695001, "answer_date": "2012-10-02T17:11:37.150Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: How to specify jackson to only use fields - preferably globally <p>Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.</p> <p>I would like to use the fields as the canonical source of serialization config and thus don't want jackson to look at properties at all.</p> <p>I can do this on an individual class basis with the annotation:</p> <pre><code> @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) </code></pre> <p>But I don't want to have to put this on every single class...</p> <p>Is it possible to configure this globally? Like add some to the Object Mapper?</p>
<p>You can configure individual ObjectMappers like this:</p> <pre><code>ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)); </code></pre> <p>If you want it set globally, I usually access a configured mapper through a wrapper class.</p>
{ "question_id": 7105745, "question_date": "2011-08-18T10:10:31.970Z", "question_score": 218, "tags": "java|json|jackson", "answer_id": 7108530, "answer_date": "2011-08-18T13:53:32.830Z", "answer_score": 183 }
Please answer the following Stack Overflow question: Title: Escape single quote character for use in an SQLite query <p>I wrote the database schema (only one table so far), and the INSERT statements for that table in one file. Then I created the database as follows:</p> <pre><code>$ sqlite3 newdatabase.db SQLite version 3.4.0 Enter ".help" for instructions sqlite&gt; .read ./schema.sql SQL error near line 16: near "s": syntax error </code></pre> <p>Line 16 of my file looks something like this:</p> <pre><code>INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there\'s'); </code></pre> <p>The problem is the escape character for a single quote. I also tried double escaping the single quote (using <code>\\\'</code> instead of <code>\'</code>), but that didn't work either. What am I doing wrong?</p>
<p>Try doubling up the single quotes (many databases expect it that way), so it would be :</p> <pre><code>INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s'); </code></pre> <p>Relevant quote from <a href="http://www.sqlite.org/lang_expr.html" rel="noreferrer">the documentation</a>:</p> <blockquote> <p>A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. BLOB literals are string literals containing hexadecimal data and preceded by a single "x" or "X" character. ... A literal value can also be the token "NULL". </p> </blockquote>
{ "question_id": 603572, "question_date": "2009-03-02T19:12:36.583Z", "question_score": 218, "tags": "sqlite|escaping", "answer_id": 603579, "answer_date": "2009-03-02T19:14:43.257Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: How to pass arguments and redirect stdin from a file to program run in gdb? <p>I usually run a program as :</p> <pre><code>./a.out arg1 arg2 &lt;file </code></pre> <p>I would like to debug it using gdb.</p> <p>I am aware of the <code>set args</code> functionality, but that only works from the gdb prompt.</p>
<p>Pass the arguments to the <code>run</code> command from within gdb.</p> <pre><code>$ gdb ./a.out (gdb) r &lt; t Starting program: /dir/a.out &lt; t </code></pre>
{ "question_id": 4521015, "question_date": "2010-12-23T17:20:31.697Z", "question_score": 218, "tags": "c++|debugging|gdb", "answer_id": 4521023, "answer_date": "2010-12-23T17:21:29.047Z", "answer_score": 148 }
Please answer the following Stack Overflow question: Title: How to use the 'main' parameter in package.json? <p>I have done quite some search already. However, still having doubts about the 'main' parameter in the package.json of a Node project.</p> <ol> <li>How would filling in this field help? Asking in another way, can I start the module in a different style if this field presents?</li> <li>Can I have more than one script filled into the main parameter? If yes, would they be started as two threads? If no, how can I start two scripts in a module and having them run in parallel?</li> </ol> <p>I know that the second question is quite weird. It is because I have hosted a Node.js application on OpenShift but the application consists of two main components. One being a REST API and one being a notification delivering service.</p> <p>I am afraid that the notification delivering process would block the REST API if they were implemented as a single thread. However, they have to connect to the same MongoDB cartridge. Moreover, I would like to save one gear if both the components could be serving in the same gear if possible.</p> <p>Any suggestions are welcome.</p>
<p>From <a href="https://docs.npmjs.com/files/package.json#main">the npm documentation</a>:</p> <blockquote> <p>The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.</p> <p>This should be a module ID relative to the root of your package folder.</p> <p>For most modules, it makes the most sense to have a main script and often not much else.</p> </blockquote> <p>To put it short:</p> <ol> <li>You only need a <code>main</code> parameter in your <code>package.json</code> if the entry point to your package differs from <code>index.js</code> in its root folder. For example, people often put the entry point to <code>lib/index.js</code> or <code>lib/&lt;packagename&gt;.js</code>, in this case the corresponding script must be described as <code>main</code> in <code>package.json</code>.</li> <li>You can't have two scripts as <code>main</code>, simply because the entry point <code>require('yourpackagename')</code> must be defined unambiguously.</li> </ol>
{ "question_id": 22512992, "question_date": "2014-03-19T16:59:26.960Z", "question_score": 218, "tags": "javascript|node.js|rest|asynchronous", "answer_id": 22513200, "answer_date": "2014-03-19T17:07:59.757Z", "answer_score": 199 }
Please answer the following Stack Overflow question: Title: How to do a non-greedy match in grep? <p>I want to grep the shortest match and the pattern should be something like:</p> <pre><code>&lt;car ... model=BMW ...&gt; ... ... ... &lt;/car&gt; </code></pre> <p>... means any character and the input is multiple lines. </p>
<p>You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier <code>?</code> after the quantifier. For example you can change <code>.*</code> to <code>.*?</code>.</p> <p>By default <code>grep</code> doesn't support non-greedy modifiers, but you can use <code>grep -P</code> to use the Perl syntax.</p>
{ "question_id": 3027518, "question_date": "2010-06-12T04:43:59.880Z", "question_score": 218, "tags": "regex|shell|command-line|grep|regex-greedy", "answer_id": 3027524, "answer_date": "2010-06-12T04:47:31.717Z", "answer_score": 347 }
Please answer the following Stack Overflow question: Title: How to execute XPath one-liners from shell? <p>Is there a package out there, for Ubuntu and/or CentOS, that has a command-line tool that can execute an XPath one-liner like <code>foo //element@attribute filename.xml</code> or <code>foo //element@attribute &lt; filename.xml</code> and return the results line by line?</p> <p>I'm looking for something that would allow me to just <code>apt-get install foo</code> or <code>yum install foo</code> and then just works out-of-the-box, no wrappers or other adaptation necessary.</p> <p>Here are some examples of things that come close:</p> <p>Nokogiri. If I write this wrapper I could call the wrapper in the way described above:</p> <pre><code>#!/usr/bin/ruby require 'nokogiri' Nokogiri::XML(STDIN).xpath(ARGV[0]).each do |row| puts row end </code></pre> <p>XML::XPath. Would work with this wrapper:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use XML::XPath; my $root = XML::XPath-&gt;new(ioref =&gt; 'STDIN'); for my $node ($root-&gt;find($ARGV[0])-&gt;get_nodelist) { print($node-&gt;getData, "\n"); } </code></pre> <p><code>xpath</code> from XML::XPath returns too much noise, <code>-- NODE --</code> and <code>attribute = "value"</code>.</p> <p><code>xml_grep</code> from XML::Twig cannot handle expressions that do not return elements, so cannot be used to extract attribute values without further processing.</p> <p>EDIT:</p> <p><code>echo cat //element/@attribute | xmllint --shell filename.xml</code> returns noise similar to <code>xpath</code>.</p> <p><code>xmllint --xpath //element/@attribute filename.xml</code> returns <code>attribute = "value"</code>.</p> <p><code>xmllint --xpath 'string(//element/@attribute)' filename.xml</code> returns what I want, but only for the first match.</p> <p>For another solution almost satisfying the question, here is an XSLT that can be used to evaluate arbitrary XPath expressions (requires dyn:evaluate support in the XSLT processor):</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:dyn="http://exslt.org/dynamic" extension-element-prefixes="dyn"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="no" method="text"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="dyn:evaluate($pattern)"&gt; &lt;xsl:value-of select="dyn:evaluate($value)"/&gt; &lt;xsl:value-of select="'&amp;#10;'"/&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Run with <code>xsltproc --stringparam pattern //element/@attribute --stringparam value . arbitrary-xpath.xslt filename.xml</code>.</p>
<p>You should try these tools :</p> <ul> <li><code>xmlstarlet</code> (<a href="http://xmlstar.sourceforge.net/" rel="nofollow noreferrer">xmlstarlet page</a>) : can edit, select, transform... Not installed by default, xpath1</li> <li><code>xmllint</code> (<a href="http://xmlsoft.org/xmllint.html" rel="nofollow noreferrer">man xmllint</a>): often installed by default with <code>libxml2-utils</code>, xpath1 (check my <a href="https://github.com/sputnick-dev/xmllint" rel="nofollow noreferrer">wrapper</a> to have <code>--xpath</code> switch on very old releases and newlines delimited output (v &lt; 2.9.9)). Can be used as interactive shell with the <code>--shell</code> switch.</li> <li><code>xpath</code> : installed via perl's module <a href="https://metacpan.org/pod/XML::XPath" rel="nofollow noreferrer"><code>XML::Xpath</code></a>, xpath1</li> <li><code>xml_grep</code> : installed via perl's module <a href="http://search.cpan.org/dist/XML-Twig/" rel="nofollow noreferrer"><code>XML::Twig</code></a>, xpath1 (limited xpath usage)</li> <li><code>xidel</code> (<a href="http://videlibri.sourceforge.net/xidel.html" rel="nofollow noreferrer">xidel</a>): xpath3</li> <li><code>saxon-lint</code> (<a href="https://github.com/sputnick-dev/saxon-lint" rel="nofollow noreferrer">saxon-lint</a>): my own project, wrapper over @Michael Kay's Saxon-HE Java library, xpath3: using <a href="http://sourceforge.net/projects/saxon/" rel="nofollow noreferrer">SaxonHE 9.6</a> ,<a href="http://www.w3.org/TR/xpath-functions-30" rel="nofollow noreferrer">XPath 3.x</a> (+retro compatibility)</li> </ul> <p><strong>Examples:</strong></p> <pre><code>xmllint --xpath '//element/@attribute' file.xml xmlstarlet sel -t -v &quot;//element/@attribute&quot; file.xml xpath -q -e '//element/@attribute' file.xml xidel -se '//element/@attribute' file.xml saxon-lint --xpath '//element/@attribute' file.xml </code></pre>
{ "question_id": 15461737, "question_date": "2013-03-17T14:16:47.200Z", "question_score": 218, "tags": "xml|shell|xpath|cross-platform", "answer_id": 15461774, "answer_date": "2013-03-17T14:19:46.490Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: Java 8 stream's .min() and .max(): why does this compile? <p>Note: this question originates from a dead link which was a previous SO question, but here goes...</p> <p>See this code (<strong>note: I do know that this code won't "work" and that <code>Integer::compare</code> should be used -- I just extracted it from the linked question</strong>):</p> <pre><code>final ArrayList &lt;Integer&gt; list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList()); System.out.println(list.stream().max(Integer::max).get()); System.out.println(list.stream().min(Integer::min).get()); </code></pre> <p>According to the javadoc of <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#min-java.util.Comparator-" rel="noreferrer"><code>.min()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#max-java.util.Comparator-" rel="noreferrer"><code>.max()</code></a>, the argument of both should be a <code>Comparator</code>. Yet here the method references are to static methods of the <a href="http://download.java.net/jdk8/docs/api/java/lang/Integer.html" rel="noreferrer"><code>Integer</code></a> class.</p> <p>So, why does this compile at all?</p>
<p>Let me explain what is happening here, because it isn't obvious!</p> <p>First, <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#max-java.util.Comparator-" rel="noreferrer"><code>Stream.max()</code></a> accepts an instance of <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> so that items in the stream can be compared against each other to find the minimum or maximum, in some optimal order that you don't need to worry too much about.</p> <p>So the question is, of course, why is <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#max-int-int-" rel="noreferrer"><code>Integer::max</code></a> accepted? After all it's not a comparator!</p> <p>The answer is in the way that the new lambda functionality works in Java 8. It relies on a concept which is informally known as "single abstract method" interfaces, or "SAM" interfaces. The idea is that any interface with one abstract method can be automatically implemented by any lambda - or method reference - whose method signature is a match for the one method on the interface. So examining the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a> interface (simple version):</p> <pre><code>public Comparator&lt;T&gt; { T compare(T o1, T o2); } </code></pre> <p>If a method is looking for a <code>Comparator&lt;Integer&gt;</code>, then it's essentially looking for this signature:</p> <pre><code>int xxx(Integer o1, Integer o2); </code></pre> <p>I use "xxx" <strong>because the method name is not used for matching purposes</strong>.</p> <p>Therefore, both <code>Integer.min(int a, int b)</code> and <code>Integer.max(int a, int b)</code> are close enough that autoboxing will allow this to appear as a <code>Comparator&lt;Integer&gt;</code> in a method context.</p>
{ "question_id": 22561614, "question_date": "2014-03-21T14:31:13.837Z", "question_score": 218, "tags": "java|java-8|java-stream", "answer_id": 22561853, "answer_date": "2014-03-21T14:42:17.967Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: Curly braces in string in PHP <p>What is the meaning of <code>{ }</code> (curly braces) in string literals in PHP?</p>
<p>This is the <a href="http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex">complex (curly) syntax</a> for string interpolation. From the manual:</p> <blockquote> <h3>Complex (curly) syntax</h3> <p>This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.</p> <p>Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in <code>{</code> and <code>}</code>. Since <code>{</code> can not be escaped, this syntax will only be recognised when the <code>$</code> immediately follows the <code>{</code>. Use <code>{\$</code> to get a literal <code>{$</code>. Some examples to make it clear:</p> <pre><code>&lt;?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square-&gt;width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj-&gt;values[3]-&gt;name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object-&gt;getName(): {${$object-&gt;getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?&gt; </code></pre> </blockquote> <p>Often, this syntax is unnecessary. For example, this:</p> <pre><code>$a = 'abcd'; $out = "$a $a"; // "abcd abcd"; </code></pre> <p>behaves exactly the same as this:</p> <pre><code>$out = "{$a} {$a}"; // same </code></pre> <p>So the curly braces are unnecessary. But <em>this</em>:</p> <pre><code>$out = "$aefgh"; </code></pre> <p>will, depending on your error level, either not work or produce an error because there's no variable named <code>$aefgh</code>, so you need to do:</p> <pre><code>$out = "${a}efgh"; // or $out = "{$a}efgh"; </code></pre>
{ "question_id": 2596837, "question_date": "2010-04-08T00:35:01.483Z", "question_score": 218, "tags": "php|string", "answer_id": 2596838, "answer_date": "2010-04-08T00:36:00.780Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: Remove shadow below actionbar <p>I use actionbarsherlock. The piece of code below is responsible for changing it's background to a custom one.</p> <pre><code>&lt;style name="Widget.Styled.ActionBar" parent="Widget.Sherlock.ActionBar"&gt; &lt;item name="background"&gt;@drawable/actionbar_bg&lt;/item&gt; &lt;item name="android:background"&gt;@drawable/actionbar_bg&lt;/item&gt; &lt;...&gt; &lt;/style&gt; &lt;style name="Theme.MyApp" parent="@style/Theme.Sherlock.Light"&gt; &lt;item name="actionBarStyle"&gt;@style/Widget.Styled.ActionBar&lt;/item&gt; &lt;item name="android:actionBarStyle"&gt;@style/Widget.Styled.ActionBar&lt;/item&gt; &lt;..&gt; &lt;/style&gt; </code></pre> <p>And it works for actionbarsherlock (on versions below honeycomb). But in ICS I have a shadow below actionbar which I don't want. <strong>What is the style item to make it disappear?</strong></p>
<blockquote> <p>What is the style item to make it disappear?</p> </blockquote> <p>In order to remove the shadow add this to your app theme:</p> <pre><code>&lt;style name="MyAppTheme" parent="android:Theme.Holo.Light"&gt; &lt;item name="android:windowContentOverlay"&gt;@null&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>UPDATE:</strong> As @Quinny898 stated, on Android 5.0 this has changed, you have to call <code>setElevation(0)</code> on your action bar. Note that if you're using the support library you must call it to that like so:</p> <pre><code>getSupportActionBar().setElevation(0); </code></pre>
{ "question_id": 12246388, "question_date": "2012-09-03T10:51:53.180Z", "question_score": 218, "tags": "android|android-actionbar|actionbarsherlock", "answer_id": 12246593, "answer_date": "2012-09-03T11:04:48.583Z", "answer_score": 494 }
Please answer the following Stack Overflow question: Title: How to deactivate or override the Android "BACK" button, in Flutter? <p>Is there a way to deactivate the Android back button when on a specific page? </p> <pre><code>class WakeUpApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: "Time To Wake Up ?", home: new WakeUpHome(), routes: &lt;String, WidgetBuilder&gt;{ '/pageOne': (BuildContext context) =&gt; new pageOne(), '/pageTwo': (BuildContext context) =&gt; new pageTwo(), }, ); } } </code></pre> <p>On pageOne I have a button to go to pageTwo: </p> <pre><code>new FloatingActionButton( onPressed: () { Navigator.of(context).pushNamed('/pageTwo'); }, ) </code></pre> <p>My problem is that if I press the Back arrow at the bottom of the android screen, I go back to pageOne. I would like this button to not show up at all. Ideally, I would like to have no possible way out of this screen unless the user for example keeps his finger pressed on the screen for 5 seconds. (I am trying to write an App for toddlers, and would like only the parents to be able to navigate out of the particular screen). </p>
<p>The answer is <code>WillPopScope</code>. It will prevent the page from being popped by the system. You'll still be able to use <code>Navigator.of(context).pop()</code></p> <pre><code>@override Widget build(BuildContext context) { return new WillPopScope( onWillPop: () async =&gt; false, child: new Scaffold( appBar: new AppBar( title: new Text("data"), leading: new IconButton( icon: new Icon(Icons.ac_unit), onPressed: () =&gt; Navigator.of(context).pop(), ), ), ), ); } </code></pre>
{ "question_id": 45916658, "question_date": "2017-08-28T10:13:40.177Z", "question_score": 218, "tags": "flutter", "answer_id": 45918186, "answer_date": "2017-08-28T11:43:52.050Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: Correct way to integrate jQuery plugins in AngularJS <p>I was wondering what is the correct way to integrate jQuery plugins into my angular app. I've found several tutorials and screen-casts but they seem catered to a specific plugin.</p> <p>For Example: <a href="http://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/">http://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/</a> <a href="http://www.youtube.com/watch?v=8ozyXwLzFYs">http://www.youtube.com/watch?v=8ozyXwLzFYs</a></p> <p>Should I create a directive like so - </p> <pre><code>App.directive('directiveName', function() { return { restrict: 'A', link: function(scope, element, attrs) { $(element).'pluginActivationFunction'(scope.$eval(attrs.directiveName)); } }; }); </code></pre> <p>And then in the html call the script and the directive?</p> <pre><code>&lt;div directiveName &gt;&lt;/div&gt; &lt;script type="text/javascript" src="pluginName.js"&gt;&lt;/script&gt; </code></pre> <p>Thanks ahead</p>
<p>Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the <code>link</code> function of the directive. </p> <p>There are a couple of points in the documentation that you could take a look at. You can find them here:<br> <a href="https://docs.angularjs.org/misc/faq#common-pitfalls" rel="noreferrer">Common Pitfalls</a> </p> <p><a href="http://docs.angularjs.org/guide/controller#using-controllers-correctly" rel="noreferrer">Using controllers correctly</a></p> <p>Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.</p> <p>EDIT: Rather than using <code>$(element)</code>, you can make use of <code>angular.element(element)</code> when using AngularJS with jQuery</p>
{ "question_id": 16935095, "question_date": "2013-06-05T08:32:35.027Z", "question_score": 218, "tags": "jquery-plugins|angularjs", "answer_id": 16935288, "answer_date": "2013-06-05T08:43:54.890Z", "answer_score": 144 }
Please answer the following Stack Overflow question: Title: How to change a nullable column to not nullable in a Rails migration? <p>I created a date column in a previous migration and set it to be nullable. Now I want to change it to be not nullable. How do I go about doing this assuming there are null rows in that database? I'm ok with setting those columns to Time.now if they're currently null.</p>
<p>If you do it in a migration then you could probably do it like this:</p> <pre><code># Make sure no null value exist MyModel.where(date_column: nil).update_all(date_column: Time.now) # Change the column to not allow null change_column :my_models, :date_column, :datetime, null: false </code></pre>
{ "question_id": 5966840, "question_date": "2011-05-11T15:34:33.360Z", "question_score": 218, "tags": "ruby-on-rails|migration", "answer_id": 5967073, "answer_date": "2011-05-11T15:49:32.457Z", "answer_score": 225 }
Please answer the following Stack Overflow question: Title: Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0 <p>I'm currently uploading my App to the App Store and Apple is asking me if this app users IDFA. I'm using the latest Admob SDK or 6.8.0 and I don't know if it uses IDFA or not, and if it does which check boxes should I hit X.X</p> <p>Image <img src="https://i.stack.imgur.com/ZtOSY.png" alt="enter image description here"><a href="http://i.gyazo.com/a7d36f95ac0cc066e5654517d4ec2f3f.png">http://i.gyazo.com/a7d36f95ac0cc066e5654517d4ec2f3f.png</a></p>
<p>I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.</p> <p>But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:</p> <p><em>The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, <strong>including Limit Ad Tracking</strong>.</em></p> <p>Including Limit Ad Tracking. This is what the last box is all about. So <strong>you must check the that box if you use AdMob</strong>. If you use other SDK I strongly recommend checking if they respect the guidelines as well.</p> <p>Since I run only ads (Google AdMob), I checked the <strong>first (Serve ads...) and last box (I, ___, confirm...)</strong>. App was approved and released, no issues.</p> <p>Source: <a href="https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk" rel="noreferrer">https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk</a></p>
{ "question_id": 23124663, "question_date": "2014-04-17T04:34:03.070Z", "question_score": 218, "tags": "ios|admob", "answer_id": 23358377, "answer_date": "2014-04-29T07:33:49.847Z", "answer_score": 241 }
Please answer the following Stack Overflow question: Title: How can a JavaScript object refer to values in itself? <p>Lets say I have the following JavaScript:</p> <pre><code>var obj = { key1 : &quot;it &quot;, key2 : key1 + &quot; works!&quot; }; alert(obj.key2); </code></pre> <p>This errors with &quot;key1 is not defined&quot;. I have tried</p> <pre><code>this.key1 this[key1] obj.key1 obj[key1] this[&quot;key1&quot;] obj[&quot;key1&quot;] </code></pre> <p>and they never seem to be defined.</p> <p>How can I get key2 to refer to key1's value?</p>
<p>Maybe you can think about removing the attribute to a function. I mean something like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = { key1: "it ", key2: function() { return this.key1 + " works!"; } }; alert(obj.key2());</code></pre> </div> </div> </p>
{ "question_id": 2787245, "question_date": "2010-05-07T08:39:14.860Z", "question_score": 218, "tags": "javascript|object", "answer_id": 2787309, "answer_date": "2010-05-07T08:52:37.453Z", "answer_score": 215 }
Please answer the following Stack Overflow question: Title: Is there a way to iterate over a dictionary? <p>I know <code>NSDictionaries</code> as something where you need a <code>key</code> in order to get a <code>value</code>. But how can I iterate over all <code>keys</code> and <code>values</code> in a <code>NSDictionary</code>, so that I know what keys there are, and what values there are? I know there is something called a <em>for-in-loop</em> in <code>JavaScript</code>. Is there something similar in <code>Objective-C</code>?</p>
<p>Yes, <code>NSDictionary</code> supports fast enumeration. With Objective-C 2.0, you can do this:</p> <pre><code>// To print out all key-value pairs in the NSDictionary myDict for(id key in myDict) NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]); </code></pre> <p>The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an <code>NSEnumerator</code>:</p> <pre><code>NSEnumerator *enumerator = [myDict keyEnumerator]; id key; // extra parens to suppress warning about using = instead of == while((key = [enumerator nextObject])) NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]); </code></pre>
{ "question_id": 1284429, "question_date": "2009-08-16T14:34:38.680Z", "question_score": 218, "tags": "ios|objective-c|foreach|iteration|nsdictionary", "answer_id": 1284443, "answer_date": "2009-08-16T14:40:16.627Z", "answer_score": 353 }
Please answer the following Stack Overflow question: Title: How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203) <p>I just lost part of my weekend because of this ... joker - zero width space. I just used some snippets from google groups and didn't recognize that there are doubled characters, because Idea (11) didn't show them, which was causing problems with parsing config file of my app... I discovered it accidentally in vi.</p> <p>Is there any way to display such things in IntelliJ (or some other way to examine files) without using external editors.</p> <p>IntelliJ 11 / Mac OS 10.7</p> <p><strong>edit - sample</strong></p> <p>These two lines looks identical, in browser and also in Idea. You can see in page's code that in first - commented line there is hidden zero width space between <code>mysql://</code> and <code>localhost</code>, which causes problems. Of course if you expect that 'joker', you can try to use search and replace it, however nobody expects the sign that should not be there, especially if he cannot see it in any way. </p> <pre><code>#db.default.url="jdbc:mysql://​localhost/play-fullcalendar" db.default.url="jdbc:mysql://localhost/play-fullcalendar" </code></pre>
<p>Not sure what you meant, but you can permanently turn showing whitespaces on and off in <code>Settings -&gt; Editor -&gt; General -&gt; Appearance -&gt; Show whitespaces</code>.</p> <p>Also, you can set it for a current file only in <code>View -&gt; Active Editor -&gt; Show WhiteSpaces</code>.</p> <p>Edit:</p> <p>Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to <a href="http://plugins.jetbrains.com/plugin/7448" rel="noreferrer">give it a try</a>.</p>
{ "question_id": 9868796, "question_date": "2012-03-26T08:25:16.197Z", "question_score": 218, "tags": "intellij-idea|phpstorm|whitespace", "answer_id": 9872584, "answer_date": "2012-03-26T13:00:34.017Z", "answer_score": 398 }
Please answer the following Stack Overflow question: Title: The type must be a reference type in order to use it as parameter 'T' in the generic type or method <p>I'm getting deeper into generics and now have a situation I need help with. I get a compile error on the 'Derived' class below as shown in the subject title. I see many other posts similar to this one but I'm not seeing the relationship. Can someone tell me how to resolve this?</p> <pre><code>using System; using System.Collections.Generic; namespace Example { public class ViewContext { ViewContext() { } } public interface IModel { } public interface IView&lt;T&gt; where T : IModel { ViewContext ViewContext { get; set; } } public class SomeModel : IModel { public SomeModel() { } public int ID { get; set; } } public class Base&lt;T&gt; where T : IModel { public Base(IView&lt;T&gt; view) { } } public class Derived&lt;SomeModel&gt; : Base&lt;SomeModel&gt; where SomeModel : IModel { public Derived(IView&lt;SomeModel&gt; view) : base(view) { SomeModel m = (SomeModel)Activator.CreateInstance(typeof(SomeModel)); Service&lt;SomeModel&gt; s = new Service&lt;SomeModel&gt;(); s.Work(m); } } public class Service&lt;SomeModel&gt; where SomeModel : IModel { public Service() { } public void Work(SomeModel m) { } } } </code></pre>
<p>I can't repro, but I <em>suspect</em> that in your actual code there is a constraint somewhere that <code>T : class</code> - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):</p> <pre><code>public class Derived&lt;SomeModel&gt; : Base&lt;SomeModel&gt; where SomeModel : class, IModel ^^^^^ see this bit </code></pre>
{ "question_id": 6451120, "question_date": "2011-06-23T08:13:35.147Z", "question_score": 218, "tags": "c#|generics", "answer_id": 6451258, "answer_date": "2011-06-23T08:27:06.510Z", "answer_score": 492 }
Please answer the following Stack Overflow question: Title: How exactly does <script defer="defer"> work? <p>I have a few <code>&lt;script&gt;</code> elements, and the code in some of them depend on code in other <code>&lt;script&gt;</code> elements. I saw the <code>defer</code> attribute can come in handy here as it allows code blocks to be postponed in execution.</p> <p>To test it I executed this on Chrome: <a href="http://jsfiddle.net/xXZMN/">http://jsfiddle.net/xXZMN/</a>.</p> <pre><code>&lt;script defer="defer"&gt;alert(2);&lt;/script&gt; &lt;script&gt;alert(1)&lt;/script&gt; &lt;script defer="defer"&gt;alert(3);&lt;/script&gt; </code></pre> <p>However, it alerts <code>2 - 1 - 3</code>. Why doesn't it alert <code>1 - 2 - 3</code>?</p>
<h2>UPDATED: 2/19/2016</h2> <p>Consider this answer outdated. Refer to other answers on this post for information relevant to newer browser version.</p> <hr> <p>Basically, defer tells the browser to wait "until it's ready" before executing the javascript in that script block. Usually this is after the DOM has finished loading and document.readyState == 4</p> <p>The defer attribute is specific to internet explorer. In Internet Explorer 8, on Windows 7 the result I am seeing in your JS Fiddle test page is, 1 - 2 - 3.</p> <p>The results may vary from browser to browser.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms533719(v=vs.85).aspx</a></p> <p>Contrary to popular belief IE follows standards more often than people let on, in actuality the "defer" attribute is defined in the DOM Level 1 spec <a href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html" rel="noreferrer">http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html</a> </p> <p>The W3C's definition of defer: <a href="http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer" rel="noreferrer">http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer</a>:</p> <p>"When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering."</p>
{ "question_id": 5250412, "question_date": "2011-03-09T18:29:32.320Z", "question_score": 218, "tags": "javascript|html|deferred-execution", "answer_id": 5250888, "answer_date": "2011-03-09T19:09:19.420Z", "answer_score": 53 }
Please answer the following Stack Overflow question: Title: Piping both stdout and stderr in bash? <p>It seems that newer versions of bash have the <code>&amp;&gt;</code> operator, which (if I understand correctly), redirects both stdout and stderr to a file (<code>&amp;&gt;&gt;</code> appends to the file instead, as Adrian clarified). </p> <p>What's the simplest way to achieve the same thing, but instead piping to another command?</p> <p>For example, in this line:</p> <pre><code>cmd-doesnt-respect-difference-between-stdout-and-stderr | grep -i SomeError </code></pre> <p>I'd like the grep to match on content both in stdout and stderr (effectively, have them combined into one stream).</p> <p><em>Note</em>: this question is asking about piping, <em>not</em> redirecting - so it is not a duplicate of the question it's currently marked as a duplicate of.</p>
<p>(Note that <code>&amp;&gt;&gt;file</code> <em>appends</em> to a file while <code>&amp;&gt;</code> would redirect and <em>overwrite</em> a previously existing file.)</p> <p>To combine <code>stdout</code> and <code>stderr</code> you would redirect the latter to the former using <code>1&gt;&amp;2</code>. This redirects stdout (file descriptor 1) to stderr (file descriptor 2), e.g.:</p> <pre><code>$ { echo &quot;stdout&quot;; echo &quot;stderr&quot; 1&gt;&amp;2; } | grep -v std stderr $ </code></pre> <p><code>stdout</code> goes to stdout, <code>stderr</code> goes to stderr. <code>grep</code> only sees <code>stdout</code>, hence <code>stderr</code> prints to the terminal.</p> <p>On the other hand:</p> <pre><code>$ { echo &quot;stdout&quot;; echo &quot;stderr&quot; 1&gt;&amp;2; } 2&gt;&amp;1 | grep -v std $ </code></pre> <p>After writing to both stdout and stderr, <code>2&gt;&amp;1</code> redirects stderr back to stdout and <code>grep</code> sees both strings on stdin, thus filters out both.</p> <p>You can read more about redirection <a href="http://www.gnu.org/software/bash/manual/bashref.html#Redirections" rel="nofollow noreferrer">here</a>.</p> <p>Regarding your example (POSIX):</p> <pre><code>cmd-doesnt-respect-difference-between-stdout-and-stderr 2&gt;&amp;1 | grep -i SomeError </code></pre> <p>or, using <code>&gt;=bash-4</code>:</p> <pre><code>cmd-doesnt-respect-difference-between-stdout-and-stderr |&amp; grep -i SomeError </code></pre>
{ "question_id": 16497317, "question_date": "2013-05-11T12:55:20.110Z", "question_score": 218, "tags": "bash|stdout|stderr|piping", "answer_id": 16497456, "answer_date": "2013-05-11T13:11:03.897Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: SQL Server Index Naming Conventions <p>Is there some standard way to name indexes for SQL Server? It seems that the primary key index is named PK_ and non-clustered indexes typically start with IX_. Are there any naming conventions beyond that for unique indexes?</p>
<p>I use</p> <p>PK_ for primary keys</p> <p>UK_ for unique keys</p> <p>IX_ for non clustered non unique indexes</p> <p>UX_ for unique indexes</p> <p>All of my index name take the form of<br> <code>&lt;index or key type&gt;_&lt;table name&gt;_&lt;column 1&gt;_&lt;column 2&gt;_&lt;column n&gt;</code></p>
{ "question_id": 2783495, "question_date": "2010-05-06T18:33:55.633Z", "question_score": 218, "tags": "sql-server|naming-conventions|indexing", "answer_id": 2783570, "answer_date": "2010-05-06T18:44:26.647Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: Evenly spacing views using ConstraintLayout <p>A common use for <a href="https://developer.android.com/reference/android/widget/LinearLayout.html"><code>LinearLayout</code></a> is to evenly space (weight) views, for example: <a href="https://i.stack.imgur.com/eDnSi.png"><img src="https://i.stack.imgur.com/eDnSi.png" alt="example layout"></a></p> <p>How do you implement evenly spaced views like this using the new <code>ConstraintLayout</code>?</p> <p><code>ConstraintLayout</code> links for reference: <a href="http://android-developers.blogspot.com.au/2016/05/android-studio-22-preview-new-ui.html">blog post</a>, <a href="https://www.youtube.com/watch?v=sO9aX87hq9c">I/O session video</a></p>
<p>There are two ways to accomplish this using <code>ConstraintLayout</code>: <a href="https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#Chains" rel="noreferrer">Chains</a> and <a href="https://developer.android.com/reference/android/support/constraint/Guideline.html" rel="noreferrer">Guidelines</a>. To use Chains, make sure you are using <code>ConstraintLayout</code> Beta 3 or newer and if you want to use the visual layout editor in Android Studio, make sure you are using Android Studio 2.3 Beta 1 or newer.</p> <p><strong>Method 1 - Using Chains</strong></p> <p>Open the layout editor and add your widgets as normal, adding parent constraints as needed. In this case, I have added two buttons with constraints to the bottom of the parent and side of the parent (left side for Save button and right side for Share button):</p> <p><a href="https://i.stack.imgur.com/o9Djj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/o9Djj.png" alt="enter image description here"></a></p> <p>Note that in this state, if I flip to landscape view, the views do not fill the parent but are anchored to the corners:</p> <p><a href="https://i.stack.imgur.com/skPVj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/skPVj.png" alt="enter image description here"></a></p> <p>Highlight both views, either by Ctrl/Cmd clicking or by dragging a box around the views:</p> <p><a href="https://i.stack.imgur.com/3a2Jf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3a2Jf.png" alt="enter image description here"></a></p> <p>Then right-click on the views and choose "Center Horizontally":</p> <p><a href="https://i.stack.imgur.com/FcE35.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FcE35.png" alt="enter image description here"></a></p> <p>This sets up a bi-directional connection between the views (which is how a Chain is defined). By default the chain style is "spread", which is applied even when no XML attribute is included. Sticking with this chain style but setting the width of our views to <code>0dp</code> lets the views fill the available space, spreading evenly across the parent:</p> <p><a href="https://i.stack.imgur.com/ugvwQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ugvwQ.png" alt="enter image description here"></a></p> <p>This is more noticeable in landscape view:</p> <p><a href="https://i.stack.imgur.com/tA4Dp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tA4Dp.png" alt="enter image description here"></a></p> <p>If you prefer to skip the layout editor, the resulting XML will look like:</p> <pre><code>&lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;Button android:id="@+id/button_save" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/button_save_text" android:layout_marginStart="8dp" android:layout_marginBottom="8dp" android:layout_marginEnd="4dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintRight_toLeftOf="@+id/button_share" app:layout_constraintHorizontal_chainStyle="spread" /&gt; &lt;Button android:id="@+id/button_share" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/button_share_text" android:layout_marginStart="4dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintLeft_toRightOf="@+id/button_save" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>Details:</p> <ul> <li>setting the width of each item to <code>0dp</code> or <code>MATCH_CONSTRAINT</code> lets the views fill the parent (optional)</li> <li>the views must be linked together bidirectionally (right of save button links to share button, left of share button links to save button), this will happen automatically via the layout editor when choosing "Center Horizontally"</li> <li>the first view in the chain can specify the chain style via <code>layout_constraintHorizontal_chainStyle</code>, see the <a href="https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#Chains" rel="noreferrer">documentation</a> for various chain styles, if the chain style is omitted, the default is "spread"</li> <li>the weighting of the chain can be adjusted via <code>layout_constraintHorizontal_weight</code></li> <li>this example is for a horizontal chain, there are corresponding attributes for vertical chains</li> </ul> <p><strong>Method 2 - Using a Guideline</strong></p> <p>Open your layout in the editor and click the guideline button:</p> <p><a href="https://i.stack.imgur.com/Bysun.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Bysun.png" alt="enter image description here"></a></p> <p>Then select "Add Vertical Guideline": <a href="https://i.stack.imgur.com/kJ434.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kJ434.png" alt="enter image description here"></a></p> <p>A new guideline will appear, that by default, will likely be anchored to the left in relative values (denoted by left-facing arrow):</p> <p><a href="https://i.stack.imgur.com/h6Exx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/h6Exx.png" alt="layout editor relative guideline"></a></p> <p>Click the left-facing arrow to switch it to a percentage value, then drag the guideline to the 50% mark:</p> <p><a href="https://i.stack.imgur.com/QJ6z9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QJ6z9.png" alt="layout editor percent guideline"></a></p> <p>The guideline can now be used as an anchor for other views. In my example, I attached the right of the save button and the left of the share button to the guideline:</p> <p><a href="https://i.stack.imgur.com/slXmG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/slXmG.png" alt="final layout"></a></p> <p>If you want the views to fill up the available space then the constraint should be set to "Any Size" (the squiggly lines running horizontally):</p> <p><a href="https://i.stack.imgur.com/EMAiW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EMAiW.png" alt="any size constraint"></a></p> <p>(This is the same as setting the <code>layout_width</code> to <code>0dp</code>).</p> <p>A guideline can also be created in XML quite easily rather than using the layout editor:</p> <pre><code>&lt;android.support.constraint.Guideline android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/guideline" android:orientation="vertical" app:layout_constraintGuide_percent="0.5" /&gt; </code></pre>
{ "question_id": 37518745, "question_date": "2016-05-30T06:13:01.400Z", "question_score": 218, "tags": "android|android-layout|android-constraintlayout", "answer_id": 37518746, "answer_date": "2016-05-30T06:13:01.400Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: Do UNIX timestamps change across timezones? <p>As the subject asks; do UNIX timestamps change in each timezone?</p> <p><strong>For example,</strong> if I sent a request to another email the other side of the world saying, <strong>"Send out an email when the time is 1397484936"</strong>, would the other server's timestamp be 12 hours behind my own?</p>
<p>The definition of UNIX timestamp is time zone independent. The UNIX timestamp is the number of seconds (or milliseconds) elapsed since an absolute point in time, midnight of Jan 1 1970 in UTC time. (UTC is Greenwich Mean Time without Daylight Savings time adjustments.) Regardless of your time zone, the UNIX timestamp represents a moment that is the same everywhere. Of course you can convert back and forth <em>to</em> a local time zone representation (time 1397484936 is such-and-such local time in New York, or some other local time in Djakarta) if you want.</p> <p>The article at <a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">http://en.wikipedia.org/wiki/Unix_time</a> is pretty impressive if you'd like a longer read.</p>
{ "question_id": 23062515, "question_date": "2014-04-14T14:17:46.093Z", "question_score": 218, "tags": "timezone|unix-timestamp|specifications", "answer_id": 23062640, "answer_date": "2014-04-14T14:23:20.543Z", "answer_score": 344 }
Please answer the following Stack Overflow question: Title: Usage of forceLayout(), requestLayout() and invalidate() <p>I'm a bit confused about the roles of <code>forceLayout()</code>, <code>requestLayout()</code> and <code>invalidate()</code> methods of the <code>View</code> class.</p> <p>When shall they be called?</p>
<p>To better understand answers provided by <a href="https://stackoverflow.com/a/13858255/1993204">François BOURLIEUX</a> and <a href="https://stackoverflow.com/a/24835463/1993204">Dalvik</a> I suggest you take a look at this awesome view lifecycle diagram by <a href="https://plus.google.com/115089607132986274709/posts/cT1EuBbxEgN" rel="noreferrer">Arpit Mathur</a>: <img src="https://i.stack.imgur.com/MDJXT.png" alt="enter image description here"></p>
{ "question_id": 13856180, "question_date": "2012-12-13T08:55:05.697Z", "question_score": 218, "tags": "android|android-layout|android-view", "answer_id": 25846243, "answer_date": "2014-09-15T10:44:20.597Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: State not updating when using React state hook within setInterval <p>I'm trying out the new <a href="https://reactjs.org/docs/hooks-intro.html" rel="noreferrer">React Hooks</a> and have a Clock component with a counter which is supposed to increase every second. However, the value does not increase beyond one.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Clock() { const [time, setTime] = React.useState(0); React.useEffect(() =&gt; { const timer = window.setInterval(() =&gt; { setTime(time + 1); }, 1000); return () =&gt; { window.clearInterval(timer); }; }, []); return ( &lt;div&gt;Seconds: {time}&lt;/div&gt; ); } ReactDOM.render(&lt;Clock /&gt;, document.querySelector('#app'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/[email protected]/umd/react.development.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
<p>The reason is because the callback passed into <code>setInterval</code>'s closure only accesses the <code>time</code> variable in the first render, it doesn't have access to the new <code>time</code> value in the subsequent render because the <code>useEffect()</code> is not invoked the second time.</p> <p><code>time</code> always has the value of 0 within the <code>setInterval</code> callback.</p> <p>Like the <code>setState</code> you are familiar with, state hooks have two forms: one where it takes in the updated state, and the callback form which the current state is passed in. You should use the second form and read the latest state value within the <code>setState</code> callback to ensure that you have the latest state value before incrementing it.</p> <blockquote> <p><strong>Bonus: Alternative Approaches</strong></p> <p>Dan Abramov, goes in-depth into the topic about using <code>setInterval</code> with hooks in his <a href="https://overreacted.io/making-setinterval-declarative-with-react-hooks/" rel="noreferrer">blog post</a> and provides alternative ways around this issue. Highly recommend reading it!</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Clock() { const [time, setTime] = React.useState(0); React.useEffect(() =&gt; { const timer = window.setInterval(() =&gt; { setTime(prevTime =&gt; prevTime + 1); // &lt;-- Change this line! }, 1000); return () =&gt; { window.clearInterval(timer); }; }, []); return ( &lt;div&gt;Seconds: {time}&lt;/div&gt; ); } ReactDOM.render(&lt;Clock /&gt;, document.querySelector('#app'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/[email protected]/umd/react.development.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 53024496, "question_date": "2018-10-27T17:25:13.103Z", "question_score": 218, "tags": "javascript|reactjs|react-hooks", "answer_id": 53024497, "answer_date": "2018-10-27T17:25:13.103Z", "answer_score": 267 }
Please answer the following Stack Overflow question: Title: Why do access tokens expire? <p>I am just getting started working with Google API and OAuth2. When the client authorizes my app I am given a "refresh token" and a short lived "access token". Now every time the access token expires, I can POST my refresh token to Google and they will give me a new access token.</p> <p>My question is what is the purpose of the access token expiring? Why can't there just be a long lasting access token instead of the refresh token?</p> <p>Also, does the refresh token expire?</p> <p>See <a href="https://developers.google.com/identity/protocols/OAuth2" rel="noreferrer">Using OAuth 2.0 to Access Google APIs</a> for more info on Google OAuth2 workflow.</p>
<p>This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?</p> <ul> <li>Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.</li> <li>Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.</li> <li>The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.</li> </ul>
{ "question_id": 7030694, "question_date": "2011-08-11T18:05:38.620Z", "question_score": 218, "tags": "oauth|oauth-2.0|google-api|google-oauth", "answer_id": 7035926, "answer_date": "2011-08-12T05:28:37.560Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: PropTypes in a TypeScript React Application <p>Does using <code>React.PropTypes</code> make sense in a TypeScript React Application or is this just a case of "belt and suspenders"?</p> <p>Since the component class is declared with a <code>Props</code> type parameter:</p> <pre><code>interface Props { // ... } export class MyComponent extends React.Component&lt;Props, any&gt; { ... } </code></pre> <p>is there any real benefit to adding</p> <pre><code>static propTypes { myProp: React.PropTypes.string } </code></pre> <p>to the class definition?</p>
<p>There's usually not much value to maintaining both your component props as TypeScript types and <code>React.PropTypes</code> at the same time.</p> <p>Here are some cases where it is useful to do so:</p> <ul> <li>Publishing a package such as a component library that will be used by plain JavaScript.</li> <li>Accepting and passing along external input such as results from an API call.</li> <li>Using data from a library that may not have adequate or accurate typings, if any.</li> </ul> <p>So, usually it's a question of how much you can trust your compile time validation.</p> <p>Newer versions of TypeScript can now infer types based on your <code>React.PropTypes</code> (<code>PropTypes.InferProps</code>), but the resulting types can be difficult to use or refer to elsewhere in your code.</p>
{ "question_id": 41746028, "question_date": "2017-01-19T15:45:55.153Z", "question_score": 218, "tags": "reactjs|typescript|react-proptypes", "answer_id": 43187969, "answer_date": "2017-04-03T14:58:10.217Z", "answer_score": 154 }
Please answer the following Stack Overflow question: Title: Suppress or Customize Intro Message in Fish Shell <p>Is it possible to remove the intro message in fish shell:</p> <blockquote> <p>Welcome to fish, the friendly interactive shell</p> <p>Type help for instructions on how to use fish</p> </blockquote>
<p>Found that the greeting message is set in fishd.Machine.local. To override the following to <code>~/.config/fish/config.fish</code>:</p> <pre><code>set fish_greeting </code></pre>
{ "question_id": 13995857, "question_date": "2012-12-21T19:12:34.287Z", "question_score": 218, "tags": "fish", "answer_id": 13995944, "answer_date": "2012-12-21T19:20:51.917Z", "answer_score": 245 }
Please answer the following Stack Overflow question: Title: How can you find unused NuGet packages in solution? <p>How can you find the unused NuGet packages in a solution?</p> <p>I've got a number of solutions where there are a lot of installed packages, and a large number of them are flagged as having updates.</p> <p>However, I'm concerned there may be breaking changes, so I first want to clean up by removing any unused packages.</p>
<p>ReSharper 2016.1 has <a href="http://blog.jetbrains.com/dotnet/2016/02/22/resharper-ultimate-10-1-eap-3/">a feature to remove unused NuGet.</a> </p> <p>It can be run on a solution and on each project in a solution and it does the following things:</p> <ol> <li>Analyze your code and collecting references to assemblies.</li> <li>Build NuGet usage graph based on usages of assemblies.</li> <li>Packages without content files, unused itself and without used dependencies are assumed as unused and suggested to remove.</li> </ol> <p>Unfortunately, this doesn't work for <code>project.json</code> projects (<a href="https://youtrack.jetbrains.com/issue/RSRP-454515">RSRP-454515</a>) and ASP.NET core projects (<a href="https://youtrack.jetbrains.com/issue/RSRP-459076">RSRP-459076</a>)</p>
{ "question_id": 19951328, "question_date": "2013-11-13T10:27:59.297Z", "question_score": 218, "tags": "visual-studio|nuget", "answer_id": 36645281, "answer_date": "2016-04-15T10:55:48.983Z", "answer_score": 76 }
Please answer the following Stack Overflow question: Title: Focus-follows-mouse (plus auto-raise) on Mac OS X <p>(I don't want to hear about how crazy I am to want that! :)</p> <p>Focus-follows-mouse is also known as point-to-focus, pointer focus, and (in some implementations) sloppy focus. [Add other terms that will make this more searchable!] X-mouse</p>
<p>I've been coming back to this question periodically for about 10 years and I finally found a simple solution: AutoRaise <a href="https://github.com/sbmpost/AutoRaise" rel="noreferrer">https://github.com/sbmpost/AutoRaise</a></p> <p>By default it enables focus-follows-mouse AND autoraise. You can delay the autoraise with a config option.</p> <p>It also has what they call &quot;warp&quot; function that centers the mouse pointer in a window when you Command-Tab to the window. I never knew I needed this until I tried it, but once I tried it, I can't live without it!</p>
{ "question_id": 98310, "question_date": "2008-09-19T00:24:30.890Z", "question_score": 218, "tags": "macos|focus|mouse", "answer_id": 64270926, "answer_date": "2020-10-08T21:33:00.740Z", "answer_score": 43 }
Please answer the following Stack Overflow question: Title: How to document Ruby code? <p>Are there certain code conventions when documenting ruby code? For example I have the following code snippet:</p> <pre><code>require 'open3' module ProcessUtils # Runs a subprocess and applies handlers for stdout and stderr # Params: # - command: command line string to be executed by the system # - outhandler: proc object that takes a pipe object as first and only param (may be nil) # - errhandler: proc object that takes a pipe object as first and only param (may be nil) def execute_and_handle(command, outhandler, errhandler) Open3.popen3(command) do |_, stdout, stderr| if (outhandler) outhandler.call(stdout) end if (errhandler) errhandler.call(stderr) end end end end </code></pre> <p>This guess this is okay, but perhaps there are better/superior documentation practices?</p>
<p>You should target your documentation for the RDoc processor, which can find your documentation and generate HTML from it. You've put your comment in the right place for that, but you should have a look at the <a href="https://github.com/ruby/rdoc" rel="noreferrer">RDoc documentation</a> to learn about the kinds of tags that RDoc knows how to format. To that end, I'd reformat your comment as follows:</p> <pre><code> # Runs a subprocess and applies handlers for stdout and stderr # Params: # +command+:: command line string to be executed by the system # +outhandler+:: +Proc+ object that takes a pipe object as first and only param (may be nil) # +errhandler+:: +Proc+ object that takes a pipe object as first and only param (may be nil) </code></pre>
{ "question_id": 1681467, "question_date": "2009-11-05T15:54:53.180Z", "question_score": 218, "tags": "ruby", "answer_id": 1681534, "answer_date": "2009-11-05T16:01:28.390Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: What's the difference between Task.Start/Wait and Async/Await? <p>I may be missing something but what is the difference between doing:</p> <pre><code>public void MyMethod() { Task t = Task.Factory.StartNew(DoSomethingThatTakesTime); t.Wait(); UpdateLabelToSayItsComplete(); } public async void MyMethod() { var result = Task.Factory.StartNew(DoSomethingThatTakesTime); await result; UpdateLabelToSayItsComplete(); } private void DoSomethingThatTakesTime() { Thread.Sleep(10000); } </code></pre>
<blockquote> <p>I may be missing something </p> </blockquote> <p>You are.</p> <blockquote> <p>what is the difference between doing <code>Task.Wait</code> and <code>await task</code>?</p> </blockquote> <p>You order your lunch from the waiter at the restaurant. A moment after giving your order, a friend walks in and sits down next to you and starts a conversation. Now you have two choices. You can ignore your friend until the task is complete -- you can wait until your soup arrives and do nothing else while you are waiting. Or you can respond to your friend, and when your friend stops talking, the waiter will bring you your soup.</p> <p><code>Task.Wait</code> blocks until the task is complete -- you ignore your friend until the task is complete. <code>await</code> keeps processing messages in the message queue, and when the task is complete, it enqueues a message that says "pick up where you left off after that await". You talk to your friend, and when there is a break in the conversation the soup arrives.</p>
{ "question_id": 9519414, "question_date": "2012-03-01T15:55:32.303Z", "question_score": 218, "tags": "c#|task-parallel-library|.net-4.5|async-await|conceptual", "answer_id": 9519578, "answer_date": "2012-03-01T16:04:22.660Z", "answer_score": 416 }
Please answer the following Stack Overflow question: Title: How do I use vimdiff to resolve a git merge conflict? <p>I just merged a branch into my master in git and I got <code>Automatic merge failed; fix conflicts and then commit the result.</code> Now I ran <code>git mergetool</code> and vimdiff opened with the image below. I don't know how to use vimdiff. What does each panel here mean and how should I proceed to fix the merge conflict?</p> <p><img src="https://i.stack.imgur.com/kxn1g.png" alt="enter image description here"></p>
<p>All four buffers provide a different view of the same file. The top left buffer (LOCAL) is how the file looked in your target branch (what you are merging into). The top right buffer (REMOTE) is how the file looked in your source branch (where you are merging from). The middle buffer (BASE) is the common ancestor of the two (so you can compare how the left and right versions have diverged from each other).</p> <p>I may be mistaken on the following point. I think the source of the merge conflict is that both files have changed the same portion of the file since BASE; LOCAL has changed the quotes from double to single, and REMOTE has made the same change but also changed the background value from a color to a URL. (I think the merge is not smart enough to notice that all the changes to LOCAL are also present in REMOTE; it just knows that LOCAL has made changes since BASE in the same places that REMOTE has).</p> <p>In any case, the bottom buffer contains the file you can actually edit&mdash;the one sitting in your working directory. You can make any changes you like; <code>vim</code> is showing you how it differs from each of the top views, which are the areas that the automatic merge couldn't not handle. Pull changes from LOCAL if you don't want the REMOTE changes. Pull changes from REMOTE if you prefer those to the LOCAL changes. Pull from BASE if you think both REMOTE and LOCAL are wrong. Do something completely different if you have a better idea! In the end, the changes you make here are the ones that will actually be committed.</p>
{ "question_id": 14904644, "question_date": "2013-02-15T22:46:13.093Z", "question_score": 218, "tags": "git|vim|git-merge|mergetool|git-merge-conflict", "answer_id": 14905137, "answer_date": "2013-02-15T23:36:31.023Z", "answer_score": 182 }
Please answer the following Stack Overflow question: Title: Cryptic "Script Error." reported in Javascript in Chrome and Firefox <p>I have a script that detects Javascript errors on my website and sends them to my backend for reporting. It reports the first error encountered, the supposed line number, and the time.</p> <p><strong>EDIT to include doctype:</strong></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml"&gt; </code></pre> <p><strong>...</strong></p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ // for debugging javascript! (function(window){ window.onerror = function(msg, url, ln) { //transform errors if (typeof(msg) === 'object' &amp;&amp; msg.srcElement &amp;&amp; msg.target) { if(msg.srcElement == '[object HTMLScriptElement]' &amp;&amp; msg.target == '[object HTMLScriptElement]'){ msg = 'Error loading script'; }else{ msg = 'Event Error - target:' + msg.target + ' srcElement:' + msg.srcElement; } } msg = msg.toString(); //ignore errors if(msg.indexOf("Location.toString") &gt; -1){ return; } if(msg.indexOf("Error loading script") &gt; -1){ return; } //report errors window.onerror = function(){}; (new Image()).src = "/jserror.php?msg=" + encodeURIComponent(msg) + "&amp;url=" + encodeURIComponent(url || document.location.toString().replace(/#.*$/, "")) + "&amp;ln=" + parseInt(ln || 0) + "&amp;r=" + (+new Date()); }; })(window); //]]&gt; &lt;/script&gt; </code></pre> <p>Because of this script, I'm acutely aware of any javascript errors that are happening on my site. <strong>One of by biggest offenders is "Script Error." on line 0.</strong> in Chrome 10+, and Firefox 3+. This error doesn't exist (or may be called something else?) in Internet Explorer.</p> <p><strong>Correction (5/23/2013):</strong> This "Script Error, Line 0" error is now showing up in IE7 and possibly other versions of IE. Possibly a result of a recent IE security patch as this behavior previously did not exist.</p> <p>Does anyone have any idea what this error means or what causes it? It happens on about 0.25% of my overall pageloads, and represents half the reported errors.</p>
<p>The "Script error." happens in Firefox, Safari, and Chrome when an exception violates the browser's <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same-origin policy</a> - i.e. when the error occurs in a script that's hosted on a domain other than the domain of the current page.</p> <p>This behavior is intentional, to prevent scripts from leaking information to external domains. For an example of why this is necessary, imagine accidentally visiting <code>evilsite.com</code>, that serves up a page with <code>&lt;script src="yourbank.com/index.html"&gt;</code>. (yes, we're pointing that script tag at html, not JS). This will result in a script error, but the error is interesting because it can tell us if you're logged in or not. If you're logged in, the error might be <code>'Welcome Fred...' is undefined</code>, whereas if you're not it might be <code>'Please Login ...' is undefined</code>. Something along those lines.</p> <p>If evilsite.com does this for the top 20 or so bank institutions, they'd have a pretty good idea of which banking sites you visit, and could provide a much more targeted phishing page. (This is just one example, of course. But it illustrates why browsers shouldn't allow <em>any</em> data to cross domain boundaries.)</p> <p>I've tested this in the latest versions of Safari, Chrome, and Firefox - they all do this. IE9 does not - it treats x-origin exceptions the same as same-origin ones. (And Opera doesn't support onerror.)</p> <p>From the horses mouth: <a href="http://trac.webkit.org/browser/branches/chromium/648/Source/WebCore/dom/ScriptExecutionContext.cpp?rev=77122#L301" rel="noreferrer">WebKit source that checks origin</a> when passing exceptions to onerror(). And the <a href="https://dxr.mozilla.org/mozilla-beta/source/dom/base/nsJSEnvironment.cpp#464" rel="noreferrer">Firefox source that checks</a>.</p> <p><strong>UPDATE (10/21/11)</strong>: The <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=363897" rel="noreferrer">Firefox bug that tracks this issue</a> includes a link to the blog post that inspired this behavior. </p> <p><strong>UPDATE (12/2/14)</strong>: You can now enable full cross-domain error reporting on some browsers by specifying a <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin" rel="noreferrer"><code>crossorigin</code> attribute</a> on script tags and having the server send the appropriate <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">CORS</a> HTTP response headers.</p>
{ "question_id": 5913978, "question_date": "2011-05-06T15:59:48.313Z", "question_score": 218, "tags": "javascript|firefox|google-chrome|error-handling", "answer_id": 7778424, "answer_date": "2011-10-15T14:30:28.290Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Removing transforms in SVG files <p>I have been struggling with this for a while, and can't seem to find an answer (that works) anywhere. I have an SVG file which looks like this:</p> <pre><code>&lt;svg xmlns:dc="http://purl.org/dc/elements/1.1/" ... width="72.9375" height="58.21875" ...&gt; ... &lt;g ... transform="translate(10.75,-308.96875)" style="..."&gt; &lt;path inkscape:connector-curvature="0" d="m -10.254587,345.43597 c 0,-1.41732 0.17692,-2.85384 0.5312502,-3.5625 0.70866,-1.41733 2.14518,-2.82259 3.5625,-3.53125 1.41733,-0.70866 2.11392,-0.70867 3.53125,0 1.41732,0.70866 ... z" ... /&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre> <p>I want to remove the <code>transform="..."</code> line but still have my image stay where I've placed it (in InkScape). If I manually remove the transform, the image zips to another part of the screen (as expected), but I need to get rid of the transform altogether and, at the same time, have the image stay exactly where I want it. Is there a way to remove/flatten the transforms into the path coordinates themselves? (The only transforms I have to deal with are translate and scale, no matrices.)</p>
<p><strong>How to remove <em>transforms</em> in Inkscape</strong></p> <ol> <li>Open svg file in Inkscape</li> <li>Go to Edit -&gt; Select All</li> <li>Go to Object -&gt; Ungroup</li> <li>Go to Edit -&gt; XML Editor</li> <li>Find &quot;transform&quot; attributes in layers and delete them</li> </ol> <p><strong>How to move all objects altogether without creating another transform attributes</strong></p> <ol> <li>Go to Edit -&gt; Select All in All Layers</li> <li>Go to Object -&gt; Transform</li> </ol> <p><strong>In Transform panel</strong></p> <ol start="3"> <li>Uncheck <strong>Relative move</strong> and check <strong>Apply to each object separately</strong></li> <li>Set <em>Horizontal</em> and <em>Vertical</em> values according to your needs and click <strong>Apply</strong></li> </ol>
{ "question_id": 13329125, "question_date": "2012-11-11T06:35:24.240Z", "question_score": 218, "tags": "svg|transform|inkscape", "answer_id": 24180005, "answer_date": "2014-06-12T08:43:16.383Z", "answer_score": 209 }
Please answer the following Stack Overflow question: Title: In a storyboard, how do I make a custom cell for use with multiple controllers? <p>I'm trying to use storyboards in an app I'm working on. In the app there are <strong>Lists</strong> and <strong>Users</strong> and each contains a collection of the other (members of a list, lists owned by a user). So, accordingly, I have <code>ListCell</code> and <code>UserCell</code> classes. The goal is to have those be re-usable throughout the app (ie, in any of my tableview controllers). </p> <p>That's where I'm running into a problem. </p> <p><strong>How do I create a custom tableview cell in the storyboard that can be re-used in any view controller?</strong> </p> <p>Here are the specific things I've tried so far.</p> <ul> <li><p>In Controller #1, added a prototype cell, set the class to my <code>UITableViewCell</code> subclass, set the reuse id, added the labels and wired them to the class's outlets. In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before. When it runs, the labels never appear when the cells are shown in Controller #2. Works fine in Controller #1.</p></li> <li><p>Designed each cell type in a different NIB and wired up to the appropriate cell class. In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class. In controllers' <code>viewDidLoad</code> methods, registered those NIB files for the reuse id. When shown, cells in both controllers were empty like the prototype.</p></li> <li><p>Kept prototypes in both controllers empty and set class and reuse id to my cell class. Constructed the cells' UI entirely in code. Cells work perfectly in all controllers.</p></li> </ul> <p>In the second case I suspect that the prototype is always overriding the NIB and if I killed the prototype cells, registering my NIB for the reuse id would work. But then I wouldn't be able to setup segues from the cells to other frames, which is really the whole point of using storyboards.</p> <p>At the end of the day, I want two things: wire up tableview based flows in the storyboard and define cell layouts visually rather than in code. I can't see how to get both of those so far.</p>
<p>As I understand it, you want to:</p> <ol> <li>Design a cell in IB which can be used in multiple storyboard scenes.</li> <li>Configure unique storyboard segues from that cell, depending on the scene the cell is in.</li> </ol> <p>Unfortunately, there is currently no way to do this. To understand why your previous attempts didn't work, you need to understand more about how storyboards and prototype table view cells work. (If you don't care about <em>why</em> these other attempts didn't work, feel free to leave now. I've got no magical workarounds for you, other than suggesting that you file a bug.)</p> <p>A storyboard is, in essence, not much more than a collection of .xib files. When you load up a table view controller that has some prototype cells out of a storyboard, here's what happens:</p> <ul> <li>Each prototype cell is actually its own embedded mini-nib. So when the table view controller is loading up, it runs through each of the prototype cell's nibs and calls <code>-[UITableView registerNib:forCellReuseIdentifier:]</code>.</li> <li>The table view asks the controller for the cells.</li> <li>You probably call <code>-[UITableView dequeueReusableCellWithIdentifier:]</code></li> <li><p>When you request a cell with a given reuse identifier, it checks whether it has a nib registered. If it does, it instantiates an instance of that cell. This is composed of the following steps:</p> <ol> <li>Look at the class of the cell, as defined in the cell's nib. Call <code>[[CellClass alloc] initWithCoder:]</code>.</li> <li>The <code>-initWithCoder:</code> method goes through and adds subviews and sets properties that were defined in the nib. (<code>IBOutlet</code>s probably get hooked up here as well, though I haven't tested that; it may happen in <code>-awakeFromNib</code>)</li> </ol></li> <li><p>You configure your cell however you want.</p></li> </ul> <p>The important thing to note here is there is a distinction between the <em>class</em> of the cell and the <em>visual appearance</em> of the cell. You could create two separate prototype cells of the same class, but with their subviews laid out completely differently. In fact, if you use the default <code>UITableViewCell</code> styles, this is exactly what's happening. The "Default" style and the "Subtitle" style, for example, are both represented by the same <code>UITableViewCell</code> class.</p> <p><strong>This is important</strong>: The <strong>class</strong> of the cell does not have a one-to-one correlation with a particular <strong>view hierarchy</strong>. The view hierarchy is determined entirely by what's in the prototype cell that was registered with this particular controller.</p> <p>Note, as well, that the cell's reuse identifier was not registered in some global cell dispensary. The reuse identifier is only used within the context of a single <code>UITableView</code> instance.</p> <hr> <p>Given this information, let's look at what happened in your above attempts.</p> <blockquote> <p>In Controller #1, added a prototype cell, set the class to my UITableViewCell subclass, set the reuse id, added the labels and wired them to the class's outlets. In Controller #2, added an empty prototype cell, set it to the same class and reuse id as before. When it runs, the labels never appear when the cells are shown in Controller #2. Works fine in Controller #1.</p> </blockquote> <p>This is expected. While both cells had the same class, the view hierarchy that was passed to the cell in Controller #2 was entirely devoid of subviews. So you got an empty cell, which is exactly what you put in the prototype.</p> <blockquote> <p>Designed each cell type in a different NIB and wired up to the appropriate cell class. In storyboard, added an empty prototype cell and set its class and reuse id to refer to my cell class. In controllers' viewDidLoad methods, registered those NIB files for the reuse id. When shown, cells in both controllers were empty like the prototype.</p> </blockquote> <p>Again, this is expected. The reuse identifier is not shared between storyboard scenes or nibs, so the fact that all of these distinct cells had the same reuse identifier was meaningless. The cell you get back from the tableview will have an appearance that matches the prototype cell in that scene of the storyboard.</p> <p>This solution was close, though. As you noted, you could just programmatically call <code>-[UITableView registerNib:forCellReuseIdentifier:]</code>, passing the <code>UINib</code> containing the cell, and you'd get back that same cell. (This isn't because the prototype was "overriding" the nib; you simply hadn't registered the nib with the tableview, so it was still looking at the nib embedded in the storyboard.) Unfortunately, there's a flaw with this approach — there's no way to hook up storyboard segues to a cell in a standalone nib.</p> <blockquote> <p>Kept prototypes in both controllers empty and set class and reuse id to my cell class. Constructed the cells' UI entirely in code. Cells work perfectly in all controllers.</p> </blockquote> <p>Naturally. Hopefully, this is unsurprising.</p> <hr> <p>So, that's why it didn't work. You can design your cells in standalone nibs and use them in multiple storyboard scenes; you just can't currently hook up storyboard segues to those cells. Hopefully, though, you've learned something in the process of reading this.</p>
{ "question_id": 9245969, "question_date": "2012-02-12T02:37:24.003Z", "question_score": 218, "tags": "objective-c|ios|uitableview|storyboard", "answer_id": 9246873, "answer_date": "2012-02-12T06:12:18.197Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: CSS \9 in width property <p>What is the meaning of this? I am guessing it is a browser hack, but I have not been able to find what exactly it does.</p> <pre><code>width: 500px\9; </code></pre> <p>What is the significance of <code>\9</code>?</p>
<p><code>\9</code> is a "CSS hack" specific to Internet Explorer 7, 8, &amp; 9.</p> <p>This simply means that the one specific line of CSS ending with a <code>\9;</code> in place of the <code>;</code> is only valid in IE 7, 8, &amp; 9.</p> <p>In your example,</p> <p><code>width: 500px\9;</code> means that a width of 500 pixels (same result as <code>width: 500px;</code>) will only be applied while using IE 7, 8, &amp; 9.</p> <p>All other browsers will ignore <code>width: 500px\9;</code> entirely, and therefore not apply <code>width: 500px;</code> to the element at all.</p> <p>If your CSS looked like this...</p> <pre><code>#myElement { width: 300px; width: 500px\9; } </code></pre> <p>The result would be <code>#myElement</code> 500 pixels wide in IE 7, 8, &amp; 9, while in all other browsers, <code>#myElement</code> would be 300 pixels wide.</p> <p><a href="https://web.archive.org/web/20160702085511/http://webdesignandsuch.com/ie9-specific-css-hack/" rel="noreferrer">More info</a></p> <hr> <p><strong>EDIT:</strong></p> <p>This answer was written in 2011. It should now be noted that this hack also works in IE 10.</p>
{ "question_id": 8004765, "question_date": "2011-11-04T04:06:03.307Z", "question_score": 218, "tags": "css|width|css-hack", "answer_id": 8004962, "answer_date": "2011-11-04T04:44:05.123Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: Having options in argparse with a dash <p>I want to have some options in argparse module such as <code>--pm-export</code> however when I try to use it like <code>args.pm-export</code> I get the error that there is not attribute <code>pm</code>. How can I get around this issue? Is it possible to have <code>-</code> in command line options?</p>
<p>As <a href="http://docs.python.org/dev/library/argparse.html#dest" rel="noreferrer">indicated in the <code>argparse</code> docs</a>:</p> <blockquote> <p>For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and <strong>stripping away the initial <code>--</code> string</strong>. <strong>Any internal <code>-</code> characters will be converted to <code>_</code> characters</strong> to make sure the string is a valid attribute name</p> </blockquote> <p>So you should be using <code>args.pm_export</code>. </p>
{ "question_id": 12834785, "question_date": "2012-10-11T07:56:07.290Z", "question_score": 218, "tags": "python|argparse", "answer_id": 12834986, "answer_date": "2012-10-11T08:09:06.330Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: SwiftUI: How to implement a custom init with @Binding variables <p>I'm working on a money input screen and need to implement a custom <code>init</code> to set a state variable based on the initialized amount.</p> <p>I thought this would work, but I'm getting a compiler error of:</p> <p><code>Cannot assign value of type 'Binding&lt;Double&gt;' to type 'Double'</code></p> <pre><code>struct AmountView : View { @Binding var amount: Double @State var includeDecimal = false init(amount: Binding&lt;Double&gt;) { self.amount = amount self.includeDecimal = round(amount)-amount &gt; 0 } ... } </code></pre>
<p>Argh! You were so close. This is how you do it. You missed a dollar sign (beta 3) or underscore (beta 4), and either self in front of your amount property, or .value after the amount parameter. All these options work:</p> <p>You'll see that I removed the <code>@State</code> in <code>includeDecimal</code>, check the explanation at the end.</p> <p>This is using the property (put self in front of it):</p> <pre class="lang-swift prettyprint-override"><code>struct AmountView : View { @Binding var amount: Double private var includeDecimal = false init(amount: Binding&lt;Double&gt;) { // self.$amount = amount // beta 3 self._amount = amount // beta 4 self.includeDecimal = round(self.amount)-self.amount &gt; 0 } } </code></pre> <p>or using .value after (but without self, because you are using the passed parameter, not the struct's property):</p> <pre class="lang-swift prettyprint-override"><code>struct AmountView : View { @Binding var amount: Double private var includeDecimal = false init(amount: Binding&lt;Double&gt;) { // self.$amount = amount // beta 3 self._amount = amount // beta 4 self.includeDecimal = round(amount.value)-amount.value &gt; 0 } } </code></pre> <p><em><strong>This is the same, but we use different names for the parameter (withAmount) and the property (amount), so you clearly see when you are using each.</strong></em></p> <pre class="lang-swift prettyprint-override"><code>struct AmountView : View { @Binding var amount: Double private var includeDecimal = false init(withAmount: Binding&lt;Double&gt;) { // self.$amount = withAmount // beta 3 self._amount = withAmount // beta 4 self.includeDecimal = round(self.amount)-self.amount &gt; 0 } } </code></pre> <pre class="lang-swift prettyprint-override"><code>struct AmountView : View { @Binding var amount: Double private var includeDecimal = false init(withAmount: Binding&lt;Double&gt;) { // self.$amount = withAmount // beta 3 self._amount = withAmount // beta 4 self.includeDecimal = round(withAmount.value)-withAmount.value &gt; 0 } } </code></pre> <p><em><strong>Note that .value is not necessary with the property, thanks to the property wrapper (@Binding), which creates the accessors that makes the .value unnecessary. However, with the parameter, there is not such thing and you have to do it explicitly. If you would like to learn more about property wrappers, check the <a href="https://developer.apple.com/videos/play/wwdc2019/415/" rel="noreferrer">WWDC session 415 - Modern Swift API Design</a> and jump to 23:12.</strong></em></p> <p>As you discovered, modifying the @State variable from the initilizer will throw the following error: <em><strong>Thread 1: Fatal error: Accessing State outside View.body</strong></em>. To avoid it, you should either remove the @State. Which makes sense because includeDecimal is not a source of truth. Its value is derived from amount. By removing @State, however, <code>includeDecimal</code> will not update if amount changes. To achieve that, the best option, is to define your includeDecimal as a computed property, so that its value is derived from the source of truth (amount). This way, whenever the amount changes, your includeDecimal does too. If your view depends on includeDecimal, it should update when it changes:</p> <pre class="lang-swift prettyprint-override"><code>struct AmountView : View { @Binding var amount: Double private var includeDecimal: Bool { return round(amount)-amount &gt; 0 } init(withAmount: Binding&lt;Double&gt;) { self.$amount = withAmount } var body: some View { ... } } </code></pre> <p>As indicated by <em><strong>rob mayoff</strong></em>, you can also use <code>$$varName</code> (beta 3), or <code>_varName</code> (beta4) to initialise a State variable:</p> <pre class="lang-swift prettyprint-override"><code>// Beta 3: $$includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0) // Beta 4: _includeDecimal = State(initialValue: (round(amount.value) - amount.value) != 0) </code></pre>
{ "question_id": 56973959, "question_date": "2019-07-10T15:23:37.173Z", "question_score": 218, "tags": "swift|swiftui", "answer_id": 56975728, "answer_date": "2019-07-10T17:22:19.490Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: 'of' vs 'from' operator <p>Is the only difference between <code>Observable.of</code> and <code>Observable.from</code> the arguments format? Like the <code>Function.prototype.call</code> and <code>Function.prototype.apply</code>?</p> <pre><code>Observable.of(1,2,3).subscribe(() =&gt; {}) Observable.from([1,2,3]).subscribe(() =&gt; {}) </code></pre>
<p>Not quite. When passing an array to <code>Observable.from</code>, the only difference between it and <code>Observable.of</code> is the way the arguments are passed.</p> <p>However, <code>Observable.from</code> will accept an <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-from" rel="noreferrer">argument</a> that is</p> <blockquote> <p>a subscribable object, a Promise, an Observable-like, an Array, an iterable or an array-like object to be converted</p> </blockquote> <p>There is no similar behaviour for <code>Observable.of</code> - which always accepts only values and performs no conversion.</p>
{ "question_id": 42704552, "question_date": "2017-03-09T20:11:13.147Z", "question_score": 218, "tags": "rxjs", "answer_id": 42706216, "answer_date": "2017-03-09T21:56:27.667Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: Retargeting solution from .Net 4.0 to 4.5 - how to retarget the NuGet packages? <p>I have migrated a solution that is currently targeting .NET 4.0 in VS2010 to VS2012 and now I would like to re-target it to .Net 4.5</p> <p>What I am not sure about is the NuGet packages. For example EF5, which I updated from EF4 in VS2010 turns out to be actually EF 4.4 as you can see here:</p> <pre><code> &lt;Reference Include="EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"&gt; &lt;SpecificVersion&gt;False&lt;/SpecificVersion&gt; &lt;HintPath&gt;..\packages\EntityFramework.5.0.0\lib\net40\EntityFramework.dll&lt;/HintPath&gt; &lt;/Reference&gt; </code></pre> <p>I can also see the following in packages.config for the project:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;packages&gt; &lt;package id="EntityFramework" version="5.0.0" targetFramework="net40" /&gt; &lt;/packages&gt; </code></pre> <p>So my question is:</p> <p>What is the best practice to re-target all NuGet packages that are currently set to target .NET 4.0 to target .NET 4.5?</p>
<p><strong>NuGet 2.1</strong> offers a feature that makes this a lot simpler: just do <code>update-package -reinstall -ignoreDependencies</code> from the Package Manager Console.</p> <p><strong>NuGet 2.0</strong> doesn't handle re-targeting your applications very well. In order to change your packages' target frameworks, you must uninstall and reinstall the packages (taking note of the packages you had installed so that you can reinstall each of them).</p> <p>The reason packages must be uninstalled and reinstalled is:</p> <ul> <li>When installing a package, we determine the target framework of your project</li> <li>We then match that up with the package contents, finding the appropriate \lib\ folder (and \content\ folder)</li> <li>Assembly references are added with Hint Paths that point to the package's \lib\ folder, with the right subfolder (\lib\net40 for example)</li> <li>Content files are copied from the packages \content\ folder, with the right subfolder (\content\net40 for example)</li> <li>We record the targetFramework used to install the package within the packages.config file</li> <li>After you change your project's target framework, the Hint Paths still point to net40</li> <li>When you uninstall packages, we check the targetFramework that was recorded in packages.config to see what target framework's libs/content to remove from your project</li> <li>When you reinstall the package, we detect your updated target framework and reference/copy the right libs/content</li> </ul>
{ "question_id": 12006991, "question_date": "2012-08-17T13:42:36.880Z", "question_score": 218, "tags": ".net|nuget|visual-studio-2012|.net-4.5", "answer_id": 12012830, "answer_date": "2012-08-17T20:35:44.180Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: Get the name of the currently executing method <p><code>$0</code> is the variable for the top level Ruby program, but is there one for the current method?</p>
<p>Even better than my first answer you can use __method__:</p> <pre><code>class Foo def test_method __method__ end end </code></pre> <p>This returns a symbol – for example, <code>:test_method</code>. To return the method name as a string, call <code>__method__.to_s</code> instead.</p> <p><strong>Note:</strong> This requires Ruby 1.8.7.</p>
{ "question_id": 199527, "question_date": "2008-10-14T00:14:06.580Z", "question_score": 218, "tags": "ruby|reflection|metaprogramming", "answer_id": 199560, "answer_date": "2008-10-14T00:24:59.727Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: Google Guava vs. Apache Commons <p>I was looking for a <a href="http://en.wikipedia.org/wiki/Bidirectional_map" rel="noreferrer">bidirectional map</a> implementation in Java, and stumbled upon these two libraries:</p> <ul> <li><a href="https://github.com/google/guava" rel="noreferrer">Google Guava</a> (formerly "Google Collections")</li> <li><a href="http://commons.apache.org/collections/" rel="noreferrer">Apache Commons Collections</a></li> </ul> <p>Both are free, have the bidirectional map implementation that I was looking for (BidiMap in Apache, BiMap in Google), are amazingly nearly the same size (Apache 493 kB, Google 499 kB) [ed.: no longer true!] and seem in all ways pretty similar to me.</p> <p>Which one should I choose, and why? Are there some other equivalent alternatives (must be free and have at least the bidirectional map)? I'm working with the latest Java SE, so no need to artificially limit to Java 5 or anything like that.</p>
<p>In my opinion the better choice is <a href="https://github.com/google/guava" rel="noreferrer"><strong>Guava</strong></a> (formerly known as Google collections):</p> <ul> <li>it's more modern (has generics)</li> <li>it absolutely follows the Collections API requirements</li> <li>it's actively maintained</li> <li><a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/cache/CacheBuilder.html" rel="noreferrer"><code>CacheBuilder</code></a> and it's predecessor <a href="https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/MapMaker.html" rel="noreferrer"><code>MapMaker</code></a> are just plain awesome</li> </ul> <p>Apache Commons Collections is a good library as well, but it has long failed to provide a generics-enabled version (which is a <em>major</em> drawback for a collections API in my opinion) and generally seems to be in a maintenance/don't-do-too-much-work-on-it mode <sub>Recently Commons Collections has picked up some steam again, but it has some catching up to do.</sub>.</p> <p>If download size/memory footprint/code size is an issue then Apache Commons Collections might be a better candidate, since it is a common dependency of other libraries. Therefore using it in your own code as well could potentially be done without adding any additional dependencies. Edit: This particular "advantage" has been partially subverted by now, since many new libraries actually depend on Guava and <em>not</em> on Apache Commons Collections.</p>
{ "question_id": 1444437, "question_date": "2009-09-18T13:05:16.190Z", "question_score": 218, "tags": "java|collections|apache-commons|guava", "answer_id": 1444467, "answer_date": "2009-09-18T13:10:49.780Z", "answer_score": 189 }
Please answer the following Stack Overflow question: Title: Access a variable outside the scope of a Handlebars.js each loop <p>I have a handlebars.js template, just like this:</p> <pre><code>{{externalValue}} &lt;select name="test"&gt; {{#each myCollection}} &lt;option value="{{id}}"&gt;{{title}} {{externalValue}}&lt;/option&gt; {{/each}} &lt;/select&gt; </code></pre> <p>And this is the generated output:</p> <pre><code>myExternalValue &lt;select name="test"&gt; &lt;option value="1"&gt;First element &lt;/option&gt; &lt;option value="2"&gt;Second element &lt;/option&gt; &lt;option value="3"&gt;Third element &lt;/option&gt; &lt;/select&gt; </code></pre> <p>As expected, I can access the <code>id</code> and <code>title</code> fields of every element of <code>myCollection</code> to generate my select. And outside the select, my <code>externalValue</code> variable is correctly printed ("myExternalValue").</p> <p>Unfortunately, in options' texts, <code>externalValue</code> value is never printed out.</p> <p>My question is: how can I access a variable outside the scope of the handlebars.js each from within the loop? </p>
<p>Try</p> <pre><code>&lt;option value="{{id}}"&gt;{{title}} {{../externalValue}}&lt;/option&gt; </code></pre> <p>The <code>../</code> path segment references the parent template scope that should be what you want.</p>
{ "question_id": 13645084, "question_date": "2012-11-30T12:17:04.133Z", "question_score": 218, "tags": "javascript|templates|scope|each|handlebars.js", "answer_id": 13645315, "answer_date": "2012-11-30T12:30:40.783Z", "answer_score": 525 }
Please answer the following Stack Overflow question: Title: How do you make a web application in Clojure? <p>I suppose this is a strange question to the huge majority of programmers that work daily with Java. I don't. I know Java-the-language, because I worked on Java projects, but not Java-the-world. I never made a web app from scratch in Java. If I have to do it with Python, Ruby, I know where to go (Django or Rails), but if I want to make a web application in Clojure, not because I'm forced to live in a Java world, but because I like the language and I want to give it a try, what libraries and frameworks should I use?</p>
<p>By far the best Clojure web framework I have yet encountered is Compojure: <a href="http://github.com/weavejester/compojure/tree/master" rel="noreferrer">http://github.com/weavejester/compojure/tree/master</a></p> <p>It's small but powerful, and has beautifully elegant syntax. (It uses Jetty under the hood, but it hides the Servlet API from you unless you want it, which won't be often). Go look at the README at that URL, then download a snapshot and start playing.</p>
{ "question_id": 167262, "question_date": "2008-10-03T14:52:58.087Z", "question_score": 218, "tags": "clojure", "answer_id": 194343, "answer_date": "2008-10-11T17:23:33.680Z", "answer_score": 104 }
Please answer the following Stack Overflow question: Title: How do I declare an array of weak references in Swift? <p>I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa <code>NSPointerArray</code> offers a non-typesafe version of this.</p>
<p>Create a generic wrapper as:</p> <pre><code>class Weak&lt;T: AnyObject&gt; { weak var value : T? init (value: T) { self.value = value } } </code></pre> <p>Add instances of this class to your array.</p> <pre><code>class Stuff {} var weakly : [Weak&lt;Stuff&gt;] = [Weak(value: Stuff()), Weak(value: Stuff())] </code></pre> <p>When defining <code>Weak</code> you can use either <code>struct</code> or <code>class</code>.</p> <p>Also, to help with reaping array contents, you could do something along the lines of:</p> <pre><code>extension Array where Element:Weak&lt;AnyObject&gt; { mutating func reap () { self = self.filter { nil != $0.value } } } </code></pre> <p>The use of <code>AnyObject</code> above should be replaced with <code>T</code> - but I don't think the current Swift language allows an extension defined as such.</p>
{ "question_id": 24127587, "question_date": "2014-06-09T19:34:30.443Z", "question_score": 218, "tags": "swift|automatic-ref-counting|weak-references|nspointerarray", "answer_id": 24128121, "answer_date": "2014-06-09T20:07:46.207Z", "answer_score": 180 }
Please answer the following Stack Overflow question: Title: Are there any legitimate use-cases for "goto" in a language that supports loops and functions? <p>I've long been under the impression that <code>goto</code> should never be used if possible.</p> <p>However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it.</p> <p>Is it ever advantageous to use <code>goto</code> in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a <code>goto</code>.</p>
<p>There are a few reasons for using the "goto" statement that I'm aware of (some have spoken to this already):</p> <p><strong>Cleanly exiting a function</strong></p> <p>Often in a function, you may allocate resources and need to exit in multiple places. Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label. This way, you don't have to write cleanup code at every "exit point" of the function.</p> <p><strong>Exiting nested loops</strong></p> <p>If you're in a nested loop and need to break out of <em>all</em> loops, a goto can make this much cleaner and simpler than break statements and if-checks.</p> <p><strong>Low-level performance improvements</strong></p> <p>This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function. This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos.</p> <p>Note that in all these examples, gotos are restricted to the scope of a single function.</p>
{ "question_id": 24451, "question_date": "2008-08-23T18:18:04.933Z", "question_score": 218, "tags": "language-agnostic|goto", "answer_id": 24476, "answer_date": "2008-08-23T18:42:33.003Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: Understanding exactly when a data.table is a reference to (vs a copy of) another data.table <p>I'm having a little trouble understanding the pass-by-reference properties of <code>data.table</code>. Some operations seem to 'break' the reference, and I'd like to understand exactly what's happening.</p> <p>On creating a <code>data.table</code> from another <code>data.table</code> (via <code>&lt;-</code>, then updating the new table by <code>:=</code>, the original table is also altered. This is expected, as per:</p> <p><code>?data.table::copy</code> and <a href="https://stackoverflow.com/questions/8030452/pass-by-reference-the-operator-in-the-data-table-package">stackoverflow: pass-by-reference-the-operator-in-the-data-table-package</a></p> <p>Here's an example:</p> <pre><code>library(data.table) DT &lt;- data.table(a=c(1,2), b=c(11,12)) print(DT) # a b # [1,] 1 11 # [2,] 2 12 newDT &lt;- DT # reference, not copy newDT[1, a := 100] # modify new DT print(DT) # DT is modified too. # a b # [1,] 100 11 # [2,] 2 12 </code></pre> <p>However, if I insert a non-<code>:=</code> based modification between the <code>&lt;-</code> assignment and the <code>:=</code> lines above, <code>DT</code> is now no longer modified:</p> <pre><code>DT = data.table(a=c(1,2), b=c(11,12)) newDT &lt;- DT newDT$b[2] &lt;- 200 # new operation newDT[1, a := 100] print(DT) # a b # [1,] 1 11 # [2,] 2 12 </code></pre> <p>So it seems that the <code>newDT$b[2] &lt;- 200</code> line somehow 'breaks' the reference. I'd guess that this invokes a copy somehow, but I would like to understand fully how R is treating these operations, to ensure I don't introduce potential bugs in my code.</p> <p>I'd very much appreciate if someone could explain this to me.</p>
<p>Yes, it's subassignment in R using <code>&lt;-</code> (or <code>=</code> or <code>-&gt;</code>) that makes a copy of the <em>whole</em> object. You can trace that using <code>tracemem(DT)</code> and <code>.Internal(inspect(DT))</code>, as below. The <code>data.table</code> features <code>:=</code> and <code>set()</code> assign by reference to whatever object they are passed. So if that object was previously copied (by a subassigning <code>&lt;-</code> or an explicit <code>copy(DT)</code>) then it's the copy that gets modified by reference.</p> <pre><code>DT &lt;- data.table(a = c(1, 2), b = c(11, 12)) newDT &lt;- DT .Internal(inspect(DT)) # @0000000003B7E2A0 19 VECSXP g0c7 [OBJ,NAM(2),ATT] (len=2, tl=100) # @00000000040C2288 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040C2250 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,12 # ATTRIB: # ..snip.. .Internal(inspect(newDT)) # precisely the same object at this point # @0000000003B7E2A0 19 VECSXP g0c7 [OBJ,NAM(2),ATT] (len=2, tl=100) # @00000000040C2288 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040C2250 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,12 # ATTRIB: # ..snip.. tracemem(newDT) # [1] "&lt;0x0000000003b7e2a0" newDT$b[2] &lt;- 200 # tracemem[0000000003B7E2A0 -&gt; 00000000040ED948]: # tracemem[00000000040ED948 -&gt; 00000000040ED830]: .Call copy $&lt;-.data.table $&lt;- .Internal(inspect(DT)) # @0000000003B7E2A0 19 VECSXP g0c7 [OBJ,NAM(2),TR,ATT] (len=2, tl=100) # @00000000040C2288 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040C2250 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,12 # ATTRIB: # ..snip.. .Internal(inspect(newDT)) # @0000000003D97A58 19 VECSXP g0c7 [OBJ,NAM(2),ATT] (len=2, tl=100) # @00000000040ED7F8 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040ED8D8 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,200 # ATTRIB: # ..snip.. </code></pre> <p>Notice how even the <code>a</code> vector was copied (different hex value indicates new copy of vector), even though <code>a</code> wasn't changed. Even the whole of <code>b</code> was copied, rather than just changing the elements that need to be changed. That's important to avoid for large data, and why <code>:=</code> and <code>set()</code> were introduced to <code>data.table</code>.</p> <p>Now, with our copied <code>newDT</code> we can modify it by reference :</p> <pre><code>newDT # a b # [1,] 1 11 # [2,] 2 200 newDT[2, b := 400] # a b # See FAQ 2.21 for why this prints newDT # [1,] 1 11 # [2,] 2 400 .Internal(inspect(newDT)) # @0000000003D97A58 19 VECSXP g0c7 [OBJ,NAM(2),ATT] (len=2, tl=100) # @00000000040ED7F8 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040ED8D8 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,400 # ATTRIB: # ..snip .. </code></pre> <p>Notice that all 3 hex values (the vector of column points, and each of the 2 columns) remain unchanged. So it was truly modified by reference with no copies at all.</p> <p>Or, we can modify the original <code>DT</code> by reference :</p> <pre><code>DT[2, b := 600] # a b # [1,] 1 11 # [2,] 2 600 .Internal(inspect(DT)) # @0000000003B7E2A0 19 VECSXP g0c7 [OBJ,NAM(2),ATT] (len=2, tl=100) # @00000000040C2288 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 1,2 # @00000000040C2250 14 REALSXP g0c2 [NAM(2)] (len=2, tl=0) 11,600 # ATTRIB: # ..snip.. </code></pre> <p>Those hex values are the same as the original values we saw for <code>DT</code> above. Type <code>example(copy)</code> for more examples using <code>tracemem</code> and comparison to <code>data.frame</code>.</p> <p>Btw, if you <code>tracemem(DT)</code> then <code>DT[2,b:=600]</code> you'll see one copy reported. That is a copy of the first 10 rows that the <code>print</code> method does. When wrapped with <code>invisible()</code> or when called within a function or script, the <code>print</code> method isn't called. </p> <p>All this applies inside functions too; i.e., <code>:=</code> and <code>set()</code> do not copy on write, even within functions. If you need to modify a local copy, then call <code>x=copy(x)</code> at the start of the function. But, remember <code>data.table</code> is for large data (as well as faster programming advantages for small data). We deliberately don't want to copy large objects (ever). As a result we don't need to allow for the usual 3* working memory factor rule of thumb. We try to only need working memory as large as one column (i.e. a working memory factor of 1/ncol rather than 3).</p>
{ "question_id": 10225098, "question_date": "2012-04-19T09:19:30.800Z", "question_score": 218, "tags": "r|reference|copy|data.table|assignment-operator", "answer_id": 10226454, "answer_date": "2012-04-19T10:49:24.990Z", "answer_score": 150 }
Please answer the following Stack Overflow question: Title: Why use non-member begin and end functions in C++11? <p>Every standard container has a <code>begin</code> and <code>end</code> method for returning iterators for that container. However, C++11 has apparently introduced free functions called <a href="http://en.cppreference.com/w/cpp/iterator/begin" rel="noreferrer"><code>std::begin</code></a> and <a href="http://en.cppreference.com/w/cpp/iterator/end" rel="noreferrer"><code>std::end</code></a> which call the <code>begin</code> and <code>end</code> member functions. So, instead of writing</p> <pre><code>auto i = v.begin(); auto e = v.end(); </code></pre> <p>you'd write</p> <pre><code>auto i = std::begin(v); auto e = std::end(v); </code></pre> <p>In his talk, <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T" rel="noreferrer">Writing Modern C++</a>, Herb Sutter says that you should always use the free functions now when you want the begin or end iterator for a container. However, he does not go into detail as to <em>why</em> you would want to. Looking at the code, it saves you all of one character. So, as far as the standard containers go, the free functions seem to be completely useless. Herb Sutter indicated that there were benefits for non-standard containers, but again, he didn't go into detail.</p> <p>So, the question is what exactly do the free function versions of <code>std::begin</code> and <code>std::end</code> do beyond calling their corresponding member function versions, and why would you want to use them?</p>
<p>How do you call <code>.begin()</code> and <code>.end()</code> on a C-array ?</p> <p>Free-functions allow for more generic programming because they can be added afterwards, on a data-structure you cannot alter.</p>
{ "question_id": 7593086, "question_date": "2011-09-29T06:00:08.763Z", "question_score": 218, "tags": "c++|c++11|stl|iterator|container-data-type", "answer_id": 7593152, "answer_date": "2011-09-29T06:07:01.550Z", "answer_score": 172 }
Please answer the following Stack Overflow question: Title: Difference between `data` and `newtype` in Haskell <p>What is the difference when I write this?</p> <pre><code>data Book = Book Int Int </code></pre> <p>versus</p> <pre><code>newtype Book = Book (Int, Int) -- "Book Int Int" is syntactically invalid </code></pre>
<p>Great question!</p> <p>There are several key differences.</p> <p><strong>Representation</strong></p> <ul> <li>A <code>newtype</code> guarantees that your data will have exactly the same representation at runtime, as the type that you wrap.</li> <li>While <code>data</code> declares a brand new data structure at runtime.</li> </ul> <p>So the key point here is that the construct for the <code>newtype</code> is guaranteed to be erased at compile time. </p> <p>Examples:</p> <ul> <li><code>data Book = Book Int Int</code></li> </ul> <p><img src="https://i.stack.imgur.com/PQWvT.png" alt="data"></p> <ul> <li><code>newtype Book = Book (Int, Int)</code></li> </ul> <p><img src="https://i.stack.imgur.com/Qca1X.png" alt="newtype"></p> <p>Note how it has exactly the same representation as a <code>(Int,Int)</code>, since the <code>Book</code> constructor is erased.</p> <ul> <li><code>data Book = Book (Int, Int)</code></li> </ul> <p><img src="https://i.stack.imgur.com/FwKcy.png" alt="data tuple"></p> <p>Has an additional <code>Book</code> constructor not present in the <code>newtype</code>.</p> <ul> <li><code>data Book = Book {-# UNPACK #-}!Int {-# UNPACK #-}!Int</code></li> </ul> <p><img src="https://i.stack.imgur.com/btUqH.png" alt="enter image description here"></p> <p>No pointers! The two <code>Int</code> fields are unboxed word-sized fields in the <code>Book</code> constructor.</p> <p><strong>Algebraic data types</strong></p> <p>Because of this need to erase the constructor, a <code>newtype</code> only works when wrapping a data type with <strong>a single constructor</strong>. There's no notion of "algebraic" newtypes. That is, you can't write a newtype equivalent of, say,</p> <pre><code>data Maybe a = Nothing | Just a </code></pre> <p>since it has more than one constructor. Nor can you write</p> <pre><code>newtype Book = Book Int Int </code></pre> <p><strong>Strictness</strong></p> <p>The fact that the constructor is erased leads to some very subtle differences in strictness between <code>data</code> and <code>newtype</code>. In particular, <code>data</code> introduces a type that is "lifted", meaning, essentially, that it has an additional way to evaluate to a bottom value. Since there's no additional constructor at runtime with <code>newtype</code>, this property doesn't hold. </p> <p>That extra pointer in the <code>Book</code> to <code>(,)</code> constructor allows us to put a bottom value in.</p> <p>As a result, <code>newtype</code> and <code>data</code> have slightly different strictness properties, as <a href="http://www.haskell.org/haskellwiki/Newtype#The_messy_bits" rel="noreferrer">explained in the Haskell wiki article</a>.</p> <p><strong>Unboxing</strong></p> <p>It doesn't make sense to unbox the components of a <code>newtype</code>, since there's no constructor. While it is perfectly reasonable to write:</p> <pre><code>data T = T {-# UNPACK #-}!Int </code></pre> <p>yielding a runtime object with a <code>T</code> constructor, and an <code>Int#</code> component. You just get a bare <code>Int</code> with <code>newtype</code>.</p> <hr> <p><em>References</em>:</p> <ul> <li><a href="http://www.haskell.org/haskellwiki/Newtype" rel="noreferrer">"Newtype" on the Haskell wiki</a></li> <li><a href="https://stackoverflow.com/questions/2649305/why-is-there-data-and-newtype-in-haskell/2650051#2650051">Norman Ramsey's answer</a> about the strictness properties</li> </ul>
{ "question_id": 5889696, "question_date": "2011-05-04T20:50:49.420Z", "question_score": 218, "tags": "haskell|types|type-systems|newtype", "answer_id": 5889784, "answer_date": "2011-05-04T20:58:39.923Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Why does the JavaScript need to start with ";"? <p>I have recently noticed that a lot of JavaScript files on the Web start with a <code>;</code> immediately following the comment section.</p> <p>For example, <a href="http://plugins.jquery.com/project/ScrollTo" rel="noreferrer">this jQuery plugin's</a> code starts with:</p> <pre><code>/** * jQuery.ScrollTo * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under MIT and GPL. * Date: 9/11/2008 .... skipping several lines for brevity... * * @desc Scroll on both axes, to different values * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } ); */ ;(function( $ ){ </code></pre> <p>Why does the file need to start with a <code>;</code>? I see this convention in server-side JavaScript files as well.</p> <p>What are the advantages and disadvantages of doing this?</p>
<p>I would say since scripts are often concatenated and minified/compressed/sent together there's a chance the last guy had something like:</p> <pre><code>return { 'var':'value' } </code></pre> <p>at the end of the last script without a <code>;</code> on the end. If you have a <code>;</code> at the start on yours, it's safe, example:</p> <pre><code>return { 'var':'value' } ;(function( $ ){ //Safe (still, screw you, last guy!) </code></pre> <hr> <pre><code>return { 'var':'value' } (function( $ ){ //Oh crap, closure open, kaboom! </code></pre> <hr> <pre><code>return { 'var':'value' }; ;(function( $ ){ //Extra ;, still safe, no harm </code></pre>
{ "question_id": 2481543, "question_date": "2010-03-20T01:33:46.720Z", "question_score": 218, "tags": "javascript|jquery|jquery-plugins|serverside-javascript", "answer_id": 2481560, "answer_date": "2010-03-20T01:39:33.807Z", "answer_score": 352 }
Please answer the following Stack Overflow question: Title: Best way to do nested case statement logic in SQL Server <p>I'm writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.</p> <p>I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?</p> <p>(I am using Microsoft SQL Server, 2005)</p> <hr> <p>A simplified example:</p> <pre><code>SELECT col1, col2, col3, CASE WHEN condition THEN CASE WHEN condition1 THEN CASE WHEN condition2 THEN calculation1 ELSE calculation2 END ELSE CASE WHEN condition2 THEN calculation3 ELSE calculation4 END END ELSE CASE WHEN condition1 THEN CASE WHEN condition2 THEN calculation5 ELSE calculation6 END ELSE CASE WHEN condition2 THEN calculation7 ELSE calculation8 END END END AS 'calculatedcol1', col4, col5 -- etc FROM table </code></pre>
<p>You could try some sort of COALESCE trick, eg:</p> <pre> SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... ) </pre>
{ "question_id": 505747, "question_date": "2009-02-03T01:39:04.123Z", "question_score": 217, "tags": "sql|sql-server|sql-server-2005|select|nested", "answer_id": 505760, "answer_date": "2009-02-03T01:44:10.183Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: Creating an array of objects in Java <p>I am new to Java and for the time created an array of objects in Java. </p> <p>I have a class A for example - </p> <pre><code>A[] arr = new A[4]; </code></pre> <p>But this is only creating pointers (references) to <code>A</code> and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception. To be able to manipulate/access the objects I had to do this:</p> <pre><code>A[] arr = new A[4]; for (int i = 0; i &lt; 4; i++) { arr[i] = new A(); } </code></pre> <p>Is this correct or am I doing something wrong? If this is correct its really odd.</p> <p>EDIT: I find this odd because in C++ you just say new <code>A[4]</code> and it creates the four objects.</p>
<p>This is correct.</p> <pre><code>A[] a = new A[4]; </code></pre> <p>...creates 4 <code>A</code> references, similar to doing this:</p> <pre><code>A a1; A a2; A a3; A a4; </code></pre> <p>Now you couldn't do <code>a1.someMethod()</code> without allocating <code>a1</code> like this:</p> <pre><code>a1 = new A(); </code></pre> <p>Similarly, with the array you need to do this:</p> <pre><code>a[0] = new A(); </code></pre> <p>...before using it.</p>
{ "question_id": 5364278, "question_date": "2011-03-19T19:13:08.553Z", "question_score": 217, "tags": "java|arrays|class", "answer_id": 5364320, "answer_date": "2011-03-19T19:19:20.563Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: Set database from SINGLE USER mode to MULTI USER <p>I need help with setting a database that was restored in <code>SINGLE_USER</code> mode to <code>MULTI_USER</code>. Every time I run</p> <pre><code>ALTER DATABASE BARDABARD SET MULTI_USER; GO </code></pre> <p>I get this error:</p> <blockquote> <p>Changes to the state or options of database 'BARDABARD' cannot be made at this time.</p> <p>The database is in single-user mode, and a user is currently connected to it.</p> </blockquote> <p>It needs to be in non-<code>SINGLE_USER</code> mode to set it to another mode, but I can’t set the database in any another mode while it is <code>SINGLE_USER</code> mode.</p>
<p>The “user is currently connected to it” might be SQL Server Management Studio window itself. Try selecting the master database and running the <code>ALTER</code> query again.</p>
{ "question_id": 14652923, "question_date": "2013-02-01T18:39:28.553Z", "question_score": 217, "tags": "sql|sql-server", "answer_id": 14653003, "answer_date": "2013-02-01T18:45:56.687Z", "answer_score": 134 }
Please answer the following Stack Overflow question: Title: Unresolved external symbol in object files <p>During coding in Visual Studio I got an unresolved external symbol error and I've got no idea what to do. I don't know what's wrong. Could you please decipher me? Where should I be looking for what kind of errors?</p> <pre><code>1&gt;Form.obj : error LNK2019: unresolved external symbol "public: class Field * __thiscall Field::addField(class Field *)" (?addField@Field@@QAEPAV1@PAV1@@Z) referenced in function "public: void __thiscall Form::parse(class std::basic_stringstream&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; &amp;)" (?parse@Form@@QAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) 1&gt;Form.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Field::parse(class std::basic_stringstream&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; &amp;)" (?parse@Field@@UAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: __thiscall InputField::InputField(class std::basic_stringstream&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; &amp;)" (??0InputField@@QAE@AAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) 1&gt;Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::prompt(void)" (?prompt@Field@@UAEXXZ) 1&gt;Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __thiscall Field::getName(void)" (?getName@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) 1&gt;Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __thiscall Field::getType(void)" (?getType@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) 1&gt;Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::describe(void)" (?describe@Field@@UAEXXZ) 1&gt;C:\Users\tomy\Documents\Visual Studio 2010\Projects\zapoctovkac++\Debug\zapoctovkac++.exe : fatal error LNK1120: 6 unresolved externals </code></pre>
<p>This error often means that some function has a declaration, but not a definition.</p> <p>Example:</p> <pre><code>// A.hpp class A { public: void myFunc(); // Function declaration }; // A.cpp // Function definition void A::myFunc() { // do stuff } </code></pre> <p><strong>In your case, the definition cannot be found.</strong> The issue could be that you are including a header file, which brings in some function declarations, but you either:</p> <ol> <li>do not define the functions in your cpp file (if you wrote this code yourself)</li> <li>do not include the lib/dll file that contains the definitions </li> </ol> <p>A common mistake is that you define a function as a standalone and forget the class selector, e.g. <code>A::</code>, in your <em>.cpp</em> file:</p> <p><strong>Wrong:</strong> <code>void myFunc() { /* do stuff */ }</code> <br><strong>Right:</strong> <code>void A::myFunc() { /* do stuff */ }</code></p>
{ "question_id": 9928238, "question_date": "2012-03-29T15:11:28.883Z", "question_score": 217, "tags": "c++|visual-studio|visual-c++|unresolved-external", "answer_id": 9928586, "answer_date": "2012-03-29T15:29:14.200Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: jQuery `.is(":visible")` not working in Chrome <pre><code>if ($("#makespan").is(":visible") == true) { var make = $("#make").val(); } else { var make = $("#othermake").val(); } Make:&lt;span id=makespan&gt;&lt;select id=make&gt;&lt;/select&gt;&lt;span id=othermakebutton class=txtbutton&gt;Other?&lt;/span&gt;&lt;/span&gt;&lt;span id=othermakespan style="display: none;"&gt;&lt;input type=text name=othermake id=othermake&gt;&amp;nbsp;-&amp;nbsp;&lt;span id=othermakecancel class=txtbutton&gt;Cancel&lt;/span&gt;&lt;/span&gt; </code></pre> <p>The above code runs smooth in Firefox, but doesn't seem to work in Chrome. In Chrome it shows <code>.is(":visible") = false</code> even when it is <code>true</code>.</p> <p>I am using following jQuery version: jquery-1.4.3.min.js</p> <p>jsFiddle Link: <a href="http://jsfiddle.net/WJU2r/4/" rel="noreferrer">http://jsfiddle.net/WJU2r/4/</a></p>
<p>It seems jQuery's <code>:visible</code> selector does not work for some inline elements in Chrome. The solution is to add a display style, like <code>"block"</code> or <code>"inline-block"</code> to make it work.</p> <p>Also note that jQuery has a somewhat different definition of what is visible than many developers:</p> <blockquote> <p><strong>Elements are considered visible if they consume space in the document.</strong><br> Visible elements have a width or height that is greater than zero.</p> </blockquote> <p>In other words, an element must have a non-zero width and height to consume space and be visible.</p> <blockquote> <p>Elements with <code>visibility: hidden</code> or <code>opacity: 0</code> are considered visible, since they still consume space in the layout.</p> </blockquote> <p>On the other hand, even if its <code>visibility</code> is set to <code>hidden</code> or the opacity is zero, it's still <code>:visible</code> to jQuery as it consumes space, which can be confusing when the CSS explicitly says its visibility is hidden.</p> <blockquote> <p>Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.</p> <p>All option elements are considered hidden, regardless of their selected state.</p> <p>During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.</p> </blockquote> <p>The easy way to look at it, is that if you can see the element on the screen, even if you can't see its content, it's transparent etc., it's visible, i.e. it takes up space.</p> <p>I cleaned up your markup a little and added a display style (<strong>i.e. setting the elements display to "block" etc</strong>), and this works for me: </p> <p><a href="http://jsfiddle.net/WJU2r/4/" rel="noreferrer"><strong>FIDDLE</strong></a></p> <p><a href="http://api.jquery.com/visible-selector/" rel="noreferrer">Official API reference for <code>:visible</code></a></p> <hr> <p>As of jQuery 3, the definition of <code>:visible</code> has changed slightly</p> <blockquote> <p>jQuery 3 slightly modifies the meaning of <code>:visible</code> (and therefore of <code>:hidden</code>).<br> Starting with this version, elements will be considered <code>:visible</code> if they have any layout boxes, including those of zero width and/or height. For example, <code>br</code> elements and inline elements with no content will be selected by the <code>:visible</code> selector.</p> </blockquote>
{ "question_id": 8337186, "question_date": "2011-12-01T06:01:45.127Z", "question_score": 217, "tags": "jquery|google-chrome", "answer_id": 8337382, "answer_date": "2011-12-01T06:30:43.113Z", "answer_score": 284 }
Please answer the following Stack Overflow question: Title: How can I remove an SSH key? <p>I currently have an old SSH key uploaded on a server. The problem is I lost my <code>~/.ssh</code> directory (with the original <code>id_rsa</code> and <code>id_rsa.pub</code> files).</p> <p>Consequently, I want to remove the old SSH key directly on the server and upload a new one.</p> <p>I tried the following command without success:</p> <pre><code>$&gt; ssh-add -D </code></pre> <p><img src="https://i.stack.imgur.com/TCNOE.png" alt="Enter image description here" /></p> <p>Is there a way to completely remove an SSH key?</p>
<p>Note that there are at least two bug reports for <code>ssh-add -d/-D</code> <em>not</em> removing keys:</p> <ul> <li>&quot;<a href="https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=472477" rel="noreferrer">Debian Bug report #472477: <code>ssh-add -D</code> does not remove SSH key from <code>gnome-keyring-daemon</code> memory</a>&quot;</li> <li>&quot;<a href="https://bugs.launchpad.net/ubuntu/+source/openssh/+bug/505278" rel="noreferrer">Ubuntu: <code>ssh-add -D</code> deleting all identities does not work. Also, why are all identities auto-added?</a>&quot;</li> </ul> <p>The exact issue is:</p> <blockquote> <p><code>ssh-add -d/-D</code> deletes only <em>manually added</em> keys from gnome-keyring.<br /> There is no way to delete automatically added keys.<br /> This is the original bug, and it's still definitely present.</p> <p>So, for example, if you have two different automatically-loaded ssh identities associated with two different GitHub accounts -- say for work and for home -- there's <em>no way</em> to switch between them. GitHubtakes the first one which matches, so you always appear as your 'home' user to GitHub, with no way to upload things to work projects.</p> <p>Allowing <code>ssh-add -d</code> to apply to <em>automatically-loaded</em> keys (and <code>ssh-add -t X</code> to change the lifetime of automatically-loaded keys), would restore the behavior most users expect.</p> </blockquote> <hr /> <p>More precisely, about the issue:</p> <blockquote> <p>The culprit is <code>gpg-keyring-daemon</code>:</p> <ul> <li>It subverts the normal operation of ssh-agent, mostly just so that it can pop up a pretty box into which you can type the passphrase for an encrypted ssh key.</li> <li>And it paws through your <code>.ssh</code> directory, and automatically adds any keys it finds to your agent.</li> <li>And it won't let you delete those keys.</li> </ul> <p>How do we hate this? Let's not count the ways -- life's too short.</p> <p>The failure is compounded because newer ssh clients automatically try all the keys in your ssh-agent when connecting to a host.<br /> If there are too many, the server will reject the connection.<br /> And since gnome-keyring-daemon has decided for itself how many keys you want your ssh-agent to have, and has autoloaded them, AND WON'T LET YOU DELETE THEM, you're toast.</p> </blockquote> <p>This bug is still confirmed in Ubuntu 14.04.4, as recently as two days ago (August 21st, 2014)</p> <hr /> <p>A possible workaround:</p> <blockquote> <ul> <li>Do <code>ssh-add -D</code> to delete all your <em>manually</em> added keys. This also locks the automatically added keys, but is not much use since <code>gnome-keyring</code> will ask you to unlock them anyways when you try doing a <code>git push</code>.</li> <li>Navigate to your <code>~/.ssh</code> folder and move all your key files except the one you want to identify with into a separate folder called backup. If necessary you can also open seahorse and delete the keys from there.</li> <li>Now you should be able to do <code>git push</code> without a problem.</li> </ul> </blockquote> <hr /> <p>Another workaround:</p> <blockquote> <p>What you really want to do is to turn off <code>gpg-keyring-daemon</code> altogether.<br /> Go to <code>System --&gt; Preferences --&gt; Startup Applications</code>, and unselect the &quot;<code>SSH Key Agent (Gnome Keyring SSH Agent)</code>&quot; box -- you'll need to scroll down to find it.</p> <p>You'll still get an <code>ssh-agent</code>, only now it will behave sanely: no keys autoloaded, you run ssh-add to add them, and if you want to delete keys, you can. Imagine that.</p> </blockquote> <p><a href="https://superuser.com/questions/281217/cant-remove-keys-from-ssh-agent-even-rebooting-doesnt-help#comment739325_301444">This comments</a> actually suggests:</p> <blockquote> <p>The solution is to keep <code>gnome-keyring-manager</code> from ever starting up, which was strangely difficult by finally achieved by removing the program file's execute permission.</p> </blockquote> <hr /> <p><a href="https://stackoverflow.com/users/4865822/ryan-lue">Ryan Lue</a> adds another interesting corner case <a href="https://stackoverflow.com/questions/25464930/how-to-remove-an-ssh-key/25465155?noredirect=1#comment106007588_25465155">in the comments</a>:</p> <blockquote> <p>In case this helps anyone: I even tried deleting the <code>id_rsa</code> and <code>id_rsa.pub</code> files altogether, and the key was still showing up.</p> <p>Turns out <strong><code>gpg-agent</code> was caching them in a <code>~/.gnupg/sshcontrol</code> file</strong>; I had to manually delete them from there.</p> </blockquote> <p>That is the case when <a href="https://incenp.org/notes/2015/gnupg-for-ssh-authentication.html" rel="noreferrer">the <strong><code>keygrip</code></strong></a> has been added <a href="https://stackoverflow.com/a/48922829/6309">as in here</a>.</p>
{ "question_id": 25464930, "question_date": "2014-08-23T18:13:15.540Z", "question_score": 217, "tags": "git|ssh|git-svn|ssh-keys|ssh-keygen", "answer_id": 25465155, "answer_date": "2014-08-23T18:37:15.597Z", "answer_score": 169 }
Please answer the following Stack Overflow question: Title: CSS: center element within a <div> element <p>To center an HTML element I can use the CSS <code>left: 50%;</code>. However, this centers the element with respect to the whole window.</p> <p>I have an element which is a child of a <code>&lt;div&gt;</code> element and I want to center the child with respect to this parent <code>&lt;div&gt;</code>, not the whole window.</p> <p>I do not want the container <code>&lt;div&gt;</code> to have <em>all</em> its content centered, just the one specific child.</p>
<p>Set <code>text-align:center;</code> to the parent div, and <code>margin:auto;</code> to the child div.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#parent { text-align:center; background-color:blue; height:400px; width:600px; } .block { height:100px; width:200px; text-align:left; } .center { margin:auto; background-color:green; } .left { margin:auto auto auto 0; background-color:red; } .right { margin:auto 0 auto auto; background-color:yellow; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="parent"&gt; &lt;div id="child1" class="block center"&gt; a block to align center and with text aligned left &lt;/div&gt; &lt;div id="child2" class="block left"&gt; a block to align left and with text aligned left &lt;/div&gt; &lt;div id="child3" class="block right"&gt; a block to align right and with text aligned left &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This a good resource to center mostly anything.<br> <a href="http://howtocenterincss.com/" rel="noreferrer">http://howtocenterincss.com/</a></p>
{ "question_id": 6810031, "question_date": "2011-07-24T21:59:56.950Z", "question_score": 217, "tags": "css", "answer_id": 6810051, "answer_date": "2011-07-24T22:02:28.307Z", "answer_score": 329 }
Please answer the following Stack Overflow question: Title: Vue.js redirection to another page <p>I'd like to make a redirection in <code>Vue.js</code> similar to the vanilla javascript</p> <pre><code>window.location.href = 'some_url' </code></pre> <p>How could I achieve this in Vue.js?</p>
<p>If you are using <code>vue-router</code>, you should use <code>router.go(path)</code> to navigate to any particular route. The router can be accessed from within a component using <code>this.$router</code>.</p> <p>Otherwise, <code>window.location.href = 'some url';</code> works fine for non single-page apps.</p> <p><strong>EDIT</strong>: <code>router.go()</code> changed in VueJS 2.0. You can use <code>$router.push({ name: &quot;yourroutename&quot;})</code> or just <code>router.push(&quot;yourroutename&quot;)</code> now to redirect.</p> <p><a href="https://router.vuejs.org/guide/essentials/named-routes.html" rel="noreferrer">Documentation</a></p> <p>Note: In controllers use: <code>this.$router.push({ name: 'routename' })</code></p>
{ "question_id": 35664550, "question_date": "2016-02-27T01:15:56.420Z", "question_score": 217, "tags": "vue.js|url-routing|vuejs2|vue-router", "answer_id": 35667628, "answer_date": "2016-02-27T08:43:45.653Z", "answer_score": 296 }
Please answer the following Stack Overflow question: Title: Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine <p>I created a windows application developed in .NET 3.5 in a 32 bit Windows 2008 server. When deployed the application in a 64 bit server it shows the error "Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine ".</p> <p>So as a solution to this issue, i have changed the build property of the project to X86, so that it will build in 32 bit mode, and rebuild the project in the 32bit machine. But, the same project uses other DB drivers (DB2, SQL etc.) to connect to other databases. So when i deployed my app again in the 64 bit OS, it throws the exception " Attempted to load a 64-bit assembly on a 32-bit platform. "</p> <p>I am using the Microsoft.Jet.OLEDB.4.0 driver to read and write to the Excel (.xls)</p>
<p>I found a solution for this problem. The issue I described in my question occured basically due to the incompatibility of the <em>Microsoft.Jet.OLEDB.4.0 driver</em> in 64 bit OS. </p> <p>So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode (This is the answer I found when I did an extensive search for this <strong>known issue</strong>) and that causes other part of my code to break.</p> <p>Fortunately, now Microsoft has released a 64 bit compatible <strong><em>2010 Office System Driver</em></strong> which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments. <del>But this driver is in <strong>BETA</strong>.</del></p> <p>You can download this driver from <a href="http://www.microsoft.com/download/en/details.aspx?id=13255" rel="noreferrer">Microsoft Access Database Engine 2010 Redistributable</a></p>
{ "question_id": 1991643, "question_date": "2010-01-02T13:52:50.167Z", "question_score": 217, "tags": "c#|.net|oledb|32bit-64bit|jet", "answer_id": 1992009, "answer_date": "2010-01-02T16:13:10.303Z", "answer_score": 271 }
Please answer the following Stack Overflow question: Title: Python add item to the tuple <p>I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like <code>(u'2',)</code> but when I try to add new one using <code>mytuple = mytuple + new.id</code> got error <code>can only concatenate tuple (not "unicode") to tuple</code>. </p>
<p>You need to make the second element a 1-tuple, eg:</p> <pre><code>a = ('2',) b = 'z' new = a + (b,) </code></pre>
{ "question_id": 16730339, "question_date": "2013-05-24T08:04:32.503Z", "question_score": 217, "tags": "python|tuples", "answer_id": 16730367, "answer_date": "2013-05-24T08:05:52.840Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: Cross-Origin Request Headers(CORS) with PHP headers <p>I have a simple PHP script that I am attempting a cross-domain CORS request:</p> <pre><code>&lt;?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); ... </code></pre> <p>Yet I still get the error:</p> <blockquote> <p>Request header field <code>X-Requested-With</code> is not allowed by <code>Access-Control-Allow-Headers</code></p> </blockquote> <p>Anything I'm missing?</p>
<p><code>Access-Control-Allow-Headers</code> does not allow <code>*</code> as accepted value, see the Mozilla Documentation <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers" rel="noreferrer">here</a>.</p> <p>Instead of the asterisk, you should send the accepted headers (first <code>X-Requested-With</code> as the error says).</p> <h2>Update:</h2> <p><code>*</code> is now accepted is <code>Access-Control-Allow-Headers</code>.</p> <p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers" rel="noreferrer">MDN Web Docs 2021</a>:</p> <blockquote> <p>The value <code>*</code> only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal header name <code>*</code> without special semantics. Note that the Authorization header can't be wildcarded and always needs to be listed explicitly.</p> </blockquote>
{ "question_id": 8719276, "question_date": "2012-01-03T22:03:56.707Z", "question_score": 217, "tags": "php|javascript|xmlhttprequest|cors", "answer_id": 8719346, "answer_date": "2012-01-03T22:10:08.170Z", "answer_score": 73 }
Please answer the following Stack Overflow question: Title: Pass props in Link react-router <p>I am using react with react-router. I am trying to pass property’s in a "Link" of react-router </p> <pre><code>var React = require('react'); var Router = require('react-router'); var CreateIdeaView = require('./components/createIdeaView.jsx'); var Link = Router.Link; var Route = Router.Route; var DefaultRoute = Router.DefaultRoute; var RouteHandler = Router.RouteHandler; var App = React.createClass({ render : function(){ return( &lt;div&gt; &lt;Link to="ideas" params={{ testvalue: "hello" }}&gt;Create Idea&lt;/Link&gt; &lt;RouteHandler/&gt; &lt;/div&gt; ); } }); var routes = ( &lt;Route name="app" path="/" handler={App}&gt; &lt;Route name="ideas" handler={CreateIdeaView} /&gt; &lt;DefaultRoute handler={Home} /&gt; &lt;/Route&gt; ); Router.run(routes, function(Handler) { React.render(&lt;Handler /&gt;, document.getElementById('main')) }); </code></pre> <p>The "Link" renders the page but does not pass the property to the new view. Below is the view code </p> <pre><code>var React = require('react'); var Router = require('react-router'); var CreateIdeaView = React.createClass({ render : function(){ console.log('props form link',this.props,this)//props not recived return( &lt;div&gt; &lt;h1&gt;Create Post: &lt;/h1&gt; &lt;input type='text' ref='newIdeaTitle' placeholder='title'&gt;&lt;/input&gt; &lt;input type='text' ref='newIdeaBody' placeholder='body'&gt;&lt;/input&gt; &lt;/div&gt; ); } }); module.exports = CreateIdeaView; </code></pre> <p>How can I pass data using "Link"?</p>
<p>This line is missing <code>path</code>:</p> <pre><code>&lt;Route name=&quot;ideas&quot; handler={CreateIdeaView} /&gt; </code></pre> <p>Should be:</p> <pre><code>&lt;Route name=&quot;ideas&quot; path=&quot;/:testvalue&quot; handler={CreateIdeaView} /&gt; </code></pre> <p>Given the following <code>Link</code> <strong>(outdated v1)</strong>:</p> <pre><code>&lt;Link to=&quot;ideas&quot; params={{ testvalue: &quot;hello&quot; }}&gt;Create Idea&lt;/Link&gt; </code></pre> <p><strong>Up to date as of v4/v5</strong>:</p> <pre><code>const backUrl = '/some/other/value' // this.props.testvalue === &quot;hello&quot; // Using query &lt;Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} /&gt; // Using search &lt;Link to={{pathname: `/${this.props.testvalue}`, search: `?backUrl=${backUrl}`} /&gt; &lt;Link to={`/${this.props.testvalue}?backUrl=${backUrl}`} /&gt; </code></pre> <p><s>and in the <code>withRouter(CreateIdeaView)</code> components <code>render()</code></s>, out dated usage of <code>withRouter</code> higher order component:</p> <pre><code>console.log(this.props.match.params.testvalue, this.props.location.query.backurl) // output hello /some/other/value </code></pre> <p>And in a functional components using the <code>useParams</code> and <code>useLocation</code> hooks:</p> <pre><code>const CreatedIdeaView = () =&gt; { const { testvalue } = useParams(); const { query, search } = useLocation(); console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl')) return &lt;span&gt;{testvalue} {backurl}&lt;/span&gt; } </code></pre> <p>From the link that you posted on the docs, towards the bottom of the page:</p> <blockquote> <p>Given a route like <code>&lt;Route name=&quot;user&quot; path=&quot;/users/:userId&quot;/&gt;</code></p> </blockquote> <br> <hr /> <p>Updated code example with some stubbed query examples:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// import React, {Component, Props, ReactDOM} from 'react'; // import {Route, Switch} from 'react-router'; etc etc // this snippet has it all attached to window since its in browser const { BrowserRouter, Switch, Route, Link, NavLink } = ReactRouterDOM; class World extends React.Component { constructor(props) { super(props); console.dir(props); this.state = { fromIdeas: props.match.params.WORLD || 'unknown' } } render() { const { match, location} = this.props; return ( &lt;React.Fragment&gt; &lt;h2&gt;{this.state.fromIdeas}&lt;/h2&gt; &lt;span&gt;thing: {location.query &amp;&amp; location.query.thing} &lt;/span&gt;&lt;br/&gt; &lt;span&gt;another1: {location.query &amp;&amp; location.query.another1 || 'none for 2 or 3'} &lt;/span&gt; &lt;/React.Fragment&gt; ); } } class Ideas extends React.Component { constructor(props) { super(props); console.dir(props); this.state = { fromAppItem: props.location.item, fromAppId: props.location.id, nextPage: 'world1', showWorld2: false } } render() { return ( &lt;React.Fragment&gt; &lt;li&gt;item: {this.state.fromAppItem.okay}&lt;/li&gt; &lt;li&gt;id: {this.state.fromAppId}&lt;/li&gt; &lt;li&gt; &lt;Link to={{ pathname: `/hello/${this.state.nextPage}`, query:{thing: 'asdf', another1: 'stuff'} }}&gt; Home 1 &lt;/Link&gt; &lt;/li&gt; &lt;li&gt; &lt;button onClick={() =&gt; this.setState({ nextPage: 'world2', showWorld2: true})}&gt; switch 2 &lt;/button&gt; &lt;/li&gt; {this.state.showWorld2 &amp;&amp; &lt;li&gt; &lt;Link to={{ pathname: `/hello/${this.state.nextPage}`, query:{thing: 'fdsa'}}} &gt; Home 2 &lt;/Link&gt; &lt;/li&gt; } &lt;NavLink to="/hello"&gt;Home 3&lt;/NavLink&gt; &lt;/React.Fragment&gt; ); } } class App extends React.Component { render() { return ( &lt;React.Fragment&gt; &lt;Link to={{ pathname:'/ideas/:id', id: 222, item: { okay: 123 }}}&gt;Ideas&lt;/Link&gt; &lt;Switch&gt; &lt;Route exact path='/ideas/:id/' component={Ideas}/&gt; &lt;Route path='/hello/:WORLD?/:thing?' component={World}/&gt; &lt;/Switch&gt; &lt;/React.Fragment&gt; ); } } ReactDOM.render(( &lt;BrowserRouter&gt; &lt;App /&gt; &lt;/BrowserRouter&gt; ), document.getElementById('ideas'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"&gt;&lt;/script&gt; &lt;div id="ideas"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>#updates:</p> <p>See: <a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors</a></p> <blockquote> <p>From the upgrade guide from 1.x to 2.x:</p> <p><code>&lt;Link to&gt;</code>, onEnter, and isActive use location descriptors</p> <p><code>&lt;Link to&gt;</code> can now take a location descriptor in addition to strings. The query and state props are deprecated.</p> <p>// v1.0.x</p> <pre><code>&lt;Link to=&quot;/foo&quot; query={{ the: 'query' }}/&gt; </code></pre> <p>// v2.0.0</p> <pre><code>&lt;Link to={{ pathname: '/foo', query: { the: 'query' } }}/&gt; </code></pre> <p>// Still valid in 2.x</p> <pre><code>&lt;Link to=&quot;/foo&quot;/&gt; </code></pre> <p>Likewise, redirecting from an onEnter hook now also uses a location descriptor.</p> <p>// v1.0.x</p> <pre><code>(nextState, replaceState) =&gt; replaceState(null, '/foo') (nextState, replaceState) =&gt; replaceState(null, '/foo', { the: 'query' }) </code></pre> <p>// v2.0.0</p> <pre><code>(nextState, replace) =&gt; replace('/foo') (nextState, replace) =&gt; replace({ pathname: '/foo', query: { the: 'query' } }) </code></pre> <p>For custom link-like components, the same applies for router.isActive, previously history.isActive.</p> <p>// v1.0.x</p> <pre><code>history.isActive(pathname, query, indexOnly) </code></pre> <p>// v2.0.0</p> <pre><code>router.isActive({ pathname, query }, indexOnly) </code></pre> </blockquote> <p>#updates for v3 to v4:</p> <ul> <li><p><a href="https://github.com/ReactTraining/react-router/blob/432dc9cf2344c772ab9f6379998aa7d74c1d43de/packages/react-router/docs/guides/migrating.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/432dc9cf2344c772ab9f6379998aa7d74c1d43de/packages/react-router/docs/guides/migrating.md</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3803" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3803</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3669" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3669</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3430" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3430</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3443" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3443</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3803" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3803</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3636" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3636</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3397" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3397</a></p> </li> <li><p><a href="https://github.com/ReactTraining/react-router/pull/3288" rel="noreferrer">https://github.com/ReactTraining/react-router/pull/3288</a></p> </li> </ul> <p>The interface is basically still the same as v2, best to look at the CHANGES.md for react-router, as that is where the updates are.</p> <p><em>&quot;legacy migration documentation&quot; for posterity</em></p> <ul> <li><a href="https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/dc7facf205f9ee43cebea9fab710dce036d04f04/packages/react-router/docs/guides/migrating.md</a></li> <li><a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v1.0.0.md</a></li> <li><a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.0.0.md</a></li> <li><a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.2.0.md</a></li> <li><a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.4.0.md</a></li> <li><a href="https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/0c6d51cd6639aff8a84b11d89e27887b3558ed8a/upgrade-guides/v2.5.0.md</a></li> </ul>
{ "question_id": 30115324, "question_date": "2015-05-08T03:35:14.637Z", "question_score": 217, "tags": "javascript|reactjs|react-router", "answer_id": 30115524, "answer_date": "2015-05-08T04:00:59.547Z", "answer_score": 186 }
Please answer the following Stack Overflow question: Title: How to query between two dates using Laravel and Eloquent? <p>I'm trying to create a report page that shows reports from a specific date to a specific date. Here's my current code:</p> <pre><code>$now = date('Y-m-d'); $reservations = Reservation::where('reservation_from', $now)-&gt;get(); </code></pre> <p>What this does in plain SQL is <code>select * from table where reservation_from = $now</code>. </p> <p>I have this query here but I don't know how to convert it to eloquent query.</p> <pre><code>SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to </code></pre> <p>How can I convert the code above to eloquent query? Thank you in advance.</p>
<p><strong>The <code>whereBetween</code> method verifies that a column's value is between two values.</strong></p> <pre><code>$from = date('2018-01-01'); $to = date('2018-05-02'); Reservation::whereBetween('reservation_from', [$from, $to])-&gt;get(); </code></pre> <hr /> <p>In some cases you need to add date range dynamically. Based on <a href="https://stackoverflow.com/users/673846/anovative">@Anovative</a>'s comment you can do this:</p> <pre><code>Reservation::all()-&gt;filter(function($item) { if (Carbon::now()-&gt;between($item-&gt;from, $item-&gt;to)) { return $item; } }); </code></pre> <hr /> <p>If you would like to add more condition then you can use <code>orWhereBetween</code>. If you would like to exclude a date interval then you can use <code>whereNotBetween </code>.</p> <pre><code>Reservation::whereBetween('reservation_from', [$from1, $to1]) -&gt;orWhereBetween('reservation_to', [$from2, $to2]) -&gt;whereNotBetween('reservation_to', [$from3, $to3]) -&gt;get(); </code></pre> <hr /> <p>Other useful where clauses: <code>whereIn</code>, <code>whereNotIn</code>, <code>whereNull</code>, <code>whereNotNull</code>, <code>whereDate</code>, <code>whereMonth</code>, <code>whereDay</code>, <code>whereYear</code>, <code>whereTime</code>, <code>whereColumn </code>, <code>whereExists</code>, <code>whereRaw</code>.</p> <p><a href="https://laravel.com/docs/5.6/queries#where-clauses" rel="noreferrer">Laravel docs about Where Clauses.</a></p>
{ "question_id": 33361628, "question_date": "2015-10-27T06:56:04.240Z", "question_score": 217, "tags": "php|laravel|laravel-5|orm", "answer_id": 33361741, "answer_date": "2015-10-27T07:04:13.067Z", "answer_score": 413 }
Please answer the following Stack Overflow question: Title: PHP - Move a file into a different folder on the server <p>I need to allow users on my website to delete their images off the server after they have uploaded them if they no longer want them. I was previously using the <code>unlink</code> function in PHP but have since been told that this can be quite risky and a security issue. (Previous code below:)</p> <pre><code>if(unlink($path.'image1.jpg')){ // deleted } </code></pre> <p>Instead i now want to simply move the file into a different folder. This must be able to be done a long time after they have first uploaded the file so any time they log into their account. If i have the main folder which stores the users image(s):</p> <pre><code>user/ </code></pre> <p>and then within that a folder called del which is the destination to put their unwanted images:</p> <pre><code>user/del/ </code></pre> <p>Is there a command to move a file into a different folder? So that say:</p> <pre><code>user/image1.jpg </code></pre> <p>moves to/becomes</p> <pre><code>user/del/image1.jpg </code></pre>
<p>The <code>rename</code> function does this</p> <p><a href="http://php.net/manual/en/function.rename.php" rel="noreferrer">docs rename</a></p> <p><code>rename('image1.jpg', 'del/image1.jpg');</code></p> <p>If you want to keep the existing file on the same place you should use <code>copy</code></p> <p><a href="http://php.net/copy" rel="noreferrer">docs copy</a></p> <p><code>copy('image1.jpg', 'del/image1.jpg');</code></p> <p>If you want to move an uploaded file use the <code>move_uploaded_file</code>, although this is almost the same as <code>rename</code> this function also checks that the given file is a file that was uploaded via the <code>POST</code>, this prevents for example that a local file is moved </p> <p><a href="http://www.php.net/manual/en/function.move-uploaded-file.php" rel="noreferrer">docs move_uploaded_file</a></p> <pre><code>$uploads_dir = '/uploads'; foreach ($_FILES["pictures"]["error"] as $key =&gt; $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = $_FILES["pictures"]["name"][$key]; move_uploaded_file($tmp_name, "$uploads_dir/$name"); } } </code></pre> <p><strong>code snipet from docs</strong></p>
{ "question_id": 19139434, "question_date": "2013-10-02T14:28:53.790Z", "question_score": 217, "tags": "php|directory|move|unlink", "answer_id": 19139524, "answer_date": "2013-10-02T14:33:09.057Z", "answer_score": 496 }
Please answer the following Stack Overflow question: Title: TypeScript sorting an array <p>I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.</p> <p>So if you try something simple like the following:</p> <pre><code>var numericArray:Array&lt;number&gt; = [2,3,4,1,5,8,11]; var sorrtedArray:Array&lt;number&gt; = numericArray.sort((n1,n2)=&gt; n1 &gt; n2); </code></pre> <p><a href="http://www.typescriptlang.org/Playground/#src=var%20numericArray:Array%3Cnumber%3E%20=%20%5B2,3,4,1,5,8,11%5D;%0A%0Avar%20sorrtedArray:Array%3Cnumber%3E%20=%20numericArray.sort%28%28n1,n2%29=%3E%20n1%20%3E%20n2%29;%0A%0A" rel="noreferrer">TryIt</a></p> <p>You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.</p>
<p>The error is completely correct.</p> <p>As it's trying to tell you, <code>.sort()</code> takes a function that returns number, not boolean.</p> <p>You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.</p>
{ "question_id": 21687907, "question_date": "2014-02-10T21:06:28.613Z", "question_score": 217, "tags": "typescript", "answer_id": 21687953, "answer_date": "2014-02-10T21:08:20.573Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: What is best tool to compare two SQL Server databases (schema and data)? <p>I would like to compare two SQL Server databases including schema (table structure) and data in tables too. What is best tool to do this?</p>
<p>I am using Red-Gate's software: <a href="http://www.red-gate.com/" rel="noreferrer">http://www.red-gate.com</a></p>
{ "question_id": 685053, "question_date": "2009-03-26T09:28:11.810Z", "question_score": 217, "tags": "sql|sql-server|database|compare", "answer_id": 685064, "answer_date": "2009-03-26T09:31:23.017Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: Android: how to draw a border to a LinearLayout <p>I have three files. The XML, the draw function and the main Activity. I have some <code>LinearLayout</code> in my XML file.</p> <pre><code>&lt;LinearLayout android:orientation=&quot;horizontal&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot; android:layout_weight=&quot;1&quot;&gt; &lt;LinearLayout android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot; android:layout_weight=&quot;1&quot; android:background=&quot;#ef3&quot; android:id=&quot;@+id/img01&quot;/&gt; &lt;LinearLayout android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot; android:layout_weight=&quot;1&quot; android:background=&quot;#E8A2B4&quot; android:id=&quot;@+id/img02&quot;/&gt; &lt;/LinearLayout&gt; </code></pre> <p>This is the draw function:</p> <pre><code>public class getBorder extends TextView { public getBorder(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(android.graphics.Color.RED); canvas.drawLine(0, 0, this.getWidth() - 1, 0, paint); canvas.drawLine(0, 0, 0, this.getHeight() - 1, paint); canvas.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1, this.getHeight() - 1, paint); canvas.drawLine(0, this.getHeight() - 1, this.getWidth() - 1, this.getHeight() - 1, paint); } } </code></pre> <p>And this is the main Activity:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final getBorder getBorder = new getBorder(this); final LinearLayout img01 = (LinearLayout) findViewById(R.id.img01); img01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub getBorder.setWidth(100); getBorder.setHeight(100); img01.addView(getBorder); } }); } </code></pre> <p>The program could draw border but the size doesn't fit the <code>LinearLayout</code>. And when I click the <code>LinearLayout</code> again, the program crashed.</p> <p>Also, I want to draw two circles in the center of the <code>LinearLayout</code>, but how could I figure out the center coordinates?</p>
<p>Do you really need to do that programmatically?</p> <p>Just considering the title: You could use a ShapeDrawable as android:background…</p> <p>For example, let's define <code>res/drawable/my_custom_background.xml</code> as:</p> <pre><code>&lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"&gt; &lt;corners android:radius="2dp" android:topRightRadius="0dp" android:bottomRightRadius="0dp" android:bottomLeftRadius="0dp" /&gt; &lt;stroke android:width="1dp" android:color="@android:color/white" /&gt; &lt;/shape&gt; </code></pre> <p>and define android:background="@drawable/my_custom_background".</p> <p>I've not tested but it should work.</p> <p><strong>Update:</strong></p> <p>I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/border" android:padding="10dip" &gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World, SOnich" /&gt; [... more TextView ...] &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World, SOnich" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>and a <code>res/drawable/border.xml</code></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"&gt; &lt;stroke android:width="5dip" android:color="@android:color/white" /&gt; &lt;/shape&gt; </code></pre> <p>Reported to work on a gingerbread device. Note that you'll need to relate <code>android:padding</code> of the LinearLayout to the <code>android:width</code> shape/stroke's value. Please, do not use <code>@android:color/white</code> in your final application but rather a project defined color.</p> <p>You could apply <code>android:background="@drawable/border" android:padding="10dip"</code> to each of the LinearLayout from your provided sample.</p> <p>As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (<a href="http://developer.android.com/guide/topics/resources/drawable-resource.html" rel="noreferrer">see Drawable Resources</a> for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…</p> <p>Your problem resides clearly in the use of <code>getBorder.set{Width,Height}(100);</code>. Why do you do that in an onClick method?</p> <p>I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.</p> <p>To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…</p>
{ "question_id": 8203606, "question_date": "2011-11-20T18:17:26.017Z", "question_score": 217, "tags": "android|android-layout|draw", "answer_id": 8203840, "answer_date": "2011-11-20T18:55:35.077Z", "answer_score": 498 }
Please answer the following Stack Overflow question: Title: How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting <p>I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic).</p> <p>I use Python and Numpy and for polynomial fitting there is a function <code>polyfit()</code>. But I found no such functions for exponential and logarithmic fitting. </p> <p>Are there any? Or how to solve it otherwise?</p>
<p>For fitting <em>y</em> = <em>A</em> + <em>B</em> log <em>x</em>, just fit <em>y</em> against (log <em>x</em>).</p> <pre><code>&gt;&gt;&gt; x = numpy.array([1, 7, 20, 50, 79]) &gt;&gt;&gt; y = numpy.array([10, 19, 30, 35, 51]) &gt;&gt;&gt; numpy.polyfit(numpy.log(x), y, 1) array([ 8.46295607, 6.61867463]) # y ≈ 8.46 log(x) + 6.62 </code></pre> <hr> <p>For fitting <em>y</em> = <em>Ae</em><sup><em>Bx</em></sup>, take the logarithm of both side gives log <em>y</em> = log <em>A</em> + <em>Bx</em>. So fit (log <em>y</em>) against <em>x</em>. </p> <p>Note that fitting (log <em>y</em>) as if it is linear will emphasize small values of <em>y</em>, causing large deviation for large <em>y</em>. This is because <code>polyfit</code> (linear regression) works by minimizing ∑<sub><em>i</em></sub> (Δ<em>Y</em>)<sup>2</sup> = ∑<sub><em>i</em></sub> (<em>Y<sub>i</sub></em> &minus; <em>Ŷ</em><sub><em>i</em></sub>)<sup>2</sup>. When <em>Y</em><sub><em>i</em></sub> = log <em>y</em><sub><em>i</em></sub>, the residues Δ<em>Y</em><sub><em>i</em></sub> = Δ(log <em>y</em><sub><em>i</em></sub>) ≈ Δ<em>y</em><sub><em>i</em></sub> / |<em>y</em><sub><em>i</em></sub>|. So even if <code>polyfit</code> makes a very bad decision for large <em>y</em>, the "divide-by-|<em>y</em>|" factor will compensate for it, causing <code>polyfit</code> favors small values.</p> <p>This could be alleviated by giving each entry a "weight" proportional to <em>y</em>. <code>polyfit</code> supports weighted-least-squares via the <code>w</code> keyword argument.</p> <pre><code>&gt;&gt;&gt; x = numpy.array([10, 19, 30, 35, 51]) &gt;&gt;&gt; y = numpy.array([1, 7, 20, 50, 79]) &gt;&gt;&gt; numpy.polyfit(x, numpy.log(y), 1) array([ 0.10502711, -0.40116352]) # y ≈ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x) # (^ biased towards small values) &gt;&gt;&gt; numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y)) array([ 0.06009446, 1.41648096]) # y ≈ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x) # (^ not so biased) </code></pre> <p><strong>Note that Excel, LibreOffice and most scientific calculators typically use the unweighted (biased) formula for the exponential regression / trend lines.</strong> If you want your results to be compatible with these platforms, do not include the weights even if it provides better results.</p> <hr> <p>Now, if you can use scipy, you could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="noreferrer"><code>scipy.optimize.curve_fit</code></a> to fit any model without transformations.</p> <p>For <em>y</em> = <em>A</em> + <em>B</em> log <em>x</em> the result is the same as the transformation method:</p> <pre><code>&gt;&gt;&gt; x = numpy.array([1, 7, 20, 50, 79]) &gt;&gt;&gt; y = numpy.array([10, 19, 30, 35, 51]) &gt;&gt;&gt; scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t), x, y) (array([ 6.61867467, 8.46295606]), array([[ 28.15948002, -7.89609542], [ -7.89609542, 2.9857172 ]])) # y ≈ 6.62 + 8.46 log(x) </code></pre> <p>For <em>y</em> = <em>Ae</em><sup><em>Bx</em></sup>, however, we can get a better fit since it computes Δ(log <em>y</em>) directly. But we need to provide an initialize guess so <code>curve_fit</code> can reach the desired local minimum.</p> <pre><code>&gt;&gt;&gt; x = numpy.array([10, 19, 30, 35, 51]) &gt;&gt;&gt; y = numpy.array([1, 7, 20, 50, 79]) &gt;&gt;&gt; scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y) (array([ 5.60728326e-21, 9.99993501e-01]), array([[ 4.14809412e-27, -1.45078961e-08], [ -1.45078961e-08, 5.07411462e+10]])) # oops, definitely wrong. &gt;&gt;&gt; scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y, p0=(4, 0.1)) (array([ 4.88003249, 0.05531256]), array([[ 1.01261314e+01, -4.31940132e-02], [ -4.31940132e-02, 1.91188656e-04]])) # y ≈ 4.88 exp(0.0553 x). much better. </code></pre> <p><a href="https://i.stack.imgur.com/8JSLa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8JSLa.png" alt="comparison of exponential regression"></a></p>
{ "question_id": 3433486, "question_date": "2010-08-08T07:36:16.263Z", "question_score": 217, "tags": "python|numpy|scipy|curve-fitting|linear-regression", "answer_id": 3433503, "answer_date": "2010-08-08T07:41:32.947Z", "answer_score": 300 }
Please answer the following Stack Overflow question: Title: How to install JDK 11 under Ubuntu? <p>So Java 11 <a href="https://mail.openjdk.java.net/pipermail/announce/2018-September/000257.html" rel="noreferrer">is out</a>. Does anybody know how to install it (OpenJDK from Oracle) from the command line?</p> <p>I would like to see something like it was before for Oracle Java 10:</p> <pre><code>sudo add-apt-repository ppa:linuxuprising/java sudo apt-get update sudo apt-get install oracle-java10-installer </code></pre> <p>P. S. In the <a href="https://stackoverflow.com/questions/49507160/how-to-install-jdk-10-under-ubuntu">similar</a> question proposed instruction:</p> <pre><code>sudo apt-get install openjdk-11-jdk </code></pre> <p>doesn't work.</p>
<p>Now it is possible to install openjdk-11 this way:</p> <pre><code>sudo apt-get install openjdk-11-jdk </code></pre> <p>(Previously it installed openjdk-10, but not anymore)</p>
{ "question_id": 52504825, "question_date": "2018-09-25T18:42:16.510Z", "question_score": 217, "tags": "java|ubuntu|java-11", "answer_id": 52950746, "answer_date": "2018-10-23T13:48:43.640Z", "answer_score": 408 }
Please answer the following Stack Overflow question: Title: Bootstrap Dropdown with Hover <p>OK, so what I need is fairly straightforward.</p> <p>I have set up a navbar with some dropdown menus in it (using <code>class="dropdown-toggle" data-toggle="dropdown"</code>), and it works fine.</p> <p>The thing is it works "<code>onClick</code>", while I would prefer if it worked "<code>onHover</code>".</p> <p>Is there any built-in way to do this?</p>
<p>The easiest solution would be in CSS. Add something like...</p> <pre><code>.dropdown:hover .dropdown-menu { display: block; margin-top: 0; // remove the gap so it doesn't close } </code></pre> <p><a href="http://jsfiddle.net/brbcoding/tah2tur9/" rel="noreferrer">Working Fiddle</a></p>
{ "question_id": 16214326, "question_date": "2013-04-25T12:08:37.470Z", "question_score": 217, "tags": "javascript|jquery|html|css|twitter-bootstrap", "answer_id": 16214473, "answer_date": "2013-04-25T12:14:50.510Z", "answer_score": 420 }
Please answer the following Stack Overflow question: Title: How to copy files across computers using SSH and MAC OS X Terminal <p>I'm trying to copy my .profile, .rvm and .ssh folders/files to a new computer and keep getting a "not a regular file" response. I know how to use the <code>cp</code> and <code>ssh</code> commands but I'm not sure how to use them in order to transfer files from one computer to another.</p> <p>Any help would be great, thanks!</p>
<p>You can do this with the <code>scp</code> command, which uses the ssh protocol to copy files across machines. It extends the syntax of <code>cp</code> to allow references to other systems:</p> <pre><code>scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file </code></pre> <p>Copy something from this machine to some other machine:</p> <pre><code>scp /path/to/local/file username@hostname:/path/to/remote/file </code></pre> <p>Copy something from another machine to this machine:</p> <pre><code>scp username@hostname:/path/to/remote/file /path/to/local/file </code></pre> <p>Copy with a port number specified:</p> <pre><code>scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file </code></pre>
{ "question_id": 3710946, "question_date": "2010-09-14T16:36:37.673Z", "question_score": 217, "tags": "macos|unix|file|terminal|copying", "answer_id": 3710966, "answer_date": "2010-09-14T16:39:40.907Z", "answer_score": 472 }
Please answer the following Stack Overflow question: Title: How to get the request parameters in Symfony 2? <p>I am very new to symfony. In other languages like java and others I can use <code>request.getParameter('parmeter name')</code> to get the value.</p> <p>Is there anything similar that we can do with symfony2.<br> I have seen some examples but none is working for me. Suppose I have a form field with the name <strong>username</strong>. In the form action I tried to use something like this:</p> <pre><code>$request = $this-&gt;getRequest(); $username= $request-&gt;request-&gt;get('username'); </code></pre> <p>I have also tried </p> <p><code>$username = $request-&gt;getParameter('username');</code> </p> <p>and</p> <pre><code>$username=$request-&gt;request-&gt;getParameter('username'); </code></pre> <p>But none of the options is working.However following worked fine:</p> <pre><code>foreach($request-&gt;request-&gt;all() as $req){ print_r($req['username']); } </code></pre> <p>Where am I doing wrong in using <code>getParameter()</code> method. Any help will be appreciated.</p>
<p>The naming is not all that intuitive:</p> <pre><code>use Symfony\Component\HttpFoundation\Request; public function updateAction(Request $request) { // $_GET parameters $request-&gt;query-&gt;get('name'); // $_POST parameters $request-&gt;request-&gt;get('name'); </code></pre> <p>Update Nov 2021: <a href="https://symfony.com/blog/new-in-symfony-5-4-controller-changes" rel="noreferrer">$request-&gt;get('name') has been deprecated in 5.4</a> and will be private as of 6.0. It's usage has been discouraged for quite some time.</p>
{ "question_id": 9784930, "question_date": "2012-03-20T10:23:24.380Z", "question_score": 217, "tags": "php|symfony", "answer_id": 9788435, "answer_date": "2012-03-20T14:08:51.553Z", "answer_score": 446 }
Please answer the following Stack Overflow question: Title: How to remove the first and the last character of a string <p>I'm wondering how to remove the first and last character of a string in Javascript.</p> <p>My url is showing <code>/installers/</code> and I just want <code>installers</code>.</p> <p>Sometimes it will be <code>/installers/services/</code> and I just need <code>installers/services</code>.</p> <p>So I can't just simply strip the slashes <code>/</code>.</p>
<p>Here you go</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var yourString = "/installers/"; var result = yourString.substring(1, yourString.length-1); console.log(result);</code></pre> </div> </div> </p> <p>Or you can use <code>.slice</code> as suggested by <a href="https://stackoverflow.com/a/25567247/3063532">Ankit Gupta</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var yourString = "/installers/services/"; var result = yourString.slice(1,-1); console.log(result);</code></pre> </div> </div> </p> <p>Documentation for the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/slice" rel="noreferrer">slice</a> and <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer">substring</a>.</p>
{ "question_id": 20196088, "question_date": "2013-11-25T14:54:00.097Z", "question_score": 217, "tags": "javascript|string", "answer_id": 20196163, "answer_date": "2013-11-25T14:57:08.923Z", "answer_score": 465 }
Please answer the following Stack Overflow question: Title: Python pip install fails: invalid command egg_info <p>I find that recently often when I try to install a <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a> package using <em><a href="https://en.wikipedia.org/wiki/Pip_%28package_manager%29">pip</a></em>, I get the error(s) below.</p> <p>I found a reference online that one has to use "<em>python2 setup.py install</em>" from the download directory, and indeed find that this will then work if I manually find and download the package (from pypi).</p> <p>But, I don't know where pip is downloading packages to, and/or why it is failing in this manner.</p> <p>I tried to do a pip upgrade, but it also failed in a similar manner, with a bunch of "Unknown distribution option" errors (entry_points, zip_safe, test_suite, tests_require)!</p> <ul> <li>pip 1.0.1</li> <li><a href="https://en.wikipedia.org/wiki/ActivePython">ActivePython</a> 2.7</li> </ul> <p>Trying to use ActiveState's pypm fails, because they have a smaller library base, and it doesn't include these packages.</p> <pre><code>C:\test&gt;pip install requests-oauth Downloading/unpacking requests-oauth Downloading requests-oauth-0.4.1.tar.gz Running setup.py egg_info for package requests-oauth E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe' warnings.warn(msg) E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'egg_info' Complete output from command python setup.py egg_info: E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe' warnings.warn(msg) E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'egg_info' </code></pre>
<p><s>Install <a href="http://pypi.python.org/pypi/distribute/0.6#installation-instructions" rel="noreferrer">distribute</a>, which comes with <code>egg_info</code>.</p> <p>Should be as simple as <code>pip install Distribute</code>.</s></p> <p>Distribute has been merged into Setuptools as of version 0.7. If you are using a version &lt;=0.6, upgrade using <code>pip install --upgrade setuptools</code> or <code>easy_install -U setuptools</code>.</p>
{ "question_id": 11425106, "question_date": "2012-07-11T03:25:46.387Z", "question_score": 217, "tags": "python|pip", "answer_id": 11425830, "answer_date": "2012-07-11T05:01:16.170Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Resizing SVG in html? <p>So, I have an SVG file in HTML, and one of the things I've heard about the format is that it doesn't get all pixelated when you zoom in on it.</p> <p>I know with a jpeg or whatever I could have it stored as a 50 by 50 icon, then actually display it as a (rather pixelated) 100 by 100 thumbnail (or 10 by 10), by manually setting the height and width in the image_src tag.</p> <p>However, SVG files seem to be used with object/embed tags, and changing the height or width of THOSE just results in more space being allocated for the picture.</p> <p>IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system?</p>
<p>Open your <code>.svg</code> file with a text editor (it's just XML), and look for something like this at the top:</p> <pre><code>&lt;svg ... width="50px" height="50px"... </code></pre> <p>Erase width and height attributes; the defaults are 100%, so it should stretch to whatever the container allows it.</p>
{ "question_id": 3120739, "question_date": "2010-06-25T19:05:26.840Z", "question_score": 217, "tags": "html|svg", "answer_id": 3120785, "answer_date": "2010-06-25T19:15:33.480Z", "answer_score": 246 }
Please answer the following Stack Overflow question: Title: Convert a list into a comma-separated string <p>My code is as below:</p> <pre><code>public void ReadListItem() { List&lt;uint&gt; lst = new List&lt;uint&gt;() { 1, 2, 3, 4, 5 }; string str = string.Empty; foreach (var item in lst) str = str + item + ","; str = str.Remove(str.Length - 1); Console.WriteLine(str); } </code></pre> <p>Output: <code>1,2,3,4,5</code></p> <p>What is the most simple way to convert the <code>List&lt;uint&gt;</code> into a comma-separated string?</p>
<p>Enjoy!</p> <pre><code>Console.WriteLine(String.Join(",", new List&lt;uint&gt; { 1, 2, 3, 4, 5 })); </code></pre> <p>First Parameter: <code>","</code><br> Second Parameter: <code>new List&lt;uint&gt; { 1, 2, 3, 4, 5 })</code></p> <p><a href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx" rel="noreferrer">String.Join</a> will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.</p>
{ "question_id": 14959824, "question_date": "2013-02-19T14:25:41.367Z", "question_score": 217, "tags": "c#|.net", "answer_id": 14959865, "answer_date": "2013-02-19T14:27:16.227Z", "answer_score": 407 }
Please answer the following Stack Overflow question: Title: How to use mod operator in bash? <p>I'm trying a line like this:</p> <pre><code>for i in {1..600}; do wget http://example.com/search/link $i % 5; done; </code></pre> <p>What I'm trying to get as output is:</p> <pre><code>wget http://example.com/search/link0 wget http://example.com/search/link1 wget http://example.com/search/link2 wget http://example.com/search/link3 wget http://example.com/search/link4 wget http://example.com/search/link0 </code></pre> <p>But what I'm actually getting is just:</p> <pre><code> wget http://example.com/search/link </code></pre>
<p>Try the following:</p> <pre><code> for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done </code></pre> <p>The <code>$(( ))</code> syntax does an <a href="http://www.gnu.org/software/bash/manual/bashref.html#Arithmetic-Expansion" rel="noreferrer">arithmetic evaluation</a> of the contents.</p>
{ "question_id": 5688576, "question_date": "2011-04-16T18:21:47.413Z", "question_score": 217, "tags": "bash|modulo|arithmetic-expressions", "answer_id": 5688592, "answer_date": "2011-04-16T18:24:38.937Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Keeping it simple and how to do multiple CTE in a query <p>I have this simple T-SQL query, it emits a bunch of columns from a table and also joins information from other <em>related</em> tables.</p> <p>My data model is simple. I have a scheduled event, with participants. I need to know how many participants participate in each event.</p> <p>My solution to this is to add a CTE that groups scheduled events and counts the number of participants.</p> <p>This will allow me to join in that information per scheduled event. Keeping the query simple.</p> <p>I like to keep my queries simple, however, If I ever in the future need to have additonal temporary results accessible during my simple query, what do I do?</p> <p>I would really like it, if I could have multiple CTEs but I can't, right? What are my options here?</p> <p>I've ruled out views and doing things at the application data layer. I prefer to isolated my SQL queries.</p>
<p>You can have multiple <code>CTE</code>s in one query, as well as reuse a <code>CTE</code>:</p> <pre><code>WITH cte1 AS ( SELECT 1 AS id ), cte2 AS ( SELECT 2 AS id ) SELECT * FROM cte1 UNION ALL SELECT * FROM cte2 UNION ALL SELECT * FROM cte1 </code></pre> <p>Note, however, that <code>SQL Server</code> may reevaluate the <code>CTE</code> each time it is accessed, so if you are using values like <code>RAND()</code>, <code>NEWID()</code> etc., they may change between the <code>CTE</code> calls.</p>
{ "question_id": 2140750, "question_date": "2010-01-26T16:22:40.137Z", "question_score": 217, "tags": "sql-server|tsql|common-table-expression", "answer_id": 2140764, "answer_date": "2010-01-26T16:24:33.047Z", "answer_score": 410 }