input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Axios - DELETE Request With Request Body and Headers? <p>I'm using Axios while programing in ReactJS and I pretend to send a DELETE request to my server.</p> <p>To do so I need the headers:</p> <pre><code>headers: { 'Authorization': ... } </code></pre> <p>and the body is composed of</p> <pre><code>var payload = { "username": .. } </code></pre> <p>I've been searching in the inter webs and only found that the DELETE method requires a "param" and accepts no "data".</p> <p>I've been trying to send it like so:</p> <pre><code>axios.delete(URL, payload, header); </code></pre> <p>or even</p> <pre><code>axios.delete(URL, {params: payload}, header); </code></pre> <p>But nothing seems to work...</p> <p>Can someone tell me if its possible (I presume it is) to send a DELETE request with both headers and body and how to do so ?</p> <p>Thank you in advance!</p>
<p>So after a number of tries, I found it working.</p> <p><strong>Please follow the order sequence</strong> it's very important else it won't work</p> <pre><code>axios.delete(URL, { headers: { Authorization: authorizationToken }, data: { source: source } }); </code></pre>
{ "question_id": 51069552, "question_date": "2018-06-27T18:45:47.293Z", "question_score": 232, "tags": "javascript|reactjs|http|axios|http-delete", "answer_id": 56210828, "answer_date": "2019-05-19T18:32:09.527Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: Unzip a file with php <p>I want to unzip a file and this works fine</p> <pre><code>system('unzip File.zip'); </code></pre> <p>But I need to pass in the file name through the URL and can not get it to work, this is what I have. </p> <pre><code>$master = $_GET["master"]; system('unzip $master.zip'); </code></pre> <p>What am I missing? I know it has to be something small and stupid I am overlooking.</p> <p>Thank you, </p>
<p>I can only assume your code came from a tutorial somewhere online? In that case, good job trying to figure it out by yourself. On the other hand, the fact that this code could actually be published online somewhere as the correct way to unzip a file is a bit frightening.</p> <p>PHP has built-in extensions for dealing with compressed files. There should be no need to use <code>system</code> calls for this. <code>ZipArchive</code><a href="http://php.net/manual/en/class.ziparchive.php"><sup><em>docs</em></sup></a> is one option.</p> <pre><code>$zip = new ZipArchive; $res = $zip-&gt;open('file.zip'); if ($res === TRUE) { $zip-&gt;extractTo('/myzips/extract_path/'); $zip-&gt;close(); echo 'woot!'; } else { echo 'doh!'; } </code></pre> <p>Also, as others have commented, <code>$HTTP_GET_VARS</code> has been deprecated since version 4.1 ... which was a reeeeeally long time ago. Don't use it. Use the <code>$_GET</code> superglobal instead.</p> <p>Finally, be very careful about accepting whatever input is passed to a script via a <code>$_GET</code> variable.</p> <h1>ALWAYS SANITIZE USER INPUT.</h1> <hr> <p><strong>UPDATE</strong></p> <p>As per your comment, the best way to extract the zip file into the same directory in which it resides is to determine the hard path to the file and extract it specifically to that location. So, you could do:</p> <pre><code>// assuming file.zip is in the same directory as the executing script. $file = 'file.zip'; // get the absolute path to $file $path = pathinfo(realpath($file), PATHINFO_DIRNAME); $zip = new ZipArchive; $res = $zip-&gt;open($file); if ($res === TRUE) { // extract it to the path we determined above $zip-&gt;extractTo($path); $zip-&gt;close(); echo "WOOT! $file extracted to $path"; } else { echo "Doh! I couldn't open $file"; } </code></pre>
{ "question_id": 8889025, "question_date": "2012-01-17T02:38:31.627Z", "question_score": 232, "tags": "php|unzip", "answer_id": 8889126, "answer_date": "2012-01-17T02:54:05.973Z", "answer_score": 571 }
Please answer the following Stack Overflow question: Title: How to convert a JSON string to a Map<String, String> with Jackson JSON <p>I'm trying to do something like this but it doesn't work:</p> <pre><code>Map&lt;String, String&gt; propertyMap = new HashMap&lt;String, String&gt;(); propertyMap = JacksonUtils.fromJSON(properties, Map.class); </code></pre> <p>But the IDE says: </p> <blockquote> <p>Unchecked assignment <code>Map to Map&lt;String,String&gt;</code></p> </blockquote> <p>What's the right way to do this? I'm only using Jackson because that's what is already available in the project, is there a native Java way of converting to/from JSON?</p> <p>In PHP I would simply <code>json_decode($str)</code> and I'd get back an array. I need basically the same thing here.</p>
<p><em>[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.</em></p> <p>I've got the following code:</p> <pre><code>public void testJackson() throws IOException { ObjectMapper mapper = new ObjectMapper(); File from = new File(&quot;albumnList.txt&quot;); TypeReference&lt;HashMap&lt;String,Object&gt;&gt; typeRef = new TypeReference&lt;HashMap&lt;String,Object&gt;&gt;() {}; HashMap&lt;String,Object&gt; o = mapper.readValue(from, typeRef); System.out.println(&quot;Got &quot; + o); } </code></pre> <p>It's reading from a file, but <code>mapper.readValue()</code> will also accept an <code>InputStream</code> and you can obtain an <code>InputStream</code> from a string by using the following:</p> <pre><code>new ByteArrayInputStream(astring.getBytes(&quot;UTF-8&quot;)); </code></pre> <p>There's a bit more explanation about the mapper on <a href="http://djna.wordpress.com/2010/03/12/json-strings-no-rest-using-the-jackson-parser/" rel="noreferrer">my blog</a>.</p>
{ "question_id": 2525042, "question_date": "2010-03-26T16:46:42.083Z", "question_score": 232, "tags": "java|jackson", "answer_id": 2525152, "answer_date": "2010-03-26T17:04:41.980Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: Format Float to n decimal places <p>I need to format a float to "n"decimal places.</p> <p>was trying to BigDecimal, but the return value is not correct...</p> <pre><code>public static float Redondear(float pNumero, int pCantidadDecimales) { // the function is call with the values Redondear(625.3f, 2) BigDecimal value = new BigDecimal(pNumero); value = value.setScale(pCantidadDecimales, RoundingMode.HALF_EVEN); // here the value is correct (625.30) return value.floatValue(); // but here the values is 625.3 } </code></pre> <p>I need to return a float value with the number of decimal places that I specify.</p> <p>I need <code>Float</code> value return not <code>Double</code></p> <p>.</p>
<p>You may also pass the float value, and use:</p> <p><code>String.format("%.2f", floatValue);</code></p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html" rel="noreferrer">Documentation</a></p>
{ "question_id": 5195837, "question_date": "2011-03-04T15:36:06.170Z", "question_score": 232, "tags": "java|android|floating-point|numbers|format", "answer_id": 5383201, "answer_date": "2011-03-21T20:24:37.997Z", "answer_score": 582 }
Please answer the following Stack Overflow question: Title: How do I convert Word files to PDF programmatically? <p>I have found several open-source/freeware programs that allow you to convert .doc files to .pdf files, but they're all of the application/printer driver variety, with no SDK attached.</p> <p>I have found several programs that do have an SDK allowing you to convert .doc files to .pdf files, but they're all of the proprietary type, $2,000 a license or thereabouts.</p> <p>Does anyone know of any clean, inexpensive (preferably free) programmatic solution to my problem, using C# or VB.NET?</p> <p>Thanks!</p>
<p>Use a foreach loop instead of a for loop - it solved my problem.</p> <pre><code>int j = 0; foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages) { var bits = p.EnhMetaFileBits; var target = path1 +j.ToString()+ "_image.doc"; try { using (var ms = new MemoryStream((byte[])(bits))) { var image = System.Drawing.Image.FromStream(ms); var pngTarget = Path.ChangeExtension(target, "png"); image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } j++; } </code></pre> <p>Here is a modification of a program that worked for me. It uses Word 2007 with the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4d951911-3e7e-4ae6-b059-a2e79ed87041&amp;displaylang=en" rel="noreferrer">Save As PDF add-in</a> installed. It searches a directory for .doc files, opens them in Word and then saves them as a PDF. Note that you'll need to add a reference to Microsoft.Office.Interop.Word to the solution.</p> <pre><code>using Microsoft.Office.Interop.Word; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; ... // Create a new Microsoft Word application object Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value; // Get list of Word files in specified directory DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder"); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { // Cast as Object for word Open method Object filename = (Object)wordFile.FullName; // Use the dummy value as a placeholder for optional arguments Document doc = word.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF Format doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; </code></pre>
{ "question_id": 607669, "question_date": "2009-03-03T19:03:26.363Z", "question_score": 232, "tags": "c#|vb.net|pdf|ms-word", "answer_id": 608153, "answer_date": "2009-03-03T20:58:44.043Z", "answer_score": 210 }
Please answer the following Stack Overflow question: Title: Render Partial View Using jQuery in ASP.NET MVC <p>How do I render the partial view using jquery?</p> <p>We can render the partial View like this:</p> <pre><code>&lt;% Html.RenderPartial("UserDetails"); %&gt; </code></pre> <p>How can we do the same using jquery?</p>
<p>I have used ajax load to do this:</p> <pre><code>$('#user_content').load('@Url.Action("UserDetails","User")'); </code></pre>
{ "question_id": 1570127, "question_date": "2009-10-15T03:22:45.133Z", "question_score": 232, "tags": "javascript|jquery|asp.net-mvc|renderpartial", "answer_id": 1721623, "answer_date": "2009-11-12T11:37:08.197Z", "answer_score": 160 }
Please answer the following Stack Overflow question: Title: Convert String to Uri <p>How can I convert a String to a Uri in Java (Android)? i.e.:</p> <pre><code>String myUrl = "http://stackoverflow.com"; </code></pre> <p><strong>myUri = ???;</strong></p>
<p>You can use the <code>parse</code> static method from <code>Uri</code></p> <pre><code>//... import android.net.Uri; //... Uri myUri = Uri.parse(&quot;http://stackoverflow.com&quot;) </code></pre>
{ "question_id": 3487389, "question_date": "2010-08-15T12:42:32.640Z", "question_score": 232, "tags": "java|android|string|uri", "answer_id": 3487413, "answer_date": "2010-08-15T12:48:57.687Z", "answer_score": 550 }
Please answer the following Stack Overflow question: Title: Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe"" <p>Searching the net this seems to be a problem caused by spaces in the Python installation path.</p> <p>How do I get <code>pip</code> to work without having to reinstall everything in a path without spaces ?</p>
<p>it seems that</p> <pre><code>python -m pip install XXX </code></pre> <p>will work anyway (worked for me) (see <a href="https://stackoverflow.com/a/25812942/3368958">link by user474491</a>)</p>
{ "question_id": 24627525, "question_date": "2014-07-08T08:51:55.587Z", "question_score": 232, "tags": "python|pip", "answer_id": 26428562, "answer_date": "2014-10-17T15:37:09.010Z", "answer_score": 482 }
Please answer the following Stack Overflow question: Title: Multiple modals overlay <p>I need that the overlay shows above the first modal, not in the back.</p> <p><a href="https://i.stack.imgur.com/LqXsY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LqXsY.png" alt="Modal overlay behind"></a></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#openBtn').click(function(){ $('#myModal').modal({show:true}) });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a data-toggle="modal" href="#myModal" class="btn btn-primary"&gt;Launch modal&lt;/a&gt; &lt;div class="modal" id="myModal"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt; &lt;h4 class="modal-title"&gt;Modal title&lt;/h4&gt; &lt;/div&gt;&lt;div class="container"&gt;&lt;/div&gt; &lt;div class="modal-body"&gt; Content for the dialog / modal goes here. &lt;br&gt; &lt;br&gt; &lt;br&gt; &lt;br&gt; &lt;br&gt; &lt;a data-toggle="modal" href="#myModal2" class="btn btn-primary"&gt;Launch modal&lt;/a&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;a href="#" data-dismiss="modal" class="btn"&gt;Close&lt;/a&gt; &lt;a href="#" class="btn btn-primary"&gt;Save changes&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal" id="myModal2" data-backdrop="static"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt; &lt;h4 class="modal-title"&gt;Second Modal title&lt;/h4&gt; &lt;/div&gt;&lt;div class="container"&gt;&lt;/div&gt; &lt;div class="modal-body"&gt; Content for the dialog / modal goes here. &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;a href="#" data-dismiss="modal" class="btn"&gt;Close&lt;/a&gt; &lt;a href="#" class="btn btn-primary"&gt;Save changes&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" /&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>I tried to change the <code>z-index</code> of <code>.modal-backdrop</code>, but it becomes a mess.</p> <p>In some cases I have more than two modals on the same page. </p>
<p><em>Solution inspired by the answers of @YermoLamers &amp; @Ketwaroo.</em></p> <p><strong>Backdrop z-index fix</strong><br /> This solution uses a <code>setTimeout</code> because the <code>.modal-backdrop</code> isn't created when the event <code>show.bs.modal</code> is triggered.</p> <pre><code>$(document).on('show.bs.modal', '.modal', function() { const zIndex = 1040 + 10 * $('.modal:visible').length; $(this).css('z-index', zIndex); setTimeout(() =&gt; $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack')); }); </code></pre> <ul> <li>This works for every <code>.modal</code> created on the page (even dynamic modals)</li> <li>The backdrop instantly overlays the previous modal</li> </ul> <h2><a href="http://jsfiddle.net/thnex9ad/" rel="noreferrer">Example jsfiddle</a></h2> <p><strong>z-index</strong><br /> If you don't like the hardcoded z-index for any reason you can calculate the highest z-index on the page like this:</p> <pre><code>const zIndex = 10 + Math.max(...Array.from(document.querySelectorAll('*')).map((el) =&gt; +el.style.zIndex)); </code></pre> <p><strong>Scrollbar fix</strong><br /> If you have a modal on your page that exceeds the browser height, then you can't scroll in it when closing an second modal. To fix this add:</p> <pre><code>$(document).on('hidden.bs.modal', '.modal', () =&gt; $('.modal:visible').length &amp;&amp; $(document.body).addClass('modal-open')); </code></pre> <p><strong>Versions</strong><br /> This solution is tested with bootstrap 3.1.0 - 3.3.5</p>
{ "question_id": 19305821, "question_date": "2013-10-10T20:41:39.227Z", "question_score": 232, "tags": "javascript|jquery|twitter-bootstrap|twitter-bootstrap-3|modal-dialog", "answer_id": 24914782, "answer_date": "2014-07-23T15:31:55.957Z", "answer_score": 535 }
Please answer the following Stack Overflow question: Title: How to convert a JSON string to a dictionary? <p>I want to make one function in my swift project that converts String to Dictionary json format but I got one error:</p> <blockquote> <p>Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...</p> </blockquote> <p>This is my code:</p> <pre><code>func convertStringToDictionary (text:String) -&gt; Dictionary&lt;String,String&gt; { var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)! var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil) return json } </code></pre> <p>I make this function in Objective-C :</p> <pre><code>- (NSDictionary*)convertStringToDictionary:(NSString*)string { NSError* error; //giving error as it takes dic, array,etc only. not custom object. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&amp;error]; return json; } </code></pre>
<p><em>Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON <strong>data</strong> available, you should instead <a href="https://stackoverflow.com/a/40438849/2227743">work with the data</a>, without using a string at all.</em></p> <p><strong>Swift 3</strong></p> <pre><code>func convertToDictionary(text: String) -&gt; [String: Any]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print(error.localizedDescription) } } return nil } let str = "{\"name\":\"James\"}" let dict = convertToDictionary(text: str) </code></pre> <p><strong>Swift 2</strong></p> <pre><code>func convertStringToDictionary(text: String) -&gt; [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] } catch let error as NSError { print(error) } } return nil } let str = "{\"name\":\"James\"}" let result = convertStringToDictionary(str) </code></pre> <p><strong>Original Swift 1 answer:</strong></p> <pre><code>func convertStringToDictionary(text: String) -&gt; [String:String]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { var error: NSError? let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &amp;error) as? [String:String] if error != nil { println(error) } return json } return nil } let str = "{\"name\":\"James\"}" let result = convertStringToDictionary(str) // ["name": "James"] if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional println(name) // "James" } </code></pre> <p>In your version, you didn't pass the proper parameters to <code>NSJSONSerialization</code> and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:</p> <pre><code>let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &amp;error) as? [String:AnyObject] </code></pre> <p>and of course you would also need to change the return type of the function:</p> <pre><code>func convertStringToDictionary(text: String) -&gt; [String:AnyObject]? { ... } </code></pre>
{ "question_id": 30480672, "question_date": "2015-05-27T11:05:33.387Z", "question_score": 232, "tags": "json|swift|dictionary|nsjsonserialization", "answer_id": 30480777, "answer_date": "2015-05-27T11:11:11.327Z", "answer_score": 454 }
Please answer the following Stack Overflow question: Title: Windows recursive grep command-line <p>I need to do a recursive grep in Windows, something like this in Unix/Linux:</p> <pre><code>grep -i 'string' `find . -print` </code></pre> <p>or the more-preferred method:</p> <pre><code>find . -print | xargs grep -i 'string' </code></pre> <p>I'm stuck with just cmd.exe, so I only have Windows built-in commands. I can't install <a href="http://en.wikipedia.org/wiki/Cygwin" rel="noreferrer">Cygwin</a>, or any 3rd party tools like <a href="http://en.wikipedia.org/wiki/UnxUtils" rel="noreferrer">UnxUtils</a> on this server unfortunately. I'm not even sure I can install PowerShell. Any suggestions using only cmd.exe built-ins (Windows 2003 Server)?</p>
<p><code>findstr</code> can do recursive searches (/S) and supports some variant of regex syntax (/R). </p> <pre><code>C:\&gt;findstr /? Searches for strings in files. FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file] [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]] strings [[drive:][path]filename[ ...]] /B Matches pattern if at the beginning of a line. /E Matches pattern if at the end of a line. /L Uses search strings literally. /R Uses search strings as regular expressions. /S Searches for matching files in the current directory and all subdirectories. /I Specifies that the search is not to be case-sensitive. /X Prints lines that match exactly. /V Prints only lines that do not contain a match. /N Prints the line number before each line that matches. /M Prints only the filename if a file contains a match. /O Prints character offset before each matching line. /P Skip files with non-printable characters. /OFF[LINE] Do not skip files with offline attribute set. /A:attr Specifies color attribute with two hex digits. See "color /?" /F:file Reads file list from the specified file(/ stands for console). /C:string Uses specified string as a literal search string. /G:file Gets search strings from the specified file(/ stands for console). /D:dir Search a semicolon delimited list of directories strings Text to be searched for. [drive:][path]filename Specifies a file or files to search. Use spaces to separate multiple search strings unless the argument is prefixed with /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or "there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for "hello there" in file x.y. Regular expression quick reference: . Wildcard: any character * Repeat: zero or more occurrences of previous character or class ^ Line position: beginning of line $ Line position: end of line [class] Character class: any one character in set [^class] Inverse class: any one character not in set [x-y] Range: any characters within the specified range \x Escape: literal use of metacharacter x \&lt;xyz Word position: beginning of word xyz\&gt; Word position: end of word For full information on FINDSTR regular expressions refer to the online Command Reference. </code></pre>
{ "question_id": 698038, "question_date": "2009-03-30T16:46:14.970Z", "question_score": 232, "tags": "windows|command-line|grep", "answer_id": 698059, "answer_date": "2009-03-30T16:50:47.813Z", "answer_score": 275 }
Please answer the following Stack Overflow question: Title: Send message to specific client with socket.io and node.js <p>I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:</p> <pre><code>client.send(message, receiverSessionId) </code></pre> <p>But neither the <code>.send()</code> nor the <code>.broadcast()</code> methods seem to supply my need.</p> <p>What I have found as a possible solution, is that the <code>.broadcast()</code> method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.</p> <p>Any ideas?</p>
<p>Well you have to grab the client for that (surprise), you can either go the simple way:</p> <pre><code>var io = io.listen(server); io.clients[sessionID].send() </code></pre> <p>Which may break, I doubt it, but it's always a possibility that <code>io.clients</code> might get changed, so use the above with caution</p> <p>Or you keep track of the clients yourself, therefore you add them to your own <code>clients</code> object in the <code>connection</code> listener and remove them in the <code>disconnect</code> listener.</p> <p>I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like <code>clients[id] = {conn: clientConnect, data: {...}}</code> might do the job.</p>
{ "question_id": 4647348, "question_date": "2011-01-10T13:29:45.640Z", "question_score": 232, "tags": "javascript|node.js|websocket|socket.io|server-side", "answer_id": 4647661, "answer_date": "2011-01-10T14:14:13.423Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: Characters allowed in a URL <p>Does anyone know the full list of characters that can be used within a GET without being encoded? At the moment I am using A-Z a-z and 0-9... but I am looking to find out the full list.</p> <p>I am also interested into if there is a specification released for the up coming addition of Chinese, Arabic url's (as obviously that will have a big impact on my question)</p>
<p>EDIT: As @Jukka K. Korpela correctly points out, RFC 1738 was updated by <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="noreferrer">RFC 3986</a>. This has expanded and clarified the characters valid for host, unfortunately it's not easily copied and pasted, but I'll do my best.</p> <p>In first matched order:</p> <pre class="lang-lisp prettyprint-override"><code>host = IP-literal / IPv4address / reg-name IP-literal = &quot;[&quot; ( IPv6address / IPvFuture ) &quot;]&quot; IPvFuture = &quot;v&quot; 1*HEXDIG &quot;.&quot; 1*( unreserved / sub-delims / &quot;:&quot; ) IPv6address = 6( h16 &quot;:&quot; ) ls32 / &quot;::&quot; 5( h16 &quot;:&quot; ) ls32 / [ h16 ] &quot;::&quot; 4( h16 &quot;:&quot; ) ls32 / [ *1( h16 &quot;:&quot; ) h16 ] &quot;::&quot; 3( h16 &quot;:&quot; ) ls32 / [ *2( h16 &quot;:&quot; ) h16 ] &quot;::&quot; 2( h16 &quot;:&quot; ) ls32 / [ *3( h16 &quot;:&quot; ) h16 ] &quot;::&quot; h16 &quot;:&quot; ls32 / [ *4( h16 &quot;:&quot; ) h16 ] &quot;::&quot; ls32 / [ *5( h16 &quot;:&quot; ) h16 ] &quot;::&quot; h16 / [ *6( h16 &quot;:&quot; ) h16 ] &quot;::&quot; ls32 = ( h16 &quot;:&quot; h16 ) / IPv4address ; least-significant 32 bits of address h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal IPv4address = dec-octet &quot;.&quot; dec-octet &quot;.&quot; dec-octet &quot;.&quot; dec-octet dec-octet = DIGIT ; 0-9 / %x31-39 DIGIT ; 10-99 / &quot;1&quot; 2DIGIT ; 100-199 / &quot;2&quot; %x30-34 DIGIT ; 200-249 / &quot;25&quot; %x30-35 ; 250-255 reg-name = *( unreserved / pct-encoded / sub-delims ) unreserved = ALPHA / DIGIT / &quot;-&quot; / &quot;.&quot; / &quot;_&quot; / &quot;~&quot; &lt;---This seems like a practical shortcut, most closely resembling original answer reserved = gen-delims / sub-delims gen-delims = &quot;:&quot; / &quot;/&quot; / &quot;?&quot; / &quot;#&quot; / &quot;[&quot; / &quot;]&quot; / &quot;@&quot; sub-delims = &quot;!&quot; / &quot;$&quot; / &quot;&amp;&quot; / &quot;'&quot; / &quot;(&quot; / &quot;)&quot; / &quot;*&quot; / &quot;+&quot; / &quot;,&quot; / &quot;;&quot; / &quot;=&quot; pct-encoded = &quot;%&quot; HEXDIG HEXDIG </code></pre> <p>Original answer from <a href="http://www.faqs.org/rfcs/rfc1738.html" rel="noreferrer">RFC 1738</a> specification:</p> <blockquote> <p>Thus, only alphanumerics, the special characters &quot;<code>$-_.+!*'(),</code>&quot;, and reserved characters used for their reserved purposes may be used unencoded within a URL.</p> </blockquote> <p>^ obsolete since 1998.</p>
{ "question_id": 1856785, "question_date": "2009-12-06T22:10:17.393Z", "question_score": 232, "tags": "url", "answer_id": 1856809, "answer_date": "2009-12-06T22:16:12.980Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: UICollectionView Self Sizing Cells with Auto Layout <p>I'm trying to get self sizing <code>UICollectionViewCells</code> working with Auto Layout, but I can't seem to get the cells to size themselves to the content. I'm having trouble understanding how the cell's size is updated from the contents of what's inside the cell's contentView.</p> <p>Here's the setup I've tried:</p> <ul> <li>Custom <code>UICollectionViewCell</code> with a <code>UITextView</code> in its contentView.</li> <li>Scrolling for the <code>UITextView</code> is disabled.</li> <li>The contentView's horizontal constraint is: "H:|[_textView(320)]", i.e. the <code>UITextView</code> is pinned to the left of the cell with an explicit width of 320.</li> <li>The contentView's vertical constraint is: "V:|-0-[_textView]", i.e. the <code>UITextView</code> pinned to the top of the cell.</li> <li>The <code>UITextView</code> has a height constraint set to a constant which the <code>UITextView</code> reports will fit the text.</li> </ul> <p>Here's what it looks like with the cell background set to red, and the <code>UITextView</code> background set to Blue: <img src="https://i.stack.imgur.com/orihJ.png" alt="cell background red, UITextView background blue"></p> <p>I put the project that I've been playing with on GitHub <a href="https://github.com/rawbee/SelfSizingCollectionViewCells" rel="noreferrer">here</a>.</p>
<blockquote> <p>This answer is outdated from iOS 14 with the addition of compositional layouts. Please consider updating the <a href="https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/implementing_modern_collection_views" rel="nofollow noreferrer">new API</a></p> </blockquote> <h1>Updated for Swift 5</h1> <p><code>preferredLayoutAttributesFittingAttributes</code> renamed to <code>preferredLayoutAttributesFitting</code> and use auto sizing</p> <hr /> <h1>Updated for Swift 4</h1> <p><code>systemLayoutSizeFittingSize</code> renamed to <code>systemLayoutSizeFitting</code></p> <hr /> <h1>Updated for iOS 9</h1> <p>After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.</p> <p><strong>TL;DR</strong></p> <p>Check out my <a href="https://github.com/danielgalasko/DGSelfSizingCollectionViewCells/tree/master" rel="nofollow noreferrer">GitHub project</a></p> <hr /> <p>Self sizing cells are only supported with flow layout so make sure thats what you are using.</p> <p>There are two things you need to setup for self sizing cells to work.</p> <p>#1. Set <code>estimatedItemSize</code> on <code>UICollectionViewFlowLayout</code></p> <p>Flow layout will become dynamic in nature once you set the <code>estimatedItemSize</code> property.</p> <pre><code>self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize </code></pre> <p>#2. Add support for sizing on your cell subclass</p> <p>This comes in 2 flavours; Auto-Layout <strong>or</strong> custom override of <code>preferredLayoutAttributesFittingAttributes</code>.</p> <h3>Create and configure cells with Auto Layout</h3> <p>I won't go to in to detail about this as there's a brilliant <a href="https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights">SO post</a> about configuring constraints for a cell. Just be wary that <a href="https://stackoverflow.com/questions/25804588/auto-layout-in-uicollectionviewcell-not-working?rq=1">Xcode 6 broke</a> a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. <code>awakeFromNib</code>).</p> <p>Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.</p> <h3>Implement <code>preferredLayoutAttributesFittingAttributes</code> in your custom cell</h3> <p>When this function is called your view has already been configured with content (i.e. <code>cellForItem</code> has been called). Assuming your constraints have been appropriately set you could have an implementation like this:</p> <pre><code>//forces the system to do one layout pass var isHeightCalculated: Bool = false override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -&gt; UICollectionViewLayoutAttributes { //Exhibit A - We need to cache our calculation to prevent a crash. if !isHeightCalculated { setNeedsLayout() layoutIfNeeded() let size = contentView.systemLayoutSizeFitting(layoutAttributes.size) var newFrame = layoutAttributes.frame newFrame.size.width = CGFloat(ceilf(Float(size.width))) layoutAttributes.frame = newFrame isHeightCalculated = true } return layoutAttributes } </code></pre> <p><strong>NOTE</strong> On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more <a href="https://github.com/danielgalasko/DGSelfSizingCollectionViewCells/issues/4" rel="nofollow noreferrer">here</a>). When you implement <code>preferredLayoutAttributesFittingAttributes</code> you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the <code>isHeightCalculated</code> property.</p> <h3>Experience your layout</h3> <p>At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like <code>UITableView</code> wins the battle for dynamic sizing IMHO.</p> <p>##Caveats Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your <a href="https://stackoverflow.com/questions/27735341/offscreen-uitableviewcells-for-size-calculations-not-respecting-size-class">XIB uses size classes</a>. The reason for this is that when you load your cell from a XIB its size class will be configured with <code>Undefined</code>. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the <code>traitCollection</code> getter and return the appropriate traits. It's up to you.</p> <p>Let me know if I missed anything, hope I helped and good luck coding</p> <hr />
{ "question_id": 25895311, "question_date": "2014-09-17T16:02:15.547Z", "question_score": 232, "tags": "ios|uicollectionview|autolayout|uicollectionviewcell", "answer_id": 25896386, "answer_date": "2014-09-17T17:04:24.270Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: How to count the number of true elements in a NumPy bool array <p>I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are <code>True</code>. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?</p>
<p>You have multiple options. Two options are the following.</p> <pre><code>boolarr.sum() numpy.count_nonzero(boolarr) </code></pre> <p>Here's an example:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool) &gt;&gt;&gt; boolarr array([[False, False, True], [ True, False, True], [ True, False, True]], dtype=bool) &gt;&gt;&gt; boolarr.sum() 5 </code></pre> <p>Of course, that is a <code>bool</code>-specific answer. More generally, you can use <code>numpy.count_nonzero</code>.</p> <pre><code>&gt;&gt;&gt; np.count_nonzero(boolarr) 5 </code></pre>
{ "question_id": 8364674, "question_date": "2011-12-03T01:13:26.243Z", "question_score": 232, "tags": "python|arrays|numpy|count|boolean", "answer_id": 8364723, "answer_date": "2011-12-03T01:22:14.207Z", "answer_score": 323 }
Please answer the following Stack Overflow question: Title: What is process.env.PORT in Node.js? <p>what is <code>process.env.PORT || 3000</code> used for in Node.js? I saw this somewhere:</p> <pre><code> app.set('port', process.env.PORT || 3000); </code></pre> <p>If it is used to set <code>3000</code> as the listening port, can I use this instead?</p> <pre><code>app.listen(3000); </code></pre> <p>If not why?</p>
<p>In many environments (e.g. Heroku), and as a convention, you can set the environment variable <code>PORT</code> to tell your web server what port to listen on.</p> <p>So <code>process.env.PORT || 3000</code> means: whatever is in the environment variable PORT, or 3000 if there's nothing there.</p> <p>So you pass that to <code>app.listen</code>, or to <code>app.set('port', ...)</code>, and that makes your server able to accept a &quot;what port to listen on&quot; parameter from the environment.</p> <p>If you pass <code>3000</code> hard-coded to <code>app.listen()</code>, you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.</p>
{ "question_id": 18864677, "question_date": "2013-09-18T05:42:44.263Z", "question_score": 232, "tags": "node.js|express|port", "answer_id": 18864718, "answer_date": "2013-09-18T05:45:18.097Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: Selecting only numeric columns from a data frame <p>Suppose, you have a data.frame like this: </p> <pre><code>x &lt;- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20]) </code></pre> <p>How would you select only those columns in x that are numeric? </p>
<p>EDIT: updated to avoid use of ill-advised <code>sapply</code>.</p> <p>Since a data frame is a list we can use the list-apply functions:</p> <pre><code>nums &lt;- unlist(lapply(x, is.numeric), use.names = FALSE) </code></pre> <p>Then standard subsetting</p> <pre><code>x[ , nums] ## don't use sapply, even though it's less code ## nums &lt;- sapply(x, is.numeric) </code></pre> <p>For a more idiomatic modern R I'd now recommend</p> <pre><code>x[ , purrr::map_lgl(x, is.numeric)] </code></pre> <p>Less codey, less reflecting R's particular quirks, and more straightforward, and robust to use on database-back-ended tibbles:</p> <pre><code>dplyr::select_if(x, is.numeric) </code></pre> <p>Newer versions of dplyr, also support the following syntax:</p> <pre><code>x %&gt;% dplyr::select(where(is.numeric)) </code></pre>
{ "question_id": 5863097, "question_date": "2011-05-02T22:19:03.313Z", "question_score": 232, "tags": "r", "answer_id": 5863165, "answer_date": "2011-05-02T22:28:36.717Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: Wrap long lines in Python <p>How do I wrap long lines in Python without sacrificing indentation? </p> <p>For example: </p> <pre><code>def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) </code></pre> <p>Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it:</p> <pre><code>def fun(): print '{0} Here is a really long \ sentence with {1}'.format(3, 5) </code></pre> <p>However, with this approach, the indentation of the continued line matches the indentation of the <code>fun()</code>. This looks kinda ugly. If someone was to go through my code, it would look bad to have uneven indentation because of this <code>print</code> statement.</p> <p>How do I indent lines like this effectively without sacrificing code readability?</p>
<pre><code>def fun(): print(('{0} Here is a really long ' 'sentence with {1}').format(3, 5)) </code></pre> <p>Adjacent string literals are concatenated at compile time, just as in C. <a href="http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation" rel="noreferrer">http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation</a> is a good place to start for more info.</p>
{ "question_id": 3346230, "question_date": "2010-07-27T17:30:42.133Z", "question_score": 232, "tags": "python|string", "answer_id": 3346295, "answer_date": "2010-07-27T17:37:59.063Z", "answer_score": 311 }
Please answer the following Stack Overflow question: Title: Replace a string in a file with nodejs <p>I use the <a href="https://npmjs.org/package/grunt-md5" rel="noreferrer">md5 grunt task</a> to generate MD5 filenames. Now I want to rename the sources in the HTML file with the new filename in the callback of the task. I wonder what's the easiest way to do this.</p>
<p>You could use simple regex:</p> <pre><code>var result = fileAsString.replace(/string to be replaced/g, 'replacement'); </code></pre> <p>So...</p> <pre><code>var fs = require('fs') fs.readFile(someFile, 'utf8', function (err,data) { if (err) { return console.log(err); } var result = data.replace(/string to be replaced/g, 'replacement'); fs.writeFile(someFile, result, 'utf8', function (err) { if (err) return console.log(err); }); }); </code></pre>
{ "question_id": 14177087, "question_date": "2013-01-05T22:28:18.477Z", "question_score": 232, "tags": "javascript|node.js|replace|gruntjs", "answer_id": 14181136, "answer_date": "2013-01-06T10:12:07.440Z", "answer_score": 396 }
Please answer the following Stack Overflow question: Title: Assert an object is a specific type <p>Is it possible in JUnit to assert an object is an instance of a class? For various reasons I have an object in my test that I want to check the type of. Is it a type of Object1 or a type of Object2?</p> <p>Currently I have:</p> <pre><code>assertTrue(myObject instanceof Object1); assertTrue(myObject instanceof Object2); </code></pre> <p>This works but I was wondering if there is a more expressive way of doing this.</p> <p>For example something like:</p> <pre><code>assertObjectIsClass(myObject, Object1); </code></pre> <p>I could do this:</p> <pre><code>assertEquals(myObject.class, Object1.getClass()); </code></pre> <p>Is there a specific assert method that allows me to test a type of an object in a more elegant, fluid manner?</p>
<p>You can use the <code>assertThat</code> method and the Matchers that comes with JUnit.</p> <p>Take a look at <a href="http://tutorials.jenkov.com/java-unit-testing/matchers.html" rel="noreferrer">this link</a> that describes a little bit about the JUnit Matchers.</p> <p>Example:</p> <pre><code>public class BaseClass { } public class SubClass extends BaseClass { } </code></pre> <p>Test:</p> <pre><code>import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; /** * @author maba, 2012-09-13 */ public class InstanceOfTest { @Test public void testInstanceOf() { SubClass subClass = new SubClass(); assertThat(subClass, instanceOf(BaseClass.class)); } } </code></pre>
{ "question_id": 12404650, "question_date": "2012-09-13T10:54:37.143Z", "question_score": 232, "tags": "java|unit-testing|junit", "answer_id": 12404813, "answer_date": "2012-09-13T11:03:47.137Z", "answer_score": 285 }
Please answer the following Stack Overflow question: Title: Move textfield when keyboard appears swift <p>I'm using Swift for programing with iOS and I'm using this code to move the <code>UITextField</code>, but it does not work. I call the function <code>keyboardWillShow</code> correctly, but the textfield doesn't move. I'm using autolayout.</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } deinit { NSNotificationCenter.defaultCenter().removeObserver(self); } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { //let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) var frame = self.ChatField.frame frame.origin.y = frame.origin.y - keyboardSize.height + 167 self.chatField.frame = frame println("asdasd") } } </code></pre>
<p>There are a couple of improvements to be made on the existing answers.</p> <p>Firstly the <strong>UIKeyboardWillChangeFrameNotification</strong> is probably the best notification as it handles changes that aren't just show/hide but changes due to keyboard changes (language, using 3rd party keyboards etc.) and rotations too (but note comment below indicating the keyboard will hide should also be handled to support hardware keyboard connection).</p> <p>Secondly the animation parameters can be pulled from the notification to ensure that animations are properly together.</p> <p>There are probably options to clean up this code a bit more especially if you are comfortable with force unwrapping the dictionary code.</p> <pre><code> class MyViewController: UIViewController { // This constraint ties an element at zero points from the bottom layout guide @IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func keyboardNotification(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let endFrameY = endFrame?.origin.y ?? 0 let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw) if endFrameY &gt;= UIScreen.main.bounds.size.height { self.keyboardHeightLayoutConstraint?.constant = 0.0 } else { self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0 } UIView.animate( withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } } </code></pre>
{ "question_id": 25693130, "question_date": "2014-09-05T19:57:25.893Z", "question_score": 232, "tags": "ios|swift|cocoa-touch|keyboard|uitextfield", "answer_id": 27135992, "answer_date": "2014-11-25T20:23:17.443Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) <p>Why python 2.7 doesn't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript?</p> <pre><code>&gt;&gt;&gt; datetime.datetime.utcnow().isoformat() '2013-10-29T09:14:03.895210' </code></pre> <p>Whereas in javascript</p> <pre><code>&gt;&gt;&gt; console.log(new Date().toISOString()); 2013-10-29T09:38:41.341Z </code></pre>
<p>Python <code>datetime</code> objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (<a href="http://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators" rel="noreferrer">if no time zone info is given, assumed to be local time</a>). You can use the <a href="https://pypi.python.org/pypi/pytz/" rel="noreferrer">pytz package</a> to get some default time zones, or directly subclass <code>tzinfo</code> yourself:</p> <pre><code>from datetime import datetime, tzinfo, timedelta class simple_utc(tzinfo): def tzname(self,**kwargs): return "UTC" def utcoffset(self, dt): return timedelta(0) </code></pre> <p>Then you can manually add the time zone info to <code>utcnow()</code>:</p> <pre><code>&gt;&gt;&gt; datetime.utcnow().replace(tzinfo=simple_utc()).isoformat() '2014-05-16T22:51:53.015001+00:00' </code></pre> <p>Note that this DOES conform to the ISO 8601 format, which allows for either <code>Z</code> or <code>+00:00</code> as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)</p>
{ "question_id": 19654578, "question_date": "2013-10-29T09:42:06.293Z", "question_score": 232, "tags": "python|python-2.7|datetime|timestamp|iso8601", "answer_id": 23705687, "answer_date": "2014-05-16T22:54:38.400Z", "answer_score": 78 }
Please answer the following Stack Overflow question: Title: How to get the selected index of a RadioGroup in Android <p>Is there an easy way to get the selected index of a RadioGroup in Android or do I have to use OnCheckedChangeListener to listen for changes and have something that holds the last index selected?</p> <p>example xml:</p> <pre><code>&lt;RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/RadioGroup&gt; </code></pre> <p>if a user selects <code>option 3</code> I want to get the index, 2.</p>
<p>You should be able to do something like this:</p> <pre><code>int radioButtonID = radioButtonGroup.getCheckedRadioButtonId(); View radioButton = radioButtonGroup.findViewById(radioButtonID); int idx = radioButtonGroup.indexOfChild(radioButton); </code></pre> <p>If the <code>RadioGroup</code> contains other Views (like a <code>TextView</code>) then the <code>indexOfChild()</code> method will return wrong index.</p> <p>To get the selected <code>RadioButton</code> text on the <code>RadioGroup</code>:</p> <pre><code> RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx); String selectedtext = r.getText().toString(); </code></pre>
{ "question_id": 6440259, "question_date": "2011-06-22T12:58:41.113Z", "question_score": 232, "tags": "java|android|xml|radio-group", "answer_id": 6441097, "answer_date": "2011-06-22T13:58:12.687Z", "answer_score": 511 }
Please answer the following Stack Overflow question: Title: Pandas get topmost n records within each group <p>Suppose I have pandas DataFrame like this:</p> <pre><code>df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4],'value':[1,2,3,1,2,3,4,1,1]}) </code></pre> <p>which looks like:</p> <pre><code> id value 0 1 1 1 1 2 2 1 3 3 2 1 4 2 2 5 2 3 6 2 4 7 3 1 8 4 1 </code></pre> <p>I want to get a new DataFrame with top 2 records for each id, like this:</p> <pre><code> id value 0 1 1 1 1 2 3 2 1 4 2 2 7 3 1 8 4 1 </code></pre> <p>I can do it with numbering records within group after <code>groupby</code>:</p> <pre><code>dfN = df.groupby('id').apply(lambda x:x['value'].reset_index()).reset_index() </code></pre> <p>which looks like:</p> <pre><code> id level_1 index value 0 1 0 0 1 1 1 1 1 2 2 1 2 2 3 3 2 0 3 1 4 2 1 4 2 5 2 2 5 3 6 2 3 6 4 7 3 0 7 1 8 4 0 8 1 </code></pre> <p>then for the desired output:</p> <pre><code>dfN[dfN['level_1'] &lt;= 1][['id', 'value']] </code></pre> <p>Output:</p> <pre><code> id value 0 1 1 1 1 2 3 2 1 4 2 2 7 3 1 8 4 1 </code></pre> <p>But is there more effective/elegant approach to do this? And also is there more elegant approach to number records within each group (like SQL window function <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="noreferrer">row_number()</a>).</p>
<p>Did you try</p> <pre><code>df.groupby('id').head(2) </code></pre> <p>Output generated:</p> <pre><code> id value id 1 0 1 1 1 1 2 2 3 2 1 4 2 2 3 7 3 1 4 8 4 1 </code></pre> <p>(Keep in mind that you might need to order/sort before, depending on your data)</p> <p>EDIT: As mentioned by the questioner, use</p> <pre><code>df.groupby('id').head(2).reset_index(drop=True) </code></pre> <p>to remove the MultiIndex and flatten the results:</p> <pre><code> id value 0 1 1 1 1 2 2 2 1 3 2 2 4 3 1 5 4 1 </code></pre>
{ "question_id": 20069009, "question_date": "2013-11-19T10:28:36.650Z", "question_score": 232, "tags": "python|pandas|greatest-n-per-group|window-functions|top-n", "answer_id": 20069379, "answer_date": "2013-11-19T10:46:03.760Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Apply CSS styles to an element depending on its child elements <p>Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?</p> <p>I think this is best explained using an example.</p> <p><strong>Note</strong>: I'm trying to <strong>style the parent element</strong>, depending on what child elements it contains.</p> <pre><code>&lt;style&gt; /* note this is invalid syntax. I'm using the non-existing ":containing" pseudo-class to show what I want to achieve. */ div:containing div.a { border: solid 3px red; } div:containing div.b { border: solid 3px blue; } &lt;/style&gt; &lt;!-- the following div should have a red border because if contains a div with class="a" --&gt; &lt;div&gt; &lt;div class="a"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- the following div should have a blue border --&gt; &lt;div&gt; &lt;div class="b"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Note 2</strong>: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.</p>
<p>As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.</p> <p>It'd be wonderful if you could do something like <code>div[div.a]</code> or <code>div:containing[div.a]</code> as you said, but this isn't possible. </p> <p>You may want to consider looking at <a href="http://jquery.com" rel="noreferrer">jQuery</a>. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.</p> <p>If you use jQuery, something along the lines of this would may work (untested but the theory is there):</p> <pre><code>$('div:has(div.a)').css('border', '1px solid red'); </code></pre> <p>or</p> <pre><code>$('div:has(div.a)').addClass('redBorder'); </code></pre> <p>combined with a CSS class:</p> <pre><code>.redBorder { border: 1px solid red; } </code></pre> <p>Here's the documentation for the <a href="http://api.jquery.com/has-selector/" rel="noreferrer">jQuery "has" selector</a>.</p>
{ "question_id": 2326499, "question_date": "2010-02-24T14:03:30.003Z", "question_score": 232, "tags": "html|css", "answer_id": 2326571, "answer_date": "2010-02-24T14:13:20.593Z", "answer_score": 143 }
Please answer the following Stack Overflow question: Title: How to filter keys of an object with lodash? <p>I have an object with some keys, and I want to only keep some of the keys with their value?</p> <p>I tried with <code>filter</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-js lang-js prettyprint-override"><code>const data = { aaa: 111, abb: 222, bbb: 333 }; const result = _.filter(data, (value, key) =&gt; key.startsWith("a")); console.log(result);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>But it prints an array:</p> <blockquote> <p>[111, 222]</p> </blockquote> <p>Which is not what I want. </p> <p>How to do it with lodash? Or something else if lodash is not working?</p>
<p><strong>Lodash has a <a href="https://lodash.com/docs#pickBy" rel="noreferrer"><code>_.pickBy</code></a> function</strong> which does exactly what you're looking for.</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 thing = { "a": 123, "b": 456, "abc": 6789 }; var result = _.pickBy(thing, function(value, key) { return _.startsWith(key, "a"); }); console.log(result.abc) // 6789 console.log(result.b) // undefined</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
{ "question_id": 30726830, "question_date": "2015-06-09T08:31:24.793Z", "question_score": 232, "tags": "javascript|filter|lodash", "answer_id": 30727745, "answer_date": "2015-06-09T09:11:52.853Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: Hidden features of Windows batch files <p>What are some of the lesser know, but important and useful features of Windows batch files?</p> <p>Guidelines:</p> <ul> <li>One feature per answer</li> <li>Give both a short <strong>description</strong> of the feature and an <strong>example</strong>, not just a link to documentation</li> <li>Limit answers to <strong>native funtionality</strong>, i.e., does not require additional software, like the <em>Windows Resource Kit</em></li> </ul> <p>Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.</p> <p>(See also: <a href="https://stackoverflow.com/questions/148968/windows-batch-files-bat-vs-cmd">Windows batch files: .bat vs .cmd?</a>)</p>
<p>Line continuation:</p> <pre><code>call C:\WINDOWS\system32\ntbackup.exe ^ backup ^ /V:yes ^ /R:no ^ /RS:no ^ /HC:off ^ /M normal ^ /L:s ^ @daily.bks ^ /F daily.bkf </code></pre>
{ "question_id": 245395, "question_date": "2008-10-29T00:34:22.390Z", "question_score": 232, "tags": "windows|batch-file|hidden-features", "answer_id": 245434, "answer_date": "2008-10-29T00:50:52.733Z", "answer_score": 185 }
Please answer the following Stack Overflow question: Title: How to create a dictionary of two pandas DataFrame columns <p>What is the most efficient way to organise the following pandas Dataframe:</p> <p>data =</p> <pre><code>Position Letter 1 a 2 b 3 c 4 d 5 e </code></pre> <p>into a dictionary like <code>alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']</code>?</p>
<pre><code>In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} </code></pre> <p>Speed comparion (using Wouter's method)</p> <pre><code>In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop </code></pre>
{ "question_id": 17426292, "question_date": "2013-07-02T12:58:45.367Z", "question_score": 232, "tags": "python|dictionary|pandas|dataframe", "answer_id": 17426500, "answer_date": "2013-07-02T13:08:23.243Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: Where is the syntax for TypeScript comments documented? <p>Is the syntax for TypeScript comments documented anywhere?</p> <p>And by any chance, does it now support the C# <code>///</code> system?</p>
<p><strong>Update November 2020</strong></p> <p>A website is now online with all the TSDoc syntax available (and that's awesome): <a href="https://tsdoc.org/" rel="noreferrer">https://tsdoc.org/</a></p> <hr /> <p><strong>For reference, old answer</strong>:</p> <p><strike>The right syntax is now the one used by <a href="https://github.com/Microsoft/tsdoc" rel="noreferrer">TSDoc</a>. It will allow you to have your comments understood by Visual Studio Code or other documentation tools.</p> <p>A good overview of the syntax is available <a href="https://api-extractor.com/pages/tsdoc/doc_comment_syntax/" rel="noreferrer">here</a> and <a href="https://github.com/Microsoft/tsdoc/blob/master/spec/code-snippets/DeclarationReferences.ts" rel="noreferrer">especially here</a>. The precise spec <a href="https://github.com/Microsoft/tsdoc/issues/130" rel="noreferrer">should be &quot;soon&quot; written up</a>.</p> <p>Another file worth checking out is <a href="https://github.com/Microsoft/tsdoc/blob/master/tsdoc/src/details/StandardTags.ts" rel="noreferrer">this one</a> where you will see useful standard tags.</p> <p><strong>Note</strong>: you should not use JSDoc, as explained on TSDoc main page: <em>Why can't JSDoc be the standard? Unfortunately, the JSDoc grammar is not rigorously specified but rather inferred from the behavior of a particular implementation. The majority of the standard JSDoc tags are preoccupied with providing type annotations for plain JavaScript, which is an irrelevant concern for a strongly-typed language such as TypeScript. TSDoc addresses these limitations while also tackling a more sophisticated set of goals.</em></strike></p>
{ "question_id": 23072286, "question_date": "2014-04-14T23:43:47.843Z", "question_score": 232, "tags": "comments|typescript", "answer_id": 53222546, "answer_date": "2018-11-09T08:56:36.683Z", "answer_score": 106 }
Please answer the following Stack Overflow question: Title: Use URI builder in Android or create URL with variables <p>I'm developing an Android app. I need to build a URI for my app to make an API request. Unless there's another way to put a variable in a URI, this is the easiest way I've found. I found that you need to use <code>Uri.Builder</code>, but I'm not quite sure how to. My url is:</p> <pre><code>http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&amp;mapid=value </code></pre> <p>My scheme is http, authority is <code>lapi.transitchicago.com</code>, path is <code>/api/1.0</code>, path segment(s) is <code>ttarrivals.aspx</code>, and query string is <code>key=[redacted]&amp;mapid=value</code>. </p> <p>My code is below:</p> <pre><code>Intent intent = getIntent(); String value = intent.getExtras().getString("value"); Uri.Builder builder = new Uri.Builder(); builder.scheme("http") .authority("www.lapi.transitchicago.com") .appendPath("api") .appendPath("1.0") .appendPath("ttarrivals.aspx") .appendQueryParameter("key", "[redacted]") .appendQueryParameter("mapid", value); </code></pre> <p>I understand that I can do <code>URI.add</code>, but how do I integrate it into the <code>Uri.Builder</code>? Should I add everything like <code>URI.add(scheme)</code>, <code>URI.add(authority)</code> and so on? Or is that not the way to do it? Also, is there any other easier way to add a variable to a URI/URL?</p>
<p>Let's say that I want to create the following URL:</p> <pre class="lang-none prettyprint-override"><code>https://www.myawesomesite.com/turtles/types?type=1&amp;sort=relevance#section-name </code></pre> <p>To build this with the <a href="http://developer.android.com/reference/android/net/Uri.Builder.html"><code>Uri.Builder</code></a> I would do the following.</p> <pre><code>Uri.Builder builder = new Uri.Builder(); builder.scheme("https") .authority("www.myawesomesite.com") .appendPath("turtles") .appendPath("types") .appendQueryParameter("type", "1") .appendQueryParameter("sort", "relevance") .fragment("section-name"); String myUrl = builder.build().toString(); </code></pre>
{ "question_id": 19167954, "question_date": "2013-10-03T19:46:52.110Z", "question_score": 232, "tags": "android|uri|uribuilder", "answer_id": 19168199, "answer_date": "2013-10-03T20:01:41.610Z", "answer_score": 471 }
Please answer the following Stack Overflow question: Title: Why doesn't the height of a container element increase if it contains floated elements? <p>I would like to ask how height and float work. I have an outer div and an inner div that has content in it. Its height may vary depending on the content of the inner div but it seems that my inner div will overflow its outside div. What would be the proper way to do it?</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;html&gt; &lt;body&gt; &lt;div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange"&gt; &lt;div style="width:500px; height:200px; background-color:black; float:right"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...</p> <p>I'll show you visually:</p> <p><img src="https://i.stack.imgur.com/jSlAi.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/N3rMW.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/7wq0g.jpg" alt="enter image description here"></p> <p>More Explanation:</p> <pre><code>&lt;div&gt; &lt;div style="float: left;"&gt;&lt;/div&gt; &lt;div style="width: 15px;"&gt;&lt;/div&gt; &lt;!-- This will shift besides the top div. Why? Because of the top div is floated left, making the rest of the space blank --&gt; &lt;div style="clear: both;"&gt;&lt;/div&gt; &lt;!-- Now in order to prevent the next div from floating beside the top ones, we use `clear: both;`. This is like a wall, so now none of the div's will be floated after this point. The container height will now also include the height of these floated divs --&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>You can also add <code>overflow: hidden;</code> on container elements, but I would suggest you use <code>clear: both;</code> instead.</p> <p>Also if you might like to self-clear an element you can use</p> <pre><code>.self_clear:after { content: ""; clear: both; display: table; } </code></pre> <hr> <h1>How Does CSS Float Work?</h1> <h2>What is float exactly and what does it do?</h2> <ul> <li><p><p>The <code>float</code> property is misunderstood by most beginners. Well, what exactly does <code>float</code> do? Initially, the <code>float</code> property was introduced to flow text around images, which are floated <code>left</code> or <code>right</code>. <a href="https://stackoverflow.com/questions/12871710/why-clear-both-css/12871734#comment26828942_12871734">Here's another explanation</a> by @Madara Uchicha. </p><p>So, is it wrong to use the <code>float</code> property for placing boxes side by side? The answer is <strong>no</strong>; there is no problem if you use the <code>float</code> property in order to set boxes side by side.</p></li> <li><p><p>Floating an <code>inline</code> or <code>block</code> level element will make the element behave like an <code>inline-block</code> element.</p><a href="http://jsfiddle.net/W3GJm/" rel="noreferrer"><strong>Demo</strong></a></p></li> <li><p>If you float an element <code>left</code> or <code>right</code>, the <code>width</code> of the element will be limited to the content it holds, unless <code>width</code> is defined explicitly ...</p></li> <li><p><p>You cannot <code>float</code> an element <code>center</code>. This is the biggest issue I've always seen with beginners, using <s><code>float: center;</code></s>, which is not a valid value for the <code>float</code> property. <code>float</code> is generally used to <code>float</code>/move content to the very <em>left</em> or to the very <em>right</em>. There are only <em>four</em> valid values for <code>float</code> property i.e <code>left</code>, <code>right</code>, <code>none</code> (default) and <code>inherit</code>.</p></li> <li><p><p>Parent element collapses, when it contains floated child elements, in order to prevent this, we use <code>clear: both;</code> property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer <a href="https://stackoverflow.com/a/12871734/1542290">here</a>.</p></li> <li><p><strong>(Important)</strong> Think of it where we have a stack of various elements. When we use <code>float: left;</code> or <code>float: right;</code> the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. <strong>(Please don't relate this to <code>z-index</code> as that is completely different.)</strong></p></li> </ul> <hr> <p>Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...</p> <p><img src="https://i.stack.imgur.com/F8Vg2.jpg" alt="enter image description here"></p> <p>In the above example, we will be floating only the red boxes, either you can <code>float</code> both to the <code>left</code>, or you can <code>float</code> on to <code>left</code>, and another to <code>right</code> as well, depends on the layout, if it's 3 columns, you may <code>float</code> 2 columns to <code>left</code> where another one to the <code>right</code> so depends, though in this example, we have a simplified 2 column layout so will <code>float</code> one to <code>left</code> and the other to the <code>right</code>.</p> <p>Markup and styles for creating the layout explained further down...</p> <pre><code>&lt;div class="main_wrap"&gt; &lt;header&gt;Header&lt;/header&gt; &lt;div class="wrapper clear"&gt; &lt;div class="floated_left"&gt; This&lt;br /&gt; is&lt;br /&gt; just&lt;br /&gt; a&lt;br /&gt; left&lt;br /&gt; floated&lt;br /&gt; column&lt;br /&gt; &lt;/div&gt; &lt;div class="floated_right"&gt; This&lt;br /&gt; is&lt;br /&gt; just&lt;br /&gt; a&lt;br /&gt; right&lt;br /&gt; floated&lt;br /&gt; column&lt;br /&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt;Footer&lt;/footer&gt; &lt;/div&gt; * { -moz-box-sizing: border-box; /* Just for demo purpose */ -webkkit-box-sizing: border-box; /* Just for demo purpose */ box-sizing: border-box; /* Just for demo purpose */ margin: 0; padding: 0; } .main_wrap { margin: 20px; border: 3px solid black; width: 520px; } header, footer { height: 50px; border: 3px solid silver; text-align: center; line-height: 50px; } .wrapper { border: 3px solid green; } .floated_left { float: left; width: 200px; border: 3px solid red; } .floated_right { float: right; width: 300px; border: 3px solid red; } .clear:after { clear: both; content: ""; display: table; } </code></pre> <p>Let's go step by step with the layout and see how float works.. </p> <p>First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use <code>header</code> and assign a <code>height</code> of <code>50px</code> so nothing fancy there. It's just a normal non floated block level element which will take up <code>100%</code> horizontal space unless it's floated or we assign <code>inline-block</code> to it.</p> <p>The first valid value for <code>float</code> is <code>left</code> so in our example, we use <code>float: left;</code> for <code>.floated_left</code>, so we intend to float a block to the <code>left</code> of our container element.</p> <p><a href="http://jsfiddle.net/Lmk9s/" rel="noreferrer">Column floated to the left</a></p> <p>And yes, if you see, the parent element, which is <code>.wrapper</code> is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to <code>left</code>.</p> <p>Coming to the second column, lets it <code>float</code> this one to the <code>right</code></p> <p><a href="http://jsfiddle.net/Lmk9s/1/" rel="noreferrer">Another column floated to the right</a></p> <p>Here, we have a <code>300px</code> wide column which we <code>float</code> to the <code>right</code>, which will sit beside the first column as it's floated to the <code>left</code>, and since it's floated to the <code>left</code>, it created empty gutter to the <code>right</code>, and since there was ample of space on the <code>right</code>, our <code>right</code> floated element sat perfectly beside the <code>left</code> one.</p> <p>Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.</p> <ul> <li>Add an empty block level element and use <code>clear: both;</code> before the parent element ends, which holds floated elements, now this one is a cheap solution to <code>clear</code> your floating elements which will do the job for you but, I would recommend not to use this.</li> </ul> <p>Add, <code>&lt;div style="clear: both;"&gt;&lt;/div&gt;</code> before the <code>.wrapper</code> <code>div</code> ends, like</p> <pre><code>&lt;div class="wrapper clear"&gt; &lt;!-- Floated columns --&gt; &lt;div style="clear: both;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/Lmk9s/2/" rel="noreferrer"><strong>Demo</strong></a></p> <p>Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use <code>overflow: hidden;</code> on the parent element holding floated child elements which work as intended.</p> <p>Use <code>overflow: hidden;</code> on <code>.wrapper</code></p> <pre><code>.wrapper { border: 3px solid green; overflow: hidden; } </code></pre> <p><a href="http://jsfiddle.net/Lmk9s/3/" rel="noreferrer"><strong>Demo</strong></a></p> <p>That saves us an element every time we need to <code>clear</code> <code>float</code> but as I tested various cases with this, it failed in one particular one, which uses <code>box-shadow</code> on the child elements.</p> <p><a href="http://jsfiddle.net/Lmk9s/4/" rel="noreferrer"><strong>Demo</strong></a> (Can't see the shadow on all 4 sides, <code>overflow: hidden;</code> causes this issue)</p> <p>So what now? Save an element, no <code>overflow: hidden;</code> so go for a clear fix hack, use the below snippet in your CSS, and just as you use <code>overflow: hidden;</code> for the parent element, call the <code>class</code> below on the parent element to self-clear.</p> <pre><code>.clear:after { clear: both; content: ""; display: table; } &lt;div class="wrapper clear"&gt; &lt;!-- Floated Elements --&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/Lmk9s/5/" rel="noreferrer"><strong>Demo</strong></a></p> <p>Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.</p> <p>And lastly, we use footer after we <code>clear</code> the floated elements.</p> <p><a href="http://jsfiddle.net/Lmk9s/6/" rel="noreferrer"><strong>Demo</strong></a></p> <hr> <p>When is <code>float: none;</code> used anyways, as it is the default, so any use to declare <code>float: none;</code>?</p> <p>Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that <code>float: none;</code> property plays an important role there.</p> <hr> <p>Few real-world examples of how <code>float</code> is useful.</p> <ul> <li>The first example we already saw is to create one or more than one column layouts.</li> <li>Using <code>img</code> floated inside <code>p</code> which will enable our content to flow around.</li> </ul> <p><a href="http://jsfiddle.net/xZPX7/" rel="noreferrer"><strong>Demo</strong></a> (Without floating <code>img</code>)</p> <p><a href="http://jsfiddle.net/xZPX7/1/" rel="noreferrer"><strong>Demo 2</strong></a> (<code>img</code> floated to the <code>left</code>)</p> <ul> <li>Using <code>float</code> for creating horizontal menu - <a href="http://jsfiddle.net/xZPX7/2/" rel="noreferrer"><strong>Demo</strong></a></li> </ul> <hr> <h3>Float second element as well, or use `margin`</h3> <p>Last but not the least, I want to explain this particular case where you <code>float</code> only single element to the <code>left</code> but you do not <code>float</code> the other, so what happens?</p> <p>Suppose if we remove <code>float: right;</code> from our <code>.floated_right</code> <code>class</code>, the <code>div</code> will be rendered from extreme <code>left</code> as it isn't floated.</p> <p><a href="http://jsfiddle.net/Lmk9s/7/" rel="noreferrer"><strong>Demo</strong></a></p> <p>So in this case, either you can <a href="http://jsfiddle.net/Lmk9s/8/" rel="noreferrer"><code>float</code> the to the <code>left</code> as well</a> </p> <p>OR </p> <p>You can <a href="http://jsfiddle.net/Lmk9s/9/" rel="noreferrer">use <code>margin-left</code> which will be equal to the size of the left floated column i.e <code>200px</code> wide</a>.</p>
{ "question_id": 16568272, "question_date": "2013-05-15T14:49:41.743Z", "question_score": 232, "tags": "html|css|css-float", "answer_id": 16568504, "answer_date": "2013-05-15T14:59:26.187Z", "answer_score": 624 }
Please answer the following Stack Overflow question: Title: DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server <p>Getting error when script move to other server. </p> <blockquote> <p>(node:15707) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. </p> </blockquote> <p>Current Versions: </p> <pre><code>Ubuntu 16.04.4 LTS Node - v10.9.0 NPM - 6.2.0 </code></pre> <p>Previous Version:</p> <pre><code>Ubuntu 14.04.3 LTS NPM - 3.10.10 Node - v6.10.3 </code></pre> <p><br></p> <pre><code>exports.basicAuthentication = function (req, res, next) { console.log("basicAuthentication"); if (!req.headers.authorization) { return res.status(401).send({ message: "Unauthorised access" }); } var auth = req.headers.authorization; var baseAuth = auth.replace("Basic", ""); baseAuth = baseAuth.trim(); var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii'); var credentials = userPasswordString.split(':'); var username = credentials[0] !== undefined ? credentials[0] : ''; var password = credentials[1] !== undefined ? credentials[1] : ''; var userQuery = {mobilenumber: username, otp: password}; console.log(userQuery); User.findOne(userQuery).exec(function (err, userinfo) { if (err || !userinfo) { return res.status(401).send({ message: "Unauthorised access" }); } else { req.user = userinfo; next(); } }); } </code></pre>
<pre><code>new Buffer(number) // Old Buffer.alloc(number) // New </code></pre> <hr> <pre><code>new Buffer(string) // Old Buffer.from(string) // New </code></pre> <hr> <pre><code>new Buffer(string, encoding) // Old Buffer.from(string, encoding) // New </code></pre> <hr> <pre><code>new Buffer(...arguments) // Old Buffer.from(...arguments) // New </code></pre> <hr> <p><strong><em>Note</strong> that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.</em></p>
{ "question_id": 52165333, "question_date": "2018-09-04T11:31:16.433Z", "question_score": 232, "tags": "node.js|npm", "answer_id": 52257416, "answer_date": "2018-09-10T12:05:26.010Z", "answer_score": 566 }
Please answer the following Stack Overflow question: Title: How to Remove Array Element and Then Re-Index Array? <p>I have some troubles with an array. I have one array that I want to modify like below. I want to remove element (elements) of it by index and then re-index array. Is it possible?</p> <pre><code>$foo = array( 'whatever', // [0] 'foo', // [1] 'bar' // [2] ); $foo2 = array( 'foo', // [0], before [1] 'bar' // [1], before [2] ); </code></pre>
<pre><code>unset($foo[0]); // remove item at index 0 $foo2 = array_values($foo); // 'reindex' array </code></pre>
{ "question_id": 5217721, "question_date": "2011-03-07T09:04:20.697Z", "question_score": 232, "tags": "php|arrays|indexing", "answer_id": 5217738, "answer_date": "2011-03-07T09:06:19.947Z", "answer_score": 511 }
Please answer the following Stack Overflow question: Title: Cloning an Object in Node.js <p>What is the best way to clone an object in node.js</p> <p>e.g. I want to avoid the situation where:</p> <pre><code>var obj1 = {x: 5, y:5}; var obj2 = obj1; obj2.x = 6; console.log(obj1.x); // logs 6 </code></pre> <p>The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?</p>
<h2>Possibility 1</h2> <p>Low-frills deep copy:</p> <pre><code>var obj2 = JSON.parse(JSON.stringify(obj1)); </code></pre> <h2>Possibility 2 (deprecated)</h2> <p><strong>Attention:</strong> This solution is now marked as deprecated in the <a href="https://nodejs.org/api/util.html#util_util_extend_target_source" rel="noreferrer">documentation of Node.js</a>:</p> <blockquote> <p>The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.</p> <p>It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().</p> </blockquote> <p><strong>Original answer:</strong>:</p> <p>For a shallow copy, use Node's built-in <code>util._extend()</code> function.</p> <pre><code>var extend = require('util')._extend; var obj1 = {x: 5, y:5}; var obj2 = extend({}, obj1); obj2.x = 6; console.log(obj1.x); // still logs 5 </code></pre> <p>Source code of Node's <code>_extend</code> function is in here: <a href="https://github.com/joyent/node/blob/master/lib/util.js" rel="noreferrer">https://github.com/joyent/node/blob/master/lib/util.js</a></p> <pre><code>exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || typeof add !== 'object') return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; </code></pre>
{ "question_id": 5055746, "question_date": "2011-02-20T07:08:05.317Z", "question_score": 232, "tags": "javascript|node.js", "answer_id": 15040626, "answer_date": "2013-02-23T12:40:28.947Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: SVN Commit specific files <p>Is there any way to commit only a list of specific files (e.q. just one of the list of files that SVN wants to commit).</p> <p>I'm working on MAC OS X under Terminal, without any UI.</p>
<p>Sure. Just list the files:</p> <pre><code>$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png </code></pre> <p>I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:</p> <pre><code>$ svn ci -m "No longer sets printer on fire" printer-driver/*.c </code></pre> <p>You can also have the svn command read the list of files to commit from a file:</p> <pre><code>$ svn ci -m "Now works" --targets fix4711.txt </code></pre>
{ "question_id": 1516188, "question_date": "2009-10-04T11:22:47.890Z", "question_score": 232, "tags": "svn|terminal", "answer_id": 1516189, "answer_date": "2009-10-04T11:24:40.710Z", "answer_score": 350 }
Please answer the following Stack Overflow question: Title: Using generic std::function objects with member functions in one class <p>For one class I want to store some function pointers to member functions of the same class in one <code>map</code> storing <code>std::function</code> objects. But I fail right at the beginning with this code:</p> <pre><code>#include &lt;functional&gt; class Foo { public: void doSomething() {} void bindFunction() { // ERROR std::function&lt;void(void)&gt; f = &amp;Foo::doSomething; } }; </code></pre> <p>I receive <code>error C2064: term does not evaluate to a function taking 0 arguments</code> in <code>xxcallobj</code> combined with some weird template instantiation errors. Currently I am working on Windows 8 with Visual Studio 2010/2011 and on Win 7 with VS10 it fails too. The error must be based on some weird C++ rules i do not follow</p>
<p>A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.</p> <p>Because your <code>std::function</code> signature specifies that your function doesn't take any arguments (<code>&lt;void(void)&gt;</code>), you must <em>bind</em> the first (and the only) argument.</p> <pre><code>std::function&lt;void(void)&gt; f = std::bind(&amp;Foo::doSomething, this); </code></pre> <p>If you want to bind a function with parameters, you need to specify placeholders:</p> <pre><code>using namespace std::placeholders; std::function&lt;void(int,int)&gt; f = std::bind(&amp;Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2); </code></pre> <p>Or, if your compiler supports C++11 lambdas:</p> <pre><code>std::function&lt;void(int,int)&gt; f = [=](int a, int b) { this-&gt;doSomethingArgs(a, b); } </code></pre> <p>(I don't have a C++11 capable compiler at hand <em>right now</em>, so I can't check this one.)</p>
{ "question_id": 7582546, "question_date": "2011-09-28T11:30:16.703Z", "question_score": 232, "tags": "c++|function|function-pointers|c++11|tr1", "answer_id": 7582576, "answer_date": "2011-09-28T11:32:39.700Z", "answer_score": 395 }
Please answer the following Stack Overflow question: Title: Cleanest way to toggle a boolean variable in Java? <p>Is there a better way to negate a boolean in Java than a simple if-else?</p> <pre><code>if (theBoolean) { theBoolean = false; } else { theBoolean = true; } </code></pre>
<pre><code>theBoolean = !theBoolean; </code></pre>
{ "question_id": 224311, "question_date": "2008-10-22T02:44:08.647Z", "question_score": 232, "tags": "java|boolean", "answer_id": 224314, "answer_date": "2008-10-22T02:45:16.757Z", "answer_score": 584 }
Please answer the following Stack Overflow question: Title: How can I count occurrences with groupBy? <p>I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.</p> <pre><code>List&lt;String&gt; list = Arrays.asList(&quot;Hello&quot;, &quot;Hello&quot;, &quot;World&quot;); Map&lt;String, Long&gt; wordToFrequency = // what goes here? </code></pre> <p>So in this case, I would like the map to consist of these entries:</p> <pre><code>Hello -&gt; 2 World -&gt; 1 </code></pre> <p>How can I do that?</p>
<p>I think you're just looking for the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.stream.Collector-" rel="noreferrer">overload</a> which takes another <code>Collector</code> to specify what to do with each group... and then <code>Collectors.counting()</code> to do the counting:</p> <pre><code>import java.util.*; import java.util.stream.*; class Test { public static void main(String[] args) { List&lt;String&gt; list = new ArrayList&lt;&gt;(); list.add("Hello"); list.add("Hello"); list.add("World"); Map&lt;String, Long&gt; counted = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); System.out.println(counted); } } </code></pre> <p>Result:</p> <pre><code>{Hello=2, World=1} </code></pre> <p>(There's also the possibility of using <code>groupingByConcurrent</code> for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)</p>
{ "question_id": 25441088, "question_date": "2014-08-22T06:46:21.183Z", "question_score": 232, "tags": "java|functional-programming|java-8", "answer_id": 25441208, "answer_date": "2014-08-22T06:55:51.077Z", "answer_score": 466 }
Please answer the following Stack Overflow question: Title: Round to 5 (or other number) in Python <p>Is there a built-in function that can round like the following?</p> <pre class="lang-none prettyprint-override"><code>10 -&gt; 10 12 -&gt; 10 13 -&gt; 15 14 -&gt; 15 16 -&gt; 15 18 -&gt; 20 </code></pre>
<p>I don't know of a standard function in Python, but this works for me:</p> <h3>Python 3</h3> <pre><code>def myround(x, base=5): return base * round(x/base) </code></pre> <p>It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (<code>round(x/5)</code>), and then since we divided by 5, we multiply by 5 as well.</p> <p>I made the function more generic by giving it a <code>base</code> parameter, defaulting to 5.</p> <h3>Python 2</h3> <p>In Python 2, <code>float(x)</code> would be needed to ensure that <code>/</code> does floating-point division, and a final conversion to <code>int</code> is needed because <code>round()</code> returns a floating-point value in Python 2.</p> <pre><code>def myround(x, base=5): return int(base * round(float(x)/base)) </code></pre>
{ "question_id": 2272149, "question_date": "2010-02-16T10:35:04.370Z", "question_score": 232, "tags": "python|rounding", "answer_id": 2272174, "answer_date": "2010-02-16T10:38:22.843Z", "answer_score": 431 }
Please answer the following Stack Overflow question: Title: How to get the last element of a slice? <p>What is the Go way for extracting the last element of a slice?</p> <pre><code>var slice []int slice = append(slice, 2) slice = append(slice, 7) slice[len(slice)-1:][0] // Retrieves the last element </code></pre> <p>The solution above works, but seems awkward.</p>
<p>For just reading the last element of a slice:</p> <pre><code>sl[len(sl)-1] </code></pre> <p>For removing it:</p> <pre><code>sl = sl[:len(sl)-1] </code></pre> <p>See this <a href="https://github.com/golang/go/wiki/SliceTricks" rel="noreferrer">page about slice tricks</a></p>
{ "question_id": 22535775, "question_date": "2014-03-20T14:19:36.783Z", "question_score": 232, "tags": "go|slice", "answer_id": 22535888, "answer_date": "2014-03-20T14:24:21.877Z", "answer_score": 414 }
Please answer the following Stack Overflow question: Title: google chrome extension :: console.log() from background page? <p>If I call <code>console.log('something');</code> from the popup page, or any script included off that it works fine.</p> <p>However as the background page is not directly run off the popup page it is not included in the console.</p> <p>Is there a way that I can get <code>console.log()</code>'s in the background page to show up in the console for the popup page?</p> <p>is there any way to, from the background page call a function in the popup page?</p>
<p>Any <em>extension page</em> (except <a href="http://developer.chrome.com/extensions/content_scripts.html" rel="noreferrer">content scripts</a>) has direct access to the background page via <a href="http://developer.chrome.com/extensions/extension.html#method-getBackgroundPage" rel="noreferrer"><code>chrome.extension.getBackgroundPage()</code></a>.</p> <p>That means, within the <a href="http://developer.chrome.com/extensions/browserAction.html" rel="noreferrer">popup page</a>, you can just do:</p> <pre><code>chrome.extension.getBackgroundPage().console.log('foo'); </code></pre> <p>To make it easier to use:</p> <pre><code>var bkg = chrome.extension.getBackgroundPage(); bkg.console.log('foo'); </code></pre> <p>Now if you want to do the same within <a href="http://developer.chrome.com/extensions/content_scripts.html" rel="noreferrer">content scripts</a> you have to use <a href="http://developer.chrome.com/extensions/messaging.html" rel="noreferrer">Message Passing</a> to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the <a href="http://developer.chrome.com/extensions/messaging.html" rel="noreferrer">Message Passing</a> page for you to check out.</p> <p>Hope that clears everything.</p>
{ "question_id": 3829150, "question_date": "2010-09-30T08:59:16.673Z", "question_score": 232, "tags": "javascript|google-chrome|google-chrome-extension", "answer_id": 3830956, "answer_date": "2010-09-30T13:28:09.067Z", "answer_score": 189 }
Please answer the following Stack Overflow question: Title: Invoking a static method using reflection <p>I want to invoke the <code>main</code> method which is static. I got the object of type <code>Class</code>, but I am not able to create an instance of that class and also not able to invoke the <code>static</code> method <code>main</code>.</p>
<pre><code>// String.class here is the parameter type, that might not be the case with you Method method = clazz.getMethod("methodName", String.class); Object o = method.invoke(null, "whatever"); </code></pre> <p>In case the method is private use <code>getDeclaredMethod()</code> instead of <code>getMethod()</code>. And call <code>setAccessible(true)</code> on the method object.</p>
{ "question_id": 2467544, "question_date": "2010-03-18T04:33:58.333Z", "question_score": 232, "tags": "java|reflection|static", "answer_id": 2467562, "answer_date": "2010-03-18T04:41:05.897Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: Verifying a specific parameter with Moq <pre><code>public void SubmitMessagesToQueue_OneMessage_SubmitSuccessfully() { var messageServiceClientMock = new Mock&lt;IMessageServiceClient&gt;(); var queueableMessage = CreateSingleQueueableMessage(); var message = queueableMessage[0]; var xml = QueueableMessageAsXml(queueableMessage); messageServiceClientMock.Setup(proxy =&gt; proxy.SubmitMessage(xml)).Verifiable(); //messageServiceClientMock.Setup(proxy =&gt; proxy.SubmitMessage(It.IsAny&lt;XmlElement&gt;())).Verifiable(); var serviceProxyFactoryStub = new Mock&lt;IMessageServiceClientFactory&gt;(); serviceProxyFactoryStub.Setup(proxyFactory =&gt; proxyFactory.CreateProxy()).Returns(essageServiceClientMock.Object); var loggerStub = new Mock&lt;ILogger&gt;(); var client = new MessageClient(serviceProxyFactoryStub.Object, loggerStub.Object); client.SubmitMessagesToQueue(new List&lt;IMessageRequestDTO&gt; {message}); //messageServiceClientMock.Verify(proxy =&gt; proxy.SubmitMessage(xml), Times.Once()); messageServiceClientMock.Verify(); } </code></pre> <p>I'm starting using Moq and struggling a bit. I'm trying to verify that messageServiceClient is receiving the right parameter, which is an XmlElement, but I can't find any way to make it work. It works only when I don't check a particular value.</p> <p>Any ideas?</p> <p>Partial answer: I've found a way to test that the xml sent to the proxy is correct, but I still don't think it's the right way to do it.</p> <pre><code>public void SubmitMessagesToQueue_OneMessage_SubmitSuccessfully() { var messageServiceClientMock = new Mock&lt;IMessageServiceClient&gt;(); messageServiceClientMock.Setup(proxy =&gt; proxy.SubmitMessage(It.IsAny&lt;XmlElement&gt;())).Verifiable(); var serviceProxyFactoryStub = new Mock&lt;IMessageServiceClientFactory&gt;(); serviceProxyFactoryStub.Setup(proxyFactory =&gt; proxyFactory.CreateProxy()).Returns(messageServiceClientMock.Object); var loggerStub = new Mock&lt;ILogger&gt;(); var client = new MessageClient(serviceProxyFactoryStub.Object, loggerStub.Object); var message = CreateMessage(); client.SubmitMessagesToQueue(new List&lt;IMessageRequestDTO&gt; {message}); messageServiceClientMock.Verify(proxy =&gt; proxy.SubmitMessage(It.Is&lt;XmlElement&gt;(xmlElement =&gt; XMLDeserializer&lt;QueueableMessage&gt;.Deserialize(xmlElement).Messages.Contains(message))), Times.Once()); } </code></pre> <p>By the way, how could I extract the expression from the Verify call?</p>
<p>If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code. </p> <p>Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard <code>Assert</code> methods to validate it. For example:</p> <pre><code>// Arrange MyObject saveObject; mock.Setup(c =&gt; c.Method(It.IsAny&lt;int&gt;(), It.IsAny&lt;MyObject&gt;())) .Callback&lt;int, MyObject&gt;((i, obj) =&gt; saveObject = obj) .Returns("xyzzy"); // Act // ... // Assert // Verify Method was called once only mock.Verify(c =&gt; c.Method(It.IsAny&lt;int&gt;(), It.IsAny&lt;MyObject&gt;()), Times.Once()); // Assert about saveObject Assert.That(saveObject.TheProperty, Is.EqualTo(2)); </code></pre>
{ "question_id": 4956974, "question_date": "2011-02-10T12:19:10.853Z", "question_score": 232, "tags": "c#|unit-testing|nunit|moq", "answer_id": 4963632, "answer_date": "2011-02-10T22:51:00.050Z", "answer_score": 331 }
Please answer the following Stack Overflow question: Title: What is a tracking branch? <p>Can someone explain a "tracking branch" as it applies to git?</p> <p>Here's the definition from <a href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches" rel="noreferrer">git-scm.com</a>:</p> <blockquote> <p>A 'tracking branch' in Git is a local branch that is connected to a remote branch. When you push and pull on that branch, it automatically pushes and pulls to the remote branch that it is connected with.</p> <p>Use this if you always pull from the same upstream branch into the new branch, and if you don't want to use "git pull" explicitly.</p> </blockquote> <p>Unfortunately, being new to git and coming from SVN, that definition makes absolutely no sense to me.</p> <p>I'm reading through "<a href="http://www.pragprog.com/titles/pg_git/pragmatic-guide-to-git" rel="noreferrer">The Pragmatic Guide to Git</a>" (great book, by the way), and they seem to suggest that tracking branches are a good thing and that after creating your first remote (origin, in this case), you should set up your master branch to be a tracking branch, but it unfortunately doesn't cover <em>why a tracking branch is a good thing</em> or <em>what benefits you get by setting up your master branch to be a tracking branch of your origin repository</em>.</p> <p>Can someone please enlighten me (in English)?</p>
<p>The <a href="http://git-scm.com/book" rel="nofollow noreferrer">ProGit book</a> has <a href="http://git-scm.com/book/en/Git-Branching-Remote-Branches#_tracking_branches" rel="nofollow noreferrer">a very good explanation</a>:</p> <p><strong>Tracking Branches</strong></p> <p>Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type <code>git push</code>, Git automatically knows which server and branch to push to. Also, running <code>git pull</code> while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch.</p> <p>When you clone a repository, it generally automatically creates a master branch that tracks origin/master. That’s why <code>git push</code> and <code>git pull</code> work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on origin and don’t track the master branch. The simple case is the example you just saw, running <code>git checkout -b [branch] [remotename]/[branch]</code>. If you have Git version 1.6.2 or later, you can also use the <code>--track</code> shorthand:</p> <pre><code>$ git checkout --track origin/serverfix Branch serverfix set up to track remote branch refs/remotes/origin/serverfix. Switched to a new branch &quot;serverfix&quot; </code></pre> <p>To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:</p> <pre><code>$ git checkout -b sf origin/serverfix Branch sf set up to track remote branch refs/remotes/origin/serverfix. Switched to a new branch &quot;sf&quot; </code></pre> <p>Now, your local branch <code>sf</code> will automatically push to and pull from <code>origin/serverfix</code>.</p> <p><strong>BONUS: extra <code>git status</code> info</strong></p> <p>With a tracking branch, <code>git status</code> will tell you how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:</p> <pre><code>$ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use &quot;git push&quot; to publish your local commits) </code></pre> <p>or</p> <pre><code>$ git status On branch dev Your branch and 'origin/dev' have diverged, and have 3 and 1 different commits each, respectively. (use &quot;git pull&quot; to merge the remote branch into yours) </code></pre>
{ "question_id": 4693588, "question_date": "2011-01-14T16:50:26.767Z", "question_score": 232, "tags": "git|version-control|branch", "answer_id": 4693780, "answer_date": "2011-01-14T17:07:09.280Z", "answer_score": 197 }
Please answer the following Stack Overflow question: Title: Change a column type from Date to DateTime during ROR migration <p>I need to change my column type from date to datetime for an app I am making. I don't care about the data as its still being developed.</p> <p>How can I do this? </p>
<p>First in your terminal:</p> <pre><code>rails g migration change_date_format_in_my_table </code></pre> <p>Then in your migration file:</p> <p>For Rails >= 3.2:</p> <pre><code>class ChangeDateFormatInMyTable &lt; ActiveRecord::Migration def up change_column :my_table, :my_column, :datetime end def down change_column :my_table, :my_column, :date end end </code></pre>
{ "question_id": 5191405, "question_date": "2011-03-04T08:36:59.610Z", "question_score": 232, "tags": "mysql|ruby-on-rails|ruby|ruby-on-rails-3|migration", "answer_id": 5191453, "answer_date": "2011-03-04T08:42:03.403Z", "answer_score": 513 }
Please answer the following Stack Overflow question: Title: How does one capture a Mac's command key via JavaScript? <p>How does one capture a Mac's <kbd>Cmd</kbd> key via JavaScript?</p>
<p><strong>EDIT:</strong> As of 2019, <code>e.metaKey</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/metaKey" rel="noreferrer">supported on all major browsers as per the MDN</a>.</p> <p>Note that on Windows, although the <kbd>⊞ Windows</kbd> key is considered to be the "meta" key, it is not going to be captured by browsers as such.</p> <p>This is only for the command key on MacOS/keyboards.</p> <hr> <p>Unlike <kbd>Shift</kbd>/<kbd>Alt</kbd>/<kbd>Ctrl</kbd>, the <kbd>Cmd</kbd> (“Apple”) key is not considered a modifier key—instead, you should listen on <code>keydown</code>/<code>keyup</code> and record when a key is pressed and then depressed based on <code>event.keyCode</code>.</p> <p>Unfortunately, these key codes are browser-dependent:</p> <ul> <li>Firefox: <code>224</code></li> <li>Opera: <code>17</code></li> <li>WebKit browsers (Safari/Chrome): <code>91</code> (Left Command) or <code>93</code> (Right Command)</li> </ul> <p>You might be interested in reading the article <a href="http://unixpapa.com/js/key.html" rel="noreferrer">JavaScript Madness: Keyboard Events</a>, from which I learned that knowledge.</p>
{ "question_id": 3902635, "question_date": "2010-10-10T23:26:47.193Z", "question_score": 232, "tags": "javascript|dom-events", "answer_id": 3922353, "answer_date": "2010-10-13T09:38:33.137Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: Is there a difference between using a dict literal and a dict constructor? <p>Using PyCharm, I noticed it offers to convert a <strong>dict literal</strong>:</p> <pre><code>d = { 'one': '1', 'two': '2', } </code></pre> <p></p></p> <p>into a <strong>dict constructor</strong>:</p> <pre><code>d = dict(one='1', two='2') </code></pre> <p></p></p> <p><strong>Do these different approaches differ in some significant way?</strong></p> <p>(While writing this question I noticed that using <code>dict()</code> it seems impossible to specify a numeric key .. <code>d = {1: 'one', 2: 'two'}</code> is possible, but, obviously, <code>dict(1='one' ...)</code> is not. Anything else?)</p>
<p>I think you have pointed out the most obvious difference. Apart from that, </p> <p>the first doesn't need to lookup <code>dict</code> which should make it a tiny bit faster </p> <p>the second looks up <code>dict</code> in <code>locals()</code> and then <code>globals()</code> and the finds the builtin, so you can switch the behaviour by defining a local called <code>dict</code> for example although I can't think of anywhere this would be a good idea apart from maybe when debugging</p>
{ "question_id": 6610606, "question_date": "2011-07-07T12:29:41.863Z", "question_score": 232, "tags": "python|dictionary|pycharm", "answer_id": 6610783, "answer_date": "2011-07-07T12:43:37.753Z", "answer_score": 131 }
Please answer the following Stack Overflow question: Title: Different CUDA versions shown by nvcc and NVIDIA-smi <p>I am very confused by the different CUDA versions shown by running <code>which nvcc</code> and <code>nvidia-smi</code>. I have both cuda9.2 and cuda10 installed on my ubuntu 16.04. Now I set the PATH to point to cuda9.2. So when I run</p> <pre class="lang-sh prettyprint-override"><code>$ which nvcc /usr/local/cuda-9.2/bin/nvcc </code></pre> <p>However, when I run</p> <pre><code>$ nvidia-smi Wed Nov 21 19:41:32 2018 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 410.72 Driver Version: 410.72 CUDA Version: 10.0 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 106... Off | 00000000:01:00.0 Off | N/A | | N/A 53C P0 26W / N/A | 379MiB / 6078MiB | 2% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1324 G /usr/lib/xorg/Xorg 225MiB | | 0 2844 G compiz 146MiB | | 0 15550 G /usr/lib/firefox/firefox 1MiB | | 0 19992 G /usr/lib/firefox/firefox 1MiB | | 0 23605 G /usr/lib/firefox/firefox 1MiB | </code></pre> <p>So am I using cuda9.2 as <code>which nvcc</code> suggests, or am I using cuda10 as <code>nvidia-smi</code> suggests? I <a href="https://stackoverflow.com/questions/34319877/nvcc-has-different-version-than-cuda">saw this answer</a> but it does not provide direct answer to the confusion, it just asks us to reinstall the CUDA Toolkit, which I already did.</p>
<p>CUDA has 2 primary APIs, the runtime and the driver API. Both have a corresponding version (e.g. 8.0, 9.0, etc.)</p> <p>The necessary support for the driver API (e.g. <code>libcuda.so</code> on linux) is installed by the GPU driver installer.</p> <p>The necessary support for the runtime API (e.g. <code>libcudart.so</code> on linux, and also <code>nvcc</code>) is installed by the CUDA toolkit installer (which may also have a GPU driver installer bundled in it).</p> <p>In any event, the (installed) driver API version may not always match the (installed) runtime API version, especially if you install a GPU driver independently from installing CUDA (i.e. the CUDA toolkit).</p> <p>The <code>nvidia-smi</code> tool gets installed by the GPU driver installer, and generally has the GPU driver in view, not anything installed by the CUDA toolkit installer.</p> <p>Recently (somewhere between 410.48 and 410.73 driver version on linux) the powers-that-be at NVIDIA decided to add reporting of the CUDA Driver API version installed by the driver, in the output from <code>nvidia-smi</code>.</p> <p>This has no connection to the installed CUDA runtime version.</p> <p><code>nvcc</code>, the CUDA compiler-driver tool that is installed with the CUDA toolkit, will always report the CUDA runtime version that it was built to recognize. It doesn't know anything about what driver version is installed, or even if a GPU driver is installed.</p> <p>Therefore, by design, these two numbers don't necessarily match, as they are reflective of two different things.</p> <p>If you are wondering why <code>nvcc -V</code> displays a version of CUDA you weren't expecting (e.g. it displays a version other than the one you think you installed) or doesn't display anything at all, version wise, it may be because you haven't followed the mandatory instructions in step 7 (prior to CUDA 11) (or step 6 in the CUDA 11 linux install guide) of the <a href="https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#post-installation-actions" rel="nofollow noreferrer">cuda linux install guide</a></p> <p>Note that although this question mostly has linux in view, the same concepts apply to <strong>windows</strong> CUDA installs. The driver has a CUDA driver version associated with it (which can be queried with <code>nvidia-smi</code>, for example). The CUDA runtime also has a CUDA runtime version associated with it. The two will not necessarily match in all cases.</p> <p>In most cases, if <code>nvidia-smi</code> reports a CUDA version that is numerically equal to or higher than the one reported by <code>nvcc -V</code>, this is not a cause for concern. That is a defined compatibility path in CUDA (newer drivers/driver API support &quot;older&quot; CUDA toolkits/runtime API). For example if <code>nvidia-smi</code> reports CUDA 10.2, and <code>nvcc -V</code> reports CUDA 10.1, that is generally not cause for concern. It should just work, and it does not necessarily mean that you &quot;actually installed CUDA 10.2 when you meant to install CUDA 10.1&quot;</p> <p>If <code>nvcc</code> command doesn't report anything at all (e.g. <code>Command 'nvcc' not found...</code>) or if it reports an unexpected CUDA version, this may also be due to an incorrect CUDA install, i.e the mandatory steps mentioned above were not performed correctly. You can start to figure this out by using a linux utility like <code>find</code> or <code>locate</code> (use man pages to learn how, please) to find your <code>nvcc</code> executable. Assuming there is only one, the path to it can then be used to fix your PATH environment variable. The <a href="https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#mandatory-post" rel="nofollow noreferrer">CUDA linux install guide</a> also explains how to set this. You may need to adjust the CUDA version in the PATH variable to match your actual CUDA version desired/installed.</p> <p>Similarly, when using docker, the <code>nvidia-smi</code> command will generally report the driver version installed on the base machine, whereas other version methods like <code>nvcc --version</code> will report the CUDA version installed inside the docker container.</p> <p>Similarly, if you have used another installation method for the CUDA &quot;toolkit&quot; such as Anaconda, you may discover that the version indicated by Anaconda does not &quot;match&quot; the version indicated by <code>nvidia-smi</code>. However, the above comments still apply. Older CUDA toolkits installed by Anaconda can be used with newer versions reported by <code>nvidia-smi</code>, and the fact that <code>nvidia-smi</code> reports a newer/higher CUDA version than the one installed by Anaconda does not mean you have an installation problem.</p> <p><a href="https://stackoverflow.com/questions/70048525/why-does-python-show-a-wrong-cuda-version">Here</a> is another question that covers similar ground. The above treatment does not in any way indicate that this answer is only applicable if you have installed multiple CUDA versions intentionally or unintentionally. The situation presents itself <em>any time you install CUDA</em>. The version reported by <code>nvcc</code> and <code>nvidia-smi</code> may not match, and that is <strong>expected</strong> behavior and in most cases quite normal.</p>
{ "question_id": 53422407, "question_date": "2018-11-22T00:44:01.010Z", "question_score": 232, "tags": "cuda", "answer_id": 53504578, "answer_date": "2018-11-27T16:57:32.897Z", "answer_score": 302 }
Please answer the following Stack Overflow question: Title: Differences between fork and exec <p>What are the differences between <code>fork</code> and <code>exec</code>?</p>
<p>The use of <code>fork</code> and <code>exec</code> exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.</p> <p>The <code>fork</code> call basically makes a duplicate of the current process, identical in <em>almost</em> every way. Not everything is copied over (for example, resource limits in some implementations) but the idea is to create as close a copy as possible.</p> <p>The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of <code>fork</code> - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the <code>fork</code> call works - if not, no child is created and the parent gets an error code.</p> <p>The <code>exec</code> call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.</p> <p>So, <code>fork</code> and <code>exec</code> are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like <code>find</code> - the shell forks, then the child loads the <code>find</code> program into memory, setting up all command line arguments, standard I/O and so forth.</p> <p>But they're not required to be used together. It's perfectly acceptable for a program to <code>fork</code> itself without <code>exec</code>ing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port and <code>fork</code> a copy of themselves to process a specific request while the parent goes back to listening.</p> <p>Similarly, programs that know they're finished and just want to run another program don't need to <code>fork</code>, <code>exec</code> and then <code>wait</code> for the child. They can just load the child directly into their process space.</p> <p>Some UNIX implementations have an optimized <code>fork</code> which uses what they call copy-on-write. This is a trick to delay the copying of the process space in <code>fork</code> until the program attempts to change something in that space. This is useful for those programs using only <code>fork</code> and not <code>exec</code> in that they don't have to copy an entire process space.</p> <p>If the <code>exec</code> <em>is</em> called following <code>fork</code> (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.</p> <p>Note that there is a whole family of <code>exec</code> calls (<code>execl</code>, <code>execle</code>, <code>execve</code> and so on) but <code>exec</code> in context here means any of them.</p> <p>The following diagram illustrates the typical <code>fork/exec</code> operation where the <code>bash</code> shell is used to list a directory with the <code>ls</code> command:</p> <pre><code>+--------+ | pid=7 | | ppid=4 | | bash | +--------+ | | calls fork V +--------+ +--------+ | pid=7 | forks | pid=22 | | ppid=4 | ----------&gt; | ppid=7 | | bash | | bash | +--------+ +--------+ | | | waits for pid 22 | calls exec to run ls | V | +--------+ | | pid=22 | | | ppid=7 | | | ls | V +--------+ +--------+ | | pid=7 | | exits | ppid=4 | &lt;---------------+ | bash | +--------+ | | continues V </code></pre>
{ "question_id": 1653340, "question_date": "2009-10-31T03:47:33.143Z", "question_score": 232, "tags": "c|unix|fork|exec", "answer_id": 1653415, "answer_date": "2009-10-31T04:31:25.070Z", "answer_score": 411 }
Please answer the following Stack Overflow question: Title: Visual Studio 2012 Web Publish doesn't copy files <p>I have a Web Application project in VS 2012 and when I use the web publishing tool it builds successfully but doesn't copy any files to the publish target (File System in this case).</p> <p>If I look at the build output I can see everything gets copied over to obj\Release\Package\PackageTmp\ correctly but then all I see in the build output is this:</p> <blockquote> <p>4>Done building project "{Project}.csproj".<br> 4>Deleting existing files...<br> 4>Publishing folder /...<br> 4> ========== Build: 3 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========<br> ========== Publish: 1 succeeded, 0 failed, 0 skipped ==========</p> </blockquote> <p>Even though it says the publish succeeded there are not files in the target directory for the publish.</p> <p>I have seen this in multiple projects and sometimes it seems like the Solution/Platform configurations cause this problem but I haven't been able to pinpoint an exact cause for this.</p> <p>Has anyone else seen this happening or have an idea on how to get this working correctly?</p> <p><strong>UPDATE:</strong></p> <p>I may have found a workaround for this. I just had this happen again and I was messing around with the publish settings. Once I changed the selected Configuration on the Settings tab away to another configuration and then back to the one I wanted to use all my files started publishing again. Hopefully this works on other projects in the future. </p> <p><strong>UPDATE 2:</strong></p> <p>I posted a bug on Microsoft Connect and heard back from a developer on the VS Web Developer team. He said they have fixed this issue in their internal builds and will releasing an update to the publish tool soon that will fix this problem.</p> <p><strong>UPDATE 3:</strong></p> <p>This has been recently fixed with Visual Studio 2012 Update 2</p>
<p>This may be caused by solutions/projects that were created with the RC of vs2012. This happened to me months ago and fixed the problem by making sure my solution build configurations matched my project configurations...</p> <p>I just recently experienced the same problem when opening the same solution originally created in vs2012RC with VS2012 Express for Web. I did exactly what the original poster suggested and it fixed my problem.</p> <p>Here is the thread that lead me to the answer:</p> <p><a href="http://connect.microsoft.com/VisualStudio/feedback/details/746321/publish-web-application-fails">connect.microsoft.com/VisualStudio/feedback/details/746321/publish-web-application-fails</a></p> <p>The pertinent response from the conversation above that helped me was:</p> <blockquote> <p>Posted by Microsoft on 6/13/2012 at 12:00 PM Hi Andrew,</p> <p>This was a bug in how we handle the solution configuration vs. the project configuration. We incorrectly assumed that they would be the same (e.g. Solution's Release|x86 would have each project set to Release|x86 as well), which caused us to use the wrong build properties for publishing files.</p> <p>The workaround is to make the solution configuration and build configuration match. This issue will be fixed in the next release of Visual Studio 2012.</p> <p>Thanks, - Jimmy Lewis SDET, Visual Web Developer team</p> </blockquote>
{ "question_id": 12201146, "question_date": "2012-08-30T16:10:21.373Z", "question_score": 232, "tags": "asp.net|asp.net-mvc|visual-studio-2012|msbuild-wpp|visual-studio-publish", "answer_id": 12505312, "answer_date": "2012-09-20T02:22:10.697Z", "answer_score": 78 }
Please answer the following Stack Overflow question: Title: How does Junit @Rule work? <p>I want to write test cases for a bulk of code, I would like to know details of JUnit <code>@Rule</code> annotation feature, so that I can use it for writing test cases. Please provide some good answers or links, which give detailed description of its functionality through a simple example.</p>
<p>Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.</p> <p>For instance, <a href="https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/rules/ExternalResource.java" rel="noreferrer">ExternalResource</a> executes code before and after a test method, without having to use <code>@Before</code> and <code>@After</code>. Using an <code>ExternalResource</code> rather than <code>@Before</code> and <code>@After</code> gives opportunities for better code reuse; the same rule can be used from two different test classes.</p> <p>The design was based upon: <a href="https://web.archive.org/web/20130429055253/http://www.threeriversinstitute.org/blog/?p=155" rel="noreferrer">Interceptors in JUnit</a></p> <p>For more information see <a href="https://github.com/junit-team/junit/wiki/Rules" rel="noreferrer">JUnit wiki : Rules</a>.</p>
{ "question_id": 13489388, "question_date": "2012-11-21T08:45:39.273Z", "question_score": 232, "tags": "java|junit|junit4|junit-rule", "answer_id": 13489506, "answer_date": "2012-11-21T08:53:39.190Z", "answer_score": 168 }
Please answer the following Stack Overflow question: Title: Add st, nd, rd and th (ordinal) suffix to a number <p>I would like to dynamically generate a string of text based on a current day. So, for example, if it is day 1 then I would like my code to generate = "Its the &lt;dynamic&gt;1*&lt;dynamic string&gt;<em>st</em>&lt;/dynamic string&gt;*&lt;/dynamic&gt;".</p> <p>There are 12 days in total so I have done the following:</p> <ol> <li><p>I've set up a for loop which loops through the 12 days.</p></li> <li><p>In my html I have given my element a unique id with which to target it, see below:</p> <pre><code>&lt;h1 id="dynamicTitle" class="CustomFont leftHeading shadow"&gt;On The &lt;span&gt;&lt;/span&gt; &lt;em&gt;of rest of generic text&lt;/em&gt;&lt;/h1&gt; </code></pre></li> <li><p>Then, inside my for loop I have the following code:</p> <pre><code>$("#dynamicTitle span").html(i); var day = i; if (day == 1) { day = i + "st"; } else if (day == 2) { day = i + "nd" } else if (day == 3) { day = i + "rd" } </code></pre></li> </ol> <p><em>UPDATE</em></p> <p>This is the entire for loop as requested:</p> <pre><code>$(document).ready(function () { for (i = 1; i &lt;= 12; i++) { var classy = ""; if (daysTilDate(i + 19) &gt; 0) { classy = "future"; $("#Day" + i).addClass(classy); $("#mainHeading").html(""); $("#title").html(""); $("#description").html(""); } else if (daysTilDate(i + 19) &lt; 0) { classy = "past"; $("#Day" + i).addClass(classy); $("#title").html(""); $("#description").html(""); $("#mainHeading").html(""); $(".cta").css('display', 'none'); $("#Day" + i + " .prizeLink").attr("href", "" + i + ".html"); } else { classy = "current"; $("#Day" + i).addClass(classy); $("#title").html(headings[i - 1]); $("#description").html(descriptions[i - 1]); $(".cta").css('display', 'block'); $("#dynamicImage").attr("src", ".." + i + ".jpg"); $("#mainHeading").html(""); $(".claimPrize").attr("href", "" + i + ".html"); $("#dynamicTitle span").html(i); var day = i; if (day == 1) { day = i + "st"; } else if (day == 2) { day = i + "nd" } else if (day == 3) { day = i + "rd" } else if (day) { } } } </code></pre>
<p>The <a href="http://en.wikipedia.org/wiki/Ordinal_indicator#English" rel="noreferrer">rules</a> are as follows:</p> <blockquote> <ul> <li>st is used with numbers ending in 1 (e.g. 1st, pronounced first)</li> <li>nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)</li> <li>rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)</li> <li>As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)</li> <li>th is used for all other numbers (e.g. 9th, pronounced ninth).</li> </ul> </blockquote> <p>The following JavaScript code (rewritten in Jun '14) accomplishes this:</p> <pre><code>function ordinal_suffix_of(i) { var j = i % 10, k = i % 100; if (j == 1 &amp;&amp; k != 11) { return i + "st"; } if (j == 2 &amp;&amp; k != 12) { return i + "nd"; } if (j == 3 &amp;&amp; k != 13) { return i + "rd"; } return i + "th"; } </code></pre> <p>Sample output for numbers between 0-115:</p> <pre><code> 0 0th 1 1st 2 2nd 3 3rd 4 4th 5 5th 6 6th 7 7th 8 8th 9 9th 10 10th 11 11th 12 12th 13 13th 14 14th 15 15th 16 16th 17 17th 18 18th 19 19th 20 20th 21 21st 22 22nd 23 23rd 24 24th 25 25th 26 26th 27 27th 28 28th 29 29th 30 30th 31 31st 32 32nd 33 33rd 34 34th 35 35th 36 36th 37 37th 38 38th 39 39th 40 40th 41 41st 42 42nd 43 43rd 44 44th 45 45th 46 46th 47 47th 48 48th 49 49th 50 50th 51 51st 52 52nd 53 53rd 54 54th 55 55th 56 56th 57 57th 58 58th 59 59th 60 60th 61 61st 62 62nd 63 63rd 64 64th 65 65th 66 66th 67 67th 68 68th 69 69th 70 70th 71 71st 72 72nd 73 73rd 74 74th 75 75th 76 76th 77 77th 78 78th 79 79th 80 80th 81 81st 82 82nd 83 83rd 84 84th 85 85th 86 86th 87 87th 88 88th 89 89th 90 90th 91 91st 92 92nd 93 93rd 94 94th 95 95th 96 96th 97 97th 98 98th 99 99th 100 100th 101 101st 102 102nd 103 103rd 104 104th 105 105th 106 106th 107 107th 108 108th 109 109th 110 110th 111 111th 112 112th 113 113th 114 114th 115 115th </code></pre>
{ "question_id": 13627308, "question_date": "2012-11-29T13:53:13.727Z", "question_score": 232, "tags": "javascript|jquery|numbers", "answer_id": 13627586, "answer_date": "2012-11-29T14:09:18.343Z", "answer_score": 488 }
Please answer the following Stack Overflow question: Title: What is the difference between a pandas Series and a single-column DataFrame? <p>Why does pandas make a distinction between a <code>Series</code> and a single-column <code>DataFrame</code>?<br> In other words: what is the reason of existence of the <code>Series</code> class? </p> <p>I'm mainly using time series with datetime index, maybe that helps to set the context. </p>
<p>Quoting the <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html" rel="noreferrer">Pandas docs</a></p> <blockquote> <p><code>pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)</code></p> <p>Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. <strong>Can be thought of as a dict-like container for Series objects.</strong> The primary pandas data structure.</p> </blockquote> <p>So, the <strong>Series is the data structure for a single column of a <code>DataFrame</code></strong>, not only conceptually, but literally, i.e. the data in a <code>DataFrame</code> is actually stored in memory as a collection of <code>Series</code>.</p> <p>Analogously: <em>We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.</em></p> <p>They both have extremely similar APIs, but you'll find that <code>DataFrame</code> methods always cater to the possibility that you have more than one column. And, of course, you can always add another <code>Series</code> (or equivalent object) to a <code>DataFrame</code>, while adding a <code>Series</code> to another <code>Series</code> involves creating a <code>DataFrame</code>.</p>
{ "question_id": 26047209, "question_date": "2014-09-25T20:09:21.210Z", "question_score": 232, "tags": "python|pandas", "answer_id": 26240208, "answer_date": "2014-10-07T15:55:09.320Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: How to copy a selection to the OS X clipboard <p>I have an area selected in Vim. How can I copy it into the OS X clipboard?</p> <p>(The OS X clipboard can be written to via a pipe to <code>/usr/bin/pbcopy</code>)</p>
<p>Depending on which version of Vim I use, I'm able to use the <code>+</code> register to access the clipboard.</p> <p>"<a href="http://vim.wikia.com/wiki/Mac_OS_X_clipboard_sharing" rel="noreferrer">Mac OS X clipboard sharing</a>" may have some ideas that work for you as well.</p>
{ "question_id": 677986, "question_date": "2009-03-24T15:41:23.783Z", "question_score": 232, "tags": "macos|vim|clipboard", "answer_id": 678011, "answer_date": "2009-03-24T15:45:45.490Z", "answer_score": 84 }
Please answer the following Stack Overflow question: Title: string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string) <p>Is use of <code>string.IsNullOrEmpty(string)</code> when checking a string considered as bad practice when there is <code>string.IsNullOrWhiteSpace(string)</code> in .NET 4.0 and above?</p>
<p>The best practice is selecting the most appropriate one.</p> <blockquote> <p>.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.</p> <p><strong>The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*</strong>. </p> </blockquote> <p>Reference : <a href="http://weblogs.asp.net/gunnarpeipman/archive/2009/10/25/net-framework-4-0-string-isnullorwhitespace-method.aspx" rel="noreferrer">Here</a></p> <blockquote> <p>For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.</p> </blockquote> <p>Reference : <a href="http://www.dotnetperls.com/isnullorwhitespace" rel="noreferrer">Here</a></p> <p><strong>Check the source code</strong> (Reference Source .NET Framework 4.6.2)</p> <p><a href="http://referencesource.microsoft.com/#mscorlib/system/string.cs,23a8597f842071f4" rel="noreferrer">IsNullorEmpty</a> </p> <pre><code>[Pure] public static bool IsNullOrEmpty(String value) { return (value == null || value.Length == 0); } </code></pre> <p><a href="http://referencesource.microsoft.com/#mscorlib/system/string.cs,55e241b6143365ef" rel="noreferrer">IsNullOrWhiteSpace</a></p> <pre><code>[Pure] public static bool IsNullOrWhiteSpace(String value) { if (value == null) return true; for(int i = 0; i &lt; value.Length; i++) { if(!Char.IsWhiteSpace(value[i])) return false; } return true; } </code></pre> <p><strong>Examples</strong></p> <pre><code>string nullString = null; string emptyString = ""; string whitespaceString = " "; string nonEmptyString = "abc123"; bool result; result = String.IsNullOrEmpty(nullString); // true result = String.IsNullOrEmpty(emptyString); // true result = String.IsNullOrEmpty(whitespaceString); // false result = String.IsNullOrEmpty(nonEmptyString); // false result = String.IsNullOrWhiteSpace(nullString); // true result = String.IsNullOrWhiteSpace(emptyString); // true result = String.IsNullOrWhiteSpace(whitespaceString); // true result = String.IsNullOrWhiteSpace(nonEmptyString); // false </code></pre>
{ "question_id": 6976597, "question_date": "2011-08-07T23:45:22.093Z", "question_score": 232, "tags": "c#|.net|string", "answer_id": 6976641, "answer_date": "2011-08-07T23:56:36.613Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: Auto-loading lib files in Rails 4 <p>I use the following line in an initializer to autoload code in my <code>/lib</code> directory during development:</p> <p><strong>config/initializers/custom.rb:</strong> </p> <pre><code>RELOAD_LIBS = Dir[Rails.root + 'lib/**/*.rb'] if Rails.env.development? </code></pre> <p>(from <a href="https://web.archive.org/web/20160407135313/http://www.hemju.com/2011/02/rails-3-quicktip-auto-reload-lib-folders-in-development-mode/" rel="noreferrer">Rails 3 Quicktip: Auto reload lib folders in development mode</a>)</p> <p>It works great, but it's too inefficient to use in production- Instead of loading libs on each request, I just want to load them on start up. The same blog has <a href="https://web.archive.org/web/20130830141432/http://hemju.com:80/index.php/2010/09/rails-3-quicktip-autoload-lib-directory-including-all-subdirectories/" rel="noreferrer">another article</a> describing how to do this:</p> <p><strong>config/application.rb:</strong> </p> <pre><code># Custom directories with classes and modules you want to be autoloadable. config.autoload_paths += %W(#{config.root}/lib) config.autoload_paths += Dir["#{config.root}/lib/**/"] </code></pre> <p>However, when I switch to that, even in development, I get NoMethodErrors when trying to use the lib functions.</p> <p>Example of one of my lib files:</p> <p><strong>lib/extensions.rb:</strong></p> <pre><code>Time.class_eval do def self.milli_stamp Time.now.strftime('%Y%m%d%H%M%S%L').to_i end end </code></pre> <p>Calling <code>Time.milli_stamp</code> will throw NoMethodError</p> <p>I realize others have answered similar questions on SO but they all seem to deal with naming conventions and other issues that I didn't to have to worry about before- My lib classes already <em>worked</em> for per-request loading, I just want to change it to per-<em>startup</em> loading. What's the right way to do this?</p>
<p>I think this may solve your problem:</p> <ol> <li><p>in <strong>config/application.rb</strong>:</p> <pre><code>config.autoload_paths &lt;&lt; Rails.root.join('lib') </code></pre> <p>and keep the right naming convention in <strong>lib</strong>.</p> <p>in <strong>lib/foo.rb</strong>:</p> <pre><code>class Foo end </code></pre> <p>in <strong>lib/foo/bar.rb</strong>:</p> <pre><code>class Foo::Bar end </code></pre></li> <li><p>if you really wanna do some monkey patches in file like <strong>lib/extensions.rb</strong>, you may manually require it:</p> <p>in <strong>config/initializers/require.rb</strong>:</p> <pre><code>require "#{Rails.root}/lib/extensions" </code></pre></li> </ol> <p><strong>P.S.</strong> </p> <ul> <li><p><a href="https://bill.harding.blog/2011/02/23/rails-3-autoload-modules-and-classes-in-production/" rel="noreferrer">Rails 3 Autoload Modules/Classes</a> by Bill Harding.</p></li> <li><p>And to understand what does Rails exactly do about auto-loading?<br> read <a href="https://urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell/#fn1" rel="noreferrer">Rails autoloading — how it works, and when it doesn't</a> by Simon Coffey.</p></li> </ul>
{ "question_id": 19098663, "question_date": "2013-09-30T15:58:44.077Z", "question_score": 232, "tags": "ruby-on-rails|ruby-on-rails-4", "answer_id": 19650564, "answer_date": "2013-10-29T05:41:39.967Z", "answer_score": 550 }
Please answer the following Stack Overflow question: Title: How to replace a hash key with another key <p>I have a condition where, I get a hash </p> <pre><code> hash = {"_id"=&gt;"4de7140772f8be03da000018", .....} </code></pre> <p>and I want this hash as</p> <pre><code> hash = {"id"=&gt;"4de7140772f8be03da000018", ......} </code></pre> <p><strong>P.S</strong>: I don't know what are the keys in the hash, they are random which comes with an "_" prefix for every key and I want no underscores</p>
<pre><code>hash[:new_key] = hash.delete :old_key </code></pre>
{ "question_id": 6210572, "question_date": "2011-06-02T04:54:49.640Z", "question_score": 232, "tags": "ruby-on-rails|ruby|ruby-on-rails-3|hash", "answer_id": 19298437, "answer_date": "2013-10-10T14:22:50.243Z", "answer_score": 800 }
Please answer the following Stack Overflow question: Title: Android room persistent: AppDatabase_Impl does not exist <p>My app database class</p> <pre><code>@Database(entities = {Detail.class}, version = Constant.DATABASE_VERSION) public abstract class AppDatabase extends RoomDatabase { private static AppDatabase INSTANCE; public abstract FavoritesDao favoritesDao(); public static AppDatabase getAppDatabase(Context context) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build(); //Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build(); } return INSTANCE; } public static void destroyInstance() { INSTANCE = null; } } </code></pre> <p>Gradle lib:<br></p> <pre><code> compile "android.arch.persistence.room:runtime:+" annotationProcessor "android.arch.persistence.room:compiler:+" </code></pre> <p>And when i ask for instance it will give this error, AppDatabase_Impl does not exist in my application class <br></p> <pre><code>public class APp extends Application { private boolean appRunning = false; @Override public void onCreate() { super.onCreate(); AppDatabase.getAppDatabase(this); //--AppDatabase_Impl does not exist } } </code></pre>
<p>For those working with <strong>Kotlin</strong>, try changing <code>annotationProcessor</code> to <code>kapt</code> in the apps <code>build.gradle</code></p> <p>for example:</p> <pre><code>// Extensions = ViewModel + LiveData implementation &quot;android.arch.lifecycle:extensions:1.1.0&quot; kapt &quot;android.arch.lifecycle:compiler:1.1.0&quot; // Room implementation &quot;android.arch.persistence.room:runtime:1.0.0&quot; kapt &quot;android.arch.persistence.room:compiler:1.0.0&quot; </code></pre> <p>also remember to add this plugin</p> <pre><code>apply plugin: 'kotlin-kapt' </code></pre> <p>to the top of the app level build.gradle file and do a clean and rebuild (according to <a href="https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#6" rel="noreferrer">https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#6</a>)</p> <blockquote> <p>In Android Studio, if you get errors when you paste code or during the build process, select Build &gt;Clean Project. Then select Build &gt; Rebuild Project, and then build again.</p> </blockquote> <hr /> <h1>UPDATE</h1> <p>If you have migrated to androidx</p> <pre><code>def room_version = &quot;2.3.0&quot; // check latest version from docs implementation &quot;androidx.room:room-runtime:$room_version&quot; kapt &quot;androidx.room:room-compiler:$room_version&quot; </code></pre> <h1>UPDATE 2 (since July 2021)</h1> <pre><code>def room_version = &quot;2.3.0&quot; // check latest version from docs implementation &quot;androidx.room:room-ktx:$room_version&quot; kapt &quot;androidx.room:room-compiler:$room_version&quot; </code></pre>
{ "question_id": 46665621, "question_date": "2017-10-10T11:29:06.413Z", "question_score": 232, "tags": "java|android|android-room", "answer_id": 49323956, "answer_date": "2018-03-16T15:08:30.213Z", "answer_score": 497 }
Please answer the following Stack Overflow question: Title: What is the difference between getFields and getDeclaredFields in Java reflection <p>I'm a little confused about the difference between the <code>getFields</code> method and the <code>getDeclaredFields</code> method when using Java reflection. </p> <p>I read that <code>getDeclaredFields</code> gives you access to all the fields of the class and that <code>getFields</code> only returns public fields. If this is the case, why wouldn't you just always use <code>getDeclaredFields</code>? </p> <p>Can someone please elaborate on this, and explain the difference between the two methods, and when/why you would want to use one over the other? </p>
<p><strong><a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Class.html#getFields()" rel="noreferrer">getFields()</a></strong></p> <p>All the <code>public</code> fields up the entire class hierarchy.</p> <p><strong><a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Class.html#getDeclaredFields()" rel="noreferrer">getDeclaredFields()</a></strong></p> <p>All the fields, regardless of their accessibility but only for the current class, not any base classes that the current class might be inheriting from.</p> <p>To get all the fields up the hierarchy, I have written the following function:</p> <pre><code>public static Iterable&lt;Field&gt; getFieldsUpTo(@Nonnull Class&lt;?&gt; startClass, @Nullable Class&lt;?&gt; exclusiveParent) { List&lt;Field&gt; currentClassFields = Lists.newArrayList(startClass.getDeclaredFields()); Class&lt;?&gt; parentClass = startClass.getSuperclass(); if (parentClass != null &amp;&amp; (exclusiveParent == null || !(parentClass.equals(exclusiveParent)))) { List&lt;Field&gt; parentClassFields = (List&lt;Field&gt;) getFieldsUpTo(parentClass, exclusiveParent); currentClassFields.addAll(parentClassFields); } return currentClassFields; } </code></pre> <p>The <code>exclusiveParent</code> class is provided to prevent the retrieval of fields from <code>Object</code>. It may be <code>null</code> if you DO want the <code>Object</code> fields.</p> <p>To clarify, <code>Lists.newArrayList</code> comes from Guava.</p> <h3>Update</h3> <p>FYI, the above code is published on GitHub in my <a href="https://github.com/dancerjohn/LibEx" rel="noreferrer">LibEx</a> project in <a href="https://github.com/dancerjohn/LibEx/blob/master/libex/src/main/java/org/libex/reflect/ReflectionUtils.java" rel="noreferrer">ReflectionUtils</a>.</p>
{ "question_id": 16966629, "question_date": "2013-06-06T15:51:09.380Z", "question_score": 232, "tags": "java|reflection", "answer_id": 16966699, "answer_date": "2013-06-06T15:54:30.573Z", "answer_score": 306 }
Please answer the following Stack Overflow question: Title: What does the brk() system call do? <p>According to Linux programmers manual:</p> <blockquote> <p>brk() and sbrk() change the location of the program break, which defines the end of the process's data segment.</p> </blockquote> <p>What does the data segment mean over here? Is it just the data segment or data, BSS, and heap combined?</p> <p>According to wiki <a href="https://en.wikipedia.org/w/index.php?title=Data_segment&amp;oldid=441263263" rel="noreferrer">Data segment</a>:</p> <blockquote> <p>Sometimes the data, BSS, and heap areas are collectively referred to as the &quot;data segment&quot;.</p> </blockquote> <p>I see no reason for changing the size of just the data segment. If it is data, <a href="https://en.wikipedia.org/wiki/.bss" rel="noreferrer">BSS</a> and heap collectively then it makes sense as heap will get more space.</p> <p>Which brings me to my second question. In all the articles I read so far, author says that heap grows upward and stack grows downward. But what they do not explain is what happens when heap occupies all the space between heap and stack?</p> <p><img src="https://i.stack.imgur.com/1aV6B.png" alt="enter image description here" /></p>
<p>In the diagram you posted, the "break"—the address manipulated by <code>brk</code> and <code>sbrk</code>—is the dotted line at the top of the heap.</p> <p><img src="https://i.stack.imgur.com/1aV6B.png" alt="simplified image of virtual memory layout"></p> <p>The documentation you've read describes this as the end of the "data segment" because in traditional (pre-shared-libraries, pre-<code>mmap</code>) Unix the data segment was continuous with the heap; before program start, the kernel would load the "text" and "data" blocks into RAM starting at address zero (actually a little above address zero, so that the NULL pointer genuinely didn't point to anything) and set the break address to the end of the data segment. The first call to <code>malloc</code> would then use <code>sbrk</code> to move the break up and create the heap <em>in between</em> the top of the data segment and the new, higher break address, as shown in the diagram, and subsequent use of <code>malloc</code> would use it to make the heap bigger as necessary.</p> <p>Meantime, the stack starts at the top of memory and grows down. The stack doesn't need explicit system calls to make it bigger; either it starts off with as much RAM allocated to it as it can ever have (this was the traditional approach) or there is a region of reserved addresses below the stack, to which the kernel automatically allocates RAM when it notices an attempt to write there (this is the modern approach). Either way, there may or may not be a "guard" region at the bottom of the address space that can be used for stack. If this region exists (all modern systems do this) it is permanently unmapped; if <em>either</em> the stack or the heap tries to grow into it, you get a segmentation fault. Traditionally, though, the kernel made no attempt to enforce a boundary; the stack could grow into the heap, or the heap could grow into the stack, and either way they would scribble over each other's data and the program would crash. If you were very lucky it would crash immediately.</p> <p>I'm not sure where the number 512GB in this diagram comes from. It implies a 64-bit virtual address space, which is inconsistent with the very simple memory map you have there. A real 64-bit address space looks more like this:</p> <p><img src="https://i.stack.imgur.com/RQxMY.png" alt="less simplified address space"></p> <pre><code> Legend: t: text, d: data, b: BSS </code></pre> <p>This is not remotely to scale, and it shouldn't be interpreted as exactly how any given OS does stuff (after I drew it I discovered that Linux actually puts the executable much closer to address zero than I thought it did, and the shared libraries at surprisingly high addresses). The black regions of this diagram are unmapped -- any access causes an immediate segfault -- and they are <em>gigantic</em> relative to the gray areas. The light-gray regions are the program and its shared libraries (there can be dozens of shared libraries); each has an <em>independent</em> text and data segment (and "bss" segment, which also contains global data but is initialized to all-bits-zero rather than taking up space in the executable or library on disk). The heap is no longer necessarily continous with the executable's data segment -- I drew it that way, but it looks like Linux, at least, doesn't do that. The stack is no longer pegged to the top of the virtual address space, and the distance between the heap and the stack is so enormous that you don't have to worry about crossing it.</p> <p>The break is still the upper limit of the heap. However, what I didn't show is that there could be dozens of independent allocations of memory off there in the black somewhere, made with <code>mmap</code> instead of <code>brk</code>. (The OS will try to keep these far away from the <code>brk</code> area so they don't collide.)</p>
{ "question_id": 6988487, "question_date": "2011-08-08T20:57:32.697Z", "question_score": 232, "tags": "c|linux|unix|memory-management|brk", "answer_id": 6990428, "answer_date": "2011-08-09T01:19:37.913Z", "answer_score": 286 }
Please answer the following Stack Overflow question: Title: Postgres unique constraint vs index <p>As I can understand <a href="https://www.postgresql.org/docs/current/indexes-unique.html" rel="noreferrer">documentation</a> the following definitions are equivalent:</p> <pre><code>create table foo ( id serial primary key, code integer, label text, constraint foo_uq unique (code, label)); create table foo ( id serial primary key, code integer, label text); create unique index foo_idx on foo using btree (code, label); </code></pre> <p>However, a note in <a href="https://www.postgresql.org/docs/9.4/indexes-unique.html" rel="noreferrer">the manual for Postgres 9.4</a> says:</p> <blockquote> <p>The preferred way to add a unique constraint to a table is <code>ALTER TABLE ... ADD CONSTRAINT</code>. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.</p> </blockquote> <p>(Edit: this note was removed from the manual with Postgres 9.5.)</p> <p>Is it only a matter of good style? What are practical consequences of choice one of these variants (e.g. in performance)?</p>
<p>I had some doubts about this basic but important issue, so I decided to learn by example.</p> <p>Let's create test table <em>master</em> with two columns, <em>con_id</em> with unique constraint and <em>ind_id</em> indexed by unique index.</p> <pre><code>create table master ( con_id integer unique, ind_id integer ); create unique index master_unique_idx on master (ind_id); Table "public.master" Column | Type | Modifiers --------+---------+----------- con_id | integer | ind_id | integer | Indexes: "master_con_id_key" UNIQUE CONSTRAINT, btree (con_id) "master_unique_idx" UNIQUE, btree (ind_id) </code></pre> <p>In table description (\d in psql) you can tell unique constraint from unique index.</p> <p><strong>Uniqueness</strong></p> <p>Let's check uniqueness, just in case.</p> <pre><code>test=# insert into master values (0, 0); INSERT 0 1 test=# insert into master values (0, 1); ERROR: duplicate key value violates unique constraint "master_con_id_key" DETAIL: Key (con_id)=(0) already exists. test=# insert into master values (1, 0); ERROR: duplicate key value violates unique constraint "master_unique_idx" DETAIL: Key (ind_id)=(0) already exists. test=# </code></pre> <p>It works as expected!</p> <p><strong>Foreign keys</strong></p> <p>Now we'll define <em>detail</em> table with two foreign keys referencing to our two columns in <em>master</em>.</p> <pre><code>create table detail ( con_id integer, ind_id integer, constraint detail_fk1 foreign key (con_id) references master(con_id), constraint detail_fk2 foreign key (ind_id) references master(ind_id) ); Table "public.detail" Column | Type | Modifiers --------+---------+----------- con_id | integer | ind_id | integer | Foreign-key constraints: "detail_fk1" FOREIGN KEY (con_id) REFERENCES master(con_id) "detail_fk2" FOREIGN KEY (ind_id) REFERENCES master(ind_id) </code></pre> <p>Well, no errors. Let's make sure it works.</p> <pre><code>test=# insert into detail values (0, 0); INSERT 0 1 test=# insert into detail values (1, 0); ERROR: insert or update on table "detail" violates foreign key constraint "detail_fk1" DETAIL: Key (con_id)=(1) is not present in table "master". test=# insert into detail values (0, 1); ERROR: insert or update on table "detail" violates foreign key constraint "detail_fk2" DETAIL: Key (ind_id)=(1) is not present in table "master". test=# </code></pre> <p>Both columns can be referenced in foreign keys.</p> <p><strong>Constraint using index</strong></p> <p>You can add table constraint using existing unique index. </p> <pre><code>alter table master add constraint master_ind_id_key unique using index master_unique_idx; Table "public.master" Column | Type | Modifiers --------+---------+----------- con_id | integer | ind_id | integer | Indexes: "master_con_id_key" UNIQUE CONSTRAINT, btree (con_id) "master_ind_id_key" UNIQUE CONSTRAINT, btree (ind_id) Referenced by: TABLE "detail" CONSTRAINT "detail_fk1" FOREIGN KEY (con_id) REFERENCES master(con_id) TABLE "detail" CONSTRAINT "detail_fk2" FOREIGN KEY (ind_id) REFERENCES master(ind_id) </code></pre> <p>Now there is no difference between column constraints description.</p> <p><strong>Partial indexes</strong></p> <p>In table constraint declaration you cannot create partial indexes. It comes directly from the <a href="http://www.postgresql.org/docs/9.1/static/sql-createtable.html" rel="noreferrer">definition</a> of <code>create table ...</code>. In unique index declaration you can set <code>WHERE clause</code> to create partial index. You can also <a href="http://www.postgresql.org/docs/9.1/static/sql-createindex.html" rel="noreferrer">create index</a> on expression (not only on column) and define some other parameters (collation, sort order, NULLs placement).</p> <p>You <strong>cannot</strong> add table constraint using partial index.</p> <pre><code>alter table master add column part_id integer; create unique index master_partial_idx on master (part_id) where part_id is not null; alter table master add constraint master_part_id_key unique using index master_partial_idx; ERROR: "master_partial_idx" is a partial index LINE 1: alter table master add constraint master_part_id_key unique ... ^ DETAIL: Cannot create a primary key or unique constraint using such an index. </code></pre>
{ "question_id": 23542794, "question_date": "2014-05-08T13:12:41.010Z", "question_score": 232, "tags": "sql|postgresql|indexing|unique", "answer_id": 23665806, "answer_date": "2014-05-14T21:53:18.383Z", "answer_score": 187 }
Please answer the following Stack Overflow question: Title: Task continuation on UI thread <p>Is there a 'standard' way to specify that a task continuation should run on the thread from which the initial task was created?</p> <p>Currently I have the code below - it is working but keeping track of the dispatcher and creating a second Action seems like unnecessary overhead.</p> <pre><code>dispatcher = Dispatcher.CurrentDispatcher; Task task = Task.Factory.StartNew(() =&gt; { DoLongRunningWork(); }); Task UITask= task.ContinueWith(() =&gt; { dispatcher.Invoke(new Action(() =&gt; { this.TextBlock1.Text = "Complete"; } }); </code></pre>
<p>Call the continuation with <code>TaskScheduler.FromCurrentSynchronizationContext()</code>:</p> <pre><code> Task UITask= task.ContinueWith(() =&gt; { this.TextBlock1.Text = "Complete"; }, TaskScheduler.FromCurrentSynchronizationContext()); </code></pre> <p>This is suitable only if the current execution context is on the UI thread.</p>
{ "question_id": 4331262, "question_date": "2010-12-02T02:58:12.260Z", "question_score": 232, "tags": "c#|.net|wpf|multithreading|task", "answer_id": 4331287, "answer_date": "2010-12-02T03:02:08.610Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: What can you use generator functions for? <p>I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.</p>
<p>Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.</p> <p>Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses <em>another</em> generator, or consumes some other resource, and it's more convenient if that happened as late as possible.</p> <p>Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.</p> <p>For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.</p> <p>If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:</p> <pre><code>big_list = list(the_generator) </code></pre>
{ "question_id": 102535, "question_date": "2008-09-19T14:58:49.343Z", "question_score": 232, "tags": "python|generator", "answer_id": 102632, "answer_date": "2008-09-19T15:09:25.340Z", "answer_score": 260 }
Please answer the following Stack Overflow question: Title: Good Python modules for fuzzy string comparison? <p>I'm looking for a Python module that can do simple fuzzy string comparisons. Specifically, I'd like a percentage of how similar the strings are. I know this is potentially subjective so I was hoping to find a library that can do positional comparisons as well as longest similar string matches, among other things.</p> <p>Basically, I'm hoping to find something that is simple enough to yield a single percentage while still configurable enough that I can specify what type of comparison(s) to do.</p>
<p>Levenshtein Python extension and C library.</p> <p><a href="http://code.google.com/p/pylevenshtein/" rel="noreferrer">https://github.com/ztane/python-Levenshtein/</a></p> <p>The Levenshtein Python C extension module contains functions for fast computation of - Levenshtein (edit) distance, and edit operations - string similarity - approximate median strings, and generally string averaging - string sequence and set similarity It supports both normal and Unicode strings.</p> <pre class="lang-none prettyprint-override"><code>$ pip install python-levenshtein ... $ python &gt;&gt;&gt; import Levenshtein &gt;&gt;&gt; help(Levenshtein.ratio) ratio(...) Compute similarity of two strings. ratio(string1, string2) The similarity is a number between 0 and 1, it's usually equal or somewhat higher than difflib.SequenceMatcher.ratio(), becuase it's based on real minimal edit distance. Examples: &gt;&gt;&gt; ratio('Hello world!', 'Holly grail!') 0.58333333333333337 &gt;&gt;&gt; ratio('Brian', 'Jesus') 0.0 &gt;&gt;&gt; help(Levenshtein.distance) distance(...) Compute absolute Levenshtein distance of two strings. distance(string1, string2) Examples (it's hard to spell Levenshtein correctly): &gt;&gt;&gt; distance('Levenshtein', 'Lenvinsten') 4 &gt;&gt;&gt; distance('Levenshtein', 'Levensthein') 2 &gt;&gt;&gt; distance('Levenshtein', 'Levenshten') 1 &gt;&gt;&gt; distance('Levenshtein', 'Levenshtein') 0 </code></pre>
{ "question_id": 682367, "question_date": "2009-03-25T16:25:08.447Z", "question_score": 232, "tags": "python|string|string-comparison|fuzzy-comparison", "answer_id": 684797, "answer_date": "2009-03-26T07:18:51.370Z", "answer_score": 164 }
Please answer the following Stack Overflow question: Title: How to mark a class as Deprecated? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1759352/how-do-i-mark-a-method-as-obsolete-deprecated-c-sharp">How do I mark a method as Obsolete/Deprecated? - C#</a> </p> </blockquote> <p>How do you mark a class as deprecated? I do not want to use a class any more in my project, but do not want to delete it before a period of 2 weeks.</p>
<p>You need to use the <code>[Obsolete]</code> attribute.</p> <p>Example:</p> <pre><code>[Obsolete(&quot;Not used any more&quot;, true)] public class MyDeprecatedClass { //... } </code></pre> <p>The parameters are optional. The first parameter is for providing the reason it's obsolete, and the last one is to throw an error at compile time instead of a warning.</p>
{ "question_id": 314505, "question_date": "2008-11-24T15:37:59.457Z", "question_score": 232, "tags": "c#|.net|oop|deprecated", "answer_id": 314507, "answer_date": "2008-11-24T15:38:39.287Z", "answer_score": 414 }
Please answer the following Stack Overflow question: Title: Difference between microtask and macrotask within an event loop context <p>I've just finished reading the Promises/A+ specification and stumbled upon the terms microtask and macrotask: see <a href="http://promisesaplus.com/#notes">http://promisesaplus.com/#notes</a></p> <p>I've never heard of these terms before, and now I'm curious what the difference could be?</p> <p>I've already tried to find some information on the web, but all I've found is this post from the w3.org Archives (which does not explain the difference to me): <a href="http://lists.w3.org/Archives/Public/public-nextweb/2013Jul/0018.html">http://lists.w3.org/Archives/Public/public-nextweb/2013Jul/0018.html</a></p> <p>Additionally, I've found an npm module called "macrotask": <a href="https://www.npmjs.org/package/macrotask">https://www.npmjs.org/package/macrotask</a> Again, it is not clarified what the difference exactly is.</p> <p>All I know is, that it has something to do with the event loop, as described in <a href="https://html.spec.whatwg.org/multipage/webappapis.html#task-queue">https://html.spec.whatwg.org/multipage/webappapis.html#task-queue</a> and <a href="https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint">https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint</a></p> <p>I know I should theoretically be able to extract the differences myself, given this WHATWG specification. But I'm sure that others could benefit as well from a short explanation given by an expert.</p>
<p>One go-around of the event loop will have <strong>exactly one</strong> task being processed from the <strong>macrotask queue</strong> (this queue is simply called the <em>task queue</em> in the <a href="https://html.spec.whatwg.org/multipage/webappapis.html#task-queue" rel="noreferrer">WHATWG specification</a>). After this macrotask has finished, all available <strong>microtasks</strong> will be processed, namely within the same go-around cycle. While these microtasks are processed, they can queue even more microtasks, which will all be run one by one, until the microtask queue is exhausted.</p> <h2>What are the practical consequences of this?</h2> <p>If a <strong>microtask</strong> recursively queues other microtasks, it might take a long time until the next macrotask is processed. This means, you could end up with a blocked UI, or some finished I/O idling in your application. </p> <p>However, at least concerning Node.js's process.nextTick function (which queues <strong>microtasks</strong>), there is an inbuilt protection against such blocking by means of process.maxTickDepth. This value is set to a default of 1000, cutting down further processing of <strong>microtasks</strong> after this limit is reached which allows the next <strong>macrotask</strong> to be processed)</p> <h2>So when to use what?</h2> <p>Basically, use <strong>microtasks</strong> when you need to do stuff asynchronously in a synchronous way (i.e. when you would say <em>perform this (micro-)task in the most immediate future</em>). Otherwise, stick to <strong>macrotasks</strong>.</p> <h2>Examples</h2> <p><strong>macrotasks:</strong> <a href="https://developer.mozilla.org/docs/Web/API/WindowTimers/setTimeout" rel="noreferrer">setTimeout</a>, <a href="https://developer.mozilla.org/docs/Web/API/WindowTimers/setInterval" rel="noreferrer">setInterval</a>, <a href="https://developer.mozilla.org/docs/Web/API/Window/setImmediate" rel="noreferrer">setImmediate</a>, <a href="https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame" rel="noreferrer">requestAnimationFrame</a>, <a href="https://developer.mozilla.org/docs/Mozilla/Projects/NSPR/Reference/I_O_Functions" rel="noreferrer">I/O</a>, UI rendering<br> <strong>microtasks:</strong> <a href="https://nodejs.org/uk/docs/guides/event-loop-timers-and-nexttick/" rel="noreferrer">process.nextTick</a>, <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer">Promises</a>, <a href="https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask" rel="noreferrer">queueMicrotask</a>, <a href="https://developer.mozilla.org/docs/Web/API/MutationObserver" rel="noreferrer">MutationObserver</a></p>
{ "question_id": 25915634, "question_date": "2014-09-18T14:36:24.193Z", "question_score": 232, "tags": "javascript|node.js|promise|event-loop", "answer_id": 25933985, "answer_date": "2014-09-19T12:29:56.497Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Why does Oracle 9i treat an empty string as NULL? <p>I know that it <em>does</em> consider ' ' as <code>NULL</code>, but that doesn't do much to tell me <em>why</em> this is the case. As I understand the SQL specifications, ' ' is not the same as <code>NULL</code> -- one is a valid datum, and the other is indicating the absence of that same information.</p> <p>Feel free to speculate, but please indicate if that's the case. If there's anyone from Oracle who can comment on it, that'd be fantastic!</p>
<p>I believe the answer is that Oracle is very, very old.</p> <p>Back in the olden days before there was a SQL standard, Oracle made the design decision that empty strings in <code>VARCHAR</code>/<code>VARCHAR2</code> columns were <code>NULL</code> and that there was only one sense of NULL (there are relational theorists that would differentiate between data that has never been prompted for, data where the answer exists but is not known by the user, data where there is no answer, etc. all of which constitute some sense of <code>NULL</code>).</p> <p>By the time that the SQL standard came around and agreed that <code>NULL</code> and the empty string were distinct entities, there were already Oracle users that had code that assumed the two were equivalent. So Oracle was basically left with the options of breaking existing code, violating the SQL standard, or introducing some sort of initialization parameter that would change the functionality of potentially large number of queries. Violating the SQL standard (IMHO) was the least disruptive of these three options.</p> <p>Oracle has left open the possibility that the <code>VARCHAR</code> data type would change in a future release to adhere to the SQL standard (which is why everyone uses <code>VARCHAR2</code> in Oracle since that data type's behavior is guaranteed to remain the same going forward).</p>
{ "question_id": 203493, "question_date": "2008-10-15T02:04:18.840Z", "question_score": 232, "tags": "sql|oracle|null|string", "answer_id": 203536, "answer_date": "2008-10-15T02:30:04.560Z", "answer_score": 235 }
Please answer the following Stack Overflow question: Title: Disable IntelliJ Starred (Package) Imports? <p>I'm a migrating Eclipse IDE user and am learning my way round IntelliJ IDEA 9.</p> <p>By default Eclipse IDE won't use a starred import until you import 99 classes from the same package, so it practically never happens.</p> <p>But IntelliJ IDEA seems only too keen to do it, and I can't work out how to disable it.</p> <p>For example, after typing <code>JList</code> then <kbd>ALT</kbd> + <kbd>ENTER</kbd> to auto-import, the whole <code>javax.swing</code> package is imported instead of just the class I specify.</p> <p>I tried excluding <code>javax.swing</code> from the auto-completion, but that just stops <em>any</em> Swing classes from being suggested, which is counter-productive.</p>
<p>You can set this setting here.</p> <p>In <strong>IDEA 14</strong>+ the sequence is: </p> <p><code>Settings</code> > <code>Editor</code> > <code>Code Style</code> > <code>Java</code> > <code>Imports</code> > <code>Class count to use import with '*'</code></p> <p>In older version of IDEA:</p> <p><code>Settings</code> -> <code>Java</code> -> <code>Code Style</code> -> <code>Imports</code> -> <code>Class count to use import with '*'</code></p> <p>The feature can not be disabled. You need to set it to a high value, e.g. 99.</p> <p>In 2016.1.1 version You should also remove the lines under <code>Packages to Use Import with '*'</code>, e.g. <code>import javax.*;</code></p>
{ "question_id": 3587071, "question_date": "2010-08-27T18:26:53.537Z", "question_score": 232, "tags": "java|autocomplete|intellij-idea", "answer_id": 3589885, "answer_date": "2010-08-28T07:30:29.430Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: How to collapse all methods in Xcode? <p>How to collapse all methods in a class in Xcode?</p> <p>Collapsing one by one is not an option anymore.</p>
<p>Updates in <a href="https://stackoverflow.com/questions/32675843/xcode-dmg-file-not-downloading-using-downloader/46887253#46887253">Xcode 10</a></p> <p>Xcode 10 has increased support for code folding, including: </p> <ol> <li>A new code folding ribbon showing all of the multi-line foldable blocks of code in the editor </li> <li>A new style for folded code in the editor that allows you to edit lines with folded code </li> <li>Support for folding any block of code enclosed in curly braces </li> <li>Support for folding blocks of code from the folding ribbon, from structured selection, or from the </li> </ol> <blockquote> <p>Menubar ► Editor ► Code Folding ► Fold menu item</p> </blockquote> <p><img src="https://i.stack.imgur.com/P2ptP.png" alt="enter image description here"></p> <p>Look at this snapshot:</p> <p><img src="https://i.stack.imgur.com/9GGFL.gif" alt="enter image description here"></p> <hr> <p>Code folding was disabled in Xcode 9 beta 1, which is working now, in Xcode 9 Beta5 according to beta release note: <a href="https://download.developer.apple.com/Developer_Tools/Xcode_9_beta_5/Release_Notes_for_Xcode_9_beta_5.pdf" rel="noreferrer">Resolved in Xcode 9 beta 5 – IDE</a></p> <p>Here is how:</p> <ol> <li>Press and hold <kbd>⌘</kbd> (command) button in keyboard and move/hover mouse cursor on any (start or end) braces. It will automatically highlight, block area.</li> <li>Keep (hold) <kbd>⌘</kbd>(command) button in pressed condition and click on highlighted area. It will enable quick menu popover window with <strong><code>Fold</code></strong> option.</li> <li>Select <strong><code>Fold</code></strong> from menu list. It will fold your code and shows 3 dots, folding/covering entire block.</li> <li>Now, to again unfold your code block, release <kbd>⌘</kbd> (command) button and click on 3 dots folding a block.</li> </ol> <p><strong>For easy understanding, look at this snapshot:</strong></p> <p><img src="https://i.stack.imgur.com/raiei.gif" alt="enter image description here"></p> <p><br> It's all keyboard short cuts are also working.</p> <pre><code>Fold ⌥ ⌘ ← option + command + left arrow Unfold ⌥ ⌘ → option + command + right arrow Unfold All ⌥ U option + U Fold Methods &amp; Functions ⌥ ⌘ ↑ option + command + up arrow Unfold Methods &amp; Functions ⌥ ⌘ ↓ option + command + down arrow Fold Comment Blocks ⌃ ⇧ ⌘ ↑ control + shift + command + up Unfold Comment Blocks ⌃ ⇧ ⌘ ↓ control + shift + command + down Focus Follows Selection ⌃ ⌥ ⌘ F control + option + command + F Fold All ⌘ ⌥ ⇧ ← command + option + shift + left Unfold All ⌘ ⌥ ⇧ → command + option + shift + left </code></pre> <p><br> <strong>Code folding options from Xcode Menu</strong>:</p> <blockquote> <p>Menubar ▶ Editor ▶ Code Folding ▶ "Here is list of code folding options"</p> </blockquote> <p>Here is ref snapshot:</p> <p><img src="https://i.stack.imgur.com/78DMm.png" alt="enter image description here"></p> <p><strong>Same options from Xcode Short-cut list</strong>:</p> <blockquote> <p>Menubar ▶ Xcode ▶ Preferences ▶ Key Bindings ▶ "Here is list of code folding short-keys"</p> </blockquote> <p><img src="https://i.stack.imgur.com/q83V2.png" alt="enter image description here"></p>
{ "question_id": 2834605, "question_date": "2010-05-14T13:49:45.520Z", "question_score": 232, "tags": "xcode|xcode9|code-folding|xcode10", "answer_id": 46020397, "answer_date": "2017-09-03T04:54:56.640Z", "answer_score": 126 }
Please answer the following Stack Overflow question: Title: What is the difference between brew install XXX and brew cask install XXX <p>I'm familiarizing myself with the whole homebrew kit and the documentation is rather poor. What is a cask, Cellar and a tap? </p>
<p><a href="https://caskroom.github.io/" rel="noreferrer">Homebrew-Cask</a> is an extension to Homebrew to install GUI applications such as Google Chrome or Atom. It started independently but its maintainers now work closely with Homebrew’s core team.</p> <p>Homebrew calls its package definition files “formulae” (British plural for “formula”). Homebrew-Cask calls them “casks”. A cask, just like a formula, is a file written in a Ruby-based <a href="https://en.wikipedia.org/wiki/Domain-specific_language" rel="noreferrer">DSL</a> that describes how to install something.</p> <p>The <strong>Cellar</strong> is where Homebrew installs things. Its default path is <code>/usr/local/Cellar</code> (<code>/opt/homebrew/Cellar</code> on Apple Silicon). It then add symlinks from standard locations to it.</p> <p>For example, when you type <code>brew install git</code>:</p> <ol> <li>Homebrew installs it under <code>/usr/local/Cellar/git/&lt;version&gt;/</code>, with the <code>git</code> binary in <code>/usr/local/Cellar/git/&lt;version&gt;/bin/git</code></li> <li>It adds a symlink from <code>/usr/local/bin/git</code> to that binary</li> </ol> <p>This allows Homebrew to keep track of what’s installed by Homebrew versus software installed by other means.</p> <p>A <strong><code>tap</code></strong> is a source of formulae. The default is <code>homebrew/core</code> but you can add more of them. The simplest way to create a formula for your own software is to create a GitHub repository called <code>homebrew-&lt;something&gt;</code>; put your formula file in it; then type <code>brew tap &lt;username&gt;/&lt;something&gt;</code> to add this new source of formulae to your Homebrew installation and so get access to all its formulae.</p> <p>Some companies have internal Homebrew taps for their own utilities. There are a lot of public taps like <a href="https://github.com/atlassian/homebrew-tap" rel="noreferrer"><code>atlassian/tap</code></a> for Atlassian software, or <a href="https://github.com/ska-sa/homebrew-tap" rel="noreferrer"><code>ska-sa/tap</code></a> for radio astronomy. Homebrew itself used to have additional taps like <code>homebrew/science</code> but they deprecated them and imported the formulæ in <code>homebrew/core</code>.</p>
{ "question_id": 46403937, "question_date": "2017-09-25T11:18:06.703Z", "question_score": 232, "tags": "homebrew", "answer_id": 46423275, "answer_date": "2017-09-26T09:56:16.473Z", "answer_score": 286 }
Please answer the following Stack Overflow question: Title: Forward declaration of nested types/classes in C++ <p>I recently got stuck in a situation like this:</p> <pre><code>class A { public: typedef struct/class {…} B; … C::D *someField; } class C { public: typedef struct/class {…} D; … A::B *someField; } </code></pre> <p>Usually you can declare a class name:</p> <pre><code>class A; </code></pre> <p>But you can't forward declare a nested type, the following causes compilation error.</p> <pre><code>class C::D; </code></pre> <p>Any ideas?</p>
<p>You can't do it, it's a hole in the C++ language. You'll have to un-nest at least one of the nested classes.</p>
{ "question_id": 951234, "question_date": "2009-06-04T15:20:39.413Z", "question_score": 232, "tags": "c++|class|nested|forward-declaration", "answer_id": 951245, "answer_date": "2009-06-04T15:23:10.313Z", "answer_score": 260 }
Please answer the following Stack Overflow question: Title: How to reference generic classes and methods in xml documentation <p>When writing xml documentation you can use <code>&lt;see cref="something"&gt;something&lt;/see&gt;</code>, which works of course. But how do you reference a class or a method with generic types? </p> <pre><code>public class FancyClass&lt;T&gt; { public string FancyMethod&lt;K&gt;(T value) { return "something fancy"; } } </code></pre> <p>If I was going to write xml documentation somewhere, how would I reference the fancy class? how can I reference a <code>FancyClass&lt;string&gt;</code>? What about the method?</p> <p>For example in a different class I wanted to let the user know that I will return an instance of <code>FancyClass&lt;int&gt;</code>. How could I make a see cref thing for that?</p>
<p>To reference the method:</p> <pre><code>/// &lt;see cref="FancyClass{T}.FancyMethod{K}(T)"/&gt; for more information. </code></pre>
{ "question_id": 532166, "question_date": "2009-02-10T12:50:38.833Z", "question_score": 232, "tags": "c#|generics|reference|xml-documentation", "answer_id": 532214, "answer_date": "2009-02-10T13:01:18.713Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: Why can't <fieldset> be flex containers? <p>I tried to style a <code>fieldset</code> element with <code>display: flex</code> and <code>display: inline-flex</code>.</p> <p>However, it didn't work: <code>flex</code> behaved like <code>block</code>, and <code>inline-flex</code> behaved like <code>inline-block</code>.</p> <p>This happens both on Firefox and Chrome, but strangely it works on IE.</p> <p>Is it a bug? I couldn't find that <code>fieldset</code> should have any special behavior, neither in <a href="http://www.w3.org/TR/html5/forms.html#the-fieldset-element">HTML5</a> nor in <a href="http://dev.w3.org/csswg/css-flexbox-1/">CSS Flexible Box Layout</a> specs.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset, div { display: flex; border: 1px solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;fieldset&gt; &lt;p&gt;foo&lt;/p&gt; &lt;p&gt;bar&lt;/p&gt; &lt;/fieldset&gt; &lt;div&gt; &lt;p&gt;foo&lt;/p&gt; &lt;p&gt;bar&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
<p>According to <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=984869">Bug 984869 - <code>display: flex</code> doesn't work for button elements</a>,</p> <blockquote> <p><code>&lt;button&gt;</code> is not implementable (by browsers) in pure CSS, so they are a bit of a black box, from the perspective of CSS. This means that they don't necessarily react in the same way that e.g. a <code>&lt;div&gt;</code> would.</p> <p>This isn't specific to flexbox -- e.g. we don't render scrollbars if you put <code>overflow:scroll</code> on a button, and we don't render it as a table if you put <code>display:table</code> on it.</p> <p>Stepping back even further, this isn't specific to <code>&lt;button&gt;</code>. Consider <code>&lt;fieldset&gt;</code> <del>and <code>&lt;table&gt;</code></del> which also have special rendering behavior:</p> <pre class="lang-html prettyprint-override"><code>data:text/html,&lt;fieldset style="display:flex"&gt;&lt;div&gt;abc&lt;/div&gt;&lt;div&gt;def&lt;/div&gt; </code></pre> <p>In these cases, Chrome agrees with us and disregards the <code>flex</code> display mode. (as revealed by the fact that "abc" and "def" end up being stacked vertically). The fact that they happen to do what you're expecting on <code>&lt;button style="display:flex"&gt;</code> is likely just due to an implementation detail.</p> <p>In Gecko's button implementation, we hardcode <code>&lt;button&gt;</code> (and <code>&lt;fieldset&gt;</code>, <del>and <code>&lt;table&gt;</code></del>) as having a specific frame class (and hence, a specific way of laying out the child elements), regardless of the <code>display</code> property.</p> <p>If you want to reliably have the children reliably arranged in a particular layout mode in a cross-browser fashion, your best bet is to use a wrapper-div inside the button, just as you would need to inside of <del>a <code>&lt;table&gt;</code> or</del> a <code>&lt;fieldset&gt;</code>.</p> </blockquote> <p>Therefore, that bug was marked as "resolved invalid".</p> <p>There is also <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1047590">Bug 1047590 - <code>display: flex;</code> doesn't work in <code>&lt;fieldset&gt;</code></a>, currently "unconfirmed".</p> <hr> <p><strong>Good news</strong>: Firefox 46+ implements Flexbox for <code>&lt;fieldset&gt;</code>. See <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1230207">bug 1230207</a>.</p>
{ "question_id": 28078681, "question_date": "2015-01-21T23:16:52.707Z", "question_score": 232, "tags": "html|css|flexbox", "answer_id": 28078942, "answer_date": "2015-01-21T23:39:50.077Z", "answer_score": 155 }
Please answer the following Stack Overflow question: Title: Effects of changing Django's SECRET_KEY <p>I made a mistake and committed my Django project's <code>SECRET_KEY</code> into a public repository.</p> <p>This key should have been kept secret <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SECRET_KEY" rel="noreferrer">according to the docs</a>.</p> <p>The Django project is live and has been running for a while with some active users. What are the effects if I change the <code>SECRET_KEY</code>? Will any existing users, cookies, sessions, etc.. be affected? Obviously, the new <code>SECRET_KEY</code> will no longer be stored in a public location.</p>
<p>Edit: This answer is based on django 1.5</p> <p><code>SECRET_KEY</code> is used in a lot of various places, I'll point out what is impacted by it first and then try to go over that list and give precise explanation of the impact.</p> <p>The list of things using <code>SECRET_KEY</code> directly or indirectly:</p> <ul> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/core/signing.py">JSON object signing</a></li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/utils/crypto.py">crypto functions</a> for salted hmacs or seeding the random engine which impacts: <ul> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/auth/tokens.py">password reset token</a></li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/comments/forms.py">comment form security</a> to protect against forged POST requests</li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/formtools/utils.py">form security</a></li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/messages/storage/cookie.py">protect against message tampering</a> as the message framework may use cookies to pass messages between views.</li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/sessions/backends/base.py">protect session data and create random session keys</a> to avoid tampering as well.</li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/auth/hashers.py">create random salt for most password hashers</a></li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/contrib/auth/models.py">create random passwords</a> if necessary</li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/core/management/commands/startproject.py">create itself when using <code>startproject</code></a></li> <li><a href="https://github.com/django/django/blob/stable/1.5.x/django/middleware/csrf.py">create CSRF key</a></li> </ul></li> </ul> <p>In reality a lot of the items listed here use <code>SECRET_KEY</code> through <code>django.utils.crypt.get_random_string()</code> which uses it to seed the random engine. This won't be impacted by a change in value of <code>SECRET_KEY</code>.</p> <p>User experience directly impacted by a change of value are:</p> <ul> <li>sessions, the data decode will break, that is valid for any session backend (cookies, database, file based or cache).</li> <li>password reset token already sent won't work, users will have to ask a new one.</li> <li>comments form (if using <code>django.contrib.comments</code>) will not validate if it was requested before the value change and submitted after the value change. I think this is very minor but might be confusing for the user.</li> <li>messages (from <code>django.contrib.messages</code>) won't validate server-side in the same timing conditions as for comments form.</li> </ul> <p><strong>UPDATE</strong>: now working on django 1.9.5, a quick look at the source gives me pretty much the same answers. Might do a thorough inspection later.</p>
{ "question_id": 15170637, "question_date": "2013-03-02T04:17:05.697Z", "question_score": 232, "tags": "django", "answer_id": 15383766, "answer_date": "2013-03-13T11:16:56.033Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: Why use purrr::map instead of lapply? <p>Is there any reason why I should use</p> <pre><code>map(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;) </code></pre> <p>instead of</p> <pre><code>lapply(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;) </code></pre> <p>the output should be the same and the benchmarks I made seem to show that <code>lapply</code> is slightly faster (it should be as <code>map</code> needs to evaluate all the non-standard-evaluation input).</p> <p>So is there any reason why for such simple cases I should actually consider switching to <code>purrr::map</code>? I am not asking here about one's likes or dislikes about the syntax, other functionalities provided by purrr etc., but strictly about comparison of <code>purrr::map</code> with <code>lapply</code> assuming using the standard evaluation, i.e. <code>map(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;)</code>. Is there any advantage that <code>purrr::map</code> has in terms of performance, exception handling etc.? The comments below suggest that it does not, but maybe someone could elaborate a little bit more?</p>
<p>If the only function you're using from purrr is <code>map()</code>, then no, the advantages are not substantial. As Rich Pauloo points out, the main advantage of <code>map()</code> is the helpers which allow you to write compact code for common special cases:</p> <ul> <li><p><code>~ . + 1</code> is equivalent to <code>function(x) x + 1</code> (and <code>\(x) x + 1</code> in R-4.1 and newer)</p> </li> <li><p><code>list(&quot;x&quot;, 1)</code> is equivalent to <code>function(x) x[[&quot;x&quot;]][[1]]</code>. These helpers are a bit more general than <code>[[</code> - see <code>?pluck</code> for details. For <a href="https://speakerdeck.com/jennybc/data-rectangling" rel="noreferrer">data rectangling</a>, the <code>.default</code> argument is particularly helpful.</p> </li> </ul> <p>But most of the time you're not using a single <code>*apply()</code>/<code>map()</code> function, you're using a bunch of them, and the advantage of purrr is much greater consistency between the functions. For example:</p> <ul> <li><p>The first argument to <code>lapply()</code> is the data; the first argument to <code>mapply()</code> is the function. The first argument to all map functions is always the data.</p> </li> <li><p>With <code>vapply()</code>, <code>sapply()</code>, and <code>mapply()</code> you can choose to suppress names on the output with <code>USE.NAMES = FALSE</code>; but <code>lapply()</code> doesn't have that argument.</p> </li> <li><p>There's no consistent way to pass consistent arguments on to the mapper function. Most functions use <code>...</code> but <code>mapply()</code> uses <code>MoreArgs</code> (which you'd expect to be called <code>MORE.ARGS</code>), and <code>Map()</code>, <code>Filter()</code> and <code>Reduce()</code> expect you to create a new anonymous function. In map functions, constant argument always come after the function name.</p> </li> <li><p>Almost every purrr function is type stable: you can predict the output type exclusively from the function name. This is not true for <code>sapply()</code> or <code>mapply()</code>. Yes, there is <code>vapply()</code>; but there's no equivalent for <code>mapply()</code>.</p> </li> </ul> <p>You may think that all of these minor distinctions are not important (just as some people think that there's no advantage to stringr over base R regular expressions), but in my experience they cause unnecessary friction when programming (the differing argument orders always used to trip me up), and they make functional programming techniques harder to learn because as well as the big ideas, you also have to learn a bunch of incidental details.</p> <p>Purrr also fills in some handy map variants that are absent from base R:</p> <ul> <li><p><code>modify()</code> preserves the type of the data using <code>[[&lt;-</code> to modify &quot;in place&quot;. In conjunction with the <code>_if</code> variant this allows for (IMO beautiful) code like <code>modify_if(df, is.factor, as.character)</code></p> </li> <li><p><code>map2()</code> allows you to map simultaneously over <code>x</code> and <code>y</code>. This makes it easier to express ideas like <code>map2(models, datasets, predict)</code></p> </li> <li><p><code>imap()</code> allows you to map simultaneously over <code>x</code> and its indices (either names or positions). This is makes it easy to (e.g) load all <code>csv</code> files in a directory, adding a <code>filename</code> column to each.</p> <pre><code>dir(&quot;\\.csv$&quot;) %&gt;% set_names() %&gt;% map(read.csv) %&gt;% imap(~ transform(.x, filename = .y)) </code></pre> </li> <li><p><code>walk()</code> returns its input invisibly; and is useful when you're calling a function for its side-effects (i.e. writing files to disk).</p> </li> </ul> <p>Not to mention the other helpers like <code>safely()</code> and <code>partial()</code>.</p> <p>Personally, I find that when I use purrr, I can write functional code with less friction and greater ease; it decreases the gap between thinking up an idea and implementing it. But your mileage may vary; there's no need to use purrr unless it actually helps you.</p> <h2>Microbenchmarks</h2> <p>Yes, <code>map()</code> is slightly slower than <code>lapply()</code>. But the cost of using <code>map()</code> or <code>lapply()</code> is driven by what you're mapping, not the overhead of performing the loop. The microbenchmark below suggests that the cost of <code>map()</code> compared to <code>lapply()</code> is around 40 ns per element, which seems unlikely to materially impact most R code.</p> <pre><code>library(purrr) n &lt;- 1e4 x &lt;- 1:n f &lt;- function(x) NULL mb &lt;- microbenchmark::microbenchmark( lapply = lapply(x, f), map = map(x, f) ) summary(mb, unit = &quot;ns&quot;)$median / n #&gt; [1] 490.343 546.880 </code></pre>
{ "question_id": 45101045, "question_date": "2017-07-14T10:45:36.643Z", "question_score": 232, "tags": "r|lapply|purrr", "answer_id": 47123420, "answer_date": "2017-11-05T15:41:14.493Z", "answer_score": 296 }
Please answer the following Stack Overflow question: Title: Dependency Inject (DI) "friendly" library <p>I'm pondering the design of a C# library, that will have several different high level functions. Of course, those high-level functions will be implemented using the <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="noreferrer">SOLID</a> class design principles as much as possible. As such, there will probably be classes intended for consumers to use directly on a regular basis, and "support classes" that are dependencies of those more common "end user" classes.</p> <p>The question is, what is the best way to design the library so it is:</p> <ul> <li>DI Agnostic - Although adding basic "support" for one or two of the common DI libraries (StructureMap, Ninject, etc) seems reasonable, I want consumers to be able to use the library with any DI framework.</li> <li>Non-DI usable - If a consumer of the library is using no DI, the library should still be as easy to use as possible, reducing the amount of work a user has to do to create all these "unimportant" dependencies just to get to the "real" classes they want to use.</li> </ul> <p>My current thinking is to provide a few "DI registration modules" for the common DI libraries (e.g a StructureMap registry, a Ninject module), and a set or Factory classes that are non-DI and contain the coupling to those few factories.</p> <p>Thoughts?</p>
<p>This is actually simple to do once you understand that DI is about <strong>patterns and principles</strong>, not technology.</p> <p>To design the API in a DI Container-agnostic way, follow these general principles:</p> <p><strong>Program to an interface, not an implementation</strong></p> <p>This principle is actually a quote (from memory though) from <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns</a>, but it should always be your <strong>real goal</strong>. <em>DI is just a means to achieve that end</em>.</p> <p><strong>Apply the Hollywood Principle</strong></p> <p>The Hollywood Principle in DI terms says: <em>Don't call the DI Container, it'll call you</em>.</p> <p>Never directly ask for a dependency by calling a container from within your code. Ask for it implicitly by using <strong>Constructor Injection</strong>.</p> <p><strong>Use Constructor Injection</strong></p> <p>When you need a dependency, ask for it <em>statically</em> through the constructor:</p> <pre><code>public class Service : IService { private readonly ISomeDependency dep; public Service(ISomeDependency dep) { if (dep == null) { throw new ArgumentNullException("dep"); } this.dep = dep; } public ISomeDependency Dependency { get { return this.dep; } } } </code></pre> <p>Notice how the Service class guarantees its invariants. Once an instance is created, the dependency is guaranteed to be available because of the combination of the Guard Clause and the <code>readonly</code> keyword.</p> <p><strong>Use Abstract Factory if you need a short-lived object</strong></p> <p>Dependencies injected with Constructor Injection tend to be long-lived, but sometimes you need a short-lived object, or to construct the dependency based on a value known only at run-time.</p> <p>See <a href="https://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-wth-a-di-container/1945023#1945023">this</a> for more information.</p> <p><strong>Compose only at the Last Responsible Moment</strong></p> <p>Keep objects decoupled until the very end. Normally, you can wait and wire everything up in the application's entry point. This is called the <strong>Composition Root</strong>.</p> <p>More details here:</p> <ul> <li><a href="https://stackoverflow.com/questions/1475575/where-should-i-do-dependency-injection-with-ninject-2/1475861#1475861">Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)</a></li> <li><a href="https://stackoverflow.com/questions/1410719/design-where-should-objects-be-registered-when-using-windsor/1410738#1410738">Design - Where should objects be registered when using Windsor</a></li> </ul> <p><strong>Simplify using a Facade</strong></p> <p>If you feel that the resulting API becomes too complex for novice users, you can always provide a few <a href="http://en.wikipedia.org/wiki/Facade_pattern" rel="noreferrer">Facade</a> classes that encapsulate common dependency combinations.</p> <p>To provide a flexible Facade with a high degree of discoverability, you could consider providing Fluent Builders. Something like this:</p> <pre><code>public class MyFacade { private IMyDependency dep; public MyFacade() { this.dep = new DefaultDependency(); } public MyFacade WithDependency(IMyDependency dependency) { this.dep = dependency; return this; } public Foo CreateFoo() { return new Foo(this.dep); } } </code></pre> <p>This would allow a user to create a default Foo by writing</p> <pre><code>var foo = new MyFacade().CreateFoo(); </code></pre> <p>It would, however, be very discoverable that it's possible to supply a custom dependency, and you could write</p> <pre><code>var foo = new MyFacade().WithDependency(new CustomDependency()).CreateFoo(); </code></pre> <p>If you imagine that the MyFacade class encapsulates a lot of different dependencies, I hope it's clear how it would provide proper defaults while still making extensibility discoverable.</p> <hr> <p>FWIW, long after writing this answer, I expanded upon the concepts herein and wrote a longer blog post about <a href="http://blog.ploeh.dk/2014/05/19/di-friendly-library" rel="noreferrer">DI-Friendly Libraries</a>, and a companion post about <a href="http://blog.ploeh.dk/2014/05/19/di-friendly-framework" rel="noreferrer">DI-Friendly Frameworks</a>.</p>
{ "question_id": 2045904, "question_date": "2010-01-12T00:20:36.693Z", "question_score": 232, "tags": "c#|dependency-injection|inversion-of-control", "answer_id": 2047657, "answer_date": "2010-01-12T08:42:13.407Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: How to get Time from DateTime format in SQL? <p>I want to get only Time from DateTime column using SQL query using SQL Server 2005 and 2008 Default output:</p> <pre><code>AttDate == 2011-02-09 13:09:00 2011-02-09 14:10:00 </code></pre> <p>I'd like this output:</p> <pre><code>AttDate Time == 2011-02-09 13:09:00 13:09 2011-02-09 14:10:00 14:10 </code></pre>
<p>SQL Server 2008:</p> <pre><code>SELECT cast(AttDate as time) [time] FROM yourtable </code></pre> <p>Earlier versions:</p> <pre><code>SELECT convert(char(5), AttDate, 108) [time] FROM yourtable </code></pre>
{ "question_id": 7710449, "question_date": "2011-10-10T08:52:22.180Z", "question_score": 231, "tags": "sql-server|tsql|sql-server-2005|datetime", "answer_id": 7710495, "answer_date": "2011-10-10T08:57:13.123Z", "answer_score": 418 }
Please answer the following Stack Overflow question: Title: How to convert a string to utf-8 in Python <p>I have a browser which sends utf-8 characters to my Python server, but when I retrieve it from the query string, the encoding that Python returns is ASCII. How can I convert the plain string to utf-8?</p> <p>NOTE: The string passed from the web is already UTF-8 encoded, I just want to make Python to treat it as UTF-8 not ASCII.</p>
<h3>In Python 2</h3> <pre><code>&gt;&gt;&gt; plain_string = &quot;Hi!&quot; &gt;&gt;&gt; unicode_string = u&quot;Hi!&quot; &gt;&gt;&gt; type(plain_string), type(unicode_string) (&lt;type 'str'&gt;, &lt;type 'unicode'&gt;) </code></pre> <p>^ This is the difference between a byte string (plain_string) and a unicode string.</p> <pre><code>&gt;&gt;&gt; s = &quot;Hello!&quot; &gt;&gt;&gt; u = unicode(s, &quot;utf-8&quot;) </code></pre> <p>^ Converting to unicode and specifying the encoding.</p> <h3>In Python 3</h3> <p>All strings are unicode. The <code>unicode</code> function does not exist anymore. See answer from @Noumenon</p>
{ "question_id": 4182603, "question_date": "2010-11-15T08:26:24.400Z", "question_score": 231, "tags": "python|python-2.7|unicode|utf-8", "answer_id": 4182635, "answer_date": "2010-11-15T08:31:41.483Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: List the queries running on SQL Server <p>Is there a way to list the queries that are currently running on MS SQL Server (either through the Enterprise Manager or SQL) and/or who's connected?</p> <p>I think I've got a very long running query is being execute on one of my database servers and I'd like to track it down and stop it (or the person who keeps starting it).</p>
<p>This will show you the longest running SPIDs on a SQL 2000 or SQL 2005 server:</p> <pre><code>select P.spid , right(convert(varchar, dateadd(ms, datediff(ms, P.last_batch, getdate()), '1900-01-01'), 121), 12) as 'batch_duration' , P.program_name , P.hostname , P.loginame from master.dbo.sysprocesses P where P.spid &gt; 50 and P.status not in ('background', 'sleeping') and P.cmd not in ('AWAITING COMMAND' ,'MIRROR HANDLER' ,'LAZY WRITER' ,'CHECKPOINT SLEEP' ,'RA MANAGER') order by batch_duration desc </code></pre> <p>If you need to see the SQL running for a given spid from the results, use something like this:</p> <pre><code>declare @spid int , @stmt_start int , @stmt_end int , @sql_handle binary(20) set @spid = XXX -- Fill this in select top 1 @sql_handle = sql_handle , @stmt_start = case stmt_start when 0 then 0 else stmt_start / 2 end , @stmt_end = case stmt_end when -1 then -1 else stmt_end / 2 end from sys.sysprocesses where spid = @spid order by ecid SELECT SUBSTRING( text, COALESCE(NULLIF(@stmt_start, 0), 1), CASE @stmt_end WHEN -1 THEN DATALENGTH(text) ELSE (@stmt_end - @stmt_start) END ) FROM ::fn_get_sql(@sql_handle) </code></pre>
{ "question_id": 941763, "question_date": "2009-06-02T20:35:31.650Z", "question_score": 231, "tags": "sql-server", "answer_id": 955834, "answer_date": "2009-06-05T13:24:28.877Z", "answer_score": 231 }
Please answer the following Stack Overflow question: Title: Is it possible to embed animated GIFs in PDFs? <p>Is it possible to embed animated GIFs in PDFs? And how might I go about such a thing? are there any dangers I should be aware of?</p> <p>For some more details on why I think it's a good thing and how it helps <a href="https://joereddington.github.io/2014/04/18/animated.html" rel="noreferrer">feel free to see this post</a>. I didn't think it was appropriately well-formed enough for SE.</p> <p>As an example - I'd like to put this into a description of quicksort:</p> <p><img src="https://i.stack.imgur.com/vZRiQ.gif" alt="quicksort animation from wikipedia" /> <br> (This animation is from <a href="https://commons.wikimedia.org/wiki/File:Sorting_quicksort_anim.gif" rel="noreferrer">wikimedia</a>.)</p>
<p>I haven't tested it but apparently you can add quicktime animations to a pdf (no idea why). So the solution would be to export the animated gif to quicktime and add it to the pdf.</p> <p>Here the solution that apparently works:</p> <ol> <li>Open the GIF in Quicktime and save as MOV (Apparently it works with other formats too, you'll have to try it out). </li> <li>Insert the MOV into the PDF (with Adobe InDesign (make sure to set Object> Interactive> film options > Embed in PDF) - It should work with Adobe Acrobat Pro DC too: <a href="https://helpx.adobe.com/acrobat/using/rich-media.html" rel="noreferrer">see link</a></li> <li>Save the PDF.</li> </ol> <p>See <a href="http://www.macuser.de/forum/f17/animierte-gifs-pdf-21509/" rel="noreferrer">this link</a> (German)</p>
{ "question_id": 9009771, "question_date": "2012-01-25T20:28:43.897Z", "question_score": 231, "tags": "pdf|animated-gif", "answer_id": 14852633, "answer_date": "2013-02-13T11:36:05.820Z", "answer_score": 78 }
Please answer the following Stack Overflow question: Title: How do I disable form fields using CSS? <p>Is it possible to disable form fields using CSS? I of course know about the attribute disabled, but is it possible to specify this in a CSS rule? Something like -</p> <pre><code>&lt;input type="text" name="username" value="admin" &gt; &lt;style type="text/css"&gt; input[name=username] { disabled: true; /* Does not work */ } &lt;/style&gt; </code></pre> <p>The reason I'm asking is that, I have an application where the form fields are autogenerated, and fields are hidden/shown based on some rules (which run in Javascript). Now I want to extend it to support disabling/enabling fields, but the way the rules are written to directly manipulate the style properties of the form fields. So now I have to extend the rule engine to change attributes as well as style of form fields and somehow it seems less than ideal.</p> <p>It's very curious that you have visible and display properties in CSS but not enable/disable. Is there anything like it in the still-under-works HTML5 standard, or even something non-standard (browser specific)?</p>
<p>This can be helpful:</p> <pre><code>&lt;input type="text" name="username" value="admin" &gt; &lt;style type="text/css"&gt; input[name=username] { pointer-events: none; } &lt;/style&gt; </code></pre> <p><strong>Update:</strong></p> <p>and if want to disable from tab index you can use it this way:</p> <pre><code> &lt;input type="text" name="username" value="admin" tabindex="-1" &gt; &lt;style type="text/css"&gt; input[name=username] { pointer-events: none; } &lt;/style&gt; </code></pre>
{ "question_id": 5963099, "question_date": "2011-05-11T10:57:51.700Z", "question_score": 231, "tags": "html|css", "answer_id": 30753316, "answer_date": "2015-06-10T10:09:53.673Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: Origin <origin> is not allowed by Access-Control-Allow-Origin <pre><code>XMLHttpRequest cannot load http://localhost:8080/api/test. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. </code></pre> <p>I read about cross domain ajax requests, and understand the underlying security issue. In my case, 2 servers are running locally, and like to enable cross domain requests during testing.</p> <pre><code>localhost:8080 - Google Appengine dev server localhost:3000 - Node.js server </code></pre> <p>I am issuing an ajax request to <code>localhost:8080 - GAE server</code> while my page is loaded from node server. What is the easiest, and safest ( Don't want to start chrome with <code>disable-web-security</code> option). If I have to change <code>'Content-Type'</code>, should I do it at node server? How?</p>
<p>Since they are running on different ports, they are different JavaScript <code>origin</code>. It doesn't matter that they are on the same machine/hostname.</p> <p>You need to enable CORS on the server (localhost:8080). Check out this site: <a href="http://enable-cors.org/" rel="noreferrer">http://enable-cors.org/</a></p> <p>All you need to do is add an HTTP header to the server:</p> <pre><code>Access-Control-Allow-Origin: http://localhost:3000 </code></pre> <p>Or, for simplicity:</p> <pre><code>Access-Control-Allow-Origin: * </code></pre> <p>Thought don't use "*" if your server is trying to set cookie and you use <code>withCredentials = true</code></p> <blockquote> <p>when responding to a credentialed request, server must specify a domain, and cannot use wild carding.</p> </blockquote> <p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">You can read more about <code>withCredentials</code> here</a></p>
{ "question_id": 18642828, "question_date": "2013-09-05T17:50:27.953Z", "question_score": 231, "tags": "javascript|node.js|ajax|google-chrome|cors", "answer_id": 18643011, "answer_date": "2013-09-05T17:59:51.490Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: Mark error in form using Bootstrap <p>I've started using Bootstrap in order to achieve a nice page design without resorting to GWT (the backend is made in java)</p> <p>For my login screen I copied this <a href="http://twitter.github.com/bootstrap/examples/signin.html" rel="noreferrer">example</a>. Now I want to mark an error, for instance, that the username was left empty. So I was wondering what is the procedure in the Bootstrap framework for this. Or maybe if there are examples showing the form with error. </p> <p>I'm not sure if the idea is to show the error message inside the input element with a red color, or to show it below the input element, or maybe with a popup?</p>
<p><strong>(UPDATED with examples for Bootstrap v4, v3 and v3)</strong></p> <p>Examples of forms with validation classes for the past few major versions of Bootstrap.</p> <p><strong>Bootstrap v4</strong></p> <p>See the <a href="https://codepen.io/jonschlinkert/pen/rGOorB" rel="noreferrer">live version</a> on codepen</p> <p><img src="https://i.imgur.com/14WpN0j.png" alt="bootstrap v4 form validation"></p> <pre class="lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;form&gt; &lt;div class="form-group row"&gt; &lt;label for="inputEmail" class="col-sm-2 col-form-label text-success"&gt;Email&lt;/label&gt; &lt;div class="col-sm-7"&gt; &lt;input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;label for="inputPassword" class="col-sm-2 col-form-label text-danger"&gt;Password&lt;/label&gt; &lt;div class="col-sm-7"&gt; &lt;input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password"&gt; &lt;/div&gt; &lt;div class="col-sm-3"&gt; &lt;small id="passwordHelp" class="text-danger"&gt; Must be 8-20 characters long. &lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p><strong>Bootstrap v3</strong></p> <p>See the <a href="https://codepen.io/jonschlinkert/pen/jGbXJJ" rel="noreferrer">live version</a> on codepen</p> <p><img src="https://i.imgur.com/LvEX4ni.png" alt="bootstrap v3 form validation"></p> <pre class="lang-html prettyprint-override"><code>&lt;form role="form"&gt; &lt;div class="form-group has-warning"&gt; &lt;label class="control-label" for="inputWarning"&gt;Input with warning&lt;/label&gt; &lt;input type="text" class="form-control" id="inputWarning"&gt; &lt;span class="help-block"&gt;Something may have gone wrong&lt;/span&gt; &lt;/div&gt; &lt;div class="form-group has-error"&gt; &lt;label class="control-label" for="inputError"&gt;Input with error&lt;/label&gt; &lt;input type="text" class="form-control" id="inputError"&gt; &lt;span class="help-block"&gt;Please correct the error&lt;/span&gt; &lt;/div&gt; &lt;div class="form-group has-info"&gt; &lt;label class="control-label" for="inputError"&gt;Input with info&lt;/label&gt; &lt;input type="text" class="form-control" id="inputError"&gt; &lt;span class="help-block"&gt;Username is taken&lt;/span&gt; &lt;/div&gt; &lt;div class="form-group has-success"&gt; &lt;label class="control-label" for="inputSuccess"&gt;Input with success&lt;/label&gt; &lt;input type="text" class="form-control" id="inputSuccess" /&gt; &lt;span class="help-block"&gt;Woohoo!&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p><strong>Bootstrap v2</strong></p> <p>See the <a href="http://jsfiddle.net/jonschlinkert/pngWh/12/" rel="noreferrer">live version</a> on jsfiddle</p> <p><img src="https://i.stack.imgur.com/ToPRZ.png" alt="bootstrap v2 form validation"></p> <p>The <code>.error</code>, <code>.success</code>, <code>.warning</code> and <code>.info</code> classes are appended to the <code>.control-group</code>. This is standard Bootstrap markup and styling in v2. Just follow that and you're in good shape. Of course you can go beyond with your own styles to add a popup or "inline flash" if you prefer, but if you follow Bootstrap convention and hang those validation classes on the <code>.control-group</code> it will stay consistent and easy to manage (at least since you'll continue to have the benefit of Bootstrap docs and examples)</p> <pre class="lang-html prettyprint-override"><code> &lt;form class="form-horizontal"&gt; &lt;div class="control-group warning"&gt; &lt;label class="control-label" for="inputWarning"&gt;Input with warning&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputWarning"&gt; &lt;span class="help-inline"&gt;Something may have gone wrong&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group error"&gt; &lt;label class="control-label" for="inputError"&gt;Input with error&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputError"&gt; &lt;span class="help-inline"&gt;Please correct the error&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group info"&gt; &lt;label class="control-label" for="inputInfo"&gt;Input with info&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputInfo"&gt; &lt;span class="help-inline"&gt;Username is taken&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group success"&gt; &lt;label class="control-label" for="inputSuccess"&gt;Input with success&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputSuccess"&gt; &lt;span class="help-inline"&gt;Woohoo!&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
{ "question_id": 14361517, "question_date": "2013-01-16T15:10:29.107Z", "question_score": 231, "tags": "twitter-bootstrap", "answer_id": 14366428, "answer_date": "2013-01-16T19:39:55.947Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: How to verify CuDNN installation? <p>I have searched many places but ALL I get is HOW to install it, not how to verify that it is installed. I can verify my NVIDIA driver is installed, and that CUDA is installed, but I don't know how to verify CuDNN is installed. Help will be much appreciated, thanks!</p> <p>PS.<br> This is for a caffe implementation. Currently everything is working without CuDNN enabled.</p>
<p>Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.</p> <p>You can check that using <code>cmake</code>. Create a directory <code>caffe/build</code> and run <code>cmake ..</code> from there. If the configuration is correct you will see these lines:</p> <pre><code>-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so) -- NVIDIA CUDA: -- Target GPU(s) : Auto -- GPU arch(s) : sm_30 -- cuDNN : Yes </code></pre> <p>If everything is correct just run the <code>make</code> orders to install caffe from there.</p>
{ "question_id": 31326015, "question_date": "2015-07-09T18:58:39.783Z", "question_score": 231, "tags": "cuda|computer-vision|caffe|conv-neural-network|cudnn", "answer_id": 31349250, "answer_date": "2015-07-10T19:56:28.280Z", "answer_score": 49 }
Please answer the following Stack Overflow question: Title: How to find the array index with a value? <p>Say I've got this</p> <pre class="lang-js prettyprint-override"><code>imageList = [100,200,300,400,500]; </code></pre> <p>Which gives me</p> <p><code>[0]100 [1]200</code> etc.</p> <p>Is there any way in JavaScript to return the index with the value?</p> <p>I.e. I want the index for <strong>200</strong>, I get returned <strong>1</strong>.</p>
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer"><code>indexOf</code></a>:</p> <pre><code>var imageList = [100,200,300,400,500]; var index = imageList.indexOf(200); // 1 </code></pre> <p>You will get -1 if it cannot find a value in the array.</p>
{ "question_id": 7346827, "question_date": "2011-09-08T10:47:46.183Z", "question_score": 231, "tags": "javascript|arrays|indexof", "answer_id": 7346853, "answer_date": "2011-09-08T10:49:35.293Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: Adding options to select with javascript <p>I want this javascript to create options from 12 to 100 in a select with id="mainSelect", because I do not want to create all of the option tags manually. Can you give me some pointers? Thanks</p> <pre><code>function selectOptionCreate() { var age = 88; line = ""; for (var i = 0; i &lt; 90; i++) { line += "&lt;option&gt;"; line += age + i; line += "&lt;/option&gt;"; } return line; } </code></pre>
<p>You could achieve this with a simple <code>for</code> loop:</p> <pre><code>var min = 12, max = 100, select = document.getElementById('selectElementId'); for (var i = min; i&lt;=max; i++){ var opt = document.createElement('option'); opt.value = i; opt.innerHTML = i; select.appendChild(opt); } </code></pre> <p><a href="http://jsfiddle.net/davidThomas/NX3ac/" rel="noreferrer">JS Fiddle demo</a>.</p> <p><a href="http://jsperf.com/" rel="noreferrer">JS Perf</a> comparison of both mine and <a href="http://jsperf.com/comparison-of-loops" rel="noreferrer">Sime Vidas' answer</a>, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.</p> <hr /> <p><strong>Edited</strong> in response to comment from OP:</p> <blockquote> <p>[How] do [I] apply this to more than one element?</p> </blockquote> <pre><code>function populateSelect(target, min, max){ if (!target){ return false; } else { var min = min || 0, max = max || min + 100; select = document.getElementById(target); for (var i = min; i&lt;=max; i++){ var opt = document.createElement('option'); opt.value = i; opt.innerHTML = i; select.appendChild(opt); } } } // calling the function with all three values: populateSelect('selectElementId',12,100); // calling the function with only the 'id' ('min' and 'max' are set to defaults): populateSelect('anotherSelect'); // calling the function with the 'id' and the 'min' (the 'max' is set to default): populateSelect('moreSelects', 50); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/NX3ac/1/" rel="noreferrer">JS Fiddle demo</a>.</p> <p>And, finally (after quite a delay...), an approach extending the prototype of the <code>HTMLSelectElement</code> in order to chain the <code>populate()</code> function, as a method, to the DOM node:</p> <pre><code>HTMLSelectElement.prototype.populate = function (opts) { var settings = {}; settings.min = 0; settings.max = settings.min + 100; for (var userOpt in opts) { if (opts.hasOwnProperty(userOpt)) { settings[userOpt] = opts[userOpt]; } } for (var i = settings.min; i &lt;= settings.max; i++) { this.appendChild(new Option(i, i)); } }; document.getElementById('selectElementId').populate({ 'min': 12, 'max': 40 }); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/NX3ac/148/" rel="noreferrer">JS Fiddle demo</a>.</p> <p>References:</p> <ul> <li><a href="https://developer.mozilla.org/en/DOM/node.appendChild" rel="noreferrer"><code>node.appendChild()</code></a>.</li> <li><a href="https://developer.mozilla.org/en/DOM/document.getElementById" rel="noreferrer"><code>document.getElementById()</code></a>.</li> <li><a href="https://developer.mozilla.org/en/DOM/element.innerHTML" rel="noreferrer"><code>element.innerHTML</code></a>.</li> </ul>
{ "question_id": 8674618, "question_date": "2011-12-29T23:18:26.883Z", "question_score": 231, "tags": "javascript|html", "answer_id": 8674667, "answer_date": "2011-12-29T23:23:31.723Z", "answer_score": 351 }
Please answer the following Stack Overflow question: Title: How can I set cookie in node js using express framework? <p>In my application, I need to set a cookie using the express framework. I have tried the following code but it's not setting the cookie.</p> <pre><code>var express = require('express'), http = require('http'); var app = express(); app.configure(function(){ app.use(express.cookieParser()); app.use(express.static(__dirname + '/public')); app.use(function (req, res) { var randomNumber=Math.random().toString(); randomNumber=randomNumber.substring(2,randomNumber.length); res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true }) console.log('cookie have created successfully'); }); }); var server = http.createServer(app); var io = require('socket.io').listen(server); server.listen(5555); </code></pre>
<p>The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.</p> <p>If <code>express.static</code> is handling the request, you need to move your middleware up:</p> <pre class="lang-js prettyprint-override"><code>// need cookieParser middleware before we can do anything with cookies app.use(express.cookieParser()); // set a cookie app.use(function (req, res, next) { // check if client sent cookie var cookie = req.cookies.cookieName; if (cookie === undefined) { // no: set a new cookie var randomNumber=Math.random().toString(); randomNumber=randomNumber.substring(2,randomNumber.length); res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true }); console.log('cookie created successfully'); } else { // yes, cookie was already present console.log('cookie exists', cookie); } next(); // &lt;-- important! }); // let static middleware do its job app.use(express.static(__dirname + '/public')); </code></pre> <p>Also, middleware needs to <em>either</em> end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling <code>next()</code> when the cookie has been set.</p> <p><strong>Update</strong></p> <p>As of now the cookie parser is a seperate npm package, so instead of using </p> <pre class="lang-js prettyprint-override"><code>app.use(express.cookieParser()); </code></pre> <p>you need to install it separately using <code>npm i cookie-parser</code> and then use it as:</p> <pre class="lang-js prettyprint-override"><code>const cookieParser = require('cookie-parser'); app.use(cookieParser()); </code></pre>
{ "question_id": 16209145, "question_date": "2013-04-25T07:48:36.713Z", "question_score": 231, "tags": "node.js|cookies|express", "answer_id": 16209531, "answer_date": "2013-04-25T08:09:40.590Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: Remove ALL styling/formatting from hyperlinks <p>I'm creating a navigation menu with words with different colors (<code>href</code> links). I would like the color NOT to change on any state (hover, visited etc).</p> <p>I know how to set the the colors for the different states, but I would like to know the code to just leave the text color (and any other styling/formatting) as it is.</p> <p>Any Suggestions?</p>
<p>You can simply define a style for links, which would override <code>a:hover</code>, <code>a:visited</code> etc.:</p> <pre class="lang-css prettyprint-override"><code>a { color: blue; text-decoration: none; /* no underline */ } </code></pre> <p>You can also use the <code>inherit</code> value if you want to use attributes from parent styles instead:</p> <pre class="lang-css prettyprint-override"><code>body { color: blue; } a { color: inherit; /* blue colors for links too */ text-decoration: inherit; /* no underline */ } </code></pre>
{ "question_id": 8919682, "question_date": "2012-01-19T00:47:45.633Z", "question_score": 231, "tags": "html|css|href", "answer_id": 8919740, "answer_date": "2012-01-19T00:55:01.277Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: Writing a Python list of lists to a csv file <p>I have a long list of lists of the following form ---</p> <pre><code>a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]] </code></pre> <p>i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like</p> <pre><code>1.2,abc,3 1.2,werew,4 . . . 1.4,qew,2 </code></pre>
<p>Python's built-in <a href="http://docs.python.org/2/library/csv.html" rel="noreferrer">CSV module</a> can handle this easily:</p> <pre><code>import csv with open("output.csv", "wb") as f: writer = csv.writer(f) writer.writerows(a) </code></pre> <p>This assumes your list is defined as <code>a</code>, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to <code>csv.writer()</code> as documented in the library reference page linked above.</p> <p><strong>Update for Python 3</strong></p> <pre><code>import csv with open("out.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(a) </code></pre>
{ "question_id": 14037540, "question_date": "2012-12-26T07:43:47.673Z", "question_score": 231, "tags": "python|file|csv|file-io|python-2.7", "answer_id": 14037564, "answer_date": "2012-12-26T07:46:09.880Z", "answer_score": 397 }
Please answer the following Stack Overflow question: Title: How to convert comma-delimited string to list in Python? <p>Given a string that is a sequence of several values separated by a commma:</p> <pre><code>mStr = 'A,B,C,D,E' </code></pre> <p>How do I convert the string to a list?</p> <pre><code>mList = ['A', 'B', 'C', 'D', 'E'] </code></pre>
<p>You can use the str.split method.</p> <pre><code>&gt;&gt;&gt; my_string = 'A,B,C,D,E' &gt;&gt;&gt; my_list = my_string.split(",") &gt;&gt;&gt; print my_list ['A', 'B', 'C', 'D', 'E'] </code></pre> <p>If you want to convert it to a tuple, just</p> <pre><code>&gt;&gt;&gt; print tuple(my_list) ('A', 'B', 'C', 'D', 'E') </code></pre> <p>If you are looking to append to a list, try this:</p> <pre><code>&gt;&gt;&gt; my_list.append('F') &gt;&gt;&gt; print my_list ['A', 'B', 'C', 'D', 'E', 'F'] </code></pre>
{ "question_id": 7844118, "question_date": "2011-10-21T01:33:51.383Z", "question_score": 231, "tags": "python|parsing|list|tuples", "answer_id": 7844128, "answer_date": "2011-10-21T01:35:55.593Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: How to delete images from a private docker registry? <p>I run a private docker registry, and I want to delete all images but the <code>latest</code> from a repository. I don't want to delete the entire repository, just some of the images inside it. The <a href="https://docs.docker.com/registry/spec/api/" rel="noreferrer">API docs</a> don't mention a way to do this, but surely it's possible?</p>
<p>Currently you cannot use the Registry API for that task. It only allows you to delete a repository or a specific tag.</p> <p>In general, deleting a repository means, that all the tags associated to this repo are deleted.</p> <p>Deleting a tag means, that the association between an image and a tag is deleted.</p> <p>None of the above will delete a single image. They are left on your disk.</p> <hr> <h1>Workaround</h1> <p><strong>For this workaround you need to have your docker images stored locally.</strong></p> <p>A workaround for your solution would be to delete all but the latest tags and thereby potentially removing the reference to the associated images. Then you can run <strong><a href="https://gist.github.com/kwk/c5443f2a1abcf0eb1eaa" rel="noreferrer">this script</a></strong> to remove all images, that are not referenced by any tag or the ancestry of any used image.</p> <h2>Terminology (images and tags)</h2> <p>Consider an image graph like this where the capital letters (<code>A</code>, <code>B</code>, ...) represent short image IDs and <code>&lt;-</code> means that an image is based on another image:</p> <pre><code> A &lt;- B &lt;- C &lt;- D </code></pre> <p>Now we add tags to the picture:</p> <pre><code> A &lt;- B &lt;- C &lt;- D | | | &lt;version2&gt; &lt;version1&gt; </code></pre> <p>Here, the tag <code>&lt;version1&gt;</code> references the image <code>C</code> and the tag <code>&lt;version2&gt;</code> references the image <code>D</code>.</p> <h2>Refining your question</h2> <p>In your question you said that you wanted to remove </p> <blockquote> <p>all images but the <code>latest</code></p> </blockquote> <p>. Now, this terminology is not quite correct. You've mixed images and tags. Looking at the graph I think you would agree that the tag <code>&lt;version2&gt;</code> represents the latest version. In fact, according to <a href="https://stackoverflow.com/questions/22080706/how-to-create-named-and-latest-tag-in-docker">this question</a> you can have a tag that represents the latest version:</p> <pre><code> A &lt;- B &lt;- C &lt;- D | | | &lt;version2&gt; | &lt;latest&gt; &lt;version1&gt; </code></pre> <p>Since the <code>&lt;latest&gt;</code> tag references image <code>D</code> I ask you: do you really want to delete all but image <code>D</code>? Probably not!</p> <h2>What happens if you delete a tag?</h2> <p>If you delete the tag <code>&lt;version1&gt;</code> using the Docker REST API you will get this:</p> <pre><code> A &lt;- B &lt;- C &lt;- D | &lt;version2&gt; &lt;latest&gt; </code></pre> <p><strong>Remember:</strong> Docker will never delete an image! Even if it did, in this case it cannot delete an image, since the image <code>C</code> is part of the ancestry for the image <code>D</code> which is tagged.</p> <p>Even if you use <strong><a href="https://gist.github.com/kwk/c5443f2a1abcf0eb1eaa" rel="noreferrer">this script</a></strong>, no image will be deleted.</p> <h2>When an image can be deleted</h2> <p>Under the condition that you can control when somebody can pull or push to your registry (e.g. by disabling the REST interface). You can delete an image from an image graph if no other image is based on it and no tag refers to it. </p> <p>Notice that in the following graph, the image <code>D</code> is <strong>not</strong> based on <code>C</code> but on <code>B</code>. Therefore, <code>D</code> doesn't depend on <code>C</code>. If you delete tag <code>&lt;version1&gt;</code> in this graph, the image <code>C</code> will not be used by any image and <strong><a href="https://gist.github.com/kwk/c5443f2a1abcf0eb1eaa" rel="noreferrer">this script</a></strong> can remove it.</p> <pre><code> A &lt;- B &lt;--------- D \ | \ &lt;version2&gt; \ &lt;latest&gt; \ &lt;- C | &lt;version1&gt; </code></pre> <p>After the cleanup your image graph looks like this:</p> <pre><code> A &lt;- B &lt;- D | &lt;version2&gt; &lt;latest&gt; </code></pre> <p>Is this what you want?</p>
{ "question_id": 25436742, "question_date": "2014-08-21T22:09:29.543Z", "question_score": 231, "tags": "docker|docker-registry", "answer_id": 25551160, "answer_date": "2014-08-28T14:20:26.940Z", "answer_score": 138 }
Please answer the following Stack Overflow question: Title: Convert JS Object to form data <p>How can I can convert my JS Object to <code>FormData</code>?</p> <p>The reason why I want to do this is, I have an object that I constructed out of the ~100 form field values. </p> <pre><code>var item = { description: 'Some Item', price : '0.00', srate : '0.00', color : 'red', ... ... } </code></pre> <p>Now I am asked to add the upload file functionality to my form which, of-course is impossible via JSON and so I am planning on moving to <code>FormData</code>. So is there any way that I can convert my JS object to <code>FormData</code>?</p>
<p>If you have an object, you can easily create a FormData object and append the names and values from that object to formData.</p> <p>You haven't posted any code, so it's a general example;</p> <pre><code>var form_data = new FormData(); for ( var key in item ) { form_data.append(key, item[key]); } $.ajax({ url : 'http://example.com/upload.php', data : form_data, processData : false, contentType : false, type: 'POST' }).done(function(data){ // do stuff }); </code></pre> <p>There are more examples in the documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects"><strong>MDN</strong></a></p>
{ "question_id": 22783108, "question_date": "2014-04-01T10:25:22.487Z", "question_score": 231, "tags": "javascript|jquery|multipartform-data|form-data", "answer_id": 22783314, "answer_date": "2014-04-01T10:33:49.583Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: pull out p-values and r-squared from a linear regression <p>How do you pull out the p-value (for the significance of the coefficient of the single explanatory variable being non-zero) and R-squared value from a simple linear regression model? For example...</p> <pre><code>x = cumsum(c(0, runif(100, -1, +1))) y = cumsum(c(0, runif(100, -1, +1))) fit = lm(y ~ x) summary(fit) </code></pre> <p>I know that <code>summary(fit)</code> <em>displays</em> the p-value and R-squared value, but I want to be able to stick these into other variables.</p>
<p><strong>r-squared</strong>: You can return the r-squared value directly from the summary object <code>summary(fit)$r.squared</code>. See <code>names(summary(fit))</code> for a list of all the items you can extract directly.</p> <p><strong>Model p-value:</strong> If you want to obtain the p-value of the overall regression model, <a href="http://gettinggeneticsdone.blogspot.com/2011/01/rstats-function-for-extracting-f-test-p.html" rel="noreferrer">this blog post</a> outlines a function to return the p-value:</p> <pre><code>lmp &lt;- function (modelobject) { if (class(modelobject) != "lm") stop("Not an object of class 'lm' ") f &lt;- summary(modelobject)$fstatistic p &lt;- pf(f[1],f[2],f[3],lower.tail=F) attributes(p) &lt;- NULL return(p) } &gt; lmp(fit) [1] 1.622665e-05 </code></pre> <p>In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same. </p> <p><strong>Coefficient p-values:</strong> If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:</p> <pre><code>summary(fit)$coefficients[,4] </code></pre> <p>Alternatively, you can grab the p-value of coefficients from the <code>anova(fit)</code> object in a similar fashion to the summary object above.</p>
{ "question_id": 5587676, "question_date": "2011-04-07T21:07:25.170Z", "question_score": 231, "tags": "r", "answer_id": 5587781, "answer_date": "2011-04-07T21:17:37.350Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: Lua string to int <p>How can I convert a string to an integer in Lua?</p> <p>I have a string like this:</p> <pre><code>a = "10" </code></pre> <p>I would like it to be converted to 10, the number.</p>
<p>Use the <a href="http://www.lua.org/manual/5.1/manual.html#pdf-tonumber" rel="noreferrer"><code>tonumber</code> function</a>. As in <code>a = tonumber("10")</code>.</p>
{ "question_id": 10962085, "question_date": "2012-06-09T15:09:26.470Z", "question_score": 231, "tags": "lua", "answer_id": 10962118, "answer_date": "2012-06-09T15:14:21.617Z", "answer_score": 363 }
Please answer the following Stack Overflow question: Title: Is it possible to animate scrollTop with jQuery? <p>I want to smoothly scroll down. I do not want to have to write a function for that - especially if jQuery already has one.</p>
<p>You can just use <a href="http://api.jquery.com/animate/" rel="noreferrer"><code>.animate()</code></a> the <code>scrollTop</code> property, like this:</p> <pre><code>$("html, body").animate({ scrollTop: "300px" }); </code></pre>
{ "question_id": 4034659, "question_date": "2010-10-27T15:00:48.010Z", "question_score": 231, "tags": "javascript|jquery", "answer_id": 4034674, "answer_date": "2010-10-27T15:02:39.077Z", "answer_score": 470 }
Please answer the following Stack Overflow question: Title: How do you stop MySQL on a Mac OS install? <p>I installed MySQL via <a href="http://en.wikipedia.org/wiki/MacPorts" rel="noreferrer">MacPorts</a>. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?</p>
<p>There are different cases depending on whether you installed <a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a> with the official binary installer, using <a href="http://en.wikipedia.org/wiki/MacPorts" rel="noreferrer">MacPorts</a>, or using <a href="http://brew.sh/" rel="noreferrer">Homebrew</a>:</p> <h2>Homebrew</h2> <pre><code>brew services start mysql brew services stop mysql brew services restart mysql </code></pre> <h2>MacPorts</h2> <pre><code>sudo port load mysql57-server sudo port unload mysql57-server </code></pre> <p>Note: this is persistent after a reboot.</p> <h2>Binary installer</h2> <pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop sudo /Library/StartupItems/MySQLCOM/MySQLCOM start sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart </code></pre>
{ "question_id": 100948, "question_date": "2008-09-19T10:21:42.700Z", "question_score": 231, "tags": "mysql|macos", "answer_id": 102094, "answer_date": "2008-09-19T14:08:18.373Z", "answer_score": 469 }
Please answer the following Stack Overflow question: Title: Difference between virtual and abstract methods <p>Here is some code from <a href="http://msdn.microsoft.com/en-us/library/ms173150.aspx" rel="noreferrer">MSDN</a>:</p> <pre><code>// compile with: /target:library public class D { public virtual void DoWork(int i) { // Original implementation. } } public abstract class E : D { public abstract override void DoWork(int i); } public class F : E { public override void DoWork(int i) { // New implementation. } } </code></pre> <p>Can anyone explain the above code with respect to the differences between abstract and virtual methods?</p>
<p>Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.</p> <p>So, abstract methods have no actual code in them, and (non-abstract) subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the <code>override</code> modifier and provide a custom implementation.</p> <pre><code>public abstract class E { public abstract void AbstractMethod(int i); public virtual void VirtualMethod(int i) { // Default implementation which can be overridden by subclasses. } } public class D : E { public override void AbstractMethod(int i) { // You HAVE to override this method } public override void VirtualMethod(int i) { // You are allowed to override this method. } } </code></pre>
{ "question_id": 14728761, "question_date": "2013-02-06T12:09:17.807Z", "question_score": 231, "tags": "c#|oop|virtual-functions|abstract-function", "answer_id": 14729005, "answer_date": "2013-02-06T12:23:01.630Z", "answer_score": 530 }
Please answer the following Stack Overflow question: Title: Show/Hide the console window of a C# console application <p>I googled around for information on how to hide one’s own console window. Amazingly, the only solutions I could find were hacky solutions that involved <code>FindWindow()</code> to find the console window <em>by its title</em>. I dug a bit deeper into the Windows API and found that there is a much better and easier way, so I wanted to post it here for others to find.</p> <p><strong>How do you hide (and show) the console window associated with my own C# console application?</strong></p>
<p>Here’s how:</p> <pre><code>using System.Runtime.InteropServices; </code></pre> <hr> <pre><code>[DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); const int SW_HIDE = 0; const int SW_SHOW = 5; </code></pre> <hr> <pre><code>var handle = GetConsoleWindow(); // Hide ShowWindow(handle, SW_HIDE); // Show ShowWindow(handle, SW_SHOW); </code></pre>
{ "question_id": 3571627, "question_date": "2010-08-26T02:19:37.873Z", "question_score": 231, "tags": "c#|console|console-application", "answer_id": 3571628, "answer_date": "2010-08-26T02:19:48.793Z", "answer_score": 317 }
Please answer the following Stack Overflow question: Title: Are arrays passed by value or passed by reference in Java? <p>Arrays are not a <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">primitive type</a> in Java, but they <a href="https://stackoverflow.com/questions/5564423/arrays-in-java-and-how-they-are-stored-in-memory">are not objects either</a>, so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?</p>
<p>Your question is based on a false premise.</p> <blockquote> <p><em>Arrays are not a primitive type in Java, but they are not objects either ... "</em></p> </blockquote> <p>In fact, all arrays in Java <strong>are</strong> objects<sup>1</sup>. Every Java array type has <code>java.lang.Object</code> as its supertype, and inherits the implementation of all methods in the <code>Object</code> API. </p> <blockquote> <p>... so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type? </p> </blockquote> <p>Short answers: 1) pass by value, and 2) it makes no difference.</p> <p>Longer answer:</p> <p>Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.</p> <p>This is NOT pass-by-reference. <em>Real</em> pass-by-reference involves passing the <em>address of a variable</em>. With <em>real</em> pass-by-reference, the called method can assign to its local variable, and this causes the variable in the caller to be updated. </p> <p>But not in Java. In Java, the called method can update the contents of the array, and it can update its copy of the array reference, but it can't update the variable in the caller that holds the caller's array reference. Hence ... what Java is providing is NOT pass-by-reference.</p> <p>Here are some links that explain the difference between pass-by-reference and pass-by-value. If you don't understand my explanations above, or if you feel inclined to disagree with the terminology, you <em>should</em> read them.</p> <ul> <li><a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr233.htm" rel="noreferrer">http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr233.htm</a></li> <li><a href="http://www.cs.fsu.edu/~myers/c++/notes/references.html" rel="noreferrer">http://www.cs.fsu.edu/~myers/c++/notes/references.html</a></li> </ul> <p>Related SO question:</p> <ul> <li><a href="https://stackoverflow.com/questions/40480/is-java-pass-by-reference">Is Java &quot;pass-by-reference&quot; or &quot;pass-by-value&quot;?</a></li> </ul> <p>Historical background:</p> <p>The phrase "pass-by-reference" was originally "call-by-reference", and it was used to distinguish the argument passing semantics of FORTRAN (call-by-reference) from those of ALGOL-60 (call-by-value and call-by-name).</p> <ul> <li><p>In call-by-value, the argument expression is evaluated to a value, and that value is copied to the called method.</p></li> <li><p>In call-by-reference, the argument expression is partially evaluated to an "lvalue" (i.e. the address of a variable or array element) that is passed to the calling method. The calling method can then directly read and update the variable / element.</p></li> <li><p>In call-by-name, the actual argument expression is passed to the calling method (!!) which can evaluate it multiple times (!!!). This was complicated to implement, and could be used (abused) to write code that was very difficult to understand. Call-by-name was only ever used in Algol-60 (thankfully!).</p></li> </ul> <p><strong>UPDATE</strong></p> <p>Actually, Algol-60's call-by-name is similar to passing lambda expressions as parameters. The wrinkle is that these not-exactly-lambda-expressions (they were referred to as "thunks" at the implementation level) can <em>indirectly</em> modify the state of variables that are in scope in the calling procedure / function. That is part of what made them so hard to understand. (See the Wikipedia page on <a href="http://en.wikipedia.org/wiki/Jensen%27s_Device" rel="noreferrer">Jensen's Device</a> for example.)</p> <hr> <p><sup>1. Nothing in the linked Q&amp;A (<a href="https://stackoverflow.com/questions/5564423/arrays-in-java-and-how-they-are-stored-in-memory">Arrays in Java and how they are stored in memory</a>) either states or implies that arrays are not objects.</sup></p>
{ "question_id": 12757841, "question_date": "2012-10-06T07:44:15.833Z", "question_score": 231, "tags": "java|arrays", "answer_id": 12757868, "answer_date": "2012-10-06T07:47:44.567Z", "answer_score": 172 }
Please answer the following Stack Overflow question: Title: bash "if [ false ];" returns true instead of false -- why? <p>Why does the following output <code>True</code>?</p> <pre><code>#!/bin/sh if [ false ]; then echo &quot;True&quot; else echo &quot;False&quot; fi </code></pre> <p>This will always output <code>True</code> even though the condition would seem to indicate otherwise. If I remove the brackets <code>[]</code> then it works, but I do not understand why.</p>
<p>You are running the <code>[</code> (aka <code>test</code>) command with the argument "false", not running the command <code>false</code>. Since "false" is a non-empty string, the <code>test</code> command always succeeds. To actually run the command, drop the <code>[</code> command.</p> <pre><code>if false; then echo "True" else echo "False" fi </code></pre>
{ "question_id": 19670061, "question_date": "2013-10-29T22:04:07.797Z", "question_score": 231, "tags": "bash|boolean|conditional-operator", "answer_id": 19670094, "answer_date": "2013-10-29T22:06:19.713Z", "answer_score": 282 }