input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: What is the syntax for writing comments in build.gradle file? <p>Looking down this <code>build.gradle</code> file</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "package.myapp" minSdkVersion 19 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.nineoldandroids:library:2.4.0' } </code></pre> <p>What if I would like to write a comment on <em>why did I chose this library for this project</em>,</p> <p>what is the syntax for writing comments in <code>build.gradle</code> file?</p>
<p>Easy:</p> <pre><code>// Single line comment /* Multi line comment */ </code></pre>
{ "question_id": 32569883, "question_date": "2015-09-14T16:49:39.250Z", "question_score": 209, "tags": "android|gradle|comments|android-gradle-plugin|build.gradle", "answer_id": 32569925, "answer_date": "2015-09-14T16:52:02.327Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: How to add edge labels in Graphviz? <p>I am trying to draw a graph using Graphviz, but I need to add labels on the edges. There does not seem to be any way to that in Graphviz. Are there a way out?</p>
<p>You use the <a href="http://www.graphviz.org/doc/info/attrs.html#d:label" rel="noreferrer">label property</a> attached to the edge. </p> <pre><code>digraph G { a -&gt; b [ label="a to b" ]; b -&gt; c [ label="another label"]; } </code></pre> <p>The above generates a graph that looks something like this.</p> <p><img src="https://i.stack.imgur.com/0L6ON.png" alt="alt text"></p>
{ "question_id": 1806870, "question_date": "2009-11-27T05:08:53.647Z", "question_score": 209, "tags": "graphviz|dot", "answer_id": 1806873, "answer_date": "2009-11-27T05:11:08.217Z", "answer_score": 283 }
Please answer the following Stack Overflow question: Title: How do I turn on text wrapping by default in VS Code <p>Usually when I use VS Code, very first thing I do on new document is command: "Toggle Word Wrap" or <kbd>Alt</kbd>+<kbd>Z</kbd>. I tried looking into User Settings, but I didn't find any relevant entries. Is there some way to have text wrapping 'on' for every document by default?</p>
<p>The setting is now <code>&quot;editor.wordWrap&quot;: &quot;on&quot;</code>, which should be set to <code>&quot;on&quot;</code> (the default value is <code>&quot;off&quot;</code>).</p> <p>Switching to <code>&quot;on&quot;</code> activates word wrap on all documents in Visual Studio Code.</p> <p>See the <a href="https://code.visualstudio.com/updates/v1_10#_word-wrap-settings-redesign" rel="noreferrer">release notes about Word Wrap changes</a> for more info.</p>
{ "question_id": 38561881, "question_date": "2016-07-25T07:24:48.990Z", "question_score": 209, "tags": "visual-studio-code|vscode-settings", "answer_id": 43219246, "answer_date": "2017-04-04T23:13:34.070Z", "answer_score": 270 }
Please answer the following Stack Overflow question: Title: Canvas is stretched when using CSS but normal with "width" / "height" properties <p>I have 2 canvases, one uses HTML attributes <code>width</code> and <code>height</code> to size it, the other uses CSS:</p> <pre class="lang-html prettyprint-override"><code>&lt;canvas id=&quot;compteur1&quot; width=&quot;300&quot; height=&quot;300&quot; onmousedown=&quot;compteurClick(this.id);&quot;&gt;&lt;/canvas&gt; &lt;canvas id=&quot;compteur2&quot; style=&quot;width: 300px; height: 300px;&quot; onmousedown=&quot;compteurClick(this.id);&quot;&gt;&lt;/canvas&gt; </code></pre> <p>Compteur1 displays like it should, but not compteur2. The content is drawn using JavaScript on a 300x300 canvas.</p> <p>Why is there a display difference?</p> <p><img src="https://i.stack.imgur.com/2jpjv.jpg" alt="alt text" /></p>
<p>It seems that the <code>width</code> and <code>height</code> attributes determine the width or height of the canvas’s coordinate system, whereas the CSS properties just determine the size of the box in which it will be shown.</p> <p>This is explained in the <a href="https://html.spec.whatwg.org/multipage/canvas.html#attr-canvas-width" rel="noreferrer">HTML specification</a>:</p> <blockquote> <p>The <code>canvas</code> element has two attributes to control the size of the element’s bitmap: <code>width</code> and <code>height</code>. These attributes, when specified, must have values that are <em>valid non-negative integers</em>. The <em>rules for parsing non-negative integers</em> must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The <code>width</code> attribute defaults to 300, and the <code>height</code> attribute defaults to 150.</p> </blockquote>
{ "question_id": 2588181, "question_date": "2010-04-06T20:45:34.007Z", "question_score": 209, "tags": "css|html|canvas|height|width", "answer_id": 2588404, "answer_date": "2010-04-06T21:16:55.937Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: Rails - Nested includes on Active Records? <p>I have a list of events that I fetch. I'm trying to include every user associated to this event and every profile associated to each user. The Users get included but not their profiles.</p> <p>How Would i do this</p> <pre><code>Event.includes(:users [{profile:}]) </code></pre> <p>The docs don't seem to be clear: <a href="http://guides.rubyonrails.org/active_record_querying.html">http://guides.rubyonrails.org/active_record_querying.html</a></p>
<p>I believe the following should work for you.</p> <pre><code>Event.includes(users: :profile) </code></pre> <p>If you want to include an association (we'll call it C) of an already included association (we'll call it B), you'd use the syntax above. However, if you'd like to include D as well, which is also an association of B, that's when you'd use the array as given in the example in the <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="noreferrer">Rails Guide</a>.</p> <pre><code>A.includes(bees: [ :cees, :dees ]) </code></pre> <p>You could continue to nest includes like that (if you actually need to). Say that A is also associated with Z, and that C is associated to E and F.</p> <pre><code>A.includes({ bees: [{ cees: [:ees, :effs] }, :dees] }, :zees) </code></pre> <p>And for good fun, we'll also say that E is associated to J and X, and that D is associated to Y.</p> <pre><code>A.includes({ bees: [{ cees: [{ ees: [:jays, :exes] }, :effs] }, { dees: :wise } ] }, :zees) </code></pre>
{ "question_id": 24397640, "question_date": "2014-06-24T22:52:49.283Z", "question_score": 209, "tags": "ruby-on-rails|rails-activerecord", "answer_id": 24397716, "answer_date": "2014-06-24T22:59:43.083Z", "answer_score": 482 }
Please answer the following Stack Overflow question: Title: How do I typedef a function pointer with the C++11 using syntax? <p>I'd like to write this</p> <pre><code>typedef void (*FunctionPtr)(); </code></pre> <p>using <code>using</code>. How would I do that?</p>
<p>It has a similar syntax, except you remove the identifier from the pointer:</p> <pre><code>using FunctionPtr = void (*)(); </code></pre> <p>Here is an <a href="http://ideone.com/dX3vQC">Example</a></p> <p>If you want to "take away the uglyness", try what Xeo suggested:</p> <pre><code>#include &lt;type_traits&gt; using FunctionPtr = std::add_pointer&lt;void()&gt;::type; </code></pre> <p>And here is another <a href="http://ideone.com/Fol5OL">demo</a>.</p>
{ "question_id": 16498969, "question_date": "2013-05-11T15:50:22.960Z", "question_score": 209, "tags": "c++|c++11|typedef", "answer_id": 16498976, "answer_date": "2013-05-11T15:50:50.503Z", "answer_score": 235 }
Please answer the following Stack Overflow question: Title: Can I use the range operator with if statement in Swift? <p>Is it possible to use the range operator <code>...</code> and <code>..&lt;</code> with if statement. Maye something like this:</p> <pre><code>let statusCode = 204 if statusCode in 200 ..&lt; 299 { NSLog("Success") } </code></pre>
<p>You can use the "pattern-match" operator <code>~=</code>:</p> <pre><code>if 200 ... 299 ~= statusCode { print("success") } </code></pre> <p>Or a switch-statement with an expression pattern (which uses the pattern-match operator internally):</p> <pre><code>switch statusCode { case 200 ... 299: print("success") default: print("failure") } </code></pre> <p>Note that <code>..&lt;</code> denotes a range that omits the upper value, so you probably want <code>200 ... 299</code> or <code>200 ..&lt; 300</code>.</p> <p><strong>Additional information:</strong> When the above code is compiled in Xcode 6.3 with optimizations switch on, then for the test</p> <pre><code>if 200 ... 299 ~= statusCode </code></pre> <p>actually no function call is generated at all, only three assembly instruction:</p> <pre><code>addq $-200, %rdi cmpq $99, %rdi ja LBB0_1 </code></pre> <p>this is exactly the same assembly code that is generated for</p> <pre><code>if statusCode &gt;= 200 &amp;&amp; statusCode &lt;= 299 </code></pre> <p>You can verify that with</p> <pre> xcrun -sdk macosx swiftc -O -emit-assembly main.swift </pre> <p><strong>As of Swift 2,</strong> this can be written as</p> <pre><code>if case 200 ... 299 = statusCode { print("success") } </code></pre> <p>using the newly introduced pattern-matching for if-statements. See also <a href="https://stackoverflow.com/questions/30720289/swift-2-pattern-matching-in-if">Swift 2 - Pattern matching in &quot;if&quot;</a>.</p>
{ "question_id": 24893110, "question_date": "2014-07-22T16:42:10.643Z", "question_score": 209, "tags": "if-statement|swift|range", "answer_id": 24893494, "answer_date": "2014-07-22T17:04:46.347Z", "answer_score": 462 }
Please answer the following Stack Overflow question: Title: "where 1=1" statement <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/242822/why-would-someone-use-where-1-1-and-conditions-in-a-sql-clause">Why would someone use WHERE 1=1 AND &lt;conditions&gt; in a SQL clause?</a> </p> </blockquote> <p>I saw some people use a statement to query a table in a MySQL database like the following:</p> <pre><code>select * from car_table where 1=1 and value="TOYOTA" </code></pre> <p>But what does <code>1=1</code> mean here?</p>
<p>It's usually when folks build up SQL statements.</p> <p>When you add <code>and value = "Toyota"</code> you don't have to worry about whether there is a condition before or just WHERE. The optimiser should ignore it</p> <p>No magic, just practical</p> <hr> <p>Example Code:</p> <pre><code>commandText = "select * from car_table where 1=1"; if (modelYear &lt;&gt; 0) commandText += " and year="+modelYear if (manufacturer &lt;&gt; "") commandText += " and value="+QuotedStr(manufacturer) if (color &lt;&gt; "") commandText += " and color="+QuotedStr(color) if (california) commandText += " and hasCatalytic=1" </code></pre> <p>Otherwise you would have to have a complicated set of logic:</p> <pre><code>commandText = "select * from car_table" whereClause = ""; if (modelYear &lt;&gt; 0) { if (whereClause &lt;&gt; "") whereClause = whereClause + " and "; commandText += "year="+modelYear; } if (manufacturer &lt;&gt; "") { if (whereClause &lt;&gt; "") whereClause = whereClause + " and "; commandText += "value="+QuotedStr(manufacturer) } if (color &lt;&gt; "") { if (whereClause &lt;&gt; "") whereClause = whereClause + " and "; commandText += "color="+QuotedStr(color) } if (california) { if (whereClause &lt;&gt; "") whereClause = whereClause + " and "; commandText += "hasCatalytic=1" } if (whereClause &lt;&gt; "") commandText = commandText + "WHERE "+whereClause; </code></pre>
{ "question_id": 8149142, "question_date": "2011-11-16T09:12:32.430Z", "question_score": 209, "tags": "mysql|sql|database", "answer_id": 8149183, "answer_date": "2011-11-16T09:15:10.463Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional <p>I don't understand what is the actual difference between annotations <code>javax.transaction.Transactional</code> and <code>org.springframework.transaction.annotation.Transactional</code>?</p> <p>Is <code>org.springframework.transaction.annotation.Transactional</code> an extension of <code>javax.transaction.Transactional</code> or they have totally different meaning? When should each of them be used? Spring <code>@Transactinal</code> in service layer and <em>javax</em> in DAO?</p> <p>Thanks for answering.</p>
<p>Spring has defined its own Transactional annotation to make Spring bean methods transactional, years ago. </p> <p>Java EE 7 has finally done the same thing and now allows CDI bean methods to be transactional, in addition to EJB methods. So since Java EE 7, it also defines its own Transactional annotation (it obviously can't reuse the Spring one).</p> <p>In a Java EE 7 application, you'll use the Java EE annotation.</p> <p>In a Spring application, you'll use the Spring annotation.</p> <p>Their use is the same: informing the container (Java EE or Spring) that a method is transactional.</p>
{ "question_id": 26387399, "question_date": "2014-10-15T16:22:40.370Z", "question_score": 209, "tags": "java|spring|hibernate|transactions|jta", "answer_id": 26387927, "answer_date": "2014-10-15T16:54:07.507Z", "answer_score": 169 }
Please answer the following Stack Overflow question: Title: Have Grunt generate index.html for different setups <p>I'm trying to use Grunt as a build tool for my webapp.</p> <p>I want to have at least two setups: </p> <p><strong>I. Development setup</strong> - load scripts from separate files, without concatenation,</p> <p>so my index.html would look something like:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="js/module1.js" /&gt; &lt;script src="js/module2.js" /&gt; &lt;script src="js/module3.js" /&gt; ... &lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>II. Production setup</strong> - load my scripts minified &amp; concatenated in one file,</p> <p>with index.html accordingly:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="js/MyApp-all.min.js" /&gt; &lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>The question is, <em>how can I make grunt make these index.html's depending on the configuration when I run <code>grunt dev</code> or <code>grunt prod</code>?</em></p> <p>Or maybe I'm digging in the wrong direction and it would be easier to always generate <code>MyApp-all.min.js</code> but put inside it either all my scripts (concatenated) or a loader script that asynchronously loads those scripts from separate files?</p> <p>How do you do it, guys?</p>
<p>I've come up with my own solution. Not polished yet but I think I'm going to move in that direction.</p> <p>In essense, I'm using <a href="https://github.com/cowboy/grunt/blob/master/docs/api_template.md">grunt.template.process()</a> to generate my <code>index.html</code> from a template that analyzes current configuration and produces either a list of my original source files or links to a single file with minified code. The below example is for js files but the same approach can be extended to css and any other possible text files.</p> <p><strong><code>grunt.js</code>:</strong></p> <pre><code>/*global module:false*/ module.exports = function(grunt) { var // js files jsFiles = [ 'src/module1.js', 'src/module2.js', 'src/module3.js', 'src/awesome.js' ]; // Import custom tasks (see index task below) grunt.loadTasks( "build/tasks" ); // Project configuration. grunt.initConfig({ pkg: '&lt;json:package.json&gt;', meta: { banner: '/*! &lt;%= pkg.name %&gt; - v&lt;%= pkg.version %&gt; - ' + '&lt;%= grunt.template.today("yyyy-mm-dd") %&gt; */' }, jsFiles: jsFiles, // file name for concatenated js concatJsFile: '&lt;%= pkg.name %&gt;-all.js', // file name for concatenated &amp; minified js concatJsMinFile: '&lt;%= pkg.name %&gt;-all.min.js', concat: { dist: { src: ['&lt;banner:meta.banner&gt;'].concat(jsFiles), dest: 'dist/&lt;%= concatJsFile %&gt;' } }, min: { dist: { src: ['&lt;banner:meta.banner&gt;', '&lt;config:concat.dist.dest&gt;'], dest: 'dist/&lt;%= concatJsMinFile %&gt;' } }, lint: { files: ['grunt.js'].concat(jsFiles) }, // options for index.html builder task index: { src: 'index.tmpl', // source template file dest: 'index.html' // destination file (usually index.html) } }); // Development setup grunt.registerTask('dev', 'Development build', function() { // set some global flags that all tasks can access grunt.config('isDebug', true); grunt.config('isConcat', false); grunt.config('isMin', false); // run tasks grunt.task.run('lint index'); }); // Production setup grunt.registerTask('prod', 'Production build', function() { // set some global flags that all tasks can access grunt.config('isDebug', false); grunt.config('isConcat', true); grunt.config('isMin', true); // run tasks grunt.task.run('lint concat min index'); }); // Default task grunt.registerTask('default', 'dev'); }; </code></pre> <p><strong><code>index.js (the index task)</code>:</strong></p> <pre><code>module.exports = function( grunt ) { grunt.registerTask( "index", "Generate index.html depending on configuration", function() { var conf = grunt.config('index'), tmpl = grunt.file.read(conf.src); grunt.file.write(conf.dest, grunt.template.process(tmpl)); grunt.log.writeln('Generated \'' + conf.dest + '\' from \'' + conf.src + '\''); }); } </code></pre> <p>Finally, <strong><code>index.tmpl</code></strong>, with generation logic baked in:</p> <pre><code>&lt;doctype html&gt; &lt;head&gt; &lt;% var jsFiles = grunt.config('jsFiles'), isConcat = grunt.config('isConcat'); if(isConcat) { print('&lt;script type="text/javascript" src="' + grunt.config('concat.dist.dest') + '"&gt;&lt;/script&gt;\n'); } else { for(var i = 0, len = jsFiles.length; i &lt; len; i++) { print('&lt;script type="text/javascript" src="' + jsFiles[i] + '"&gt;&lt;/script&gt;\n'); } } %&gt; &lt;/head&gt; &lt;html&gt; &lt;/html&gt; </code></pre> <hr> <p><strong>UPD.</strong> Found out that <a href="http://yeoman.io/">Yeoman</a>, which is based on grunt, has a built-in <a href="https://github.com/yeoman/yeoman/blob/0.9.6/cli/tasks/usemin.js">usemin</a> task that integrates with Yeoman's build system. It generates a production version of index.html from information in development version of index.html as well as other environment settings. A bit sophisticated but interesting to look at.</p>
{ "question_id": 12401998, "question_date": "2012-09-13T08:08:55.367Z", "question_score": 209, "tags": "javascript|build|build-automation|gruntjs", "answer_id": 12424966, "answer_date": "2012-09-14T12:51:32.913Z", "answer_score": 35 }
Please answer the following Stack Overflow question: Title: Difference between Lookup() and Dictionary(Of list()) <p>I'm trying to wrap my head around which data structures are the most efficient and when / where to use which ones.</p> <p>Now, it could be that I simply just don't understand the structures well enough, but how is an <code>ILookup(of key, ...)</code> different from a <code>Dictionary(of key, list(of ...))</code>?</p> <p>Also where would I want to use an <code>ILookup</code> and where would it be more efficient in terms of program speed / memory / data accessing, etc?</p>
<p>Two significant differences:</p> <ul> <li><code>Lookup</code> is immutable. Yay :) (At least, I believe the concrete <code>Lookup</code> class is immutable, and the <code>ILookup</code> interface doesn't provide any mutating members. There <em>could</em> be other mutable implementations, of course.)</li> <li>When you lookup a key which isn't present in a lookup, you get an empty sequence back instead of a <code>KeyNotFoundException</code>. (Hence there's no <code>TryGetValue</code>, AFAICR.)</li> </ul> <p>They're likely to be equivalent in efficiency - the lookup may well use a <code>Dictionary&lt;TKey, GroupingImplementation&lt;TValue&gt;&gt;</code> behind the scenes, for example. Choose between them based on your requirements. Personally I find that the lookup is usually a better fit than a <code>Dictionary&lt;TKey, List&lt;TValue&gt;&gt;</code>, mostly due to the first two points above.</p> <p>Note that as an implementation detail, the concrete implementation of <code>IGrouping&lt;,&gt;</code> which is used for the values implements <code>IList&lt;TValue&gt;</code>, which means that it's efficient to use with <code>Count()</code>, <code>ElementAt()</code> etc.</p>
{ "question_id": 13362490, "question_date": "2012-11-13T14:28:21.200Z", "question_score": 209, "tags": "c#|.net|vb.net|linq", "answer_id": 13362570, "answer_date": "2012-11-13T14:33:15.503Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: Turning live() into on() in jQuery <p>My application has dynamically added Dropdowns. The user can add as many as they need to. </p> <p>I was traditionally using jQuery's <code>live()</code> method to detect when one of these Dropdowns was <code>change()</code>ed:</p> <pre><code>$('select[name^="income_type_"]').live('change', function() { alert($(this).val()); }); </code></pre> <p>As of jQuery 1.7, I've updated this to:</p> <pre><code>$('select[name^="income_type_"]').on('change', function() { alert($(this).val()); }); </code></pre> <p>Looking at the Docs, that should be perfectly valid (right?) - but the event handler never fires. Of course, I've confirmed jQuery 1.7 is loaded and running, etc. There are no errors in the error log.</p> <p>What am I doing wrong? Thanks!</p>
<p>The <a href="http://api.jquery.com/on/"><code>on</code> documentation</a> states (in bold ;)):</p> <blockquote> <p>Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to <code>.on()</code>. </p> </blockquote> <p>Equivalent to <code>.live()</code> would be something like</p> <pre><code>$(document.body).on('change', 'select[name^="income_type_"]', function() { alert($(this).val()); }); </code></pre> <p>Although it is better if you bind the event handler as close as possible to the elements, that is, to an element being closer in the hierarchy.</p> <p><strong>Update:</strong> While answering another question, I found out that this is also mentioned in the <a href="http://api.jquery.com/live/"><code>.live</code> documentation</a>:</p> <blockquote> <p>Rewriting the <code>.live()</code> method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:</p> <pre><code>$(selector).live(events, data, handler); // jQuery 1.3+ $(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ $(document).on(events, selector, data, handler); // jQuery 1.7+ </code></pre> </blockquote>
{ "question_id": 8021436, "question_date": "2011-11-05T16:16:03.357Z", "question_score": 209, "tags": "javascript|jquery|jquery-1.7", "answer_id": 8021462, "answer_date": "2011-11-05T16:20:01.693Z", "answer_score": 252 }
Please answer the following Stack Overflow question: Title: How do I move the turtle in LOGO? <p>How do I move the <a href="http://en.wikipedia.org/wiki/Turtle_graphics" rel="nofollow noreferrer">turtle</a> in <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)" rel="nofollow noreferrer">LOGO</a>?</p>
<pre><code>// MOVE FORWARD FD 75 // TURN RIGHT RT 54 // TURN LEFT LT 21 // MOVE BACKWARD BK 17 </code></pre> <p>Check out some other turtle commands found <a href="http://gaza.freehosting.net/logo/index.html" rel="nofollow noreferrer">here</a>...</p> <hr> <h1>Turtle Commands</h1> <ul> <li><code>BACK ## [BK]</code> - Move turtle back</li> <li><p><code>BACKGROUND ## [BG]</code> - Set Background color (0-15)</p> <ul> <li>0 - Black</li> <li>1 - White </li> <li>2 - Red</li> <li>3 - Cyan</li> <li>4 - Purple </li> <li>5 - Green</li> <li>6 - Blue</li> <li>7 - Yellow</li> <li>8 - Orange</li> <li>9 - Brown</li> <li>10 - Light Red</li> <li>11 - Grey 1</li> <li>12 - Grey 2</li> <li>13 - Light Green</li> <li>14 - Light Blue</li> <li>15 - Grey 3</li> </ul></li> <li><p><code>CLEARSCREEN [CS]</code> - Clear Screen without moving turtle</p></li> <li><code>DRAW</code> - Clear Screen and take turtle home</li> <li><code>EACH</code> - Tell several sprites, whose numbers are in a list, to accept commands in a second list, e.g. <code>EACH [1 2] [SQUARE 10]</code></li> <li><code>FORWARD ## [FD]</code> - Move turtle forward</li> <li><code>FULLSCREEN</code> - Full graphics screen (same as pressing F5)</li> <li><code>HEADING</code> - Output turtle heading as a number (0-359)</li> <li><code>HIDETURTLE [HT]</code> - Make turtle invisible</li> <li><code>HOME</code> - Move turtle to center of screen pointing up</li> <li><code>LEFT [LT]</code> - Turn turtle left</li> <li><code>NODRAW [ND]</code> - Enter text mode with clear screen</li> <li><code>NOWRAP</code> - Prevent drawings from wrapping around screen</li> <li><code>PENCOLOR [PC]</code> - Change pen color</li> <li><code>PENDOWN [PD]</code> - Turtle leaves trail</li> <li><code>PENUP [PU]</code> - Turtle ceases to leave trail</li> <li><code>RIGHT ## [RT]</code> - Turn turtle right</li> <li><code>SETHEADING [SETH]</code> - Set turtle heading, e.g. <code>SETH 180</code></li> <li><code>SETSHAPE</code> - Set the current sprite shape (0-7)</li> <li><code>SETX</code> Move the turtle to the specified x co-ordinates e.g. <code>SETX 50</code></li> <li><code>SETXY</code> Move the turtle to the specified x, y co-ordinates Eg. <code>SETXY 50 50</code></li> <li><code>SETY</code> Move the turtle to the specified y co-ordinate, e.g. <code>SETY 50</code></li> <li><code>SHAPE</code> - Output number of current sprite's shape</li> <li><code>SHOWTURTLE [ST]</code> - Make turtle visible</li> <li><code>SPLITSCREEN</code> - Mixed graphics and text screen (same as pressing F3)</li> <li><code>STAMPCHAR</code> - Make the turtle stamp a character at the current location, e.g. <code>STAMPCHAR "A</code></li> <li><code>TELL</code> - Tell designated sprite to receive commands, e.g. <code>TELL 2</code></li> <li><code>TEXTSCREEN</code> - Use whole screen for text (same as pressing <kbd>F1</kbd>)</li> <li><code>TOWARDS</code> - Output heading for turtle to face an X,Y coordinate, e.g. <code>TOWARDS 0 0</code></li> <li><code>WRAP</code> - Make turtle drawings wrap around the screen</li> <li><code>XCOR</code> - Output current x co-ordinate of turtle</li> <li><code>YCOR</code> - Output current y co-ordinate of turtle</li> <li><code>ASPECT</code> - Set verticle screen scale factor, default is 0.76</li> </ul> <hr> <p><em>Samples taken directly from website: <a href="http://gaza.freehosting.net/logo/index.html" rel="nofollow noreferrer">http://gaza.freehosting.net/logo/index.html</a></em></p>
{ "question_id": 1003841, "question_date": "2009-06-16T20:42:06.190Z", "question_score": 209, "tags": "turtle-graphics|logo-lang", "answer_id": 1003856, "answer_date": "2009-06-16T20:46:38.753Z", "answer_score": 234 }
Please answer the following Stack Overflow question: Title: how to write setTimeout with params by Coffeescript <p>Please tell me how to write javascript below in coffeescript.</p> <pre><code>setTimeout(function(){ something(param); }, 1000); </code></pre>
<p>I think it's a useful convention for callbacks to come as the last argument to a function. This is usually the case with the Node.js API, for instance. So with that in mind:</p> <pre><code>delay = (ms, func) -&gt; setTimeout func, ms delay 1000, -&gt; something param </code></pre> <p>Granted, this adds the overhead of an extra function call to every <code>setTimeout</code> you make; but in today's JS interpreters, the performance drawback is insignificant unless you're doing it thousands of times per second. (And what are you doing setting thousands of timeouts per second, anyway?)</p> <p>Of course, a more straightforward approach is to simply name your callback, which tends to produce more readable code anyway (jashkenas is a big fan of this idiom):</p> <pre><code>callback = -&gt; something param setTimeout callback, 1000 </code></pre>
{ "question_id": 6459630, "question_date": "2011-06-23T19:33:21.753Z", "question_score": 209, "tags": "javascript|settimeout|coffeescript", "answer_id": 6460151, "answer_date": "2011-06-23T20:22:21.930Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: What are attributes in .NET? <p>What are attributes in .NET, what are they good for, and how do I create my own attributes?</p>
<p>Metadata. Data about your objects/methods/properties. </p> <p>For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.</p> <pre><code>public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject .SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject .SomeDate; } } } </code></pre> <p>Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.</p> <p>However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:</p> <pre><code>[Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } </code></pre> <p>Tells the designer not to list this in the available properties in the Properties window at design time for example.</p> <p>You <em>could</em> also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods.</p> <pre><code>public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } </code></pre> <p>Declaring them is easy, just make a class that inherits from Attribute. </p> <pre><code>public class DisplayOrderAttribute : Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } </code></pre> <p>And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you.</p> <p><strong>NOTE:</strong> Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly).<br> So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them. </p>
{ "question_id": 20346, "question_date": "2008-08-21T15:59:39.773Z", "question_score": 209, "tags": "c#|.net|glossary|.net-attributes", "answer_id": 20418, "answer_date": "2008-08-21T16:18:26.767Z", "answer_score": 146 }
Please answer the following Stack Overflow question: Title: How to apt-get install in a GitHub Actions workflow? <p>In the new GitHub Actions, I am trying to install a package in order to use it in one of the next steps.</p> <pre class="lang-yaml prettyprint-override"><code>name: CI on: [push, pull_request] jobs: translations: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 with: fetch-depth: 1 - name: Install xmllint run: apt-get install libxml2-utils # ... </code></pre> <p>However this fails with</p> <pre><code>Run apt-get install libxml2-utils apt-get install libxml2-utils shell: /bin/bash -e {0} E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root? ##[error]Process completed with exit code 100. </code></pre> <p>What's the best way to do this? Do I need to reach for Docker?</p>
<p>The <a href="https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners" rel="noreferrer">docs</a> say:</p> <blockquote> <p>The Linux and macOS virtual machines both run using passwordless <code>sudo</code>. When you need to execute commands or install tools that require more privileges than the current user, you can use <code>sudo</code> without needing to provide a password.</p> </blockquote> <p>So simply doing the following should work:</p> <pre><code>- name: Install xmllint run: sudo apt-get install -y libxml2-utils </code></pre>
{ "question_id": 57982945, "question_date": "2019-09-17T22:51:27.333Z", "question_score": 209, "tags": "installation|github-actions|sudo|apt", "answer_id": 58002908, "answer_date": "2019-09-19T02:29:14.597Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: How does the new automatic reference counting mechanism work? <p>Can someone briefly explain to me how ARC works? I know it's different from Garbage Collection, but I was just wondering exactly how it worked.</p> <p>Also, if ARC does what GC does without hindering performance, then why does Java use GC? Why doesn't it use ARC as well?</p>
<p>Every new developer who comes to Objective-C has to learn the rigid rules of when to retain, release, and autorelease objects. These rules even specify naming conventions that imply the retain count of objects returned from methods. Memory management in Objective-C becomes second nature once you take these rules to heart and apply them consistently, but even the most experienced Cocoa developers slip up from time to time.</p> <p>With the Clang Static Analyzer, the LLVM developers realized that these rules were reliable enough that they could build a tool to point out memory leaks and overreleases within the paths that your code takes.</p> <p><a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" rel="noreferrer">Automatic reference counting</a> (ARC) is the next logical step. If the compiler can recognize where you should be retaining and releasing objects, why not have it insert that code for you? Rigid, repetitive tasks are what compilers and their brethren are great at. Humans forget things and make mistakes, but computers are much more consistent.</p> <p>However, this doesn't completely free you from worrying about memory management on these platforms. I describe the primary issue to watch out for (retain cycles) in my answer <a href="https://stackoverflow.com/questions/6260256/what-kind-of-leaks-does-objective-cs-automatic-reference-counting-in-xcode-4-2/6388601#6388601">here</a>, which may require a little thought on your part to mark weak pointers. However, that's minor when compared to what you're gaining in ARC.</p> <p>When compared to manual memory management and garbage collection, ARC gives you the best of both worlds by cutting out the need to write retain / release code, yet not having the halting and sawtooth memory profiles seen in a garbage collected environment. About the only advantages garbage collection has over this are its ability to deal with retain cycles and the fact that atomic property assignments are inexpensive (as discussed <a href="http://lists.apple.com/archives/objc-language/2011/Jun/msg00013.html" rel="noreferrer">here</a>). I know I'm replacing all of my existing Mac GC code with ARC implementations.</p> <p>As to whether this could be extended to other languages, it seems geared around the reference counting system in Objective-C. It might be difficult to apply this to Java or other languages, but I don't know enough about the low-level compiler details to make a definitive statement there. Given that Apple is the one pushing this effort in LLVM, Objective-C will come first unless another party commits significant resources of their own to this.</p> <p>The unveiling of this shocked developers at WWDC, so people weren't aware that something like this could be done. It may appear on other platforms over time, but for now it's exclusive to LLVM and Objective-C.</p>
{ "question_id": 6385212, "question_date": "2011-06-17T11:40:40.300Z", "question_score": 209, "tags": "objective-c|cocoa-touch|garbage-collection|automatic-ref-counting", "answer_id": 6418410, "answer_date": "2011-06-20T22:43:31.627Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: What Java 8 Stream.collect equivalents are available in the standard Kotlin library? <p>In Java 8, there is <a href="https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html#collect" rel="noreferrer"><code>Stream.collect</code></a> which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib. But it isn't clear what the equivalences are for different use cases. </p> <p>For example, at the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html" rel="noreferrer">top of the JavaDoc for <code>Collectors</code></a> are examples written for Java 8, and when porting them to Kolin you can't use the Java 8 classes when on a different JDK version, so likely they should be written differently. </p> <p>In terms of resources online showing examples of Kotlin collections, they are typically trivial and don't really compare to the same use cases. What are good examples that really match the cases such as documented for Java 8 <code>Stream.collect</code>? The list there is:</p> <ul> <li>Accumulate names into a List</li> <li>Accumulate names into a TreeSet</li> <li>Convert elements to strings and concatenate them, separated by commas</li> <li>Compute sum of salaries of employee</li> <li>Group employees by department</li> <li>Compute sum of salaries by department</li> <li>Partition students into passing and failing</li> </ul> <p>With details in the JavaDoc linked above.</p> <p><strong><em>Note:</em></strong> <em>this question is intentionally written and answered by the author (<a href="https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/">Self-Answered Questions</a>), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.</em></p>
<p>There are functions in the Kotlin stdlib for average, count, distinct,filtering, finding, grouping, joining, mapping, min, max, partitioning, slicing, sorting, summing, to/from arrays, to/from lists, to/from maps, union, co-iteration, all the functional paradigms, and more. So you can use those to create little 1-liners and there is no need to use the more complicated syntax of Java 8.</p> <p><s><em>I think the only thing missing from the built-in Java 8 <code>Collectors</code> class is summarization (but in <a href="https://stackoverflow.com/a/34661483/3679676">another answer to this question</a> is a simple solution)</em>.</p> <p>One thing missing from both is batching by count, which is seen in <a href="https://stackoverflow.com/a/34504231/3679676">another Stack Overflow answer</a> and has a simple answer as well. Another interesting case is this one also from Stack Overflow: <a href="https://stackoverflow.com/questions/32574783/idiomatic-way-to-spilt-sequence-into-three-lists-using-kotlin">Idiomatic way to spilt sequence into three lists using Kotlin</a>. And if you want to create something like <code>Stream.collect</code> for another purpose, see <a href="https://stackoverflow.com/questions/34639208">Custom Stream.collect in Kotlin</a></s></p> <p><strong>EDIT 11.08.2017:</strong> Chunked/windowed collection operations were added in kotlin 1.2 M2, see <a href="https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-2-m2-is-out/" rel="noreferrer">https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-2-m2-is-out/</a></p> <hr /> <p>It is always good to explore the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html" rel="noreferrer">API Reference for kotlin.collections</a> as a whole before creating new functions that might already exist there.</p> <p>Here are some conversions from Java 8 <code>Stream.collect</code> examples to the equivalent in Kotlin:</p> <p><strong>Accumulate names into a List</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: List&lt;String&gt; list = people.stream().map(Person::getName).collect(Collectors.toList()); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val list = people.map { it.name } // toList() not needed </code></pre> <p><strong>Convert elements to strings and concatenate them, separated by commas</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: String joined = things.stream() .map(Object::toString) .collect(Collectors.joining(&quot;, &quot;)); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val joined = things.joinToString(&quot;, &quot;) </code></pre> <p><strong>Compute sum of salaries of employee</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: int total = employees.stream() .collect(Collectors.summingInt(Employee::getSalary))); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val total = employees.sumBy { it.salary } </code></pre> <p><strong>Group employees by department</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: Map&lt;Department, List&lt;Employee&gt;&gt; byDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val byDept = employees.groupBy { it.department } </code></pre> <p><strong>Compute sum of salaries by department</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: Map&lt;Department, Integer&gt; totalByDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary))); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val totalByDept = employees.groupBy { it.dept }.mapValues { it.value.sumBy { it.salary }} </code></pre> <p><strong>Partition students into passing and failing</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: Map&lt;Boolean, List&lt;Student&gt;&gt; passingFailing = students.stream() .collect(Collectors.partitioningBy(s -&gt; s.getGrade() &gt;= PASS_THRESHOLD)); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val passingFailing = students.partition { it.grade &gt;= PASS_THRESHOLD } </code></pre> <p><strong>Names of male members</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: List&lt;String&gt; namesOfMaleMembers = roster .stream() .filter(p -&gt; p.getGender() == Person.Sex.MALE) .map(p -&gt; p.getName()) .collect(Collectors.toList()); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val namesOfMaleMembers = roster.filter { it.gender == Person.Sex.MALE }.map { it.name } </code></pre> <p><strong>Group names of members in roster by gender</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: Map&lt;Person.Sex, List&lt;String&gt;&gt; namesByGender = roster.stream().collect( Collectors.groupingBy( Person::getGender, Collectors.mapping( Person::getName, Collectors.toList()))); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val namesByGender = roster.groupBy { it.gender }.mapValues { it.value.map { it.name } } </code></pre> <p><strong>Filter a list to another list</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: List&lt;String&gt; filtered = items.stream() .filter( item -&gt; item.startsWith(&quot;o&quot;) ) .collect(Collectors.toList()); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val filtered = items.filter { it.startsWith('o') } </code></pre> <p><strong>Finding shortest string a list</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: String shortest = items.stream() .min(Comparator.comparing(item -&gt; item.length())) .get(); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val shortest = items.minBy { it.length } </code></pre> <p><strong>Counting items in a list after filter is applied</strong></p> <pre class="lang-java prettyprint-override"><code>// Java: long count = items.stream().filter( item -&gt; item.startsWith(&quot;t&quot;)).count(); </code></pre> <pre class="lang-kotlin prettyprint-override"><code>// Kotlin: val count = items.filter { it.startsWith('t') }.size // but better to not filter, but count with a predicate val count = items.count { it.startsWith('t') } </code></pre> <p>and on it goes... In all cases, no special fold, reduce, or other functionality was required to mimic <code>Stream.collect</code>. If you have further use cases, add them in comments and we can see!</p> <h2>About laziness</h2> <p>If you want to lazy process a chain, you can convert to a <code>Sequence</code> using <code>asSequence()</code> before the chain. At the end of the chain of functions, you usually end up with a <code>Sequence</code> as well. Then you can use <code>toList()</code>, <code>toSet()</code>, <code>toMap()</code> or some other function to materialize the <code>Sequence</code> at the end.</p> <pre class="lang-kotlin prettyprint-override"><code>// switch to and from lazy val someList = items.asSequence().filter { ... }.take(10).map { ... }.toList() // switch to lazy, but sorted() brings us out again at the end val someList = items.asSequence().filter { ... }.take(10).map { ... }.sorted() </code></pre> <h2>Why are there no Types?!?</h2> <p>You will notice the Kotlin examples do not specify the types. This is because Kotlin has full type inference and is completely type safe at compile time. More so than Java because it also has nullable types and can help prevent the dreaded NPE. So this in Kotlin:</p> <pre><code>val someList = people.filter { it.age &lt;= 30 }.map { it.name } </code></pre> <p>is the same as:</p> <pre><code>val someList: List&lt;String&gt; = people.filter { it.age &lt;= 30 }.map { it.name } </code></pre> <p>Because Kotlin knows what <code>people</code> is, and that <code>people.age</code> is <code>Int</code> therefore the filter expression only allows comparison to an <code>Int</code>, and that <code>people.name</code> is a <code>String</code> therefore the <code>map</code> step produces a <code>List&lt;String&gt;</code> (readonly <code>List</code> of <code>String</code>).</p> <p>Now, if <code>people</code> were possibly <code>null</code>, as-in a <code>List&lt;People&gt;?</code> then:</p> <pre><code>val someList = people?.filter { it.age &lt;= 30 }?.map { it.name } </code></pre> <p>Returns a <code>List&lt;String&gt;?</code> that would need to be null checked (<em>or use one of the other Kotlin operators for nullable values, see this <a href="https://stackoverflow.com/questions/34498562/in-kotlin-what-is-the-idiomatic-way-to-deal-with-nullable-values-referencing-o">Kotlin idiomatic way to deal with nullable values</a> and also <a href="https://stackoverflow.com/questions/26341225/idiomatic-way-of-handling-nullable-or-empty-list-in-kotlin">Idiomatic way of handling nullable or empty list in Kotlin</a></em>)</p> <h2>See also:</h2> <ul> <li>API Reference for <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/kotlin.-iterable/index.html" rel="noreferrer">extension functions for Iterable</a></li> <li>API reference for <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/kotlin.-array/index.html" rel="noreferrer">extension functions for Array</a></li> <li>API reference for <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/kotlin.-list/index.html" rel="noreferrer">extension functions for List</a></li> <li>API reference for <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/kotlin.-map/index.html" rel="noreferrer">extension functions to Map</a></li> </ul>
{ "question_id": 34642254, "question_date": "2016-01-06T20:34:35.013Z", "question_score": 209, "tags": "java|kotlin|collections|java-8|java-stream", "answer_id": 34642255, "answer_date": "2016-01-06T20:34:35.013Z", "answer_score": 299 }
Please answer the following Stack Overflow question: Title: Why is SCTP not much used/known <p>I recently checked out the book <a href="http://www.kohala.com/start/unpv12e.html" rel="noreferrer">"UNIX Network Programming, Vol. 1"</a> by Richards Stevens and I found that there is a third transport layer standard besides TCP and UDP: <em>SCTP</em>. </p> <p>Summary: SCTP is a transport-level protocol that is message-driven like UDP, but reliable like TCP. Here is a <a href="http://www.ibm.com/developerworks/linux/library/l-sctp/?ca=dgr-lnxw07SCTP" rel="noreferrer">short introduction from IBM DeveloperWorks</a>.</p> <p>Honestly, I have never heard of SCTP before. I can't remember reading about it in any networking books or hearing about it in classes I had taken. Reading <a href="https://stackoverflow.com/search?q=SCTP">other stackoverflow questions</a> that mentions SCTP suggests that I'm not alone with this lack of knowledge.</p> <p><strong>Why is SCTP so unknown? Why is it not much used?</strong> </p>
<p>Indeed, SCTP is used mostly in the telecom area. Traditionally, telecom switches use SS7 (<a href="http://en.wikipedia.org/wiki/Signaling_System_7" rel="noreferrer">Signaling System No. 7</a>) to interconnect different entities in the telecom network. For example - the telecom provider's subscriber data base(HLR), with a switch (MSC), the subscriber is connected too (MSC).</p> <p>The telecom area is moving to higher speeds and more reachable environment. One of these changes is to replace SS7 protocol by some more elegant, fast and flexible IP-based protocol.</p> <p>The telecom area is very conservative. The SS7 network has been used here for decades. It is very a reliable and closed network. This means a regular user has no access to it.</p> <p>The IP network, in contrast, is open and not reliable, and telecoms will not convert to it if it won't handle at least the load that SS7 handles. This is why SCTP was developed. It tries:</p> <ul> <li>to mimic all advantages of the SS7 network accumulated over the decades.</li> <li>to create a connection-oriented protocol better than TCP in speed, security, and redundancy</li> </ul> <p>The latest releases of Linux already have SCTP support.</p>
{ "question_id": 1171555, "question_date": "2009-07-23T13:02:51.200Z", "question_score": 209, "tags": "networking|tcp|popularity|sctp", "answer_id": 1172148, "answer_date": "2009-07-23T14:27:21.057Z", "answer_score": 103 }
Please answer the following Stack Overflow question: Title: Is errno thread-safe? <p>In <code>errno.h</code>, this variable is declared as <code>extern int errno;</code> so my question is, is it safe to check <code>errno</code> value after some calls or use perror() in multi-threaded code. Is this a thread safe variable? If not, then whats the alternative ? </p> <p>I am using linux with gcc on x86 architecture. </p>
<p>Yes, it is thread safe. On Linux, the global errno variable is thread-specific. POSIX requires that errno be threadsafe.</p> <p>See <a href="http://www.unix.org/whitepapers/reentrant.html" rel="noreferrer">http://www.unix.org/whitepapers/reentrant.html</a></p> <blockquote> <p>In POSIX.1, errno is defined as an external global variable. But this definition is unacceptable in a multithreaded environment, because its use can result in nondeterministic results. The problem is that two or more threads can encounter errors, all causing the same errno to be set. Under these circumstances, a thread might end up checking errno after it has already been updated by another thread.</p> <p>To circumvent the resulting nondeterminism, POSIX.1c redefines errno as a service that can access the per-thread error number as follows (ISO/IEC 9945:1-1996, §2.4):</p> <p>Some functions may provide the error number in a variable accessed through the symbol errno. The symbol errno is defined by including the header , as specified by the C Standard ... For each thread of a process, the value of errno shall not be affected by function calls or assignments to errno by other threads.</p> </blockquote> <p>Also see <a href="http://linux.die.net/man/3/errno" rel="noreferrer">http://linux.die.net/man/3/errno</a></p> <blockquote> <p>errno is thread-local; setting it in one thread does not affect its value in any other thread. </p> </blockquote>
{ "question_id": 1694164, "question_date": "2009-11-07T19:39:54.473Z", "question_score": 209, "tags": "c|linux|multithreading|gcc", "answer_id": 1694170, "answer_date": "2009-11-07T19:41:40.773Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: Why does this Java program terminate despite that apparently it shouldn't (and didn't)? <p>A sensitive operation in my lab today went completely wrong. An actuator on an electron microscope went over its boundary, and after a chain of events I lost $12 million of equipment. I've narrowed down over 40K lines in the faulty module to this:</p> <pre><code>import java.util.*; class A { static Point currentPos = new Point(1,2); static class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } public static void main(String[] args) { new Thread() { void f(Point p) { synchronized(this) {} if (p.x+1 != p.y) { System.out.println(p.x+" "+p.y); System.exit(1); } } @Override public void run() { while (currentPos == null); while (true) f(currentPos); } }.start(); while (true) currentPos = new Point(currentPos.x+1, currentPos.y+1); } } </code></pre> <p>Some samples of the output I'm getting:</p> <pre><code>$ java A 145281 145282 $ java A 141373 141374 $ java A 49251 49252 $ java A 47007 47008 $ java A 47427 47428 $ java A 154800 154801 $ java A 34822 34823 $ java A 127271 127272 $ java A 63650 63651 </code></pre> <p>Since there isn't any floating point arithmetic here, and we all know signed integers behave well on overflow in Java, I'd think there's nothing wrong with this code. However, despite the output indicating that the program didn't reach the exit condition, it reached the exit condition (it was both reached <strong>and</strong> not reached?). Why?</p> <hr> <p>I've noticed this doesn't happen in some environments. I'm on <a href="http://en.wikipedia.org/wiki/OpenJDK" rel="noreferrer">OpenJDK</a> 6 on 64-bit Linux.</p>
<blockquote> <p>Obviously the write to currentPos doesn't happen-before the read of it, but I don't see how that can be the issue.</p> </blockquote> <p><code>currentPos = new Point(currentPos.x+1, currentPos.y+1);</code> does a few things, including writing default values to <code>x</code> and <code>y</code> (0) and then writing their initial values in the constructor. Since your object is not safely published those 4 write operations can be freely reordered by the compiler / JVM.</p> <p>So from the perspective of the reading thread, it is a legal execution to read <code>x</code> with its new value but <code>y</code> with its default value of 0 for example. By the time you reach the <code>println</code> statement (which by the way is synchronized and therefore does influence the read operations), the variables have their initial values and the program prints the expected values.</p> <p>Marking <code>currentPos</code> as <code>volatile</code> will ensure safe publication since your object is effectively immutable - if in your real use case the object is mutated after construction, <code>volatile</code> guarantees won't be enough and you could see an inconsistent object again.</p> <p>Alternatively, you can make the <code>Point</code> immutable which will also ensure safe publication, even without using <code>volatile</code>. To achieve immutability, you simply need to mark <code>x</code> and <code>y</code> final.</p> <p>As a side note and as already mentioned, <code>synchronized(this) {}</code> can be treated as a no-op by the JVM (I understand you included it to reproduce the behaviour).</p>
{ "question_id": 16159203, "question_date": "2013-04-23T01:03:58.693Z", "question_score": 209, "tags": "java|concurrency|java-memory-model|memory-visibility", "answer_id": 16323196, "answer_date": "2013-05-01T17:29:10.083Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: When should I use ?? (nullish coalescing) vs || (logical OR)? <p>Related to <a href="https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript">Is there a &quot;null coalescing&quot; operator in JavaScript?</a> - JavaScript now has a <code>??</code> operator which I see is in use more frequently. Previously most JavaScript code used <code>||</code>.</p> <pre class="lang-js prettyprint-override"><code>let userAge = null // These values will be the same. let age1 = userAge || 21 let age2 = userAge ?? 21 </code></pre> <p><strong>In what circumstances will <code>??</code> and <code>||</code> behave differently?</strong></p>
<p>The OR operator <code>||</code> uses the right value if left is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy" rel="noreferrer">falsy</a>, while the nullish coalescing operator <code>??</code> uses the right value if left is <code>null</code> or <code>undefined</code>.</p> <p>These operators are often used to provide a default value if the first one is missing.</p> <p><strong>But the OR operator <code>||</code> can be problematic if your left value might contain <code>&quot;&quot;</code> or <code>0</code> or <code>false</code> (because these are <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy" rel="noreferrer">falsy values</a>)</strong>:</p> <pre class="lang-js prettyprint-override"><code>console.log(12 || &quot;not found&quot;) // 12 console.log(0 || &quot;not found&quot;) // &quot;not found&quot; console.log(&quot;jane&quot; || &quot;not found&quot;) // &quot;jane&quot; console.log(&quot;&quot; || &quot;not found&quot;) // &quot;not found&quot; console.log(true || &quot;not found&quot;) // true console.log(false || &quot;not found&quot;) // &quot;not found&quot; console.log(undefined || &quot;not found&quot;) // &quot;not found&quot; console.log(null || &quot;not found&quot;) // &quot;not found&quot; </code></pre> <p>In many cases, you might only want the right value if left is <code>null</code> or <code>undefined</code>. That's what the nullish coalescing operator <code>??</code> is for:</p> <pre class="lang-js prettyprint-override"><code>console.log(12 ?? &quot;not found&quot;) // 12 console.log(0 ?? &quot;not found&quot;) // 0 console.log(&quot;jane&quot; ?? &quot;not found&quot;) // &quot;jane&quot; console.log(&quot;&quot; ?? &quot;not found&quot;) // &quot;&quot; console.log(true ?? &quot;not found&quot;) // true console.log(false ?? &quot;not found&quot;) // false console.log(undefined ?? &quot;not found&quot;) // &quot;not found&quot; console.log(null ?? &quot;not found&quot;) // &quot;not found&quot; </code></pre> <p>While the <code>??</code> operator isn't available in <a href="https://nodejs.org/en/about/releases/" rel="noreferrer">current LTS versions of Node</a> (v10 and v12), you can use it with some versions of TypeScript or Node:</p> <p>The <code>??</code> operator was added to <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing" rel="noreferrer">TypeScript 3.7</a> back in November 2019.</p> <p>And more recently, the <code>??</code> operator was <a href="https://tc39.es/ecma262/2020/" rel="noreferrer">included in ES2020</a>, which is supported by Node 14 (released in April 2020).</p> <p><strong>When the nullish coalescing operator <code>??</code> is supported, I typically use it instead of the OR operator <code>||</code> (unless there's a good reason not to).</strong></p>
{ "question_id": 61480993, "question_date": "2020-04-28T13:11:01.077Z", "question_score": 209, "tags": "javascript|logical-or", "answer_id": 61481631, "answer_date": "2020-04-28T13:40:44.223Z", "answer_score": 299 }
Please answer the following Stack Overflow question: Title: Final arguments in interface methods - what's the point? <p>In Java, it is perfectly legal to define <code>final</code> arguments in interface methods and do not obey that in the implementing class, e.g.:</p> <pre><code>public interface Foo { public void foo(int bar, final int baz); } public class FooImpl implements Foo { @Override public void foo(final int bar, int baz) { ... } } </code></pre> <p>In the above example, <code>bar</code> and <code>baz</code> has the opposite <code>final</code> definitions in the class VS the interface.</p> <p>In the same fashion, no <code>final</code> restrictions are enforced when one class method extends another, either <code>abstract</code> or not.</p> <p>While <code>final</code> has some practical value inside the class method body, is there any point specifying <code>final</code> for interface method parameters?</p>
<p>It doesn't seem like there's any point to it. According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4" rel="noreferrer">Java Language Specification 4.12.4</a>:</p> <blockquote> <p>Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.</p> </blockquote> <p>However, a <code>final</code> modifier on a method parameter is not mentioned in the <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#38649" rel="noreferrer">rules for matching signatures</a> of overridden methods, and it has no effect on the caller, only within the body of an implementation. Also, as noted by Robin in a comment, the <code>final</code> modifier on a method parameter has no effect on the generated byte code. (This is not true for other uses of <code>final</code>.)</p>
{ "question_id": 5380177, "question_date": "2011-03-21T15:53:47.017Z", "question_score": 209, "tags": "java|class|interface|methods|final", "answer_id": 5380309, "answer_date": "2011-03-21T16:05:28.587Z", "answer_score": 121 }
Please answer the following Stack Overflow question: Title: Is assert evil? <p>The <code>Go</code> language creators <a href="https://golang.org/doc/faq#assertions" rel="noreferrer">write</a>:</p> <blockquote> <p><strong>Go doesn't provide assertions.</strong> They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. Proper error handling means that servers continue operation after non-fatal errors instead of crashing. Proper error reporting means that errors are direct and to the point, saving the programmer from interpreting a large crash trace. Precise errors are particularly important when the programmer seeing the errors is not familiar with the code.</p> </blockquote> <p>What is your opinion about this?</p>
<p>No, there's nothing wrong with <code>assert</code> as long as you use it as intended.</p> <p>That is, it's supposed to be for catching cases that "can't happen", during debugging, as opposed to normal error handling.</p> <ul> <li>Assert: A failure in the program's logic itself.</li> <li>Error Handling: An erroneous input or system state not due to a bug in the program.</li> </ul>
{ "question_id": 1854302, "question_date": "2009-12-06T04:04:19.403Z", "question_score": 209, "tags": "c++|c|error-handling|go|assert", "answer_id": 1854338, "answer_date": "2009-12-06T04:20:46.577Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: What is "Service Include" in a csproj file for? <p>In a C# solution, I added a existing project.<br> After that, Visual Studio has added the following entry in other .csproj files:</p> <pre><code>&lt;ItemGroup&gt; &lt;Service Include="{B4F97281-0DBD-4835-9ED8-7DFB966E87FF}" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>What's this for?<br> Can I delete it?</p>
<p>I had a similar case, where this was added:</p> <pre><code>&lt;ItemGroup&gt; &lt;Service Include=&quot;{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}&quot; /&gt; &lt;/ItemGroup&gt; </code></pre> <p>This inclusion turns out to be generated on purpose by VS2013 if you create an NUnit test project, but forget to tag it as test project, as described in this <a href="https://connect.microsoft.com/VisualStudio/feedback/details/800245/vs2013rc-adds-to-vs2012-c-project-section-itemgroup" rel="noreferrer">answer</a> from Microsoft:</p> <blockquote> <p>This behavior is intentional.</p> <p>To support third-party test frameworks, like NUnit and XUnit, Visual Studio 2012 loaded Test Explorer on solution open, regardless of whether it contained test projects. This added seconds of delay to startup and solution open scenarios for all users, majority of whom don't use tests.</p> <p>In Visual Studio 2013, we changed it so that Test Explorer package is loaded only when the solution contains one or more test projects. Test projects are identified in two different ways. Projects created from one of the built-in unit test project templates are identified using project type GUIDs. Other types of projects, such as Class Library project with XUnit or NUnit tests, are identified by Test Explorer during first test discovery and “tagged” with the <code>&lt;Service/&gt;</code> item.</p> </blockquote>
{ "question_id": 18614342, "question_date": "2013-09-04T12:51:06.097Z", "question_score": 209, "tags": "c#|visual-studio|visual-studio-2013|csproj", "answer_id": 22917902, "answer_date": "2014-04-07T16:24:17.077Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: How will I know when to create an interface? <p>I'm at a point in my development learning where I feel like I must learn more about interfaces.</p> <p>I frequently read about them but it just seems like I cannot grasp them.</p> <p>I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"</p> <p>What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.</p>
<p>it solves this concrete problem:</p> <p>you have a, b, c, d of 4 different types. all over your code you have something like:</p> <pre><code>a.Process(); b.Process(); c.Process(); d.Process(); </code></pre> <p>why not have them implement IProcessable, and then do</p> <pre><code>List&lt;IProcessable&gt; list; foreach(IProcessable p in list) p.Process(); </code></pre> <p>this will scale much better when you add, say, 50 types of classes that all do the same thing.</p> <hr> <p>Another concrete problem:</p> <p>Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.</p>
{ "question_id": 444245, "question_date": "2009-01-14T19:03:23.833Z", "question_score": 209, "tags": "design-patterns|oop|interface|class-design", "answer_id": 444259, "answer_date": "2009-01-14T19:06:32.050Z", "answer_score": 159 }
Please answer the following Stack Overflow question: Title: How and why does 'a'['toUpperCase']() in JavaScript work? <p>JavaScript keeps surprising me and this is another instance. I just came across some code which I did not understood at first. So I debugged it and came to this finding:</p> <pre><code>alert('a'['toUpperCase']()); //alerts 'A' </code></pre> <p>Now this must be obvious if <code>toUpperCase()</code> is defined as a member of string type, but it did not make sense to me initially.</p> <p>Anyway,</p> <ul> <li>does this work because <code>toUpperCase</code> is a member of 'a'? Or there is something else going on behind the scenes?</li> <li><p>the <a href="http://danwebb.net/2006/11/3/from-the-archives-cleaner-callbacks-with-partial-application" rel="noreferrer">code</a> I was reading has a function as follows:</p> <pre><code>function callMethod(method) { return function (obj) { return obj[method](); //**how can I be sure method will always be a member of obj** } } var caps2 = map(['a', 'b', 'c'], callMethod('toUpperCase')); // ['A','B','C'] // ignoring details of map() function which essentially calls methods on every // element of the array and forms another array of result and returns it </code></pre> <p>It is kinda generic function to call <strong>ANY</strong> methods on <strong>ANY</strong> object. But does that mean the specified method will already be an implicit member of the specified object?</p></li> </ul> <p>I am sure that I am missing some serious understanding of basic concept of JavaScript functions. Please help me to understand this.</p>
<p>To break it down.</p> <ul> <li><code>.toUpperCase()</code> is a method of <code>String.prototype</code></li> <li><code>'a'</code> is a primitive value, but gets converted into its <em>Object representation</em></li> <li>We have two possible notations to access object properties/methods, dot and bracket notation</li> </ul> <p>So</p> <pre><code>'a'['toUpperCase']; </code></pre> <p>is the access via <em>bracket notation</em> on the property <code>toUpperCase</code>, from <code>String.prototype</code>. Since this property references a <em>method</em>, we can invoke it by attaching <code>()</code></p> <pre><code>'a'['toUpperCase'](); </code></pre>
{ "question_id": 15659809, "question_date": "2013-03-27T13:17:08.287Z", "question_score": 209, "tags": "javascript|function", "answer_id": 15659923, "answer_date": "2013-03-27T13:22:49.807Z", "answer_score": 294 }
Please answer the following Stack Overflow question: Title: How to parse JSON data with jQuery / JavaScript? <p>I have a AJAX call that returns some JSON like this:</p> <pre><code>$(document).ready(function () { $.ajax({ type: 'GET', url: 'http://example/functions.php', data: { get_param: 'value' }, success: function (data) { var names = data $('#cand').html(data); } }); }); </code></pre> <p>Inside the <code>#cand</code> div I'll get:</p> <pre><code>[ { "id" : "1", "name" : "test1" }, { "id" : "2", "name" : "test2" }, { "id" : "3", "name" : "test3" }, { "id" : "4", "name" : "test4" }, { "id" : "5", "name" : "test5" } ] </code></pre> <p>How can I loop through this data and place each name in a div?</p>
<p>Assuming your server side script doesn't set the proper <code>Content-Type: application/json</code> response header you will need to indicate to jQuery that this is JSON by using the <code>dataType: 'json'</code> parameter.</p> <p>Then you could use the <a href="http://api.jquery.com/jQuery.each/"><code>$.each()</code></a> function to loop through the data:</p> <pre><code>$.ajax({ type: 'GET', url: 'http://example/functions.php', data: { get_param: 'value' }, dataType: 'json', success: function (data) { $.each(data, function(index, element) { $('body').append($('&lt;div&gt;', { text: element.name })); }); } }); </code></pre> <p>or use the <code>$.getJSON</code> method:</p> <pre><code>$.getJSON('/functions.php', { get_param: 'value' }, function(data) { $.each(data, function(index, element) { $('body').append($('&lt;div&gt;', { text: element.name })); }); }); </code></pre>
{ "question_id": 8951810, "question_date": "2012-01-21T09:02:16.010Z", "question_score": 208, "tags": "jquery|ajax|json|parsing", "answer_id": 8951858, "answer_date": "2012-01-21T09:09:58.330Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Cannot read property 'addEventListener' of null <p>I have to use vanilla JavaScript for a project. I have a few functions, one of which is a button that opens a menu. It works on pages where the target id exists, but causes an error on pages where the id doesn't exist. On those pages where the function cannot find the id, I receive a "Cannot read property 'addEventListener' of null " error and none of my other functions work.</p> <p>Below is the code for the button that opens the menu. </p> <pre><code>function swapper() { toggleClass(document.getElementById('overlay'), 'open'); } var el = document.getElementById('overlayBtn'); el.addEventListener('click', swapper, false); var text = document.getElementById('overlayBtn'); text.onclick = function(){ this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu"; return false; }; </code></pre> <p>How do I deal with this? I probably need to all wrap this code in another function or use an if/else statement so that it only searches for the id on specific pages, but not sure exactly. </p>
<p>I think the easiest approach would be to just check that <code>el</code> is not null before adding an event listener:</p> <pre><code>var el = document.getElementById('overlayBtn'); if(el){ el.addEventListener('click', swapper, false); } </code></pre>
{ "question_id": 26107125, "question_date": "2014-09-29T19:11:31.303Z", "question_score": 208, "tags": "javascript|function|getelementbyid|addeventlistener", "answer_id": 26107174, "answer_date": "2014-09-29T19:14:37.347Z", "answer_score": 308 }
Please answer the following Stack Overflow question: Title: How to check which locks are held on a table <p>How can we check which database locks are applied on which rows against a query batch? </p> <p>Any tool that highlights table row level locking in real time? </p> <p>DB: SQL Server 2005</p>
<p>To add to the other responses, <code>sp_lock</code> can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with <code>sp_who2</code> to quickly zero in on locking problems.</p> <p>There are multiple different versions of "friendlier" <code>sp_lock</code> procedures available online, depending on the version of SQL Server in question.</p> <p>In your case, for SQL Server 2005, <code>sp_lock</code> is still available, but deprecated, so it's now recommended to use the <a href="http://msdn.microsoft.com/en-us/library/ms190345.aspx" rel="noreferrer"><code>sys.dm_tran_locks</code></a> view for this kind of thing. You can find an example of how to "roll your own" sp_lock function <a href="http://www.techrepublic.com/blog/the-enterprise-cloud/write-your-own-sp-lock-system-stored-procedure-in-sql-server-2005/" rel="noreferrer">here</a>.</p>
{ "question_id": 694581, "question_date": "2009-03-29T12:46:43.150Z", "question_score": 208, "tags": "sql|sql-server|database|performance|sql-server-2005", "answer_id": 694659, "answer_date": "2009-03-29T14:02:18.897Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: Find the division remainder of a number <p>How could I go about finding the division remainder of a number in Python?</p> <p>For example:<br> If the number is 26 and divided number is 7, then the division remainder is 5.<br> (since 7+7+7=21 and 26-21=5.)</p>
<p>you are looking for the modulo operator:</p> <pre><code>a % b </code></pre> <p>for example:</p> <pre><code>&gt;&gt;&gt; 26 % 7 5 </code></pre> <p>Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.</p>
{ "question_id": 5584586, "question_date": "2011-04-07T16:44:16.820Z", "question_score": 208, "tags": "python|modulo|integer-division", "answer_id": 5584604, "answer_date": "2011-04-07T16:45:29.847Z", "answer_score": 257 }
Please answer the following Stack Overflow question: Title: Laravel Redirect Back with() Message <p>I am trying to redirect to the previous page with a message when there is a fatal error.</p> <pre><code>App::fatal(function($exception) { return Redirect::back()-&gt;with('msg', 'The Message'); } </code></pre> <p>In the view trying to access the msg with </p> <pre><code>Sessions::get('msg') </code></pre> <p>But nothing is getting rendered, am I doing something wrong here?</p>
<p>Try</p> <pre><code>return Redirect::back()-&gt;withErrors(['msg' =&gt; 'The Message']); </code></pre> <p>and inside your view call this</p> <pre><code>@if($errors-&gt;any()) &lt;h4&gt;{{$errors-&gt;first()}}&lt;/h4&gt; @endif </code></pre>
{ "question_id": 19838978, "question_date": "2013-11-07T14:52:25.380Z", "question_score": 208, "tags": "laravel|laravel-5|laravel-4", "answer_id": 19839060, "answer_date": "2013-11-07T14:55:44.063Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: Formatting code in Notepad++ <p>Is there a keyboard shortcut to format code in Notepad++ ?<br> I'm mainly working with HTML, CSS and Python code.</p> <p>For example:</p> <pre class="lang-html prettyprint-override"><code>&lt;title&gt;{% block title %} {% endblock %}&lt;/title&gt; &lt;link rel="stylesheet" href="/media/style.css" type="text/css" media="screen" /&gt; &lt;/head&gt; </code></pre> <p>To:</p> <pre class="lang-html prettyprint-override"><code>&lt;head&gt; &lt;title&gt; {% block title %} {% endblock %} &lt;/title&gt; &lt;link rel="stylesheet" href="/media/style.css" type="text/css" media="screen" /&gt; &lt;/head&gt; </code></pre> <p><br> I remember Visual Studio doing it with <kbd>Ctrl</kbd>+<kbd>K</kbd>+<kbd>D</kbd> and NetBeans having the feature too but can't find it within Notepad++, if it can even do it. </p>
<p>TextFX -> HTML Tidy -> Tidy: Reindent XML</p> <p>Remember to have the HTML code selected before you do this.</p>
{ "question_id": 3635460, "question_date": "2010-09-03T11:58:03.330Z", "question_score": 208, "tags": "html|notepad++|code-formatting", "answer_id": 3635611, "answer_date": "2010-09-03T12:17:45.007Z", "answer_score": 131 }
Please answer the following Stack Overflow question: Title: How to get parameters from the URL with JSP <p>In JSP how do I get parameters from the URL?</p> <p>For example I have a URL <code>www.somesite.com/Transaction_List.jsp?accountID=5</code> <br />I want to get the 5. <br /><br /> Is there a request.getAttribute( "accountID" ) like there is for sessions or something similar?</p>
<p>In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL <a href="http://hostname.com?p1=v1&amp;p2=v2" rel="noreferrer">http://hostname.com?p1=v1&amp;p2=v2</a> contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.</p> <p>This example demonstrates how to include the value of a request parameter in the generated output:</p> <pre><code>Hello &lt;b&gt;&lt;%= request.getParameter("name") %&gt;&lt;/b&gt;! </code></pre> <p>If the page was accessed with the URL:</p> <pre><code>http://hostname.com/mywebapp/mypage.jsp?name=John+Smith </code></pre> <p>the resulting output would be:</p> <pre><code>Hello &lt;b&gt;John Smith&lt;/b&gt;! </code></pre> <p>If name is not specified on the query string, the output would be:</p> <pre><code>Hello &lt;b&gt;null&lt;/b&gt;! </code></pre> <p>This example uses the value of a query parameter in a scriptlet:</p> <pre><code>&lt;% if (request.getParameter("name") == null) { out.println("Please enter your name."); } else { out.println("Hello &lt;b&gt;"+request. getParameter("name")+"&lt;/b&gt;!"); } %&gt; </code></pre>
{ "question_id": 1890438, "question_date": "2009-12-11T19:46:09.147Z", "question_score": 208, "tags": "java|jsp|url|get-method", "answer_id": 1890451, "answer_date": "2009-12-11T19:48:43.040Z", "answer_score": 192 }
Please answer the following Stack Overflow question: Title: Display the current time and date in an Android application <p>How do I display the current date and time in an Android application?</p>
<p>Okay, not that hard as there are several methods to do this. I assume you want to put the current date &amp; time into a <code>TextView</code>.</p> <pre><code>String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date()); // textView is the TextView view that should display it textView.setText(currentDateTimeString); </code></pre> <p>There is more to read in the documentation that can easily be found <a href="http://developer.android.com/reference/java/text/DateFormat.html#getDateTimeInstance%28%29" rel="noreferrer">here</a> . There you'll find more information on how to change the format used for conversion.</p>
{ "question_id": 2271131, "question_date": "2010-02-16T07:02:47.090Z", "question_score": 208, "tags": "android|datetime|android-date", "answer_id": 2271305, "answer_date": "2010-02-16T07:44:44.293Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: Encrypt & Decrypt using PyCrypto AES 256 <p>I'm trying to build two functions using PyCrypto that accept two parameters: the message and the key, and then encrypt/decrypt the message.</p> <p>I found several links on the web to help me out, but each one of them has flaws:</p> <p><a href="http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/" rel="noreferrer">This one at codekoala</a> uses os.urandom, which is discouraged by PyCrypto.</p> <p>Moreover, the key I give to the function is not guaranteed to have the exact length expected. What can I do to make that happen ?</p> <p>Also, there are several modes, which one is recommended? I don't know what to use :/</p> <p>Finally, what exactly is the IV? Can I provide a different IV for encrypting and decrypting, or will this return in a different result?</p> <p><strong>Edit</strong>: Removed the code part since it was not secure.</p>
<p>Here is my implementation and works for me with some fixes and enhances the alignment of the key and secret phrase with 32 bytes and iv to 16 bytes:</p> <pre><code>import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES class AESCipher(object): def __init__(self, key): self.bs = AES.block_size self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw.encode())) def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') def _pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) @staticmethod def _unpad(s): return s[:-ord(s[len(s)-1:])] </code></pre>
{ "question_id": 12524994, "question_date": "2012-09-21T05:54:41.483Z", "question_score": 208, "tags": "python|encryption|padding|pycrypto|initialization-vector", "answer_id": 21928790, "answer_date": "2014-02-21T08:10:37.227Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: Remove unwanted parts from strings in a column <p>I am looking for an efficient way to remove unwanted parts from strings in a DataFrame column.</p> <p>Data looks like:</p> <pre><code> time result 1 09:00 +52A 2 10:00 +62B 3 11:00 +44a 4 12:00 +30b 5 13:00 -110a </code></pre> <p>I need to trim these data to:</p> <pre><code> time result 1 09:00 52 2 10:00 62 3 11:00 44 4 12:00 30 5 13:00 110 </code></pre> <p>I tried <code>.str.lstrip('+-')</code> and .<code>str.rstrip('aAbBcC')</code>, but got an error: </p> <pre><code>TypeError: wrapper() takes exactly 1 argument (2 given) </code></pre> <p>Any pointers would be greatly appreciated!</p>
<pre><code>data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC')) </code></pre>
{ "question_id": 13682044, "question_date": "2012-12-03T11:11:56.090Z", "question_score": 208, "tags": "python|string|pandas|dataframe", "answer_id": 13682381, "answer_date": "2012-12-03T11:33:51.673Z", "answer_score": 246 }
Please answer the following Stack Overflow question: Title: How to word wrap text in HTML? <p>How can text like <code>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</code> which exceeds the width of a <code>div</code> (say <code>200px</code>) be wrapped?</p> <p>I am open to any kind of solution such as CSS, jQuery, etc.</p>
<p>Try this:</p> <pre><code>div { width: 200px; word-wrap: break-word; } </code></pre>
{ "question_id": 1147877, "question_date": "2009-07-18T15:56:31.810Z", "question_score": 208, "tags": "html|css|word-wrap", "answer_id": 1147889, "answer_date": "2009-07-18T16:02:12.810Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Convert char to int in C# <p>I have a char in c#:</p> <pre><code>char foo = '2'; </code></pre> <p>Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:</p> <pre><code>int bar = Convert.ToInt32(new string(foo, 1)); </code></pre> <p>int.parse only works on strings as well. </p> <p>Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.</p>
<p>Interesting answers but the docs say differently:</p> <blockquote> <p>Use the <code>GetNumericValue</code> methods to convert a <code>Char</code> object that represents a number to a numeric value type. Use <code>Parse</code> and <code>TryParse</code> to convert a character in a string into a <code>Char</code> object. Use <code>ToString</code> to convert a <code>Char</code> object to a <code>String</code> object.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/system.char.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.char.aspx</a></p>
{ "question_id": 239103, "question_date": "2008-10-27T04:49:21.707Z", "question_score": 208, "tags": "c#|char|int", "answer_id": 795991, "answer_date": "2009-04-28T02:20:19.333Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: PHP - Get key name of array value <p>I have an array as the following:</p> <pre><code>function example() { /* some stuff here that pushes items with dynamically created key strings into an array */ return array( // now lets pretend it returns the created array 'firstStringName' =&gt; $whatEver, 'secondStringName' =&gt; $somethingElse ); } $arr = example(); // now I know that $arr contains $arr['firstStringName']; </code></pre> <p>I need to find out the index of <code>$arr['firstStringName']</code> so that I am able to loop through <code>array_keys($arr)</code> and return the key string <code>'firstStringName'</code> by its index. How can I do that?</p>
<p>If you have a value and want to find the key, use <a href="http://php.net/manual/en/function.array-search.php" rel="noreferrer"><code>array_search()</code></a> like this:</p> <pre><code>$arr = array ('first' =&gt; 'a', 'second' =&gt; 'b', ); $key = array_search ('a', $arr); </code></pre> <p><code>$key</code> will now contain the key for value <code>'a'</code> (that is, <code>'first'</code>).</p>
{ "question_id": 8729410, "question_date": "2012-01-04T15:32:53.727Z", "question_score": 208, "tags": "php|arrays|array-key", "answer_id": 8729491, "answer_date": "2012-01-04T15:37:20.010Z", "answer_score": 423 }
Please answer the following Stack Overflow question: Title: jQuery equivalent of JavaScript's addEventListener method <p>I'm trying to find the jQuery equivalent of this JavaScript method call:</p> <pre><code>document.addEventListener('click', select_element, true); </code></pre> <p>I've gotten as far as:</p> <pre><code>$(document).click(select_element); </code></pre> <p>but that doesn't achieve the same result, as the last parameter of the JavaScript method - a boolean that indicates whether the event handler should be executed in the capturing or bubbling phase (per my understanding from <a href="http://www.quirksmode.org/js/events_advanced.html" rel="noreferrer">http://www.quirksmode.org/js/events_advanced.html</a>) - is left out.</p> <p>How do I specify that parameter, or otherwise achieve the same functionality, using jQuery?</p>
<p>Not all browsers support event capturing (for example, Internet Explorer versions less than 9 don't) but all do support event bubbling, which is why it is the phase used to bind handlers to events in all cross-browser abstractions, jQuery's included.</p> <p>The nearest to what you are looking for in jQuery is using <a href="http://api.jquery.com/bind/" rel="noreferrer"><code>bind()</code></a> (superseded by <a href="http://api.jquery.com/on/" rel="noreferrer"><code>on()</code></a> in jQuery 1.7+) or the event-specific jQuery methods (in this case, <a href="http://api.jquery.com/click/" rel="noreferrer"><code>click()</code></a>, which calls <code>bind()</code> internally anyway). All use the bubbling phase of a raised event.</p>
{ "question_id": 2398099, "question_date": "2010-03-07T21:44:35.910Z", "question_score": 208, "tags": "javascript|jquery|events|event-handling|dom-events", "answer_id": 2398244, "answer_date": "2010-03-07T22:25:55.737Z", "answer_score": 155 }
Please answer the following Stack Overflow question: Title: Use Fieldset Legend with bootstrap <p>I'm using Bootstrap for my <code>JSP</code> page.</p> <p>I want to use <em><code>&lt;fieldset&gt;</code></em> and <em><code>&lt;legend&gt;</code></em> for my form. This is my code.</p> <pre><code>&lt;fieldset class="scheduler-border"&gt; &lt;legend class="scheduler-border"&gt;Start Time&lt;/legend&gt; &lt;div class="control-group"&gt; &lt;label class="control-label input-label" for="startTime"&gt;Start :&lt;/label&gt; &lt;div class="controls bootstrap-timepicker"&gt; &lt;input type="text" class="datetime" id="startTime" name="startTime" placeholder="Start Time" /&gt; &lt;i class="icon-time"&gt;&lt;/i&gt; &lt;/div&gt; &lt;/div&gt; &lt;/fieldset&gt; </code></pre> <p>CSS is</p> <pre class="lang-css prettyprint-override"><code>fieldset.scheduler-border { border: 1px groove #ddd !important; padding: 0 1.4em 1.4em 1.4em !important; margin: 0 0 1.5em 0 !important; -webkit-box-shadow: 0px 0px 0px 0px #000; box-shadow: 0px 0px 0px 0px #000; } legend.scheduler-border { font-size: 1.2em !important; font-weight: bold !important; text-align: left !important; } </code></pre> <p>I am getting output like this <img src="https://i.stack.imgur.com/cTTgq.jpg" alt="enter image description here"></p> <p>I want output in the following way</p> <p><img src="https://i.stack.imgur.com/Kh9xq.jpg" alt="enter image description here"></p> <p>I tried adding</p> <pre class="lang-css prettyprint-override"><code>border:none; width:100px; </code></pre> <p>to <code>legend.scheduler-border</code> in CSS. And I'm getting the expected output. But the problem is I would like to add another <em><code>&lt;fieldset&gt;</code></em> for another fields. That time the width of text in legend is a problem as it is lengthier than than <code>100px</code>.</p> <p>So what shall I do to get output like I have mentioned? (Without striking the legend text)</p>
<p>That's because Bootstrap by default sets the width of the <code>legend</code> element to 100%. You can fix this by changing your <code>legend.scheduler-border</code> to also use:</p> <pre class="lang-css prettyprint-override"><code>legend.scheduler-border { width:inherit; /* Or auto */ padding:0 10px; /* To give a bit of padding on the left and right */ border-bottom:none; } </code></pre> <p><a href="http://jsfiddle.net/JamesD/PgA84/1" rel="noreferrer"><strong>JSFiddle example</strong></a>.</p> <p>You'll also need to ensure your custom stylesheet is being added <em>after</em> Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.</p> <p>You may also want to add <code>margin-bottom:0;</code> to it as well to reduce the gap between the legend and the divider.</p>
{ "question_id": 16852484, "question_date": "2013-05-31T07:56:55.107Z", "question_score": 208, "tags": "html|css|forms|twitter-bootstrap", "answer_id": 16852571, "answer_date": "2013-05-31T08:02:28.893Z", "answer_score": 240 }
Please answer the following Stack Overflow question: Title: How can I return two values from a function in Python? <p>I would like to return two values from a function in two separate variables. For example:</p> <pre><code>def select_choice(): loop = 1 row = 0 while loop == 1: print('''Choose from the following options?: 1. Row 1 2. Row 2 3. Row 3''') row = int(input("Which row would you like to move the card from?: ")) if row == 1: i = 2 card = list_a[-1] elif row == 2: i = 1 card = list_b[-1] elif row == 3: i = 0 card = list_c[-1] return i return card </code></pre> <p>And I want to be able to use these values separately. When I tried to use <code>return i, card</code>, it returns a <code>tuple</code> and this is not what I want. </p>
<p>You cannot return two values, but you can return a <code>tuple</code> or a <code>list</code> and unpack it after the call:</p> <pre><code>def select_choice(): ... return i, card # or [i, card] my_i, my_card = select_choice() </code></pre> <p>On line <code>return i, card</code> <code>i, card</code> means creating a tuple. You can also use parenthesis like <code>return (i, card)</code>, but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line <code>my_i, my_card = select_choice()</code>.</p> <p>If you want to return more than two values, consider using a <a href="https://docs.python.org/3.6/library/collections.html#collections.namedtuple" rel="nofollow noreferrer">named tuple</a>. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in <code>Schema.loads</code> method Marshmallow framework returns a <a href="https://marshmallow.readthedocs.io/en/2.x-line/api_reference.html#marshmallow.UnmarshalResult" rel="nofollow noreferrer"><code>UnmarshalResult</code></a> which is a <a href="https://github.com/marshmallow-code/marshmallow/blob/fe5469998a6f1f297f8c85acfba8c48ff7bc3d7d/marshmallow/schema.py#L29" rel="nofollow noreferrer"><code>namedtuple</code></a>. So you can do:</p> <pre><code>data, errors = MySchema.loads(request.json()) if errors: ... </code></pre> <p>or</p> <pre><code>result = MySchema.loads(request.json()) if result.errors: ... else: # use `result.data` </code></pre> <p>In other cases you may return a <code>dict</code> from your function:</p> <pre><code>def select_choice(): ... return {'i': i, 'card': card, 'other_field': other_field, ...} </code></pre> <p>But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:</p> <pre><code>class ChoiceData(): def __init__(self, i, card, other_field, ...): # you can put here some validation logic self.i = i self.card = card self.other_field = other_field ... def select_choice(): ... return ChoiceData(i, card, other_field, ...) choice_data = select_choice() print(choice_data.i, choice_data.card) </code></pre>
{ "question_id": 9752958, "question_date": "2012-03-17T19:18:53.350Z", "question_score": 208, "tags": "python|function|return|return-value", "answer_id": 9752970, "answer_date": "2012-03-17T19:20:34.683Z", "answer_score": 419 }
Please answer the following Stack Overflow question: Title: GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error <p>Q - I installed git to get the latest version of Angular. When I tried to run</p> <pre><code>git clone https://github.com/angular/angular-phonecat.git </code></pre> <p>I got failed to connect to github 443 error</p> <p>I even tried </p> <pre><code>git clone git://github.com/angular/angular-phonecat.git </code></pre> <p>That gave me failed to connect no error message.</p> <p>I am behind my company firewall. I can not see my proxy details when I go to <code>control panel-&gt;Internet Options -&gt; connections -&gt; LAN setting</code>. IT guys are not sharing proxy information with me. I do not know what to do ??</p> <p>I finally managed to do it. I will update the procedure that I had taken in order to Just wanted to compile all the steps that I did to get it to work</p>
<p>Well I did following steps</p> <ol> <li><p>Google the error</p> </li> <li><p>Got to SO Links(<a href="https://stackoverflow.com/questions/496277/git-error-fatal-unable-to-connect-a-socket-invalid-argument">here</a>, <a href="https://stackoverflow.com/questions/3512202/github-https-access">here</a>) which suggested the same thing, that I have to update the Git Config for proxy setting</p> </li> <li><p>Damn, can not see proxy information from control panel. IT guys must have hidden it. I can not even change the setting to not to use proxy.</p> </li> <li><p>Found <a href="https://superuser.com/questions/346372/how-do-i-know-what-proxy-server-im-using">this wonderful tutorial</a> of finding which proxy your are connected to</p> </li> <li><p>Updated the <code>http.proxy</code> key in git config by following command</p> <pre><code>git config --global http.proxy http[s]://userName:password@proxyaddress:port </code></pre> </li> <li><p>Error - &quot;could not resolve proxy <code>some@proxyaddress:port</code>&quot;. It turned out my password had a <code>@</code> symbol in it.</p> </li> <li><p>Encode <code>@</code> in your password to <code>%40</code>, because git splits the proxy setting by @</p> </li> <li><p>If your userName is a email address, which has <code>@</code>, also encode it to <code>%40</code>. (see <a href="https://stackoverflow.com/a/40478893/4910876">this answer</a>)</p> <pre><code> git config --global http.proxy http[s]://userName(encoded):password(encoded)@proxyaddress:port </code></pre> </li> </ol> <p>Baam! It worked!</p> <p>Note - I just wanted to answer this question for souls like me, who would come looking for answer on SO :D</p>
{ "question_id": 18356502, "question_date": "2013-08-21T11:43:31.563Z", "question_score": 208, "tags": "git|github", "answer_id": 18356572, "answer_date": "2013-08-21T11:47:07.717Z", "answer_score": 401 }
Please answer the following Stack Overflow question: Title: How to Apply global font to whole HTML document <p>I have a HTML page which includes some text and formatting. I want to make it have the same font-family and the same text-size ignoring all inner formatting of text.</p> <p>I want to set a global font format for the HTML page.</p> <p>How can I achieve this?</p>
<p>You should be able to utilize the asterisk and <code>!important</code> elements within CSS.</p> <pre><code>html * { font-size: 1em !important; color: #000 !important; font-family: Arial !important; } </code></pre> <p>The asterisk matches everything (you could probably get away without the <code>html</code> too).</p> <p>The <code>!important</code> ensures that <strong>nothing can override what you've set in this style</strong> (unless it is also important). (this is to help with your requirement that it should "ignore inner formatting of text" - which I took to mean that other styles could not overwrite these)</p> <p>The rest of the style within the braces is just like any other styling and you can do whatever you'd like to in there. I chose to change the font size, color and family as an example.</p>
{ "question_id": 7025756, "question_date": "2011-08-11T12:21:35.857Z", "question_score": 208, "tags": "html|css|font-family", "answer_id": 7025783, "answer_date": "2011-08-11T12:24:32.630Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: MySQL high CPU usage <p>Recently my server CPU has been going very high.</p> <p>CPU load averages 13.91 (1 min) 11.72 (5 mins) 8.01 (15 mins) and my site has only had a slight increase in traffic.</p> <p>After running a top command, I saw MySQL was using 160% CPU!</p> <p>Recently I've been optimizing tables and I've switched to persistent connections. Could this be causing MySQL to use high amounts of CPU?</p>
<p>First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.</p> <p>Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.</p> <p>Thirdly I'd say you want to turn on the <a href="http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html" rel="noreferrer">MySQL Slow Query</a> Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.</p> <p>Some other things you can check would be to run the following query while the CPU load is high:</p> <pre><code>SHOW PROCESSLIST; </code></pre> <p>This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).</p> <p>You'll also want to keep an eye on things like your buffer sizes, <a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_table_cache" rel="noreferrer">table cache</a>, <a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_query_cache_limit" rel="noreferrer">query cache</a> and <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-parameters.html#sysvar_innodb_buffer_pool_size" rel="noreferrer">innodb_buffer_pool_size</a> (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.</p> <p>You'll also probably want to give the following a read over as they contain some good information.</p> <ul> <li><a href="http://dev.mysql.com/doc/refman/5.0/en/memory-use.html" rel="noreferrer">How MySQL Uses Memory</a></li> <li><a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html" rel="noreferrer">MySQL System Variables</a></li> </ul> <p>It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called <a href="http://github.com/steves/PHP-Profiler" rel="noreferrer">PHP Profiler</a> but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.</p>
{ "question_id": 1282232, "question_date": "2009-08-15T16:17:04.167Z", "question_score": 208, "tags": "mysql|cpu-usage", "answer_id": 1282265, "answer_date": "2009-08-15T16:35:46.110Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How to include bootstrap css and js in reactjs app? <p>I am new to ReactJS, I want to include bootstrap in my React app</p> <p>I have installed bootstrap by <code>npm install bootstrap --save</code></p> <p>Now, want to load bootstrap CSS and JS in my React app.</p> <p>I am using webpack.</p> <p><em><strong>webpack.config.js</strong></em></p> <pre><code>var config = { entry: './src/index', output: { path: './', filename: 'index.js' }, devServer: { inline: true, port: 8080, historyApiFallback: true, contentBase:'./src' }, module: { loaders: [ { test: /\.js?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } }; module. exports = config; </code></pre> <p>My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?&quot; How to set up for bootstrap to include in my React app?</p>
<p>If you are new to React and using <strong><code>create-react-app</code></strong> cli setup, run the <strong>npm</strong> command below to include the latest version of bootstrap.</p> <pre><code>npm install --save bootstrap </code></pre> <p>or </p> <pre><code>npm install --save bootstrap@latest </code></pre> <p>Then add the following import statement to <strong><code>index.js</code></strong> file. (<a href="https://getbootstrap.com/docs/4.4/getting-started/webpack/#importing-compiled-css" rel="noreferrer">https://getbootstrap.com/docs/4.4/getting-started/webpack/#importing-compiled-css</a>)</p> <pre><code>import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; </code></pre> <p>or </p> <pre><code>import 'bootstrap/dist/css/bootstrap.min.css'; </code></pre> <p>don't forget to use <strong><code>className</code></strong> as attribute on target elements (react uses <strong><code>className</code></strong> as attribute instead of <strong><code>class</code></strong>).</p>
{ "question_id": 40037657, "question_date": "2016-10-14T07:42:53.097Z", "question_score": 208, "tags": "twitter-bootstrap|reactjs|webpack", "answer_id": 44985246, "answer_date": "2017-07-08T10:36:37.037Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Add a duration to a moment (moment.js) <p>Moment version: 2.0.0</p> <p><a href="http://momentjs.com/docs/#/manipulating/add/">After reading the docs</a>, I thought this would be straight-forward (Chrome console):</p> <pre><code>var timestring1 = "2013-05-09T00:00:00Z"; var timestring2 = "2013-05-09T02:00:00Z"; var startdate = moment(timestring1); var expected_enddate = moment(timestring2); var returned_endate = startdate.add(moment.duration(2, 'hours')); returned_endate == expected_enddate // false returned_endate // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…} </code></pre> <p>This is a trivial example, but I can't even get it to work. I feel like I'm missing something big here, but I really don't get it. Even this this doesn't seem to work:</p> <pre><code>startdate.add(2, 'hours') // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…} </code></pre> <p>Any help would be much appreciated.</p> <p><strong>Edit:</strong> My end goal is to make an binary status chart like the one I'm working on here: <a href="http://bl.ocks.org/phobson/5872894">http://bl.ocks.org/phobson/5872894</a></p> <p>As you can see, I'm currently using dummy x-values while I work through this issue.</p>
<p>I think you missed a key point in the documentation for <code>.add()</code></p> <blockquote> <p>Mutates the original moment by adding time.</p> </blockquote> <p>You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)</p> <p>If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.</p> <p>You can work around this behavior by cloning the moment, <a href="http://momentjs.com/docs/#/parsing/moment-clone/">as described here</a>.</p> <p>Also, you cannot just use <code>==</code> to test. You could format each moment to the same output and compare those, or you could just use the <code>.isSame()</code> method.</p> <p>Your code is now:</p> <pre><code>var timestring1 = "2013-05-09T00:00:00Z"; var timestring2 = "2013-05-09T02:00:00Z"; var startdate = moment(timestring1); var expected_enddate = moment(timestring2); var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning? returned_endate.isSame(expected_enddate) // true </code></pre>
{ "question_id": 17333425, "question_date": "2013-06-27T02:08:45.763Z", "question_score": 208, "tags": "javascript|momentjs", "answer_id": 17334415, "answer_date": "2013-06-27T04:13:15.673Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native) <p>I am stuck with this error no matter what directory I am in, and what I type after "npm" in cmd.exe. Here is the npm-debug.log: </p> <pre><code>0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js' ] 2 info using [email protected] 3 info using [email protected] 4 verbose stack Error: EISDIR: illegal operation on a directory, read 4 verbose stack at Error (native) 5 verbose cwd C:\Users\me 6 error Windows_NT 6.1.7601 7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" 8 error node v4.2.6 9 error npm v2.14.12 10 error code EISDIR 11 error errno -4068 12 error syscall read 13 error eisdir EISDIR: illegal operation on a directory, read 13 error eisdir This is most likely not a problem with npm itself 13 error eisdir and is related to npm not being able to find a package.json in 13 error eisdir a package you are trying to install. 14 verbose exit [ -4068, true ] </code></pre> <p>I have tried and uninstalling/reinstalling nodejs multiple times, I even deleted npm and npm-cache folders in C:\Users\me\AppData\Roaming. I'm not sure what went wrong to cause this. One second it was working fine, and now I can't get rid of this error. The explanation in the log does not make sense, as it gives this error in any directory. I should note that running a command prompt as administrator does not give this error. I'm pulling my hair out this Friday evening trying to get this fixed, any help would be greatly appreciated!</p>
<p>I ran into the same problem while I was changing some npm settings. I did a mistake with one <code>npm config set</code> command and this added a line referring to a non-existing directory to <code>C:\Users\{User}\.npmrc</code>. After I deleted that line manually from <code>.npmrc</code>, the problem was gone.</p>
{ "question_id": 34959038, "question_date": "2016-01-23T02:43:37.330Z", "question_score": 208, "tags": "node.js|windows|cmd|npm|file-permissions", "answer_id": 35429397, "answer_date": "2016-02-16T10:04:37.503Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: Efficient method to generate UUID String in Java (UUID.randomUUID().toString() without the dashes) <p>I would like an efficient utility to generate unique sequences of bytes. UUID is a good candidate but <code>UUID.randomUUID().toString()</code> generates stuff like <code>44e128a5-ac7a-4c9a-be4c-224b6bf81b20</code> which is good, but I would prefer dash-less string.</p> <p>I'm looking for an efficient way to generate a random strings, only from alphanumeric characters (no dashes or any other special symbols).</p>
<p>Ended up writing something of my own based on UUID.java implementation. Note that I'm <strong>not generating a UUID</strong>, instead just a random 32 bytes hex string in the most efficient way I could think of.</p> <h2>Implementation</h2> <pre><code>import java.security.SecureRandom; import java.util.UUID; public class RandomUtil { // Maxim: Copied from UUID implementation :) private static volatile SecureRandom numberGenerator = null; private static final long MSB = 0x8000000000000000L; public static String unique() { SecureRandom ng = numberGenerator; if (ng == null) { numberGenerator = ng = new SecureRandom(); } return Long.toHexString(MSB | ng.nextLong()) + Long.toHexString(MSB | ng.nextLong()); } } </code></pre> <h1>Usage</h1> <pre><code>RandomUtil.unique() </code></pre> <h1>Tests</h1> <p>Some of the inputs I've tested to make sure it's working:</p> <pre><code>public static void main(String[] args) { System.out.println(UUID.randomUUID().toString()); System.out.println(RandomUtil.unique()); System.out.println(); System.out.println(Long.toHexString(0x8000000000000000L |21)); System.out.println(Long.toBinaryString(0x8000000000000000L |21)); System.out.println(Long.toHexString(Long.MAX_VALUE + 1)); } </code></pre>
{ "question_id": 3804591, "question_date": "2010-09-27T14:05:52.163Z", "question_score": 208, "tags": "java|random|uuid", "answer_id": 3811761, "answer_date": "2010-09-28T10:22:21.600Z", "answer_score": 14 }
Please answer the following Stack Overflow question: Title: XPath find if node exists <p>Using a XPath query how do you find if a node (tag) exists at all?</p> <p>For example if I needed to make sure a website page has the correct basic structure like <code>/html/body</code> and <code>/html/head/title</code>.</p>
<pre><code>&lt;xsl:if test="xpath-expression"&gt;...&lt;/xsl:if&gt; </code></pre> <p>so for example</p> <pre><code>&lt;xsl:if test="/html/body"&gt;body node exists&lt;/xsl:if&gt; &lt;xsl:if test="not(/html/body)"&gt;body node missing&lt;/xsl:if&gt; </code></pre>
{ "question_id": 767851, "question_date": "2009-04-20T11:14:39.237Z", "question_score": 208, "tags": "xslt|xpath|expression", "answer_id": 767873, "answer_date": "2009-04-20T11:26:43.343Z", "answer_score": 331 }
Please answer the following Stack Overflow question: Title: Best practices for copying files with Maven <p>I have config files and various documents that I want to copy from the dev environment to the dev-server directory using Maven2. Strangely, Maven does not seem strong at this task. </p> <p>Some of the options: </p> <ul> <li>Simple use a <em>copy</em> task in Maven</li> </ul> <blockquote> <pre><code>&lt;copy file="src/main/resources/config.properties" tofile="${project.server.config}/config.properties"/&gt; </code></pre> </blockquote> <ul> <li><p>Use the Ant plugin to execute <em>copy</em> from Ant.</p> <ul> <li><p>Construct an artifact of type <em>zip</em>, alongside the "main" artifact of the POM which is usually of type <em>jar</em>, then <em>unpack</em> that artifact from the repository into the target directory.</p></li> <li><p><em>maven-resources</em> plugin, as mentioned below.</p></li> <li><p>Maven Assembly plugin -- but this seems to require a lot of manual definitions, when I want to do things simply and "conventionally."</p></li> <li><p><a href="http://maven-plugins.sourceforge.net/cgi-bin/wiki?PluginTutorial" rel="noreferrer">This page</a> even shows how to build a plugin to do copying!</p></li> <li><p><em>maven-upload</em> plugin, as mentioned below.</p></li> <li><p><em>maven-dependency-plugin</em> with <em>copy</em>, as mentioned below.</p></li> </ul></li> </ul> <p><br> All these seem needlessly ad hoc: Maven is supposed to excel at doing these standard tasks without fuss and bother. </p> <p>Any advice?</p>
<p>Don't shy away from the Antrun plugin. Just because some people tend to think that Ant and Maven are in opposition, they are not. Use the copy task if you need to perform some unavoidable one-off customization:</p> <pre><code>&lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; [...] &lt;plugin&gt; &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;deploy&lt;/phase&gt; &lt;configuration&gt; &lt;target&gt; &lt;!-- Place any Ant task here. You can add anything you can add between &lt;target&gt; and &lt;/target&gt; in a build.xml. --&gt; &lt;/target&gt; &lt;/configuration&gt; &lt;goals&gt; &lt;goal&gt;run&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; </code></pre> <p>In answering this question, I'm focusing on the details of what you asked. How do I copy a file? The question and the variable name lead me to a larger questions like: &quot;Is there a better way to deal with server provisioning?&quot; Use Maven as a build system to generate deployable artifact, then perform these customizations either in separate modules or somewhere else entirely. If you shared a bit more of your build environment, there might be a better way - there are plugins to provision a number of servers. Could you attach an assembly that is unpacked in the server's root? What server are you using?</p> <p>Again, I'm sure there's a better way.</p>
{ "question_id": 586202, "question_date": "2009-02-25T14:38:00.700Z", "question_score": 208, "tags": "maven|maven-2|build-process|release-management", "answer_id": 694175, "answer_date": "2009-03-29T05:51:02.977Z", "answer_score": 130 }
Please answer the following Stack Overflow question: Title: How can I loop through ALL DOM elements on a page? <p>I'm trying to loop over ALL elements on a page, so I want to check every element that exists on this page for a special class.</p> <p>So, how do I say that I want to check EVERY element?</p>
<p>You can pass a <code>*</code> to <a href="https://developer.mozilla.org/en/DOM/document.getElementsByTagName" rel="noreferrer"><code>getElementsByTagName()</code></a> so that it will return all elements in a page:</p> <pre><code>var all = document.getElementsByTagName(&quot;*&quot;); for (var i=0, max=all.length; i &lt; max; i++) { // Do something with the element here } </code></pre> <p>Note that you could use <a href="https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll" rel="noreferrer"><code>querySelectorAll()</code></a>, if it's available (IE9+, CSS in IE8), to just find elements with a particular class.</p> <pre><code>if (document.querySelectorAll) var clsElements = document.querySelectorAll(&quot;.mySpeshalClass&quot;); else // loop through all elements instead </code></pre> <p>This would certainly speed up matters for modern browsers.</p> <hr /> <p>Browsers now support <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach" rel="noreferrer">foreach on NodeList</a>. This means you can directly loop the elements instead of writing your own for loop.</p> <pre><code>document.querySelectorAll('*').forEach(function(node) { // Do whatever you want with the node object. }); </code></pre> <blockquote> <p><strong>Performance note</strong> - Do your best to scope what you're looking for by using a specific selector. A universal selector can return lots of nodes depending on the complexity of the page. Also, consider using <code>document.body.querySelectorAll</code> instead of <code>document.querySelectorAll</code> when you don’t care about <code>&lt;head&gt;</code> children.</p> </blockquote>
{ "question_id": 4256339, "question_date": "2010-11-23T13:13:13.343Z", "question_score": 208, "tags": "javascript|dom", "answer_id": 4256372, "answer_date": "2010-11-23T13:15:44.703Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: 1030 Got error 28 from storage engine <p>I am working on a project where i need to create a database with 300 tables for each user who wants to see the demo application. it was working fine but today when i was testing with a new user to see a demo it showed me this error message </p> <pre><code>1030 Got error 28 from storage engine </code></pre> <p>After spending some time googling i found it is an error that is related to space of database or temporary files. I tried to fix it but i failed. now i am not even able to start mysql. How can i fix this and i would also like to increase the size to maximum so that i won't face the same issue again and again. </p>
<p>Mysql error "<em>28 from storage engine</em>" - means "<em>not enough disk space</em>".</p> <p>To show disc space use command below.</p> <pre><code>myServer# df -h </code></pre> <p>Results must be like this.</p> <pre><code>Filesystem Size Used Avail Capacity Mounted on /dev/vdisk 13G 13G 46M 100% / devfs 1.0k 1.0k 0B 100% /dev </code></pre>
{ "question_id": 10631387, "question_date": "2012-05-17T07:10:44.770Z", "question_score": 208, "tags": "mysql", "answer_id": 13728466, "answer_date": "2012-12-05T17:01:10.233Z", "answer_score": 417 }
Please answer the following Stack Overflow question: Title: How do I set hostname in docker-compose? <p>In my <code>docker-compose.yml</code> file, I have the following. However the container does not pick up the hostname value. Any ideas?</p> <pre class="lang-yaml prettyprint-override"><code>dns: image: phensley/docker-dns hostname: affy domainname: affy.com volumes: - /var/run/docker.sock:/docker.sock </code></pre> <p>When I check the hostname in the container it does not pick up <code>affy</code>.</p>
<p>As of <a href="https://docs.docker.com/compose/compose-file/compose-file-v3/#domainname-hostname-ipc-mac_address-privileged-read_only-shm_size-stdin_open-tty-user-working_dir" rel="noreferrer">docker-compose version 3.0 and later</a>, you can just use the <code>hostname</code> key:</p> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.0&quot; services: yourservicename: hostname: your-name </code></pre>
{ "question_id": 29924843, "question_date": "2015-04-28T16:25:12.410Z", "question_score": 208, "tags": "docker|docker-compose", "answer_id": 63291253, "answer_date": "2020-08-06T20:25:11.157Z", "answer_score": 119 }
Please answer the following Stack Overflow question: Title: How to load external scripts dynamically in Angular? <p>I have this module which componentize the external library together with additional logic without adding the <code>&lt;script&gt;</code> tag directly into the index.html:</p> <pre><code>import 'http://external.com/path/file.js' //import '../js/file.js' @Component({ selector: 'my-app', template: ` &lt;script src="http://iknow.com/this/does/not/work/either/file.js"&gt;&lt;/script&gt; &lt;div&gt;Template&lt;/div&gt;` }) export class MyAppComponent {...} </code></pre> <p>I notice the <code>import</code> by ES6 spec is static and resolved during TypeScript transpiling rather than at runtime.</p> <p>Anyway to make it configurable so the file.js will be loading either from CDN or local folder? How to tell Angular 2 to load a script dynamically?</p>
<p>If you're using system.js, you can use <code>System.import()</code> at runtime: </p> <pre><code>export class MyAppComponent { constructor(){ System.import('path/to/your/module').then(refToLoadedModule =&gt; { refToLoadedModule.someFunction(); } ); } </code></pre> <p>If you're using webpack, you can take full advantage of its robust code splitting support with <a href="https://webpack.js.org/guides/code-splitting/" rel="noreferrer"><code>require.ensure</code></a> : </p> <pre><code>export class MyAppComponent { constructor() { require.ensure(['path/to/your/module'], require =&gt; { let yourModule = require('path/to/your/module'); yourModule.someFunction(); }); } } </code></pre>
{ "question_id": 34489916, "question_date": "2015-12-28T08:14:05.040Z", "question_score": 208, "tags": "javascript|angular|typescript|ecmascript-6", "answer_id": 34489991, "answer_date": "2015-12-28T08:20:39.840Z", "answer_score": 73 }
Please answer the following Stack Overflow question: Title: gradlew command not found? <p>I am working on a Java project with gradlew. I use Ubuntu Linux as my OS. When I run &quot;gradle&quot; it runs, and gives me info. But when I run &quot;gradlew&quot;, it outputs as &quot;No command 'gradlew' found, did you mean: Command 'gradle' from package 'gradle' (universe) gradlew: command not found&quot;</p> <p>I did my research, I have jdk, and I did sudo apt-get install gradle. I am totally clueless</p> <p>Error is:</p> <pre><code>$ gradlew clean jpackage bash: gradlew: command not found... </code></pre>
<p>Gradle wrapper needs to be built. Try running <code>gradle wrapper --gradle-version 2.13</code> Remember to change 2.13 to your gradle version number. After running this command, you should see new scripts added to your project folder. You should be able to run the wrapper with <code>./gradlew build</code> to build your code. Please refer to this guid for more information <a href="https://spring.io/guides/gs/gradle/" rel="noreferrer">https://spring.io/guides/gs/gradle/</a>.</p>
{ "question_id": 41700798, "question_date": "2017-01-17T15:19:38.150Z", "question_score": 208, "tags": "java|linux|gradle|installation", "answer_id": 41700939, "answer_date": "2017-01-17T15:25:25.070Z", "answer_score": 134 }
Please answer the following Stack Overflow question: Title: CSS to line break before/after a particular `inline-block` item <p>Let's say I have this HTML:</p> <pre><code>&lt;h3&gt;Features&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Smells Good&lt;/li&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Tastes Great&lt;/li&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Delicious&lt;/li&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Wholesome&lt;/li&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Eats Children&lt;/li&gt; &lt;li&gt;&lt;img src="alphaball.png"&gt;Yo' Mama&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>and this CSS:</p> <pre><code>li { text-align:center; display:inline-block; padding:0.1em 1em } img { width:64px; display:block; margin:0 auto } </code></pre> <p>The result can be seen here: <a href="http://jsfiddle.net/YMN7U/1/" rel="noreferrer">http://jsfiddle.net/YMN7U/1/</a></p> <p>Now imagine that I want to break this into three columns, the equivalent of injecting a <code>&lt;br&gt;</code> after the third <code>&lt;li&gt;</code>. <em>(Actually doing that would be semantically and syntactically invalid.)</em></p> <p>I know how to select the third <code>&lt;li&gt;</code> in CSS, but how do I force a line break after it? This does not work:</p> <pre><code>li:nth-child(4):after { content:"xxx"; display:block } </code></pre> <p><em>I also know that this particular case is possible by using <code>float</code> instead of <code>inline-block</code>, but I am not interested in solutions using <code>float</code>. I also know that with fixed-width blocks this is possible by setting the width on the parent <code>ul</code> to about 3x that width; I am not interested in this solution. I also know that I could use <code>display:table-cell</code> if I wanted real columns; I am not interested in this solution. I am interested in the possibility of forcing a break inside inline content.</em></p> <p><strong>Edit</strong>: To be clear, I am interested in 'theory', not the solution to a particular problem. <em>Can CSS inject a line break in the middle of <code>display:inline(-block)?</code> elements, or is it impossible?</em> If you are certain that it is impossible, that is an acceptable answer.</p>
<p>I've been able to make it work on inline LI elements. Unfortunately, it does not work if the LI elements are inline-block:</p> <p><strong><em>Live demo:</em></strong> <a href="http://jsfiddle.net/dWkdp/" rel="noreferrer">http://jsfiddle.net/dWkdp/</a></p> <p>Or the cliff notes version:</p> <pre class="lang-css prettyprint-override"><code>li { display: inline; } li:nth-child(3):after { content: "\A"; white-space: pre; } </code></pre>
{ "question_id": 4609279, "question_date": "2011-01-05T21:16:31.667Z", "question_score": 208, "tags": "html|css", "answer_id": 4609491, "answer_date": "2011-01-05T21:40:05.273Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: Difference in Months between two dates in JavaScript <p>How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?</p> <p>Any help would be great :)</p>
<p>The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)</p> <p>You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.</p> <p>For instance, off-the-cuff:</p> <pre><code>function monthDiff(d1, d2) { var months; months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth(); months += d2.getMonth(); return months &lt;= 0 ? 0 : months; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function monthDiff(d1, d2) { var months; months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth(); months += d2.getMonth(); return months &lt;= 0 ? 0 : months; } function test(d1, d2) { var diff = monthDiff(d1, d2); console.log( d1.toISOString().substring(0, 10), "to", d2.toISOString().substring(0, 10), ":", diff ); } test( new Date(2008, 10, 4), // November 4th, 2008 new Date(2010, 2, 12) // March 12th, 2010 ); // Result: 16 test( new Date(2010, 0, 1), // January 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010 ); // Result: 2 test( new Date(2010, 1, 1), // February 1st, 2010 new Date(2010, 2, 12) // March 12th, 2010 ); // Result: 1</code></pre> </div> </div> </p> <p>(Note that month values in JavaScript start with 0 = January.)</p> <p>Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.</p> <p>There are also some <a href="http://www.datejs.com/" rel="noreferrer">date and time libraries</a> available for JavaScript that probably make this sort of thing easier.</p> <hr> <p><strong>Note</strong>: There used to be a <code>+ 1</code> in the above, here:</p> <pre><code>months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth() + 1; // −−−−−−−−−−−−−−−−−−−−^^^^ months += d2.getMonth(); </code></pre> <p>That's because originally I said:</p> <blockquote> <p>...this finds out how many <em>full months</em> lie between two dates, not counting partial months (e.g., excluding the month each date is in).</p> </blockquote> <p>I've removed it for two reasons:</p> <ol> <li><p>Not counting partial months turns out not to be what many (most?) people coming to the answer want, so I thought I should separate them out.</p></li> <li><p>It didn't always work even by that definition. :-D (Sorry.)</p></li> </ol>
{ "question_id": 2536379, "question_date": "2010-03-29T07:34:15.927Z", "question_score": 208, "tags": "javascript|date|datediff", "answer_id": 2536445, "answer_date": "2010-03-29T07:49:37.787Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: How to find out if you're using HTTPS without $_SERVER['HTTPS'] <p>I've seen many tutorials online that says you need to check <code>$_SERVER['HTTPS']</code> if the server is connection is secured with HTTPS. My problem is that on some of the servers I use, <code>$_SERVER['HTTPS']</code> is an undefined variable that results in an error. Is there another variable I can check that should always be defined?</p> <p>Just to be clear, I am currently using this code to resolve if it is an HTTPS connection:</p> <pre><code>if(isset($_SERVER['HTTPS'])) { if ($_SERVER['HTTPS'] == "on") { $secure_connection = true; } } </code></pre>
<p>This should always work even when <code>$_SERVER['HTTPS']</code> is undefined:</p> <pre><code>function isSecure() { return (!empty($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443; } </code></pre> <p>The code is compatible with IIS.</p> <p>From the <a href="http://www.php.net/manual/en/reserved.variables.server.php" rel="nofollow noreferrer">PHP.net documentation and user comments</a> :</p> <blockquote> <ol> <li><p>Set to a non-empty value if the script was queried through the HTTPS protocol.</p> </li> <li><p>Note that when using ISAPI with IIS, the value will be &quot;off&quot; if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).</p> </li> </ol> </blockquote> <p>Also, Apache 1.x servers (and broken installations) might not have <code>$_SERVER['HTTPS']</code> defined even if connecting securely. Although not guaranteed, connections on port 443 are, by <a href="https://www.rfc-editor.org/rfc/rfc2818#section-2.3" rel="nofollow noreferrer">convention</a>, likely using <a href="http://en.wikipedia.org/wiki/Secure_Sockets_Layer" rel="nofollow noreferrer">secure sockets</a>, hence the additional port check.</p> <p>Additional note: if there is a load balancer between the client and your server, this code doesn't test the connection between the client and the load balancer, but the connection between the load balancer and your server. To test the former connection, you would have to test using the <code>HTTP_X_FORWARDED_PROTO</code> header, but it's much more complex to do; see <a href="https://stackoverflow.com/questions/1175096/how-to-find-out-if-youre-using-https-without-serverhttps/2886224#comment102520055_2886224">latest comments</a> below this answer.</p>
{ "question_id": 1175096, "question_date": "2009-07-23T23:42:49.050Z", "question_score": 208, "tags": "php|https", "answer_id": 2886224, "answer_date": "2010-05-21T23:26:38.880Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: How to change the playing speed of videos in HTML5? <p>How to change the video play speed in HTML5? I've checked <a href="https://www.w3schools.com/html/html5_video.asp" rel="noreferrer">video tag's attributes</a> in w3school but couldn't approach that.</p>
<p>According to <a href="http://www.chipwreck.de/blog/2010/03/01/html-5-video-dom-attributes-and-events/" rel="noreferrer">this site</a>, this is supported in the <code>playbackRate</code> and <code>defaultPlaybackRate</code> attributes, accessible via the DOM. Example:</p> <pre><code>/* play video twice as fast */ document.querySelector('video').defaultPlaybackRate = 2.0; document.querySelector('video').play(); /* now play three times as fast just for the heck of it */ document.querySelector('video').playbackRate = 3.0; </code></pre> <p>The above <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playbackRate" rel="noreferrer">works</a> on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.</p>
{ "question_id": 3027707, "question_date": "2010-06-12T06:11:58.343Z", "question_score": 208, "tags": "javascript|html|performance|video|html5-video", "answer_id": 3027957, "answer_date": "2010-06-12T08:05:58.277Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Where are environment variables stored in the Windows Registry? <p>I need to access an environment variable remotely. To do this, I think the best way is to read it from registry.</p> <p>Where are environment variables stored in the Windows Registry?</p>
<p>Here's where they're stored on <a href="https://en.wikipedia.org/wiki/Windows_XP" rel="noreferrer">Windows XP</a> through <a href="https://en.wikipedia.org/wiki/Windows_Server_2012" rel="noreferrer">Windows Server 2012</a> R2:</p> <h3>User Variables</h3> <pre><code>HKEY_CURRENT_USER\Environment </code></pre> <h3>System Variables</h3> <pre><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment </code></pre>
{ "question_id": 573817, "question_date": "2009-02-21T22:06:25.540Z", "question_score": 208, "tags": "windows|environment-variables|registry", "answer_id": 573818, "answer_date": "2009-02-21T22:08:36.983Z", "answer_score": 302 }
Please answer the following Stack Overflow question: Title: How can I resolve the error "The minCompileSdk (31) specified in a dependency's AAR metadata" in native Java or Kotlin? <p>The error message:</p> <blockquote> <p>The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.core:core-ktx:1.7.0-alpha02.</p> <p>AAR metadata file: <br /> C:\Users\mohammad.zeeshan1.gradle\caches\transforms-2\files-2.1\a20beb0771f59a8ddbbb8d416ea06a9d\jetified-core-ktx-1.7.0-alpha02\META-INF\com\android\build\gradle\aar-metadata.properties.</p> </blockquote>
<p>I have found the solution. Enter this line of code above package in the app Gradle file.</p> <p>For Kotlin developers:</p> <pre><code>configurations.all { resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' } } </code></pre> <p><a href="https://i.stack.imgur.com/lAE2k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lAE2k.png" alt="Screenshot of code with a red freehand circle" /></a></p> <p>For Java developers</p> <pre><code>configurations.all { resolutionStrategy { force 'androidx.core:core:1.6.0' } } </code></pre>
{ "question_id": 69034879, "question_date": "2021-09-02T17:36:44.970Z", "question_score": 208, "tags": "java|android|kotlin|gradle", "answer_id": 69043734, "answer_date": "2021-09-03T10:51:04.670Z", "answer_score": 138 }
Please answer the following Stack Overflow question: Title: Openssl is not recognized as an internal or external command <p>I wish to generate an application signature for my app which will later be integrated with Facebook. In one of Facebook's tutorials, I found this command:</p> <pre><code>keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 </code></pre> <p>In the tutorial, it says that by running this cmd, my process of generating the signature will start.</p> <p>However, this command gives an error:</p> <pre><code>openssl is not recognized as an internal or external command </code></pre> <p>How can I get rid of this?</p>
<p>Well at the place of OpenSSL ... you have to put actually the path to your OpenSSL folder that you have downloaded. Your actual command should look like this:</p> <pre><code>keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | &quot;C:\Users\abc\openssl\bin\openssl.exe&quot; sha1 -binary | &quot;C:\Users\abc\openssl\bin\openssl.exe&quot; base64 </code></pre> <p>Remember, the path that you will enter will be the path where you have installed the OpenSSL.</p> <p><strong>Edit:</strong></p> <p>you can download OpenSSL for windows 32 and 64 bit from the respective links below:</p> <p><a href="http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_X64.zip" rel="noreferrer">OpenSSL for 64 Bits</a></p> <p><a href="https://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip" rel="noreferrer">OpenSSL for 32 Bits</a></p>
{ "question_id": 11896304, "question_date": "2012-08-10T06:04:04.053Z", "question_score": 208, "tags": "java|android|facebook-android-sdk|keytool", "answer_id": 11896406, "answer_date": "2012-08-10T06:15:44.760Z", "answer_score": 429 }
Please answer the following Stack Overflow question: Title: Splitting a Java String by the pipe symbol using split("|") <p>The Java official documentation states:</p> <p>The string <code>"boo:and:foo"</code>, for example, yields the following results with these expressions Regex Result : </p> <pre><code>{ "boo", "and", "foo" }" </code></pre> <p>And that's the way I need it to work. However, if I run this:</p> <pre><code>public static void main(String[] args){ String test = "A|B|C||D"; String[] result = test.split("|"); for(String s : result){ System.out.println("&gt;"+s+"&lt;"); } } </code></pre> <p>it prints:</p> <pre><code>&gt;&lt; &gt;A&lt; &gt;|&lt; &gt;B&lt; &gt;|&lt; &gt;C&lt; &gt;|&lt; &gt;|&lt; &gt;D&lt; </code></pre> <p>Which is far from what I would expect:</p> <pre><code>&gt;A&lt; &gt;B&lt; &gt;C&lt; &gt;&lt; &gt;D&lt; </code></pre> <p>Why is this happening?</p>
<p>You need </p> <pre><code>test.split("\\|"); </code></pre> <p><code>split</code> uses regular expression and in <em>regex</em> <code>|</code> is a metacharacter representing the <code>OR</code> operator. You need to escape that character using <code>\</code> (written in String as <code>"\\"</code> since <code>\</code> is also a metacharacter in String literals and require another <code>\</code> to escape it).</p> <p>You can also use </p> <pre><code>test.split(Pattern.quote("|")); </code></pre> <p>and let <code>Pattern.quote</code> create the escaped version of the regex representing <code>|</code>.</p>
{ "question_id": 10796160, "question_date": "2012-05-29T09:10:02.097Z", "question_score": 208, "tags": "java|regex|string", "answer_id": 10796174, "answer_date": "2012-05-29T09:10:47.180Z", "answer_score": 450 }
Please answer the following Stack Overflow question: Title: Format XML string to print friendly XML string <p>I have an XML string as such:</p> <pre><code>&lt;?xml version='1.0'?&gt;&lt;response&gt;&lt;error code='1'&gt; Success&lt;/error&gt;&lt;/response&gt; </code></pre> <p>There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:</p> <pre><code>&lt;?xml version='1.0'?&gt; &lt;response&gt; &lt;error code='1'&gt; Success&lt;/error&gt; &lt;/response&gt; </code></pre> <p>Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?</p>
<p>You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.</p> <pre><code>string FormatXml(string xml) { try { XDocument doc = XDocument.Parse(xml); return doc.ToString(); } catch (Exception) { // Handle and throw if fatal exception here; don't just ignore them return xml; } } </code></pre> <p>[using statements are ommitted for brevity]</p>
{ "question_id": 1123718, "question_date": "2009-07-14T06:15:38.413Z", "question_score": 208, "tags": "c#|xml|formatting", "answer_id": 1123947, "answer_date": "2009-07-14T07:25:24.403Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: Which characters are valid/invalid in a JSON key name? <p>Are there any forbidden characters in key names, for JavaScript objects or JSON strings? Or characters that need to be escaped?</p> <p>To be more specific, I'd like to use "$", "-" and space in key names.</p>
<p>No. Any valid string is a valid key. It can even have <code>"</code> as long as you escape it:</p> <pre><code>{"The \"meaning\" of life":42} </code></pre> <p>There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.</p>
{ "question_id": 8676011, "question_date": "2011-12-30T03:58:17.793Z", "question_score": 208, "tags": "javascript|json|object|key", "answer_id": 8676021, "answer_date": "2011-12-30T03:59:39.483Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: browser sessionStorage. share between tabs? <p>I have some values in my site which I want to clear when the browser is closed. I chose <code>sessionStorage</code> to store those values. When tab is closed they are indeed cleared, and kept if the user presses f5; But if the user opens some link in a different tab these values are unavailable.</p> <p>How I can share <code>sessionStorage</code> values between all browser tabs with my application?</p> <p>The use case: put a value in some storage, keep that value accessible in all browser tabs and clear it if all tabs are closed.</p> <pre><code>if (!sessionStorage.getItem(key)) { sessionStorage.setItem(key, defaultValue) } </code></pre>
<p>You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another. </p> <p>This code would need to exist on ALL tabs. It should execute before your other scripts.</p> <pre><code>// transfers sessionStorage from one tab to another var sessionStorage_transfer = function(event) { if(!event) { event = window.event; } // ie suq if(!event.newValue) return; // do nothing if no value to work with if (event.key == 'getSessionStorage') { // another tab asked for the sessionStorage -&gt; send it localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage)); // the other tab should now have it, so we're done with it. localStorage.removeItem('sessionStorage'); // &lt;- could do short timeout as well. } else if (event.key == 'sessionStorage' &amp;&amp; !sessionStorage.length) { // another tab sent data &lt;- get it var data = JSON.parse(event.newValue); for (var key in data) { sessionStorage.setItem(key, data[key]); } } }; // listen for changes to localStorage if(window.addEventListener) { window.addEventListener("storage", sessionStorage_transfer, false); } else { window.attachEvent("onstorage", sessionStorage_transfer); }; // Ask other tabs for session storage (this is ONLY to trigger event) if (!sessionStorage.length) { localStorage.setItem('getSessionStorage', 'foobar'); localStorage.removeItem('getSessionStorage', 'foobar'); }; </code></pre> <p>I tested this in chrome, ff, safari, ie 11, ie 10, ie9</p> <p>This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)</p> <p>Credit goes to this full article: <a href="http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/">http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/</a></p>
{ "question_id": 20325763, "question_date": "2013-12-02T10:16:51.723Z", "question_score": 208, "tags": "javascript|cross-browser|session-storage", "answer_id": 32766809, "answer_date": "2015-09-24T16:47:24.710Z", "answer_score": 180 }
Please answer the following Stack Overflow question: Title: Append values to query string <p>I have set of URLs similar to the ones below in a list</p> <ul> <li><code>http://somesite.example/backup/lol.php?id=1&amp;server=4&amp;location=us</code></li> <li><code>http://somesite.example/news.php?article=1&amp;lang=en</code></li> </ul> <p>I have managed to get the query strings using the following code:</p> <pre><code>myurl = longurl.Split('?'); NameValueCollection qs = HttpUtility.ParseQueryString(myurl [1]); foreach (string lol in qs) { // results will return } </code></pre> <p>But it only returns the parameters like <strong>id</strong>, <strong>server</strong>, <strong>location</strong> and so on based on the URL provided.</p> <p>What I need is to add / append values to the existing query strings.</p> <p>For example with the URL:</p> <p><code>http://somesite.example/backup/index.php?action=login&amp;attempts=1</code></p> <p>I need to alter the values of the query string parameters:</p> <p><strong>action=login1</strong></p> <p><strong>attempts=11</strong></p> <p>As you can see, I have appended &quot;1&quot; for each value. I need to get a set of URLs from a string with different query strings in them and add a value to each parameter at the end &amp; again add them to a list.</p>
<p>You could use the <a href="http://msdn.microsoft.com/en-us/library/ms150046.aspx" rel="noreferrer"><code>HttpUtility.ParseQueryString</code></a> method and an <a href="http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx" rel="noreferrer"><code>UriBuilder</code></a> which provides a nice way to work with query string parameters without worrying about things like parsing, URL encoding, ...:</p> <pre><code>string longurl = &quot;http://somesite.example/news.php?article=1&amp;lang=en&quot;; var uriBuilder = new UriBuilder(longurl); var query = HttpUtility.ParseQueryString(uriBuilder.Query); query[&quot;action&quot;] = &quot;login1&quot;; query[&quot;attempts&quot;] = &quot;11&quot;; uriBuilder.Query = query.ToString(); longurl = uriBuilder.ToString(); // &quot;http://somesite.example:80/news.php?article=1&amp;lang=en&amp;action=login1&amp;attempts=11&quot; </code></pre>
{ "question_id": 14517798, "question_date": "2013-01-25T08:10:25.883Z", "question_score": 208, "tags": "c#|parameters|query-string", "answer_id": 14517976, "answer_date": "2013-01-25T08:24:24.670Z", "answer_score": 420 }
Please answer the following Stack Overflow question: Title: C++ compiling on Windows and Linux: ifdef switch <p>I want to run some c++ code on Linux and Windows. There are some pieces of code that I want to include only for one operating system and not the other. Is there a standard <em>#ifdef</em> that once can use?</p> <p>Something like:</p> <pre><code> #ifdef LINUX_KEY_WORD ... // linux code goes here. #elif WINDOWS_KEY_WORD ... // windows code goes here. #else #error "OS not supported!" #endif </code></pre> <hr> <p>The question is indeed a duplicate but the answers here are much better, especially the accepted one.</p>
<p>use:</p> <pre><code>#ifdef __linux__ //linux code goes here #elif _WIN32 // windows code goes here #else #endif </code></pre>
{ "question_id": 6649936, "question_date": "2011-07-11T12:15:55.453Z", "question_score": 208, "tags": "c++|linux|windows|conditional-compilation", "answer_id": 6649992, "answer_date": "2011-07-11T12:21:15.457Z", "answer_score": 254 }
Please answer the following Stack Overflow question: Title: Saving results with headers in SQL Server Management Studio <p>I am using SQL Server Management Studio. </p> <p>I wish to save the results of a query to an excel file. </p> <p>I choose "save as" and then save to CSV file which I can open in excel. All good except I am missing column headers, any ideas how I get them exported?</p>
<p><code>Tools</code> > <code>Options</code> > <code>Query Results</code> > <code>SQL Server</code> > <code>Results to Text (or Grid if you want)</code> > <code>Include columns headers in the result set</code></p> <p>You might need to close and reopen SSMS after changing this option.</p> <p><strong>On the SQL Editor Toolbar you can select save to file without having to restart SSMS</strong></p>
{ "question_id": 10677133, "question_date": "2012-05-20T20:54:18.197Z", "question_score": 208, "tags": "sql|sql-server-2008|excel|ssms|export-to-excel", "answer_id": 10677148, "answer_date": "2012-05-20T20:57:23.410Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: How do I automatically update a timestamp in PostgreSQL <p>I want the code to be able to automatically update the time stamp when a new row is inserted as I can do in MySQL using CURRENT_TIMESTAMP.</p> <p>How will I be able to achieve this in PostgreSQL?</p> <pre><code>CREATE TABLE users ( id serial not null, firstname varchar(100), middlename varchar(100), lastname varchar(100), email varchar(200), timestamp timestamp ) </code></pre>
<p>To populate the column during insert, use a <a href="http://www.postgresql.org/docs/current/static/ddl-default.html" rel="noreferrer"><code>DEFAULT</code></a> value:</p> <pre><code>CREATE TABLE users ( id serial not null, firstname varchar(100), middlename varchar(100), lastname varchar(100), email varchar(200), timestamp timestamp default current_timestamp ) </code></pre> <p>Note that the value for that column can explicitly be overwritten by supplying a value in the <a href="http://www.postgresql.org/docs/current/static/dml-insert.html" rel="noreferrer"><code>INSERT</code></a> statement. If you want to prevent that you do need a <a href="http://www.postgresql.org/docs/current/static/plpgsql-trigger.html" rel="noreferrer">trigger</a>. </p> <p>You also need a trigger if you need to update that column whenever the row is updated (as <a href="https://stackoverflow.com/a/9556527/642706">mentioned by E.J. Brennan</a>)</p> <p>Note that using reserved words for column names is usually not a good idea. You should find a different name than <code>timestamp</code></p>
{ "question_id": 9556474, "question_date": "2012-03-04T16:08:15.403Z", "question_score": 208, "tags": "database|postgresql|timestamp", "answer_id": 9556581, "answer_date": "2012-03-04T16:23:59.320Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: Where are static variables stored in C and C++? <p>In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision? For example:</p> <pre><code> foo.c: bar.c: static int foo = 1; static int foo = 10; void fooTest() { void barTest() { static int bar = 2; static int bar = 20; foo++; foo++; bar++; bar++; printf("%d,%d", foo, bar); printf("%d, %d", foo, bar); } } </code></pre> <p>If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.</p> <p>But where is the storage allocated?</p> <p>To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I <em>believe</em> that there <strong>has</strong> to be some space reserved in the executable file for those static variables.<br> For discussion purposes, lets assume we use the GCC toolchain.</p>
<p>Where your statics go depends on whether they are <em>zero-initialized</em>. <em>zero-initialized</em> static data goes in <a href="http://en.wikipedia.org/wiki/.bss" rel="noreferrer">.BSS (Block Started by Symbol)</a>, <em>non-zero-initialized</em> data goes in <a href="http://en.wikipedia.org/wiki/Data_segment" rel="noreferrer">.DATA</a></p>
{ "question_id": 93039, "question_date": "2008-09-18T14:29:05.937Z", "question_score": 208, "tags": "c++|c|compiler-construction", "answer_id": 93411, "answer_date": "2008-09-18T15:07:35.283Z", "answer_score": 149 }
Please answer the following Stack Overflow question: Title: Linux delete file with size 0 <p>How do I delete a certain file in linux if its size is 0. I want to execute this in an crontab without any extra script.</p> <pre><code>l filename.file | grep 5th-tab | not eq 0 | rm </code></pre> <p>Something like this?</p>
<p>This will delete all the files in a directory (and below) that are size zero.</p> <pre><code>find /tmp -size 0 -print -delete </code></pre> <p>If you just want a particular file;</p> <pre><code>if [ ! -s /tmp/foo ] ; then rm /tmp/foo fi </code></pre>
{ "question_id": 5475905, "question_date": "2011-03-29T16:39:20.667Z", "question_score": 208, "tags": "linux|filesystems|delete-file|ls|rm", "answer_id": 5475933, "answer_date": "2011-03-29T16:41:24.113Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: Problem with converting int to string in Linq to entities <pre><code>var items = from c in contacts select new ListItem { Value = c.ContactId, //Cannot implicitly convert type 'int' (ContactId) to 'string' (Value). Text = c.Name }; var items = from c in contacts select new ListItem { Value = c.ContactId.ToString(), //Throws exception: ToString is not supported in linq to entities. Text = c.Name }; </code></pre> <p>Is there anyway I can achieve this? Note, that in VB.NET there is no problem use the first snippet it works just great, VB is flexible, im unable to get used to C#'s strictness!!!</p>
<p>With EF v4 you can use <a href="http://msdn.microsoft.com/en-us/library/dd466166.aspx" rel="noreferrer"><code>SqlFunctions.StringConvert</code></a>. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:</p> <pre><code>var items = from c in contacts select new ListItem { Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(), Text = c.Name }; </code></pre>
{ "question_id": 1066760, "question_date": "2009-07-01T00:20:25.797Z", "question_score": 208, "tags": "c#|asp.net|linq-to-entities|tostring", "answer_id": 3292773, "answer_date": "2010-07-20T17:44:02.340Z", "answer_score": 320 }
Please answer the following Stack Overflow question: Title: How to trim white spaces of array values in php <p>I have an array as follows</p> <pre><code>$fruit = array(' apple ','banana ', ' , ', ' cranberry '); </code></pre> <p>I want an array which contains the values without the white spaces on either sides but it can contain empty values how to do this in php.the output array should be like this</p> <pre><code>$fruit = array('apple','banana', ',', 'cranberry'); </code></pre>
<p><a href="http://php.net/manual/en/function.array-map.php" rel="noreferrer"><strong>array_map</strong></a> and <a href="http://php.net/manual/en/function.trim.php" rel="noreferrer"><strong>trim</strong></a> can do the job</p> <pre><code>$trimmed_array = array_map('trim', $fruit); print_r($trimmed_array); </code></pre>
{ "question_id": 5762439, "question_date": "2011-04-23T05:41:37.547Z", "question_score": 208, "tags": "php|arrays", "answer_id": 5762453, "answer_date": "2011-04-23T05:44:42.277Z", "answer_score": 563 }
Please answer the following Stack Overflow question: Title: What is the correct XPath for choosing attributes that contain "foo"? <p>Given this XML, what XPath returns all elements whose <code>prop</code> attribute contains <code>Foo</code> (the first three nodes):</p> <pre><code>&lt;bla&gt; &lt;a prop="Foo1"/&gt; &lt;a prop="Foo2"/&gt; &lt;a prop="3Foo"/&gt; &lt;a prop="Bar"/&gt; &lt;/bla&gt; </code></pre>
<pre><code>//a[contains(@prop,'Foo')] </code></pre> <p>Works if I use this XML to get results back.</p> <pre><code>&lt;bla&gt; &lt;a prop="Foo1"&gt;a&lt;/a&gt; &lt;a prop="Foo2"&gt;b&lt;/a&gt; &lt;a prop="3Foo"&gt;c&lt;/a&gt; &lt;a prop="Bar"&gt;a&lt;/a&gt; &lt;/bla&gt; </code></pre> <p>Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use</p> <pre><code>/bla/a[contains(@prop,'Foo')] </code></pre> <p>This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element</p> <pre><code>//a[contains(@prop,'Foo')] </code></pre> <p>I added this for the sake of thoroughness and in the spirit of stackoverflow. :)</p>
{ "question_id": 103325, "question_date": "2008-09-19T16:11:05.567Z", "question_score": 208, "tags": "xml|xpath", "answer_id": 103417, "answer_date": "2008-09-19T16:23:03.337Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: Android Room - simple select query - Cannot access database on the main thread <p>I am trying a sample with <a href="https://developer.android.com/topic/libraries/architecture/room.html" rel="noreferrer">Room Persistence Library</a>. I created an Entity:</p> <pre><code>@Entity public class Agent { @PrimaryKey public String guid; public String name; public String email; public String password; public String phone; public String licence; } </code></pre> <p>Created a DAO class:</p> <pre><code>@Dao public interface AgentDao { @Query("SELECT COUNT(*) FROM Agent where email = :email OR phone = :phone OR licence = :licence") int agentsCount(String email, String phone, String licence); @Insert void insertAgent(Agent agent); } </code></pre> <p>Created the Database class:</p> <pre><code>@Database(entities = {Agent.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract AgentDao agentDao(); } </code></pre> <p>Exposed database using below subclass in Kotlin:</p> <pre><code>class MyApp : Application() { companion object DatabaseSetup { var database: AppDatabase? = null } override fun onCreate() { super.onCreate() MyApp.database = Room.databaseBuilder(this, AppDatabase::class.java, "MyDatabase").build() } } </code></pre> <p>Implemented below function in my activity:</p> <pre><code>void signUpAction(View view) { String email = editTextEmail.getText().toString(); String phone = editTextPhone.getText().toString(); String license = editTextLicence.getText().toString(); AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao(); //1: Check if agent already exists int agentsCount = agentDao.agentsCount(email, phone, license); if (agentsCount &gt; 0) { //2: If it already exists then prompt user Toast.makeText(this, "Agent already exists!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show(); onBackPressed(); } } </code></pre> <p>Unfortunately on execution of above method it crashes with below stack trace:</p> <pre><code> FATAL EXCEPTION: main Process: com.example.me.MyApp, PID: 31592 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:5612) at android.view.View$PerformClick.run(View.java:22288) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:5612)  at android.view.View$PerformClick.run(View.java:22288)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6123)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)  Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time. at android.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:137) at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:165) at com.example.me.MyApp.RoomDb.Dao.AgentDao_Impl.agentsCount(AgentDao_Impl.java:94) at com.example.me.MyApp.View.SignUpActivity.signUpAction(SignUpActivity.java:58) at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:5612)  at android.view.View$PerformClick.run(View.java:22288)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6123)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)  </code></pre> <p>Seems like that problem is related to execution of db operation on main thread. However the sample test code provided in above link does not run on a separate thread:</p> <pre><code>@Test public void writeUserAndReadInList() throws Exception { User user = TestUtil.createUser(3); user.setName("george"); mUserDao.insert(user); List&lt;User&gt; byName = mUserDao.findUsersByName("george"); assertThat(byName.get(0), equalTo(user)); } </code></pre> <p>Am I missing anything over here? How can I make it execute without crash? Please suggest.</p>
<p>Database access on main thread locking the UI is the error, like Dale said.</p> <p><strong>--EDIT 2--</strong></p> <p>Since many people may come across this answer... The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta). <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html" rel="noreferrer">https://kotlinlang.org/docs/reference/coroutines-overview.html</a> <a href="https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01" rel="noreferrer">https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01</a></p> <p><strong>--EDIT 1--</strong></p> <p>For people wondering... You have other options. I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room. <a href="https://developer.android.com/topic/libraries/architecture/livedata.html" rel="noreferrer">https://developer.android.com/topic/libraries/architecture/livedata.html</a></p> <p>Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData. <a href="https://github.com/ReactiveX/RxJava" rel="noreferrer">https://github.com/ReactiveX/RxJava</a></p> <p><strong>--Original answer--</strong></p> <p>Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.</p> <pre><code>private static class AgentAsyncTask extends AsyncTask&lt;Void, Void, Integer&gt; { //Prevent leak private WeakReference&lt;Activity&gt; weakActivity; private String email; private String phone; private String license; public AgentAsyncTask(Activity activity, String email, String phone, String license) { weakActivity = new WeakReference&lt;&gt;(activity); this.email = email; this.phone = phone; this.license = license; } @Override protected Integer doInBackground(Void... params) { AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao(); return agentDao.agentsCount(email, phone, license); } @Override protected void onPostExecute(Integer agentsCount) { Activity activity = weakActivity.get(); if(activity == null) { return; } if (agentsCount &gt; 0) { //2: If it already exists then prompt user Toast.makeText(activity, &quot;Agent already exists!&quot;, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, &quot;Agent does not exist! Hurray :)&quot;, Toast.LENGTH_LONG).show(); activity.onBackPressed(); } } } </code></pre> <p>Or you can create a final class on its own file.</p> <p>Then execute it in the signUpAction(View view) method:</p> <pre><code>new AgentAsyncTask(this, email, phone, license).execute(); </code></pre> <p>In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.</p> <p>Also, your question about the Google's test example... They state in that web page:</p> <blockquote> <p>The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.</p> </blockquote> <p>No Activity, no UI.</p>
{ "question_id": 44167111, "question_date": "2017-05-24T19:36:33.417Z", "question_score": 208, "tags": "android|crash|kotlin|android-studio-3.0|android-room", "answer_id": 44167951, "answer_date": "2017-05-24T20:30:29.643Z", "answer_score": 73 }
Please answer the following Stack Overflow question: Title: String Resource new line /n not possible? <p>It doesn't seem like it's possible to add a new line <code>/n</code> to an XML resource string. Is there another way of doing this?</p>
<p>use a blackslash not a forwardslash. <code>\n</code></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;resources&gt; &lt;string name=&quot;title&quot;&gt;Hello\nWorld!&lt;/string&gt; &lt;/resources&gt; </code></pre> <p>Also, if you plan on using the string as HTML, you can use <code>&amp;lt;br /&amp;gt;</code> for a line break(<code>&lt;br /&gt;</code>)</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;resources&gt; &lt;string name=&quot;title&quot;&gt;Hello&amp;lt;br /&amp;gt;World!&lt;/string&gt; &lt;/resources&gt; </code></pre>
{ "question_id": 5460256, "question_date": "2011-03-28T14:13:47.017Z", "question_score": 208, "tags": "android|xml|android-layout|newline|android-resources", "answer_id": 5460289, "answer_date": "2011-03-28T14:16:36.323Z", "answer_score": 431 }
Please answer the following Stack Overflow question: Title: Is there a jQuery unfocus method? <p>How can I unfocus a textarea or input? I couldn't find a <code>$('#my-textarea').unfocus();</code> method?</p>
<pre><code>$('#textarea').blur() </code></pre> <p>Documentation at: <a href="http://api.jquery.com/blur/" rel="noreferrer">http://api.jquery.com/blur/</a></p>
{ "question_id": 857245, "question_date": "2009-05-13T10:45:50.047Z", "question_score": 208, "tags": "javascript|jquery", "answer_id": 857256, "answer_date": "2009-05-13T10:47:30.603Z", "answer_score": 358 }
Please answer the following Stack Overflow question: Title: GIT clone repo across local file system in windows <p>I am a complete Noob when it comes to GIT. I have been just taking my first steps over the last few days. I setup a repo on my laptop, pulled down the Trunk from an SVN project (had some issues with branches, not got them working), but all seems ok there.</p> <p>I now want to be able to pull or push from the laptop to my main desktop. The reason being the laptop is handy on the train as I spend 2 hours a day travelling and can get some good work done. But my main machine at home is great for development. So I want to be able to push / pull from the laptop to the main computer when I get home. I thought the most simple way of doing this would be to just have the code folder shared out across the LAN and do:</p> <pre><code>git clone file://192.168.10.51/code </code></pre> <p>unfortunately this doesn't seem to be working for me:</p> <p>so I open a git bash cmd and type the above command, I am in C:\code (the shared folder for both machines) this is what I get back:</p> <pre><code>Initialized empty Git repository in C:/code/code/.git/ fatal: 'C:/Program Files (x86)/Git/code' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>How can I share the repository between the two machines in the most simple of ways.</p> <p>There will be other locations that will be official storage points and places where the other devs and CI server etc will pull from, this is just so that I can work on the same repo across two machines.</p> <p>As per Sebastian's suggestion I get the following:</p> <pre><code>C:\code&gt;git clone --no-hardlinks file://192.168.10.51/code Initialized empty Git repository in C:/code/code/.git/ fatal: 'C:/Program Files (x86)/Git/code' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>**EDIT - ANSWER **</p> <p>Thanks to all that helped. I tried the mapping a drive and that worked so thought I would go back and retry without mapping. The final result was:</p> <pre><code>git clone file://\\\\192.168.0.51\code </code></pre> <p>This worked great.</p> <p>Thanks</p>
<p>You can specify the remote’s URL by applying the <a href="http://msdn.microsoft.com/en-us/library/gg465305.aspx" rel="noreferrer" title="Universal Naming Convention">UNC</a> path to the file protocol. This requires you to use four slashes:</p> <pre><code>git clone file:////&lt;host&gt;/&lt;share&gt;/&lt;path&gt; </code></pre> <p>For example, if your main machine has the IP <em>192.168.10.51</em> and the computer name <code>main</code>, and it has a share named <code>code</code> which itself is a git repository, then both of the following commands should work equally:</p> <pre><code>git clone file:////main/code git clone file:////192.168.10.51/code </code></pre> <p>If the Git repository is in a subdirectory, simply append the path:</p> <pre><code>git clone file:////main/code/project-repository git clone file:////192.168.10.51/code/project-repository </code></pre>
{ "question_id": 2519933, "question_date": "2010-03-25T22:34:47.117Z", "question_score": 208, "tags": "windows|git|git-clone", "answer_id": 2520121, "answer_date": "2010-03-25T23:16:55.433Z", "answer_score": 183 }
Please answer the following Stack Overflow question: Title: Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android <p>I know there are lots of questions similiar to this one, but i couldn't find a solution for my problem in any of those. Besides, I'll provide details for my specific case.</p> <p>I coded an Ionic project in Ubuntu 16.04 LTS, and now I have to build it for release. So I run the command:</p> <pre><code>cordova build --release android </code></pre> <p>And I'm shown the following error:</p> <pre><code>Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK. Looked here: /home/user/Android/Sdk/tools/templates/gradle/wrapper </code></pre> <ul> <li>I don't have this <code>templates/gradle/wrapper</code> directory.</li> <li>My Android Studio is 2.3, the latest version for now</li> <li>Android SDK Platform-Tools 25.0.3</li> <li>Android SDK Tools 25.3.1</li> <li>All Android versions from 2.1 (Eclair) to 7.1.1 (Nougat)</li> </ul> <p>After extensive research, I put all the Android Studio-related environment variables in the file <code>/etc/environment</code>. So now it looks like this:</p> <pre><code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/game:/home/&lt;user&gt;/Android/Sdk:/home/&lt;user&gt;/Android/Sdk/tools:/home/&lt;user&gt;/Android/Sdk/platform-tools" ANDROID_HOME=/home/&lt;user&gt;/Android/Sdk export ANDROID_HOME JAVA_HOME=/usr/lib/jvm/java-8-oracle export JAVA_HOME GRADLE_HOME=/opt/android-studio/gradle/gradle-3.2 export GRADLE_HOME </code></pre> <p>Now, for the sake of testing the environment variables, I run the following commands:</p> <pre><code>source /etc/environment echo $PATH echo $ANDROID_HOME echo $JAVA_HOME echo $GRADLE_HOME </code></pre> <p>And all the path variables are correctly displayed.</p> <p><strong>So, it looks like the environment variables are like they should be according to the various similar questions and in tutorials i've searched. Does anyone know what am I doing wrong? Why do I still get the Gradle Wrapper error?</strong></p>
<p>I just experienced the same problem.</p> <p>It may be an occlusion in the instructions regarding how to install (or upgrade) Android Studio with all the SDK Tools which both you and I missed or possibly a bug created by a new release of Studio which does not follow the same file conventions as the older versions. I lean towards the latter since many of <a href="https://stackoverflow.com/questions/33123898/missing-gradle-in-android-sdk-using-cordova-ionic#39469596">the SO posts</a> on this topic seems to point to an ANDROID_PATH with a folder called android-sdk which does not appear in the latest (2.3.0.8) version.</p> <p>There appears to be <a href="https://stackoverflow.com/a/41177145/4941585">a workaround though</a>, which I just got to work on my machine. Here's what I did:</p> <ul> <li><p>Download tools_r25.2.3-windows.zip from <a href="https://dl.google.com/android/repository/tools_r25.2.3-windows.zip?hl=id" rel="nofollow noreferrer">Android Downloads</a>.</p> </li> <li><p>Extracted zip on desktop</p> </li> <li><p>Replaced C:\Users\username\AppData\Local\Android\sdk\tools with extracted sub-folder tools/</p> </li> <li><p>In project folder:</p> <p>$ cordova platforms remove android<br /> $ cordova platforms add android</p> </li> </ul> <p>You may also need to force remove the node_modules in android. Hopefully this helps.</p>
{ "question_id": 42613882, "question_date": "2017-03-05T20:56:11.763Z", "question_score": 208, "tags": "cordova|ionic-framework|android-gradle-plugin", "answer_id": 42639125, "answer_date": "2017-03-07T02:32:17.780Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Find where java class is loaded from <p>Does anyone know how to programmaticly find out where the java classloader actually loads the class from? </p> <p>I often work on large projects where the classpath gets very long and manual searching is not really an option. I recently had a <a href="https://stackoverflow.com/questions/226280/eclipse-class-version-bug" title="problem">problem</a> where the classloader was loading an incorrect version of a class because it was on the classpath in two different places.</p> <p>So how can I get the classloader to tell me where on disk the actual class file is coming from?</p> <p><strong><em>Edit:</em></strong> What about if the classloader actually fails to load the class due to a version mismatch (or something else), is there anyway we could find out what file its trying to read before it reads it?</p>
<p>Here's an example:</p> <pre><code>package foo; public class Test { public static void main(String[] args) { ClassLoader loader = Test.class.getClassLoader(); System.out.println(loader.getResource("foo/Test.class")); } } </code></pre> <p>This printed out:</p> <pre><code>file:/C:/Users/Jon/Test/foo/Test.class </code></pre>
{ "question_id": 227486, "question_date": "2008-10-22T20:44:41.040Z", "question_score": 208, "tags": "java|classpath|classloader", "answer_id": 227569, "answer_date": "2008-10-22T21:15:09.013Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: What is the use of the square brackets [] in sql statements? <p>I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.</p> <p>Example:</p> <p>Visual Studio:</p> <pre><code>SELECT [column1], [column2] etc... </code></pre> <p>My own way:</p> <pre><code>SELECT column1, column2 etc... </code></pre>
<p>The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column <code>[First Name]</code> (with a space) – but then you'd need to use brackets every time you referred to that column.</p> <p>The newer tools add them everywhere just in case or for consistency.</p>
{ "question_id": 52898, "question_date": "2008-09-09T21:02:24.337Z", "question_score": 208, "tags": "sql-server|syntax", "answer_id": 52901, "answer_date": "2008-09-09T21:03:57.483Z", "answer_score": 230 }
Please answer the following Stack Overflow question: Title: What is the best way to pass AWS credentials to a Docker container? <p>I am running docker-container on Amazon EC2. Currently I have added AWS Credentials to Dockerfile. Could you please let me know the best way to do this?</p>
<p>The best way is to use IAM Role and do not deal with credentials at all. (see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html" rel="noreferrer">http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html</a> )</p> <p>Credentials could be retrieved from <code>http://169.254.169.254.....</code> Since this is a private ip address, it could be accessible only from EC2 instances. </p> <p>All modern AWS client libraries "know" how to fetch, refresh and use credentials from there. So in most cases you don't even need to know about it. Just run ec2 with correct IAM role and you good to go.</p> <p>As an option you can pass them at the runtime as environment variables ( i.e <code>docker run -e AWS_ACCESS_KEY_ID=xyz -e AWS_SECRET_ACCESS_KEY=aaa myimage</code>)</p> <p>You can access these environment variables by running printenv at the terminal.</p>
{ "question_id": 36354423, "question_date": "2016-04-01T10:50:51.487Z", "question_score": 208, "tags": "amazon-web-services|docker|docker-compose", "answer_id": 36357388, "answer_date": "2016-04-01T13:16:40.530Z", "answer_score": 162 }
Please answer the following Stack Overflow question: Title: How to declare a Fixed length Array in TypeScript <p>At the risk of demonstrating my lack of knowledge surrounding TypeScript types - I have the following question.</p> <p>When you make a type declaration for an array like this...</p> <pre><code>position: Array&lt;number&gt;; </code></pre> <p>...it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length i.e. 3 for x,y,z components can you make a type with for a fixed length array, something like this?</p> <pre><code>position: Array&lt;3&gt; </code></pre> <p>Any help or clarification appreciated!</p>
<p>The JavaScript array has a constructor that accepts the length of the array:</p> <pre><code>let arr = new Array&lt;number&gt;(3); console.log(arr); // [undefined × 3] </code></pre> <p>However, this is just the initial size, there's no restriction on changing that:</p> <pre><code>arr.push(5); console.log(arr); // [undefined × 3, 5] </code></pre> <p>TypeScript has <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html#tuple" rel="noreferrer">tuple types</a> which let you define an array with a specific length and types:</p> <pre><code>let arr: [number, number, number]; arr = [1, 2, 3]; // ok arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]' arr = [1, 2, &quot;3&quot;]; // Type '[number, number, string]' is not assignable to type '[number, number, number]' </code></pre>
{ "question_id": 41139763, "question_date": "2016-12-14T10:04:19.803Z", "question_score": 208, "tags": "typescript|types|fixed-length-array", "answer_id": 41140074, "answer_date": "2016-12-14T10:19:26.190Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: PHP - Get bool to echo false when false <p>The following code doesn't print out anything:</p> <pre><code>$bool_val = (bool)false; echo $bool_val; </code></pre> <p>But the following code prints <code>1</code>:</p> <pre><code>$bool_val = (bool)true; echo $bool_val; </code></pre> <p>Is there a better way to print <code>0</code> or <code>false</code> when <code>$bool_val</code> is <code>false</code> than adding an <code>if</code> statement?</p>
<pre><code>echo $bool_val ? 'true' : 'false'; </code></pre> <p>Or if you only want output when it's false:</p> <pre><code>echo !$bool_val ? 'false' : ''; </code></pre>
{ "question_id": 4948663, "question_date": "2011-02-09T18:02:25.150Z", "question_score": 208, "tags": "php|boolean", "answer_id": 4948685, "answer_date": "2011-02-09T18:05:12.680Z", "answer_score": 291 }
Please answer the following Stack Overflow question: Title: vim - How to delete a large block of text without counting the lines? <p>In vim, I often find myself deleting (or copying) large blocks of text. One can count the lines of text and say (for example) <code>50dd</code> to delete 50 lines. </p> <p>But how would one delete this large block of text without having to know how many lines to delete?</p>
<p>I'm no vim guru, but what I use in this circumstance is "visual mode". In command mode, type <code>V</code> (capital). Then move up/down to highlight the block you want deleted (all the usual movement commands work). Then remove it with <code>x</code> or <code>d</code>.</p>
{ "question_id": 5362363, "question_date": "2011-03-19T13:29:15.717Z", "question_score": 208, "tags": "vim", "answer_id": 5362397, "answer_date": "2011-03-19T13:35:25.183Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: Restart pods when configmap updates in Kubernetes? <p>How do I automatically restart Kubernetes pods and pods associated with deployments when their configmap is changed/updated?</p> <hr> <p>I know there's been talk about the ability to automatically restart pods when a config maps changes but to my knowledge this is not yet available in Kubernetes 1.2. </p> <p>So what (I think) I'd like to do is a "rolling restart" of the <a href="http://kubernetes.io/docs/user-guide/deployments/" rel="noreferrer">deployment</a> resource associated with the pods consuming the config map. Is it possible, and if so how, to force a rolling restart of a deployment in Kubernetes without changing anything in the actual template? Is this currently the best way to do it or is there a better option?</p>
<p>Signalling a pod on config map update is a feature in the works (<a href="https://github.com/kubernetes/kubernetes/issues/22368" rel="noreferrer">https://github.com/kubernetes/kubernetes/issues/22368</a>). </p> <p>You can always write a custom pid1 that notices the confimap has changed and restarts your app. </p> <p>You can also eg: mount the same config map in 2 containers, expose a http health check in the second container that fails if the hash of config map contents changes, and shove that as the liveness probe of the first container (because containers in a pod share the same network namespace). The kubelet will restart your first container for you when the probe fails. </p> <p>Of course if you don't care about which nodes the pods are on, you can simply delete them and the replication controller will "restart" them for you. </p>
{ "question_id": 37317003, "question_date": "2016-05-19T07:47:25.377Z", "question_score": 208, "tags": "kubernetes|kubernetes-pod|configmap", "answer_id": 37331352, "answer_date": "2016-05-19T18:27:55.483Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: Installing Bower on Ubuntu <p>I'm trying to install Bower on XUbuntu 13.10, following the instructions on the Bower home page, after doing <code>sudo apt-get install npm</code> and <code>sudo npm install -g bower</code> I get the following after issuing <code>bower</code> on the command line:</p> <pre><code>/usr/bin/env: node: No such file or directory </code></pre> <p>I then install Node (even though I assume that would not be unnecessary since Bower's only dependency would be NPM, correct?). Anyhow, after I install node with <code>sudo apt-get install node</code> any of the Bower commands, such as <code>bower help</code>, simply don't do anything, i.e. output nothing.</p> <p>How to install Bower on Ubuntu (preferably without manually downloading various versions of things)?</p>
<pre><code>sudo ln -s /usr/bin/nodejs /usr/bin/node </code></pre> <p>or install legacy nodejs:</p> <pre><code>sudo apt-get install nodejs-legacy </code></pre> <p>As seen in <a href="https://github.com/joyent/node/issues/3911" rel="noreferrer">this GitHub issue</a>.</p>
{ "question_id": 21491996, "question_date": "2014-01-31T23:31:07.957Z", "question_score": 208, "tags": "npm|bower", "answer_id": 22791301, "answer_date": "2014-04-01T16:14:42.057Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: How to switch namespace in kubernetes <p>Say, I have two namespaces k8s-app1 and k8s-app2</p> <p>I can list all pods from specific namespace using the below command</p> <pre><code>kubectl get pods -n &lt;namespace&gt; </code></pre> <p>We need to append namespace to all commands to list objects from the respective namespaces. Is there a way to set specific namespace and list objects without including the namespace explicitly?</p>
<p>I was able to switch namespace using the below steps</p> <pre><code>kubectl config set-context $(kubectl config current-context) --namespace=&lt;namespace&gt; kubectl config view | grep namespace kubectl get pods </code></pre> <p>This is how i have tested</p> <pre><code># Create namespaces k8s-app1, k8s-app2 and k8s-app3 master $ kubectl create ns k8s-app1 namespace/k8s-app1 created master $ kubectl create ns k8s-app2 namespace/k8s-app2 created master $ kubectl create ns k8s-app3 namespace/k8s-app3 created # Create Service Account app1-sa in k8s-app1 # Service Account app2-sa in k8s-app2 # Service Account app3-sa in k8s-app3 master $ kubectl create sa app1-sa -n k8s-app1 serviceaccount/app1-sa created master $ kubectl create sa app2-sa -n k8s-app2 serviceaccount/app2-sa created master $ kubectl create sa app3-sa -n k8s-app3 serviceaccount/app3-sa created # Switch namespace master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app1 Context "kubernetes-admin@kubernetes" modified. master $ kubectl config view | grep namespace namespace: k8s-app1 master $ kubectl get sa NAME SECRETS AGE app1-sa 1 1m default 1 6m master $ master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app2 Context "kubernetes-admin@kubernetes" modified. master $ kubectl get sa NAME SECRETS AGE app2-sa 1 2m default 1 7m master $ master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app3 Context "kubernetes-admin@kubernetes" modified. master $ kubectl get sa NAME SECRETS AGE app3-sa 1 2m default 1 7m </code></pre>
{ "question_id": 55373686, "question_date": "2019-03-27T09:24:39.587Z", "question_score": 208, "tags": "kubernetes|namespaces", "answer_id": 55373915, "answer_date": "2019-03-27T09:37:05.147Z", "answer_score": 31 }
Please answer the following Stack Overflow question: Title: Given an array of numbers, return array of products of all other numbers (no division) <p>I was asked this question in a job interview, and I'd like to know how others would solve it. I'm most comfortable with Java, but solutions in other languages are welcome.</p> <blockquote> <p>Given an array of numbers, <code>nums</code>, return an array of numbers <code>products</code>, where <code>products[i]</code> is the product of all <code>nums[j], j != i</code>.</p> <pre><code>Input : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24] </code></pre> <p>You must do this in <code>O(N)</code> without using division.</p> </blockquote>
<p>An explanation of <a href="https://stackoverflow.com/users/276101/polygenelubricants">polygenelubricants</a> method is:</p> <p>The trick is to construct the arrays (in the case for 4 elements):</p> <pre class="lang-cpp prettyprint-override"><code>{ 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], } { a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, } </code></pre> <p>Both of which can be done in O(n) by starting at the left and right edges respectively.</p> <p>Then, multiplying the two arrays element-by-element gives the required result.</p> <p>My code would look something like this:</p> <pre class="lang-cpp prettyprint-override"><code>int a[N] // This is the input int products_below[N]; int p = 1; for (int i = 0; i &lt; N; ++i) { products_below[i] = p; p *= a[i]; } int products_above[N]; p = 1; for (int i = N - 1; i &gt;= 0; --i) { products_above[i] = p; p *= a[i]; } int products[N]; // This is the result for (int i = 0; i &lt; N; ++i) { products[i] = products_below[i] * products_above[i]; } </code></pre> <p>If you need the solution be O(1) in space as well, you can do this (which is less clear in my opinion):</p> <pre class="lang-cpp prettyprint-override"><code>int a[N] // This is the input int products[N]; // Get the products below the current index int p = 1; for (int i = 0; i &lt; N; ++i) { products[i] = p; p *= a[i]; } // Get the products above the current index p = 1; for (int i = N - 1; i &gt;= 0; --i) { products[i] *= p; p *= a[i]; } </code></pre>
{ "question_id": 2680548, "question_date": "2010-04-21T05:29:08.347Z", "question_score": 208, "tags": "arrays|algorithm", "answer_id": 2680697, "answer_date": "2010-04-21T06:09:38.283Z", "answer_score": 284 }
Please answer the following Stack Overflow question: Title: What are .iml files in Android Studio? <p>What are <code>.iml</code> files in Android Studio project? I read that it is configuration file for modules. I do not understand how it works, and can't I just use gradle scripts to integrate with external modules that you add to your project.</p> <p>Also, most of the time AS generates them, so I cannot control project behaviour. If I have a team that works in different IDEs like Eclipse and AS, is it possible to setup my project so it's IDE agnostic?</p> <p>I don't fully understand how this system works.</p>
<blockquote> <p>What are iml files in Android Studio project?</p> </blockquote> <p>A Google search on <code>iml file</code> turns up:</p> <blockquote> <p>IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.</p> </blockquote> <p>(from <a href="http://www.openthefile.net/extension/iml">this page</a>)</p> <blockquote> <p>why not to use gradle scripts to integrate with external modules that you add to your project.</p> </blockquote> <p>You do "use gradle scripts to integrate with external modules", or your own modules.</p> <p>However, Gradle is not IntelliJ IDEA's native project model &mdash; that is separate, held in <code>.iml</code> files and the metadata in <code>.idea/</code> directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like <code>build.gradle</code>. This is also why you don't bother putting <code>.iml</code> files or <code>.idea/</code> in version control, as their contents will be regenerated.</p> <blockquote> <p>If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?</p> </blockquote> <p>To a large extent, you can't.</p> <p>You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via <code>build.gradle</code>, how to find files in that structure. However, other metadata (<code>compileSdkVersion</code>, dependencies, etc.) will not be nearly as easily replicated.</p> <p>Other alternatives include:</p> <ul> <li><p>Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio</p></li> <li><p>Hope that <a href="https://projects.eclipse.org/projects/tools.andmore">Andmore</a> takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts</p></li> <li><p>Have everyone use one IDE</p></li> </ul>
{ "question_id": 30737082, "question_date": "2015-06-09T15:55:06.070Z", "question_score": 208, "tags": "android-studio|intellij-idea|iml", "answer_id": 30737568, "answer_date": "2015-06-09T16:17:42.253Z", "answer_score": 190 }
Please answer the following Stack Overflow question: Title: Best practices for styling HTML emails <p>I'm designing an HTML template for an email newsletter. I've learned that many email clients ignore linked stylesheets, and many others (including Gmail) ignore CSS block declarations altogether. Are inline style attributes my only choice? What are the best practices for styling HTML emails?</p>
<p>Campaign Monitor have an excellent <a href="http://www.campaignmonitor.com/css/">support matrix</a> detailing what's supported and what isn't among various mail clients.</p> <p>You can use a service like <a href="http://litmus.com/">Litmus</a> to view how an email appears across several clients and whether they get caught by filters, etc.</p>
{ "question_id": 4829254, "question_date": "2011-01-28T14:22:58.967Z", "question_score": 208, "tags": "html|css|html-email", "answer_id": 4829306, "answer_date": "2011-01-28T14:29:23.060Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: Using an image caption in Markdown Jekyll <p>I am hosting a Jekyll Blog on Github and write my posts with Markdown. When I am adding images, I do it the following way:</p> <p><code>![name of the image](http://link.com/image.jpg)</code></p> <p>This then shows the image in the text. </p> <p>However, how can I tell Markdown to add a caption which is presented below or above the image?</p>
<p>If you don't want to use any plugins (which means you can push it to GitHub directly without generating the site first), you can create a new file named <code>image.html</code> in <code>_includes</code>:</p> <pre><code>&lt;figure class="image"&gt; &lt;img src="{{ include.url }}" alt="{{ include.description }}"&gt; &lt;figcaption&gt;{{ include.description }}&lt;/figcaption&gt; &lt;/figure&gt; </code></pre> <p>And then display the image from your markdown with:</p> <pre><code>{% include image.html url="/images/my-cat.jpg" description="My cat, Robert Downey Jr." %} </code></pre>
{ "question_id": 19331362, "question_date": "2013-10-12T06:42:58.563Z", "question_score": 208, "tags": "github|markdown|jekyll", "answer_id": 19360305, "answer_date": "2013-10-14T12:30:40.200Z", "answer_score": 160 }
Please answer the following Stack Overflow question: Title: How to handle AccessViolationException <p>I am using a COM object (MODI) from within my .net application. The method I am calling throws a <code>System.AccessViolationException</code>, which is intercepted by Visual Studio. The odd thing is that I have wrapped my call in a try catch, which has handlers for <code>AccessViolationException</code>, <code>COMException</code> and everything else, but when Visual Studio (2010) intercepts the <code>AccessViolationException</code>, the debugger breaks on the method call (doc.OCR), and if I step through, it continues to the next line instead of entering the catch block. Additionally, if I run this outside of the visual studio my application crashes. How can I handle this exception that is thrown within the COM object?</p> <pre><code>MODI.Document doc = new MODI.Document(); try { doc.Create(sFileName); try { doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false); sText = doc.Images[0].Layout.Text; } catch (System.AccessViolationException ex) { //MODI seems to get access violations for some reason, but is still able to return the OCR text. sText = doc.Images[0].Layout.Text; } catch (System.Runtime.InteropServices.COMException ex) { //if no text exists, the engine throws an exception. sText = &quot;&quot;; } catch { sText = &quot;&quot;; } if (sText != null) { sText = sText.Trim(); } } finally { doc.Close(false); //Cleanup routine, this is how we are able to delete files used by MODI. System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc); doc = null; GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } </code></pre>
<p><strong>EDIT</strong> <em>(3/17/2021)</em></p> <p>Disclaimer: This answer was written in 2011 and references the original <strong>.NET Framework 4.0</strong> implementation, NOT the open-source implementation of .NET.</p> <hr /> <p>In .NET 4.0, the runtime handles certain exceptions raised as Windows Structured Error Handling (SEH) errors as indicators of Corrupted State. These Corrupted State Exceptions (CSE) are not allowed to be caught by your standard managed code. I won't get into the why's or how's here. Read this article about CSE's in the .NET 4.0 Framework:</p> <p><a href="http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035</a></p> <p>But there is hope. There are a few ways to get around this:</p> <ol> <li><p>Recompile as a .NET 3.5 assembly and run it in .NET 4.0.</p> </li> <li><p>Add a line to your application's config file under the configuration/runtime element: <code>&lt;legacyCorruptedStateExceptionsPolicy enabled=&quot;true|false&quot;/&gt;</code></p> </li> <li><p>Decorate the methods you want to catch these exceptions in with the <code>HandleProcessCorruptedStateExceptions</code> attribute. See <a href="http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035</a> for details.</p> </li> </ol> <hr /> <p><strong>EDIT</strong></p> <p>Previously, I referenced a <a href="https://web.archive.org/web/20120104165841/http://connect.microsoft.com:80/VisualStudio/feedback/details/557105/unable-to-catch-accessviolationexception" rel="nofollow noreferrer">forum post</a> for additional details. But since Microsoft Connect has been retired, here are the additional details in case you're interested:</p> <p>From Gaurav Khanna, a developer from the Microsoft CLR Team</p> <blockquote> <p>This behaviour is by design due to a feature of CLR 4.0 called Corrupted State Exceptions. Simply put, managed code shouldnt make an attempt to catch exceptions that indicate corrupted process state and AV is one of them.</p> </blockquote> <p>He then goes on to reference the documentation on the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.handleprocesscorruptedstateexceptionsattribute.aspx" rel="nofollow noreferrer">HandleProcessCorruptedStateExceptionsAttribute</a> and the above article. Suffice to say, it's definitely worth a read if you're considering catching these types of exceptions.</p>
{ "question_id": 3469368, "question_date": "2010-08-12T15:33:00.993Z", "question_score": 208, "tags": "c#|.net|exception|com|process-state-exception", "answer_id": 4759831, "answer_date": "2011-01-21T14:19:31.177Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: Visual Studio: ContextSwitchDeadlock <p>I have been getting an error message that I can't resolve. It originates from Visual Studio or the debugger. I'm not sure whether the ultimate error condition is in VS, the debugger, my program, or the database. </p> <p>This is a Windows app. Not a web app.</p> <p>First message from VS is a popup box saying: "No symbols are loaded for any call stack frame. The source code can not be displayed." When that is clicked away, I get: "<strong>ContextSwitchDeadlock was detected</strong>", along with a long message reproduced below.</p> <p>The error arises in a loop that scans down a DataTable. For each line, it uses a key (HIC #) value from the table as a parameter for a SqlCommand. The command is used to create a SqlDataReader which returns one line. Data are compared. If an error is detected a row is added to a second DataTable.</p> <p>The error seems to be related to how long the procedure takes to run (i.e. after 60 sec), not how many errors are found. I don't think it's a memory issue. No variables are declared within the loop. The only objects that are created are the SqlDataReaders, and they are in Using structures. Add System.GC.Collect() had no effect.</p> <p>The db is a SqlServer site on the same laptop.</p> <p>There are no fancy gizmos or gadgets on the Form.</p> <p>I am not aware of anything in this proc which is greatly different from what I've done dozens of times before. I have seen the error before, but never on a consistent basis.</p> <p>Any ideas, anyone?</p> <p><strong>Full error Text:</strong> The CLR has been unable to transition from COM context 0x1a0b88 to COM context 0x1a0cf8 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.</p>
<p>The <code>ContextSwitchDeadlock</code> doesn't necessarily mean your code has an issue, just that there is a potential. If you go to <code>Debug &gt; Exceptions</code> in the menu and expand the <code>Managed Debugging Assistants</code>, you will find <code>ContextSwitchDeadlock</code> is enabled.</p> <p>If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.</p>
{ "question_id": 578357, "question_date": "2009-02-23T16:47:33.650Z", "question_score": 208, "tags": "c#|sql-server|visual-studio", "answer_id": 578439, "answer_date": "2009-02-23T17:07:18.953Z", "answer_score": 347 }
Please answer the following Stack Overflow question: Title: Angular 2 - innerHTML styling <p>I am getting chunks of HTML codes from HTTP calls. I put the HTML blocks in a variable and insert it on my page with [innerHTML] but I can not style the inserted HTML block. Does anyone have any suggestion how I might achieve this?</p> <pre class="lang-typescript prettyprint-override"><code>@Component({ selector: 'calendar', template: '&lt;div [innerHTML]=&quot;calendar&quot;&gt;&lt;/div&gt;', providers: [HomeService], styles: [`h3 { color: red; }`] }) </code></pre> <p>The HTML that I want to style is the block contained in the variable &quot;calendar&quot;.</p>
<p><strong>update 2 <code>::slotted</code></strong></p> <p><code>::slotted</code> is now supported by all new browsers and can be used with <code>ViewEncapsulation.ShadowDom</code></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted</a></p> <p><strong>update 1 ::ng-deep</strong></p> <p><code>/deep/</code> was deprecated and replaced by <code>::ng-deep</code>.</p> <p><code>::ng-deep</code> is also already marked deprecated, but there is no replacement available yet. </p> <p>When <code>ViewEncapsulation.Native</code> is properly supported by all browsers and supports styling accross shadow DOM boundaries, <code>::ng-deep</code> will probably be discontinued. </p> <p><strong>original</strong></p> <p>Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using <code>[innerHTML]</code> these classes are not added and the rewritten CSS doesn't match.</p> <p>As a workaround try </p> <ul> <li>for CSS added to the component</li> </ul> <pre class="lang-css prettyprint-override"><code>/* :host /deep/ mySelector { */ :host ::ng-deep mySelector { background-color: blue; } </code></pre> <ul> <li>for CSS added to <code>index.html</code></li> </ul> <pre class="lang-css prettyprint-override"><code>/* body /deep/ mySelector { */ body ::ng-deep mySelector { background-color: green; } </code></pre> <p><code>&gt;&gt;&gt;</code> (and the equivalent<code>/deep/</code> but <code>/deep/</code> works better with SASS) and <code>::shadow</code> were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with <code>encapsulation: ViewEncapsulation.Emulated</code> which is the default in Angular2. They probably also work with <code>ViewEncapsulation.None</code> but are then only ignored because they are not necessary. These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.</p> <p>Another approach is to use</p> <pre class="lang-css prettyprint-override"><code>@Component({ ... encapsulation: ViewEncapsulation.None, }) </code></pre> <p>for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be <strong>all</strong> components in your application)</p> <p><strong>Update</strong></p> <p><a href="https://plnkr.co/edit/ZHByFR?p=preview" rel="noreferrer">Example Plunker</a></p>
{ "question_id": 36265026, "question_date": "2016-03-28T15:04:23.290Z", "question_score": 208, "tags": "angular|innerhtml", "answer_id": 36265072, "answer_date": "2016-03-28T15:06:46.800Z", "answer_score": 374 }
Please answer the following Stack Overflow question: Title: What is the logic behind the "using" keyword in C++? <p>What is the logic behind the "using" keyword in C++?</p> <p>It is used in different situations and I am trying to find if all those have something in common and there is a reason why the "using" keyword is used as such.</p> <pre><code>using namespace std; // to import namespace in the current namespace using T = int; // type alias using SuperClass::X; // using super class methods in derived class </code></pre>
<p>In C++11, the <code>using</code> keyword when used for <code>type alias</code> is identical to <code>typedef</code>.</p> <p>7.1.3.2</p> <blockquote> <p>A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.</p> </blockquote> <p>Bjarne Stroustrup provides a practical example:</p> <pre><code>typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double using PF = void (*)(double); // `using`-based equivalent of the typedef above using P = [](double)-&gt;void; // using plus suffix return type, syntax error using P = auto(double)-&gt;void // Fixed thanks to DyP </code></pre> <p>Pre-C++11, the <code>using</code> keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):</p> <pre><code>class Derived : public Base { public: using Base::f; // lift Base's f into Derived's scope -- works in C++98 void f(char); // provide a new f void f(int); // prefer this f to Base::f(int) using Base::Base; // lift Base constructors Derived's scope -- C++11 only Derived(char); // provide a new constructor Derived(int); // prefer this constructor to Base::Base(int) // ... }; </code></pre> <hr /> <p>Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like <code>Impact on the Standard</code>, <code>Design decisions</code>, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.</p> <hr /> <p>Here is an old paper from 2003 <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1449.pdf" rel="noreferrer">n1449</a>. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.</p> <blockquote> <p>First let’s consider a toy example:</p> <pre><code>template &lt;typename T&gt; class MyAlloc {/*...*/}; template &lt;typename T, class A&gt; class MyVector {/*...*/}; template &lt;typename T&gt; struct Vec { typedef MyVector&lt;T, MyAlloc&lt;T&gt; &gt; type; }; Vec&lt;int&gt;::type p; // sample usage </code></pre> <p>The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.</p> <pre><code>template &lt;typename T&gt; void foo (Vec&lt;T&gt;::type&amp;); </code></pre> <p>So, the syntax is somewhat ugly. We would rather avoid the nested <code>::type</code> We’d prefer something like the following:</p> <pre><code>template &lt;typename T&gt; using Vec = MyVector&lt;T, MyAlloc&lt;T&gt; &gt;; //defined in section 2 below Vec&lt;int&gt; p; // sample usage </code></pre> <p>Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on <code>Vec&lt;T&gt;</code> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:</p> <pre><code>template &lt;typename T&gt; void foo (Vec&lt;T&gt;&amp;); </code></pre> <p>We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to <code>foo(p)</code> will succeed.</p> </blockquote> <hr /> <p>The follow-up paper <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1489.pdf" rel="noreferrer">n1489</a> explains why <code>using</code> instead of using <code>typedef</code>:</p> <blockquote> <p>It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:</p> <pre><code>template&lt;class T&gt; typedef std::vector&lt;T, MyAllocator&lt;T&gt; &gt; Vec; </code></pre> <p>That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; <code>Vec</code> is not an alias for a type, and should not be taken for a typedef-name. The name <code>Vec</code> is a name for the family <code>std::vector&lt; [bullet] , MyAllocator&lt; [bullet] &gt; &gt;</code> – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence</p> <pre><code>template&lt;class T&gt; using Vec = std::vector&lt;T, MyAllocator&lt;T&gt; &gt;; </code></pre> <p>can be read/interpreted as: from now on, I’ll be using <code>Vec&lt;T&gt;</code> as a synonym for <code>std::vector&lt;T, MyAllocator&lt;T&gt; &gt;</code>. With that reading, the new syntax for aliasing seems reasonably logical.</p> </blockquote> <p>I think the important distinction is made here, <em>alias</em>es instead of <em>type</em>s. Another quote from the same document:</p> <blockquote> <p>An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ✁ 2.3 for further discussion). [<b>My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.</b>] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.</p> </blockquote> <p>Summary, for the role of <code>using</code>:</p> <ul> <li>template aliases (or template typedefs, the former is preferred namewise)</li> <li>namespace aliases (i.e., <code>namespace PO = boost::program_options</code> and <code>using PO = ...</code> equivalent)</li> <li>the document says <code>A typedef declaration can be viewed as a special case of non-template alias-declaration</code>. It's an aesthetic change, and is considered identical in this case.</li> <li>bringing something into scope (for example, <code>namespace std</code> into the global scope), member functions, inheriting constructors</li> </ul> <p>It <b>cannot</b> be used for:</p> <pre><code>int i; using r = i; // compile-error </code></pre> <p>Instead do:</p> <pre><code>using r = decltype(i); </code></pre> <p>Naming a set of overloads.</p> <pre><code>// bring cos into scope using std::cos; // invalid syntax using std::cos(double); // not allowed, instead use Bjarne Stroustrup function pointer alias example using test = std::cos(double); </code></pre>
{ "question_id": 20790932, "question_date": "2013-12-26T20:37:14.943Z", "question_score": 208, "tags": "c++|c++11", "answer_id": 20791007, "answer_date": "2013-12-26T20:44:40.867Z", "answer_score": 160 }
Please answer the following Stack Overflow question: Title: Using different Web.config in development and production environment <p>I need to use different database connection string and SMTP server address in my ASP.NET application depending on it is run in development or production environment. </p> <p>The application reads settings from Web.config file via <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager.appsettings.aspx" rel="noreferrer">WebConfigurationManager.AppSettings</a> property.</p> <p>I use Build/Publish command to deploy the application to production server via FTP and then manually replace remote Web.config with correct one.</p> <p>Is it possible somehow simplify the process of deployment? Thanks!</p>
<p>In Visual Studio 2010 and above, you now have the ability to apply a transformation to your web.config depending on the build configuration.</p> <p>When creating a web.config, you can expand the file in the solution explorer, and you will see two files:</p> <ul> <li>Web.Debug.Config</li> <li>Web.Release.Config</li> </ul> <p>They contain transformation code that can be used to</p> <ul> <li>Change the connection string</li> <li>Remove debugging trace and settings</li> <li>Register error pages</li> </ul> <p>See <a href="http://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx" rel="noreferrer">Web.config Transformation Syntax for Web Application Project Deployment</a> on MSDN for more information.</p> <p>It is also possible, albeit officially unsupported, to apply the same kind of transformation to an non web application <code>app.config</code> file. See <a href="http://philbolduc.blogspot.com/2010/03/using-config-transforms-outside-web.html" rel="noreferrer">Phil Bolduc blog</a> concerning how to modify your project file to add a new task to msbuild.</p> <p>This is a long withstanding <a href="https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2043217-support-web-config-style-transforms-on-any-file-in" rel="noreferrer">request on the Visual Studio Uservoice</a>.</p> <p>An <a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" rel="noreferrer">extension for Visual Studio 2010</a> and above, "<a href="http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5" rel="noreferrer">SlowCheetah</a>," is available to take care of creating transform for any config file. Starting with Visual Studio 2017.3, <a href="https://blogs.msdn.microsoft.com/visualstudio/2017/08/15/updates-in-visual-studio-2017-based-on-your-uservoice-suggestions/" rel="noreferrer">SlowCheetah has been integrated into the IDE</a> and the code base is being managed by Microsoft. This new version also support JSON transformation.</p>
{ "question_id": 305447, "question_date": "2008-11-20T14:31:35.473Z", "question_score": 208, "tags": "asp.net|visual-studio|configuration|web-config", "answer_id": 3064598, "answer_date": "2010-06-17T18:46:19.823Z", "answer_score": 173 }