input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: View markdown files offline <p>Is there a way to display <code>.md</code> files offline so we know what it will look like once it's uploaded in Github? I'm referring to showing the <code>README.md</code> file as it would come out in Github, and not as for editing purposes.</p> <p>Needs to work on Mac and Windows since I use both.</p>
<p>I found a way to view it in PHP. After doing some more snooping I found 2 solutions for offline and online viewing of .md files:</p> <ul> <li><strong>Offline:</strong> <a href="https://github.com/WolfieZero/Markdown-Viewer-PHP" rel="noreferrer">https://github.com/WolfieZero/Markdown-Viewer-PHP</a></li> <li><strong>Online:</strong> <a href="http://daringfireball.net/projects/markdown/dingus" rel="noreferrer">http://daringfireball.net/projects/markdown/dingus</a></li> </ul> <p>I recommend the offline version so you can do your editing even while you're doing your business on the throne. :)</p>
{ "question_id": 9843609, "question_date": "2012-03-23T17:17:29.993Z", "question_score": 669, "tags": "github|markdown|viewer", "answer_id": 9843882, "answer_date": "2012-03-23T17:35:10.930Z", "answer_score": 28 }
Please answer the following Stack Overflow question: Title: What is the difference between UTF-8 and Unicode? <p>I have heard conflicting opinions from people - according to the <a href="http://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">Wikipedia UTF-8</a> page.</p> <p>They are the same thing, aren't they? Can someone clarify?</p>
<p>To expand on the answers others have given:</p> <p>We've got lots of languages with lots of characters that computers should ideally display. Unicode assigns each character a unique number, or code point.</p> <p>Computers deal with such numbers as bytes... skipping a bit of history here and ignoring memory addressing issues, 8-bit computers would treat an 8-bit byte as the largest numerical unit easily represented on the hardware, 16-bit computers would expand that to two bytes, and so forth.</p> <p>Old character encodings such as ASCII are from the (pre-) 8-bit era, and try to cram the dominant language in computing at the time, i.e. English, into numbers ranging from 0 to 127 (7 bits). With 26 letters in the alphabet, both in capital and non-capital form, numbers and punctuation signs, that worked pretty well. ASCII got extended by an 8th bit for other, non-English languages, but the additional 128 numbers/code points made available by this expansion would be mapped to different characters depending on the language being displayed. The ISO-8859 standards are the most common forms of this mapping; ISO-8859-1 and ISO-8859-15 (also known as ISO-Latin-1, latin1, and yes there are two different versions of the 8859 ISO standard as well).</p> <p>But that's not enough when you want to represent characters from more than one language, so cramming all available characters into a single byte just won't work.</p> <p>There are essentially two different types of encodings: one expands the value range by adding more bits. Examples of these encodings would be UCS2 (2 bytes = 16 bits) and UCS4 (4 bytes = 32 bits). They suffer from inherently the same problem as the ASCII and ISO-8859 standards, as their value range is still limited, even if the limit is vastly higher.</p> <p>The other type of encoding uses a variable number of bytes per character, and the most commonly known encodings for this are the UTF encodings. All UTF encodings work in roughly the same manner: you choose a unit size, which for UTF-8 is 8 bits, for UTF-16 is 16 bits, and for UTF-32 is 32 bits. The standard then defines a few of these bits as flags: if they're set, then the next unit in a sequence of units is to be considered part of the same character. If they're not set, this unit represents one character fully. Thus the most common (English) characters only occupy one byte in UTF-8 (two in UTF-16, 4 in UTF-32), but other language characters can occupy six bytes or more.</p> <p>Multi-byte encodings (I should say multi-unit after the above explanation) have the advantage that they are relatively space-efficient, but the downside that operations such as finding substrings, comparisons, etc. all have to decode the characters to unicode code points before such operations can be performed (there are some shortcuts, though).</p> <p>Both the UCS standards and the UTF standards encode the code points as defined in Unicode. In theory, those encodings could be used to encode any number (within the range the encoding supports) - but of course these encodings were made to encode Unicode code points. And that's your relationship between them.</p> <p>Windows handles so-called "Unicode" strings as UTF-16 strings, while most UNIXes default to UTF-8 these days. Communications protocols such as HTTP tend to work best with UTF-8, as the unit size in UTF-8 is the same as in ASCII, and most such protocols were designed in the ASCII era. On the other hand, UTF-16 gives the best <em>average</em> space/processing performance when representing all living languages.</p> <p>The Unicode standard defines fewer code points than can be represented in 32 bits. Thus for all practical purposes, UTF-32 and UCS4 became the same encoding, as you're unlikely to have to deal with multi-unit characters in UTF-32.</p> <p>Hope that fills in some details.</p>
{ "question_id": 643694, "question_date": "2009-03-13T17:06:46.190Z", "question_score": 669, "tags": "unicode|encoding|utf-8|character-encoding|terminology", "answer_id": 643810, "answer_date": "2009-03-13T17:37:20.903Z", "answer_score": 594 }
Please answer the following Stack Overflow question: Title: Adding a directory to the PATH environment variable in Windows <p>I am trying to add <code>C:\xampp\php</code> to my system <code>PATH</code> environment variable in Windows.</p> <p>I have already added it using the <em>Environment Variables</em> dialog box.</p> <p>But when I type into my console:</p> <pre><code>C:\&gt;path </code></pre> <p>it doesn't show the new <code>C:\xampp\php</code> directory:</p> <pre><code>PATH=D:\Program Files\Autodesk\Maya2008\bin;C:\Ruby192\bin;C:\WINDOWS\system32;C:\WINDOWS; C:\WINDOWS\System32\Wbem;C:\PROGRA~1\DISKEE~2\DISKEE~1\;c:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\QuickTime\QTSystem\;D:\Program Files\TortoiseSVN\bin ;D:\Program Files\Bazaar;C:\Program Files\Android\android-sdk\tools;D:\Program Files\ Microsoft Visual Studio\Common\Tools\WinNT;D:\Program Files\Microsoft Visual Studio\Common \MSDev98\Bin;D:\Program Files\Microsoft Visual Studio\Common\Tools;D:\Program Files\ Microsoft Visual Studio\VC98\bin </code></pre> <p>I have two questions:</p> <ol> <li>Why did this happen? Is there something I did wrong?</li> <li>Also, how do I add directories to my <code>PATH</code> variable using the console (and programmatically, with a batch file)?</li> </ol>
<p>This only modifies the registry. An existing process won't use these values. A new process will do so if it is started <em>after</em> this change <em>and</em> doesn't inherit the old environment from its parent.</p> <p>You didn't specify how you started the console session. The best way to ensure this is to exit the command shell and run it again. It should then inherit the updated PATH environment variable.</p>
{ "question_id": 9546324, "question_date": "2012-03-03T12:58:55.103Z", "question_score": 668, "tags": "windows|command-line|path|environment-variables", "answer_id": 9546462, "answer_date": "2012-03-03T13:23:41.153Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: Plot two graphs in same plot in R <p>I would like to plot y1 and y2 in the same plot.</p> <pre><code>x &lt;- seq(-2, 2, 0.05) y1 &lt;- pnorm(x) y2 &lt;- pnorm(x, 1, 1) plot(x, y1, type = "l", col = "red") plot(x, y2, type = "l", col = "green") </code></pre> <p>But when I do it like this, they are not plotted in the same plot together.</p> <p>In Matlab one can do <code>hold on</code>, but does anyone know how to do this in R?</p>
<p><code>lines()</code> or <code>points()</code> will add to the existing graph, but will not create a new window. So you'd need to do</p> <pre><code>plot(x,y1,type="l",col="red") lines(x,y2,col="green") </code></pre>
{ "question_id": 2564258, "question_date": "2010-04-01T23:28:14.070Z", "question_score": 668, "tags": "r|plot|ggplot2|r-faq", "answer_id": 2564276, "answer_date": "2010-04-01T23:33:35.003Z", "answer_score": 709 }
Please answer the following Stack Overflow question: Title: Bash script and /bin/bash^M: bad interpreter: No such file or directory <p>I'm learning through this tutorial to learn <a href="http://linuxcommand.org/wss0010.php" rel="noreferrer">bash scripts</a> to automate a few tasks for me. I'm connecting to a server using putty.</p> <p>The script, located in <code>.../Documents/LOG</code>, is:</p> <pre><code>#!/bin/bash # My first script echo "Hello World!" </code></pre> <p>And I executed the following for <code>read/write/execute permissions</code></p> <pre><code>chmod 755 my_script </code></pre> <p>Then, when I enter <code>./my_script</code>, I'm getting the error given in the title.</p> <p>Some similar questions wanted to see these, so I think they might help:</p> <pre><code>which bash </code></pre> <blockquote> <p><code>/bin/bash</code></p> </blockquote> <p>and</p> <pre><code>echo $PATH </code></pre> <blockquote> <p><code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/bin/mh</code></p> </blockquote> <p>I tried adding current directory to <code>PATH</code>, but that doesn't work..</p>
<p>I have seen this issue when creating scripts in Windows env and then porting over to run on a Unix environment.</p> <p>Try running <code>dos2unix</code> on the script:</p> <p><a href="http://dos2unix.sourceforge.net/" rel="noreferrer">http://dos2unix.sourceforge.net/</a></p> <p>Or just rewrite the script in your Unix env using <code>vi</code> and test.</p> <p>Unix uses different line endings so can't read the file you created on Windows. Hence it is seeing ^M as an illegal character.</p> <p>If you want to write a file on Windows and then port over, make sure your editor is set to create files in UNIX format.</p> <p>In notepad++ in the bottom right of the screen, it tells you the document format. By default, it will say <code>Dos\Windows</code>. To change it go to </p> <ul> <li>settings->preferences </li> <li>new document / default directory tab</li> <li>select the format as unix and close</li> <li>create a new document</li> </ul>
{ "question_id": 14219092, "question_date": "2013-01-08T16:03:35.087Z", "question_score": 668, "tags": "bash", "answer_id": 14219160, "answer_date": "2013-01-08T16:07:24.690Z", "answer_score": 795 }
Please answer the following Stack Overflow question: Title: RecyclerView onClick <p>Has anyone using <code>RecyclerView</code> found a way to set an <code>onClickListener</code> to items in the <code>RecyclerView</code>? I thought of setting a listener to each of the layouts for each item but that seems a little too much hassle I'm sure there is a way for the <code>RecyclerView</code> to listen for the <code>onClick</code> event but I can't quite figure it out.</p>
<p>As the API's have radically changed, It wouldn't surprise me if you were to create an <code>OnClickListener</code> for each item. It isn't that much of a hassle though. In your implementation of <code>RecyclerView.Adapter&lt;MyViewHolder&gt;</code>, you should have: </p> <pre><code>private final OnClickListener mOnClickListener = new MyOnClickListener(); @Override public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false); view.setOnClickListener(mOnClickListener); return new MyViewHolder(view); } </code></pre> <p>The <code>onClick</code> method:</p> <pre><code>@Override public void onClick(final View view) { int itemPosition = mRecyclerView.getChildLayoutPosition(view); String item = mList.get(itemPosition); Toast.makeText(mContext, item, Toast.LENGTH_LONG).show(); } </code></pre>
{ "question_id": 24471109, "question_date": "2014-06-28T21:27:43.160Z", "question_score": 668, "tags": "java|android|android-recyclerview|onclick|onclicklistener", "answer_id": 24471410, "answer_date": "2014-06-28T22:15:19.970Z", "answer_score": 519 }
Please answer the following Stack Overflow question: Title: How do I align views at the bottom of the screen? <p>Here's my layout code;</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="fill_parent" android:layout_height="fill_parent"&gt; &lt;TextView android:text="@string/welcome" android:id="@+id/TextView" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;/TextView&gt; &lt;LinearLayout android:id="@+id/LinearLayout" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="bottom"&gt; &lt;EditText android:id="@+id/EditText" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;/EditText&gt; &lt;Button android:text="@string/label_submit_button" android:id="@+id/Button" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;/Button&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>What this looks like is on the left and what I want it to look like is on the right.</p> <p><img src="https://lh4.ggpht.com/_EW60jqE5_B0/S5D_wMGvK7I/AAAAAAAAALs/p5YdtjqMr-E/s800/Android%20Layout.png" alt="Android Layout - Actual (Left) and Desired (Right)"></p> <p>The obvious answer is to set the TextView to fill_parent on height, but this causes no room to be left for the button or entry field.</p> <p>Essentially the issue is that I want the submit button and the text entry to be a fixed height at the bottom and the text view to fill the rest of the space. Similarly, in the horizontal linear layout I want the submit button to wrap its content and for the text entry to fill the rest of the space.</p> <p>If the first item in a linear layout is told to fill_parent it does exactly that, leaving no room for other items. How do I get an item which is first in a linear layout to fill all space apart from the minimum required by the rest of the items in the layout?</p> <hr/> <p>Relative layouts were indeed the answer:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;TextView android:text="@string/welcome" android:id="@+id/TextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true"&gt; &lt;/TextView&gt; &lt;RelativeLayout android:id="@+id/InnerRelativeLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" &gt; &lt;Button android:text="@string/label_submit_button" android:id="@+id/Button" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;/Button&gt; &lt;EditText android:id="@+id/EditText" android:layout_width="fill_parent" android:layout_toLeftOf="@id/Button" android:layout_height="wrap_content"&gt; &lt;/EditText&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
<p>The modern way to do this is to have a <a href="https://developer.android.com/reference/android/support/constraint/ConstraintLayout" rel="noreferrer">ConstraintLayout</a> and constrain the bottom of the view to the bottom of the ConstraintLayout with <strong><code>app:layout_constraintBottom_toBottomOf="parent"</code></strong></p> <p>The example below creates a FloatingActionButton that will be aligned to the end and the bottom of the screen.</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" xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:layout_width="match_parent"&gt; &lt;android.support.design.widget.FloatingActionButton android:layout_height="wrap_content" android:layout_width="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>For reference, I will keep my old answer.</p> <p>Before the introduction of ConstraintLayout the answer was a <a href="http://developer.android.com/guide/topics/ui/layout/relative.html" rel="noreferrer">relative layout</a>.</p> <hr> <p>If you have a relative layout that fills the whole screen you should be able to use <a href="http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#attr_android:layout_alignParentBottom" rel="noreferrer"><code>android:layout_alignParentBottom</code></a> to move the button to the bottom of the screen.</p> <p>If your views at the bottom are not shown in a relative layout then maybe the layout above it takes all the space. In this case you can put the view, that should be at the bottom, first in your layout file and position the rest of the layout above the views with <code>android:layout_above</code>. This enables the bottom view to take as much space as it needs, and the rest of the layout can fill all the rest of the screen.</p>
{ "question_id": 2386866, "question_date": "2010-03-05T13:04:23.203Z", "question_score": 668, "tags": "android|xml|user-interface|android-layout", "answer_id": 2386929, "answer_date": "2010-03-05T13:14:30.263Z", "answer_score": 549 }
Please answer the following Stack Overflow question: Title: Why are #ifndef and #define used in C++ header files? <p>I have been seeing code like this usually in the start of header files:</p> <pre><code>#ifndef HEADERFILE_H #define HEADERFILE_H </code></pre> <p>And at the end of the file is</p> <pre><code>#endif </code></pre> <p>What is the purpose of this?</p>
<p>Those are called <a href="http://en.wikipedia.org/wiki/Include_guard" rel="noreferrer">#include guards</a>.</p> <p>Once the header is included, it checks if a unique value (in this case <code>HEADERFILE_H</code>) is defined. Then if it's not defined, it defines it and continues to the rest of the page.</p> <p>When the code is included again, the first <code>ifndef</code> fails, resulting in a blank file.</p> <p>That prevents double declaration of any identifiers such as types, enums and static variables.</p>
{ "question_id": 1653958, "question_date": "2009-10-31T10:06:34.503Z", "question_score": 668, "tags": "c++|c|c-preprocessor", "answer_id": 1653965, "answer_date": "2009-10-31T10:09:58.547Z", "answer_score": 679 }
Please answer the following Stack Overflow question: Title: What is the point of "final class" in Java? <p>I am reading a book about Java and it says that you can declare the whole class as <code>final</code>. I cannot think of anything where I'd use this. </p> <p>I am just new to programming and I am wondering <strong>if programmers actually use this on their programs</strong>. If they do, when do they use it so I can understand it better and know when to use it. </p> <p>If Java is object oriented, and you declare a class <code>final</code>, doesn't it stop the idea of class having the characteristics of objects?</p>
<p>First of all, I recommend this article: <a href="http://programming.guide/java/when-to-create-a-final-class.html" rel="noreferrer">Java: When to create a final class</a></p> <hr> <blockquote> <p><strong>If they do, when do they use it so I can understand it better and know when to use it.</strong></p> </blockquote> <p>A <code>final</code> class is simply a class that <strong>can't be extended</strong>.</p> <p>(It does not mean that all references to objects of the class would act as if they were declared as <code>final</code>.) </p> <p>When it's useful to declare a class as final is covered in the answers of this question:</p> <ul> <li><a href="https://stackoverflow.com/questions/218744/good-reasons-to-prohibit-inheritance-in-java">Good reasons to prohibit inheritance in Java?</a></li> </ul> <blockquote> <p><strong>If Java is object oriented, and you declare a class <code>final</code>, doesn't it stop the idea of class having the characteristics of objects?</strong></p> </blockquote> <p>In some sense yes.</p> <p>By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases <em>can</em> not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)</p>
{ "question_id": 5181578, "question_date": "2011-03-03T13:52:23.097Z", "question_score": 668, "tags": "java|final", "answer_id": 5181618, "answer_date": "2011-03-03T13:55:34.600Z", "answer_score": 616 }
Please answer the following Stack Overflow question: Title: Command not found error in Bash variable assignment <p>I have this script called test.sh:</p> <pre><code>#!/bin/bash STR = "Hello World" echo $STR </code></pre> <p>when I run <code>sh test.sh</code> I get this:</p> <pre><code>test.sh: line 2: STR: command not found </code></pre> <p>What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.</p> <p>I'm on Ubuntu Server 9.10. And yes, bash is located at <code>/bin/bash</code>.</p>
<p>You cannot have spaces around the <code>=</code> sign.</p> <p>When you write:</p> <pre><code>STR = &quot;foo&quot; </code></pre> <p>bash tries to run a command named <code>STR</code> with 2 arguments (the strings <code>=</code> and <code>foo</code>)</p> <p>When you write:</p> <pre><code>STR =foo </code></pre> <p>bash tries to run a command named <code>STR</code> with 1 argument (the string <code>=foo</code>)</p> <p>When you write:</p> <pre><code>STR= foo </code></pre> <p>bash tries to run the command <code>foo</code> with STR set to the empty string in its environment.</p> <p>I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:</p> <ol> <li>the first command is exactly equivalent to: <code>STR &quot;=&quot; &quot;foo&quot;</code>,</li> <li>the second is the same as <code>STR &quot;=foo&quot;</code>,</li> <li>and the last is equivalent to <code>STR=&quot;&quot; foo</code>.</li> </ol> <p>The relevant section of the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01" rel="noreferrer">sh language spec, section 2.9.1</a> states:</p> <blockquote> <p>A &quot;simple command&quot; is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.</p> </blockquote> <p>In that context, a <code>word</code> is the command that bash is going to run. Any string containing <code>=</code> (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the <code>=</code> is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In <code>STR = &quot;foo&quot;</code>, <code>STR</code> is not a variable assignment.</p>
{ "question_id": 2268104, "question_date": "2010-02-15T18:32:30.140Z", "question_score": 668, "tags": "bash|shell|syntax|sh|variable-assignment", "answer_id": 2268117, "answer_date": "2010-02-15T18:34:40.900Z", "answer_score": 1167 }
Please answer the following Stack Overflow question: Title: How to reset Postgres' primary key sequence when it falls out of sync? <p>I ran into the problem that my primary key sequence is not in sync with my table rows. </p> <p>That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.</p> <p>It seems to be caused by import/restores not maintaining the sequence properly.</p>
<pre><code>-- Login to psql and run the following -- What is the result? SELECT MAX(id) FROM your_table; -- Then run... -- This should be higher than the last result. SELECT nextval('your_table_id_seq'); -- If it's not higher... run this set the sequence last to your highest id. -- (wise to run a quick pg_dump first...) BEGIN; -- protect against concurrent inserts while you update the counter LOCK TABLE your_table IN EXCLUSIVE MODE; -- Update the sequence SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false); COMMIT; </code></pre> <p><a href="http://www.ruby-forum.com/topic/64428#72333" rel="noreferrer">Source - Ruby Forum</a></p>
{ "question_id": 244243, "question_date": "2008-10-28T18:08:21.453Z", "question_score": 668, "tags": "sql|postgresql|primary-key|ddl|database-sequence", "answer_id": 244265, "answer_date": "2008-10-28T18:14:13.750Z", "answer_score": 890 }
Please answer the following Stack Overflow question: Title: Why does ENOENT mean "No such file or directory"? <p>What does the <code>ENT</code> mean in <code>ENOENT</code>?</p> <p>Shouldn't the error:</p> <blockquote> <p>No such file or directory</p> </blockquote> <p>just be named by <code>ENOFILE</code>?</p> <p>Is there any story or reason?</p>
<p>It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.</p> <p>It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.</p>
{ "question_id": 19902828, "question_date": "2013-11-11T09:25:40.360Z", "question_score": 668, "tags": "c|linux|unix", "answer_id": 19902850, "answer_date": "2013-11-11T09:27:00.767Z", "answer_score": 1045 }
Please answer the following Stack Overflow question: Title: Why catch and rethrow an exception in C#? <p>I'm looking at the article <em><a href="http://www.codeproject.com/KB/cs/datatransferobject.aspx" rel="noreferrer">C# - Data Transfer Object</a></em> on serializable DTOs.</p> <p>The article includes this piece of code:</p> <pre><code>public static string SerializeDTO(DTO dto) { try { XmlSerializer xmlSer = new XmlSerializer(dto.GetType()); StringWriter sWriter = new StringWriter(); xmlSer.Serialize(sWriter, dto); return sWriter.ToString(); } catch(Exception ex) { throw ex; } } </code></pre> <p>The rest of the article looks sane and reasonable (to a noob), but that try-catch-throw throws a WtfException... <strong>Isn't this exactly equivalent to not handling exceptions at all?</strong></p> <p>Ergo:</p> <pre><code>public static string SerializeDTO(DTO dto) { XmlSerializer xmlSer = new XmlSerializer(dto.GetType()); StringWriter sWriter = new StringWriter(); xmlSer.Serialize(sWriter, dto); return sWriter.ToString(); } </code></pre> <p>Or am I missing something fundamental about error handling in C#? It's pretty much the same as Java (minus checked exceptions), isn't it? ... That is, they both refined C++.</p> <p>The Stack Overflow question <em><a href="https://stackoverflow.com/questions/717489">The difference between re-throwing parameter-less catch and not doing anything?</a></em> seems to support my contention that try-catch-throw is-a no-op.</p> <hr> <p><strong>EDIT:</strong></p> <p>Just to summarise for anyone who finds this thread in future...</p> <p><strong>DO NOT</strong></p> <pre><code>try { // Do stuff that might throw an exception } catch (Exception e) { throw e; // This destroys the strack trace information! } </code></pre> <p>The stack trace information can be crucial to identifying the root cause of the problem!</p> <p><strong>DO</strong></p> <pre><code>try { // Do stuff that might throw an exception } catch (SqlException e) { // Log it if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound. // Do special cleanup, like maybe closing the "dirty" database connection. throw; // This preserves the stack trace } } catch (IOException e) { // Log it throw; } catch (Exception e) { // Log it throw new DAOException("Excrement occurred", e); // wrapped &amp; chained exceptions (just like java). } finally { // Normal clean goes here (like closing open files). } </code></pre> <p>Catch the more specific exceptions before the less specific ones (just like Java).</p> <hr> <p><strong>References:</strong></p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms229005.aspx" rel="noreferrer">MSDN - Exception Handling</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/0yd65esw.aspx" rel="noreferrer">MSDN - try-catch (C# Reference)</a></li> </ul>
<p>First; the way that the code in the article does it is evil. <code>throw ex</code> will reset the call stack in the exception to the point where this throw statement is; losing the information about where the exception actually was created.</p> <p>Second, if you just catch and re-throw like that, I see no added value, the code example above would be just as good (or, given the <code>throw ex</code> bit, even better) without the try-catch.</p> <p>However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them:</p> <pre><code>try { // code that may throw exceptions } catch(Exception ex) { // add error logging here throw; } </code></pre>
{ "question_id": 881473, "question_date": "2009-05-19T07:56:55.073Z", "question_score": 668, "tags": "c#|exception-handling|try-catch", "answer_id": 881489, "answer_date": "2009-05-19T08:02:45Z", "answer_score": 501 }
Please answer the following Stack Overflow question: Title: Image inside div has extra space below the image <p>Why in the <a href="http://jsfiddle.net/BZeLR/4/" rel="noreferrer">following code</a> the height of the <code>div</code> is bigger than the height of the <code>img</code> ? There is a gap below the image, but it doesn't seems to be a padding/margin. </p> <p><strong>What is the gap or extra space below image?</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper { border: 1px solid red; width:200px; } img { width:200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt; &lt;img src="http://i.imgur.com/RECDV24.jpg" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><img src="https://i.stack.imgur.com/iR7E8.jpg" alt="Image with a gap or white space under it"></p>
<p>By default, an image is rendered inline, like a letter so it sits on the same line that a, b, c and d sit on.</p> <p>There is space below that line for the <a href="https://en.wikipedia.org/wiki/Descender" rel="noreferrer">descenders</a> you find on letters like g, j, p and q.</p> <p><a href="https://i.stack.imgur.com/ZKEuQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZKEuQ.png" alt="Demonstration of descenders"></a></p> <p>You can:</p> <ul> <li>adjust the <a href="http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align" rel="noreferrer"><code>vertical-align</code></a> of the image to position it elsewhere (e.g. the <code>middle</code>) <em>or</em></li> <li>change the <code>display</code> so it isn't inline.</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { border: solid black 1px; margin-bottom: 10px; } #align-middle img { vertical-align: middle; } #align-base img { vertical-align: bottom; } #display img { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="default"&gt; &lt;h1&gt;Default&lt;/h1&gt; The quick brown fox jumps over the lazy dog &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""&gt; &lt;/div&gt; &lt;div id="align-middle"&gt; &lt;h1&gt;vertical-align: middle&lt;/h1&gt; The quick brown fox jumps over the lazy dog &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""&gt; &lt;/div&gt; &lt;div id="align-base"&gt; &lt;h1&gt;vertical-align: bottom&lt;/h1&gt; The quick brown fox jumps over the lazy dog &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""&gt; &lt;/div&gt; &lt;div id="display"&gt; &lt;h1&gt;display: block&lt;/h1&gt; The quick brown fox jumps over the lazy dog &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>The included image is public domain and <a href="https://commons.wikimedia.org/wiki/File:Descender.png" rel="noreferrer">sourced</a> from Wikimedia Commons</p>
{ "question_id": 5804256, "question_date": "2011-04-27T12:40:35.840Z", "question_score": 668, "tags": "html|css|image", "answer_id": 5804278, "answer_date": "2011-04-27T12:42:32.247Z", "answer_score": 803 }
Please answer the following Stack Overflow question: Title: How to select all records from one table that do not exist in another table? <blockquote> <p>table1 (id, name)<br> table2 (id, name)</p> </blockquote> <p>Query:</p> <pre><code>SELECT name FROM table2 -- that are not in table1 already </code></pre>
<pre><code>SELECT t1.name FROM table1 t1 LEFT JOIN table2 t2 ON t2.name = t1.name WHERE t2.name IS NULL </code></pre> <p><strong>Q</strong>: What is happening here?</p> <p><strong>A</strong>: Conceptually, we select all rows from <code>table1</code> and for each row we attempt to find a row in <code>table2</code> with the same value for the <code>name</code> column. If there is no such row, we just leave the <code>table2</code> portion of our result empty for that row. Then we constrain our selection by picking only those rows in the result where the matching row does not exist. Finally, We ignore all fields from our result except for the <code>name</code> column (the one we are sure that exists, from <code>table1</code>).</p> <p>While it may not be the most performant method possible in all cases, it should work in basically every database engine ever that attempts to implement <a href="https://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">ANSI 92 SQL</a></p>
{ "question_id": 2686254, "question_date": "2010-04-21T20:18:25.207Z", "question_score": 667, "tags": "sql|sql-server|tsql", "answer_id": 2686266, "answer_date": "2010-04-21T20:20:06.673Z", "answer_score": 1152 }
Please answer the following Stack Overflow question: Title: How do I erase an element from std::vector<> by index? <p>I have a std::vector&lt;int>, and I want to delete the n'th element. How do I do that?</p> <pre><code>std::vector&lt;int&gt; vec; vec.push_back(6); vec.push_back(-17); vec.push_back(12); vec.erase(???); </code></pre>
<p>To delete a single element, you could do:</p> <pre><code>std::vector&lt;int&gt; vec; vec.push_back(6); vec.push_back(-17); vec.push_back(12); // Deletes the second element (vec[1]) vec.erase(std::next(vec.begin())); </code></pre> <p>Or, to delete more than one element at once:</p> <pre><code>// Deletes the second through third elements (vec[1], vec[2]) vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3)); </code></pre>
{ "question_id": 875103, "question_date": "2009-05-17T17:59:36.290Z", "question_score": 667, "tags": "c++|stl|vector|erase", "answer_id": 875109, "answer_date": "2009-05-17T18:01:45.087Z", "answer_score": 842 }
Please answer the following Stack Overflow question: Title: Removing duplicate rows in Notepad++ <p>Is it possible to remove duplicated rows in Notepad++, leaving only a single occurrence of a line?</p>
<p><strong>Notepad++ with the TextFX plugin can do this, provided you wanted to sort by line, and remove the duplicate lines at the same time.</strong></p> <p>To install the TextFX in the latest release of Notepad++ you need to download it from here: <a href="https://sourceforge.net/projects/npp-plugins/files/TextFX" rel="noreferrer">https://sourceforge.net/projects/npp-plugins/files/TextFX</a></p> <p>The TextFX plugin used to be included in older versions of Notepad++, or be possible to add from the menu by going to <code>Plugins -&gt; Plugin Manager -&gt; Show Plugin Manager -&gt; Available tab -&gt; TextFX -&gt; Install</code>. In some cases it may also be called <code>TextFX Characters</code>, but this is the same thing.</p> <p>The check boxes and buttons required will now appear in the menu under: <code>TextFX -&gt; TextFX Tools</code>.</p> <p>Make sure &quot;sort outputs only unique...&quot; is checked. Next, select a block of text (<kbd>Ctrl</kbd>+<kbd>A</kbd> to select the entire document). Finally, click &quot;sort lines case sensitive&quot; or &quot;sort lines case insensitive&quot;</p> <p><img src="https://i.stack.imgur.com/1qnvS.png" alt="menu layout in n++" /></p>
{ "question_id": 3958350, "question_date": "2010-10-18T10:42:56.057Z", "question_score": 667, "tags": "duplicates|notepad++", "answer_id": 3958364, "answer_date": "2010-10-18T10:46:42.383Z", "answer_score": 791 }
Please answer the following Stack Overflow question: Title: The useState set method is not reflecting a change immediately <p>I am trying to learn hooks and the <code>useState</code> method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in <code>useState</code> is not working for me, both with and without the spread syntax.</p> <p>I have made an API on another PC that I am calling and fetching the data which I want to set into the state.</p> <p>Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="root"&gt;&lt;/div&gt; &lt;script type="text/babel" defer&gt; // import React, { useState, useEffect } from "react"; // import ReactDOM from "react-dom"; const { useState, useEffect } = React; // web-browser variant const StateSelector = () =&gt; { const initialValue = [ { category: "", photo: "", description: "", id: 0, name: "", rating: 0 } ]; const [movies, setMovies] = useState(initialValue); useEffect(() =&gt; { (async function() { try { // const response = await fetch("http://192.168.1.164:5000/movies/display"); // const json = await response.json(); // const result = json.data.result; const result = [ { category: "cat1", description: "desc1", id: "1546514491119", name: "randomname2", photo: null, rating: "3" }, { category: "cat2", description: "desc1", id: "1546837819818", name: "randomname1", rating: "5" } ]; console.log("result =", result); setMovies(result); console.log("movies =", movies); } catch (e) { console.error(e); } })(); }, []); return &lt;p&gt;hello&lt;/p&gt;; }; const rootElement = document.getElementById("root"); ReactDOM.render(&lt;StateSelector /&gt;, rootElement); &lt;/script&gt; &lt;script src="https://unpkg.com/@babel/standalone@7/babel.min.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/react@17/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Neither <code>setMovies(result)</code> nor <code>setMovies(...result)</code> works.</p> <p>I expect the <code>result</code> variable to be pushed into the <code>movies</code> array.</p>
<p>Much <a href="https://stackoverflow.com/q/30782948/1048572">like <code>.setState()</code> in class components</a> created by extending <code>React.Component</code> or <code>React.PureComponent</code>, the state update using the updater provided by <code>useState</code> hook is also asynchronous, and will not be reflected immediately.</p> <p><strong>Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created</strong>. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.</p> <p>Even if you add a <code>setTimeout</code> the function, though the timeout will run after some time by which the re-render would have happened, the <code>setTimeout</code> will still use the value from its previous closure and not the updated one.</p> <pre><code>setMovies(result); console.log(movies) // movies here will not be updated </code></pre> <p>If you want to perform an action on state update, you need to use the <code>useEffect</code> hook, much like using <code>componentDidUpdate</code> in class components since the setter returned by <code>useState</code> doesn't have a callback pattern</p> <pre><code>useEffect(() =&gt; { // action on update of movies }, [movies]); </code></pre> <p>As far as the syntax to update state is concerned, <code>setMovies(result)</code> will replace the previous <code>movies</code> value in the state with those available from the async request.</p> <p>However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like</p> <pre><code>setMovies(prevMovies =&gt; ([...prevMovies, ...result])); </code></pre>
{ "question_id": 54069253, "question_date": "2019-01-07T06:05:32.903Z", "question_score": 667, "tags": "javascript|reactjs|react-hooks", "answer_id": 54069332, "answer_date": "2019-01-07T06:15:28.110Z", "answer_score": 774 }
Please answer the following Stack Overflow question: Title: Difference between DTO, VO, POJO, JavaBeans? <p>Have seen some similar questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/1394265/what-is-the-difference-between-a-javabean-and-a-pojo">What is the difference between a JavaBean and a POJO?</a></li> <li><a href="https://stackoverflow.com/questions/1425302/what-is-the-difference-between-pojo-and-dto">What is the Difference Between POJO (Plain Old Java Object) and DTO (Data Transfer Object)?</a></li> </ul> <p>Can you also please tell me the contexts in which they are used? Or the purpose of them?</p>
<h2>JavaBeans</h2> <p>A JavaBean is a class that follows <a href="http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html" rel="noreferrer">the JavaBeans conventions</a> as defined by Sun. Wikipedia has a pretty good summary of what <a href="http://en.wikipedia.org/wiki/JavaBean" rel="noreferrer">JavaBeans</a> are:</p> <blockquote> <p>JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.</p> <p>In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.</p> <p>The required conventions are:</p> <ul> <li>The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.</li> <li>The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.</li> <li>The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.</li> </ul> <p>Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.</p> </blockquote> <h2>POJO</h2> <p>A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any <code>javax.ejb</code> interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining <a href="http://en.wikipedia.org/wiki/Plain_Old_Java_Object" rel="noreferrer">POJO</a>:</p> <blockquote> <p>POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:</p> <blockquote> <p><em>"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."</em></p> </blockquote> <p>The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.</p> <p>The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).</p> <p>As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.</p> </blockquote> <h2>Value Object</h2> <p>A Value Object or VO is an object such as <code>java.lang.Integer</code> that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of <a href="http://martinfowler.com/bliki/ValueObject.html" rel="noreferrer">Value Object</a>:</p> <blockquote> <p>In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.</p> <p>You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.</p> <p>A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.</p> <p>Early J2EE literature used the term value object to describe a different notion, what I call a <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" rel="noreferrer">Data Transfer Object</a>. They have since changed their usage and use the term <a href="http://www.oracle.com/technetwork/java/transferobject-139870.html" rel="noreferrer">Transfer Object</a> instead.</p> <p>You can find some more good material on value objects on the <a href="http://c2.com/cgi/wiki?ValueObject" rel="noreferrer">wiki</a> and by <a href="http://www.riehle.org/computer-science/research/1998/ubilab-tr-1998-10-1.html" rel="noreferrer">Dirk Riehle</a>.</p> </blockquote> <h2>Data Transfer Object</h2> <p>Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of <a href="http://en.wikipedia.org/wiki/Data_Transfer_Object" rel="noreferrer">Data Transfer Object</a>:</p> <blockquote> <p>Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.</p> <p>The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).</p> <p>In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.</p> </blockquote> <hr> <p>So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.</p>
{ "question_id": 1612334, "question_date": "2009-10-23T09:30:36.483Z", "question_score": 667, "tags": "java|terminology|javabeans|dto|pojo", "answer_id": 1612671, "answer_date": "2009-10-23T10:51:33.173Z", "answer_score": 938 }
Please answer the following Stack Overflow question: Title: Storing C++ template function definitions in a .CPP file <p>I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:</p> <p><strong>.h file</strong></p> <pre><code>class foo { public: template &lt;typename T&gt; void do(const T&amp; t); }; </code></pre> <p><strong>.cpp file</strong></p> <pre><code>template &lt;typename T&gt; void foo::do(const T&amp; t) { // Do something with t } template void foo::do&lt;int&gt;(const int&amp;); template void foo::do&lt;std::string&gt;(const std::string&amp;); </code></pre> <p>Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.</p> <p>My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.</p>
<p>The problem you describe can be solved by defining the template in the header, or via the approach you describe above.</p> <p>I recommend reading the following points from the <a href="https://isocpp.org/wiki/faq/templates" rel="noreferrer">C++ FAQ Lite</a>: </p> <ul> <li><a href="https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl" rel="noreferrer">Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?</a></li> <li><a href="https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl" rel="noreferrer">How can I avoid linker errors with my template functions?</a></li> <li><a href="https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword" rel="noreferrer">How does the C++ keyword export help with template linker errors?</a></li> </ul> <p>They go into a lot of detail about these (and other) template issues.</p>
{ "question_id": 115703, "question_date": "2008-09-22T15:55:52.830Z", "question_score": 667, "tags": "c++|templates", "answer_id": 115735, "answer_date": "2008-09-22T16:00:44.317Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: C# difference between == and Equals() <p>I have a condition in a silverlight application that compares 2 strings, for some reason when I use <code>==</code> it returns <strong>false</strong> while <code>.Equals()</code> returns <strong>true</strong>.</p> <p>Here is the code:</p> <pre><code>if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack")) { // Execute code } if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack") { // Execute code } </code></pre> <p>Any reason as to why this is happening?</p>
<p>When <code>==</code> is used on an expression of type <code>object</code>, it'll resolve to <a href="https://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx" rel="noreferrer"><code>System.Object.ReferenceEquals</code></a>.</p> <p><a href="https://msdn.microsoft.com/en-us/library/bsc2ak47.aspx" rel="noreferrer"><code>Equals</code></a> is just a <code>virtual</code> method and behaves as such, so the overridden version will be used (which, for <code>string</code> type compares the contents).</p>
{ "question_id": 814878, "question_date": "2009-05-02T13:36:58.237Z", "question_score": 667, "tags": "c#|.net|equals", "answer_id": 814880, "answer_date": "2009-05-02T13:39:29.853Z", "answer_score": 502 }
Please answer the following Stack Overflow question: Title: Official way to ask jQuery wait for all images to load before executing something <p>In jQuery when you do this:</p> <pre><code>$(function() { alert("DOM is loaded, but images not necessarily all loaded"); }); </code></pre> <p>It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code. This is obviously what we want if we're initializing any DOM stuff such as showing or hiding elements or attaching events.</p> <p>Let's say though that I want some animation and I don't want it running until all the images are loaded. Is there an official way in jQuery to do this?</p> <p>The best way I have is to use <code>&lt;body onload="finished()"&gt;</code>, but I don't really want to do that unless I have to.</p> <p>Note: There is a <a href="https://stackoverflow.com/questions/477463/jquery-is-waiting-for-images-to-load-before-executing-document-ready">bug in jQuery 1.3.1</a> in Internet Explorer which actually does wait for all images to load before executing code inside <code>$function() { }</code>. So if you're using that platform you'll get the behavior I'm looking for instead of the correct behavior described above. </p>
<p>With jQuery, you use <code>$(document).ready()</code> to execute something when the <em>DOM</em> is loaded and <code>$(window).on(&quot;load&quot;, handler)</code> to execute something when all other things are loaded as well, such as the images.</p> <p>The difference can be seen in the following complete HTML file, provided you have a lot of <code>jollyrogerNN</code> JPEG files (or other suitable ones):</p> <pre><code>&lt;html&gt;     &lt;head&gt;         &lt;script src=&quot;jquery-1.7.1.js&quot;&gt;&lt;/script&gt;         &lt;script type=&quot;text/javascript&quot;&gt;             $(document).ready(function() {                 alert (&quot;done&quot;);             });         &lt;/script&gt;     &lt;/head&gt;&lt;body&gt;         Hello         &lt;img src=&quot;jollyroger00.jpg&quot;&gt;         &lt;img src=&quot;jollyroger01.jpg&quot;&gt;         // : 100 copies of this in total         &lt;img src=&quot;jollyroger99.jpg&quot;&gt;     &lt;/body&gt; &lt;/html&gt; </code></pre> <p>With that, the alert box appears before the images are loaded, because the DOM is ready at that point. If you then change:</p> <pre><code>$(document).ready(function() { </code></pre> <p>into:</p> <pre><code>$(window).on(&quot;load&quot;, function() { </code></pre> <p>then the alert box doesn't appear until <em>after</em> the images are loaded.</p> <p>Hence, to wait until the entire page is ready, you could use something like:</p> <pre><code>$(window).on(&quot;load&quot;, function() { // weave your magic here. }); </code></pre>
{ "question_id": 544993, "question_date": "2009-02-13T06:56:25.927Z", "question_score": 667, "tags": "jquery", "answer_id": 545005, "answer_date": "2009-02-13T07:03:14.397Z", "answer_score": 1070 }
Please answer the following Stack Overflow question: Title: What's the significance of the "No newline at end of file" log? <p>When doing a <code>git diff</code> it says <em>&quot;No newline at end of file&quot;</em>.</p> <p>What's the significance of the message and what's it trying to tell us?</p>
<p>It indicates that you do not have a newline (usually <code>\n</code>, aka LF or CRLF) at the end of file.</p> <p>That is, simply speaking, the last byte (or bytes if you're on Windows) in the file is not a newline.</p> <p>The message is displayed because otherwise there is no way to tell the difference between a file where there is a newline at the end and one where is not. Diff has to output a newline anyway, or the result would be harder to read or process automatically.</p> <p>Note that it is a good style to always put the newline as a last character if it is allowed by the file format. Furthermore, for example, for C and C++ header files it is required by the language standard.</p>
{ "question_id": 5813311, "question_date": "2011-04-28T03:35:13.687Z", "question_score": 667, "tags": "git|git-svn", "answer_id": 5813359, "answer_date": "2011-04-28T03:42:24.983Z", "answer_score": 612 }
Please answer the following Stack Overflow question: Title: Are the days of passing const std::string & as a parameter over? <p>I heard a recent talk by Herb Sutter who suggested that the reasons to pass <code>std::vector</code> and <code>std::string</code> by <code>const &amp;</code> are largely gone. He suggested that writing a function such as the following is now preferable:</p> <pre><code>std::string do_something ( std::string inval ) { std::string return_val; // ... do stuff ... return return_val; } </code></pre> <p>I understand that the <code>return_val</code> will be an rvalue at the point the function returns and can therefore be returned using move semantics, which are very cheap. However, <code>inval</code> is still much larger than the size of a reference (which is usually implemented as a pointer). This is because a <code>std::string</code> has various components including a pointer into the heap and a member <code>char[]</code> for short string optimization. So it seems to me that passing by reference is still a good idea.</p> <p>Can anyone explain why Herb might have said this?</p>
<p>The reason Herb said what he said is because of cases like this.</p> <p>Let's say I have function <code>A</code> which calls function <code>B</code>, which calls function <code>C</code>. And <code>A</code> passes a string through <code>B</code> and into <code>C</code>. <code>A</code> does not know or care about <code>C</code>; all <code>A</code> knows about is <code>B</code>. That is, <code>C</code> is an implementation detail of <code>B</code>.</p> <p>Let's say that A is defined as follows:</p> <pre><code>void A() { B("value"); } </code></pre> <p>If B and C take the string by <code>const&amp;</code>, then it looks something like this:</p> <pre><code>void B(const std::string &amp;str) { C(str); } void C(const std::string &amp;str) { //Do something with `str`. Does not store it. } </code></pre> <p>All well and good. You're just passing pointers around, no copying, no moving, everyone's happy. <code>C</code> takes a <code>const&amp;</code> because it doesn't store the string. It simply uses it.</p> <p>Now, I want to make one simple change: <code>C</code> needs to store the string somewhere.</p> <pre><code>void C(const std::string &amp;str) { //Do something with `str`. m_str = str; } </code></pre> <p>Hello, copy constructor and potential memory allocation (ignore the <a href="https://stackoverflow.com/questions/10315041/meaning-of-acronym-sso-in-the-context-of-stdstring">Short String Optimization (SSO)</a>). C++11's move semantics are supposed to make it possible to remove needless copy-constructing, right? And <code>A</code> passes a temporary; there's no reason why <code>C</code> should have to <em>copy</em> the data. It should just abscond with what was given to it.</p> <p>Except it can't. Because it takes a <code>const&amp;</code>.</p> <p>If I change <code>C</code> to take its parameter by value, that just causes <code>B</code> to do the copy into that parameter; I gain nothing.</p> <p>So if I had just passed <code>str</code> by value through all of the functions, relying on <code>std::move</code> to shuffle the data around, we wouldn't have this problem. If someone wants to hold on to it, they can. If they don't, oh well.</p> <p>Is it more expensive? Yes; moving into a value is more expensive than using references. Is it less expensive than the copy? Not for small strings with SSO. Is it worth doing?</p> <p>It depends on your use case. How much do you hate memory allocations?</p>
{ "question_id": 10231349, "question_date": "2012-04-19T15:20:57.927Z", "question_score": 667, "tags": "c++|c++11", "answer_id": 10232761, "answer_date": "2012-04-19T16:41:47.903Z", "answer_score": 427 }
Please answer the following Stack Overflow question: Title: What is "with (nolock)" in SQL Server? <p>Can someone explain the implications of using <code>with (nolock)</code> on queries, when you should/shouldn't use it?</p> <p>For example, if you have a banking application with high transaction rates and a lot of data in certain tables, in what types of queries would nolock be okay? Are there cases when you should always use it/never use it?</p>
<p>WITH (NOLOCK) is the equivalent of using READ UNCOMMITED as a transaction isolation level. So, you stand the risk of reading an uncommitted row that is subsequently rolled back, i.e. data that never made it into the database. So, while it can prevent reads being deadlocked by other operations, it comes with a risk. In a banking application with high transaction rates, it's probably not going to be the right solution to whatever problem you're trying to solve with it IMHO.</p>
{ "question_id": 686724, "question_date": "2009-03-26T17:13:35.640Z", "question_score": 666, "tags": "sql-server|nolock", "answer_id": 686733, "answer_date": "2009-03-26T17:16:28.050Z", "answer_score": 514 }
Please answer the following Stack Overflow question: Title: What is the max size of localStorage values? <p>Since <code>localStorage</code> (currently) only supports strings as values, and in order to do that the objects need to be stringified (stored as JSON-string) before they can be stored, is there a defined limitation regarding the length of the values.</p> <p>Does anyone know if there is a definition which applies to all browsers?</p>
<p>Quoting from the <a href="http://en.wikipedia.org/wiki/Web_Storage" rel="noreferrer">Wikipedia article on Web Storage</a>:</p> <blockquote> <p>Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity (<strong>10 MB per origin in Google Chrome(<a href="https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh" rel="noreferrer">https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh</a>), Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer</strong>) and better programmatic interfaces.</p> </blockquote> <p>And also quoting from a <a href="http://ejohn.org/blog/dom-storage/" rel="noreferrer">John Resig article</a> [posted January 2007]:</p> <blockquote> <p><strong>Storage Space</strong></p> <p>It is implied that, with DOM Storage, you have considerably more storage space than the typical user agent limitations imposed upon Cookies. However, the amount that is provided is not defined in the specification, nor is it meaningfully broadcast by the user agent.</p> <p>If you look at the Mozilla source code we can see that 5120KB is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 2KB cookie.</p> <p><strong>However, the size of this storage area can be customized by the user</strong> (so a 5MB storage area is not guaranteed, nor is it implied) and the user agent (Opera, for example, may only provide 3MB - but only time will tell.)</p> </blockquote>
{ "question_id": 2989284, "question_date": "2010-06-07T12:09:15.567Z", "question_score": 666, "tags": "javascript|html|local-storage", "answer_id": 2989317, "answer_date": "2010-06-07T12:12:55.480Z", "answer_score": 486 }
Please answer the following Stack Overflow question: Title: How to see docker image contents <p>I did a docker pull and can list the image that's downloaded. I want to see the contents of this image. Did a search on the net but no straight answer.</p>
<p>You can run an interactive shell container using that image and explore whatever content that image has.</p> <p>For instance:</p> <pre><code>docker run -it image_name sh </code></pre> <p>Or following for images with an <code>entrypoint</code></p> <pre><code>docker run -it --entrypoint sh image_name </code></pre> <p>Or if you want to see how the image was build, meaning the steps in its <code>Dockerfile</code>, you can:</p> <pre><code>docker image history --no-trunc image_name &gt; image_history </code></pre> <p>The steps will be logged into the <code>image_history</code> file.</p>
{ "question_id": 44769315, "question_date": "2017-06-26T22:01:49.633Z", "question_score": 666, "tags": "docker", "answer_id": 44769468, "answer_date": "2017-06-26T22:16:57.013Z", "answer_score": 818 }
Please answer the following Stack Overflow question: Title: Why does AngularJS include an empty option in select? <p>I've been working with AngularJS for the last few weeks, and the one thing which is really bothering me is that even after trying all permutations or the configuration defined in the specification at <a href="http://docs.angularjs.org/api/ng.directive:select">http://docs.angularjs.org/api/ng.directive:select</a>, I still get an empty option as the first child of select element.</p> <p>Here's the Jade:</p> <pre><code>select.span9(ng-model='form.type', required, ng-options='option.value as option.name for option in typeOptions'); </code></pre> <p>Here the controller:</p> <pre><code>$scope.typeOptions = [ { name: 'Feature', value: 'feature' }, { name: 'Bug', value: 'bug' }, { name: 'Enhancement', value: 'enhancement' } ]; </code></pre> <p>Finally, here's the HTML which gets generated:</p> <pre><code>&lt;select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" class="span9 ng-pristine ng-invalid ng-invalid-required"&gt; &lt;option value="?" selected="selected"&gt;&lt;/option&gt; &lt;option value="0"&gt;Feature&lt;/option&gt; &lt;option value="1"&gt;Bug&lt;/option&gt; &lt;option value="2"&gt;Enhancement&lt;/option&gt; &lt;/select&gt; </code></pre> <p>What do I need to do to get rid of it?</p> <p>P.S.: Things work without this as well, but it just looks odd if you use select2 without multiple selection.</p>
<p>The empty <code>option</code> is generated when a value referenced by <code>ng-model</code> doesn't exist in a set of options passed to <code>ng-options</code>. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.</p> <p>If you want to get rid of the empty option just select an initial value in your controller, something like:</p> <pre><code>$scope.form.type = $scope.typeOptions[0].value; </code></pre> <p>Here is the jsFiddle: <a href="http://jsfiddle.net/MTfRD/3/">http://jsfiddle.net/MTfRD/3/</a></p> <p>In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option.</p>
{ "question_id": 12654631, "question_date": "2012-09-29T17:04:45.367Z", "question_score": 666, "tags": "angularjs", "answer_id": 12654812, "answer_date": "2012-09-29T17:26:45.853Z", "answer_score": 656 }
Please answer the following Stack Overflow question: Title: What is Mocking? <p>What is Mocking?                                                                                                    .</p>
<p>Prologue: If you look up the noun <em>mock</em> in the dictionary you will find that one of the definitions of the word is <em>something made as an imitation</em>.</p> <blockquote> <p>Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.</p> <p>In short, mocking is creating objects that simulate the behavior of real objects.</p> </blockquote> <p>At times you may want to distinguish between <em>mocking</em> as opposed to <em>stubbing</em>. There may be some disagreement about this subject but my definition of a stub is a &quot;minimal&quot; simulated object. The stub implements just enough behavior to allow the object under test to execute the test.</p> <p>A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly.</p> <p>To give an example: You can stub a database by implementing a simple in-memory structure for storing records. The object under test can then read and write records to the database stub to allow it to execute the test. This could test some behavior of the object not related to the database and the database stub would be included just to let the test run.</p> <p>If you instead want to verify that the object under test writes some specific data to the database you will have to mock the database. Your test would then incorporate assertions about what was written to the database mock.</p>
{ "question_id": 2665812, "question_date": "2010-04-19T07:33:21.920Z", "question_score": 666, "tags": "unit-testing|mocking", "answer_id": 2666006, "answer_date": "2010-04-19T08:07:31.997Z", "answer_score": 718 }
Please answer the following Stack Overflow question: Title: How to update a pull request from forked repo? <p>So I first forked a repo and then made a commit to that forked repo. I then opened a pull request. The pull request listed all the changes I wanted.</p> <p>After reviewing my pull request, there were a number of changes that the repo owner wanted me to make before he accepted it. I have made those changes in my fork, now how do I update the pull request with those changes (or is this not how I should handle it)?</p>
<p>You have done it correctly. The pull request will automatically update. The process is:</p> <ol> <li>Open pull request</li> <li>Commit changes based on feedback in your local repo</li> <li>Push to the relevant branch of your fork</li> </ol> <p>The pull request will automatically add the new commits to the <code>Commits</code> tab of the PR.</p>
{ "question_id": 9790448, "question_date": "2012-03-20T16:04:58.203Z", "question_score": 666, "tags": "git|version-control|github", "answer_id": 9790530, "answer_date": "2012-03-20T16:09:01.217Z", "answer_score": 649 }
Please answer the following Stack Overflow question: Title: Add a new item to a dictionary in Python <p>How do I add an item to an existing dictionary in Python? For example, given:</p> <pre><code>default_data = { 'item1': 1, 'item2': 2, } </code></pre> <p>I want to add a new item such that:</p> <pre><code>default_data = default_data + {'item3': 3} </code></pre>
<pre><code>default_data['item3'] = 3 </code></pre> <p>Easy as py.</p> <p>Another possible solution:</p> <pre><code>default_data.update({'item3': 3}) </code></pre> <p>which is nice if you want to insert multiple items at once.</p>
{ "question_id": 6416131, "question_date": "2011-06-20T19:07:11.450Z", "question_score": 665, "tags": "python|dictionary|items", "answer_id": 6416142, "answer_date": "2011-06-20T19:08:11.433Z", "answer_score": 1348 }
Please answer the following Stack Overflow question: Title: How do I remove an array item in TypeScript? <p>I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?</p>
<p>Same way as you would in JavaScript. </p> <pre><code>delete myArray[key]; </code></pre> <p>Note that this sets the element to <code>undefined</code>.</p> <p>Better to use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>Array.prototype.splice</code></a> function:</p> <pre><code>const index = myArray.indexOf(key, 0); if (index &gt; -1) { myArray.splice(index, 1); } </code></pre>
{ "question_id": 15292278, "question_date": "2013-03-08T10:52:18.200Z", "question_score": 665, "tags": "arrays|typescript|collections", "answer_id": 15295806, "answer_date": "2013-03-08T14:06:56.030Z", "answer_score": 968 }
Please answer the following Stack Overflow question: Title: Position absolute but relative to parent <p>I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this? </p> <p>Sample html:</p> <pre><code>&lt;div id="father"&gt; &lt;div id="son1"&gt;&lt;/div&gt; &lt;div id="son2"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
<pre><code>#father { position: relative; } #son1 { position: absolute; top: 0; } #son2 { position: absolute; bottom: 0; } </code></pre> <p>This works because <code>position: absolute</code> means something like "use <code>top</code>, <code>right</code>, <code>bottom</code>, <code>left</code> to position yourself in relation to the nearest ancestor who has <code>position: absolute</code> or <code>position: relative</code>."</p> <p>So we make <code>#father</code> have <code>position: relative</code>, and the children have <code>position: absolute</code>, then use <code>top</code> and <code>bottom</code> to position the children.</p>
{ "question_id": 10487292, "question_date": "2012-05-07T18:41:54.500Z", "question_score": 665, "tags": "html|css", "answer_id": 10487329, "answer_date": "2012-05-07T18:44:11.647Z", "answer_score": 1178 }
Please answer the following Stack Overflow question: Title: Why not use tables for layout in HTML? <p>It seems to be the <a href="https://stackoverflow.com/questions/82391/should-tables-be-avoided-in-html-at-any-cost#82402">general opinion</a> that tables should not be used for layout in HTML. </p> <p>Why?</p> <p>I have never (or rarely to be honest) seen good arguments for this. The usual answers are:</p> <ul> <li><p>It's good to <a href="https://stackoverflow.com/questions/82391/should-tables-be-avoided-in-html-at-any-cost#82422">separate content from layout</a><br>But this is a fallacious argument; <a href="http://www.don-lindsay-archive.org/skeptic/arguments.html#cliche" rel="nofollow noreferrer">Cliche Thinking</a>. I guess it's true that using the table element for layout has little to do with tabular data. So what? Does my boss care? Do my users care?<br><br>Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is <a href="https://stackoverflow.com/questions/82391/should-tables-be-avoided-in-html-at-any-cost#82571">easier</a> than using divs and CSS.<br><br>By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs.</p></li> <li><p>Readability of the code<br>I think it's the other way around. Most people understand HTML, few understand CSS.</p></li> <li><p>It's better for SEO not to use tables<br>Why? Can anybody show some evidence that it is? Or a statement from Google that tables are discouraged from an SEO perspective?</p></li> <li><p>Tables are slower.<br>An extra tbody element has to be inserted. This is peanuts for modern web browsers. Show me some benchmarks where the use of a table significantly slows down a page.</p></li> <li><p>A layout overhaul is easier without tables, see <a href="http://csszengarden.com/" rel="nofollow noreferrer">css Zen Garden</a>.<br>Most web sites that need an upgrade need new content (HTML) as well. Scenarios where a new version of a web site only needs a new CSS file are not very likely. Zen Garden is a nice web site, but a bit theoretical. Not to mention its <a href="https://stackoverflow.com/questions/83073/div-vs-table#83639">misuse</a> of CSS.</p></li> </ul> <p>I am really interested in good arguments to use divs + CSS instead of tables.</p>
<p>I'm going to go through your arguments one after another and try to show the errors in them. </p> <blockquote> <p>It's good to separate content from layout But this is a fallacious argument; Cliché Thinking.</p> </blockquote> <p>It's not fallacious at all because HTML was designed intentionally. Misuse of an element might not be completely out of question (after all, new idioms have developed in other languages, as well) but possible negative implications have to be counterbalanced. Additionally, even if there were no arguments against misusing the <code>&lt;table&gt;</code> element today, there might be tomorrow because of the way browser vendors apply special treatment to the element. After all, they know that “<code>&lt;table&gt;</code> elements are for tabular data only” and might use this fact to improve the rendering engine, in the process subtly changing how <code>&lt;table&gt;</code>s behave, and thus breaking cases where it was previously misused.</p> <blockquote> <p>So what? Does my boss care? Do my users care?</p> </blockquote> <p>Depends. Is your boss pointy-haired? Then he might not care. If she's competent, then she will care, because the users <a href="http://www.hotdesign.com/seybold/" rel="nofollow noreferrer">will</a>.</p> <blockquote> <p>Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and css.</p> </blockquote> <p><del>The majority of professional web developers seem to oppose you</del><sup>[<em>citation needed</em>]</sup>. That tables <em>are</em> in fact less maintainable should be obvious. Using tables for layout means that changing the corporate layout will in fact mean changing every single page. This can be <em>very</em> expensive. On the other hand, judicious use of semantically meaningful HTML combined with CSS <em>might</em> confine such changes to the CSS and the pictures used.</p> <blockquote> <p>By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs.</p> </blockquote> <p>Deeply nested <code>&lt;div&gt;</code>s are an anti-pattern just as table layouts. Good web designers don't need many of them. On the other hand, even such deep-nested divs don't have many of the problems of table layouts. In fact, they can even contribute to a semantic structure by logically dividing the content in parts.</p> <blockquote> <p>Readability of the code I think it's the other way around. Most people understand html, little understand css. It's simpler.</p> </blockquote> <p>“Most people” don't matter. Professionals matter. For professionals, table layouts create many more problems than HTML + CSS. This is like saying I shouldn't use GVim or Emacs because Notepad is simpler for most people. Or that I shouldn't use LaTeX because MS Word is simpler for most people.</p> <blockquote> <p>It's better for SEO not to use tables</p> </blockquote> <p>I don't know if this is true and wouldn't use this as an argument but it would be logical. Search engines search for <em>relevant</em> data. While tabular data could of course be relevant, it's rarely what users search for. Users search for terms used in the page title or similarly prominent positions. It would therefore be logical to exclude tabular content from filtering and thus cutting the processing time (and costs!) by a large factor.</p> <blockquote> <p>Tables are slower. An extra tbody element has to be inserted. This is peanuts for modern web browsers.</p> </blockquote> <p>The extra element has got nothing to do with tables being slower. On the other hand, the layout algorithm for tables is much harder, the browser often has to wait for the whole table to load before it can begin to layout the content. Additionally, caching of the layout won't work (CSS can easily be cached). All this has been mentioned before. </p> <blockquote> <p>Show me some benchmarks where the use of a table significantly slows down a page.</p> </blockquote> <p>Unfortunately, I don't have any benchmark data. I would be interested in it myself because it's right that this argument lacks a certain scientific rigour.</p> <blockquote> <p>Most web sites that need an upgrade need new content (html) as well. Scenarios where a new version of a web site only needs a new css file are not very likely.</p> </blockquote> <p>Not at all. I've worked on several cases where changing the design was simplified by a separation of content and design. It's often still necessary to change some HTML code but the changes will always be much more confined. Additionally, design changes must on occasion be made dynamically. Consider template engines such as the one used by the WordPress blogging system. Table layouts would literally kill this system. I've worked on a similar case for a commercial software. Being able to change the design without changing the HTML code was one of the business requirements.</p> <p>Another thing. Table layout makes automated parsing of websites (screen scraping) much harder. This might sound trivial because, after all, who does it? I was surprised myself. Screen scraping can help a lot if the service in question doesn't offer a WebService alternative to access its data. I'm working in bioinformatics where this is a sad reality. Modern web techniques and WebServices have not reached most developers and often, screen scraping is the only way to automate the process of getting data. No wonder that many biologists still perform such tasks manually. For thousands of data sets.</p>
{ "question_id": 83073, "question_date": "2008-09-17T13:19:09.297Z", "question_score": 665, "tags": "html|css", "answer_id": 84986, "answer_date": "2008-09-17T16:23:06.623Z", "answer_score": 495 }
Please answer the following Stack Overflow question: Title: How do I parse command line arguments in Java? <p>What is a good way of parsing command line arguments in Java?</p>
<p>Check these out:</p> <ul> <li><a href="http://commons.apache.org/cli/" rel="noreferrer">http://commons.apache.org/cli/</a></li> <li><a href="http://www.martiansoftware.com/jsap/" rel="noreferrer">http://www.martiansoftware.com/jsap/</a></li> </ul> <p>Or roll your own:</p> <ul> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html</a></li> </ul> <hr /> <p><strong>For instance,</strong> this is how you use <a href="https://mvnrepository.com/artifact/commons-cli/commons-cli/1.3.1" rel="noreferrer"><code>commons-cli</code></a> to parse 2 string arguments:</p> <pre><code>import org.apache.commons.cli.*; public class Main { public static void main(String[] args) throws Exception { Options options = new Options(); Option input = new Option(&quot;i&quot;, &quot;input&quot;, true, &quot;input file path&quot;); input.setRequired(true); options.addOption(input); Option output = new Option(&quot;o&quot;, &quot;output&quot;, true, &quot;output file&quot;); output.setRequired(true); options.addOption(output); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null;//not a good practice, it serves it purpose try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(&quot;utility-name&quot;, options); System.exit(1); } String inputFilePath = cmd.getOptionValue(&quot;input&quot;); String outputFilePath = cmd.getOptionValue(&quot;output&quot;); System.out.println(inputFilePath); System.out.println(outputFilePath); } } </code></pre> <p>usage from command line:</p> <pre><code>$&gt; java -jar target/my-utility.jar -i asd Missing required option: o usage: utility-name -i,--input &lt;arg&gt; input file path -o,--output &lt;arg&gt; output file </code></pre>
{ "question_id": 367706, "question_date": "2008-12-15T07:46:10.870Z", "question_score": 665, "tags": "java|command-line|command-line-arguments", "answer_id": 367714, "answer_date": "2008-12-15T07:49:15.980Z", "answer_score": 497 }
Please answer the following Stack Overflow question: Title: How to squash all git commits into one? <p>How do you squash your entire repository down to the first commit?</p> <p>I can rebase to the first commit, but that would leave me with 2 commits. Is there a way to reference the commit before the first one?</p>
<p>Perhaps the easiest way is to just create a new repository with current state of the working copy. If you want to keep all the commit messages you could first do <code>git log &gt; original.log</code> and then edit that for your initial commit message in the new repository:</p> <pre><code>rm -rf .git git init git add . git commit </code></pre> <p>or</p> <pre><code>git log &gt; original.log # edit original.log as desired rm -rf .git git init git add . git commit -F original.log </code></pre>
{ "question_id": 1657017, "question_date": "2009-11-01T08:38:06.927Z", "question_score": 665, "tags": "git|rebase|git-rebase|squash|git-rewrite-history", "answer_id": 1657287, "answer_date": "2009-11-01T14:23:33.680Z", "answer_score": 165 }
Please answer the following Stack Overflow question: Title: Hyphen, underscore, or camelCase as word delimiter in URIs? <p>I'm designing an HTTP-based API for an intranet app. I realize it's a pretty small concern in the grand scheme of things, but: <strong>should I use hyphens, underscores, or camelCase to delimit words in the URIs?</strong></p> <hr /> <p>Here are my initial thoughts:</p> <p><strong>camelCase</strong></p> <ul> <li>possible issues if server is case-insensitive</li> <li>seems to have fairly widespread use in query string keys (<a href="http://api.example.com?**searchQuery**=..." rel="noreferrer">http://api.example.com?**searchQuery**=...</a>), but not in other URI parts</li> </ul> <p><strong>Hyphen</strong></p> <ul> <li>more aesthetically pleasing than the other alternatives</li> <li>seems to be widely used in the path portion of the URI</li> <li>never seen hyphenated query string key in the wild</li> <li><em>possibly</em> better for SEO (this may be a myth)</li> </ul> <p><strong>Underscore</strong></p> <ul> <li>potentially easier for programming languages to handle</li> <li>several popular APIs (Facebook, Netflix, <strike>StackExchange</strike>, etc.) are using underscores in all parts of the URI.</li> </ul> <p>I'm leaning towards underscores for everything. The fact that most of the big players are using them is compelling (see <a href="https://stackoverflow.com/a/608458/360570">https://stackoverflow.com/a/608458/360570</a>).</p>
<p>You should use hyphens in a crawlable web application URL. Why? Because the hyphen separates words (so that a search engine can index the individual words), and a hyphen is not a <a href="http://msdn.microsoft.com/en-us/library/20bw873z.aspx#WordCharacter" rel="noreferrer">word character</a>. Underscore is a word character, meaning it should be considered part of a word.</p> <p>Double-click this in Chrome: camelCase<br /> Double-click this in Chrome: under_score<br /> Double-click this in Chrome: hyphen-ated</p> <p>See how Chrome (I hear Google makes a search engine too) only thinks one of those is two words?</p> <p><code>camelCase</code> and <code>underscore</code> also require the user to use the <kbd>shift</kbd> key, whereas <code>hyphenated</code> does not.</p> <p>So if you should use hyphens in a crawlable web application, why would you bother doing something different in an intranet application? One less thing to remember.</p>
{ "question_id": 10302179, "question_date": "2012-04-24T16:37:34.527Z", "question_score": 665, "tags": "rest|url|uri|restful-url", "answer_id": 18450653, "answer_date": "2013-08-26T18:32:22.967Z", "answer_score": 667 }
Please answer the following Stack Overflow question: Title: How to convert a normal Git repository to a bare one? <p>How can I convert a 'normal' Git repository to a bare one?</p> <p>The main difference seems to be:</p> <ul> <li><p>in the normal Git repository, you have a <code>.git</code> folder inside the repository containing all relevant data and all other files making up your working copy</p></li> <li><p>in a bare Git repository, there is no working copy and the folder (let's call it <code>repo.git</code>) contains the actual repository data</p></li> </ul>
<p>In short: replace the contents of <code>repo</code> with the contents of <code>repo/.git</code>, then tell the repository that it is now a bare repository.</p> <p>To do this, execute the following commands:</p> <pre><code>cd repo mv .git ../repo.git # renaming just for clarity cd .. rm -fr repo cd repo.git git config --bool core.bare true </code></pre> <p>Note that this is different from doing a <code>git clone --bare</code> to a new location (see below).</p>
{ "question_id": 2199897, "question_date": "2010-02-04T13:18:17.683Z", "question_score": 665, "tags": "git|version-control|git-clone|git-bare|git-non-bare-repository", "answer_id": 2200662, "answer_date": "2010-02-04T15:06:17.983Z", "answer_score": 692 }
Please answer the following Stack Overflow question: Title: "std::endl" vs "\n" <p>Many C++ books contain example code like this...</p> <pre><code>std::cout &lt;&lt; "Test line" &lt;&lt; std::endl; </code></pre> <p>...so I've always done that too. But I've seen a lot of code from working developers like this instead:</p> <pre><code>std::cout &lt;&lt; "Test line\n"; </code></pre> <p>Is there a technical reason to prefer one over the other, or is it just a matter of coding style?</p>
<p>The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.</p> <p>The only difference is that <a href="http://en.cppreference.com/w/cpp/io/manip/endl" rel="noreferrer"><code>std::endl</code></a> flushes the output buffer, and <code>'\n'</code> doesn't. If you don't want the buffer flushed frequently, use <code>'\n'</code>. If you do (for example, if you want to get all the output, and the program is unstable), use <code>std::endl</code>.</p>
{ "question_id": 213907, "question_date": "2008-10-17T21:25:17.107Z", "question_score": 665, "tags": "c++|coding-style|iostream|c++-faq", "answer_id": 213977, "answer_date": "2008-10-17T21:56:50.490Z", "answer_score": 543 }
Please answer the following Stack Overflow question: Title: How to add a changed file to an older (not last) commit in Git <p>I have changed several things over the last hour and committed them step by step, but I just realized I've forgot to add a changed file some commits ago.</p> <p>The Log looks like this:</p> <pre><code>GIT TidyUpRequests u:1 d:0&gt; git log commit fc6734b6351f6c36a587dba6dbd9d5efa30c09ce Author: David Klein &lt;&gt; Date: Tue Apr 27 09:43:55 2010 +0200 The Main program now tests both Webservices at once commit 8a2c6014c2b035e37aebd310a6393a1ecb39f463 Author: David Klein &lt;&gt; Date: Tue Apr 27 09:43:27 2010 +0200 ISBNDBQueryHandler now uses the XPath functions from XPath.fs too commit 06a504e277fd98d97eed4dad22dfa5933d81451f Author: David Klein &lt;&gt; Date: Tue Apr 27 09:30:34 2010 +0200 AmazonQueryHandler now uses the XPath Helper functions defined in XPath.fs commit a0865e28be35a3011d0b6091819ec32922dd2dd8 &lt;--- changed file should go here Author: David Klein &lt;&gt; Date: Tue Apr 27 09:29:53 2010 +0200 Factored out some common XPath Operations </code></pre> <p>Any ideas?</p>
<p>Use <a href="http://git-scm.com/docs/git-rebase" rel="noreferrer"><code>git rebase</code></a>. Specifically:</p> <ol> <li>Use <code>git stash</code> to store the changes you want to add.</li> <li>Use <code>git rebase -i HEAD~10</code> (or however many commits back you want to see).</li> <li>Mark the commit in question (<code>a0865...</code>) for edit by changing the word <code>pick</code> at the start of the line into <code>edit</code>. Don't delete the other lines as that would delete the commits.[^vimnote]</li> <li>Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.</li> <li>Pop the stash by using <code>git stash pop</code></li> <li>Add your file with <code>git add &lt;file&gt;</code>.</li> <li>Amend the commit with <code>git commit --amend --no-edit</code>.</li> <li>Do a <code>git rebase --continue</code> which will rewrite the rest of your commits against the new one.</li> <li>Repeat from step 2 onwards if you have marked more than one commit for edit.</li> </ol> <p>[^vimnote]: If you are using <code>vim</code> then you will have to hit the <kbd>Insert</kbd> key to edit, then <kbd>Esc</kbd> and type in <code>:wq</code> to save the file, quit the editor, and apply the changes. Alternatively, you can <a href="https://stackoverflow.com/questions/2596805/how-do-i-make-git-use-the-editor-of-my-choice-for-commits">configure a user-friendly git commit editor</a> with <code>git config --global core.editor "nano"</code>.</p>
{ "question_id": 2719579, "question_date": "2010-04-27T07:59:42.773Z", "question_score": 665, "tags": "git", "answer_id": 2719636, "answer_date": "2010-04-27T08:10:25.660Z", "answer_score": 1003 }
Please answer the following Stack Overflow question: Title: How to get the SHA-1 fingerprint certificate in Android Studio for debug mode? <p>I have shifted myself from <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29">Eclipse</a> to <a href="https://en.wikipedia.org/wiki/Android_Studio">Android Studio</a>. Now I am trying to work on my Map app. So I need my SHA-1 fingerprint certificate number.</p> <p>When I was using Eclipse it was right under <strong>Windows -> Preferences -> Android -> Build</strong>. But in Android Studio I couldn't find out any option like this so that I could find easily the fingerprint. I am using Windows. I have read from this <a href="http://developer.android.com/tools/publishing/app-signing.html">link</a> that:</p> <blockquote> <p>Android Studio signs your app in debug mode automatically when you run or debug your project from the IDE.</p> </blockquote> <p>So I tried to run this in command line after setting my Java bin path from <a href="http://pongodev.com/get-sha1-for-debug/">this link</a> and unfortunately couldn't find my fingerprint. <strong>It is saying that it is an illegal option</strong>.</p> <pre><code>keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android </code></pre> <p>Is there a way to find the SHA-1 fingerprint from Android Studio like it was very easy in Eclipse? As I am newbie in Android Studio, what is the full process to find it?</p> <p>Another thing I want to add is that I have my Eclipse generates the SHA-1 fingerprint and previously I have my app registered on that fingerprint in Google developer console, and I worked on that app in Eclipse by that API key. Is the same API key can be worked on this my project in Android Studio?</p>
<p><strong>Easiest ways ever:</strong></p> <h2>Update added for Android Studio V 2.2 in last step</h2> <p>There are two ways to do this.</p> <p><strong>1. Faster way</strong>:</p> <ol> <li>Open Android Studio</li> <li>Open your Project</li> <li>Click on Gradle (From Right Side Panel, you will see <strong>Gradle Bar</strong>)</li> <li>Click on Refresh (Click on Refresh from <strong>Gradle Bar</strong>, you will see <strong>List</strong> Gradle scripts of your Project)</li> <li>Click on Your Project (Your Project Name form <strong>List</strong> (root))</li> <li>Click on Tasks</li> <li>Click on Android</li> <li>Double Click on signingReport (You will get <strong>SHA1</strong> and <strong>MD5</strong> in <strong>Run Bar</strong>(Sometimes it will be in Gradle Console))</li> <li>Select <strong>app</strong> module from <strong>module selection dropdown</strong> to run or debug your application</li> </ol> <p><strong>Check the screenshot below:</strong></p> <p><a href="https://i.stack.imgur.com/ZG7rI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZG7rI.png" alt="enter image description here"></a></p> <p><strong>2. Work with Google Maps Activity</strong>:</p> <ol> <li>Open Android Studio</li> <li>Open Your Project</li> <li>Click on <strong>File</strong> menu -> Select <strong>New</strong> -> Click on <strong>Google</strong> -> Select <strong>Google Maps Activity</strong></li> <li>A dialog would appear -> Click on <strong>Finish</strong></li> <li>Android Studio would automatically generate an <strong>XML</strong> file <strong>named</strong> with <code>google_maps_api.xml</code></li> <li>You would get <strong>debug SHA1</strong> key here (at <strong>line number 10</strong> of the XML file)</li> </ol> <p><strong>Check Screenshot below:</strong></p> <p><a href="https://i.stack.imgur.com/u4Ppn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u4Ppn.png" alt="Enter image description here"></a></p> <h2>Android Studio V 2.2 Update</h2> <p>There is an issue with <strong>Execution</strong>.</p> <p><strong>Solution:</strong> </p> <ul> <li>Click on <strong>Toggle tasks execution/text mode</strong> from <strong>Run bar</strong></li> </ul> <p><strong>Check Screenshot below:</strong></p> <p><a href="https://i.stack.imgur.com/UG1vW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UG1vW.png" alt="enter image description here"></a></p> <p><strong>Done.</strong></p>
{ "question_id": 27609442, "question_date": "2014-12-22T19:47:15.460Z", "question_score": 664, "tags": "google-maps|android-studio", "answer_id": 34223470, "answer_date": "2015-12-11T12:22:19.163Z", "answer_score": 1475 }
Please answer the following Stack Overflow question: Title: Finding local IP addresses using Python's stdlib <p>How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?</p>
<pre><code>import socket socket.gethostbyname(socket.gethostname()) </code></pre> <p>This won't work always (returns <code>127.0.0.1</code> on machines having the hostname in <code>/etc/hosts</code> as <code>127.0.0.1</code>), a paliative would be what gimel shows, use <code>socket.getfqdn()</code> instead. Of course your machine needs a resolvable hostname.</p>
{ "question_id": 166506, "question_date": "2008-10-03T12:03:36.963Z", "question_score": 664, "tags": "python|networking|ip-address", "answer_id": 166520, "answer_date": "2008-10-03T12:06:50.653Z", "answer_score": 538 }
Please answer the following Stack Overflow question: Title: Does Python's time.time() return the local or UTC timestamp? <p>Does <code>time.time()</code> in the Python time module return the system's time or the time in UTC?</p>
<p>The <a href="https://docs.python.org/library/time.html#time.time" rel="noreferrer"><code>time.time()</code></a> function returns the number of seconds since the epoch, as a float. Note that &quot;<a href="https://en.wikipedia.org/wiki/Unix_epoch" rel="noreferrer">the epoch</a>&quot; is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where on Earth you are, &quot;seconds past epoch&quot; (<code>time.time()</code>) returns the same value at the same moment.</p> <p>Here is some sample output I ran on my computer, converting it to a string as well.</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; ts = time.time() &gt;&gt;&gt; ts 1355563265.81 &gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') '2012-12-15 01:21:05' &gt;&gt;&gt; </code></pre> <p>The <code>ts</code> variable is the time returned in seconds. I then converted it to a human-readable string using the <code>datetime</code> library.</p>
{ "question_id": 13890935, "question_date": "2012-12-15T09:14:57.827Z", "question_score": 663, "tags": "python|time|timezone", "answer_id": 13891070, "answer_date": "2012-12-15T09:33:42.543Z", "answer_score": 886 }
Please answer the following Stack Overflow question: Title: How can I use grep to find a word inside a folder? <p>In Windows, I would have done a search for finding a word inside a folder. Similarly, I want to know if a specific word occurs inside a directory containing many sub-directories and files. My searches for grep syntax shows I must specify the filename, i.e. <code>grep string filename</code>.</p> <p>Now, I do not know the filename, so what do I do? A friend suggested to do <code>grep -nr string</code>, but I don't know what this means and I got no results with it (there is no response until I issue a <kbd>Ctrl</kbd> + <kbd>C</kbd>).</p>
<pre><code>grep -nr 'yourString*' . </code></pre> <p>The dot at the end searches the current directory. Meaning for each parameter:</p> <pre><code>-n Show relative line number in the file 'yourString*' String for search, followed by a wildcard character -r Recursively search subdirectories listed . Directory for search (current directory) </code></pre> <p><code>grep -nr 'MobileAppSer*' .</code> (Would find <code>MobileAppServlet.java</code> or <code>MobileAppServlet.class</code> or <code>MobileAppServlet.txt</code>; <code>'MobileAppASer*.*'</code> is another way to do the same thing.)</p> <p>To check more parameters use <strong>man grep</strong> command.</p>
{ "question_id": 4121803, "question_date": "2010-11-08T06:50:03.597Z", "question_score": 663, "tags": "string|command-line|grep|keyword-search|file-search", "answer_id": 13908492, "answer_date": "2012-12-17T04:58:37.840Z", "answer_score": 1043 }
Please answer the following Stack Overflow question: Title: Find and replace with a newline in Visual Studio Code <p>I am trying out the new Microsoft Visual Studio Code editor in Linux Fedora environment. I would like to know how to replace new line (\n) in place of some other text. </p> <p>For example, I have html text like this</p> <pre><code>&lt;tag&gt;&lt;tag&gt; </code></pre> <p>which I would like to replace as </p> <pre><code>&lt;tag&gt; &lt;tag&gt; </code></pre> <p>In sublime I would use regex pattern and find <em>">&lt;"</em> and replace with <em>">\n&lt;"</em> How do I accomplish this in Visual Studio Code?</p>
<p>In the local searchbox (<kbd>ctrl</kbd> + <kbd>f</kbd>) you can insert newlines by pressing <kbd>ctrl</kbd> + <kbd>enter</kbd>.</p> <p><a href="https://code.visualstudio.com/assets/updates/1_38/multiple-line-support.gif" rel="noreferrer"><img src="https://code.visualstudio.com/assets/updates/1_38/multiple-line-support.gif" alt="Image of multiline search in local search"></a></p> <p>If you use the global search (<kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>f</kbd>) you can insert newlines by pressing <kbd>shift</kbd> + <kbd>enter</kbd>.</p> <p><a href="https://i.stack.imgur.com/aEmuy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aEmuy.png" alt="Image of multiline search in global search"></a></p> <p>If you want to search for multilines by the character literal, remember to check the <strong>rightmost regex icon</strong>.</p> <p><a href="https://i.stack.imgur.com/uR2Zc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uR2Zc.png" alt="Image of regex mode in search replace"></a></p> <hr> <p>In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.</p>
{ "question_id": 30351529, "question_date": "2015-05-20T13:43:37.393Z", "question_score": 663, "tags": "visual-studio-code", "answer_id": 30775857, "answer_date": "2015-06-11T08:46:04.687Z", "answer_score": 1110 }
Please answer the following Stack Overflow question: Title: Send Email Intent <pre><code>Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(&quot;text/html&quot;); intent.putExtra(Intent.EXTRA_EMAIL, &quot;[email protected]&quot;); intent.putExtra(Intent.EXTRA_SUBJECT, &quot;Subject&quot;); intent.putExtra(Intent.EXTRA_TEXT, &quot;I'm email body.&quot;); startActivity(Intent.createChooser(intent, &quot;Send Email&quot;)); </code></pre> <p>The above code opens a dialog showing the following apps:- Bluetooth, Google Docs, Yahoo Mail, Gmail, Orkut, Skype, etc.</p> <p>Actually, I want to filter these list options. I want to show only email-related apps e.g. Gmail, and Yahoo Mail. How to do it?</p> <p>I've seen such an example on the 'Android Market application.</p> <ol> <li>Open the Android Market app</li> <li>Open any application where the developer has specified his/her email address. (If you can't find such an app just open my app:- market://details?id=com.becomputer06.vehicle.diary.free, OR search by 'Vehicle Diary')</li> <li>Scroll down to 'DEVELOPER'</li> <li>Click on 'Send Email'</li> </ol> <p>The dialog shows only email Apps e.g. Gmail, Yahoo Mail, etc. It does not show Bluetooth, Orkut, etc. What code produces such dialog?</p>
<p>when you will change your intent.setType like below you will get</p> <pre><code>intent.setType("text/plain"); </code></pre> <p>Use <code>android.content.Intent.ACTION_SENDTO</code> to get only the list of e-mail clients, with no facebook or other apps. Just the email clients. Ex:</p> <pre><code>new Intent(Intent.ACTION_SENDTO); </code></pre> <p>I wouldn't suggest you get directly to the email app. Let the user choose his favorite email app. Don't constrain him.</p> <p>If you use ACTION_SENDTO, putExtra does not work to add subject and text to the intent. Use Uri to add the subject and body text.</p> <p><strong>EDIT:</strong> We can use <code>message/rfc822</code> instead of <code>"text/plain"</code> as the MIME type. However, that is not indicating "only offer email clients" -- it indicates "offer anything that supports message/rfc822 data". That could readily include some application that are not email clients. </p> <p><code>message/rfc822</code> supports MIME Types of <code>.mhtml, .mht, .mime</code></p>
{ "question_id": 8701634, "question_date": "2012-01-02T13:50:09.900Z", "question_score": 663, "tags": "android|email|android-intent", "answer_id": 8701718, "answer_date": "2012-01-02T13:58:25.373Z", "answer_score": 236 }
Please answer the following Stack Overflow question: Title: Where can I find Android source code online? <p>Where can I browse the source code for any Android Open Source Project (AOSP) application (for example the Contacts application)? Is the only way to clone the entire source repository for all of AOSP?</p>
<p>Everything is mirrored on <a href="http://omapzoom.org/" rel="noreferrer">omapzoom.org</a>. Some of the code is also <a href="https://github.com/android" rel="noreferrer">mirrored on github</a>.</p> <p><a href="https://github.com/android/platform_packages_apps_contacts" rel="noreferrer">Contacts is here</a> for example.</p> <p><strong>Since December 2019</strong>, you can use the new official public code search tool for AOSP: <a href="https://cs.android.com/" rel="noreferrer">cs.android.com</a>. There's also the <a href="https://android.googlesource.com/" rel="noreferrer">Android official source browser</a> (based on <a href="https://code.google.com/p/gitiles/" rel="noreferrer">Gitiles</a>) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories. </p> <p>To get all the code locally, you can use the <a href="http://source.android.com/source/git-repo.html" rel="noreferrer">repo</a> helper program, or you can just clone individual repositories.</p> <p>And others:</p> <ul> <li><a href="http://source.android.com/source/downloading.html" rel="noreferrer">Downloading the Source Tree</a></li> </ul>
{ "question_id": 449763, "question_date": "2009-01-16T07:31:18.333Z", "question_score": 663, "tags": "android|android-source", "answer_id": 449790, "answer_date": "2009-01-16T07:58:46.747Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: What is Turing Complete? <p>What does the expression "Turing Complete" mean? </p> <p>Can you give a simple explanation, without going into too many theoretical details?</p>
<p>Here's the briefest explanation:</p> <p>A Turing Complete system means a system in which a program can be written that will find an answer (although with no guarantees regarding runtime or memory).</p> <p>So, if somebody says &quot;my new thing is Turing Complete&quot; that means in principle (although often not in practice) it could be used to solve any computation problem.</p> <p>Sometimes it's a joke... a guy wrote a Turing Machine simulator in vi, so it's possible to say that vi is the only computational engine ever needed in the world.</p>
{ "question_id": 7284, "question_date": "2008-08-10T18:41:02.300Z", "question_score": 663, "tags": "theory|turing-machines|turing-complete", "answer_id": 7320, "answer_date": "2008-08-10T20:10:48.687Z", "answer_score": 489 }
Please answer the following Stack Overflow question: Title: What's the strategy for handling CRLF (carriage return, line feed) with Git? <p>I tried committing files with CRLF-ending lines, but it failed.</p> <p>I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>.</p> <p>How to properly handle CRLF line endings?</p>
<p>Almost four years after asking this question, I have finally found <strong>an answer that completely satisfies me</strong>!</p> <p>See the details in <strong>github:help</strong>'s guide to <a href="https://help.github.com/articles/dealing-with-line-endings/">Dealing with line endings</a>.</p> <blockquote> <p>Git allows you to set the line ending properties for a repo directly using the <a href="http://git-scm.com/docs/gitattributes#_checking-out_and_checking-in">text attribute</a> in the <strong><code>.gitattributes</code></strong> file. This file is committed into the repo and overrides the <code>core.autocrlf</code> setting, allowing you to ensure consistent behaviour for all users regardless of their git settings.</p> </blockquote> <p>And thus</p> <blockquote> <p>The advantage of this is that your end of line configuration now travels with your repository and you don't need to worry about whether or not collaborators have the proper global settings.</p> </blockquote> <p>Here's an example of a <strong><code>.gitattributes</code></strong> file</p> <pre class="lang-sh prettyprint-override"><code># Auto detect text files and perform LF normalization * text=auto *.cs text diff=csharp *.java text diff=java *.html text diff=html *.css text *.js text *.sql text *.csproj text merge=union *.sln text merge=union eol=crlf *.docx diff=astextplain *.DOCX diff=astextplain # absolute paths are ok, as are globs /**/postinst* text eol=lf # paths that don't start with / are treated relative to the .gitattributes folder relative/path/*.txt text eol=lf </code></pre> <p>There is a convenient <a href="https://github.com/Danimoth/gitattributes">collection of ready to use .gitattributes files</a> for the most popular programming languages. It's useful to get you started.</p> <p>Once you've created or adjusted your <strong><code>.gitattributes</code></strong>, you should perform a once-and-for-all <a href="https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings">line endings re-normalization</a>.</p> <p>Note that the <a href="https://desktop.github.com">GitHub Desktop</a> app can suggest and create a <strong><code>.gitattributes</code></strong> file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended <strong><code>.gitattributes</code></strong> and if you agree, the app will also perform a normalization of all the files in your repository.</p> <p>Finally, the <a href="http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/">Mind the End of Your Line</a> article provides more background and explains how Git has evolved on the matters at hand. I consider this <em>required reading</em>.</p> <p>You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments:</p> <blockquote> <p>This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372">https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372</a></p> </blockquote> <p>One trick might be to have them commit their changes in another client, say <a href="http://www.sourcetreeapp.com">SourceTree</a>. Our team back then preferred that tool to Eclipse's EGit for many use cases.</p> <p>Who said software is easy? :-/</p>
{ "question_id": 170961, "question_date": "2008-10-04T20:39:28.013Z", "question_score": 663, "tags": "git|cross-platform|newline|eol", "answer_id": 10855862, "answer_date": "2012-06-01T18:56:35.800Z", "answer_score": 827 }
Please answer the following Stack Overflow question: Title: Why does JavaScript only work after opening developer tools in IE once? <p>IE9 Bug - JavaScript only works after opening developer tools once.</p> <p>Our site offers free pdf downloads to users, and it has a simple "enter password to download" function. However, it doesn't work at all in Internet Explorer. </p> <p>You can see for yourself in this <a href="http://www.makeuseof.com/pages/how-to-use-virtual-box">example</a>.</p> <p>The download pass is "makeuseof". In any other browser, it works fine. In IE, both buttons do nothing. </p> <p>The most curious thing I've found is that if you open and close the developer toolbar with F12, it all suddenly starts to work. </p> <p>We've tried compatibility mode and such, nothing makes a difference.</p> <p>How do I make this work in Internet Explorer?</p>
<p>It sounds like you might have some debugging code in your javascript.</p> <p>The experience you're describing is typical of code which contain <code>console.log()</code> or any of the other <code>console</code> functionality.</p> <p>The <code>console</code> object is only activated when the Dev Toolbar is opened. Prior to that, calling the console object will result in it being reported as <code>undefined</code>. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.</p> <p>There are a few solutions to this:</p> <p>The most obvious one is to go through your code removing references to <code>console</code>. You shouldn't be leaving stuff like that in production code anyway.</p> <p>If you want to keep the console references, you could wrap them in an <code>if()</code> statement, or some other conditional which checks whether the console object exists before trying to call it.</p>
{ "question_id": 7742781, "question_date": "2011-10-12T15:44:37.970Z", "question_score": 663, "tags": "javascript|internet-explorer|internet-explorer-9", "answer_id": 7742862, "answer_date": "2011-10-12T15:51:05.143Z", "answer_score": 831 }
Please answer the following Stack Overflow question: Title: How to set the current working directory? <p>How to set the current working directory in Python?</p>
<p>Try <a href="http://docs.python.org/library/os.html#os.chdir" rel="noreferrer"><code>os.chdir</code></a></p> <blockquote> <pre><code>os.chdir(path) </code></pre> <p>        Change the current working directory to path. Availability: Unix, Windows.</p> </blockquote>
{ "question_id": 1810743, "question_date": "2009-11-27T21:53:48.817Z", "question_score": 662, "tags": "python|working-directory", "answer_id": 1810760, "answer_date": "2009-11-27T21:59:59.637Z", "answer_score": 942 }
Please answer the following Stack Overflow question: Title: How to check if a string starts with a specified string? <p>I'm trying to check if a string starts with <code>http</code>. How can I do this check?</p> <pre><code>$string1 = 'google.com'; $string2 = 'http://www.google.com'; </code></pre>
<h2>PHP 8 or newer:</h2> <p>Use the <a href="https://www.php.net/manual/en/function.str-starts-with.php" rel="noreferrer"><strong>str_starts_with</strong></a> function:</p> <pre><code>str_starts_with('http://www.google.com', 'http') </code></pre> <h2>PHP 7 or older:</h2> <p>Use the <a href="https://www.php.net/manual/function.substr.php" rel="noreferrer"><strong>substr</strong></a> function to return a part of a string.</p> <pre><code>substr( $string_n, 0, 4 ) === &quot;http&quot; </code></pre> <p>If you're trying to make sure it's not another protocol. I'd use <code>http://</code> instead, since https would also match, and other things such as http-protocol.com.</p> <pre><code>substr( $string_n, 0, 7 ) === &quot;http://&quot; </code></pre> <p>And in general:</p> <pre><code>substr($string, 0, strlen($query)) === $query </code></pre>
{ "question_id": 2790899, "question_date": "2010-05-07T18:43:37.213Z", "question_score": 662, "tags": "php", "answer_id": 2790919, "answer_date": "2010-05-07T18:46:00.267Z", "answer_score": 1159 }
Please answer the following Stack Overflow question: Title: How to change indentation in Visual Studio Code? <p>For every typescript file visual studio code uses an auto indentation of 8 spaces. This is a bit too much for my taste but I can't find where to change it.</p> <p>Maybe it's available as a setting but under a different name as I can't find anything related to indentation.</p> <p><strong>UPDATE</strong></p> <p>I'm currently using the <a href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode" rel="noreferrer">Prettier code formatter</a> and that solves all formatting problems by auto formatting on save (if there is no syntax error)</p>
<p>You can change this in global <code>User</code> level or <code>Workspace</code> level.</p> <p>Open the settings: Click the gear on the bottom left, then click <code>Settings</code> as shown below.</p> <p><a href="https://i.stack.imgur.com/FvoPG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FvoPG.png" alt="Settings on VS Code menu" /></a></p> <p>Then, do the following 2 changes: (type <code>tabSize</code> in the search bar)</p> <ol> <li>Uncheck the checkbox of <code>Detect Indentation</code></li> <li>Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS. Haha :))</li> </ol> <p><a href="https://i.stack.imgur.com/BltIv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BltIv.png" alt="vscode set tabsize" /></a></p>
{ "question_id": 34174207, "question_date": "2015-12-09T08:40:33.730Z", "question_score": 662, "tags": "formatting|visual-studio-code", "answer_id": 59353357, "answer_date": "2019-12-16T09:04:01.437Z", "answer_score": 478 }
Please answer the following Stack Overflow question: Title: How can I convert byte size into a human-readable format in Java? <p>How can I convert byte size into a human-readable format in Java?</p> <p>Like 1024 should become &quot;1 Kb&quot; and 1024*1024 should become &quot;1 Mb&quot;.</p> <p>I am kind of sick of writing this utility method for each project. Is there a static method in <a href="https://commons.apache.org/" rel="noreferrer">Apache Commons</a> for this?</p>
<blockquote> <p><strong>Fun fact:</strong> The original snippet posted here was the most copied Java snippet of all time on Stack Overflow, and it was flawed. It was fixed, but it got messy.</p> <p>Full story in this article: <a href="https://programming.guide/worlds-most-copied-so-snippet.html" rel="noreferrer">The most copied Stack Overflow snippet of all time is flawed!</a></p> </blockquote> <p>Source: <a href="http://programming.guide/java/formatting-byte-size-to-human-readable-format.html" rel="noreferrer">Formatting byte size to human readable format | Programming.Guide</a></p> <h1>SI (1 k = 1,000)</h1> <pre><code>public static String humanReadableByteCountSI(long bytes) { if (-1000 &lt; bytes &amp;&amp; bytes &lt; 1000) { return bytes + &quot; B&quot;; } CharacterIterator ci = new StringCharacterIterator(&quot;kMGTPE&quot;); while (bytes &lt;= -999_950 || bytes &gt;= 999_950) { bytes /= 1000; ci.next(); } return String.format(&quot;%.1f %cB&quot;, bytes / 1000.0, ci.current()); } </code></pre> <h1>Binary (1 Ki = 1,024)</h1> <pre><code>public static String humanReadableByteCountBin(long bytes) { long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); if (absB &lt; 1024) { return bytes + &quot; B&quot;; } long value = absB; CharacterIterator ci = new StringCharacterIterator(&quot;KMGTPE&quot;); for (int i = 40; i &gt;= 0 &amp;&amp; absB &gt; 0xfffccccccccccccL &gt;&gt; i; i -= 10) { value &gt;&gt;= 10; ci.next(); } value *= Long.signum(bytes); return String.format(&quot;%.1f %ciB&quot;, value / 1024.0, ci.current()); } </code></pre> <h1>Example output:</h1> <pre class="lang-none prettyprint-override"><code> SI BINARY 0: 0 B 0 B 27: 27 B 27 B 999: 999 B 999 B 1000: 1.0 kB 1000 B 1023: 1.0 kB 1023 B 1024: 1.0 kB 1.0 KiB 1728: 1.7 kB 1.7 KiB 110592: 110.6 kB 108.0 KiB 7077888: 7.1 MB 6.8 MiB 452984832: 453.0 MB 432.0 MiB 28991029248: 29.0 GB 27.0 GiB 1855425871872: 1.9 TB 1.7 TiB 9223372036854775807: 9.2 EB 8.0 EiB (Long.MAX_VALUE) </code></pre>
{ "question_id": 3758606, "question_date": "2010-09-21T08:42:59.537Z", "question_score": 662, "tags": "java|formatting|apache-commons", "answer_id": 3758880, "answer_date": "2010-09-21T09:22:21.483Z", "answer_score": 1462 }
Please answer the following Stack Overflow question: Title: SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session <p>I am currently getting this error:</p> <blockquote> <p>System.Data.SqlClient.SqlException: New transaction is not allowed because there are other threads running in the session.</p> </blockquote> <p>while running this code:</p> <pre><code>public class ProductManager : IProductManager { #region Declare Models private RivWorks.Model.Negotiation.RIV_Entities _dbRiv = RivWorks.Model.Stores.RivEntities(AppSettings.RivWorkEntities_connString); private RivWorks.Model.NegotiationAutos.RivFeedsEntities _dbFeed = RivWorks.Model.Stores.FeedEntities(AppSettings.FeedAutosEntities_connString); #endregion public IProduct GetProductById(Guid productId) { // Do a quick sync of the feeds... SyncFeeds(); ... // get a product... ... return product; } private void SyncFeeds() { bool found = false; string feedSource = "AUTO"; switch (feedSource) // companyFeedDetail.FeedSourceTable.ToUpper()) { case "AUTO": var clientList = from a in _dbFeed.Client.Include("Auto") select a; foreach (RivWorks.Model.NegotiationAutos.Client client in clientList) { var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a; foreach (RivWorks.Model.Negotiation.AutoNegotiationDetails companyFeedDetail in companyFeedDetailList) { if (companyFeedDetail.FeedSourceTable.ToUpper() == "AUTO") { var company = (from a in _dbRiv.Company.Include("Product") where a.CompanyId == companyFeedDetail.CompanyId select a).First(); foreach (RivWorks.Model.NegotiationAutos.Auto sourceProduct in client.Auto) { foreach (RivWorks.Model.Negotiation.Product targetProduct in company.Product) { if (targetProduct.alternateProductID == sourceProduct.AutoID) { found = true; break; } } if (!found) { var newProduct = new RivWorks.Model.Negotiation.Product(); newProduct.alternateProductID = sourceProduct.AutoID; newProduct.isFromFeed = true; newProduct.isDeleted = false; newProduct.SKU = sourceProduct.StockNumber; company.Product.Add(newProduct); } } _dbRiv.SaveChanges(); // ### THIS BREAKS ### // } } } break; } } } </code></pre> <p>Model #1 - This model sits in a database on our Dev Server. <a href="http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/bdb2b000-6e60-4af0-a7a1-2bb6b05d8bc1/Model1.png">Model #1 http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/bdb2b000-6e60-4af0-a7a1-2bb6b05d8bc1/Model1.png</a> </p> <p>Model #2 - This model sits in a database on our Prod Server and is updated each day by automatic feeds. <a href="http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/4260259f-bce6-43d5-9d2a-017bd9a980d4/Model2.png">alt text http://content.screencast.com/users/Keith.Barrows/folders/Jing/media/4260259f-bce6-43d5-9d2a-017bd9a980d4/Model2.png</a></p> <p>Note - The red circled items in Model #1 are the fields I use to "map" to Model #2. Please ignore the red circles in Model #2: that is from another question I had which is now answered.</p> <p>Note: I still need to put in an isDeleted check so I can soft delete it from DB1 if it has gone out of our client's inventory.</p> <p>All I want to do, with this particular code, is connect a company in DB1 with a client in DB2, get their product list from DB2 and INSERT it in DB1 if it is not already there. First time through should be a full pull of inventory. Each time it is run there after nothing should happen unless new inventory came in on the feed over night.</p> <blockquote> <p><strong>So the big question - how to I solve the transaction error I am getting? Do I need to drop and recreate my context each time through the loops (does not make sense to me)?</strong></p> </blockquote>
<p>After much pulling out of hair I discovered that the <code>foreach</code> loops were the culprits. What needs to happen is to call EF but return it into an <code>IList&lt;T&gt;</code> of that target type then loop on the <code>IList&lt;T&gt;</code>.</p> <p>Example:</p> <pre><code>IList&lt;Client&gt; clientList = from a in _dbFeed.Client.Include("Auto") select a; foreach (RivWorks.Model.NegotiationAutos.Client client in clientList) { var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a; // ... } </code></pre>
{ "question_id": 2113498, "question_date": "2010-01-21T22:37:14.920Z", "question_score": 662, "tags": "c#|entity-framework|transactions|inversion-of-control", "answer_id": 2180920, "answer_date": "2010-02-01T23:46:39.693Z", "answer_score": 763 }
Please answer the following Stack Overflow question: Title: Adding values to a C# array <p>Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:</p> <pre><code>int[] terms; for(int runs = 0; runs &lt; 400; runs++) { terms[] = runs; } </code></pre> <p>For those who have used PHP, here's what I'm trying to do in C#:</p> <pre><code>$arr = array(); for ($i = 0; $i &lt; 10; $i++) { $arr[] = $i; } </code></pre>
<p>You can do this way -</p> <pre><code>int[] terms = new int[400]; for (int runs = 0; runs &lt; 400; runs++) { terms[runs] = value; } </code></pre> <p>Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.</p> <pre><code>List&lt;int&gt; termsList = new List&lt;int&gt;(); for (int runs = 0; runs &lt; 400; runs++) { termsList.Add(value); } // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); </code></pre> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/a/365658/495455">a) <strong>for</strong> loops on List&lt;T> are a bit more than 2 times cheaper than <strong>foreach</strong> loops on List&lt;T>, b) Looping on array is around 2 times cheaper than looping on List&lt;T>, c) looping on array using <strong>for</strong> is 5 times cheaper than looping on List&lt;T> using <strong>foreach</strong> (which most of us do).</a></p>
{ "question_id": 202813, "question_date": "2008-10-14T21:02:58.730Z", "question_score": 661, "tags": "c#|arrays", "answer_id": 202854, "answer_date": "2008-10-14T21:08:42.337Z", "answer_score": 985 }
Please answer the following Stack Overflow question: Title: How can I check if a string represents an int, without using try/except? <p>Is there any way to tell whether a <strong>string</strong> represents an integer (e.g., <code>'3'</code>, <code>'-17'</code> but not <code>'3.14'</code> or <code>'asfasfas'</code>) Without using a try/except mechanism?</p> <pre class="lang-py prettyprint-override"><code>is_int('3.14') == False is_int('-7') == True </code></pre>
<p>If you're really just annoyed at using <code>try/except</code>s all over the place, please just write a helper function:</p> <pre><code>def RepresentsInt(s): try: int(s) return True except ValueError: return False &gt;&gt;&gt; print RepresentsInt("+123") True &gt;&gt;&gt; print RepresentsInt("10.0") False </code></pre> <p>It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.</p>
{ "question_id": 1265665, "question_date": "2009-08-12T11:46:13.920Z", "question_score": 661, "tags": "python|string|integer", "answer_id": 1267145, "answer_date": "2009-08-12T16:05:28.667Z", "answer_score": 489 }
Please answer the following Stack Overflow question: Title: How do I assign a port mapping to an existing Docker container? <p>I'm not sure if I've misunderstood something here, but it seems like it's only possible to set port mappings by creating a new container from an image. Is there a way to assign a port mapping to an existing Docker container?</p>
<p>You can change the port mapping by directly editing the <code>hostconfig.json</code> file at <code>/var/lib/docker/containers/[hash_of_the_container]/hostconfig.json</code> or <code>/var/snap/docker/common/var-lib-docker/containers/[hash_of_the_container]/hostconfig.json</code>, I believe, if You installed Docker as a snap.</p> <p>You can determine the [hash_of_the_container] via the <code>docker inspect &lt;container_name&gt;</code> command and the value of the &quot;Id&quot; field is the hash.</p> <ol> <li>Stop the container (<code>docker stop &lt;container_name&gt;</code>).</li> <li>Stop docker service (per Tacsiazuma's comment)</li> <li>Change the file.</li> <li>Restart your docker engine (to flush/clear config caches).</li> <li>Start the container (<code>docker start &lt;container_name&gt;</code>).</li> </ol> <p>So you don't need to create an image with this approach. You can also change the restart flag here.</p> <p><em>P.S. You may visit <a href="https://docs.docker.com/engine/admin/" rel="noreferrer">https://docs.docker.com/engine/admin/</a> to learn how to correctly restart your docker engine as per your host machine. I used <code>sudo systemctl restart docker</code> to restart my docker engine that is running on Ubuntu 16.04</em>.</p>
{ "question_id": 19335444, "question_date": "2013-10-12T14:46:18.073Z", "question_score": 661, "tags": "docker|port|lxc|linux-containers", "answer_id": 38783433, "answer_date": "2016-08-05T07:20:57.267Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: Calling remove in foreach loop in Java <p>In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:</p> <pre><code>List&lt;String&gt; names = .... for (String name : names) { // Do something names.remove(name). } </code></pre> <p>As an addendum, is it legal to remove items that have not been iterated over yet? For instance, </p> <pre><code>//Assume that the names list as duplicate entries List&lt;String&gt; names = .... for (String name : names) { // Do something while (names.remove(name)); } </code></pre>
<p>To safely remove from a collection while iterating over it you should use an Iterator.</p> <p>For example:</p> <pre><code>List&lt;String&gt; names = .... Iterator&lt;String&gt; i = names.iterator(); while (i.hasNext()) { String s = i.next(); // must be called before you can call i.remove() // Do something i.remove(); } </code></pre> <p>From the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html" rel="noreferrer">Java Documentation</a> :</p> <blockquote> <p>The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.</p> </blockquote> <p>Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html" rel="noreferrer">here</a></p>
{ "question_id": 1196586, "question_date": "2009-07-28T20:39:07.540Z", "question_score": 661, "tags": "java|loops|iterator|foreach", "answer_id": 1196612, "answer_date": "2009-07-28T20:43:38.653Z", "answer_score": 1010 }
Please answer the following Stack Overflow question: Title: When to use static classes in C# <p>Here's what <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members" rel="noreferrer">MSDN has to say under <em>When to Use Static Classes</em></a>:</p> <blockquote> <pre><code>static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... } </code></pre> <p>Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.</p> </blockquote> <p>To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static? </p>
<p>I wrote my thoughts of static classes in an earlier Stack Overflow answer: <em><a href="https://stackoverflow.com/questions/205689/class-with-single-method-best-approach#206481">Class with single method -- best approach?</a></em></p> <p>I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.</p> <p><strong>Polymorphism</strong></p> <p>Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.</p> <p><strong>Interface woes</strong></p> <p>Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by <a href="https://docs.microsoft.com/archive/blogs/kirillosenkov/how-to-override-static-methods" rel="noreferrer">passing delegates instead of interfaces</a>.</p> <p><strong>Testing</strong></p> <p>This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.</p> <p><strong>Fosters blobs</strong></p> <p>As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.</p> <p><strong>Parameter creep</strong></p> <p>To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.</p> <p><strong>Demanding consumers to create an instance of classes for no reason</strong></p> <p>One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns <code>new MyClass();</code></p> <p><strong>Only a Sith deals in absolutes</strong></p> <p>Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.</p> <p><strong>Standards, standards, standards!</strong></p> <p>Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.</p>
{ "question_id": 241339, "question_date": "2008-10-27T20:53:37.673Z", "question_score": 661, "tags": "c#|class|static", "answer_id": 241372, "answer_date": "2008-10-27T21:01:00.293Z", "answer_score": 767 }
Please answer the following Stack Overflow question: Title: Why is __init__() always called after __new__()? <p>I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the <a href="https://en.wikipedia.org/wiki/Flyweight_pattern" rel="noreferrer">flyweight design pattern</a>.</p> <p>However, I'm a bit confused as to why <code>__init__</code> is always called after <code>__new__</code>. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the <code>__new__</code> which feels quite hacky.)</p> <p>Here's an example:</p> <pre><code>class A(object): _dict = dict() def __new__(cls): if 'key' in A._dict: print "EXISTS" return A._dict['key'] else: print "NEW" return super(A, cls).__new__(cls) def __init__(self): print "INIT" A._dict['key'] = self print "" a1 = A() a2 = A() a3 = A() </code></pre> <p>Outputs:</p> <pre><code>NEW INIT EXISTS INIT EXISTS INIT </code></pre> <p>Why?</p>
<blockquote> <p>Use <strong><code>__new__</code></strong> when you need to control the creation of a new instance.</p> </blockquote> <blockquote> <p>Use <strong><code>__init__</code></strong> when you need to control initialization of a new instance.</p> <p><strong><code>__new__</code></strong> is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.</p> </blockquote> <blockquote> <p>In contrast, <strong><code>__init__</code></strong> doesn't return anything; it's only responsible for initializing the instance after it's been created.</p> <p>In general, you shouldn't need to override <strong><code>__new__</code></strong> unless you're subclassing an immutable type like str, int, unicode or tuple.</p> </blockquote> <p>From April 2008 post: <a href="http://mail.python.org/pipermail/tutor/2008-April/061426.html" rel="noreferrer">When to use <code>__new__</code> vs. <code>__init__</code>?</a> on mail.python.org.</p> <p>You should consider that what you are trying to do is usually done with a <a href="http://en.wikipedia.org/wiki/Factory_object" rel="noreferrer">Factory</a> and that's the best way to do it. Using <strong><code>__new__</code></strong> is not a good clean solution so please consider the usage of a factory. Here's a good example: <a href="http://code.activestate.com/recipes/86900/" rel="noreferrer">ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ Recipe</a>.</p>
{ "question_id": 674304, "question_date": "2009-03-23T17:13:01.187Z", "question_score": 661, "tags": "python|design-patterns|class-design", "answer_id": 674369, "answer_date": "2009-03-23T17:23:04.923Z", "answer_score": 692 }
Please answer the following Stack Overflow question: Title: Why does git perform fast-forward merges by default? <p>Coming from mercurial, I use branches to organize features. Naturally, I want to see this work-flow in my history as well.</p> <p>I started my new project using git and finished my first feature. When merging the feature, I realized git uses fast-forward, i.e. it applies my changes directly to the master branch if possible and forgets about my branch.</p> <p>So to think into the future: I'm the only one working on this project. If I use git's default approach (fast-forward merging), my history would result in one giant master branch. Nobody knows I used a separate branch for every feature, because in the end I'll have only that giant master branch. Won't that look unprofessional?</p> <p>By this reasoning, I don't want fast-forward merging and can't see why it is the default. What's so good about it?</p>
<p>Fast-forward merging makes sense for short-lived branches, but in a more <a href="http://nvie.com/posts/a-successful-git-branching-model/" rel="noreferrer">complex history</a>, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.</p> <p><em><strong>Warning</strong>: Non-fast-forwarding has potential side effects as well. Please review <a href="https://sandofsky.com/blog/git-workflow.html" rel="noreferrer">https://sandofsky.com/blog/git-workflow.html</a>, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for <code>master</code>.</em></p> <p><img src="https://i.stack.imgur.com/vRdkr.png" alt="alt text"><br> <sup>(From <a href="http://nvie.com/" rel="noreferrer">nvie.com</a>, <a href="http://nvie.com/about/" rel="noreferrer">Vincent Driessen</a>, post "<a href="http://nvie.com/posts/a-successful-git-branching-model/" rel="noreferrer"><strong>A successful Git branching model</strong></a>")</sup></p> <blockquote> <p><strong>Incorporating a finished feature on develop</strong></p> <p>Finished features may be merged into the develop branch to add them to the upcoming release:</p> </blockquote> <pre><code>$ git checkout develop Switched to branch 'develop' $ git merge --no-ff myfeature Updating ea1b82a..05e9557 (Summary of changes) $ git branch -d myfeature Deleted branch myfeature (was 05e9557). $ git push origin develop </code></pre> <blockquote> <p>The <code>--no-ff</code> flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.</p> </blockquote> <p><a href="https://stackoverflow.com/users/46058/jakub-narebski">Jakub Narębski</a> also <a href="https://stackoverflow.com/questions/2850369/why-does-git-use-fast-forward-merging-by-default/2850413?noredirect=1#comment24301311_2850413">mentions</a> the <a href="http://git-scm.com/docs/git-config" rel="noreferrer">config <strong><code>merge.ff</code></strong></a>:</p> <blockquote> <p>By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.<br> When set to <code>false</code>, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the <code>--no-ff</code> option from the command line).<br> When set to '<code>only</code>', only such fast-forward merges are allowed (equivalent to giving the <code>--ff-only</code> option from the command line).</p> </blockquote> <hr> <p>The fast-forward is the default because:</p> <ul> <li>short-lived branches are very easy to create and use in Git</li> <li>short-lived branches often isolate many commits that can be reorganized freely within that branch</li> <li>those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.</li> </ul> <p>But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.</p> <p>In this case, you can end up setting <a href="http://sip-router.org/wiki/git/gitconfig" rel="noreferrer">this kind of config file</a>:</p> <pre><code>[branch "master"] # This is the list of cmdline options that should be added to git-merge # when I merge commits into the master branch. # The option --no-commit instructs git not to commit the merge # by default. This allows me to do some final adjustment to the commit log # message before it gets commited. I often use this to add extra info to # the merge message or rewrite my local branch names in the commit message # to branch names that are more understandable to the casual reader of the git log. # Option --no-ff instructs git to always record a merge commit, even if # the branch being merged into can be fast-forwarded. This is often the # case when you create a short-lived topic branch which tracks master, do # some changes on the topic branch and then merge the changes into the # master which remained unchanged while you were doing your work on the # topic branch. In this case the master branch can be fast-forwarded (that # is the tip of the master branch can be updated to point to the tip of # the topic branch) and this is what git does by default. With --no-ff # option set, git creates a real merge commit which records the fact that # another branch was merged. I find this easier to understand and read in # the log. mergeoptions = --no-commit --no-ff </code></pre> <hr> <p>The OP adds in the comments:</p> <blockquote> <p>I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?</p> </blockquote> <p>Jefromi answers:</p> <blockquote> <p>I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches. </p> <p>To me, <strong>a short-lived branch is one that I create in order to make a certain operation easier</strong> (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.<br> That means it likely <strong>should be absorbed into the topic branch it forked from</strong>, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature. </p> </blockquote> <p>More generally, I add:</p> <blockquote> <p>it really depends on your <a href="https://stackoverflow.com/questions/216212#216228">development workflow</a>: </p> <ul> <li>if it is linear, one branch makes sense. </li> <li>If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense. </li> </ul> <p>See "<a href="https://stackoverflow.com/questions/2100829/when-should-you-branch/2107672#2107672"><strong>When should you branch?</strong></a>"</p> </blockquote> <p>Actually, when you consider the Mercurial branch model, it is at its core <a href="https://stackoverflow.com/questions/448567/best-practices-in-mercurial-branch-vs-clone-and-partial-merges"><em>one</em> branch per repository</a> (even though you can create <a href="http://stevelosh.com/blog/2009/08/a-guide-to-branching-in-mercurial/" rel="noreferrer">anonymous heads, bookmarks and even named branches</a>)<br> See <a href="https://stackoverflow.com/questions/1598759/git-and-mercurial-compare-and-contrast/1599930#1599930">"Git and Mercurial - Compare and Contrast"</a>.</p> <blockquote> <p>Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".<br> Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.<br> Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "<a href="https://stackoverflow.com/questions/3965676/why-did-git-detach-my-head/3965714#3965714">detached HEAD</a>"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.</p> </blockquote>
{ "question_id": 2850369, "question_date": "2010-05-17T15:26:16.313Z", "question_score": 661, "tags": "git|git-branch|git-merge|fast-forward", "answer_id": 2850413, "answer_date": "2010-05-17T15:31:36.253Z", "answer_score": 733 }
Please answer the following Stack Overflow question: Title: How to open the Google Play Store directly from my Android application? <p>I have open the Google Play store using the following code </p> <pre><code>Intent i = new Intent(android.content.Intent.ACTION_VIEW); i.setData(Uri.parse("https://play.google.com/store/apps/details?id=my packagename ")); startActivity(i);. </code></pre> <p>But it shows me a Complete Action View as to select the option (browser/play store). I need to open the application in Play Store directly.</p>
<p>You can do this using the <a href="https://developer.android.com/distribute/tools/promote/linking.html" rel="noreferrer"><code>market://</code> prefix</a>.</p> <h2>Java</h2> <pre><code>final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;market://details?id=&quot; + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;https://play.google.com/store/apps/details?id=&quot; + appPackageName))); } </code></pre> <h2>Kotlin</h2> <pre><code>try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(&quot;market://details?id=$packageName&quot;))) } catch (e: ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(&quot;https://play.google.com/store/apps/details?id=$packageName&quot;))) } </code></pre> <p>We use a <code>try/catch</code> block here because an <code>Exception</code> will be thrown if the Play Store is not installed on the target device.</p> <p><strong>NOTE</strong>: any app can register as capable of handling the <code>market://details?id=&lt;appId&gt;</code> Uri, if you want to specifically target Google Play check the <em>Berťák</em> answer</p>
{ "question_id": 11753000, "question_date": "2012-08-01T05:27:10.423Z", "question_score": 660, "tags": "android|android-intent|google-play", "answer_id": 11753070, "answer_date": "2012-08-01T05:34:22.717Z", "answer_score": 1637 }
Please answer the following Stack Overflow question: Title: How can I get file extensions with JavaScript? <p>See code: </p> <pre><code>var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returns xsl getFileExtension(file2); //returns doc function getFileExtension(filename) { /*TODO*/ } </code></pre>
<p><strong>Newer Edit:</strong> Lots of things have changed since this question was initially posted - there's a lot of really good information in <a href="https://stackoverflow.com/a/1203361/23746">wallacer's revised answer</a> as well as <a href="https://stackoverflow.com/a/12900504/23746">VisioN's excellent breakdown</a></p> <hr> <p><strong>Edit:</strong> Just because this is the accepted answer; <a href="https://stackoverflow.com/a/1203361/23746">wallacer's answer</a> is indeed much better:</p> <pre><code>return filename.split('.').pop(); </code></pre> <hr> <p>My old answer:</p> <pre><code>return /[^.]+$/.exec(filename); </code></pre> <p>Should do it.</p> <p><strong>Edit:</strong> In response to PhiLho's comment, use something like:</p> <pre><code>return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined; </code></pre>
{ "question_id": 190852, "question_date": "2008-10-10T11:08:05.090Z", "question_score": 660, "tags": "javascript|file-extension", "answer_id": 190878, "answer_date": "2008-10-10T11:18:02.933Z", "answer_score": 1075 }
Please answer the following Stack Overflow question: Title: How to install Google Play Services in a Genymotion VM (with no drag and drop support)? <p>VmHow can I install Google Play Services in a Genymotion emulator with no drag and drop support?</p> <p>I can't install it as mentioned in Stack Overflow post <em><a href="https://stackoverflow.com/questions/17831990">How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?</a></em> due to the lack of support for drag and drop installation.</p> <p>Genymotion supports Google Apps for a few emulators, but it doesn't support tablet emulators.</p>
<p>As of Genymotion 2.10.0 and onwards, GApps can be installed from the emulator toolbar. Please refer to <a href="https://stackoverflow.com/a/45455999/2099146">answer</a> by @<a href="https://stackoverflow.com/users/3494639/michaelstoddart">MichaelStoddart</a>.</p> <p>Next follows former answer kept here for historic reason:</p> <p>Genymotion doesn't provide Google Apps. To install Google Apps:</p> <ol> <li><p>Upgrade Genymotion and VirtualBox to the latest version.</p></li> <li><p>Download two zip files: <br> - ARM Translation Installer v1.1 <br> - <strong>Google Apps for your Android version</strong>: <a href="http://wiki.cyanogenmod.org/w/Google_Apps" rel="noreferrer">2.3.7 - 4.4.4</a> or <a href="http://opengapps.org/" rel="noreferrer">4.4 - 6.0 (with platform and variant)</a> You can also find the GApps list in the <strong>wbroek</strong> user <a href="https://gist.github.com/wbroek/9321145" rel="noreferrer">GitHubGist page</a>.</p></li> <li><p>Open Genymotion emulator and go to home screen then drag and drop the first file <strong>Genymotion-ARM-Translation_v1.1.zip</strong> over the emulator. A dialog will appear and show as file transfer in progress, then another dialog will appear and ask that do you want to flash it on the emulator. Click OK and reboot the device by running <code>adb reboot</code> from your terminal or command prompt. </p></li> <li><p>Drag and drop the second file <strong>gapps-*-signed.zip</strong> and repeat the same steps as above. Run <code>adb reboot</code> again and, once rebooted, Google Apps will be in the emulator. </p></li> <li><p><strong>At this point 'Google Apps Services' will crash frequently</strong> with the following message <code>google play services has stopped working</code>. Open Google Play. After providing your account details, open Google Play and update your installed Google Apps. This seems to make Google Play realize you have an old Google Play Services and will ask you to update (in my case, <strong>updating Google Hangouts required a new version of Google Play Services</strong>). I've also heard that simply waiting will also prompt you to update. The 'Google Play Services' app doesn't seem to appear otherwise - you can't search for it. You should then see an offer to update Google Play Services. Once the new Google Play Services is installed you will now have stable, working access to Google Play</p></li> </ol>
{ "question_id": 20121883, "question_date": "2013-11-21T13:07:28.277Z", "question_score": 660, "tags": "android|android-emulator|google-play-services|genymotion", "answer_id": 20137324, "answer_date": "2013-11-22T04:58:02.213Z", "answer_score": 982 }
Please answer the following Stack Overflow question: Title: Selecting all text in HTML text input when clicked <p>I have the following code to display a textbox in a HTML webpage.</p> <pre><code>&lt;input type="text" id="userid" name="userid" value="Please enter the user ID" /&gt; </code></pre> <p>When the page displays, the text contains the <em>Please enter the user ID</em> message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is <em>Please enter the user ID</em>). </p> <p>Is it possible to select the entire text with only one click?</p> <p><strong>Edit:</strong></p> <p>Sorry, I forgot to say: I must use the input <code>type="text"</code></p>
<p>You can use the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select" rel="noreferrer"><code>.select()</code> method for HTMLElement</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;label for="userid"&gt;User ID&lt;/label&gt; &lt;input onClick="this.select();" value="Please enter the user ID" id="userid" /&gt;</code></pre> </div> </div> </p> <p>But apparently it doesn't work on mobile Safari. In those cases you can use:</p> <pre><code>&lt;input onClick=&quot;this.setSelectionRange(0, this.value.length)&quot; value=&quot;Sample Text&quot; id=&quot;userid&quot; /&gt; </code></pre>
{ "question_id": 4067469, "question_date": "2010-11-01T08:27:05.637Z", "question_score": 660, "tags": "javascript|html|textinput", "answer_id": 4067488, "answer_date": "2010-11-01T08:32:32.920Z", "answer_score": 1079 }
Please answer the following Stack Overflow question: Title: Query-string encoding of a Javascript Object <p>Do you know a fast and simple way to encode a Javascript Object into a <code>string</code> that I can pass via a <code>GET</code> Request?</p> <p>No <code>jQuery</code>, no other frameworks - just plain Javascript :)</p>
<p>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>serialize = function(obj) { var str = []; for (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&amp;"); } console.log(serialize({ foo: "hi there", bar: "100%" })); // foo=hi%20there&amp;bar=100%25</code></pre> </div> </div> </p> <p>Edit: this one also converts recursive objects (using php "array" notation for the query string)</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>serialize = function(obj, prefix) { var str = [], p; for (p in obj) { if (obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null &amp;&amp; typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&amp;"); } console.log(serialize({ foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] } })); // foo=hi%20there&amp;bar%5Bblah%5D=123&amp;bar%5Bquux%5D%5B0%5D=1&amp;bar%5Bquux%5D%5B1%5D=2&amp;bar%5Bquux%5D%5B2%5D=3</code></pre> </div> </div> </p>
{ "question_id": 1714786, "question_date": "2009-11-11T12:07:37.940Z", "question_score": 660, "tags": "javascript|query-string|urlencode", "answer_id": 1714899, "answer_date": "2009-11-11T12:31:26.380Z", "answer_score": 952 }
Please answer the following Stack Overflow question: Title: Ternary operator (?:) in Bash <p>Is there a way to do something like this</p> <pre><code>int a = (b == 5) ? c : d; </code></pre> <p>using Bash?</p>
<p>ternary operator <code>? :</code> is just short form of <code>if/else</code></p> <pre><code>case "$b" in 5) a=$c ;; *) a=$d ;; esac </code></pre> <p>Or</p> <pre><code> [[ $b = 5 ]] &amp;&amp; a="$c" || a="$d" </code></pre>
{ "question_id": 3953645, "question_date": "2010-10-17T14:38:52.120Z", "question_score": 660, "tags": "bash|syntax|conditional-operator", "answer_id": 3953666, "answer_date": "2010-10-17T14:42:42.130Z", "answer_score": 688 }
Please answer the following Stack Overflow question: Title: In Java, what is the best way to determine the size of an object? <p>I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause <code>OutOfMemoryError</code>s. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a <code>VM</code>?</p> <p>Right now, I have code that says read up to <strong>32,000 rows</strong>, but I'd also like to have code that says read as many rows as possible until I've used <strong>32MB</strong> of memory. Maybe that is a different question, but I'd still like to know. </p>
<p>You can use the <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html" rel="noreferrer"><code>java.lang.instrument</code> package</a>.</p> <p>Compile and put this class in a JAR:</p> <pre><code>import java.lang.instrument.Instrumentation; public class ObjectSizeFetcher { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } public static long getObjectSize(Object o) { return instrumentation.getObjectSize(o); } } </code></pre> <p>Add the following to your <code>MANIFEST.MF</code>:</p> <pre><code>Premain-Class: ObjectSizeFetcher </code></pre> <p>Use the <code>getObjectSize()</code> method:</p> <pre><code>public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); } } </code></pre> <p>Invoke with:</p> <pre><code>java -javaagent:ObjectSizeFetcherAgent.jar C </code></pre>
{ "question_id": 52353, "question_date": "2008-09-09T17:07:03.323Z", "question_score": 660, "tags": "java|memory", "answer_id": 52682, "answer_date": "2008-09-09T19:24:37.863Z", "answer_score": 484 }
Please answer the following Stack Overflow question: Title: Capturing multiple line output into a Bash variable <p>I've got a script 'myscript' that outputs the following:</p> <pre><code>abc def ghi </code></pre> <p>in another script, I call:</p> <pre><code>declare RESULT=$(./myscript) </code></pre> <p>and <code>$RESULT</code> gets the value</p> <pre><code>abc def ghi </code></pre> <p>Is there a way to store the result either with the newlines, or with '\n' character so I can output it with '<code>echo -e</code>'?</p>
<p>Actually, RESULT contains what you want — to demonstrate:</p> <pre><code>echo "$RESULT" </code></pre> <p>What you show is what you get from:</p> <pre><code>echo $RESULT </code></pre> <hr> <p>As noted in the comments, the difference is that (1) the double-quoted version of the variable (<code>echo "$RESULT"</code>) preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (<code>echo $RESULT</code>) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).</p>
{ "question_id": 613572, "question_date": "2009-03-05T04:32:18.437Z", "question_score": 660, "tags": "bash|variables", "answer_id": 613580, "answer_date": "2009-03-05T04:36:09.877Z", "answer_score": 1231 }
Please answer the following Stack Overflow question: Title: What is the difference between compileSdkVersion and targetSdkVersion? <p>I have looked at the <a href="http://developer.android.com/sdk/installing/studio-build.html#buildFileBasics" rel="noreferrer" title="documentation">documentation</a> for building with Gradle, but I'm still not sure what the difference between <code>compileSdkVersion</code> and <code>targetSdkVersion</code> is.</p> <p>All it says is:</p> <blockquote> <p>The <code>compileSdkVersion</code> property specifies the compilation target.</p> </blockquote> <p>Well, what is the "compilation target"?</p> <p>I see two possible ways to interpret this:</p> <ol> <li><code>compileSdkVersion</code> is the version of the compiler used in building the app, while <code>targetSdkVersion</code> is the <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html" rel="noreferrer">"API level that the application targets"</a>. (If this were the case, I'd assume <code>compileSdkVersion</code> must be greater than or equal to the <code>targetSdkVersion</code>?</li> <li>They mean the same thing. "compilation target" == "the API level that the application targets"</li> <li>Something else?</li> </ol> <p>I see that <a href="https://stackoverflow.com/questions/24510219/android-studio-min-skd-version-target-sdk-version-vs-compile-sdk-version" title="this question">this question</a> has been asked before, but the one answer just quotes the doc, which is what is unclear to me.</p>
<h3>compileSdkVersion</h3> <p>The <code>compileSdkVersion</code> is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set <code>compileSdkVersion</code> to 15, you will get a compilation error. If you set <code>compileSdkVersion</code> to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.</p> <h3>targetSdkVersion</h3> <p>The <code>targetSdkVersion</code> has nothing to do with how your app is compiled or what APIs you can utilize. The <code>targetSdkVersion</code> is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.</p> <p>For example, as <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html">the documentation</a> states:</p> <blockquote> <p>For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...</p> </blockquote> <p>The Android OS, <strong>at runtime</strong>, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.</p> <p>For all practical purposes, most apps are going to want to set <code>targetSdkVersion</code> to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the <code>targetSdkVersion</code>, it defaults to the <code>minSdkVersion</code>.</p>
{ "question_id": 26694108, "question_date": "2014-11-01T22:54:26.653Z", "question_score": 660, "tags": "android|sdk|android-gradle-plugin|android-build", "answer_id": 26694276, "answer_date": "2014-11-01T23:17:30.400Z", "answer_score": 677 }
Please answer the following Stack Overflow question: Title: Why is “while( !feof(file) )” always wrong? <p>What is wrong with using <code>feof()</code> to control a read loop? For example:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { char *path = &quot;stdin&quot;; FILE *fp = argc &gt; 1 ? fopen(path=argv[1], &quot;r&quot;) : stdin; if( fp == NULL ){ perror(path); return EXIT_FAILURE; } while( !feof(fp) ){ /* THIS IS WRONG */ /* Read and process data from file… */ } if( fclose(fp) != 0 ){ perror(path); return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <p>What is wrong with this loop?</p>
<h3>TL;DR</h3> <p><code>while(!feof)</code> is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.</p> <p>I'd like to provide an abstract, high-level perspective. So continue reading if you're interested in what <code>while(!feof)</code> actually does.</p> <h3>Concurrency and simultaneity</h3> <p>I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists &quot;concurrently&quot; with your program. As with all things concurrent, questions about the &quot;current state&quot; don't make sense: There is no concept of &quot;simultaneity&quot; across concurrent events. Many properties of state simply don't <em>exist</em> concurrently.</p> <p>Let me make this more precise: Suppose you want to ask, &quot;do you have more data&quot;. You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says &quot;yes&quot; – by the time you try reading, it may no longer have data. Similarly, if the answer is &quot;no&quot;, by the time you try reading, data may have arrived. The conclusion is that there simply <em>is</em> no property like &quot;I have data&quot;, since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a &quot;yes, I have data&quot; that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)</p> <p>So we conclude that it is impossible, and in fact un<em>reasonable</em>, to ask an I/O system whether it <em>will be</em> able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to <em>attempt</em> the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a &quot;synchronisation point&quot;, if you will.)</p> <h3>EOF</h3> <p>Now we get to EOF. EOF is the <em>response</em> you get from an <em>attempted</em> I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply <em>cannot know</em> whether further, future operations will succeed. You <em>must</em> always first try the operation and then respond to success or failure.</p> <h3>Examples</h3> <p>In each of the examples, note carefully that we <em>first</em> attempt the I/O operation and <em>then</em> consume the result if it is valid. Note further that we <em>always</em> must use the result of the I/O operation, though the result takes different shapes and forms in each example.</p> <ul> <li><p>C stdio, read from a file:</p> <pre><code> for (;;) { size_t n = fread(buf, 1, bufsize, infile); consume(buf, n); if (n == 0) { break; } } </code></pre> <p>The result we must use is <code>n</code>, the number of elements that were read (which may be as little as zero).</p> </li> <li><p>C stdio, <code>scanf</code>:</p> <pre><code> for (int a, b, c; scanf(&quot;%d %d %d&quot;, &amp;a, &amp;b, &amp;c) == 3; ) { consume(a, b, c); } </code></pre> <p>The result we must use is the return value of <code>scanf</code>, the number of elements converted.</p> </li> <li><p>C++, iostreams formatted extraction:</p> <pre><code> for (int n; std::cin &gt;&gt; n; ) { consume(n); } </code></pre> <p>The result we must use is <code>std::cin</code> itself, which can be evaluated in a boolean context and tells us whether the stream is still in the <code>good()</code> state.</p> </li> <li><p>C++, iostreams getline:</p> <pre><code> for (std::string line; std::getline(std::cin, line); ) { consume(line); } </code></pre> <p>The result we must use is again <code>std::cin</code>, just as before.</p> </li> <li><p>POSIX, <code>write(2)</code> to flush a buffer:</p> <pre><code> char const * p = buf; ssize_t n = bufsize; for (ssize_t k = bufsize; (k = write(fd, p, n)) &gt; 0; p += k, n -= k) {} if (n != 0) { /* error, failed to write complete buffer */ } </code></pre> <p>The result we use here is <code>k</code>, the number of bytes written. The point here is that we can only know how many bytes were written <em>after</em> the write operation.</p> </li> <li><p>POSIX <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html" rel="noreferrer"><code>getline()</code></a></p> <pre><code> char *buffer = NULL; size_t bufsiz = 0; ssize_t nbytes; while ((nbytes = getline(&amp;buffer, &amp;bufsiz, fp)) != -1) { /* Use nbytes of data in buffer */ } free(buffer); </code></pre> <p>The result we must use is <code>nbytes</code>, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).</p> <p>Note that the function explicitly returns <code>-1</code> (and not EOF!) when an error occurs or it reaches EOF.</p> </li> </ul> <p>You may notice that we very rarely spell out the actual word &quot;EOF&quot;. We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.</p> <ul> <li><p>A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:</p> <pre><code> std::string input = &quot; 123 &quot;; // example std::istringstream iss(input); int value; if (iss &gt;&gt; value &gt;&gt; std::ws &amp;&amp; iss.get() == EOF) { consume(value); } else { // error, &quot;input&quot; is not parsable as an integer } </code></pre> </li> </ul> <p>We use two results here. The first is <code>iss</code>, the stream object itself, to check that the formatted extraction to <code>value</code> succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, <code>iss.get()</code>, and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.</p> <p>In the C standard library you can achieve something similar with the <code>strto*l</code> functions by checking that the end pointer has reached the end of the input string.</p>
{ "question_id": 5431941, "question_date": "2011-03-25T11:42:33.207Z", "question_score": 660, "tags": "c|file|while-loop|eof|feof", "answer_id": 26557243, "answer_date": "2014-10-24T22:28:36.680Z", "answer_score": 530 }
Please answer the following Stack Overflow question: Title: How to generate a random int in C? <p>Is there a function to generate a random int number in C? Or will I have to use a third party library?</p>
<blockquote> <p><strong>Note</strong>: Don't use <code>rand()</code> for security. If you need a cryptographically secure number, <a href="https://stackoverflow.com/a/39475626/2224584">see this answer</a> instead.</p> </blockquote> <pre><code>#include &lt;time.h&gt; #include &lt;stdlib.h&gt; srand(time(NULL)); // Initialization, should only be called once. int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX. </code></pre> <p>On Linux, you might prefer to use <a href="https://linux.die.net/man/3/random" rel="noreferrer">random and srandom</a>.</p>
{ "question_id": 822323, "question_date": "2009-05-04T22:07:59.787Z", "question_score": 659, "tags": "c|random", "answer_id": 822368, "answer_date": "2009-05-04T22:18:36.453Z", "answer_score": 806 }
Please answer the following Stack Overflow question: Title: How to check if array is empty or does not exist? <p>What's the best way to check if an array is empty or does not exist?</p> <p>Something like this?</p> <pre><code>if(array.length &lt; 1 || array == undefined){ //empty } </code></pre>
<p>You want to do the check for <code>undefined</code> first. If you do it the other way round, it will generate an error if the array is undefined.</p> <pre><code>if (array === undefined || array.length == 0) { // array does not exist or is empty } </code></pre> <h3>Update</h3> <p>This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as <code>null</code> values, other types of objects with a <code>length</code> property, etc. It is also not very idiomatic JavaScript.</p> <p><strong>The foolproof approach</strong><br /> Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a <code>length</code> property.</p> <pre><code>if (!Array.isArray(array) || !array.length) { // array does not exist, is not an array, or is empty // ⇒ do not attempt to process array } </code></pre> <p>To break it down:</p> <ol> <li><p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" rel="noreferrer"><code>Array.isArray()</code></a>, unsurprisingly, checks whether its argument is an array. This weeds out values like <code>null</code>, <code>undefined</code> and anything else that is not an array.<br /> Note that this will also eliminate <em>array-like objects</em>, such as the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments" rel="noreferrer"><code>arguments</code></a> object and DOM <a href="https://developer.mozilla.org/en/docs/Web/API/NodeList" rel="noreferrer"><code>NodeList</code></a> objects. Depending on your situation, this might not be the behavior you're after.</p> </li> <li><p>The <code>array.length</code> condition checks whether the variable's <code>length</code> property evaluates to a <a href="https://developer.mozilla.org/en/docs/Glossary/Truthy" rel="noreferrer"><em>truthy</em></a> value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like <code>array.length != 0</code> or <code>array.length !== 0</code> are not required here.</p> </li> </ol> <p><strong>The pragmatic approach</strong><br /> In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.</p> <p>In those cases, I tend to go for the following, more idiomatic JavaScript:</p> <pre><code>if (!array || !array.length) { // array or array.length are falsy // ⇒ do not attempt to process array } </code></pre> <p>Or, more frequently, its inverse:</p> <pre><code>if (array &amp;&amp; array.length) { // array and array.length are truthy // ⇒ probably OK to process array } </code></pre> <p>With the introduction of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">optional chaining operator</a> (Elvis operator) in ECMAScript 2020, this can be shortened even further:</p> <pre><code>if (!array?.length) { // array or array.length are falsy // ⇒ do not attempt to process array } </code></pre> <p>Or the opposite:</p> <pre><code>if (array?.length) { // array and array.length are truthy // ⇒ probably OK to process array } </code></pre>
{ "question_id": 24403732, "question_date": "2014-06-25T08:28:50.023Z", "question_score": 659, "tags": "javascript|arrays", "answer_id": 24403771, "answer_date": "2014-06-25T08:30:54.193Z", "answer_score": 1323 }
Please answer the following Stack Overflow question: Title: How can I unset a JavaScript variable? <p>I have a global variable in JavaScript (actually a <code>window</code> property, but I don't think it matters) which was already populated by a previous script, but I don't want another script that will run later to see its value or that it was even defined.</p> <p>I've put <code>some_var = undefined</code> and it works for the purpose of testing <code>typeof some_var == &quot;undefined&quot;</code> but I really do not think it's the right way to go about it.</p> <p>What do you think?</p>
<p>The <code>delete</code> operator removes a property from an object. It cannot remove a variable. So the answer to the question depends on how the global variable or property is defined.</p> <p>(1) If it is created with <code>var</code>, it cannot be deleted.</p> <p>For example:</p> <pre class="lang-js prettyprint-override"><code>var g_a = 1; //create with var, g_a is a variable delete g_a; //return false console.log(g_a); //g_a is still 1 </code></pre> <p>(2) If it is created without <code>var</code>, it can be deleted.</p> <pre class="lang-js prettyprint-override"><code>g_b = 1; //create without var, g_b is a property delete g_b; //return true console.log(g_b); //error, g_b is not defined </code></pre> <h2 id="technical-explanation-huj1">Technical Explanation</h2> <h3 id="using-var-b0z2">1. Using <code>var</code></h3> <p>In this case the reference <code>g_a</code> is created in what the ECMAScript spec calls &quot;<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.3" rel="noreferrer"><em>VariableEnvironment</em></a>&quot; that is attached to the current scope - this may be the a function execution context in the case of using <code>var</code> inside a function (though it may be get a little more complicated when you consider <code>let</code>) or in the case of &quot;global&quot; code the <em>VariableEnvironment</em> is attached to the global object (often <code>window</code>).</p> <p>References in the <em>VariableEnvironment</em> are not normally deletable - the process detailed in <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.5" rel="noreferrer">ECMAScript 10.5</a> explains this in detail, but suffice it to say that unless your code is executed in an <code>eval</code> context (which most browser-based development consoles use), then variables declared with <code>var</code> cannot be deleted.</p> <h3 id="without-using-var-jknj">2. Without Using <code>var</code></h3> <p>When trying to assign a value to a name without using the <code>var</code> keyword, JavaScript tries to locate the named reference in what the ECMAScript spec calls &quot;<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.3" rel="noreferrer"><em>LexicalEnvironment</em></a>&quot;, and the main difference is that <em>LexicalEnvironment</em>s are nested - that is a <em>LexicalEnvironment</em> has a parent (what the ECMAScript spec calls &quot;outer environment reference&quot;) and when JavaScript fails to locate the reference in a <em>LexicalEnvironment</em>, it looks in the parent <em>LexicalEnvironment</em> (as detailed in <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.3.1" rel="noreferrer">10.3.1</a> and <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.2.1" rel="noreferrer">10.2.2.1</a>). The top level <em>LexicalEnvironment</em> is the &quot;<a href="http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3" rel="noreferrer"><em>global environment</em></a>&quot;, and that is bound to the global object in that its references are the global object's properties. So if you try to access a name that was not declared using a <code>var</code> keyword in the current scope or any outer scopes, JavaScript will eventually fetch a property of the <code>window</code> object to serve as that reference. As we've learned before, properties on objects can be deleted.</p> <h3 id="notes-ip5f">Notes</h3> <ol> <li><p>It is important to remember that <code>var</code> declarations are &quot;hoisted&quot; - i.e. they are always considered to have happened in the beginning of the scope that they are in - though not the value initialization that may be done in a <code>var</code> statement - that is left where it is. So in the following code, <code>a</code> is a reference from the <em>VariableEnvironment</em> and not the <code>window</code> property and its value will be <code>10</code> at the end of the code:</p> <pre class="lang-js prettyprint-override"><code>function test() { a = 5; var a = 10; } </code></pre> </li> <li><p>The above discussion is when &quot;strict mode&quot; is not enabled. Lookup rules are a bit different when using &quot;strict mode&quot; and lexical references that would have resolved to window properties without &quot;strict mode&quot; will raise &quot;undeclared variable&quot; errors under &quot;strict mode&quot;. I didn't really understand where this is specified, but its how browsers behave.</p> </li> </ol>
{ "question_id": 1596782, "question_date": "2009-10-20T19:23:59.493Z", "question_score": 659, "tags": "javascript|global-variables|undefined|variable-declaration|unset", "answer_id": 25919959, "answer_date": "2014-09-18T18:33:28.943Z", "answer_score": 523 }
Please answer the following Stack Overflow question: Title: Find duplicate lines in a file and count how many time each line was duplicated? <p>Suppose I have a file similar to the following:</p> <pre><code>123 123 234 234 123 345 </code></pre> <p>I would like to find how many times '123' was duplicated, how many times '234' was duplicated, etc. So ideally, the output would be like:</p> <pre><code>123 3 234 2 345 1 </code></pre>
<p>Assuming there is one number per line:</p> <pre><code>sort &lt;file&gt; | uniq -c </code></pre> <p>You can use the more verbose <code>--count</code> flag too with the GNU version, e.g., on Linux:</p> <pre><code>sort &lt;file&gt; | uniq --count </code></pre>
{ "question_id": 6712437, "question_date": "2011-07-15T19:53:00.703Z", "question_score": 659, "tags": "file|count|find|duplicates|lines", "answer_id": 6712477, "answer_date": "2011-07-15T19:56:29.537Z", "answer_score": 946 }
Please answer the following Stack Overflow question: Title: How to SSH to a VirtualBox guest externally through a host? <p>I have a Ubuntu VM running on my Windows 7 machine. How do I set it up so that I can access the webserver externally through SSH?</p> <p>I found steps (<em><a href="http://www.wiredrevolution.com/virtualbox/setup-ssh-access-between-virtualbox-host-and-guest-vms" rel="noreferrer">Setup SSH access between VirtualBox Host and Guest VMs</a></em>) to be able to ssh to my guest from my host, but that still leaves me with the problem of accessing it through my router.</p> <p>I suppose that I could install an SSH server on my Windows machine and then tunnel a few times (though I'm not 100% sure what to use in terms of local, dynamic, etc. or how to set up multiple tunnels?), but is there a way to make the VM directly accessible to my router so I could directly port forward to it?</p>
<p>The best way to login to a guest Linux VirtualBox VM is <a href="https://www.virtualbox.org/manual/ch06.html#natforward" rel="noreferrer">port forwarding</a>. By default, you should have one interface already which is using <a href="http://en.wikipedia.org/wiki/Network_address_translation" rel="noreferrer">NAT</a>. Then go to the <em>Network</em> settings and click the <em>Port Forwarding</em> button. Add a new <em>Rule</em>. As the rule name, insert "ssh". As "Host port", insert 3022. As "Guest port", insert 22. Everything else of the rule can be left blank.</p> <p>or from the command line</p> <pre class="lang-bash prettyprint-override"><code>VBoxManage modifyvm myserver --natpf1 "ssh,tcp,,3022,,22" </code></pre> <p>where 'myserver' is the name of the created VM. Check the added rules:</p> <pre class="lang-bash prettyprint-override"><code>VBoxManage showvminfo myserver | grep 'Rule' </code></pre> <p>That's all! Please be sure you don't forget to install an <a href="http://en.wikipedia.org/wiki/Secure_Shell" rel="noreferrer">SSH</a> server in the VM:</p> <pre class="lang-bash prettyprint-override"><code>sudo apt-get install openssh-server </code></pre> <p>To SSH into the guest VM, write:</p> <pre class="lang-bash prettyprint-override"><code>ssh -p 3022 [email protected] </code></pre> <p>Where <code>user</code> is your username within the VM.</p>
{ "question_id": 5906441, "question_date": "2011-05-06T03:24:03.857Z", "question_score": 659, "tags": "ssh|virtualbox", "answer_id": 10532299, "answer_date": "2012-05-10T10:39:54.820Z", "answer_score": 1350 }
Please answer the following Stack Overflow question: Title: How to use a filter in a controller? <p>I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller? </p> <p>This is what I've tried so far:</p> <pre><code>function myCtrl($scope,filter1) { // i simply used the filter function name, it is not working. } </code></pre>
<p>Inject <strong>$filter</strong> to your controller</p> <pre><code>function myCtrl($scope, $filter) { } </code></pre> <p>Then wherever you want to use that filter, just use it like this:</p> <pre><code>$filter('filtername'); </code></pre> <p>If you want to pass arguments to that filter, do it using separate parentheses:</p> <pre><code>function myCtrl($scope, $filter) { $filter('filtername')(arg1,arg2); } </code></pre> <p>Where <code>arg1</code> is the array you want to filter on and <code>arg2</code> is the object used to filter.</p>
{ "question_id": 14302267, "question_date": "2013-01-13T09:29:54.373Z", "question_score": 659, "tags": "angularjs|angular-filters|ng-controller", "answer_id": 14302334, "answer_date": "2013-01-13T09:42:20.110Z", "answer_score": 1058 }
Please answer the following Stack Overflow question: Title: Python progression path - From apprentice to guru <p>I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutions and also with the semantics of the language that allows such a natural flow from thoughts to workable code.</p> <p>What I would like to know is your answer to a kind of question I have seldom seen in this or other forums. This question seems central to me for anyone on the path to Python improvement but who wonders what his next steps should be.</p> <p>Let me sum up what I do NOT want to ask first ;)</p> <ul> <li>I don't want to know how to QUICKLY learn Python</li> <li>Nor do I want to find out the best way to get acquainted with the language</li> <li>Finally, I don't want to know a 'one trick that does it all' approach.</li> </ul> <p>What I do want to know your opinion about, is:</p> <p><strong>What are the steps YOU would recommend to a Python journeyman, from apprenticeship to guru status (feel free to stop wherever your expertise dictates it), in order that one IMPROVES CONSTANTLY, becoming a better and better Python coder, one step at a time. Some of the people on SO almost seem worthy of worship for their Python prowess, please enlighten us :)</strong></p> <p>The kind of answers I would enjoy (but feel free to surprise the readership :P ), is formatted more or less like this:</p> <ul> <li>Read this (eg: python tutorial), pay attention to that kind of details</li> <li>Code for so manytime/problems/lines of code</li> <li>Then, read this (eg: this or that book), but this time, pay attention to this</li> <li>Tackle a few real-life problems</li> <li>Then, proceed to reading Y.</li> <li>Be sure to grasp these concepts</li> <li>Code for X time</li> <li>Come back to such and such basics or move further to...</li> <li>(you get the point :)</li> </ul> <p>I really care about knowing your opinion on what exactly one should pay attention to, at various stages, in order to progress CONSTANTLY (with due efforts, of course). If you come from a specific field of expertise, discuss the path you see as appropriate in this field.</p> <p>EDIT: Thanks to your great input, I'm back on the Python improvement track! I really appreciate!</p>
<p>I thought the process of Python mastery went something like:</p> <ol> <li>Discover <a href="http://en.wikipedia.org/wiki/List_comprehension#Python" rel="noreferrer">list comprehensions</a></li> <li>Discover <a href="http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators" rel="noreferrer">generators</a></li> <li>Incorporate <a href="http://docs.python.org/library/functions.html" rel="noreferrer">map, reduce, filter, iter, range, xrange</a> often into your code</li> <li>Discover <a href="http://wiki.python.org/moin/PythonDecorators" rel="noreferrer">Decorators</a></li> <li>Write recursive functions, a lot</li> <li>Discover <a href="http://docs.python.org/library/itertools.html" rel="noreferrer">itertools</a> and <a href="http://docs.python.org/library/functools.html" rel="noreferrer">functools</a></li> <li>Read <a href="https://rads.stackoverflow.com/amzn/click/com/0596514980" rel="noreferrer" rel="nofollow noreferrer">Real World Haskell</a> (<a href="http://book.realworldhaskell.org/read/" rel="noreferrer">read free online</a>)</li> <li>Rewrite all your old Python code with tons of higher order functions, recursion, and whatnot.</li> <li>Annoy your cubicle mates every time they present you with a Python class. Claim it could be "better" implemented as a dictionary plus some functions. Embrace functional programming.</li> <li>Rediscover the <a href="http://en.wikipedia.org/wiki/Strategy_pattern#Python" rel="noreferrer">Strategy</a> pattern and then <a href="https://rads.stackoverflow.com/amzn/click/com/0596007124" rel="noreferrer" rel="nofollow noreferrer">all those things</a> from imperative code you tried so hard to forget after Haskell.</li> <li>Find a balance.</li> </ol>
{ "question_id": 2573135, "question_date": "2010-04-04T00:28:33.830Z", "question_score": 659, "tags": "python", "answer_id": 2576240, "answer_date": "2010-04-04T23:19:53.480Z", "answer_score": 471 }
Please answer the following Stack Overflow question: Title: How can I remove the debug banner in Flutter? <p>I am using <code>flutter screenshot</code> and I would like the screenshot not to have a banner. Now it does have.</p> <p>Note that I get a <code>not supported for emulator</code> message for profile and release mode.</p>
<p>On your <code>MaterialApp</code> set <code>debugShowCheckedModeBanner</code> to <code>false</code>.</p> <pre class="lang-dart prettyprint-override"><code>MaterialApp( debugShowCheckedModeBanner: false, ) </code></pre> <p>The <em><strong>debug</strong></em> banner will also automatically be removed on the release build.</p>
{ "question_id": 48893935, "question_date": "2018-02-20T20:46:41.487Z", "question_score": 659, "tags": "flutter|debugging|android-emulator", "answer_id": 48893964, "answer_date": "2018-02-20T20:48:55.330Z", "answer_score": 1270 }
Please answer the following Stack Overflow question: Title: How to clone a Date object? <p>Assigning a <code>Date</code> variable to another one will copy the reference to the same instance. This means that changing one will change the other.</p> <p>How can I actually clone or copy a <code>Date</code> instance?</p>
<p>Use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="noreferrer">Date</a> object's <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>getTime()</code></a> method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (<a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">epoch time</a>):</p> <pre><code>var date = new Date(); var copiedDate = new Date(date.getTime()); </code></pre> <p>In Safari 4, you can also write:</p> <pre><code>var date = new Date(); var copiedDate = new Date(date); </code></pre> <p>...but I'm not sure whether this works in other browsers. (It seems to work in IE8).</p>
{ "question_id": 1090815, "question_date": "2009-07-07T07:22:42.460Z", "question_score": 659, "tags": "javascript", "answer_id": 1090817, "answer_date": "2009-07-07T07:24:00.040Z", "answer_score": 972 }
Please answer the following Stack Overflow question: Title: What is the "double tilde" (~~) operator in JavaScript? <p>I'm seeing this in some code, and I have no idea what it does:</p> <pre><code>var jdn = function(y, m, d) { var tmp = (m &lt;= 2 ? -1 : 0); return ~~((1461 * (y + 4800 + tmp)) / 4) + ~~((367 * (m - 2 - 12 * tmp)) / 12) - ~~((3 * ((y + 4900 + tmp) / 100)) / 4) + d - 2483620; }; </code></pre> <p>What's the <code>~~</code> operator do?</p>
<p>That <code>~~</code> is a double NOT bitwise operator.</p> <p>It is used as a <a href="http://rocha.la/JavaScript-bitwise-operators-in-practice" rel="noreferrer">faster substitute for <code>Math.floor()</code></a> for <em>positive</em> numbers. It does not return the same result as <code>Math.floor()</code> for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).</p>
{ "question_id": 5971645, "question_date": "2011-05-11T23:18:14.870Z", "question_score": 659, "tags": "javascript", "answer_id": 5971668, "answer_date": "2011-05-11T23:21:35.450Z", "answer_score": 859 }
Please answer the following Stack Overflow question: Title: Is JavaScript guaranteed to be single-threaded? <p>JavaScript is known to be single-threaded in all modern browser implementations, but is that specified in any standard or is it just by tradition? Is it totally safe to assume that JavaScript is always single-threaded?</p>
<p>That's a good question. I'd love to say “yes”. I can't.</p> <p>JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.</p> <p>(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)</p> <p>However, in reality this <em>isn't quite true</em>, in sneaky nasty ways.</p> <p>The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var l= document.getElementById('log'); var i= document.getElementById('inp'); i.onblur= function() { l.value+= 'blur\n'; }; setTimeout(function() { l.value+= 'log in\n'; l.focus(); l.value+= 'log out\n'; }, 100); i.focus();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;textarea id="log" rows="20" cols="40"&gt;&lt;/textarea&gt; &lt;input id="inp"&gt;</code></pre> </div> </div> </p> <p>Results in <code>log in, blur, log out</code> on all except IE. These events don't just fire because you called <code>focus()</code> directly, they could happen because you called <code>alert()</code>, or opened a pop-up window, or anything else that moves the focus.</p> <p>This can also result in other events. For example add an <code>i.onchange</code> listener and type something in the input before the <code>focus()</code> call unfocuses it, and the log order is <code>log in, change, blur, log out</code>, except in Opera where it's <code>log in, blur, log out, change</code> and IE where it's (even less explicably) <code>log in, change, log out, blur</code>.</p> <p>Similarly calling <code>click()</code> on an element that provides it calls the <code>onclick</code> handler immediately in all browsers (at least this is consistent!).</p> <p>(I'm using the direct <code>on...</code> event handler properties here, but the same happens with <code>addEventListener</code> and <code>attachEvent</code>.)</p> <p>There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done <em>nothing</em> to provoke it. An example:</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 l= document.getElementById('log'); document.getElementById('act').onclick= function() { l.value+= 'alert in\n'; alert('alert!'); l.value+= 'alert out\n'; }; window.onresize= function() { l.value+= 'resize\n'; };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;textarea id="log" rows="20" cols="40"&gt;&lt;/textarea&gt; &lt;button id="act"&gt;alert&lt;/button&gt;</code></pre> </div> </div> </p> <p>Hit <code>alert</code> and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get <code>alert in, resize, alert out</code> in the textarea.</p> <p>You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.</p> <p>You might think, well, it's only <code>resize</code> (and probably a few more like <code>scroll</code>) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.</p> <p>Places where events that you can cause to be generated can be raised whilst script is still threaded:</p> <ul> <li><p>when the modal popups (<code>alert</code>, <code>confirm</code>, <code>prompt</code>) are open, in all browsers but Opera;</p></li> <li><p>during <code>showModalDialog</code> on browsers that support it;</p></li> <li><p>the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.</p></li> <li><p>a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).</p></li> <li><p>probably more. It's been a while since I tested this and browsers have gained complexity since.</p></li> </ul> <p>In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.</p> <p>If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a <code>setInterval</code> function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. <code>postMessage</code> will also hopefully soothe the pain of cross-document scripting in the future.</p>
{ "question_id": 2734025, "question_date": "2010-04-29T00:24:54.127Z", "question_score": 659, "tags": "javascript|concurrency", "answer_id": 2734311, "answer_date": "2010-04-29T01:51:45.830Z", "answer_score": 632 }
Please answer the following Stack Overflow question: Title: Property '...' has no initializer and is not definitely assigned in the constructor <p>in my Angular app i have a component:</p> <pre><code>import { MakeService } from './../../services/make.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-vehicle-form', templateUrl: './vehicle-form.component.html', styleUrls: ['./vehicle-form.component.css'] }) export class VehicleFormComponent implements OnInit { makes: any[]; vehicle = {}; constructor(private makeService: MakeService) { } ngOnInit() { this.makeService.getMakes().subscribe(makes =&gt; { this.makes = makes console.log("MAKES", this.makes); }); } onMakeChange(){ console.log("VEHICLE", this.vehicle); } } </code></pre> <p>but in the "makes" property I have a mistake. I dont know what to do with it...</p> <p><a href="https://i.stack.imgur.com/QpJLJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QpJLJ.png" alt="mistake"></a></p>
<p>I think you are using the latest version of TypeScript. Please see the section &quot;Strict Class Initialization&quot; in the <strong><a href="http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html" rel="noreferrer"><code>link</code></a></strong>.</p> <p>There are two ways to fix this:</p> <p>A. If you are using VSCode you need to change the TS version that the editor use.</p> <p>B. Just initialize the array when you declare it</p> <pre><code>makes: any[] = []; </code></pre> <p>or inside the constructor:</p> <pre><code>constructor(private makeService: MakeService) { // Initialization inside the constructor this.makes = []; } </code></pre>
{ "question_id": 49699067, "question_date": "2018-04-06T18:33:21.417Z", "question_score": 658, "tags": "angular|typescript", "answer_id": 49699097, "answer_date": "2018-04-06T18:35:08.160Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: Does Python have an ordered set? <p>Python has an <a href="http://www.python.org/dev/peps/pep-0372/" rel="noreferrer">ordered dictionary</a>. What about an ordered set?</p>
<p>There is an <a href="http://code.activestate.com/recipes/576694/" rel="noreferrer">ordered set</a> (possible <a href="https://github.com/ActiveState/code/blob/3b27230f418b714bc9a0f897cb8ea189c3515e99/recipes/Python/576696_OrderedSet_with_Weakrefs/README.md" rel="noreferrer">new link</a>) recipe for this which is referred to from the <a href="https://docs.python.org/2/library/collections.html" rel="noreferrer">Python 2 Documentation</a>. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.</p> <pre><code>OrderedSet([1, 2, 3]) </code></pre> <p>This is a MutableSet, so the signature for <code>.union</code> doesn't match that of set, but since it includes <code>__or__</code> something similar can easily be added:</p> <pre><code>@staticmethod def union(*sets): union = OrderedSet() union.union(*sets) return union def union(self, *sets): for set in sets: self |= set </code></pre>
{ "question_id": 1653970, "question_date": "2009-10-31T10:12:07.643Z", "question_score": 658, "tags": "python|set", "answer_id": 1653974, "answer_date": "2009-10-31T10:15:06.857Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: Mipmaps vs. drawable folders <p>I'm working with Android Studio 1.1 Preview 1. I noticed that when I create a new project I'm getting the following hierarchy:</p> <p><img src="https://i.stack.imgur.com/6UnvM.png" alt="Enter image description here"></p> <p>Mipmap folders for different DPIs, no more different DPIs drawable folders.</p> <p>Should I put all my resources in the mipmap folders, or just the app icon?</p>
<p>The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.</p> <p>According to <a href="https://android-developers.googleblog.com/2014/10/getting-your-apps-ready-for-nexus-6-and.html" rel="noreferrer">this Google blogpost</a>:</p> <blockquote> <p>It’s best practice to place your app icons in <strong>mipmap-</strong> folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.</p> </blockquote> <p>When referencing the <strong>mipmap-</strong> folders ensure you are using the following reference:</p> <pre><code>android:icon="@mipmap/ic_launcher" </code></pre> <p>The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.</p>
{ "question_id": 28065267, "question_date": "2015-01-21T10:48:18.740Z", "question_score": 658, "tags": "android|android-drawable|mipmaps", "answer_id": 28065664, "answer_date": "2015-01-21T11:06:38.467Z", "answer_score": 939 }
Please answer the following Stack Overflow question: Title: Programmatically Lighten or Darken a hex color (or rgb, and blend colors) <p>Here is a function I was working on to programmatically lighten or darken a hex color by a specific amount. Just pass in a string like <code>&quot;3F6D2A&quot;</code> for the color (<code>col</code>) and a base10 integer (<code>amt</code>) for the amount to lighten or darken. To darken, pass in a negative number (i.e. <code>-20</code>).</p> <p>The reason for me to do this was because of all the solutions I found, thus far, they seemed to over-complicate the issue. And I had a feeling it could be done with just a couple lines of code. Please let me know if you find any problems, or have any adjustments to make that would speed it up.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function LightenDarkenColor(col, amt) { col = parseInt(col, 16); return (((col &amp; 0x0000FF) + amt) | ((((col &gt;&gt; 8) &amp; 0x00FF) + amt) &lt;&lt; 8) | (((col &gt;&gt; 16) + amt) &lt;&lt; 16)).toString(16); } // TEST console.log( LightenDarkenColor("3F6D2A",40) );</code></pre> </div> </div> </p> <p>For Development use here is an easier to read version:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function LightenDarkenColor(col, amt) { var num = parseInt(col, 16); var r = (num &gt;&gt; 16) + amt; var b = ((num &gt;&gt; 8) &amp; 0x00FF) + amt; var g = (num &amp; 0x0000FF) + amt; var newColor = g | (b &lt;&lt; 8) | (r &lt;&lt; 16); return newColor.toString(16); } // TEST console.log(LightenDarkenColor("3F6D2A", -40));</code></pre> </div> </div> </p> <p>And finally a version to handle colors that may (or may not) have the &quot;#&quot; in the beginning. Plus adjusting for improper color values:</p> <pre><code>function LightenDarkenColor(col,amt) { var usePound = false; if ( col[0] == &quot;#&quot; ) { col = col.slice(1); usePound = true; } var num = parseInt(col,16); var r = (num &gt;&gt; 16) + amt; if ( r &gt; 255 ) r = 255; else if (r &lt; 0) r = 0; var b = ((num &gt;&gt; 8) &amp; 0x00FF) + amt; if ( b &gt; 255 ) b = 255; else if (b &lt; 0) b = 0; var g = (num &amp; 0x0000FF) + amt; if ( g &gt; 255 ) g = 255; else if ( g &lt; 0 ) g = 0; return (usePound?&quot;#&quot;:&quot;&quot;) + (g | (b &lt;&lt; 8) | (r &lt;&lt; 16)).toString(16); } </code></pre> <p>OK, so now it's not just a couple of lines, but it seems far simpler and if you're not using the &quot;#&quot; and don't need to check for colors out of range, it is only a couple of lines.</p> <p>If not using the &quot;#&quot;, you can just add it in code like:</p> <pre><code>var myColor = &quot;3F6D2A&quot;; myColor = LightenDarkenColor(myColor,10); thePlaceTheColorIsUsed = (&quot;#&quot; + myColor); </code></pre> <p>I guess my main question is, am I correct here? Does this not encompass most (normal) situations? And if so, what is the fastest and smallest way to do this? I want to use in animations and in a small environment, so speed is the first most important factor here, size second, accuracy third, readability? huh? not on the list of requirements (sorry, I know half of you are tearing out your eyes right now!).</p>
<p><em>Well, this answer has become its own beast. Many new versions, it was getting stupid long. Many thanks to all of the great many contributors to this answer. But, in order to keep it simple for the masses. I archived all the versions/history of this answer's evolution to my <a href="https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)#stackoverflow-archive-begin" rel="noreferrer">github</a>. And started it over clean on StackOverflow here with the newest version. A special thanks goes out to <a href="https://stackoverflow.com/users/740553/mike-pomax-kamermans">Mike 'Pomax' Kamermans</a> for this version. He gave me the new math.</em></p> <hr /> <p>This function (<code>pSBC</code>) will take a HEX or RGB web color. <code>pSBC</code> can shade it darker or lighter, or blend it with a second color, and can also pass it right thru but convert from Hex to RGB (Hex2RGB) or RGB to Hex (RGB2Hex). All without you even knowing what color format you are using.</p> <p>This runs really fast, probably the fastest, especially considering its many features. It was a long time in the making. See the whole story on my <a href="https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)#stackoverflow-archive-begin" rel="noreferrer">github</a>. If you want the absolutely smallest and fastest possible way to shade or blend, see the Micro Functions below and use one of the 2-liner speed demons. They are great for intense animations, but this version here is fast enough for most animations.</p> <p>This function uses Log Blending or Linear Blending. However, it does NOT convert to HSL to properly lighten or darken a color. Therefore, <strong>results from this function will differ</strong> from those much larger and much slower functions that use HSL.</p> <blockquote> <p><a href="https://jsfiddle.net/PimpTrizkit/a7ac0qvp/" rel="noreferrer">jsFiddle with pSBC</a></p> <p><a href="https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)" rel="noreferrer">github &gt; pSBC Wiki</a></p> </blockquote> <p>Features:</p> <ul> <li>Auto-detects and accepts standard Hex colors in the form of strings. For example: <code>&quot;#AA6622&quot;</code> or <code>&quot;#bb551144&quot;</code>.</li> <li>Auto-detects and accepts standard RGB colors in the form of strings. For example: <code>&quot;rgb(123,45,76)&quot;</code> or <code>&quot;rgba(45,15,74,0.45)&quot;</code>.</li> <li>Shades colors to white or black by percentage.</li> <li>Blends colors together by percentage.</li> <li>Does Hex2RGB and RGB2Hex conversion at the same time, or solo.</li> <li>Accepts 3 digit (or 4 digit w/ alpha) HEX color codes, in the form #RGB (or #RGBA). It will expand them. For Example: <code>&quot;#C41&quot;</code> becomes <code>&quot;#CC4411&quot;</code>.</li> <li>Accepts and (Linear) blends alpha channels. If either the <code>c0</code> (from) color or the <code>c1</code> (to) color has an alpha channel, then the returned color will have an alpha channel. If both colors have an alpha channel, then the returned color will be a linear blend of the two alpha channels using the percentage given (just as if it were a normal color channel). If only one of the two colors has an alpha channel, this alpha will just be passed thru to the returned color. This allows one to blend/shade a transparent color while maintaining the transparency level. Or, if the transparency levels should blend as well, make sure both colors have alphas. When shading, it will pass the alpha channel straight thru. If you want basic shading that also shades the alpha channel, then use <code>rgb(0,0,0,1)</code> or <code>rgb(255,255,255,1)</code> as your <code>c1</code> (to) color (or their hex equivalents). For RGB colors, the returned color's alpha channel will be rounded to 3 decimal places.</li> <li>RGB2Hex and Hex2RGB conversions are implicit when using blending. Regardless of the <code>c0</code> (from) color; the returned color will always be in the color format of the <code>c1</code> (to) color, if one exists. If there is no <code>c1</code> (to) color, then pass <code>'c'</code> in as the <code>c1</code> color and it will shade and convert whatever the <code>c0</code> color is. If conversion only is desired, then pass <code>0</code> in as the percentage (<code>p</code>) as well. If the <code>c1</code> color is omitted or a non-<code>string</code> is passed in, it will not convert.</li> <li>A secondary function is added to the global as well. <code>pSBCr</code> can be passed a Hex or RGB color and it returns an object containing this color information. Its in the form: {r: XXX, g: XXX, b: XXX, a: X.XXX}. Where <code>.r</code>, <code>.g</code>, and <code>.b</code> have range 0 to 255. And when there is no alpha: <code>.a</code> is -1. Otherwise: <code>.a</code> has range 0.000 to 1.000.</li> <li>For RGB output, it outputs <code>rgba()</code> over <code>rgb()</code> when a color with an alpha channel was passed into <code>c0</code> (from) and/or <code>c1</code> (to).</li> <li>Minor Error Checking has been added. It's not perfect. It can still crash or create jibberish. But it will catch some stuff. Basically, if the structure is wrong in some ways or if the percentage is not a number or out of scope, it will return <code>null</code>. An example: <code>pSBC(0.5,&quot;salt&quot;) == null</code>, where as it thinks <code>#salt</code> is a valid color. Delete the four lines which end with <code>return null;</code> to remove this feature and make it faster and smaller.</li> <li>Uses Log Blending. Pass <code>true</code> in for <code>l</code> (the 4th parameter) to use Linear Blending.</li> </ul> <h3>Code:</h3> <pre class="lang-js prettyprint-override"><code>// Version 4.0 const pSBC=(p,c0,c1,l)=&gt;{ let r,g,b,P,f,t,h,i=parseInt,m=Math.round,a=typeof(c1)==&quot;string&quot;; if(typeof(p)!=&quot;number&quot;||p&lt;-1||p&gt;1||typeof(c0)!=&quot;string&quot;||(c0[0]!='r'&amp;&amp;c0[0]!='#')||(c1&amp;&amp;!a))return null; if(!this.pSBCr)this.pSBCr=(d)=&gt;{ let n=d.length,x={}; if(n&gt;9){ [r,g,b,a]=d=d.split(&quot;,&quot;),n=d.length; if(n&lt;3||n&gt;4)return null; x.r=i(r[3]==&quot;a&quot;?r.slice(5):r.slice(4)),x.g=i(g),x.b=i(b),x.a=a?parseFloat(a):-1 }else{ if(n==8||n==6||n&lt;4)return null; if(n&lt;6)d=&quot;#&quot;+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(n&gt;4?d[4]+d[4]:&quot;&quot;); d=i(d.slice(1),16); if(n==9||n==5)x.r=d&gt;&gt;24&amp;255,x.g=d&gt;&gt;16&amp;255,x.b=d&gt;&gt;8&amp;255,x.a=m((d&amp;255)/0.255)/1000; else x.r=d&gt;&gt;16,x.g=d&gt;&gt;8&amp;255,x.b=d&amp;255,x.a=-1 }return x}; h=c0.length&gt;9,h=a?c1.length&gt;9?true:c1==&quot;c&quot;?!h:false:h,f=this.pSBCr(c0),P=p&lt;0,t=c1&amp;&amp;c1!=&quot;c&quot;?this.pSBCr(c1):P?{r:0,g:0,b:0,a:-1}:{r:255,g:255,b:255,a:-1},p=P?p*-1:p,P=1-p; if(!f||!t)return null; if(l)r=m(P*f.r+p*t.r),g=m(P*f.g+p*t.g),b=m(P*f.b+p*t.b); else r=m((P*f.r**2+p*t.r**2)**0.5),g=m((P*f.g**2+p*t.g**2)**0.5),b=m((P*f.b**2+p*t.b**2)**0.5); a=f.a,t=t.a,f=a&gt;=0||t&gt;=0,a=f?a&lt;0?t:t&lt;0?a:a*P+t*p:0; if(h)return&quot;rgb&quot;+(f?&quot;a(&quot;:&quot;(&quot;)+r+&quot;,&quot;+g+&quot;,&quot;+b+(f?&quot;,&quot;+m(a*1000)/1000:&quot;&quot;)+&quot;)&quot;; else return&quot;#&quot;+(4294967296+r*16777216+g*65536+b*256+(f?m(a*255):0)).toString(16).slice(1,f?undefined:-2) } </code></pre> <h3>Usage:</h3> <pre class="lang-js prettyprint-override"><code>// Setup: let color1 = &quot;rgb(20,60,200)&quot;; let color2 = &quot;rgba(20,60,200,0.67423)&quot;; let color3 = &quot;#67DAF0&quot;; let color4 = &quot;#5567DAF0&quot;; let color5 = &quot;#F3A&quot;; let color6 = &quot;#F3A9&quot;; let color7 = &quot;rgb(200,60,20)&quot;; let color8 = &quot;rgba(200,60,20,0.98631)&quot;; // Tests: /*** Log Blending ***/ // Shade (Lighten or Darken) pSBC ( 0.42, color1 ); // rgb(20,60,200) + [42% Lighter] =&gt; rgb(166,171,225) pSBC ( -0.4, color5 ); // #F3A + [40% Darker] =&gt; #c62884 pSBC ( 0.42, color8 ); // rgba(200,60,20,0.98631) + [42% Lighter] =&gt; rgba(225,171,166,0.98631) // Shade with Conversion (use &quot;c&quot; as your &quot;to&quot; color) pSBC ( 0.42, color2, &quot;c&quot; ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] =&gt; #a6abe1ac // RGB2Hex &amp; Hex2RGB Conversion Only (set percentage to zero) pSBC ( 0, color6, &quot;c&quot; ); // #F3A9 + [Convert] =&gt; rgba(255,51,170,0.6) // Blending pSBC ( -0.5, color2, color8 ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] =&gt; rgba(142,60,142,0.83) pSBC ( 0.7, color2, color7 ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] =&gt; rgba(168,60,111,0.67423) pSBC ( 0.25, color3, color7 ); // #67DAF0 + rgb(200,60,20) + [25% Blend] =&gt; rgb(134,191,208) pSBC ( 0.75, color7, color3 ); // rgb(200,60,20) + #67DAF0 + [75% Blend] =&gt; #86bfd0 /*** Linear Blending ***/ // Shade (Lighten or Darken) pSBC ( 0.42, color1, false, true ); // rgb(20,60,200) + [42% Lighter] =&gt; rgb(119,142,223) pSBC ( -0.4, color5, false, true ); // #F3A + [40% Darker] =&gt; #991f66 pSBC ( 0.42, color8, false, true ); // rgba(200,60,20,0.98631) + [42% Lighter] =&gt; rgba(223,142,119,0.98631) // Shade with Conversion (use &quot;c&quot; as your &quot;to&quot; color) pSBC ( 0.42, color2, &quot;c&quot;, true ); // rgba(20,60,200,0.67423) + [42% Lighter] + [Convert] =&gt; #778edfac // RGB2Hex &amp; Hex2RGB Conversion Only (set percentage to zero) pSBC ( 0, color6, &quot;c&quot;, true ); // #F3A9 + [Convert] =&gt; rgba(255,51,170,0.6) // Blending pSBC ( -0.5, color2, color8, true ); // rgba(20,60,200,0.67423) + rgba(200,60,20,0.98631) + [50% Blend] =&gt; rgba(110,60,110,0.83) pSBC ( 0.7, color2, color7, true ); // rgba(20,60,200,0.67423) + rgb(200,60,20) + [70% Blend] =&gt; rgba(146,60,74,0.67423) pSBC ( 0.25, color3, color7, true ); // #67DAF0 + rgb(200,60,20) + [25% Blend] =&gt; rgb(127,179,185) pSBC ( 0.75, color7, color3, true ); // rgb(200,60,20) + #67DAF0 + [75% Blend] =&gt; #7fb3b9 /*** Other Stuff ***/ // Error Checking pSBC ( 0.42, &quot;#FFBAA&quot; ); // #FFBAA + [42% Lighter] =&gt; null  (Invalid Input Color) pSBC ( 42, color1, color5 ); // rgb(20,60,200) + #F3A + [4200% Blend] =&gt; null  (Invalid Percentage Range) pSBC ( 0.42, {} ); // [object Object] + [42% Lighter] =&gt; null  (Strings Only for Color) pSBC ( &quot;42&quot;, color1 ); // rgb(20,60,200) + [&quot;42&quot;] =&gt; null  (Numbers Only for Percentage) pSBC ( 0.42, &quot;salt&quot; ); // salt + [42% Lighter] =&gt; null  (A Little Salt is No Good...) // Error Check Fails (Some Errors are not Caught) pSBC ( 0.42, &quot;#salt&quot; ); // #salt + [42% Lighter] =&gt; #a5a5a500  (...and a Pound of Salt is Jibberish) // Ripping pSBCr ( color4 ); // #5567DAF0 + [Rip] =&gt; [object Object] =&gt; {'r':85,'g':103,'b':218,'a':0.941} </code></pre> <hr /> <p>The picture below will help show the difference in the two blending methods:</p> <p><img src="https://i.imgur.com/FBe90R8.png" alt="" /></p> <hr /> <h2>Micro Functions</h2> <p>If you really want speed and size, you will have to use RGB not HEX. RGB is more straightforward and simple, HEX writes too slow and comes in too many flavors for a simple two-liner (IE. it could be a 3, 4, 6, or 8 digit HEX code). You will also need to sacrifice some features, no error checking, no HEX2RGB nor RGB2HEX. As well, you will need to choose a specific function (based on its function name below) for the color blending math, and if you want shading or blending. These functions do support alpha channels. And when both input colors have alphas it will Linear Blend them. If only one of the two colors has an alpha, it will pass it straight thru to the resulting color. Below are two liner functions that are incredibly fast and small:</p> <pre class="lang-js prettyprint-override"><code>const RGB_Linear_Blend=(p,c0,c1)=&gt;{ var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(&quot;,&quot;),[e,f,g,h]=c1.split(&quot;,&quot;),x=d||h,j=x?&quot;,&quot;+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+&quot;)&quot;):&quot;)&quot;; return&quot;rgb&quot;+(x?&quot;a(&quot;:&quot;(&quot;)+r(i(a[3]==&quot;a&quot;?a.slice(5):a.slice(4))*P+i(e[3]==&quot;a&quot;?e.slice(5):e.slice(4))*p)+&quot;,&quot;+r(i(b)*P+i(f)*p)+&quot;,&quot;+r(i(c)*P+i(g)*p)+j; } const RGB_Linear_Shade=(p,c)=&gt;{ var i=parseInt,r=Math.round,[a,b,c,d]=c.split(&quot;,&quot;),P=p&lt;0,t=P?0:255*p,P=P?1+p:1-p; return&quot;rgb&quot;+(d?&quot;a(&quot;:&quot;(&quot;)+r(i(a[3]==&quot;a&quot;?a.slice(5):a.slice(4))*P+t)+&quot;,&quot;+r(i(b)*P+t)+&quot;,&quot;+r(i(c)*P+t)+(d?&quot;,&quot;+d:&quot;)&quot;); } const RGB_Log_Blend=(p,c0,c1)=&gt;{ var i=parseInt,r=Math.round,P=1-p,[a,b,c,d]=c0.split(&quot;,&quot;),[e,f,g,h]=c1.split(&quot;,&quot;),x=d||h,j=x?&quot;,&quot;+(!d?h:!h?d:r((parseFloat(d)*P+parseFloat(h)*p)*1000)/1000+&quot;)&quot;):&quot;)&quot;; return&quot;rgb&quot;+(x?&quot;a(&quot;:&quot;(&quot;)+r((P*i(a[3]==&quot;a&quot;?a.slice(5):a.slice(4))**2+p*i(e[3]==&quot;a&quot;?e.slice(5):e.slice(4))**2)**0.5)+&quot;,&quot;+r((P*i(b)**2+p*i(f)**2)**0.5)+&quot;,&quot;+r((P*i(c)**2+p*i(g)**2)**0.5)+j; } const RGB_Log_Shade=(p,c)=&gt;{ var i=parseInt,r=Math.round,[a,b,c,d]=c.split(&quot;,&quot;),P=p&lt;0,t=P?0:p*255**2,P=P?1+p:1-p; return&quot;rgb&quot;+(d?&quot;a(&quot;:&quot;(&quot;)+r((P*i(a[3]==&quot;a&quot;?a.slice(5):a.slice(4))**2+t)**0.5)+&quot;,&quot;+r((P*i(b)**2+t)**0.5)+&quot;,&quot;+r((P*i(c)**2+t)**0.5)+(d?&quot;,&quot;+d:&quot;)&quot;); } </code></pre> <hr /> <p>Want more info? Read the full writeup on <a href="https://github.com/PimpTrizkit/PJs/wiki/12.-Shade,-Blend-and-Convert-a-Web-Color-(pSBC.js)" rel="noreferrer">github</a>.</p> <p>PT</p> <p>(P.s. If anyone has the math for another blending method, please share.)</p>
{ "question_id": 5560248, "question_date": "2011-04-06T00:39:35.607Z", "question_score": 658, "tags": "javascript|colors|hex", "answer_id": 13542669, "answer_date": "2012-11-24T15:34:08.940Z", "answer_score": 1017 }
Please answer the following Stack Overflow question: Title: Correct way to try/except using Python requests module? <pre><code>try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print(e) </code></pre> <p>Is this correct? Is there a better way to structure this? Will this cover all my bases?</p>
<p>Have a look at the Requests <a href="https://requests.readthedocs.io/en/latest/user/quickstart/#errors-and-exceptions" rel="noreferrer">exception docs</a>. In short:</p> <blockquote> <p>In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a <strong><code>ConnectionError</code></strong> exception.</p> <p>In the event of the rare invalid HTTP response, Requests will raise an <strong><code>HTTPError</code></strong> exception.</p> <p>If a request times out, a <strong><code>Timeout</code></strong> exception is raised.</p> <p>If a request exceeds the configured number of maximum redirections, a <strong><code>TooManyRedirects</code></strong> exception is raised.</p> <p>All exceptions that Requests explicitly raises inherit from <strong><code>requests.exceptions.RequestException</code></strong>.</p> </blockquote> <p>To answer your question, what you show will <em>not</em> cover all of your bases. You'll only catch connection-related errors, not ones that time out.</p> <p>What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising <a href="https://docs.python.org/3/library/exceptions.html#SystemExit" rel="noreferrer">SystemExit</a> (a nice way to both print an error and call <code>sys.exit</code>).</p> <p>You can either catch the base-class exception, which will handle all cases:</p> <pre><code>try: r = requests.get(url, params={'s': thing}) except requests.exceptions.RequestException as e: # This is the correct syntax raise SystemExit(e) </code></pre> <p>Or you can catch them separately and do different things.</p> <pre><code>try: r = requests.get(url, params={'s': thing}) except requests.exceptions.Timeout: # Maybe set up for a retry, or continue in a retry loop except requests.exceptions.TooManyRedirects: # Tell the user their URL was bad and try a different one except requests.exceptions.RequestException as e: # catastrophic error. bail. raise SystemExit(e) </code></pre> <hr /> <p>As <a href="https://stackoverflow.com/users/456550/christian-long">Christian</a> pointed out:</p> <blockquote> <p>If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call <a href="https://requests.readthedocs.io/en/latest/api/#requests.Response.raise_for_status" rel="noreferrer"><code>Response.raise_for_status</code></a>. That will raise an <code>HTTPError</code>, if the response was an http error.</p> </blockquote> <p>An example:</p> <pre><code>try: r = requests.get('http://www.google.com/nothere') r.raise_for_status() except requests.exceptions.HTTPError as err: raise SystemExit(err) </code></pre> <p>Will print:</p> <pre class="lang-none prettyprint-override"><code>404 Client Error: Not Found for url: http://www.google.com/nothere </code></pre>
{ "question_id": 16511337, "question_date": "2013-05-12T19:44:44.203Z", "question_score": 657, "tags": "python|exception|python-requests|request", "answer_id": 16511493, "answer_date": "2013-05-12T20:00:33.430Z", "answer_score": 1203 }
Please answer the following Stack Overflow question: Title: What is the python keyword "with" used for? <p>What is the python keyword "with" used for?</p> <p>Example from: <a href="http://docs.python.org/tutorial/inputoutput.html" rel="noreferrer">http://docs.python.org/tutorial/inputoutput.html</a></p> <pre><code>&gt;&gt;&gt; with open('/tmp/workfile', 'r') as f: ... read_data = f.read() &gt;&gt;&gt; f.closed True </code></pre>
<p>In python the <code>with</code> keyword is used when working with unmanaged resources (like file streams). It is similar to the <code>using</code> statement in VB.NET and C#. It allows you to ensure that a resource is &quot;cleaned up&quot; when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for <code>try/finally</code> blocks.</p> <p>From <a href="http://docs.python.org/whatsnew/2.6.html#pep-343-the-with-statement" rel="noreferrer">Python Docs</a>:</p> <blockquote> <p>The <code>with</code> statement clarifies code that previously would use <code>try...finally</code> blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.</p> <p>The <code>with</code> statement is a control-flow structure whose basic structure is:</p> <pre><code>with expression [as variable]: with-block </code></pre> <p>The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has <code>__enter__()</code> and <code>__exit__()</code> methods).</p> </blockquote> <p><em>Update</em> fixed VB callout per Scott Wisniewski's comment. I was indeed confusing <code>with</code> with <code>using</code>.</p>
{ "question_id": 1369526, "question_date": "2009-09-02T18:57:51.017Z", "question_score": 657, "tags": "python", "answer_id": 1369553, "answer_date": "2009-09-02T19:05:11.033Z", "answer_score": 594 }
Please answer the following Stack Overflow question: Title: Invoking JavaScript code in an iframe from the parent page <p>Basically, I have an <code>iframe</code> embedded in a page and the <code>iframe</code> has some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> routines I need to invoke from the parent page.</p> <p>Now the opposite is quite simple as you only need to call <code>parent.functionName()</code>, but unfortunately, I need exactly the opposite of that.</p> <p>Please note that my problem is not changing the source <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URL</a> of the <code>iframe</code>, but invoking a function defined in the <code>iframe</code>.</p>
<p>Assume your iFrame's id is "targetFrame" and the function you want to call is <code>targetFunction()</code>:</p> <pre><code>document.getElementById('targetFrame').contentWindow.targetFunction(); </code></pre> <p>You can also access the frame using <code>window.frames</code> instead of <code>document.getElementById</code>.</p> <pre><code>// this option does not work in most of latest versions of chrome and Firefox window.frames[0].frameElement.contentWindow.targetFunction(); </code></pre>
{ "question_id": 251420, "question_date": "2008-10-30T19:27:56.177Z", "question_score": 657, "tags": "javascript|html|iframe", "answer_id": 251453, "answer_date": "2008-10-30T19:35:41.400Z", "answer_score": 588 }
Please answer the following Stack Overflow question: Title: How to ignore a property in class if null, using json.net <p>I am using <a href="http://www.newtonsoft.com/json" rel="noreferrer">Json.NET</a> to serialize a class to JSON.</p> <p>I have the class like this:</p> <pre><code>class Test1 { [JsonProperty("id")] public string ID { get; set; } [JsonProperty("label")] public string Label { get; set; } [JsonProperty("url")] public string URL { get; set; } [JsonProperty("item")] public List&lt;Test2&gt; Test2List { get; set; } } </code></pre> <p>I want to add a <code>JsonIgnore()</code> attribute to <code>Test2List</code> property only when <code>Test2List</code> is <code>null</code>. If it is not null then I want to include it in my json.</p>
<p>As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a <a href="http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_NullValueHandling.htm" rel="noreferrer"><code>NullValueHandling</code> property</a> which you can set to ignore.</p> <p>Here's a sample:</p> <pre><code>JsonSerializer _jsonWriter = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore }; </code></pre> <hr> <p>Alternatively, as suggested by @amit</p> <pre><code>JsonConvert.SerializeObject(myObject, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); </code></pre>
{ "question_id": 6507889, "question_date": "2011-06-28T14:14:55.380Z", "question_score": 657, "tags": "c#|json.net", "answer_id": 6507965, "answer_date": "2011-06-28T14:20:27.103Z", "answer_score": 822 }
Please answer the following Stack Overflow question: Title: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on <p>I have a scenario. (Windows Forms, C#, .NET)</p> <ol> <li>There is a main form which hosts some user control.</li> <li>The user control does some heavy data operation, such that if I directly call the <code>UserControl_Load</code> method the UI become nonresponsive for the duration for load method execution.</li> <li>To overcome this I load data on different thread (trying to change existing code as little as I can)</li> <li>I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.</li> <li>Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.</li> </ol> <p>The pseudocode would look like this:</p> <p><strong>CODE 1</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (textbox1.text == &quot;MyName&quot;) // This gives exception { //Load data corresponding to &quot;MyName&quot;. //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage. } } </code></pre> <p>The Exception it gave was</p> <blockquote> <p>Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.</p> </blockquote> <p>To know more about this I did some googling and a suggestion came up like using the following code</p> <p><strong>CODE 2</strong></p> <pre><code>UserContrl1_LoadDataMethod() { if (InvokeRequired) // Line #1 { this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod)); return; } if (textbox1.text == &quot;MyName&quot;) // Now it won't give an exception { //Load data correspondin to &quot;MyName&quot; //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage } } </code></pre> <p>But it still seems that I've come back to square one. The Application again becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.</p> <p>I don't know whether I perceived this right or wrong. I'm new to threading.</p> <p>How do I resolve this and also what is the effect of execution of Line#1 if block?</p> <p><strong>The situation is this</strong>: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p> <p>So only accessing the value so that the corresponding data can be fetched from the database.</p>
<p>As per <a href="https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108">Prerak K's update comment</a> (since deleted):</p> <blockquote> <p>I guess I have not presented the question properly.</p> <p>Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p> <p>So only accessing the value so that corresponding data can be fetched from the database.</p> </blockquote> <p>The solution you want then should look like:</p> <pre><code>UserContrl1_LOadDataMethod() { string name = &quot;&quot;; if(textbox1.InvokeRequired) { textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; })); } if(name == &quot;MyName&quot;) { // do whatever } } </code></pre> <p>Do your serious processing in the separate thread <em>before</em> you attempt to switch back to the control's thread. For example:</p> <pre><code>UserContrl1_LOadDataMethod() { if(textbox1.text==&quot;MyName&quot;) //&lt;&lt;======Now it wont give exception** { //Load data correspondin to &quot;MyName&quot; //Populate a globale variable List&lt;string&gt; which will be //bound to grid at some later stage if(InvokeRequired) { // after we've done all the processing, this.Invoke(new MethodInvoker(delegate { // load the control with the appropriate data })); return; } } } </code></pre>
{ "question_id": 142003, "question_date": "2008-09-26T21:12:41.917Z", "question_score": 657, "tags": "c#|multithreading|winforms|invoke", "answer_id": 142069, "answer_date": "2008-09-26T21:22:30.303Z", "answer_score": 473 }
Please answer the following Stack Overflow question: Title: What does on_delete do on Django models? <p>I'm quite familiar with Django, but I recently noticed there exists an <code>on_delete=models.CASCADE</code> option with the models. I have searched for the documentation for the same, but I couldn't find anything more than:</p> <blockquote> <p><strong>Changed in Django 1.9:</strong></p> <p><code>on_delete</code> can now be used as the second positional argument (previously it was typically only passed as a keyword argument). It will be a required argument in Django 2.0.</p> </blockquote> <p><a href="https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.ForeignKey" rel="noreferrer">An example case of usage is</a>:</p> <pre><code>from django.db import models class Car(models.Model): manufacturer = models.ForeignKey( 'Manufacturer', on_delete=models.CASCADE, ) # ... class Manufacturer(models.Model): # ... pass </code></pre> <p>What does on_delete do? (<em>I guess the actions to be done if the model is deleted</em>.)</p> <p>What does <code>models.CASCADE</code> do? (<em>any hints in documentation</em>)</p> <p>What other options are available (<em>if my guess is correct</em>)?</p> <p>Where does the documentation for this reside?</p>
<p>This is the behaviour to adopt when the <em>referenced</em> object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. <strong>(1)</strong></p> <p>There are seven possible actions to take when such event occurs:</p> <ul> <li><code>CASCADE</code>: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: <code>CASCADE</code>.</li> <li><code>PROTECT</code>: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: <code>RESTRICT</code>.</li> <li><code>RESTRICT</code>: <em>(introduced in Django 3.1)</em> Similar behavior as <code>PROTECT</code> that matches SQL's <code>RESTRICT</code> more accurately. (See <a href="https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.RESTRICT" rel="noreferrer">django documentation example</a>)</li> <li><code>SET_NULL</code>: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: <code>SET NULL</code>.</li> <li><code>SET_DEFAULT</code>: Set the default value. SQL equivalent: <code>SET DEFAULT</code>.</li> <li><code>SET(...)</code>: Set a given value. This one is not part of the SQL standard and is entirely handled by Django.</li> <li><code>DO_NOTHING</code>: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: <code>NO ACTION</code>. <strong>(2)</strong></li> </ul> <p>Source: <a href="https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.ForeignKey.on_delete" rel="noreferrer">Django documentation</a></p> <p>See also <a href="https://www.postgresql.org/docs/current/static/sql-createtable.html" rel="noreferrer">the documentation of PostgreSQL</a> for instance.</p> <p>In most cases, <code>CASCADE</code> is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. <code>PROTECT</code> and <code>SET_NULL</code> are often useful. Setting <code>CASCADE</code> where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.</p> <hr /> <p><strong>Additional note to clarify cascade direction</strong></p> <p>It's funny to notice that the direction of the <code>CASCADE</code> action is not clear to many people. Actually, it's funny to notice that <strong>only</strong> the <code>CASCADE</code> action is not clear. I understand the cascade behavior might be confusing, however you must think that <strong>it is the same direction as any other action</strong>. Thus, if you feel that <code>CASCADE</code> direction is not clear to you, it actually means that <code>on_delete</code> behavior is not clear to you.</p> <p>In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry <strong>comment_A</strong>, which has a foreign key to an entry <strong>article_B</strong>. If you delete the entry <strong>comment_A</strong>, everything is fine. <strong>article_B</strong> used to live without <strong>comment_A</strong> and don't bother if it's deleted. However, if you delete <strong>article_B</strong>, then <strong>comment_A</strong> panics! It never lived without <strong>article_B</strong> and needs it, and it's part of its attributes (<code>article=article_B</code>, but what is <strong>article_B</strong>???). This is where <code>on_delete</code> steps in, to determine how to resolve this <em>integrity error</em>, either by saying:</p> <ul> <li><em>&quot;No! Please! Don't! I can't live without you!&quot;</em> (which is said <code>PROTECT</code> or <code>RESTRICT</code> in Django/SQL)</li> <li><em>&quot;All right, if I'm not yours, then I'm nobody's&quot;</em> (which is said <code>SET_NULL</code>)</li> <li><em>&quot;Good bye world, I can't live without article_B&quot;</em> and commit suicide (this is the <code>CASCADE</code> behavior).</li> <li><em>&quot;It's OK, I've got spare lover, and I'll reference article_C from now&quot;</em> (<code>SET_DEFAULT</code>, or even <code>SET(...)</code>).</li> <li><em>&quot;I can't face reality, and I'll keep calling your name even if that's the only thing left to me!&quot;</em> (<code>DO_NOTHING</code>)</li> </ul> <p>I hope it makes cascade direction clearer. :)</p> <hr /> <p><strong>Footnotes</strong></p> <blockquote> <p><strong>(1)</strong> Django has its own implementation on top of SQL. And, as <a href="https://stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models/38389488#comment107117244_38389488">mentioned by @JoeMjr2 in the comments below</a>, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is <a href="https://code.djangoproject.com/ticket/21961" rel="noreferrer">an open ticket</a> to add support for database-level on delete constrains in Django.</p> </blockquote> <blockquote> <p><strong>(2)</strong> Actually, there is one case where <code>DO_NOTHING</code> can be useful: If you want to skip Django's implementation and implement the constraint yourself at the database-level.</p> </blockquote>
{ "question_id": 38388423, "question_date": "2016-07-15T05:26:57.277Z", "question_score": 657, "tags": "django|django-models", "answer_id": 38389488, "answer_date": "2016-07-15T06:44:00.273Z", "answer_score": 1494 }
Please answer the following Stack Overflow question: Title: Func delegate with no return type <p>All of the Func delegates return a value. What are the .NET delegates that can be used with methods that return void?</p>
<p>All Func delegates return something; all the Action delegates return void.</p> <p><code>Func&lt;TResult&gt;</code> takes no arguments and returns TResult:</p> <pre><code>public delegate TResult Func&lt;TResult&gt;() </code></pre> <p><code>Action&lt;T&gt;</code> takes one argument and does not return a value:</p> <pre><code>public delegate void Action&lt;T&gt;(T obj) </code></pre> <p><code>Action</code> is the simplest, 'bare' delegate:</p> <pre><code>public delegate void Action() </code></pre> <p>There's also <code>Func&lt;TArg1, TResult&gt;</code> and <code>Action&lt;TArg1, TArg2&gt;</code> (and others up to 16 arguments). All of these (except for <code>Action&lt;T&gt;</code>) are new to .NET 3.5 (defined in System.Core).</p>
{ "question_id": 917551, "question_date": "2009-05-27T19:21:42.033Z", "question_score": 657, "tags": "c#|.net", "answer_id": 917572, "answer_date": "2009-05-27T19:24:54.337Z", "answer_score": 876 }
Please answer the following Stack Overflow question: Title: Difference between DOM parentNode and parentElement <p>Can somebody explain in simple terms, what is the difference between classical DOM <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode" rel="noreferrer">parentNode</a> and newly introduced in Firefox 9 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement" rel="noreferrer">parentElement</a></p>
<p><code>parentElement</code> is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.</p> <p>In most cases, it is the same as <code>parentNode</code>. The only difference comes when a node's <code>parentNode</code> is not an element. If so, <code>parentElement</code> is <code>null</code>.</p> <p>As an example:</p> <pre><code>document.body.parentNode; // the &lt;html&gt; element document.body.parentElement; // the &lt;html&gt; element document.documentElement.parentNode; // the document node document.documentElement.parentElement; // null (document.documentElement.parentNode === document); // true (document.documentElement.parentElement === document); // false </code></pre> <p>Since the <code>&lt;html&gt;</code> element (<code>document.documentElement</code>) doesn't have a parent that is an element, <code>parentElement</code> is <code>null</code>. (There are other, more unlikely, cases where <code>parentElement</code> could be <code>null</code>, but you'll probably never come across them.)</p>
{ "question_id": 8685739, "question_date": "2011-12-31T01:50:09.500Z", "question_score": 657, "tags": "javascript|firefox|dom", "answer_id": 8685780, "answer_date": "2011-12-31T01:58:33.913Z", "answer_score": 646 }
Please answer the following Stack Overflow question: Title: Send POST data using XMLHttpRequest <p>I'd like to send some data using an XMLHttpRequest in JavaScript.</p> <p>Say I have the following form in HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;form name=&quot;inputform&quot; action=&quot;somewhere&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;hidden&quot; value=&quot;person&quot; name=&quot;user&quot;&gt; &lt;input type=&quot;hidden&quot; value=&quot;password&quot; name=&quot;pwd&quot;&gt; &lt;input type=&quot;hidden&quot; value=&quot;place&quot; name=&quot;organization&quot;&gt; &lt;input type=&quot;hidden&quot; value=&quot;key&quot; name=&quot;requiredkey&quot;&gt; &lt;/form&gt; </code></pre> <p>How can I write the equivalent using an XMLHttpRequest in JavaScript?</p>
<p>The code below demonstrates on how to do this.</p> <pre><code>var http = new XMLHttpRequest(); var url = 'get_data.php'; var params = 'orem=ipsum&amp;name=binny'; http.open('POST', url, true); //Send the proper header information along with the request http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 &amp;&amp; http.status == 200) { alert(http.responseText); } } http.send(params); </code></pre> <p>In case you have/create an object you can turn it into params using the following code, i.e:</p> <pre><code>var params = new Object(); params.myparam1 = myval1; params.myparam2 = myval2; // Turn the data object into an array of URL-encoded key/value pairs. let urlEncodedData = &quot;&quot;, urlEncodedDataPairs = [], name; for( name in params ) { urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name])); } </code></pre>
{ "question_id": 9713058, "question_date": "2012-03-15T02:09:33.250Z", "question_score": 656, "tags": "javascript|ajax|forms|post|xmlhttprequest", "answer_id": 9713078, "answer_date": "2012-03-15T02:12:04.333Z", "answer_score": 924 }
Please answer the following Stack Overflow question: Title: How to insert a line break in a SQL Server VARCHAR/NVARCHAR string <p>I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.</p>
<p>I found the answer here: <a href="http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/" rel="noreferrer">http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/</a></p> <p>You just concatenate the string and insert a <code>CHAR(13)</code> where you want your line break. </p> <p>Example:</p> <pre><code>DECLARE @text NVARCHAR(100) SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.' SELECT @text </code></pre> <p>This prints out the following:</p> <blockquote> <p>This is line 1.<br> This is line 2.</p> </blockquote>
{ "question_id": 31057, "question_date": "2008-08-27T19:53:01.303Z", "question_score": 656, "tags": "sql|sql-server|line-breaks", "answer_id": 31063, "answer_date": "2008-08-27T19:55:42.467Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: The request was aborted: Could not create SSL/TLS secure channel <p>We are unable to connect to an HTTPS server using <code>WebRequest</code> because of this error message:</p> <p><code>The request was aborted: Could not create SSL/TLS secure channel.</code></p> <p>We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:</p> <pre><code>private void Somewhere() { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate); } private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; } </code></pre> <p>The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?</p> <hr /> <p>I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only &quot;major difference&quot; we've found is that I'm using Windows 7 and he was using Windows XP. Does that change something?</p>
<p>I finally found the answer (I haven't noted my source but it was from a search); </p> <p>While the code works in Windows XP, in Windows 7, you must add this at the beginning:</p> <pre><code>// using System.Net; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Use SecurityProtocolType.Ssl3 if needed for compatibility reasons </code></pre> <p>And now, it works perfectly.</p> <hr> <p><strong>ADDENDUM</strong></p> <p>As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's <a href="https://www.paypal.com/uk/webapps/mpp/ssl-security-update" rel="noreferrer">Paypal page</a> about it.</p>
{ "question_id": 2859790, "question_date": "2010-05-18T18:07:03.770Z", "question_score": 656, "tags": "c#|asp.net|windows-8|windows-7|httpwebrequest", "answer_id": 2904963, "answer_date": "2010-05-25T13:18:27.920Z", "answer_score": 822 }
Please answer the following Stack Overflow question: Title: Is it possible to break a long line to multiple lines in Python? <p>Just like C, you can break a long line into multiple short lines. But in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>, if I do this, there will be an indent error... Is it possible?</p>
<p>From <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8 - Style Guide for Python Code</a>:</p> <blockquote> <p>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.</p> </blockquote> <p>Example of implicit line continuation:</p> <pre><code>a = some_function( '1' + '2' + '3' - '4') </code></pre> <p>On the topic of line breaks around a binary operator, it goes on to say:</p> <blockquote> <p>For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.</p> </blockquote> <blockquote> <p>In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks <em>before</em> the operator) is suggested.</p> </blockquote> <p>Example of explicit line continuation:</p> <pre><code>a = '1' \ + '2' \ + '3' \ - '4' </code></pre>
{ "question_id": 4172448, "question_date": "2010-11-13T12:17:04.593Z", "question_score": 656, "tags": "python|line-breaks", "answer_id": 4172465, "answer_date": "2010-11-13T12:20:00.190Z", "answer_score": 737 }
Please answer the following Stack Overflow question: Title: How do I create a branch? <p>How do I create a branch in SVN?</p>
<p>Branching in Subversion is facilitated by a very very light and efficient copying facility.</p> <p>Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the <code>svn copy</code> command.</p> <p>Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style.</p> <p>Common styles are to have a bunch of folders at the top of your repository called <code>tags</code>, <code>branches</code>, <code>trunk</code>, etc. - that allows you to copy your whole <code>trunk</code> (or sub-sets) into the <code>tags</code> and/or <code>branches</code> folders. If you have more than one project you might want to replicate this kind of structure under each project:</p> <p>It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete.</p>
{ "question_id": 2041, "question_date": "2008-08-05T09:25:29Z", "question_score": 656, "tags": "svn|version-control|branch|branching-and-merging", "answer_id": 2310, "answer_date": "2008-08-05T13:40:20.777Z", "answer_score": 372 }