input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Android Command line tools sdkmanager always shows: Warning: Could not create settings <p>I use the <a href="https://developer.android.com/studio/#command-tools" rel="noreferrer">new <em>command line tools</em> for Android</a> because the old <em>sdk-tools</em> repository of Android isn't available anymore. So I changed my gitlab-ci to load the <code>commandlintools</code>. But when I try to run it I get the following error:</p> <pre><code>Warning: Could not create settings java.lang.IllegalArgumentException at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.&lt;init&gt;(SdkManagerCliSettings.java:428) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:152) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:134) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:57) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48) </code></pre> <p>I already tried executing those commandy by hand, but I get the same error. Also if I run <code>sdkmanager --version</code>, the same error occurs. My gitlab-ci looks like:</p> <pre><code>image: openjdk:9-jdk variables: ANDROID_COMPILE_SDK: &quot;29&quot; ANDROID_BUILD_TOOLS: &quot;29.0.3&quot; ANDROID_SDK_TOOLS: &quot;6200805&quot; before_script: - apt-get --quiet update --yes - apt-get --quiet install --yes wget tar unzip lib32stdc++6 lib32z1 - wget --quiet --output-document=android-sdk.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}_latest.zip - unzip -d android-sdk-linux android-sdk.zip - echo y | android-sdk-linux/tools/bin/sdkmanager &quot;platform-tools&quot; &quot;platforms;android-${ANDROID_COMPILE_SDK}&quot; &gt;/dev/null #- echo y | android-sdk-linux/tools/bin/sdkmanager &quot;platform-tools&quot; &gt;/dev/null - echo y | android-sdk-linux/tools/bin/sdkmanager &quot;build-tools;${ANDROID_BUILD_TOOLS}&quot; &gt;/dev/null - export ANDROID_HOME=$PWD/android-sdk-linux - export PATH=$PATH:$PWD/android-sdk-linux/platform-tools/ - chmod +x ./gradlew # temporarily disable checking for EPIPE error and use yes to accept all licenses - set +o pipefail - yes | android-sdk-linux/tools/bin/sdkmanager --licenses - set -o pipefail stages: - build - test lintDebug: stage: build script: - ./gradlew -Pci --console=plain :app:lintDebug -PbuildDir=lint assembleDebug: stage: build script: - ./gradlew assembleDebug artifacts: paths: - app/build/outputs/ debugTests: stage: test script: - ./gradlew -Pci --console=plain :app:testDebug </code></pre>
<p>Instead of passing the argument <code>--sdk_root</code> for each single command execution, let's deep dive into the real cause.</p> <p>Starting from <strong>Android SDK Command-line Tools 1.0.0 (6200805)</strong>, in contrast to <strong>Android SDK 26.1.1 (4333796)</strong>, the <code>tools</code> directory hierarchy has been changed. Previously it was placed right inside <code>ANDROID_HOME</code> (which is deprecated, we will use the term <code>ANDROID_SDK_ROOT</code> for the rest of the paragraph), now it's still named as <code>tools</code> (the only thing you'll get after unpacking the downloaded <em>commandlinetools</em> zip file), but differently, you have to place it inside a directory called <code>cmdline-tools</code> on your own. The name <code>cmdline-tools</code> comes from its package name, where you can get from listing packages command <code>sdkmanager --list</code>, whose outputs include <code>cmdline-tools;1.0 | 1.0 | Android SDK Command-line Tools</code>.</p> <p>Wrapping <code>tools</code> directory inside <code>cmdline-tools</code> directory would make it work, and help you get rid of the annoying <code>--sdk_root</code> argument. But what about the other parts?</p> <p>Well, that's all you have to change. Let me explain more.</p> <ul> <li>The king - <code>sdkmanager</code> lives inside <code>cmdline-tools/tools/bin</code>, you'd better set in <code>PATH</code> environment variable</li> <li><code>cmdline-tools</code> should not be set as <code>ANDROID_SDK_ROOT</code>. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under <code>ANDROID_SDK_ROOT</code>, but not under <code>cmdline-tools</code>.</li> <li>The final, complete <code>ANDROID_SDK_ROOT</code> directory structure should look like below, consist of quite a few sub-directories: <code>build-tools</code>, <code>cmdline-tools</code>, <code>emulator</code>, <code>licenses</code>, <code>patcher</code>, <code>platform-tools</code>, <code>platforms</code>, <code>system-images</code>. You can easily point out that <code>build-tools</code> and <code>cmdline-tools</code> are siblings, all sit inside the parent <code>ANDROID_SDK_ROOT</code>.</li> </ul> <p>Let me recap in a simple way:</p> <ul> <li>Set your preferred <code>ANDROID_SDK_ROOT</code> (just like before)</li> <li>Download and unpack the <em>commandlinetools</em> zip file into a directory called <code>cmdline-tools</code>, which is inside <code>ANDROID_SDK_ROOT</code></li> <li>Append the directory <code>$ANDROID_SDK_ROOT/cmdline-tools/tools/bin</code> to environment variable <code>PATH</code>, so that the system knows where to find <code>sdkmanager</code></li> </ul> <p><strong>!!UPDATE!!</strong></p> <p>The behavior has changed again since the build <code>6858069</code> (Android SDK Command-line Tools 3.0):</p> <ul> <li>After unzipping the package, the top-most directory you'll get is <code>cmdline-tools</code>.</li> <li>Rename the unpacked directory from <code>cmdline-tools</code> to <code>tools</code>, and place it under <code>$ANDROID_SDK_ROOT/cmdline-tools</code>, so now it should look like: <code>$ANDROID_SDK_ROOT/cmdline-tools/tools</code>. And inside it, you should have: <code>NOTICE.txt bin lib source.properties</code>. Actually according to the <a href="https://developer.android.com/studio/command-line#tools-sdk" rel="noreferrer">official Command-Line Tools doc</a>, the tree structure should be <code>android_sdk/cmdline-tools/version/bin/</code>, but I've checked, using <code>version</code> or <code>tools</code> makes no difference here.</li> <li>For your environment variable <code>PATH</code>, I would recommend you to set like this: <code>PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin</code>, because after update later, you'll get the latest <code>sdkmanager</code> placed under <code>$ANDROID_SDK_ROOT/cmdline-tools/latest/bin</code>, put it in front will make it higher priority.</li> </ul>
{ "question_id": 60440509, "question_date": "2020-02-27T19:32:08.060Z", "question_score": 208, "tags": "android|gitlab-ci|android-build|android-sdk-manager|android-studio-3.6", "answer_id": 61176718, "answer_date": "2020-04-12T19:06:45.223Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: React: "this" is undefined inside a component function <pre><code>class PlayerControls extends React.Component { constructor(props) { super(props) this.state = { loopActive: false, shuffleActive: false, } } render() { var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon" return ( &lt;div className="player-controls"&gt; &lt;FontAwesome className="player-control-icon" name='refresh' onClick={this.onToggleLoop} spin={this.state.loopActive} /&gt; &lt;FontAwesome className={shuffleClassName} name='random' onClick={this.onToggleShuffle} /&gt; &lt;/div&gt; ); } onToggleLoop(event) { // "this is undefined??" &lt;--- here this.setState({loopActive: !this.state.loopActive}) this.props.onToggleLoop() } </code></pre> <p>I want to update <code>loopActive</code> state on toggle, but <code>this</code> object is undefined in the handler. According to the tutorial doc, I <code>this</code> should refer to the component. Am I missing something?</p>
<p>ES6 <code>React.Component</code> doesn't auto bind methods to itself. You need to bind them yourself in <code>constructor</code>. Like this:</p> <pre><code>constructor (props){ super(props); this.state = { loopActive: false, shuffleActive: false, }; this.onToggleLoop = this.onToggleLoop.bind(this); } </code></pre>
{ "question_id": 33973648, "question_date": "2015-11-28T16:30:26.873Z", "question_score": 208, "tags": "javascript|reactjs|this", "answer_id": 33973758, "answer_date": "2015-11-28T16:40:35.730Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: How to set connection timeout with OkHttp <p>I am developing app using OkHttp library and my trouble is I cannot find how to set connection timeout and socket timeout.</p> <pre><code>OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); </code></pre>
<p>As of <strong>OkHttp3</strong> you can do this through the <a href="https://github.com/square/okhttp/blob/parent-3.0.0/okhttp/src/main/java/okhttp3/OkHttpClient.java#L386" rel="noreferrer">Builder</a> like so</p> <pre><code>client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); </code></pre> <p>You can also view the recipe <a href="https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java" rel="noreferrer">here</a>.</p> <p>For older versions, you simply have to do this</p> <pre><code>OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); </code></pre> <p>Be aware that value set in <code>setReadTimeout</code> is the one used in <code>setSoTimeout</code> on the <code>Socket</code> internally in the <code>OkHttp</code> <a href="https://github.com/square/okhttp/blob/parent-2.4.0/okhttp/src/main/java/com/squareup/okhttp/Connection.java#L300" rel="noreferrer"><code>Connection</code></a> class.</p> <p>Not setting any timeout on the <code>OkHttpClient</code> is the equivalent of setting a value of <code>0</code> on <code>setConnectTimeout</code> or <code>setReadTimeout</code> and will result in no timeout at all. Description can be found <a href="https://github.com/square/okhttp/blob/parent-2.4.0/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L247" rel="noreferrer">here</a>.</p> <p>As mentioned by @marceloquinta in the comments <code>setWriteTimeout</code> can also be set.</p> <p>As of version <code>2.5.0</code> read / write / connect timeout values are set to 10 seconds by default as mentioned by @ChristerNordvik. This can be seen <a href="https://github.com/square/okhttp/blob/parent-2.5.0/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L190" rel="noreferrer">here</a>.</p>
{ "question_id": 25953819, "question_date": "2014-09-20T22:16:06.583Z", "question_score": 208, "tags": "java|timeout|okhttp", "answer_id": 25973778, "answer_date": "2014-09-22T12:08:22.433Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: Visual Studio: How to break on handled exceptions? <p>I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).</p> <p>e.g. I want the debugger to break at the exception:</p> <pre><code>try { System.IO.File.Delete(someFilename); } catch (Exception) { //we really don't care at runtime if the file couldn't be deleted } </code></pre> <p>I came across <a href="http://www.syncfusion.com/faq/windowsforms/faq_c60c.aspx#q583q" rel="noreferrer">these</a> notes for Visual Studio.NET:</p> <blockquote> <p>1) In VS.NET go to the Debug Menu >> "Exceptions..." >> "Common Language Runtime Exceptions" >> "System" and select "System.NullReferenceException"</p> <p>2) In the bottom of that dialog there is a "When the exception is thrown:" group box, select "Break into the debugger" </p> <p>3) Run your scenario. When the exception is thrown, the debugger will stop and notify you with a dialog that says something like: "An exception of type "System.NullReferenceException" has been thrown. [Break] [Continue]" </p> <p>Hit [Break]. This will put you on the line of code that's causing the problem.</p> </blockquote> <p>But they do not apply to Visual Studio 2005 (there is no <strong>Exceptions</strong> option on the <strong>Debug</strong> menu).</p> <p>Does anyone know where the find this options dialog in Visual Studio that the "<em>When the exception is thrown</em>" group box, with the option to "<em>Break into the debugger</em>"?</p> <p><em>Update: The problem was that my <strong>Debug</strong> menu didn't have an <strong>Exceptions</strong> item. I customized the menu to manually add it.</em></p>
<p>With a solution open, go to the Debug - Windows - Exception Settings (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd>) menu option. From there you can choose to break on <em>Thrown</em> or <em>User-unhandled</em> exceptions.</p> <p>EDIT: My instance is set up with the C# &quot;profile&quot; perhaps it isn't there for other profiles?</p>
{ "question_id": 116896, "question_date": "2008-09-22T19:18:24.483Z", "question_score": 208, "tags": "visual-studio|exception|debugging", "answer_id": 116934, "answer_date": "2008-09-22T19:23:11.553Z", "answer_score": 197 }
Please answer the following Stack Overflow question: Title: How to build and use Google TensorFlow C++ api <p>I'm really eager to start using Google's new Tensorflow library in C++. The website and docs are just really unclear in terms of how to build the project's C++ API and I don't know where to start. </p> <p>Can someone with more experience help by discovering and sharing a guide to using tensorflow's C++ API? </p>
<p>One alternative to using Tensorflow C++ API I found is to use <a href="https://github.com/serizba/cppflow" rel="noreferrer">cppflow</a>. </p> <p>It's a lightweight C++ wrapper around <a href="https://www.tensorflow.org/install/lang_c" rel="noreferrer">Tensorflow C API</a>. You get very small executables and it links against the <code>libtensorflow.so</code> already compiled file. There are also examples of use and you use CMAKE instead of Bazel. </p>
{ "question_id": 33620794, "question_date": "2015-11-10T00:18:33.113Z", "question_score": 208, "tags": "c++|tensorflow", "answer_id": 62245422, "answer_date": "2020-06-07T12:36:42.607Z", "answer_score": 13 }
Please answer the following Stack Overflow question: Title: NSRange from Swift Range? <p><strong>Problem:</strong> NSAttributedString takes an NSRange while I'm using a Swift String that uses Range</p> <pre><code>let text = "Long paragraph saying something goes here!" let textRange = text.startIndex..&lt;text.endIndex let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -&gt; () in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) </code></pre> <p><strong>Produces the following error:</strong></p> <blockquote> <p>error: 'Range' is not convertible to 'NSRange' attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)</p> </blockquote>
<p>Swift <code>String</code> ranges and <code>NSString</code> ranges are not "compatible". For example, an emoji like counts as one Swift character, but as two <code>NSString</code> characters (a so-called UTF-16 surrogate pair).</p> <p>Therefore your suggested solution will produce unexpected results if the string contains such characters. Example:</p> <pre><code>let text = "Long paragraph saying!" let textRange = text.startIndex..&lt;text.endIndex let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -&gt; () in let start = distance(text.startIndex, substringRange.startIndex) let length = distance(substringRange.startIndex, substringRange.endIndex) let range = NSMakeRange(start, length) if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range) } }) println(attributedString) </code></pre> <p>Output:</p> <pre> Long paragra{ }ph say{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }ing!{ } </pre> <p>As you see, "ph say" has been marked with the attribute, not "saying".</p> <p>Since <code>NS(Mutable)AttributedString</code> ultimately requires an <code>NSString</code> and an <code>NSRange</code>, it is actually better to convert the given string to <code>NSString</code> first. Then the <code>substringRange</code> is an <code>NSRange</code> and you don't have to convert the ranges anymore:</p> <pre><code>let text = "Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: nsText) nsText.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -&gt; () in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) println(attributedString) </code></pre> <p>Output:</p> <pre> Long paragraph { }saying{ NSColor = "NSCalibratedRGBColorSpace 1 0 0 1"; }!{ } </pre> <p><strong>Update for Swift 2:</strong></p> <pre><code>let text = "Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: text) nsText.enumerateSubstringsInRange(textRange, options: .ByWords, usingBlock: { (substring, substringRange, _, _) in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange) } }) print(attributedString) </code></pre> <p><strong>Update for Swift 3:</strong></p> <pre><code>let text = "Long paragraph saying!" let nsText = text as NSString let textRange = NSMakeRange(0, nsText.length) let attributedString = NSMutableAttributedString(string: text) nsText.enumerateSubstrings(in: textRange, options: .byWords, using: { (substring, substringRange, _, _) in if (substring == "saying") { attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.red, range: substringRange) } }) print(attributedString) </code></pre> <p><strong>Update for Swift 4:</strong></p> <p>As of Swift 4 (Xcode 9), the Swift standard library provides method to convert between <code>Range&lt;String.Index&gt;</code> and <code>NSRange</code>. Converting to <code>NSString</code> is no longer necessary:</p> <pre><code>let text = "Long paragraph saying!" let attributedString = NSMutableAttributedString(string: text) text.enumerateSubstrings(in: text.startIndex..&lt;text.endIndex, options: .byWords) { (substring, substringRange, _, _) in if substring == "saying" { attributedString.addAttribute(.foregroundColor, value: NSColor.red, range: NSRange(substringRange, in: text)) } } print(attributedString) </code></pre> <p>Here <code>substringRange</code> is a <code>Range&lt;String.Index&gt;</code>, and that is converted to the corresponding <code>NSRange</code> with</p> <pre><code>NSRange(substringRange, in: text) </code></pre>
{ "question_id": 27040924, "question_date": "2014-11-20T13:33:16.393Z", "question_score": 208, "tags": "ios|macos|swift|nsrange", "answer_id": 27041376, "answer_date": "2014-11-20T13:58:18.227Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: Bash: infinite sleep (infinite blocking) <p>I use <code>startx</code> to start X which will evaluate my <code>.xinitrc</code>. In my <code>.xinitrc</code> I start my window manager using <code>/usr/bin/mywm</code>. Now, if I kill my WM (in order to f.e. test some other WM), X will terminate too because the <code>.xinitrc</code> script reached EOF. So I added this at the end of my <code>.xinitrc</code>:</p> <pre><code>while true; do sleep 10000; done </code></pre> <p>This way X won't terminate if I kill my WM. Now my question: how can I do an <strong>infinite sleep</strong> instead of looping sleep? Is there a command which will kinda like freeze the script?</p>
<p><code>sleep infinity</code> does exactly what it suggests and works without cat abuse.</p>
{ "question_id": 2935183, "question_date": "2010-05-29T13:12:14.017Z", "question_score": 208, "tags": "linux|bash|sleep|infinite", "answer_id": 22100106, "answer_date": "2014-02-28T16:07:57.027Z", "answer_score": 451 }
Please answer the following Stack Overflow question: Title: Flutter: Expanded vs Flexible <p>I've used both <code>Expanded</code> and <code>Flexible</code> widgets and they both seem to work the same.</p> <p>What is the difference between Expanded and Flexible?</p>
<pre><code>Scaffold( appBar: AppBar(), body: Column( children: &lt;Widget&gt;[ Row( children: &lt;Widget&gt;[ buildExpanded(), buildFlexible(), ], ), Row( children: &lt;Widget&gt;[ buildExpanded(), buildExpanded(), ], ), Row( children: &lt;Widget&gt;[ buildFlexible(), buildFlexible(), ], ), ], ), ); </code></pre> <p><a href="https://i.stack.imgur.com/bcv4n.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bcv4n.png" alt="enter image description here"></a></p>
{ "question_id": 52645944, "question_date": "2018-10-04T11:49:11.313Z", "question_score": 208, "tags": "flutter|dart|flutter-layout|flutter-widget", "answer_id": 52904214, "answer_date": "2018-10-20T09:28:46.167Z", "answer_score": 216 }
Please answer the following Stack Overflow question: Title: How do I select a random value from an enumeration? <p>Given an arbitrary enumeration in C#, how do I select a random value?</p> <p>(I did not find this very basic question on SO. I'll post my answer in a minute as reference for anyone, but please feel free to post your own answer.)</p>
<pre><code>Array values = Enum.GetValues(typeof(Bar)); Random random = new Random(); Bar randomBar = (Bar)values.GetValue(random.Next(values.Length)); </code></pre>
{ "question_id": 3132126, "question_date": "2010-06-28T11:59:28.967Z", "question_score": 208, "tags": "c#|random|enums", "answer_id": 3132151, "answer_date": "2010-06-28T12:03:26.913Z", "answer_score": 341 }
Please answer the following Stack Overflow question: Title: Is it possible to disable floating headers in UITableView with UITableViewStylePlain? <p>I'm using a <code>UITableView</code> to layout content 'pages'. I'm using the headers of the table view to layout certain images etc. and I'd prefer it if they didn't float but stayed static as they do when the style is set to <code>UITableViewStyleGrouped</code>.</p> <p>Other then using <code>UITableViewStyleGrouped</code>, is there a way to do this? I'd like to avoid using grouped as it adds a margin down all my cells and requires disabling of the background view for each of the cells. I'd like full control of my layout. Ideally they'd be a "UITableViewStyleBareBones", but I didn't see that option in the docs...</p> <p>Many thanks,</p>
<p>You should be able to fake this by using a custom cell to do your header rows. These will then scroll like any other cell in the table view.</p> <p>You just need to add some logic in your <code>cellForRowAtIndexPath</code> to return the right cell type when it is a header row. </p> <p>You'll probably have to manage your sections yourself though, i.e. have everything in one section and fake the headers. (You could also try returning a hidden view for the header view, but I don't know if that will work)</p>
{ "question_id": 1074006, "question_date": "2009-07-02T12:09:19.290Z", "question_score": 208, "tags": "ios|objective-c|iphone|cocoa-touch|uikit", "answer_id": 1074115, "answer_date": "2009-07-02T12:38:58.887Z", "answer_score": 26 }
Please answer the following Stack Overflow question: Title: Check if property has attribute <p>Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:</p> <pre><code> [IsNotNullable] [IsPK] [IsIdentity] [SequenceNameAttribute("Id")] public Int32 Id { get { return _Id; } set { _Id = value; } } </code></pre> <p>What is the fastest method to determine that for example it has the "IsIdentity" attribute?</p>
<p>There's no fast way to retrieve attributes. But code ought to look like this (credit to <a href="https://stackoverflow.com/users/38360/aaronaught">Aaronaught</a>):</p> <pre><code>var t = typeof(YourClass); var pi = t.GetProperty("Id"); var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity)); </code></pre> <p>If you need to retrieve attribute properties then</p> <pre><code>var t = typeof(YourClass); var pi = t.GetProperty("Id"); var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false); if (attr.Length &gt; 0) { // Use attr[0], you'll need foreach on attr if MultiUse is true } </code></pre>
{ "question_id": 2051065, "question_date": "2010-01-12T17:44:44.627Z", "question_score": 208, "tags": "c#|performance", "answer_id": 2051116, "answer_date": "2010-01-12T17:54:11.687Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: "unadd" a file to svn before commit <p>I was in the middle of doing a recursive svn add/commit, and a folder which did not have the proper ignore properties was included. I've got about 100 uploaded binary files versioned now, but I haven't committed yet.</p> <p>What is the easiest way to 'undo' this, without deleting all the documents?</p>
<p>Use <code>svn revert --recursive folder_name</code></p> <hr> <h1>Warning</h1> <blockquote> <p><code>svn revert</code> is inherently dangerous, since its entire purpose is to throw away data&nbsp;&mdash; namely, your uncommitted changes. Once you've reverted, Subversion provides <em>no way</em> to get back those uncommitted changes.</p> </blockquote> <p><a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html</a></p>
{ "question_id": 2906892, "question_date": "2010-05-25T17:25:01.860Z", "question_score": 208, "tags": "svn", "answer_id": 2906928, "answer_date": "2010-05-25T17:29:23.627Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: How to create abstract properties in python abstract classes <p>In the following code, I create a base abstract class <code>Base</code>. I want all the classes that inherit from <code>Base</code> to provide the <code>name</code> property, so I made this property an <code>@abstractmethod</code>.</p> <p>Then I created a subclass of <code>Base</code>, called <code>Base_1</code>, which is meant to supply some functionality, but still remain abstract. There is no <code>name</code> property in <code>Base_1</code>, but nevertheless python instatinates an object of that class without an error. How does one create abstract properties?</p> <pre><code>from abc import ABCMeta, abstractmethod class Base(object): __metaclass__ = ABCMeta def __init__(self, strDirConfig): self.strDirConfig = strDirConfig @abstractmethod def _doStuff(self, signals): pass @property @abstractmethod def name(self): # this property will be supplied by the inheriting classes # individually pass class Base_1(Base): __metaclass__ = ABCMeta # this class does not provide the name property, should raise an error def __init__(self, strDirConfig): super(Base_1, self).__init__(strDirConfig) def _doStuff(self, signals): print 'Base_1 does stuff' class C(Base_1): @property def name(self): return 'class C' if __name__ == '__main__': b1 = Base_1('abc') </code></pre>
<p>Since <a href="https://docs.python.org/3/whatsnew/3.3.html#abc" rel="noreferrer">Python 3.3</a> a bug was fixed meaning the <code>property()</code> decorator is now correctly identified as abstract when applied to an abstract method.</p> <p>Note: Order matters, you have to use <code>@property</code> above <code>@abstractmethod</code></p> <p><strong>Python 3.3+:</strong> (<a href="https://docs.python.org/3/library/abc.html#abc.abstractproperty" rel="noreferrer">python docs</a>):</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod class C(ABC): @property @abstractmethod def my_abstract_property(self): ... </code></pre> <p><strong>Python 2:</strong> (<a href="https://docs.python.org/2/library/abc.html#abc.abstractproperty" rel="noreferrer">python docs</a>)</p> <pre><code>from abc import ABC, abstractproperty class C(ABC): @abstractproperty def my_abstract_property(self): ... </code></pre>
{ "question_id": 5960337, "question_date": "2011-05-11T06:49:24.587Z", "question_score": 208, "tags": "python|properties|abstract-class|decorator", "answer_id": 48710068, "answer_date": "2018-02-09T16:23:09.947Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Good beginners tutorial to socket.io? <p>I am very new to the world of webdevelopment and jumped into the bandwagon because I find the concept of HTML5 very interesting. I am fairly confident on working with canvas and would now like to move over to websockets part of it. I have come to understand socket.io is by far the framework to work with, when we want to work with web sockets.</p> <p>Any pointers on what tutorial and examples to refer to for a total dummy would be very appreciated!</p>
<p>To start with <strong>Socket.IO</strong> I suggest you read first the example on the main page:</p> <p><a href="http://socket.io/" rel="nofollow noreferrer">http://socket.io/</a></p> <p>On the <strong>server side</strong>, read the &quot;How to use&quot; on the GitHub source page:</p> <p><a href="https://github.com/Automattic/socket.io" rel="nofollow noreferrer">https://github.com/Automattic/socket.io</a></p> <p>And on the <strong>client side</strong>:</p> <p><a href="https://github.com/Automattic/socket.io-client" rel="nofollow noreferrer">https://github.com/Automattic/socket.io-client</a></p> <p>Official tutorial <a href="https://socket.io/get-started/chat" rel="nofollow noreferrer">https://socket.io/get-started/chat</a></p>
{ "question_id": 4094350, "question_date": "2010-11-04T06:25:32.977Z", "question_score": 208, "tags": "javascript|node.js|html|websocket|socket.io", "answer_id": 4096690, "answer_date": "2010-11-04T12:36:33.937Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: How do I copy SQL Azure database to my local development server? <p>Does anyone know how I can copy a SQL Azure database to my development machine? I'd like to stop paying to have a development database in the cloud, but it's the best way to get production data. I copy my production database to a new development database but I'd like to have that same database local. </p> <p>Any suggestions? </p>
<p>There are multiple ways to do this:</p> <ol> <li><strong>Using SSIS (SQL Server Integration Services)</strong>. It only imports <code>data</code> in your table. Column properties, constraints, keys, indices, stored procedures, triggers, security settings, users, logons, etc. are not transferred. However it is very simple process and can be done simply by going through wizard in SQL Server Management Studio. </li> <li>Using combination of <strong>SSIS and DB creation scripts</strong>. This will get you data and all missing metadata that is not transferred by SSIS. This is also very simple. First transfer data using SSIS (see instructions below), then create DB Create script from SQL Azure database, and re-play it on your local database. </li> <li>Finally, you can use <strong>Import/Export service in SQL Azure</strong>. This transfers data (with a schema objects) to Azure Blob Storage as a BACPAC. You will need an Azure Storage account and do this in Azure web portal. It is as simple as pressing an "Export" button in the Azure web portal when you select the database you want to export. The downside is that it is only manual procedure, I don't know a way to automate this through tools or scripts -- at least the first part that requires a click on the web page.</li> </ol> <p>Manual procedure for <em>method #1</em> (using SSIS) is the following:</p> <ul> <li>In Sql Server Management Studio (SSMS) create new empty database on your local SQL instance.</li> <li>Choose Import Data from context menu (right click the database -> Tasks -> Import data...)</li> <li>Type in connection parameters for the source (SQL Azure). Select ".Net Framework Data Provider for SqlServer" as a provider.</li> <li>Choose existing empty local database as destination.</li> <li>Follow the wizard -- you will be able to select tables data you want to copy. You can choose to skip any of the tables you don't need. E.g. if you keep application logs in database, you probably don't need it in your backup. </li> </ul> <p>You can automate it by creating SSIS package and re-executing it any time you like to re-import the data. Note that you can only import using SSIS to a clean DB, you cannot do incremental updates to your local database once you already done it once. </p> <p><em>Method #2</em> (SSID data plus schema objects) is very simple. First go though a steps described above, then create DB Creation script (righ click on database in SSMS, choose Generate Scripts -> Database Create). Then re-play this script on your local database.</p> <p><em>Method #3</em> is described in the Blog here: <a href="http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/" rel="noreferrer">http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/</a>. There is a video clip with the process of transferring DB contents to Azure Blob storage as BACPAC. After that you can copy the file locally and import it to your SQL instance. Process of importing BACPAC to Data-Tier application is described here: <a href="http://msdn.microsoft.com/en-us/library/hh710052.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/hh710052.aspx</a>.</p>
{ "question_id": 5475306, "question_date": "2011-03-29T15:49:25.187Z", "question_score": 208, "tags": "sql-server|azure|azure-sql-database|database-migration", "answer_id": 5481143, "answer_date": "2011-03-30T02:11:50.803Z", "answer_score": 140 }
Please answer the following Stack Overflow question: Title: What does this "react-scripts eject" command do? <p>What does the <code>npm run eject</code> command do? I do understand what other commands do like start, build, test. But no idea about eject. </p>
<p>create-react-app encapsulates all of the npm modules it is using internally, so that your package.json will be very clean and simple without you having to worry about it.</p> <p>However, if you want to start doing more complex things and installing modules that may interact with modules create-react-app is using under the hood, those new modules need to know what is available and not, meaning you need to have create-react-app un-abstract them.</p> <p>That, in essence, is what <code>react-scripts eject</code> does. It will stop hiding what it's got installed under the hood and instead eject those things into your project's package.json for everyone to see.</p>
{ "question_id": 48308936, "question_date": "2018-01-17T19:52:10.030Z", "question_score": 208, "tags": "reactjs|webpack|create-react-app|react-scripts", "answer_id": 48309071, "answer_date": "2018-01-17T19:59:27.480Z", "answer_score": 264 }
Please answer the following Stack Overflow question: Title: How to set RecyclerView app:layoutManager="" from XML? <p>How to set <a href="http://developer.android.com/intl/zh-tw/reference/android/support/v7/widget/RecyclerView.html">RecyclerView</a> layoutManager from XML? </p> <pre><code> &lt;android.support.v7.widget.RecyclerView app:layoutManager="???" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; </code></pre>
<p>As you can check in the doc:</p> <blockquote> <p>Class name of the <strong><code>Layout Manager</code></strong> to be used.</p> <p>The class must extend <code>androidx.recyclerview.widget.RecyclerViewView$LayoutManager</code> and have either a default constructor or constructor with the signature <code>(android.content.Context, android.util.AttributeSet, int, int)</code></p> <p>If the name starts with a <code>'.'</code>, application package is prefixed. Else, if the name contains a <code>'.'</code>, the classname is assumed to be a full class name. Else, the recycler view package (<code>androidx.appcompat.widget</code>) is prefixed</p> </blockquote> <p>With <strong>androidx</strong> you can use:</p> <pre><code>&lt;androidx.recyclerview.widget.RecyclerView xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; app:layoutManager=&quot;androidx.recyclerview.widget.GridLayoutManager&quot;&gt; </code></pre> <p>With the <strong>support libraries</strong> you can use:</p> <pre><code>&lt;android.support.v7.widget.RecyclerView xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; app:layoutManager=&quot;android.support.v7.widget.GridLayoutManager&quot; &gt; </code></pre> <p>Also you can add these attributes:</p> <ul> <li><strong><code>android:orientation</code></strong> = <code>&quot;horizontal|vertical&quot;</code>: to control the orientation of the LayoutManager (eg:<code>LinearLayoutManager</code>)</li> <li><strong><code>app:spanCount</code></strong>: to set the number of columns for <code>GridLayoutManager</code></li> </ul> <p>Example:</p> <pre><code>&lt;androidx.recyclerview.widget.RecyclerView app:layoutManager=&quot;androidx.recyclerview.widget.GridLayoutManager&quot; app:spanCount=&quot;2&quot; ...&gt; </code></pre> <p>or:</p> <pre><code>&lt;androidx.recyclerview.widget.RecyclerView app:layoutManager=&quot;androidx.recyclerview.widget.LinearLayoutManager&quot; android:orientation=&quot;vertical&quot; ...&gt; </code></pre> <p>You can also add them using the <strong><code>tools</code></strong> namespace (i.e. <code>tools:orientation</code> and <code>tools:layoutManager</code>) and then it only impacts the IDE preview and you can continue setting those values in code.</p>
{ "question_id": 35679776, "question_date": "2016-02-28T07:07:11.390Z", "question_score": 208, "tags": "android|xml|android-recyclerview|androidx", "answer_id": 35680716, "answer_date": "2016-02-28T09:18:45.227Z", "answer_score": 346 }
Please answer the following Stack Overflow question: Title: What is wrong with using goto? <blockquote> <p><strong>Possible Duplicates:</strong><br> <a href="https://stackoverflow.com/questions/3444060/why-is-it-bad-to-use-goto">Why is it bad to use goto?</a><br> <a href="https://stackoverflow.com/questions/46586/goto-still-considered-harmful">GOTO still considered harmful?</a> </p> </blockquote> <p>I was ramdomming through xkcd and saw this one (if also read some negative texts about them some years ago):<br> <img src="https://imgs.xkcd.com/comics/goto.png" alt="your slow connection sucks, get a faster one to see this image"><br> What is actually wrong with it? Why are goto's even possible in C++ then?</p> <p>Why should I <strong>not</strong> use them?</p>
<p>Because they lead to <a href="http://en.wikipedia.org/wiki/Spaghetti_code" rel="noreferrer">spaghetti code</a>.</p> <p>In the past, programming languages didn't have while loops, if statements, etc., and programmers used goto to make up the logic of their programs. It lead to an unmaintainable mess.</p> <p>That's why the CS gods created methods, conditionals and loops. <a href="http://en.wikipedia.org/wiki/Structured_programming" rel="noreferrer">Structured</a> programming was a revolution at the time.</p> <p>gotos are appropriate in a few places, such as for jumping out of nested loops.</p>
{ "question_id": 3517726, "question_date": "2010-08-19T00:05:55.090Z", "question_score": 208, "tags": "c++|goto", "answer_id": 3517746, "answer_date": "2010-08-19T00:10:14.410Z", "answer_score": 156 }
Please answer the following Stack Overflow question: Title: How do cache lines work? <p>I understand that the processor brings data into the cache via cache lines, which - for instance, on my Atom processor - brings in about 64 bytes at a time, whatever the size of the actual data being read.</p> <p>My question is:</p> <p>Imagine that you need to read one byte from memory, which 64 bytes will be brought into the cache?</p> <p>The two possibilities I can see is that, either the 64 bytes start at the closest 64 bytes boundary below the byte of interest, or the 64 bytes are spread around the byte in some predetermined way (for instance, half under, half above, or all above).</p> <p>Which is it?</p>
<p>If the cache line containing the byte or word you're loading is not already present in the cache, your CPU will request the 64 bytes that begin at the cache line boundary (the largest address below the one you need that is multiple of 64).</p> <p>Modern PC memory modules transfer 64 bits (8 bytes) at a time, <a href="https://en.wikipedia.org/wiki/Synchronous_dynamic_random-access_memory#Commands" rel="noreferrer">in a burst of eight transfers</a>, so one command triggers a read or write of a full cache line from memory. (DDR1/2/3/4 SDRAM burst transfer size is configurable up to 64B; CPUs will select the burst transfer size to match their cache line size, but 64B is common)</p> <p>As a rule of thumb, if the processor can't forecast a memory access (and prefetch it), the retrieval process can take ~90 nanoseconds, or ~250 clock cycles (from the CPU knowing the address to the CPU receiving data).</p> <p>By contrast, a hit in L1 cache has a load-use latency of 3 or 4 cycles, and a store-reload has a store-forwarding latency of 4 or 5 cycles on modern x86 CPUs. Things are similar on other architectures.</p> <p>Further reading: Ulrich Drepper's <a href="http://www.akkadia.org/drepper/cpumemory.pdf" rel="noreferrer">What Every Programmer Should Know About Memory</a>. The software-prefetch advice is a bit outdated: modern HW prefetchers are smarter, and hyperthreading is way better than in P4 days (so a prefetch thread is typically a waste). Also, the <a href="/questions/tagged/x86" class="post-tag" title="show questions tagged &#39;x86&#39;" rel="tag">x86</a> tag wiki has lots of performance links for that architecture.</p>
{ "question_id": 3928995, "question_date": "2010-10-13T23:56:23.753Z", "question_score": 208, "tags": "memory|caching|line|processor", "answer_id": 3947435, "answer_date": "2010-10-16T02:32:55.070Z", "answer_score": 171 }
Please answer the following Stack Overflow question: Title: Golang tests in sub-directory <p>I want to create a package in Go with tests and examples for the package as subdirectories to keep the workspace cleaner. Is this possible and if so how? </p> <p>All the documentation always puts the testing code in the same place as the other code, is this better in some way or just convention?</p>
<p>Note that you <em>can</em> run <code>go test</code> &quot;recursively&quot;: you need to <strong>list all the packages you want to test</strong>.</p> <p>If you are in the root folder of your Go project, type:</p> <pre><code>go test ./... </code></pre> <p>The '<code>./...</code>' notation is described in the section &quot;<a href="http://golang.org/cmd/go/#hdr-Description_of_package_lists" rel="noreferrer">Description of package lists</a>&quot; of the &quot;<a href="http://golang.org/cmd/go/" rel="noreferrer">command <code>go</code></a>&quot;:</p> <blockquote> <p>An import path is a pattern if it includes one or more &quot;<code>...</code>&quot; wildcards, each of which can match any string, including the empty string and strings containing slashes.</p> <p>Such a pattern expands to all package directories found in the <code>GOPATH</code> trees with names matching the patterns.</p> <p>As a special case, <code>x/...</code> matches <code>x</code> as well as <code>x</code>'s subdirectories.<br /> For example, <code>net/...</code> expands to <code>net</code> and packages in its subdirectories.</p> </blockquote> <hr /> <p>If you keep your <code>_test.go</code> files in a subfolder, the '<code>go test ./...</code>' command will be able to pick them up.<br /> But:</p> <ul> <li>you will need to prefix your exported variables and functions (used in your tests) with the name of your package, in order for the test file to be able to access the package exported content.</li> <li>you wouldn't access non-exported content.</li> </ul> <p>That being said, I would still prefer keep the <code>_test.go</code> file right beside the main source file: it is easier to find.</p> <hr /> <p>For code coverage:</p> <pre><code>go test -coverpkg=./... ./... </code></pre> <p>See &quot;<a href="https://osinet.fr/go/en/articles/plotting-go-test-coverage/" rel="noreferrer">How to plot Go test coverage over time</a>&quot; from <a href="https://osinet.fr/a-propos" rel="noreferrer">Frédéric G. MARAND</a> and <a href="https://gitlab.com/fgmarand/gocoverstats" rel="noreferrer"><code>fgmarand/gocoverstats</code></a> to produce aggregate coverage statistics for CI integration of Go projects.</p> <p>Also <a href="https://go-cover-treemap.io/" rel="noreferrer"><code>go-cover-treemap.io</code></a> is fun.</p>
{ "question_id": 19200235, "question_date": "2013-10-05T16:50:04.317Z", "question_score": 208, "tags": "unit-testing|go|build", "answer_id": 21725603, "answer_date": "2014-02-12T10:43:55.013Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: How do you overcome the HTML form nesting limitation? <p>I know that XHTML doesn't support nested form tags and I have already read other answers here on Stack Overflow regarding this subject, but I still haven't figured out an elegant solution to the problem.</p> <p>Some say you don't need it and that they can't think of a scenario were this would be needed. Well, personally I can't think of a scenario that I <em>haven't</em> needed it.</p> <p>Let's see a very simple example:</p> <p>You are making a blog app and you have a form with some fields for creating a new post and a toolbar with "actions" like "Save", "Delete", "Cancel".</p> <pre><code>&lt;form action="/post/dispatch/too_bad_the_action_url_is_in_the_form_tag_even_though_conceptually_every_submit_button_inside_it_may_need_to_post_to_a_diffent_distinct_url" method="post"&gt; &lt;input type="text" name="foo" /&gt; &lt;!-- several of those here --&gt; &lt;div id="toolbar"&gt; &lt;input type="submit" name="save" value="Save" /&gt; &lt;input type="submit" name="delete" value="Delete" /&gt; &lt;a href="/home/index"&gt;Cancel&lt;/a&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Our objective is to write the form in a way that <em>doesn't require JavaScript</em>, just plain old HTML form and submit buttons.</p> <p>Since the action URL is defined in the Form tag and not in each individual submit button, our only option is to post to a generic URL and then start "if...then...else" to determine the name of the button that was submitted. Not very elegant, but our only choice, since we don't want to rely on JavaScript.</p> <p>The only problem is that pressing "Delete", will submit ALL the form fields on the server even though the only thing needed for this action is a Hidden input with the post-id. Not very big deal in this small example, but I have forms with hundreds (so to speak) of fields and tabs in my <a href="http://en.wikipedia.org/wiki/Line_of_business" rel="noreferrer">LOB</a> applications that (because of requirements) have to submit everything in one-go and in any case this seems very inefficient and a waste. If form nesting was supported, I would at least be able to wrap the "Delete" submit button inside it's own form with only the post-id field.</p> <p>You may say "Just implement the "Delete" as a link instead of submit". This would be wrong in so many levels, but most importantly because Side-effect actions like "Delete" here, should never be a GET request.</p> <p>So my question (particularly to those that say they haven't needed form nesting) is What do YOU do? Is there any elegant solution that I'm missing or the bottom line is really "Either require JavaScript or submit everything"?</p>
<p>I would implement this exactly as you described: submit everything to the server and do a simple if/else to check what button was clicked.</p> <p>And then I would implement a Javascript call tying into the form's onsubmit event which would check before the form was submitted, and only submit the relevant data to the server (possibly through a second form on the page with the ID needed to process the thing as a hidden input, or refresh the page location with the data you need passed as a GET request, or do an Ajax post to the server, or...).</p> <p>This way the people without Javascript are able to use the form just fine, but the server load is offset because the people who do have Javascript are only submitting the single piece of data needed. Getting yourself focused on only supporting one or the other really limits your options unnecessarily.</p> <p>Alternatively, if you're working behind a corporate firewall or something and everybody has Javascript disabled, you might want to do two forms and work some CSS magic to make it look like the delete button is part of the first form.</p>
{ "question_id": 597596, "question_date": "2009-02-28T06:01:35.270Z", "question_score": 208, "tags": "html|forms|nested", "answer_id": 597627, "answer_date": "2009-02-28T06:24:03.703Z", "answer_score": 55 }
Please answer the following Stack Overflow question: Title: Building a minimal plugin architecture in Python <p>I have an application, written in Python, which is used by a fairly technical audience (scientists). </p> <p>I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. </p> <p>I am looking for something <strong>extremely lightweight</strong>. Most scripts, or plugins, are not going to be developed and distributed by a third-party and installed, but are going to be something whipped up by a user in a few minutes to automate a repeating task, add support for a file format, etc. So plugins should have the absolute minimum boilerplate code, and require no 'installation' other than copying to a folder (so something like setuptools entry points, or the Zope plugin architecture seems like too much.)</p> <p>Are there any systems like this already out there, or any projects that implement a similar scheme that I should look at for ideas / inspiration?</p>
<p>Mine is, basically, a directory called "plugins" which the main app can poll and then use <a href="https://docs.python.org/library/imp.html#imp.load_module" rel="noreferrer">imp.load_module</a> to pick up files, look for a well-known entry point possibly with module-level config params, and go from there. I use file-monitoring stuff for a certain amount of dynamism in which plugins are active, but that's a nice-to-have.</p> <p>Of course, any requirement that comes along saying "I don't need [big, complicated thing] X; I just want something lightweight" runs the risk of re-implementing X one discovered requirement at a time. But that's not to say you can't have some fun doing it anyway :)</p>
{ "question_id": 932069, "question_date": "2009-05-31T13:46:41.670Z", "question_score": 208, "tags": "python|architecture|plugins", "answer_id": 932072, "answer_date": "2009-05-31T13:51:05.453Z", "answer_score": 159 }
Please answer the following Stack Overflow question: Title: How to get min/max of two integers in Postgres/SQL? <p>How do I find the maximum (or minimum) of two integers in Postgres/SQL? One of the integers is not a column value.</p> <p>I will give an example scenario:</p> <p>I would like to subtract an integer from a column (in all rows), but the result should not be less than zero. So, to begin with, I have:</p> <pre><code>UPDATE my_table SET my_column = my_column - 10; </code></pre> <p>But this can make some of the values negative. What I would like (in pseudo code) is:</p> <pre><code>UPDATE my_table SET my_column = MAXIMUM(my_column - 10, 0); </code></pre>
<p>Have a look at <a href="http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-GREATEST-LEAST" rel="noreferrer">GREATEST and LEAST</a>.</p> <pre><code>UPDATE my_table SET my_column = GREATEST(my_column - 10, 0); </code></pre>
{ "question_id": 2936348, "question_date": "2010-05-29T19:38:21.710Z", "question_score": 208, "tags": "postgresql", "answer_id": 2936364, "answer_date": "2010-05-29T19:42:03.897Z", "answer_score": 422 }
Please answer the following Stack Overflow question: Title: What are some popular naming conventions for Unit Tests? <h2>General</h2> <ul> <li>Follow the same standards for all tests.</li> <li>Be clear about what each test state is.</li> <li>Be specific about the expected behavior.</li> </ul> <h2>Examples</h2> <p>1) MethodName_StateUnderTest_ExpectedBehavior</p> <pre><code>Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () Public void Sum_simpleValues_Calculated () </code></pre> <p>Source: <a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html" rel="noreferrer">Naming standards for Unit Tests</a></p> <p>2) Separating Each Word By Underscore</p> <pre><code>Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () Public void Sum_Simple_Values_Calculated () </code></pre> <h2>Other</h2> <ul> <li>End method names with <em>Test</em></li> <li>Start method names with class name</li> </ul>
<p>I am pretty much with you on this one man. The naming conventions you have used are:</p> <ul> <li>Clear about what each test state is.</li> <li>Specific about the expected behaviour.</li> </ul> <p>What more do you need from a test name?</p> <p>Contrary to <a href="https://stackoverflow.com/questions/96297/naming-conventions-for-unit-tests#96476">Ray's answer</a> I don't think the <em>Test</em> prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, <strong>your test code should not be mixed up with your production code.</strong></p> <p>As for length and use of underscore, its <strong>test code</strong>, who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :)</p> <p>That said, I am still quite new to testing and <a href="http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-started-with-test-driven.html" rel="noreferrer">blogging my adventures with it</a> :)</p>
{ "question_id": 96297, "question_date": "2008-09-18T19:59:56.237Z", "question_score": 208, "tags": "unit-testing|naming-conventions", "answer_id": 96602, "answer_date": "2008-09-18T20:32:48.137Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: How do I speed up the gwt compiler? <p>We're starting to make heavier use of GWT in our projects, and the performance of the GWT compiler is becoming increasingly annoying. </p> <p>We're going to start altering our working practices to mitigate the problem, including a greater emphasis on the hosted-mode browser, which defers the need to run the GWT compiler until a later time, but that brings its own risks, particularly that of not catching issues with real browsers until much later than we'd like.</p> <p>Ideally, we'd like to make the GWT compiler itself quicker - a minute to compile a fairly small application is taking the piss. However, we are using the compile if a fairly naive fashion, so I'm hoping we can make some quick and easy gains.</p> <p>We're currently invoking com.google.gwt.dev.Compiler as a java application from ant Ant target, with 256m max heap and lots of stack space. The compiler is launched by Ant using fork=true and the latest Java 6 JRE, to try and take advantage of Java6's improved performance. We pass our main controller class to the compiler along with the application classpath, and off it goes.</p> <p>What else can we do to get some extra speed? Can we give it more information so it spends less time doing discovery of what to do?</p> <p>I know we can tell it to only compile for one browser, but we need to do multi-browser testing, so that's not really practical.</p> <p>All suggestions welcome at this point.</p>
<p>Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.</p> <p>A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your <code>gwt.xml</code>:</p> <pre><code>&lt;define-property name="user.agent" values="ie6,gecko,gecko1_8"&gt;&lt;/define-property&gt; </code></pre> <p>or in gwt 2.x syntax, and for one browser only:</p> <pre><code>&lt;set-property name="user.agent" value="gecko1_8"/&gt; </code></pre> <p>This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.</p> <p>Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.</p> <p>Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.</p>
{ "question_id": 1011863, "question_date": "2009-06-18T09:56:45.317Z", "question_score": 208, "tags": "java|performance|gwt", "answer_id": 1011877, "answer_date": "2009-06-18T10:01:41.623Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: How to make the hardware beep sound in Mac OS X 10.6 <p>I just want that Mac OS X 10.6 does a hardware beep sound like in open suse and other distributions. I tried following approaches</p> <p>Terminal -> beep = -bash: beep: command not found</p> <p>Terminal -> say beep = voice speaks out beep (Not a Hardware beep but awesome ;) )</p> <p>applescript -> beep = Macintosh bell (I want a Hardware beep!)</p> <p>Does anybody know how to make the Hardware beep in bin/bash or applescript?</p>
<p>There is no "hardware beep" in macOS.</p> <p>The functionality you're thinking of is an artifact of very old (pre-1990s) IBM PC-compatible hardware. Before most computers had sound cards, most machines had a small speaker or piezo buzzer connected to one of the channels of a timer chip. This could be used to generate simple tones or beeps. Even after many computers integrated sound cards, it remained common for quite some time for computers to route this output to a separate internal speaker. More recently, many computers, especially laptops, have integrated this functionality into the onboard sound card.</p> <p>(If you're curious about the technical details of how the PC speaker interface worked, <a href="https://courses.engr.illinois.edu/ece390/books/labmanual/io-devices-speaker.html" rel="noreferrer">there are more details here</a>.)</p> <p>This hardware has never existed in Apple computers. The only audio output available is through the sound card, and the only system beep in macOS is the user's alert sound.</p>
{ "question_id": 3127977, "question_date": "2010-06-27T16:28:43.227Z", "question_score": 208, "tags": "bash|macos|applescript|beep", "answer_id": 44056637, "answer_date": "2017-05-18T19:49:50.847Z", "answer_score": 30 }
Please answer the following Stack Overflow question: Title: Why should I use Amazon Kinesis and not SNS-SQS? <p>I have a use case where there will be stream of data coming and I cannot consume it at the same pace and need a buffer. This can be solved using an SNS-SQS queue. I came to know the Kinesis solves the same purpose, so what is the difference? Why should I prefer (or should not prefer) Kinesis? </p>
<p>On the surface they are vaguely similar, but your use case will determine which tool is appropriate. IMO, if you can get by with SQS then you should - if it will do what you want, it will be simpler and cheaper, but here is a better explanation from the AWS FAQ which gives examples of appropriate use-cases for both tools to help you decide:</p> <p><a href="http://aws.amazon.com/kinesis/faqs/">FAQ's</a></p>
{ "question_id": 26623673, "question_date": "2014-10-29T06:01:32.827Z", "question_score": 208, "tags": "amazon-web-services|amazon-sqs|amazon-kinesis", "answer_id": 26626820, "answer_date": "2014-10-29T09:34:29.553Z", "answer_score": 62 }
Please answer the following Stack Overflow question: Title: WPF and initial focus <p>It seems that when a WPF application starts, nothing has focus.</p> <p>This is really weird. Every other framework I've used does just what you'd expect: puts initial focus on the first control in the tab order. But I've confirmed that it's WPF, not just my app -- if I create a new Window, and just put a TextBox in it, and run the app, the TextBox doesn't have focus until I click on it or press Tab. Yuck.</p> <p>My actual app is more complicated than just a TextBox. I have several layers of UserControls within UserControls. One of those UserControls has Focusable="True" and KeyDown/KeyUp handlers, and I want it to have the focus as soon as my window opens. I'm still somewhat of a WPF novice, though, and I'm not having much luck figuring out how to do this.</p> <p>If I start my app and press the Tab key, then focus goes to my focusable control, and it starts working the way I want. But I don't want my users to have to hit Tab before they can start using the window.</p> <p>I've played around with FocusManager.FocusedElement, but I'm not sure which control to set it on (the top-level Window? the parent that contains the focusable control? the focusable control itself?) or what to set it to.</p> <p>What do I need to do to get my deeply-nested control to have initial focus as soon as the window opens? Or better yet, to focus the first focusable control in the tab order?</p>
<p>I had the bright idea to dig through Reflector to see where the Focusable property is used, and found my way to this solution. I just need to add the following code to my Window's constructor:</p> <pre><code>Loaded += (sender, e) =&gt; MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); </code></pre> <p>This will automatically select the first control in the tab order, so it's a general solution that should be able to be dropped into any window and Just Work.</p>
{ "question_id": 817610, "question_date": "2009-05-03T17:59:08.847Z", "question_score": 208, "tags": "wpf|focus", "answer_id": 818536, "answer_date": "2009-05-04T01:46:22.610Z", "answer_score": 172 }
Please answer the following Stack Overflow question: Title: Brew update failed: untracked working tree files would be overwritten by merge <p>Trying to update Homebrew with <code>brew update</code> I got the following error</p> <pre><code>error: The following untracked working tree files would be overwrittenby merge: Library/Formula/argp-standalone.rb Library/Formula/cocot.rb Please move or remove them before you can merge. Aborting Updating e088818..5909e2c Error: Failed while executing git pull origin refs/heads/master:refs/remotes/origin/master </code></pre> <p>I found a blog post by someone who experienced a similar problem after having installed Mountain Lion (which I did this week too). He explains how he removed the files referred to in the error message</p> <pre><code>I removed these files: $ cd $(brew --prefix) $ rm cocot.rb However, removing these files didn't help with the brew update. Instead I had to manually update brew through git: $ cd $(brew --prefix) $ git fetch origin $ git reset --hard origin/master $ brew update Already up-to-date. </code></pre> <p>Assuming those instructions are correct (which I maybe shouldn't assume), I tried to follow these instructions and do </p> <pre><code> $ cd $(brew --prefix) $ rm cocot.rb </code></pre> <p>However, it said 'file doesn't exist' when I tried to rm cocot.rb</p> <p>One thing I'm not sure about is the <code>cd $(brew --prefix)</code> Are those the exact words I type or do I have to replace prefix with something? the cd was successful, so I'm assuming it was correct -- it moved me into /usr/local, but there was no file to remove. Contents of /usr/local are</p> <pre><code>Cellar clamXav git mysql var Library doc heroku mysql-5.5.15-osx10.6-x86_64 README.md etc include rvm bin foreman lib share </code></pre> <p>At any rate, do you know how I can fix the 'brew update'</p> <p>Update: After removing the files according to favoretti's instructions and trying <code>chown -R &lt;your_username&gt; $(brew --prefix)/.git</code>, I got the following error running <code>brew update</code></p> <pre><code>error: The following untracked working tree files would be overwritten by merge: Library/Aliases/gperftools Library/Aliases/hashdeep Library/Aliases/htop Library/Aliases/nodejs Library/Aliases/ocio Library/Aliases/oiio Library/Aliases/pgrep Library/Aliases/pkill Library/Aliases/qt4 Library/Aliases/twolame Library/Aliases/wxwidgets Library/Contributions/cmds/brew-aspell-dictionaries Library/Contributions/cmds/brew-beer.rb Library/Contributions/cmds/brew-dirty.rb Library/Contributions/cmds/brew-graph Library/Contributions/cmds/brew-grep Library/Contributions/cmds/brew-leaves.rb Library/Contributions/cmds/brew-linkapps.rb Library/Contributions/cmds/brew-ls-taps.rb Library/Contributions/cmds/brew-man Library/Contributions/cmds/brew-md5-to-sha1 Library/Contributions/cmds/brew-mirror-check.rb Library/Contributions/cmds/brew-pull.rb Library/Contributions/cmds/brew-readall.rb Library/Contributions/cmds/brew-server Library/Contributions/cmds/brew-services.rb Library/Contributions/cmds/brew-switch.rb Library/Contributions/cmds/brew-test-bot.rb Library/Contributions/cmds/brew-tests.rb Library/Contributions/cmds/brew-unpack.rb Library/Contributions/cmds/brew-which.rb Library/Contributions/cmds/git Library/Contributions/cmds/svn Library/ENV/4.3/apr-1-config Library/ENV/4.3/bsdmake Library/ENV/4.3/c++ Library/ENV/4.3/c89 Library/ENV/4.3/c99 Library/ENV/4.3/cc Library/ENV/4.3/clang Library/ENV/4.3/clang++ Library/ENV/4.3/cpp Library/ENV/4.3/g++ Library/ENV/4.3/gcc Library/ENV/4.3/git Library/ENV/4.3/i686-apple-darwin11-llvm-g++-4.2 Library/ENV/4.3/i686-apple-darwin11-llvm-gcc-4.2 Library/ENV/4.3/ld Library/ENV/4.3/llvm-g++ Library/ENV/4.3/llvm-g++-4.2 Library/ENV/4.3/llvm-gcc Library/ENV/4.3/llvm-gcc-4.2 Library/ENV/4.3/make Library/ENV/4.3/mig Library/ENV/4.3/sed Library/ENV/4.3/svn Library/ENV/4.3/xcrun Library/ENV/libsuperenv.rb Library/ENV/pkgconfig/leopard/libcrypto.pc Library/ENV/pkgconfig/leopard/libcurl.pc Library/ENV/pkgconfig/mountain_lion/libcurl.pc Library/ENV/pkgconfig/mountain_lion/libexslt.pc Library/ENV/pkgconfig/mountain_lion/libxml-2.0.pc Library/ENV/pkgconfig/mountain_lion/libxslt.pc Library/Formula/abcl.rb Library/Formula/abcmidi.rb Library/Formula/aiccu.rb Library/Formula/akka.rb Library/Formula/alac.rb Library/Formula/alure.rb Library/Formula/appledoc.rb Library/Formula/arangodb.rb Library/Formula/argp-standalone.rb Library/Formula/argtable.rb Library/Formula/autopano-sift-c.rb Library/Formula/avian.rb Library/Formula/avidemux.rb Library/Formula/avro-cpp.rb Library/Formula/aws-cloudsearch.rb Library/Formula/aws-sns-cli.rb Library/Formula/backupninja.rb Library/Formula/bact.rb Library/Formula/bam.rb Library/Formula/basex.rb Library/Formula/berkeley-db4.rb Library/Formula/bind.rb Library/Formula/blazeblogger.rb Library/Formula/bochs.rb Library/Formula/boost149.rb Library/Formula/bsdconv.rb Library/Formula/bsdmake.rb Library/Formula/buildapp.rb Library/Formula/bup.rb Library/Formula/byacc.rb Library/Formula/cadubi.rb Library/Formula/camellia.rb Library/Formula/casperjs.rb Library/Formula/ccextractor.rb Library/Formula/cconv.rb Library/Formula/cdo.rb Library/Formula/cdpr.rb Library/Formula/cgvg.rb Library/Formula/checkstyle.rb Library/Formula/chordii.rb Library/Formula/chruby.rb Library/Formula/cifer.rb Library/Formula/clhep.rb Library/Formula/cntlm.rb Library/Formula/cocot.rb Library/Formula/cogl.rb Library/Formula/collada-dom.rb Library/Formula/crash.rb Library/Formula/crossroads.rb Library/Formula/crosstool-ng.rb Library/Formula/css-crush.rb Library/Formula/csync.rb Library/Formula/ctemplate.rb Library/Formula/curlftpfs.rb Library/Formula/cutter.rb Library/Formula/cvsutils.rb Library/Formula/darkstat.rb Library/Formula/darner.rb Library/Formula/dart.rb Library/Formula/dasm.rb Library/Formula/debianutils.rb Library/Formula/dfc.rb Library/Formula/dgtal.rb Library/Formula/dhcping.rb Library/Formula/di.rb Library/Formula/dmtx-utils.rb Library/Formula/drip.rb Library/Formula/dsniff.rb Library/Fo Aborting Updating e088818..c1fbc29 Error: Failed while executing git pull origin refs/heads/master:refs/remotes/origin/master </code></pre>
<pre><code>cd $(brew --prefix) git reset --hard HEAD brew update </code></pre>
{ "question_id": 14113427, "question_date": "2013-01-01T19:19:03.380Z", "question_score": 208, "tags": "homebrew", "answer_id": 15395445, "answer_date": "2013-03-13T20:08:40.970Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: Is it possible for intellij to organize imports the same way as in Eclipse? <p>I'm working on a project where all the team members are using Eclipse and I'm the only IDEA user. This creates a lot of noise from imports rearrangements. The order in which eclipse imports is: Java, Javax, Org, Com, everything else in alphabetical order. Is it possible to configure IDEA to follow these rules?</p>
<p>Some more details: I ended up performing these steps to match out of the box eclipse organizing:</p> <p>(in <code>Settings</code> &gt; <code>Editor</code> &gt; <code>Code Style</code> &gt; <code>Java</code> &gt; <code>imports</code>, as mentioned by @yole)</p> <ul> <li><p>set &quot;class count to use import with '*'&quot; to 99 (seems like you cannot turn this off)</p> </li> <li><p>set this ordering for <code>Import Layout</code> (like eclipse defaults):</p> <pre><code> static all other, blank, java.*, blank, javax.*, blank, org.*, blank, com.*, blank, all other imports </code></pre> </li> </ul> <p>FWIW, there is an Intellij plugin called &quot;<a href="https://code.google.com/p/eclipse-code-formatter-intellij-plugin/wiki/HowTo" rel="noreferrer">eclipse code formatter</a>&quot; that I evaluated for this purpose and ended up discarding, because it set up a separate shortcut (in OSX) that was already in use by core IDE functionality.</p>
{ "question_id": 14716283, "question_date": "2013-02-05T20:26:59.990Z", "question_score": 208, "tags": "intellij-idea", "answer_id": 17194980, "answer_date": "2013-06-19T15:15:17.137Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: What is data oriented design? <p>I was reading <a href="http://gamesfromwithin.com/data-oriented-design" rel="noreferrer">this article</a>, and this guy goes on talking about how everyone can greatly benefit from mixing in data oriented design with OOP. He doesn't show any code samples, however.</p> <p>I googled this and couldn't find any real information as to what this is, let alone any code samples. Is anyone familiar with this term and can provide an example? Is this maybe a different word for something else?</p>
<p>First of all, don't confuse this with data-driven design.</p> <p>My understanding of Data-Oriented Design is that it is about organizing your data for efficient processing. Especially with respect to cache misses etc. Data-Driven Design on the other hand is about letting data control a lot of the behavior of your program (described very well by <a href="https://stackoverflow.com/questions/1641580/what-is-data-oriented-design/1641615#1641615">Andrew Keith's answer</a>).</p> <p>Say you have ball objects in your application with properties such as color, radius, bounciness, position, etc.</p> <h3 id="object-oriented-approach-beay">Object Oriented Approach</h3> <p>In OOP you would describe balls like this:</p> <pre class="lang-cpp prettyprint-override"><code>class Ball { Point position; Color color; double radius; void draw(); }; </code></pre> <p>And then you would create a collection of balls like this:</p> <pre class="lang-cpp prettyprint-override"><code>vector&lt;Ball&gt; balls; </code></pre> <h3 id="data-oriented-approach-jbux">Data-Oriented Approach</h3> <p>In Data Oriented Design, however, you are more likely to write the code like this:</p> <pre class="lang-cpp prettyprint-override"><code>class Balls { vector&lt;Point&gt; position; vector&lt;Color&gt; color; vector&lt;double&gt; radius; void draw(); }; </code></pre> <p>As you can see there is no single unit representing one Ball anymore. Ball objects only exist implicitly.</p> <p>This can have many advantages, performance-wise. Usually, we want to do operations on many balls at the same time. The hardware usually wants large contiguous chunks of memory to operate efficiently.</p> <p>Secondly, you might do operations that affect only part of the properties of a ball. For E.g. if you combine the colors of all the balls in various ways, then you want your cache to only contain color information. However, when all ball properties are stored in one unit you will pull in all the other properties of a ball as well. Even though you don't need them.</p> <h3 id="cache-usage-example-k8ek">Cache Usage Example</h3> <p>Say each ball takes up 64 bytes and a Point takes 4 bytes. A cache slot takes, say, 64 bytes as well. If I want to update the position of 10 balls, I have to pull in 10 x 64 = 640 bytes of memory into cache and get 10 cache misses. If however, I can work the positions of the balls as separate units, that will only take 4 x 10 = 40 bytes. That fits in one cache fetch. Thus we only get 1 cache miss to update all the 10 balls. These numbers are arbitrary - I assume a cache block is bigger.</p> <p>But it illustrates how memory layout can have a severe effect on cache hits and thus performance. This will only increase in importance as the difference between CPU and RAM speed widens.</p> <h3 id="how-to-layout-the-memory-qg4l">How to layout the memory</h3> <p>In my ball example, I simplified the issue a lot, because usually for any normal app you will likely access multiple variables together. E.g. position and radius will probably be used together frequently. Then your structure should be:</p> <pre class="lang-cpp prettyprint-override"><code>class Body { Point position; double radius; }; class Balls { vector&lt;Body&gt; bodies; vector&lt;Color&gt; color; void draw(); }; </code></pre> <p>The reason you should do this is that if data used together are placed in separate arrays, there is a risk that they will compete for the same slots in the cache. Thus loading one will throw out the other.</p> <p>So compared to Object-Oriented programming, the classes you end up making are not related to the entities in your mental model of the problem. Since data is lumped together based on data usage, you won't always have sensible names to give your classes in Data-Oriented Design.</p> <h3 id="relation-to-relational-databases-bzcd">Relation to relational databases</h3> <p>The thinking behind Data-Oriented Design is very similar to how you think about relational databases. Optimizing a relational database can also involve using the cache more efficiently, although in this case, the cache is not CPU cache but pages in memory. A good database designer will also likely split out infrequently accessed data into a separate table rather than creating a table with a huge number of columns where only a few of the columns are ever used. He might also choose to denormalize some of the tables so that data don't have to be accessed from multiple locations on disk. Just like with Data-Oriented Design these choices are made by looking at what the data access patterns are and where the performance bottleneck is.</p>
{ "question_id": 1641580, "question_date": "2009-10-29T04:13:33.353Z", "question_score": 208, "tags": "data-oriented-design", "answer_id": 2021868, "answer_date": "2010-01-07T16:29:54.120Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: Spring Boot - parent pom when you already have a parent pom <p>Is there a specific recommended approach to the inclusion of the spring-boot parent pom into projects that already have a required parent POM?</p> <p>What do you recommend for projects that need to extend from an organizational parent (this is extremely common and even something many/most projects published to Maven central depending on the feeder repos they come from). Most of the build stuff is related to creating executable JARs (e.g. running embedded Tomcat/Jetty). There are ways to structure things so that you can get all the dependencies without extending from a parent (similar to composition vs. inheritance). You can't get a build stuff that way though.</p> <p>So is it preferable to include all of the spring-boot parent pom inside of the required parent POM or to simply have a POM dependency within the project POM file.</p> <p>Other options?</p> <p>TIA,</p> <p>Scott</p>
<p><strong>You can use the spring-boot-starter-parent like a "bom"</strong> (c.f. <a href="https://spring.io/blog/2013/12/03/spring-framework-4-0-rc2-available" rel="noreferrer">Spring</a> and Jersey other projects that support this feature now), and include it only in the dependency management section with scope=import.That way you get a lot of the benefits of using it (i.e. dependency management) without replacing the settings in your actual parent.</p> <p>The 2 main other things it does are</p> <ol> <li>define a load of properties for quickly setting versions of dependencies that you want to override</li> <li>configure some plugins with default configuration (principally the Spring Boot maven plugin). So those are the things you will have to do manually if you use your own parent.</li> </ol> <p>Example provided in <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-maven-without-a-parent" rel="noreferrer">Spring Boot documentation</a>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;!-- Import dependency management from Spring Boot --&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt; &lt;version&gt;2.1.3.RELEASE&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; </code></pre>
{ "question_id": 21317006, "question_date": "2014-01-23T18:56:16.810Z", "question_score": 208, "tags": "maven|spring-boot|parent-pom", "answer_id": 21318359, "answer_date": "2014-01-23T20:12:16Z", "answer_score": 194 }
Please answer the following Stack Overflow question: Title: Is SQL or even TSQL Turing Complete? <p>This came up at the office today. I have no plans of doing such a thing, but theoretically could you write a compiler in SQL? At first glance it appears to me to be turing complete, though extremely cumbersome for many classes of problems. </p> <p>If it is not turing complete, what would it require to become so?</p> <p>Note: I have no desire to do anything like write a compiler in SQL, I know it would be a silly thing to do, so if we can avoid that discussion I would appreciate it.</p>
<p>It turns out that SQL can be Turing Complete even without a true 'scripting' extension such as PL/SQL or PSM (which are designed to be true programming languages, so that's kinda cheating).</p> <p>In <a href="http://assets.en.oreilly.com/1/event/27/High%20Performance%20SQL%20with%20PostgreSQL%20Presentation.pdf" rel="noreferrer">this set of slides</a> Andrew Gierth proves that with CTE and Windowing SQL is Turing Complete, by constructing a <a href="http://mathworld.wolfram.com/CyclicTagSystem.html" rel="noreferrer">cyclic tag system</a>, which has been proved to be Turing Complete. The CTE feature is the important part however -- it allows you to create named sub-expressions that can refer to themselves, and thereby recursively solve problems.</p> <p>The interesting thing to note is that CTE was not really added to turn SQL into a programming language -- just to turn a declarative querying language into a more powerful declarative querying language. Sort of like in C++, whose templates turned out to be Turing complete even though they weren't intended to create a meta programming language.</p> <p>Oh, the <a href="http://wiki.postgresql.org/wiki/Mandelbrot_set" rel="noreferrer">Mandelbrot set in SQL</a> example is very impressive, as well :)</p>
{ "question_id": 900055, "question_date": "2009-05-22T21:21:37.927Z", "question_score": 208, "tags": "sql|tsql|programming-languages|language-features", "answer_id": 7580013, "answer_date": "2011-09-28T07:59:35.277Z", "answer_score": 251 }
Please answer the following Stack Overflow question: Title: How are multi-dimensional arrays formatted in memory? <p>In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code:</p> <pre><code>int** someNumbers = malloc(arrayRows*sizeof(int*)); for (i = 0; i &lt; arrayRows; i++) { someNumbers[i] = malloc(arrayColumns*sizeof(int)); } </code></pre> <p>Clearly, this actually creates a one-dimensional array of pointers to a bunch of separate one-dimensional arrays of integers, and "The System" can figure out what I mean when I ask for:</p> <pre><code>someNumbers[4][2]; </code></pre> <p>But when I statically declare a 2D array, as in the following line...:</p> <pre><code>int someNumbers[ARRAY_ROWS][ARRAY_COLUMNS]; </code></pre> <p>...does a similar structure get created on the stack, or is it of another form completely? (i.e. is it a 1D array of pointers? If not, what is it, and how do references to it get figured out?)</p> <p>Also, when I said, "The System," what is actually responsible for figuring that out? The kernel? Or does the C compiler sort it out while compiling?</p>
<p>A static two-dimensional array looks like an array of arrays - it's just laid out contiguously in memory. Arrays are not the same thing as pointers, but because you can often use them pretty much interchangeably it can get confusing sometimes. The compiler keeps track properly, though, which makes everything line up nicely. You do have to be careful with static 2D arrays like you mention, since if you try to pass one to a function taking an <code>int **</code> parameter, bad things are going to happen. Here's a quick example:</p> <pre><code>int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}}; </code></pre> <p>In memory looks like this:</p> <pre><code>0 1 2 3 4 5 </code></pre> <p><strong>exactly</strong> the same as:</p> <pre><code>int array2[6] = { 0, 1, 2, 3, 4, 5 }; </code></pre> <p>But if you try to pass <code>array1</code> to this function:</p> <pre><code>void function1(int **a); </code></pre> <p>you'll get a warning (and the app will fail to access the array correctly): </p> <pre><code>warning: passing argument 1 of ‘function1’ from incompatible pointer type </code></pre> <p>Because a 2D array is not the same as <code>int **</code>. The automatic decaying of an array into a pointer only goes "one level deep" so to speak. You need to declare the function as:</p> <pre><code>void function2(int a[][2]); </code></pre> <p>or</p> <pre><code>void function2(int a[3][2]); </code></pre> <p>To make everything happy. </p> <p>This same concept extends to <em>n</em>-dimensional arrays. Taking advantage of this kind of funny business in your application generally only makes it harder to understand, though. So be careful out there.</p>
{ "question_id": 2565039, "question_date": "2010-04-02T04:46:42.523Z", "question_score": 208, "tags": "c|arrays|memory|data-structures|stack-memory", "answer_id": 2565048, "answer_date": "2010-04-02T04:49:58.120Z", "answer_score": 164 }
Please answer the following Stack Overflow question: Title: What is Virtual DOM? <p>Recently, I looked at Facebook's <a href="https://facebook.github.io/react/" rel="noreferrer">React</a> framework. It uses a concept called "the Virtual DOM," which I didn't really understand.</p> <p>What is the Virtual DOM? What are the advantages?</p>
<p>React creates a tree of custom objects representing a part of the DOM. For example, instead of creating an actual DIV element containing a UL element, it creates a React.div object that contains a React.ul object. It can manipulate these objects very quickly without actually touching the real DOM or going through the DOM API. Then, when it renders a component, it uses this virtual DOM to figure out what it needs to do with the real DOM to get the two trees to match.</p> <p>You can think of the virtual DOM like a blueprint. It contains all the details needed to construct the DOM, but because it doesn't require all the heavyweight parts that go into a real DOM, it can be created and changed much more easily.</p>
{ "question_id": 21965738, "question_date": "2014-02-23T08:05:26.637Z", "question_score": 208, "tags": "javascript|reactjs", "answer_id": 21965987, "answer_date": "2014-02-23T08:35:10.687Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: Github: Import upstream branch into fork <p>I have a fork (<code>origin</code>) from a project (<code>upstream</code>) on github. Now the upstream project has added a new branch, I want to import into my fork. How do I do that?</p> <p>I tried checking out the remote and creating a branch on top of that, but that configures the branch the way that <code>git push</code> is trying to push to the <code>upstream</code>:</p> <pre><code>git checkout upstream/branch git checkout -b branch </code></pre> <h3>edit</h3> <p>Maybe that wasn't clear, but I want to add the branch to my local repository, so I can push it to <code>origin</code> (my fork) via <code>git push</code>. Because upstream repositories are usually read-only and you fork it to contribute.</p> <p>So I basically want to checkout a non-existent branch on <code>origin</code> whose contents will be pulled in from <code>upstream</code>.</p>
<ol> <li><p>Make sure you've pulled the new <strong>upstream</strong> branch into your <strong>local repo</strong>: </p> <ul> <li>First, <strong>ensure your working tree is clean</strong> (commit/stash/revert any changes) </li> <li>Then, <code>git fetch upstream</code> to retrieve the new upstream branch</li> </ul></li> <li><p>Create and switch to a <strong>local version of the new upstream branch</strong> (<strong><code>newbranch</code></strong>): </p> <ul> <li><code>git checkout -b newbranch upstream/newbranch</code></li> </ul></li> <li><p>When you're ready to push the new branch to <strong>origin</strong>: </p> <ul> <li><code>git push -u origin newbranch</code> </li> </ul></li> </ol> <p>The <strong>-u</strong> switch sets up tracking to the specified remote (in this example, <strong><code>origin</code></strong>)</p>
{ "question_id": 4410091, "question_date": "2010-12-10T14:59:26.253Z", "question_score": 208, "tags": "git|github", "answer_id": 4410502, "answer_date": "2010-12-10T15:42:09.540Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: What is state-of-the-art for text rendering in OpenGL as of version 4.1? <p>There are already a number of questions about text rendering in OpenGL, such as:</p> <ul> <li><a href="https://stackoverflow.com/questions/2071621/opengl-live-text-rendering">How to do OpenGL live text-rendering for a GUI?</a></li> </ul> <p>But mostly what is discussed is rendering textured quads using the fixed-function pipeline. Surely shaders must make a better way.</p> <p>I'm not really concerned about internationalization, most of my strings will be plot tick labels (date and time or purely numeric). But the plots will be re-rendered at the screen refresh rate and there could be quite a bit of text (not more than a few thousand glyphs on-screen, but enough that hardware accelerated layout would be nice).</p> <p>What is the recommended approach for text-rendering using modern OpenGL? (Citing existing software using the approach is good evidence that it works well)</p> <ul> <li>Geometry shaders that accept e.g. position and orientation and a character sequence and emit textured quads</li> <li>Geometry shaders that render vector fonts</li> <li>As above, but using tessellation shaders instead</li> <li>A compute shader to do font rasterization</li> </ul>
<p>Rendering outlines, unless you render only a dozen characters total, remains a "no go" due to the number of vertices needed per character to approximate curvature. Though there have been approaches to evaluate bezier curves in the pixel shader instead, these suffer from not being easily antialiased, which is trivial using a distance-map-textured quad, and evaluating curves in the shader is still computationally much more expensive than necessary.</p> <p>The best trade-off between "fast" and "quality" are still textured quads with a signed distance field texture. It is <em>very slightly</em> slower than using a plain normal textured quad, but not so much. The quality on the other hand, is in an entirely different ballpark. The results are truly stunning, it is as fast as you can get, and effects such as glow are trivially easy to add, too. Also, the technique can be downgraded nicely to older hardware, if needed.</p> <p>See the famous <a href="https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf" rel="noreferrer">Valve paper</a> for the technique.</p> <p>The technique is conceptually similar to how implicit surfaces (metaballs and such) work, though it does not generate polygons. It runs entirely in the pixel shader and takes the distance sampled from the texture as a distance function. Everything above a chosen threshold (usually 0.5) is "in", everything else is "out". In the simplest case, on 10 year old non-shader-capable hardware, setting the alpha test threshold to 0.5 will do that exact thing (though without special effects and antialiasing).<br> If one wants to add a little more weight to the font (faux bold), a slightly smaller threshold will do the trick without modifying a single line of code (just change your "font_weight" uniform). For a glow effect, one simply considers everything above one threshold as "in" and everything above another (smaller) threshold as "out, but in glow", and LERPs between the two. Antialiasing works similarly.</p> <p>By using an 8-bit signed distance value rather than a single bit, this technique increases the effective resolution of your texture map 16-fold in each dimension (instead of black and white, all possible shades are used, thus we have 256 times the information using the same storage). But even if you magnify far beyond 16x, the result still looks quite acceptable. Long straight lines will eventually become a bit wiggly, but there will be no typical "blocky" sampling artefacts.</p> <p>You can use a geometry shader for generating the quads out of points (reduce bus bandwidth), but honestly the gains are rather marginal. The same is true for instanced character rendering as described in GPG8. The overhead of instancing is only amortized if you have a <em>lot</em> of text to draw. The gains are, in my opinion, in no relation to the added complexity and non-downgradeability. Plus, you are either limited by the amount of constant registers, or you have to read from a texture buffer object, which is non-optimal for cache coherence (and the intent was to optimize to begin with!).<br> A simple, plain old vertex buffer is just as fast (possibly faster) if you schedule the upload a bit ahead in time and will run on every hardware built during the last 15 years. And, it is not limited to any particular number of characters in your font, nor to a particular number of characters to render.</p> <p>If you are sure that you do not have more than 256 characters in your font, texture arrays may be worth a consideration to strip off bus bandwidth in a similar manner as generating quads from points in the geometry shader. When using an array texture, the texture coordinates of all quads have identical, constant <code>s</code> and <code>t</code> coordinates and only differ in the <code>r</code> coordinate, which is equal to the character index to render.<br> But like with the other techniques, the expected gains are marginal at the cost of being incompatible with previous generation hardware.</p> <p>There is a handy tool by Jonathan Dummer for generating distance textures: <a href="http://www.gamedev.net/topic/491938-signed-distance-bitmap-font-tool/" rel="noreferrer">description page</a></p> <p><strong>Update:</strong><br> As more recently pointed out in <em>Programmable Vertex Pulling</em> (D. Rákos, "OpenGL Insights", pp. 239), there is no significant extra latency or overhead associated with pulling vertex data programmatically from the shader on the newest generations of GPUs, as compared to doing the same using the standard fixed function.<br> Also, the latest generations of GPUs have more and more reasonably sized general-purpose L2 caches (e.g. 1536kiB on nvidia Kepler), so one may expect the incoherent access problem when pulling random offsets for the quad corners from a buffer texture being less of a problem.</p> <p>This makes the idea of pulling constant data (such as quad sizes) from a buffer texture more attractive. A hypothetical implementation could thus reduce PCIe and memory transfers, as well as GPU memory, to a minimum with an approach like this:</p> <ul> <li>Only upload a character index (one per character to be displayed) as the only input to a vertex shader that passes on this index and <code>gl_VertexID</code>, and amplify that to 4 points in the geometry shader, still having the character index and the vertex id (this will be "gl_primitiveID made available in the vertex shader") as the sole attributes, and capture this via transform feedback.</li> <li>This will be fast, because there are only two output attributes (main bottleneck in GS), and it is close to "no-op" otherwise in both stages.</li> <li>Bind a buffer texture which contains, for each character in the font, the textured quad's vertex positions relative to the base point (these are basically the "font metrics"). This data can be compressed to 4 numbers per quad by storing only the offset of the bottom left vertex, and encoding the width and height of the axis-aligned box (assuming half floats, this will be 8 bytes of constant buffer per character -- a typical 256 character font could fit completely into 2kiB of L1 cache).</li> <li>Set an uniform for the baseline</li> <li>Bind a buffer texture with horizontal offsets. These <em>could</em> probably even be calculated on the GPU, but it is much easier and more efficient to that kind of thing on the CPU, as it is a strictly sequential operation and not at all trivial (think of kerning). Also, it would need another feedback pass, which would be another sync point.</li> <li>Render the previously generated data from the feedback buffer, the vertex shader pulls the horizontal offset of the base point and the offsets of the corner vertices from buffer objects (using the primitive id and the character index). The original vertex ID of the submitted vertices is now our "primitive ID" (remember the GS turned the vertices into quads).</li> </ul> <p>Like this, one could ideally reduce the required vertex bandwith by 75% (amortized), though it would only be able to render a single line. If one wanted to be able to render several lines in one draw call, one would need to add the baseline to the buffer texture, rather than using an uniform (making the bandwidth gains smaller).</p> <p>However, even assuming a 75% reduction -- since the vertex data to display "reasonable" amounts of text is only somewhere around 50-100kiB (which is practically <em>zero</em> to a GPU or a PCIe bus) -- I still doubt that the added complexity and losing backwards-compatibility is really worth the trouble. Reducing zero by 75% is still only zero. I have admittedly not tried the above approach, and more research would be needed to make a truly qualified statement. But still, unless someone can demonstrate a truly stunning performance difference (using "normal" amounts of text, not billions of characters!), my point of view remains that for the vertex data, a simple, plain old vertex buffer is justifiably good enough to be considered part of a "state of the art solution". It's simple and straightforward, it works, and it works well.</p> <p>Having already referenced "<a href="http://openglinsights.com/" rel="noreferrer">OpenGL Insights</a>" above, it is worth to also point out the chapter <em>"2D Shape Rendering by Distance Fields"</em> by Stefan Gustavson which explains distance field rendering in great detail.</p> <p><strong>Update 2016:</strong> </p> <p>Meanwhile, there exist several additional techniques which aim to remove the corner rounding artefacts which become disturbing at extreme magnifications.</p> <p>One approach simply uses pseudo-distance fields instead of distance fields (the difference being that the distance is the shortest distance not to the actual outline, but to the outline <em>or an imaginary</em> line protruding over the edge). This is somewhat better, and runs at the same speed (identical shader), using the same amount of texture memory.</p> <p>Another approach uses the median-of-three in a three-channel texture details and implementation <a href="https://github.com/Chlumsky/msdfgen" rel="noreferrer">available at github</a>. This aims to be an improvement over the and-or hacks used previously to address the issue. Good quality, slightly, almost not noticeably, slower, but uses three times as much texture memory. Also, extra effects (e.g. glow) are harder to get right.</p> <p>Lastly, storing the actual bezier curves making up characters, and evaluating them in a fragment shader <a href="http://wdobbie.com/post/gpu-text-rendering-with-vector-textures/" rel="noreferrer">has become practical</a>, with slightly inferior performance (but not so much that it's a problem) and stunning results even at highest magnifications.<br> WebGL demo rendering a large PDF with this technique in real time available <a href="http://wdobbie.com/pdf/" rel="noreferrer">here</a>.</p>
{ "question_id": 5262951, "question_date": "2011-03-10T16:48:27.680Z", "question_score": 208, "tags": "opengl|text|glsl|shader|opengl-4", "answer_id": 5278471, "answer_date": "2011-03-11T21:16:40.840Z", "answer_score": 211 }
Please answer the following Stack Overflow question: Title: Double vs single quotes <p>Is there a specific time when I should use <code>&quot;&quot;</code> vs <code>''</code>?</p> <p>I've been using single quotes most of the time because it's easier to type but I'm not sure if I should.</p> <p>e.g. <code>get 'user/new'</code> vs. <code>get &quot;user/new&quot;</code></p>
<p><code>" "</code> allows you to do string interpolation, e.g.:</p> <pre><code>world_type = 'Mars' "Hello #{world_type}" </code></pre>
{ "question_id": 6395288, "question_date": "2011-06-18T10:12:44.893Z", "question_score": 208, "tags": "ruby|string|quotes|double-quotes|single-quotes", "answer_id": 6395332, "answer_date": "2011-06-18T10:22:22.407Z", "answer_score": 226 }
Please answer the following Stack Overflow question: Title: Where did the Object Library go in Xcode 10? <p>In Xcode 10, where is the Object Library which shows view and controller objects, code snippets and media that used to appear towards the lower right corner in Xcode 9 and older?</p> <h3>Xcode 9:</h3> <p><a href="https://i.stack.imgur.com/P4Ar2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P4Ar2.png" alt="Xcode project window showing object library"></a></p> <h3>Xcode 10:</h3> <p><a href="https://i.stack.imgur.com/HeQzA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HeQzA.png" alt="Xcode project window showing the same space as the Xcode 9 window, empty"></a></p>
<p><strong>Shortcuts</strong>:</p> <ul> <li><p><kbd>Shift</kbd> + <kbd>Command</kbd> + <kbd>L</kbd>: Show Library.</p></li> <li><p><kbd>Shift</kbd> + <kbd>Command</kbd> + <kbd>M</kbd>: Show Media Library.</p></li> </ul> <hr> <p>Xcode 10 has added a toolbar button to access the Object Library.</p> <p><a href="https://i.stack.imgur.com/3J26u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3J26u.png" alt="enter image description here"></a></p> <p>From a <a href="https://forums.developer.apple.com/thread/103777" rel="noreferrer">thread</a> on Apple Developer Forum:</p> <blockquote> <p>Library content has moved from the bottom of the Inspector area to an overlay window, which can be moved and resized like Spotlight search. It dismisses once items are dragged, but holding the Option key before dragging will keep the library open for an additional drag.</p> <p>The library can be opened via a new toolbar button, the <code>View &gt; Libraries</code> menu, or the ⇧⌘L keyboard shortcut. Content dynamically matches the active editor, so the same UI provides access to code snippets, Interface Builder, SpriteKit, or SceneKit items. The media library is available via a long press on the toolbar button, the <code>View &gt; Libraries</code> menu, or the ⇧⌘M keyboard shortcut. (37318979, 39885726)</p> </blockquote>
{ "question_id": 50962797, "question_date": "2018-06-21T07:30:22.197Z", "question_score": 208, "tags": "xcode|user-interface|xcode10", "answer_id": 50962838, "answer_date": "2018-06-21T07:32:27.240Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How can I disable logging while running unit tests in Python Django? <p>I am using a simple unit test based test runner to test my Django application.</p> <p>My application itself is configured to use a basic logger in settings.py using:</p> <pre><code>logging.basicConfig(level=logging.DEBUG) </code></pre> <p>And in my application code using:</p> <pre><code>logger = logging.getLogger(__name__) logger.setLevel(getattr(settings, 'LOG_LEVEL', logging.DEBUG)) </code></pre> <p>However, when running unittests, I'd like to disable logging so that it doesn't clutter my test result output. Is there a simple way to turn off logging in a global way, so that the application specific loggers aren't writing stuff out to the console when I run tests?</p>
<pre><code>logging.disable(logging.CRITICAL) </code></pre> <p>will disable all logging calls with levels less severe than or equal to <code>CRITICAL</code>. Logging can be re-enabled with</p> <pre><code>logging.disable(logging.NOTSET) </code></pre>
{ "question_id": 5255657, "question_date": "2011-03-10T04:59:55.170Z", "question_score": 208, "tags": "python|django|unit-testing|logging", "answer_id": 5255760, "answer_date": "2011-03-10T05:14:58.917Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: What is causing this ActiveRecord::ReadOnlyRecord error? <p>This follows <a href="https://stackoverflow.com/questions/628000/rails-whats-wrong-with-this-multiple-join-with-conditions-on-the-associations" title="this">this</a> prior question, which was answered. I actually discovered I could remove a join from that query, so now the working query is</p> <pre><code>start_cards = DeckCard.find :all, :joins =&gt; [:card], :conditions =&gt; ["deck_cards.deck_id = ? and cards.start_card = ?", @game.deck.id, true] </code></pre> <p>This appears to work. However, when I try to move these DeckCards into another association, I get the ActiveRecord::ReadOnlyRecord error.</p> <p>Here's the code</p> <pre><code>for player in @game.players player.tableau = Tableau.new start_card = start_cards.pop start_card.draw_pile = false player.tableau.deck_cards &lt;&lt; start_card # the error occurs on this line end </code></pre> <p>and the relevant Models (tableau are the players cards on the table)</p> <pre><code>class Player &lt; ActiveRecord::Base belongs_to :game belongs_to :user has_one :hand has_one :tableau end class Tableau &lt; ActiveRecord::Base belongs_to :player has_many :deck_cards end class DeckCard &lt; ActiveRecord::Base belongs_to :card belongs_to :deck end </code></pre> <p>I am doing a similar action just after this code, adding <code>DeckCards</code> to the players hand, and that code is working fine. I wondered if I needed <code>belongs_to :tableau</code> in the DeckCard Model, but it works fine for the adding to player's hand. I do have a <code>tableau_id</code> and <code>hand_id</code> columns in the DeckCard table.</p> <p>I looked up ReadOnlyRecord in the rails api, and it doesn't say much beyond the description.</p>
<p><strong>Rails 2.3.3 and lower</strong></p> <p>From the <a href="https://raw.github.com/rails/rails/3-0-stable/activerecord/CHANGELOG" rel="noreferrer">ActiveRecord <code>CHANGELOG</code></a><sup>(v1.12.0, October 16th, 2005)</sup>:</p> <blockquote> <p>Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. <strong>The :joins option now implies :readonly, so if you use this option, saving the same record will now fail.</strong> Use find_by_sql to work around.</p> </blockquote> <p>Using <code>find_by_sql</code> is not really an alternative as it returns raw row/column data, not <code>ActiveRecords</code>. You have two options:</p> <ol> <li>Force the instance variable <code>@readonly</code> to false in the record (hack)</li> <li>Use <code>:include =&gt; :card</code> instead of <code>:join =&gt; :card</code></li> </ol> <p><strong>Rails 2.3.4 and above</strong></p> <p>Most of the above no longer holds true, after September 10 2012:</p> <ul> <li>using <code>Record.find_by_sql</code> <strong>is</strong> a viable option</li> <li><code>:readonly =&gt; true</code> is automatically inferred <strong>only</strong> if <code>:joins</code> was specified <strong>without</strong> an explicit <code>:select</code> <strong>nor</strong> an explicit (or finder-scope-inherited) <code>:readonly</code> option (see the implementation of <code>set_readonly_option!</code> in <code>active_record/base.rb</code> for Rails 2.3.4, or the implementation of <code>to_a</code> in <code>active_record/relation.rb</code> and of <code>custom_join_sql</code> in <code>active_record/relation/query_methods.rb</code> for Rails 3.0.0)</li> <li>however, <code>:readonly =&gt; true</code> is always automatically inferred in <code>has_and_belongs_to_many</code> if the join table has more than the two foreign keys columns and <code>:joins</code> was specified without an explicit <code>:select</code> (i.e. user-supplied <code>:readonly</code> values are ignored -- see <code>finding_with_ambiguous_select?</code> in <code>active_record/associations/has_and_belongs_to_many_association.rb</code>.)</li> <li>in conclusion, unless dealing with a special join table and <code>has_and_belongs_to_many</code>, then <code>@aaronrustad</code>'s answer applies just fine in Rails 2.3.4 and 3.0.0.</li> <li>do <em>not</em> use <code>:includes</code> if you want to achieve an <code>INNER JOIN</code> (<code>:includes</code> implies a <code>LEFT OUTER JOIN</code>, which is less selective and less efficient than <code>INNER JOIN</code>.)</li> </ul>
{ "question_id": 639171, "question_date": "2009-03-12T15:28:33.733Z", "question_score": 208, "tags": "ruby-on-rails|ruby|activerecord|join|associations", "answer_id": 639844, "answer_date": "2009-03-12T18:15:06.923Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: Using the "final" modifier whenever applicable in Java <p>In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.</p> <p>Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.</p> <p>What are your thoughts on this and what do you follow?</p>
<p>I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of <code>final</code> modifiers anywhere, but when you think about it... </p> <p>Adding <code>final</code> to all things which <em>should not</em> change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.</p> <p>At first, it kind of looks awkward to see a lot of <code>final</code> keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, <em>that-thing-will-never-change-from-this-point-on</em> (you can take it from me ;-)</p> <p>I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something <code>final</code> I'll do it.</p>
{ "question_id": 137868, "question_date": "2008-09-26T05:05:59.070Z", "question_score": 208, "tags": "java|oop", "answer_id": 137946, "answer_date": "2008-09-26T05:45:57.833Z", "answer_score": 200 }
Please answer the following Stack Overflow question: Title: Chrome Developer Tools: How to find out what is overriding a CSS rule? <p>Well, this is pretty straightforward. If Chrome's Developer Tools is showing me that a style is overridden, how to see what CSS rule is overriding it?</p> <p>I want to know if is there anything like <em>"Show me what overrides this"</em>.</p> <p><strong>OBS:</strong> <em>Please, don't point me to Firebug.</em></p>
<p>Use the <strong>Computed Style</strong> panel of the element inspector. Expand the property of interest to see the list of applicable rules, and which one won.</p> <p><img src="https://i.stack.imgur.com/30GVK.png" alt="Chrome screenshot"></p>
{ "question_id": 13867088, "question_date": "2012-12-13T19:35:00.323Z", "question_score": 208, "tags": "css|google-chrome|developer-tools|inspector", "answer_id": 13867536, "answer_date": "2012-12-13T20:03:16.460Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: How to check if an object is a generator object in python? <p>In python, how do I check if an object is a generator object?</p> <p>Trying this - </p> <pre><code>&gt;&gt;&gt; type(myobject, generator) </code></pre> <p>gives the error -</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'generator' is not defined </code></pre> <p>(I know I can check if the object has a <code>next</code> method for it to be a generator, but I want some way using which I can determine the type of any object, not just generators.)</p>
<p>You can use GeneratorType from types:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; types.GeneratorType &lt;class 'generator'&gt; &gt;&gt;&gt; gen = (i for i in range(10)) &gt;&gt;&gt; isinstance(gen, types.GeneratorType) True </code></pre>
{ "question_id": 6416538, "question_date": "2011-06-20T19:42:28.057Z", "question_score": 208, "tags": "python|generator", "answer_id": 6416585, "answer_date": "2011-06-20T19:46:00.813Z", "answer_score": 288 }
Please answer the following Stack Overflow question: Title: How do I execute a Git command without being in the repository? <p>Is there a way to execute Git commands against a repository without being in that repository?</p> <p>For example something like this: <code>git /home/repo log</code>?</p> <p>Please do not tell me to <code>cd</code> to it. I'm doing this via an <code>exec</code> call.</p>
<p>Try:</p> <pre><code>git --git-dir=/home/repo/.git log </code></pre> <p>It is important to give the path all the way up to the .git directory of your repository. Otherwise you will get only an error message that says something like:</p> <pre><code>fatal: Not a git repository </code></pre>
{ "question_id": 7149984, "question_date": "2011-08-22T15:42:56.013Z", "question_score": 208, "tags": "git", "answer_id": 7150012, "answer_date": "2011-08-22T15:45:30.417Z", "answer_score": 114 }
Please answer the following Stack Overflow question: Title: How to exclude a file extension from IntelliJ IDEA search? <p>Is there a way to exclude particular file extension from the results in IntelliJ IDEA's "<em>Find in Path</em>" dialog (invoked by <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>F</kbd>)? I want to exclude all <code>.css</code> files.</p>
<p>In intellij 16 there is a section "File name Filter" to exclude an extension use <code>!*.java</code>. You can give more detailed patterns as well for example I use the pattern below to only return .java files except those with a name starting or ending with test. Pattern: <code>!*test.java,*.java,!Test*.java</code></p> <p><a href="https://i.stack.imgur.com/HuTg1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HuTg1.png" alt="enter image description here"></a></p> <p>In recent versions of Intellij the GUI has been updated a bit but the same still applies see the "File mask" on the top right hand corner see image below:</p> <p><a href="https://i.stack.imgur.com/RNPY1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RNPY1.png" alt="enter image description here"></a></p>
{ "question_id": 22143881, "question_date": "2014-03-03T10:13:28.457Z", "question_score": 208, "tags": "intellij-idea", "answer_id": 37781104, "answer_date": "2016-06-13T02:40:42.387Z", "answer_score": 293 }
Please answer the following Stack Overflow question: Title: AutoMapper vs ValueInjecter <p>Everytime I'm looking for <a href="http://automapper.codeplex.com/" rel="noreferrer">AutoMapper</a> stuff on StackOverflow, I'm reading something about <a href="http://valueinjecter.codeplex.com/" rel="noreferrer">ValueInjecter</a>.</p> <p>Can somebody tell me the pros and cons between them (performance, features, API usage, extensibility, testing) ?</p>
<p>as the creator of <a href="http://valueinjecter.codeplex.com/" rel="noreferrer">ValueInjecter</a>, I can tell you that I did it because I wanted something <strong>simple and very flexible</strong> </p> <p>I really don't like writing much or writing lots of <code>monkey code</code> like:</p> <pre><code>Prop1.Ignore, Prop2.Ignore etc. CreateMap&lt;Foo,Bar&gt;(); CreateMap&lt;Tomato, Potato&gt;(); etc. </code></pre> <p>ValueInjecter is something <strong>like mozilla with it's plugins,</strong> you create ValueInjections and use them</p> <p>there are built-in injections for flattening, unflattening, and some that are intended to be inherited </p> <p>and it works more in <strong>an aspect type of way</strong>, you don't have to specify all properties 1-to-1, instead you do something like: </p> <p><em>take all the int properties from source which name ends with "Id", transform the value and set each to a property in the source object with same name without the Id suffix and it's type is inherited from Entity, stuff like that</em></p> <p><strong>so one obvious difference, ValueInjecter is used even in windows forms with flattening and unflattening, that's how flexible it is</strong></p> <p>(mapping from object to form controls and back)</p> <p>Automapper, not usable in windows forms, no unflatenning, but it has good stuff like collections mapping, so in case you need it with ValueInjecter you just do something like:</p> <p><code>foos.Select(o =&gt; new Bar().InjectFrom(o));</code></p> <p>you can also use ValueInjecter to map from <strong>anonymous</strong> and <strong>dynamic</strong> objects</p> <p><strong>differences:</strong></p> <ul> <li><p>automapper create configuration for each mapping possibility CreateMap()</p></li> <li><p>valueinjecter inject from any object to any object (there are also cases when you inject from object to valuetype)</p></li> <li><p>automapper has flattening built it, and only for simple types or from same type, and it doesn't has unflattening</p></li> <li><p>valueinjecter only if you need it you do <code>target.InjectFrom&lt;FlatLoopValueInjection&gt;(source); also &lt;UnflatLoopValueInjection&gt;</code> and if you want from <code>Foo.Bar.Name of type String</code> to <code>FooBarName of type Class1</code> you inherit FlatLoopValueInjection and specify this</p></li> <li><p>automapper maps properties with same name by default and for the rest you have to specify one by one, and do stuff like Prop1.Ignore(), Prop2.Ignore() etc.</p></li> <li><p>valueinjecter has a default injection .InjectFrom() that does the properties with the same name and type; for everything else you create your custom valueinjections with individual mapping logic/rules, more like aspects, e.g. <em>from all props of Type Foo to all props of type Bar</em></p></li> </ul>
{ "question_id": 4663577, "question_date": "2011-01-11T22:49:45.700Z", "question_score": 208, "tags": "c#|.net|automapper|valueinjecter|object-object-mapping", "answer_id": 4673771, "answer_date": "2011-01-12T20:38:07.270Z", "answer_score": 170 }
Please answer the following Stack Overflow question: Title: Double not (!!) operator in PHP <p>What does the double <em>not</em> operator do in PHP?</p> <p>For example:</p> <pre><code>return !! $row; </code></pre> <p>What would the code above do?</p>
<p>It's not the "double not operator", it's the <strong>not</strong> operator applied twice. The right <code>!</code> will result in a boolean, <em>regardless of the operand</em>. Then the left <code>!</code> will negate that boolean. </p> <p>This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value <code>TRUE</code>, and for any false value (0, 0.0, <code>NULL</code>, empty strings or empty arrays) you will get the boolean value <code>FALSE</code>.</p> <p>It is functionally equivalent to a cast to <code>boolean</code>:</p> <pre><code>return (bool)$row; </code></pre>
{ "question_id": 2127260, "question_date": "2010-01-24T13:51:45.737Z", "question_score": 208, "tags": "php|operators", "answer_id": 2127324, "answer_date": "2010-01-24T14:13:47.573Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: Remove ✅, , ✈ , ♛ and other such emojis/images/signs from Java strings <p>I have some strings with all kinds of different emojis/images/signs in them.</p> <p>Not all the strings are in English -- some of them are in other non-Latin languages, for example:</p> <pre class="lang-none prettyprint-override"><code>▓ railway?? → Cats and dogs I'm on Apples ⚛ ✅ Vi sign ♛ I'm the king ♛ Corée ♦ du Nord ☁ (French) gjør at både ◄╗ (Norwegian) Star me ★ Star ⭐ once more 早上好 ♛ (Chinese) Καλημέρα ✂ (Greek) another ✓ sign ✓ добрай раніцы ✪ (Belarus) ◄ शुभ प्रभात ◄ (Hindi) ✪ ✰ ❈ ❧ Let's get together ★. We shall meet at 12/10/2018 10:00 AM at Tony's.❉ </code></pre> <p>...and many more of these.</p> <p>I would like to get rid of all these signs/images and to keep only the letters (and punctuation) in the different languages. </p> <p>I tried to clean the signs using the <a href="https://github.com/vdurmont/emoji-java" rel="noreferrer">EmojiParser library</a>:</p> <pre><code>String withoutEmojis = EmojiParser.removeAllEmojis(input); </code></pre> <p>The problem is that EmojiParser is not able to remove the majority of the signs. The ♦ sign is the only one I found till now that it removed. Other signs such as ✪ ❉ ★ ✰ ❈ ❧ ✂ ❋ ⓡ ✿ ♛ are not removed.</p> <p>Is there a way to remove all these signs from the input strings and keeping only the letters and punctuation in the <strong>different languages</strong>?</p>
<p>Instead of blacklisting some elements, how about creating a whitelist of the characters you do wish to keep? This way you don't need to worry about every new emoji being added.</p> <pre><code>String characterFilter = "[^\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]"; String emotionless = aString.replaceAll(characterFilter,""); </code></pre> <p>So:</p> <ul> <li><code>[\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]</code> is a range representing all numeric (<code>\\p{N}</code>), letter (<code>\\p{L}</code>), mark (<code>\\p{M}</code>), punctuation (<code>\\p{P}</code>), whitespace/separator (<code>\\p{Z}</code>), other formatting (<code>\\p{Cf}</code>) and other characters above <code>U+FFFF</code> in Unicode (<code>\\p{Cs}</code>), and newline (<code>\\s</code>) characters. <strong><code>\\p{L}</code> specifically</strong> includes the characters from other alphabets such as Cyrillic, Latin, Kanji, etc. </li> <li>The <code>^</code> in the regex character set negates the match.</li> </ul> <p>Example:</p> <pre><code>String str = "hello world _# 皆さん、こんにちは! 私はジョンと申します。"; System.out.print(str.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]","")); // Output: // "hello world _# 皆さん、こんにちは! 私はジョンと申します。" </code></pre> <p>If you need more information, check out the Java <a href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#unicode" rel="noreferrer">documentation</a> for regexes.</p>
{ "question_id": 49510006, "question_date": "2018-03-27T10:05:45.470Z", "question_score": 208, "tags": "java|string|emoji", "answer_id": 49516025, "answer_date": "2018-03-27T14:46:45.147Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: Should everything really be a bundle in Symfony 2.x? <p>I'm aware of questions like <a href="https://stackoverflow.com/questions/7958346/an-exact-description-of-a-symfony-bundle-in-a-complex-web-application">this</a>, where people tend to discuss the general Symfony 2 concept of bundle.</p> <p>The thing is, in a specific application, like, for instance, a twitter-like application, should everything really be inside a generic bundle, like the <a href="http://symfony.com/doc/2.7/page_creation.html#bundles-configuration" rel="noreferrer">official docs</a> say? </p> <p>The reason I'm asking this is because when we develop applications, in general, we don't want to highly couple our code to some full-stack glue framework.</p> <p>If I develop a Symfony 2 based application and, at some point, I decide Symfony 2 is not really the best choice to <em>keep the development going</em>, will that be a problem for me?</p> <p>So the general question is: why is everything being a bundle a good thing? </p> <p><strong>EDIT#1</strong></p> <p>Almost a year now since I asked this question I wrote an <a href="https://medium.com/@drgomesp/yes-you-can-have-low-coupling-in-a-symfony-standard-edition-application-41c5a34aaf94" rel="noreferrer">article</a> to share my knowledge on this topic.</p>
<p>I've written a more thorough and updated blog post on this topic: <a href="http://elnur.pro/symfony-without-bundles/" rel="noreferrer">http://elnur.pro/symfony-without-bundles/</a></p> <hr /> <p>No, not everything has to be in a bundle. You could have a structure like this:</p> <ul> <li><code>src/Vendor/Model</code> — for models,</li> <li><code>src/Vendor/Controller</code> — for controllers,</li> <li><code>src/Vendor/Service</code> — for services,</li> <li><code>src/Vendor/Bundle</code> — for bundles, like <code>src/Vendor/Bundle/AppBundle</code>,</li> <li>etc.</li> </ul> <p>This way, you would put in the <code>AppBundle</code> only that stuff that is really Symfony2 specific. If you decide to switch to another framework later, you would get rid of the <code>Bundle</code> namespace and replace it with the chosen framework stuff.</p> <p><em>Please note that what I'm suggesting here is for <strong>app</strong> specific code. For reusable bundles, I still suggest using <a href="http://symfony.com/doc/master/cookbook/bundles/best_practices.html" rel="noreferrer">the best practices</a>.</em></p> <h1>Keeping entities out of bundles</h1> <p>To keep entities in <code>src/Vendor/Model</code> outside of any bundle, I've changed the <code>doctrine</code> section in <code>config.yml</code> from</p> <pre><code>doctrine: # ... orm: # ... auto_mapping: true </code></pre> <p>to</p> <pre><code>doctrine: # ... orm: # ... mappings: model: type: annotation dir: %kernel.root_dir%/../src/Vendor/Model prefix: Vendor\Model alias: Model is_bundle: false </code></pre> <p>Entities's names — to access from Doctrine repositories — begin with <code>Model</code> in this case, for example, <code>Model:User</code>.</p> <p>You can use subnamespaces to group related entities together, for example, <code>src/Vendor/User/Group.php</code>. In this case, the entity's name is <code>Model:User\Group</code>.</p> <h1>Keeping controllers out of bundles</h1> <p>First, you need to tell <a href="https://github.com/schmittjoh/JMSDiExtraBundle" rel="noreferrer">JMSDiExtraBundle</a> to scan the <code>src</code> folder for services by adding this to <code>config.yml</code>:</p> <pre><code>jms_di_extra: locations: directories: %kernel.root_dir%/../src </code></pre> <p>Then you <a href="http://symfony.com/doc/master/cookbook/controller/service.html" rel="noreferrer">define controllers as services</a> and put them under the <code>Controller</code> namespace:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace Vendor\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use JMS\DiExtraBundle\Annotation\Service; use JMS\DiExtraBundle\Annotation\InjectParams; use JMS\SecurityExtraBundle\Annotation\Secure; use Elnur\AbstractControllerBundle\AbstractController; use Vendor\Service\UserService; use Vendor\Model\User; /** * @Service(&quot;user_controller&quot;, parent=&quot;elnur.controller.abstract&quot;) * @Route(service=&quot;user_controller&quot;) */ class UserController extends AbstractController { /** * @var UserService */ private $userService; /** * @InjectParams * * @param UserService $userService */ public function __construct(UserService $userService) { $this-&gt;userService = $userService; } /** * @Route(&quot;/user/add&quot;, name=&quot;user.add&quot;) * @Template * @Secure(&quot;ROLE_ADMIN&quot;) * * @param Request $request * @return array */ public function addAction(Request $request) { $user = new User; $form = $this-&gt;formFactory-&gt;create('user', $user); if ($request-&gt;getMethod() == 'POST') { $form-&gt;bind($request); if ($form-&gt;isValid()) { $this-&gt;userService-&gt;save($user); $request-&gt;getSession()-&gt;getFlashBag()-&gt;add('success', 'user.add.success'); return new RedirectResponse($this-&gt;router-&gt;generate('user.list')); } } return ['form' =&gt; $form-&gt;createView()]; } /** * @Route(&quot;/user/profile&quot;, name=&quot;user.profile&quot;) * @Template * @Secure(&quot;ROLE_USER&quot;) * * @param Request $request * @return array */ public function profileAction(Request $request) { $user = $this-&gt;getCurrentUser(); $form = $this-&gt;formFactory-&gt;create('user_profile', $user); if ($request-&gt;getMethod() == 'POST') { $form-&gt;bind($request); if ($form-&gt;isValid()) { $this-&gt;userService-&gt;save($user); $request-&gt;getSession()-&gt;getFlashBag()-&gt;add('success', 'user.profile.edit.success'); return new RedirectResponse($this-&gt;router-&gt;generate('user.view', [ 'username' =&gt; $user-&gt;getUsername() ])); } } return [ 'form' =&gt; $form-&gt;createView(), 'user' =&gt; $user ]; } } </code></pre> <p>Note that I'm using my <a href="https://github.com/elnur/ElnurAbstractControllerBundle" rel="noreferrer">ElnurAbstractControllerBundle</a> to simplify defining controllers as services.</p> <p>The last thing left is to tell Symfony to look for templates without bundles. I do this by overriding the template guesser service, but since the approach is different between Symfony 2.0 and 2.1, I'm providing versions for both of them.</p> <h3>Overriding the Symfony 2.1+ template guesser</h3> <p>I've created a <a href="https://github.com/elnur/ElnurTemplateGuesserBundle" rel="noreferrer">bundle</a> that does that for you.</p> <h3>Overriding the Symfony 2.0 template listener</h3> <p>First, define the class:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace Vendor\Listener; use InvalidArgumentException; use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Bundle\Bundle; use Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener as FrameworkExtraTemplateListener; use JMS\DiExtraBundle\Annotation\Service; class TemplateListener extends FrameworkExtraTemplateListener { /** * @param array $controller * @param Request $request * @param string $engine * @throws InvalidArgumentException * @return TemplateReference */ public function guessTemplateName($controller, Request $request, $engine = 'twig') { if (!preg_match('/Controller\\\(.+)Controller$/', get_class($controller[0]), $matchController)) { throw new InvalidArgumentException(sprintf('The &quot;%s&quot; class does not look like a controller class (it must be in a &quot;Controller&quot; sub-namespace and the class name must end with &quot;Controller&quot;)', get_class($controller[0]))); } if (!preg_match('/^(.+)Action$/', $controller[1], $matchAction)) { throw new InvalidArgumentException(sprintf('The &quot;%s&quot; method does not look like an action method (it does not end with Action)', $controller[1])); } $bundle = $this-&gt;getBundleForClass(get_class($controller[0])); return new TemplateReference( $bundle ? $bundle-&gt;getName() : null, $matchController[1], $matchAction[1], $request-&gt;getRequestFormat(), $engine ); } /** * @param string $class * @return Bundle */ protected function getBundleForClass($class) { try { return parent::getBundleForClass($class); } catch (InvalidArgumentException $e) { return null; } } } </code></pre> <p>And then tell Symfony to use it by adding this to <code>config.yml</code>:</p> <pre><code>parameters: jms_di_extra.template_listener.class: Vendor\Listener\TemplateListener </code></pre> <h3>Using templates without bundles</h3> <p>Now, you can use templates out of bundles. Keep them under the <code>app/Resources/views</code> folder. For example, templates for those two actions from the example controller above are located in:</p> <ul> <li><code>app/Resources/views/User/add.html.twig</code></li> <li><code>app/Resources/views/User/profile.html.twig</code></li> </ul> <p>When referring to a template, just omit the bundle part:</p> <pre><code>{% include ':Controller:view.html.twig' %} </code></pre>
{ "question_id": 9999433, "question_date": "2012-04-03T18:45:52.617Z", "question_score": 208, "tags": "symfony|architecture|bundle", "answer_id": 10001019, "answer_date": "2012-04-03T20:38:09.030Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: How can I handle R CMD check "no visible binding for global variable" notes when my ggplot2 syntax is sensible? <p><em>EDIT: Hadley Wickham points out that I misspoke. R CMD check is throwing NOTES, not Warnings. I'm terribly sorry for the confusion. It was my oversight.</em></p> <h2>The short version</h2> <p><code>R CMD check</code> throws this note every time I use <a href="https://github.com/briandk/granovaGG/blob/dev/R/granovagg.contr.R#L254-265" rel="noreferrer">sensible plot-creation syntax</a> in ggplot2:</p> <pre><code>no visible binding for global variable [variable name] </code></pre> <p>I understand why R CMD check does that, but it seems to be criminalizing an entire vein of otherwise sensible syntax. I'm not sure what steps to take to get my package to pass <code>R CMD check</code> and get admitted to CRAN.</p> <h2>The background</h2> <p>Sascha Epskamp previously posted on <a href="https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check">essentially the same issue</a>. The difference, I think, is that <code>subset()</code>'s manpage <a href="https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check/8096456#8096456">says it's designed for interactive use</a>.</p> <p>In my case, the issue is not over <code>subset()</code> but over a core feature of <code>ggplot2</code>: the <code>data =</code> argument.</p> <h2>An example of code I write that generates these notes</h2> <p>Here's <a href="https://github.com/briandk/granovaGG/blob/dev/R/granovagg.contr.R#L254-265" rel="noreferrer">a sub-function</a> in <a href="https://github.com/briandk/granovaGG" rel="noreferrer">my package</a> that adds points to a plot:</p> <pre><code>JitteredResponsesByContrast &lt;- function (data) { return( geom_point( aes( x = x.values, y = y.values ), data = data, position = position_jitter(height = 0, width = GetDegreeOfJitter(jj)) ) ) } </code></pre> <p><code>R CMD check</code>, on parsing this code, will say</p> <pre><code>granovagg.contr : JitteredResponsesByContrast: no visible binding for global variable 'x.values' granovagg.contr : JitteredResponsesByContrast: no visible binding for global variable 'y.values' </code></pre> <h2>Why R CMD check is right</h2> <p>The check is technically correct. <code>x.values</code> and <code>y.values</code></p> <ul> <li>Aren't defined locally in the function <code>JitteredResponsesByContrast()</code></li> <li>Aren't pre-defined in the form <code>x.values &lt;- [something]</code> either globally or in the caller.</li> </ul> <p>Instead, they're variables within a dataframe that gets defined earlier and passed into the function <code>JitteredResponsesByContrast()</code>.</p> <h2>Why ggplot2 makes it difficult to appease R CMD check</h2> <p>ggplot2 seems to encourage the use of a <code>data</code> argument. The data argument, presumably, is why this code will execute</p> <pre><code>library(ggplot2) p &lt;- ggplot(aes(x = hwy, y = cty), data = mpg) p + geom_point() </code></pre> <p>but <strong>this</strong> code will produce an object-not-found error:</p> <pre><code>library(ggplot2) hwy # a variable in the mpg dataset </code></pre> <h2>Two work-arounds, and why I'm happy with neither</h2> <h3>The NULLing out strategy</h3> <p><a href="https://stackoverflow.com/a/8096882/180626">Matthew Dowle recommends</a> setting the problematic variables to NULL first, which in my case would look like this:</p> <pre><code>JitteredResponsesByContrast &lt;- function (data) { x.values &lt;- y.values &lt;- NULL # Setting the variables to NULL first return( geom_point( aes( x = x.values, y = y.values ), data = data, position = position_jitter(height = 0, width = GetDegreeOfJitter(jj)) ) ) } </code></pre> <p>I appreciate this solution, but I dislike it for three reasons.</p> <ol> <li>it serves no additional purpose beyond appeasing <code>R CMD check</code>.</li> <li>it doesn't reflect intent. It raises the expectation that the <code>aes()</code> call will see our now-NULL variables (it won't), while obscuring the real purpose (making R CMD check aware of variables it apparently wouldn't otherwise know were bound)</li> <li>The problems of 1 and 2 multiply because every time you write a function that returns a plot element, you have to add a confusing NULLing statement</li> </ol> <h3>The with() strategy</h3> <p>You can use <code>with()</code> to explicitly signal that the variables in question can be found inside some larger environment. In my case, using <code>with()</code> looks like this:</p> <pre><code>JitteredResponsesByContrast &lt;- function (data) { with(data, { geom_point( aes( x = x.values, y = y.values ), data = data, position = position_jitter(height = 0, width = GetDegreeOfJitter(jj)) ) } ) } </code></pre> <p>This solution works. But, I don't like this solution because it doesn't even work the way I would expect it to. If <code>with()</code> were really solving the problem of pointing the interpreter to where the variables are, then I shouldn't even <em>need</em> the <code>data =</code> argument. But, <code>with()</code> doesn't work that way:</p> <pre><code>library(ggplot2) p &lt;- ggplot() p &lt;- p + with(mpg, geom_point(aes(x = hwy, y = cty))) p # will generate an error saying `hwy` is not found </code></pre> <p>So, again, I think this solution has similar flaws to the NULLing strategy:</p> <ol> <li>I still have to go through every plot element function and wrap the logic in a <code>with()</code> call</li> <li>The <code>with()</code> call is misleading. I still need to supply a <code>data =</code> argument; all <code>with()</code> is doing is appeasing <code>R CMD check</code>.</li> </ol> <h2>Conclusion</h2> <p>The way I see it, there are three options I could take:</p> <ol> <li>Lobby CRAN to ignore the notes by arguing that they're &quot;spurious&quot; (pursuant to <a href="http://cran.r-project.org/web/packages/policies.html#Submission" rel="noreferrer">CRAN policy</a>), and do that every time I submit a package</li> <li>Fix my code with one of two undesirable strategies (NULLing or <code>with()</code> blocks)</li> <li>Hum really loudly and hope the problem goes away</li> </ol> <p>None of the three make me happy, and I'm wondering what people suggest I (and other package developers wanting to tap into ggplot2) should do.</p>
<p>Have you tried with <code>aes_string</code> instead of <code>aes</code>? This should work, although I haven't tried it:</p> <pre><code>aes_string(x = 'x.values', y = 'y.values') </code></pre>
{ "question_id": 9439256, "question_date": "2012-02-24T23:00:56.057Z", "question_score": 208, "tags": "r|ggplot2", "answer_id": 9439360, "answer_date": "2012-02-24T23:10:10.810Z", "answer_score": 50 }
Please answer the following Stack Overflow question: Title: Why aren't my ball (objects) shrinking/disappearing? <p><a href="http://jsfiddle.net/goldrunt/jGL84/42/">http://jsfiddle.net/goldrunt/jGL84/42/</a> this is from line 84 in this JS fiddle. There are 3 different effects which can be applied to the balls by uncommenting lines 141-146. The 'bounce' effect works as it should, but the 'asplode' effect does nothing. Should I include the 'shrink' function inside the asplode function?</p> <pre><code>// balls shrink and disappear if they touch var shrink = function(p) { for (var i = 0; i &lt; 100; i++) { p.radius -= 1; } function asplode(p) { setInterval(shrink(p),100); balls.splice(p, 1); } } </code></pre>
<p>Your code has a few problems.</p> <p>First, in your definition:</p> <pre><code>var shrink = function(p) { for (var i = 0; i &lt; 100; i++) { p.radius -= 1; } function asplode(p) { setInterval(shrink(p),100); balls.splice(p, 1); } } </code></pre> <p><code>asplode</code> is local to the scope inside <code>shrink</code> and therefore not accessible to the code in <code>update</code> where you are attempting to call it. JavaScript scope is function-based, so <code>update</code> cannot see <code>asplode</code> because it is not inside <code>shrink</code>. (<a href="https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers">In your console</a>, you'll see an error like: <code>Uncaught ReferenceError: asplode is not defined</code>.)</p> <p>You might first try instead moving <code>asplode</code> outside of <code>shrink</code>: </p> <pre><code>var shrink = function(p) { for (var i = 0; i &lt; 100; i++) { p.radius -= 1; } } function asplode(p) { setInterval(shrink(p),100); balls.splice(p, 1); } </code></pre> <p>However, your code has several more problems that are outside the scope of this question:</p> <ul> <li><p><code>setInterval</code> expects a function. <code>setInterval(shrink(p), 100)</code> causes <code>setInterval</code> to get the <em>return value</em> of <em>immediate-invoked</em> <code>shrink(p)</code>. You probably want</p> <pre><code>setInterval(function() { shrink(p) }, 100) </code></pre></li> <li><p>Your code <code>for (var i = 0; i &lt; 100; i++) { p.radius -= 1; }</code> probably does not do what you think it does. This will immediately run the decrement operation 100 times, and <em>then</em> visually show the result. If you want to re-render the ball at each new size, you will need to perform each individual decrement inside a separate timing callback (like a <code>setInterval</code> operation).</p></li> <li><p><code>.splice</code> expects a numeric index, not an object. You can get the numeric index of an object with <code>indexOf</code>:</p> <pre><code>balls.splice(balls.indexOf(p), 1); </code></pre></li> <li><p>By the time your interval runs for the first time, the <code>balls.splice</code> statement has already happened (it happened about 100ms ago, to be exact). I assume that's not what you want. Instead, you should have a decrementing function that gets repeatedly called by <code>setInterval</code> and finally performs <code>balls.splice(p,1)</code> after <code>p.radius == 0</code>.</p></li> </ul>
{ "question_id": 20550930, "question_date": "2013-12-12T18:07:20.413Z", "question_score": 208, "tags": "javascript|html", "answer_id": 20551218, "answer_date": "2013-12-12T18:21:26.997Z", "answer_score": 65 }
Please answer the following Stack Overflow question: Title: Sql Server string to date conversion <p>I want to convert a string like this:</p> <pre><code>'10/15/2008 10:06:32 PM' </code></pre> <p>into the equivalent DATETIME value in Sql Server.</p> <p>In Oracle, I would say this:</p> <pre><code>TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM') </code></pre> <p><a href="https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server">This question</a> implies that I must parse the string into one of the <a href="http://www.sql-server-helper.com/tips/date-formats.aspx" rel="noreferrer">standard formats</a>, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?</p>
<p>Try this</p> <pre><code>Cast('7/7/2011' as datetime) </code></pre> <p>and</p> <pre><code>Convert(DATETIME, '7/7/2011', 101) </code></pre> <p>See <a href="https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx" rel="nofollow noreferrer">CAST and CONVERT (Transact-SQL)</a> for more details.</p>
{ "question_id": 207190, "question_date": "2008-10-16T02:08:51.683Z", "question_score": 207, "tags": "sql-server|tsql|datetime|sql-server-2005|string-to-datetime", "answer_id": 7175369, "answer_date": "2011-08-24T12:26:05.590Z", "answer_score": 337 }
Please answer the following Stack Overflow question: Title: How can I get column names from a table in Oracle? <p>I need to query the database to get the <em>column names</em>, not to be confused with data in the table. For example, if I have a table named <code>EVENT_LOG</code> that contains <code>eventID</code>, <code>eventType</code>, <code>eventDesc</code>, and <code>eventTime</code>, then I would want to retrieve those field names from the query and nothing else.</p> <p>I found how to do this in:</p> <ul> <li><a href="https://stackoverflow.com/q/1054984/419956">Microsoft SQL Server</a></li> <li><a href="https://stackoverflow.com/q/193780/419956">MySQL</a></li> <li><a href="https://dba.stackexchange.com/q/22362/5089">PostgreSQL</a></li> </ul> <p>But I need to know: <strong>how can this be done in <em>Oracle</em>?</strong></p>
<p>You can query the USER_TAB_COLUMNS table for table column metadata.</p> <pre><code>SELECT table_name, column_name, data_type, data_length FROM USER_TAB_COLUMNS WHERE table_name = 'MYTABLE' </code></pre>
{ "question_id": 452464, "question_date": "2009-01-16T23:53:00.937Z", "question_score": 207, "tags": "sql|database|oracle", "answer_id": 452476, "answer_date": "2009-01-16T23:57:18.960Z", "answer_score": 234 }
Please answer the following Stack Overflow question: Title: How to detect scroll position of page using jQuery <p>I am having trouble with jQuery functionality on my website. What it does, is that it uses the <code>window.scroll()</code> function to recognize when the windows changes its scroll position and at the change calls a few functions to load data from the server.</p> <p>The problem is the <code>.scroll()</code> function is called as soon as there is even a little change in the scroll position and loads data at the bottom; however, what I wish to achieve is to load new data when the scroll/page position reaches at the bottom, like it happens for Facebook feed.</p> <p>But I am not sure how to detect scroll position using jQuery?</p> <pre><code>function getData() { $.getJSON('Get/GetData?no=1', function (responseText) { //Load some data from the server }) }; $(window).scroll(function () { getData(); }); </code></pre>
<p>You can extract the scroll position using jQuery's <a href="http://api.jquery.com/scrollTop/" rel="noreferrer"><code>.scrollTop()</code></a> method</p> <pre><code>$(window).scroll(function (event) { var scroll = $(window).scrollTop(); // Do something }); </code></pre>
{ "question_id": 17441065, "question_date": "2013-07-03T06:24:45.600Z", "question_score": 207, "tags": "javascript|jquery|scroll", "answer_id": 17441121, "answer_date": "2013-07-03T06:28:46.940Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: How can I add double quotes to a string that is inside a variable? <p>I have a string variable such as this:</p> <pre><code>string title = string.empty; </code></pre> <p>I have to display the content of whatever is passed to it inside a <em>div</em> within double quotes. I have written something like this:</p> <pre><code>... ... &lt;div&gt;&quot;+ title +@&quot;&lt;/div&gt; ... ... </code></pre> <p>How can I add the double quotes here? So that it will display like:</p> <pre><code>&quot;How to add double quotes&quot; </code></pre>
<p>You need to escape them by doubling them (verbatim string literal):</p> <pre><code>string str = @"""How to add doublequotes"""; </code></pre> <p>Or with a normal string literal you escape them with a <code>\</code>:</p> <pre><code>string str = "\"How to add doublequotes\""; </code></pre>
{ "question_id": 3905946, "question_date": "2010-10-11T11:57:46.423Z", "question_score": 207, "tags": "c#|asp.net|double-quotes", "answer_id": 3905970, "answer_date": "2010-10-11T12:01:21.597Z", "answer_score": 396 }
Please answer the following Stack Overflow question: Title: Hash Map in Python <p>I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value.</p> <p>How do I implement this functionality in Python?</p> <pre><code>HashMap&lt;String,String&gt; streetno=new HashMap&lt;String,String&gt;(); streetno.put("1", "Sachin Tendulkar"); streetno.put("2", "Dravid"); streetno.put("3","Sehwag"); streetno.put("4","Laxman"); streetno.put("5","Kohli") </code></pre>
<p><a href="http://docs.python.org/library/stdtypes.html#dict" rel="noreferrer">Python dictionary</a> is a built-in type that supports key-value pairs.</p> <pre><code>streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"} </code></pre> <p>as well as using the dict keyword:</p> <pre><code>streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) </code></pre> <p>or:</p> <pre><code>streetno = {} streetno["1"] = "Sachin Tendulkar" </code></pre>
{ "question_id": 8703496, "question_date": "2012-01-02T17:17:10.747Z", "question_score": 207, "tags": "python|hashmap", "answer_id": 8703509, "answer_date": "2012-01-02T17:18:52.447Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: Eclipse error: indirectly referenced from required .class files? <p>I got an error in Eclipse. What does this error message means:</p> <blockquote> <p>The type iglu.ir.TermVector cannot be resolved. It is indirectly referenced from required .class files</p> </blockquote>
<p>It means: "A class that you use needs another class that is not on the classpath." You should make sure (as Harry Joy suggests) to add the required jar to the classpath.</p>
{ "question_id": 5547162, "question_date": "2011-04-05T04:21:11.637Z", "question_score": 207, "tags": "eclipse|eclipse-classpath", "answer_id": 5547680, "answer_date": "2011-04-05T05:39:19.683Z", "answer_score": 209 }
Please answer the following Stack Overflow question: Title: Dynamically creating keys in a JavaScript associative array <p>All the documentation I've found so far is to update keys that are already created:</p> <pre><code> arr['key'] = val; </code></pre> <p>I have a string like this: <code>&quot; name = oscar &quot; </code></p> <p>And I want to end up with something like this:</p> <pre><code>{ name: 'whatever' } </code></pre> <p>That is, split the string and get the first element, and then put that in a dictionary.</p> <h3>Code</h3> <pre><code>var text = ' name = oscar ' var dict = new Array(); var keyValuePair = text.split(' = '); dict[ keyValuePair[0] ] = 'whatever'; alert( dict ); // Prints nothing. </code></pre>
<p>Use the first example. If the key doesn't exist it will be added.</p> <pre><code>var a = new Array(); a['name'] = 'oscar'; alert(a['name']); </code></pre> <p>Will pop up a message box containing 'oscar'.</p> <p>Try:</p> <pre><code>var text = 'name = oscar' var dict = new Array() var keyValuePair = text.replace(/ /g,'').split('='); dict[ keyValuePair[0] ] = keyValuePair[1]; alert( dict[keyValuePair[0]] ); </code></pre>
{ "question_id": 351495, "question_date": "2008-12-09T01:13:34.330Z", "question_score": 207, "tags": "javascript|associative-array", "answer_id": 351507, "answer_date": "2008-12-09T01:19:02.807Z", "answer_score": 149 }
Please answer the following Stack Overflow question: Title: Can we call the function written in one JavaScript in another JS file? <p>Can we call the function written in one JS file in another JS file? Can anyone help me how to call the function from another JS file? </p>
<p>The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.</p> <p>I.e.</p> <p>File1.js</p> <pre><code>function alertNumber(number) { alert(number); } </code></pre> <p>File2.js</p> <pre><code>function alertOne() { alertNumber("one"); } </code></pre> <p>HTML</p> <pre><code>&lt;head&gt; .... &lt;script src="File1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="File2.js" type="text/javascript"&gt;&lt;/script&gt; .... &lt;/head&gt; &lt;body&gt; .... &lt;script type="text/javascript"&gt; alertOne(); &lt;/script&gt; .... &lt;/body&gt; </code></pre> <p><s>The other way won't work.</s> As correctly pointed out by <a href="https://stackoverflow.com/a/3811763/149885">Stuart Wakefield</a>. The other way will also work.</p> <p>HTML</p> <pre><code>&lt;head&gt; .... &lt;script src="File2.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="File1.js" type="text/javascript"&gt;&lt;/script&gt; .... &lt;/head&gt; &lt;body&gt; .... &lt;script type="text/javascript"&gt; alertOne(); &lt;/script&gt; .... &lt;/body&gt; </code></pre> <p>What will not work would be:</p> <p>HTML</p> <pre><code>&lt;head&gt; .... &lt;script src="File2.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; alertOne(); &lt;/script&gt; &lt;script src="File1.js" type="text/javascript"&gt;&lt;/script&gt; .... &lt;/head&gt; &lt;body&gt; .... &lt;/body&gt; </code></pre> <p>Although <code>alertOne</code> is defined when calling it, internally it uses a function that is still not defined (<code>alertNumber</code>).</p>
{ "question_id": 3809862, "question_date": "2010-09-28T05:13:59.627Z", "question_score": 207, "tags": "javascript|include", "answer_id": 3809896, "answer_date": "2010-09-28T05:22:38.970Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: How do I convert an object to an array? <pre><code>&lt;?php print_r($response-&gt;response-&gt;docs); ?&gt; </code></pre> <p>Outputs the following:</p> <pre><code> Array ( [0] =&gt; Object ( [_fields:private] =&gt; Array ( [id]=&gt;9093 [name]=&gt;zahir ) Object ( [_fields:private] =&gt; Array ( [id]=&gt;9094 [name]=&gt;hussain ).. ) ) </code></pre> <p>How can I convert this object to an array? I'd like to output the following:</p> <pre><code>Array ( [0]=&gt; ( [id]=&gt;9093 [name]=&gt;zahir ) [1]=&gt; ( [id]=&gt;9094 [name]=&gt;hussain )... ) </code></pre> <p>Is this possible?</p>
<p>You should look at <a href="http://php.net/manual/function.get-object-vars.php" rel="noreferrer">get_object_vars</a> , as your properties are declared private you should call this inside the class and return its results. </p> <p>Be careful, for primitive data types like strings it will work great, but I don't know how it behaves with nested objects.</p> <p>in your case you have to do something like;</p> <pre><code>&lt;?php print_r(get_object_vars($response-&gt;response-&gt;docs)); ?&gt; </code></pre>
{ "question_id": 2476876, "question_date": "2010-03-19T11:42:32.400Z", "question_score": 207, "tags": "php", "answer_id": 2477159, "answer_date": "2010-03-19T12:23:46.050Z", "answer_score": 136 }
Please answer the following Stack Overflow question: Title: What is the difference between npm install and npm run build? <p>What is the difference between <code>npm install</code> and <code>npm run build</code>?</p> <p>I have noticed in my project that sometimes npm starts failing when <code>npm install</code> is performed, but, upon running <code>npm run build</code>, it works just fine.</p> <p>How do the inner workings of these two targets namely <code>install</code> and <code>run build</code> differ?</p>
<p><code>npm install</code> installs dependencies into the <code>node_modules/</code> directory, for the node project you're working on. You can call <code>install</code> on another node.js project (module), to install it as a dependency for your project.</p> <p><code>npm run build</code> does nothing unless you specify what &quot;build&quot; does in your package.json file. It lets you perform any necessary building/prep tasks for your project, prior to it being used in another project.</p> <p><code>npm build</code> is an internal command and is called by <code>link</code> and <code>install</code> commands, according to <a href="https://docs.npmjs.com/cli/v6/commands/npm-build" rel="nofollow noreferrer">the documentation for build</a>:</p> <blockquote> <p>This is the plumbing command called by npm link and npm install.</p> </blockquote> <p>You will not be calling <code>npm build</code> normally as it is used internally to build native C/C++ Node addons using node-gyp.</p>
{ "question_id": 43664200, "question_date": "2017-04-27T17:19:38.810Z", "question_score": 207, "tags": "node.js|npm|npm-install", "answer_id": 43664456, "answer_date": "2017-04-27T17:35:17.927Z", "answer_score": 153 }
Please answer the following Stack Overflow question: Title: How to append contents of multiple files into one file <p>I want to copy the contents of five files to one file as is. I tried doing it using cp for each file. But that overwrites the contents copied from the previous file. I also tried </p> <pre><code>paste -d "\n" 1.txt 0.txt </code></pre> <p>and it did not work.</p> <p>I want my script to add the newline at the end of each text file.</p> <p>eg. Files 1.txt, 2.txt, 3.txt. Put contents of 1,2,3 in 0.txt</p> <p>How do I do it ?</p>
<p>You need the <code>cat</code> (short for concatenate) command, with shell redirection (<code>&gt;</code>) into your output file </p> <pre><code>cat 1.txt 2.txt 3.txt &gt; 0.txt </code></pre>
{ "question_id": 18006581, "question_date": "2013-08-01T23:54:08.367Z", "question_score": 207, "tags": "linux|bash|unix", "answer_id": 18006605, "answer_date": "2013-08-01T23:56:58.783Z", "answer_score": 366 }
Please answer the following Stack Overflow question: Title: Spring boot - Not a managed type <p>I use Spring boot+JPA and having a problem while starting the service.</p> <pre><code>Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.nervytech.dialer.domain.PhoneSettings at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219) at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.&lt;init&gt;(JpaMetamodelEntityInformation.java:68) at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89) at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69) at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:177) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225) at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562) </code></pre> <p>Here is the Application.java file,</p> <pre><code>@Configuration @ComponentScan @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) @SpringBootApplication public class DialerApplication { public static void main(String[] args) { SpringApplication.run(DialerApplication.class, args); } } </code></pre> <p>I use UCp for connection pooling and the DataSource configuration is below,</p> <pre><code>@Configuration @ComponentScan @EnableTransactionManagement @EnableAutoConfiguration @EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervy.dialer.spring.jpa.repository" }) public class ApplicationDataSource { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory .getLogger(ApplicationDataSource.class); /** The Constant TEST_SQL. */ private static final String TEST_SQL = "select 1 from dual"; /** The pooled data source. */ private PoolDataSource pooledDataSource; </code></pre> <p>UserDetailsService Implementation,</p> <pre><code>@Service("userDetailsService") @SessionAttributes("user") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserService userService; </code></pre> <p>Service layer implementation,</p> <pre><code>@Service public class PhoneSettingsServiceImpl implements PhoneSettingsService { } </code></pre> <p>The repository class,</p> <pre><code>@Repository public interface PhoneSettingsRepository extends JpaRepository&lt;PhoneSettings, Long&gt; { } </code></pre> <p>Entity class,</p> <pre><code>@Entity @Table(name = "phone_settings", catalog = "dialer") public class PhoneSettings implements java.io.Serializable { </code></pre> <p>WebSecurityConfig class,</p> <pre><code>@Configuration @EnableWebMvcSecurity @ComponentScan public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; /** * Instantiates a new web security config. */ public WebSecurityConfig() { super(); } /** * {@inheritDoc} * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) */ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/logoffUser", "/sessionExpired", "/error", "/unauth", "/redirect", "*support*").permitAll() .anyRequest().authenticated().and().rememberMe().and().httpBasic() .and() .csrf() .disable().logout().deleteCookies("JSESSIONID").logoutSuccessUrl("/logoff").invalidateHttpSession(true); } @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } } </code></pre> <p>The packages are as follows,</p> <ol> <li><code>Application</code> class is in - <code>com.nervy.dialer</code></li> <li><code>Datasource</code> class is in - <code>com.nervy.dialer.common</code></li> <li>Entity classes are in - <code>com.nervy.dialer.domain</code></li> <li>Service classes are in - <code>com.nervy.dialer.domain.service.impl</code></li> <li>Controllers are in - <code>com.nervy.dialer.spring.controller</code></li> <li>Repository classes are in - <code>com.nervy.dialer.spring.jpa.repository</code></li> <li><code>WebSecurityConfig</code> is in - <code>com.nervy.dialer.spring.security</code></li> </ol> <p>Thanks</p>
<p>I think replacing <code>@ComponentScan</code> with <code>@ComponentScan("com.nervy.dialer.domain")</code> will work.</p> <p>Edit :</p> <p>I have added a <a href="https://github.com/azizunsal/SpringBoot-BoneCP-PooledDataSource" rel="noreferrer">sample application</a> to demonstrate how to set up a pooled datasource connection with BoneCP. </p> <p>The application has the same structure with yours. I hope this will help you to resolve your configuration problems</p>
{ "question_id": 28664064, "question_date": "2015-02-22T22:28:13.750Z", "question_score": 207, "tags": "spring|spring-mvc|jpa|spring-boot|spring-data", "answer_id": 28668674, "answer_date": "2015-02-23T07:21:03.183Z", "answer_score": 64 }
Please answer the following Stack Overflow question: Title: Getting activity from context in android <p>This one has me stumped.</p> <p>I need to call an activity method from within a custom layout class. The problem with this is that I don't know how to access the activity from within the layout.</p> <h2>ProfileView</h2> <pre><code>public class ProfileView extends LinearLayout { TextView profileTitleTextView; ImageView profileScreenImageButton; boolean isEmpty; ProfileData data; String name; public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData) { super(context, attrs); ...... ...... } //Heres where things get complicated public void onClick(View v) { //Need to get the parent activity and call its method. ProfileActivity x = (ProfileActivity) context; x.activityMethod(); } } </code></pre> <h2>ProfileActivity</h2> <pre><code>public class ProfileActivityActivity extends Activity { //In here I am creating multiple ProfileViews and adding them to the activity dynamically. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile_activity_main); } public void addProfilesToThisView() { ProfileData tempPd = new tempPd(.....) Context actvitiyContext = this.getApplicationContext(); //Profile view needs context, null, name and a profileData ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd); profileLayout.addView(pv); } } </code></pre> <p>As you can see above, I am instantiating the profileView programatically and passing in the activityContext with it. 2 questions:</p> <ol> <li>Am i passing the correct context into the Profileview?</li> <li>How do I get the containing activity from the context?</li> </ol>
<p>From your <code>Activity</code>, just pass in <code>this</code> as the <code>Context</code> for your layout:</p> <pre><code>ProfileView pv = new ProfileView(this, null, temp, tempPd); </code></pre> <p>Afterwards you will have a <code>Context</code> in the layout, but you will know it is actually your <code>Activity</code> and you can cast it so that you have what you need:</p> <pre><code>Activity activity = (Activity) context; </code></pre>
{ "question_id": 9891360, "question_date": "2012-03-27T14:16:53.533Z", "question_score": 207, "tags": "android|android-layout|android-activity|view|hierarchy", "answer_id": 9891449, "answer_date": "2012-03-27T14:21:40.657Z", "answer_score": 500 }
Please answer the following Stack Overflow question: Title: random.seed(): What does it do? <p>I am a bit confused on what <code>random.seed()</code> does in Python. For example, why does the below trials do what they do (consistently)? </p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.seed(9001) &gt;&gt;&gt; random.randint(1, 10) 1 &gt;&gt;&gt; random.randint(1, 10) 3 &gt;&gt;&gt; random.randint(1, 10) 6 &gt;&gt;&gt; random.randint(1, 10) 6 &gt;&gt;&gt; random.randint(1, 10) 7 </code></pre> <p>I couldn't find good documentation on this.</p>
<p>Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.</p> <p>Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.</p> <p>Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.</p>
{ "question_id": 22639587, "question_date": "2014-03-25T15:46:46.820Z", "question_score": 207, "tags": "python|random|random-seed", "answer_id": 22639752, "answer_date": "2014-03-25T15:52:57.770Z", "answer_score": 248 }
Please answer the following Stack Overflow question: Title: Why do I get access denied to data folder when using adb? <p>I connected to my live device using the adb and the following commands:</p> <pre><code>C:\&gt;adb -s HT829GZ52000 shell $ ls ls sqlite_stmt_journals cache sdcard etc system sys sbin proc logo.rle init.trout.rc init.rc init.goldfish.rc init default.prop data root dev $ cd data cd data $ ls ls opendir failed, Permission denied </code></pre> <p>I was surprised to see that I have access denied. How come I can't browse around the directories using the commandline like this?</p> <p>How do I get root access on my phone?</p>
<p>There are two things to remember if you want to browse everything on your device.</p> <ol> <li>You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (<a href="http://en.wikipedia.org/wiki/Android_Dev_Phone#Android_Dev_Phone_1" rel="noreferrer">ADP1</a> or an <a href="http://www.engadget.com/2009/05/27/google-ion-hands-on-and-unboxing/" rel="noreferrer">ION</a> from Google I/O) or you've found a way to 'root' your phone some other way.</li> <li>You need to be running ADB in root mode, do this by executing: <code>adb root</code></li> </ol>
{ "question_id": 1043322, "question_date": "2009-06-25T11:04:43.450Z", "question_score": 207, "tags": "android|adb", "answer_id": 1043722, "answer_date": "2009-06-25T12:50:31.737Z", "answer_score": 151 }
Please answer the following Stack Overflow question: Title: Intellij Cannot resolve symbol on import <p>This problem happens intermittently for different libraries and different projects. When trying to import a library, the package will be recognized, but the class name can't be resolved.</p> <p>If on the import statement, I <code>right-click -&gt; Goto -&gt; the package's declaration</code>, I see all the decompiled classes displayed in the side pane -- Including the ones I need -- If I try to auto-complete the import statement, I notice the class I need is not featured in the dropdown.</p> <p>I tried invalidating caches already, doesn't work. I cannot find any class conflicts -- there is no other jar file in my classpath with the same package name. I am able to import this class into other projects.</p> <p>Please see screen shots:</p> <p><a href="https://i.stack.imgur.com/WwQ5f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WwQ5fl.png" alt="" /></a></p> <p><a href="https://i.stack.imgur.com/6OXn2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6OXn2l.png" alt="" /></a></p> <p>Anyone have a clue?</p>
<p>There can be multiple reasons for this. In my case it was wrong source root issue. Invalidate caches didn't work along with other solutions.</p> <p>Check your module source roots.</p> <ol> <li><p>Project Structure (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>S</kbd>).</p></li> <li><p>Modules</p></li> <li><p>Select your problem module.</p></li> <li><p>Change tab on top of window "Sources".</p></li> <li><p>Remove unwanted source roots. Keep one and add src and test source roots in this root.</p></li> </ol>
{ "question_id": 26952078, "question_date": "2014-11-15T23:39:32.130Z", "question_score": 207, "tags": "java|intellij-idea|import|classpath", "answer_id": 32999210, "answer_date": "2015-10-07T17:54:58.477Z", "answer_score": 54 }
Please answer the following Stack Overflow question: Title: How to get a random value from dictionary? <p>How can I get a random pair from a <code>dict</code>? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.</p> <p>The <code>dict</code> looks like <code>{'VENEZUELA':'CARACAS'}</code></p> <p>How can I do this?</p>
<p>One way would be:</p> <pre><code>import random d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'} random.choice(list(d.values())) </code></pre> <p><strong>EDIT</strong>: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:</p> <pre><code>country, capital = random.choice(list(d.items())) </code></pre>
{ "question_id": 4859292, "question_date": "2011-02-01T05:37:05.667Z", "question_score": 207, "tags": "python|random|dictionary|key", "answer_id": 4859322, "answer_date": "2011-02-01T05:40:50.213Z", "answer_score": 350 }
Please answer the following Stack Overflow question: Title: PHP substring extraction. Get the string before the first '/' or the whole string <p>I am trying to extract a substring. I need some help with doing it in PHP.</p> <p>Here are some sample strings I am working with and the results I need: </p> <pre><code>home/cat1/subcat2 =&gt; home test/cat2 =&gt; test startpage =&gt; startpage </code></pre> <p>I want to get the string till the first <code>/</code>, but if no <code>/</code> is present, get the whole string.</p> <p>I tried,</p> <pre><code>substr($mystring, 0, strpos($mystring, '/')) </code></pre> <p>I think it says - get the position of <code>/</code> and then get the substring from position 0 to <em>that</em> position.</p> <p>I don't know how to handle the case where there is no <code>/</code>, without making the statement too big.</p> <p>Is there a way to handle that case also without making the PHP statement too complex?</p>
<p>Use <a href="http://php.net/explode"><code>explode()</code></a></p> <pre><code>$arr = explode("/", $string, 2); $first = $arr[0]; </code></pre> <p>In this case, I'm using the <code>limit</code> parameter to <code>explode</code> so that php won't scan the string any more than what's needed.</p>
{ "question_id": 1935918, "question_date": "2009-12-20T14:07:02.017Z", "question_score": 207, "tags": "php|string|substring", "answer_id": 1935929, "answer_date": "2009-12-20T14:11:03.063Z", "answer_score": 296 }
Please answer the following Stack Overflow question: Title: Groovy executing shell commands <p>Groovy adds the <code>execute</code> method to <code>String</code> to make executing shells fairly easy;</p> <pre><code>println "ls".execute().text </code></pre> <p>but if an error happens, then there is no resulting output. <strong>Is there an easy way to get both the standard error and standard out?</strong> (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)</p> <p>It would be nice to have something like;</p> <pre><code> def x = shellDo("ls /tmp/NoFile") println "out: ${x.out} err:${x.err}" </code></pre>
<p>Ok, solved it myself;</p> <pre><code>def sout = new StringBuilder(), serr = new StringBuilder() def proc = 'ls /badDir'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println &quot;out&gt; $sout\nerr&gt; $serr&quot; </code></pre> <p>displays:</p> <p><code>out&gt; err&gt; ls: cannot access /badDir: No such file or directory</code></p>
{ "question_id": 159148, "question_date": "2008-10-01T18:54:39.320Z", "question_score": 207, "tags": "groovy", "answer_id": 159270, "answer_date": "2008-10-01T19:20:26.123Z", "answer_score": 267 }
Please answer the following Stack Overflow question: Title: Right way to reverse a pandas DataFrame? <p>Here is my code:</p> <pre><code>import pandas as pd data = pd.DataFrame({'Odd':[1,3,5,6,7,9], 'Even':[0,2,4,6,8,10]}) for i in reversed(data): print(data['Odd'], data['Even']) </code></pre> <p>When I run this code, i get the following error:</p> <pre><code>Traceback (most recent call last): File "C:\Python33\lib\site-packages\pandas\core\generic.py", line 665, in _get_item_cache return cache[item] KeyError: 5 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\*****\Documents\******\********\****.py", line 5, in &lt;module&gt; for i in reversed(data): File "C:\Python33\lib\site-packages\pandas\core\frame.py", line 2003, in __getitem__ return self._get_item_cache(key) File "C:\Python33\lib\site-packages\pandas\core\generic.py", line 667, in _get_item_cache values = self._data.get(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1656, in get _, block = self._find_block(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1936, in _find_block self._check_have(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1943, in _check_have raise KeyError('no item named %s' % com.pprint_thing(item)) KeyError: 'no item named 5' </code></pre> <p><strong>Why am I getting this error?<br> How can I fix that?<br> What is the right way to reverse <code>pandas.DataFrame</code>?</strong></p>
<pre><code>data.reindex(index=data.index[::-1]) </code></pre> <p>or simply:</p> <pre><code>data.iloc[::-1] </code></pre> <p>will reverse your data frame, if you want to have a <code>for</code> loop which goes from down to up you may do:</p> <pre><code>for idx in reversed(data.index): print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd']) </code></pre> <p>or</p> <pre><code>for idx in reversed(data.index): print(idx, data.Even[idx], data.Odd[idx]) </code></pre> <p>You are getting an error because <code>reversed</code> first calls <code>data.__len__()</code> which returns 6. Then it tries to call <code>data[j - 1]</code> for <code>j</code> in <code>range(6, 0, -1)</code>, and the first call would be <code>data[5]</code>; but in pandas dataframe <code>data[5]</code> means column 5, and there is no column 5 so it will throw an exception. ( see <a href="http://docs.python.org/2/library/functions.html#reversed">docs</a> )</p>
{ "question_id": 20444087, "question_date": "2013-12-07T17:07:58.993Z", "question_score": 207, "tags": "python|pandas|reverse", "answer_id": 20444256, "answer_date": "2013-12-07T17:24:42.637Z", "answer_score": 403 }
Please answer the following Stack Overflow question: Title: Reasons for using the set.seed function <p>Many times I have seen the <code>set.seed</code> function in R, before starting the program. I know it's basically used for the random number generation. Is there any specific need to set this? </p>
<p>The need is the possible desire for reproducible results, which may for example come from trying to debug your program, or of course from trying to redo what it does:</p> <p>These two results we will "never" reproduce as I just asked for something "random":</p> <pre><code>R&gt; sample(LETTERS, 5) [1] "K" "N" "R" "Z" "G" R&gt; sample(LETTERS, 5) [1] "L" "P" "J" "E" "D" </code></pre> <p>These two, however, are identical <em>because I set the seed</em>:</p> <pre><code>R&gt; set.seed(42); sample(LETTERS, 5) [1] "X" "Z" "G" "T" "O" R&gt; set.seed(42); sample(LETTERS, 5) [1] "X" "Z" "G" "T" "O" R&gt; </code></pre> <p>There is vast literature on all that; Wikipedia is a good start. In essence, these RNGs are called Pseudo Random Number Generators because they are in fact <em>fully algorithmic</em>: given the same seed, you get the same sequence. And that <em>is a feature</em> and not a bug.</p>
{ "question_id": 13605271, "question_date": "2012-11-28T12:39:04.507Z", "question_score": 207, "tags": "r|random", "answer_id": 13605506, "answer_date": "2012-11-28T12:52:17.233Z", "answer_score": 299 }
Please answer the following Stack Overflow question: Title: Error: Cannot pull with rebase: You have unstaged changes <p>I have started collaborating with a few friends on a project &amp; they use the heroku git repository.</p> <p>I cloned the repository a few days ago and they have since made some changes so I am trying to get the latest updates</p> <p>I ran the <code>git pull --rebase</code> command as stated here(Is this the right way to do it?): <a href="https://devcenter.heroku.com/articles/sharing#merging-code-changes">https://devcenter.heroku.com/articles/sharing#merging-code-changes</a></p> <p>I get the following error:</p> <pre><code>$ git pull --rebase Cannot pull with rebase: You have unstaged changes. Please commit or stash them. </code></pre> <p>My guess is that I messed around with the code and now it wants me to either commit or discard(is that what does stash means?) the changes. Is this what is happening? If this is the case I would like to discard any changes I might have made and just get the updated code from the git repository. </p> <p>Any idea of what I can do?</p>
<p>Do <code>git status</code>, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do <code>git checkout -- &lt;file name&gt;</code> or <code>git reset --hard</code> to get rid of the changes.</p> <p>For the most part, git will tell you what to do about changes. For example, your error message said to <code>git stash</code> your changes. This would be if you wanted to keep them. After pulling, you would then do <code>git stash pop</code> and your changes would be reapplied.</p> <p><code>git status</code> also has how to get rid of changes depending on if the file is staged for commit or not. </p>
{ "question_id": 23517464, "question_date": "2014-05-07T12:12:04.567Z", "question_score": 207, "tags": "git|heroku|pull", "answer_id": 23517643, "answer_date": "2014-05-07T12:20:19.460Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: Automatically deleting related rows in Laravel (Eloquent ORM) <p>When I delete a row using this syntax:</p> <pre><code>$user-&gt;delete(); </code></pre> <p>Is there a way to attach a callback of sorts, so that it would e.g. do this automatically:</p> <pre><code>$this-&gt;photo()-&gt;delete(); </code></pre> <p>Preferably inside the model-class.</p>
<p>I believe this is a perfect use-case for Eloquent events (<a href="http://laravel.com/docs/eloquent#model-events" rel="noreferrer">http://laravel.com/docs/eloquent#model-events</a>). You can use the "deleting" event to do the cleanup:</p> <p> <pre><code>class User extends Eloquent { public function photos() { return $this-&gt;has_many('Photo'); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method call this $user-&gt;photos()-&gt;delete(); // do the rest of the cleanup... }); } } </code></pre> <p>You should probably also put the whole thing inside a transaction, to ensure the referential integrity..</p>
{ "question_id": 14174070, "question_date": "2013-01-05T16:55:28.967Z", "question_score": 207, "tags": "php|laravel|eloquent|eloquent-relationship", "answer_id": 20108037, "answer_date": "2013-11-20T22:05:56.767Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Angular + Material - How to refresh a data source (mat-table) <p>I am using a <a href="https://material.angular.io/components/table/overview" rel="noreferrer">mat-table</a> to list the content of the users chosen languages. They can also add new languages using dialog panel. After they added a language and returned back. I want my datasource to refresh to show the changes they made. </p> <p>I initialize the datastore by getting user data from a service and passing that into a datasource in the refresh method.</p> <p><strong>Language.component.ts</strong></p> <pre class="lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core'; import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model'; import { LanguageAddComponent } from './language-add/language-add.component'; import { AuthService } from '../../../../services/auth.service'; import { LanguageDataSource } from './language-data-source'; import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component'; import { DataSource } from '@angular/cdk/collections'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { MatSnackBar, MatDialog } from '@angular/material'; @Component({ selector: 'app-language', templateUrl: './language.component.html', styleUrls: ['./language.component.scss'] }) export class LanguageComponent implements OnInit { displayedColumns = ['name', 'native', 'code', 'level']; teachDS: any; user: any; constructor(private authService: AuthService, private dialog: MatDialog) { } ngOnInit() { this.refresh(); } add() { this.dialog.open(LanguageAddComponent, { data: { user: this.user }, }).afterClosed().subscribe(result =&gt; { this.refresh(); }); } refresh() { this.authService.getAuthenticatedUser().subscribe((res) =&gt; { this.user = res; this.teachDS = new LanguageDataSource(this.user.profile.languages.teach); }); } } </code></pre> <p><strong>language-data-source.ts</strong></p> <pre class="lang-js prettyprint-override"><code>import {MatPaginator, MatSort} from '@angular/material'; import {DataSource} from '@angular/cdk/collections'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; import 'rxjs/add/operator/map'; export class LanguageDataSource extends DataSource&lt;any&gt; { constructor(private languages) { super(); } connect(): Observable&lt;any&gt; { return Observable.of(this.languages); } disconnect() { // No-op } } </code></pre> <p>So I have tried to call a refresh method where I get the user from the backend again and then I reinitialize the data source. However this does not work, no changes are occurring.</p>
<p>Trigger a change detection by using <a href="https://angular.io/api/core/ChangeDetectorRef" rel="noreferrer"><code>ChangeDetectorRef</code></a> in the <code>refresh()</code> method just after receiving the new data, inject <a href="https://angular.io/api/core/ChangeDetectorRef" rel="noreferrer">ChangeDetectorRef</a> in the constructor and use <a href="https://angular.io/api/core/ChangeDetectorRef#detectChanges" rel="noreferrer">detectChanges</a> like this:</p> <pre class="lang-js prettyprint-override"><code>import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model'; import { LanguageAddComponent } from './language-add/language-add.component'; import { AuthService } from '../../../../services/auth.service'; import { LanguageDataSource } from './language-data-source'; import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component'; import { DataSource } from '@angular/cdk/collections'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { MatSnackBar, MatDialog } from '@angular/material'; @Component({ selector: 'app-language', templateUrl: './language.component.html', styleUrls: ['./language.component.scss'] }) export class LanguageComponent implements OnInit { displayedColumns = ['name', 'native', 'code', 'level']; teachDS: any; user: any; constructor(private authService: AuthService, private dialog: MatDialog, private changeDetectorRefs: ChangeDetectorRef) { } ngOnInit() { this.refresh(); } add() { this.dialog.open(LanguageAddComponent, { data: { user: this.user }, }).afterClosed().subscribe(result =&gt; { this.refresh(); }); } refresh() { this.authService.getAuthenticatedUser().subscribe((res) =&gt; { this.user = res; this.teachDS = new LanguageDataSource(this.user.profile.languages.teach); this.changeDetectorRefs.detectChanges(); }); } } </code></pre>
{ "question_id": 46746598, "question_date": "2017-10-14T16:10:09.820Z", "question_score": 207, "tags": "angular|angular-material|refresh", "answer_id": 46746905, "answer_date": "2017-10-14T16:39:25.517Z", "answer_score": 81 }
Please answer the following Stack Overflow question: Title: Making the main scrollbar always visible <p>What CSS is required to make the browser's vertical scrollbar remain visible when a user visits a web page (when the page hasn't enough content to trigger the scrollbar's activation)?</p>
<pre><code>html { overflow: -moz-scrollbars-vertical; overflow-y: scroll; } </code></pre> <p>This makes the scrollbar always visible and only active when needed.</p> <p><strong>Update</strong>: If the above does not work then just using this may.</p> <pre><code>html { overflow-y:scroll; } </code></pre>
{ "question_id": 1202425, "question_date": "2009-07-29T19:12:33.210Z", "question_score": 207, "tags": "html|css|xhtml", "answer_id": 1202542, "answer_date": "2009-07-29T19:36:28.673Z", "answer_score": 374 }
Please answer the following Stack Overflow question: Title: How to keep the console window open in Visual C++? <p>I'm starting out in Visual C++ and I'd like to know how to keep the console window.</p> <p>For instance this would be a typical "hello world" application: </p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { cout &lt;&lt; "Hello World"; return 0; } </code></pre> <p>What's the line I'm missing?</p>
<p>Start the project with <kbd>Ctrl</kbd>+<kbd>F5</kbd> instead of just <kbd>F5</kbd>.</p> <p>The console window will now stay open with the <code>Press any key to continue . . .</code> message after the program exits.</p> <p>Note that this requires the <code>Console (/SUBSYSTEM:CONSOLE)</code> linker option, which you can enable as follows:</p> <ol> <li>Open up your project, and go to the Solution Explorer. If you're following along with me in K&amp;R, your &quot;Solution&quot; will be 'hello' with 1 project under it, also 'hello' in bold.</li> <li>Right click on the 'hello&quot; (or whatever your project name is.)</li> <li>Choose &quot;Properties&quot; from the context menu.</li> <li>Choose Configuration Properties&gt;Linker&gt;System.</li> <li>For the &quot;Subsystem&quot; property in the right-hand pane, click the drop-down box in the right hand column.</li> <li>Choose &quot;Console (/SUBSYSTEM:CONSOLE)&quot;</li> <li>Click Apply, wait for it to finish doing whatever it does, then click OK. (If &quot;Apply&quot; is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)</li> </ol> <p>CTRL-F5 and the subsystem hints work together; they are not separate options.</p> <p>(Courtesy of DJMorreTX from <a href="http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6</a>)</p>
{ "question_id": 454681, "question_date": "2009-01-18T05:00:22.623Z", "question_score": 207, "tags": "visual-c++|console", "answer_id": 1152873, "answer_date": "2009-07-20T10:53:43.143Z", "answer_score": 407 }
Please answer the following Stack Overflow question: Title: How to import local packages without gopath <p>I've used <code>GOPATH</code> but for this current issue I'm facing it does not help. I want to be able to create packages that are specific to a project:</p> <pre><code>myproject/ ├── binary1.go ├── binary2.go ├── package1.go └── package2.go </code></pre> <p>I tried multiple ways but how do I get <code>package1.go</code> to work in the <code>binary1.go</code> or the <code>binary2.go</code> and so on?</p> <p>For example; I want to be able to <code>import "package1"</code> and then be able to run <code>go build binary1.go</code> and everything works fine without the error being thrown that the package cannot be found on <code>GOROOT</code> or <code>GOPATH</code>. The reason why I need this kind of functionality is for large scale projects; I do not want to have to reference multiple other packages or keep them in one large file.</p>
<p>Go dependency management summary:</p> <ul> <li><code>vgo</code> if your go version is: <code>x &gt;= go 1.11</code></li> <li><code>dep</code> or <code>vendor</code> if your go version is: <code>go 1.6 &gt;= x &lt; go 1.11</code></li> <li>Manually if your go version is: <code>x &lt; go 1.6</code></li> </ul> <hr> <p>Edit 3: Go 1.11 has a feature <code>vgo</code> which will <a href="https://github.com/golang/go/wiki/vgo#current-state" rel="noreferrer">replace</a> <code>dep</code>.</p> <p>To use <code>vgo</code>, see <a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">Modules</a> documentation. TLDR below:</p> <pre><code>export GO111MODULE=on go mod init go mod vendor # if you have vendor/ folder, will automatically integrate go build </code></pre> <p>This method creates a file called <code>go.mod</code> in your projects directory. You can then build your project with <code>go build</code>. If <code>GO111MODULE=auto</code> is set, then your project cannot be in <code>$GOPATH</code>.</p> <hr> <p>Edit 2: The vendoring method is still valid and works without issue. <code>vendor</code> is largely a manual process, because of this <code>dep</code> and <code>vgo</code> were created.</p> <hr> <p>Edit 1: While my old way works it's not longer the "correct" way to do it. You should be using <strong>vendor</strong> capabilities, <code>vgo</code>, or <code>dep</code> (for now) that are enabled by default in Go 1.6; <a href="https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo/edit?pref=2&amp;pli=1" rel="noreferrer">see</a>. You basically add your "external" or "dependent" packages within a <code>vendor</code> directory; upon compilation the compiler will use these packages first.</p> <hr> <p>Found. I was able import local package with <code>GOPATH</code> by creating a subfolder of <code>package1</code> and then importing with <code>import "./package1"</code> in <code>binary1.go</code> and <code>binary2.go</code> scripts like this :</p> <p>binary1.go </p> <pre><code>... import ( "./package1" ) ... </code></pre> <p>So my current directory structure looks like this:</p> <pre><code>myproject/ ├── binary1.go ├── binary2.go ├── package1/ │ └── package1.go └── package2.go </code></pre> <p>I should also note that relative paths (at least in go 1.5) also work; for example:</p> <pre><code>import "../packageX" </code></pre>
{ "question_id": 17539407, "question_date": "2013-07-09T03:28:54.053Z", "question_score": 207, "tags": "go|package", "answer_id": 17539525, "answer_date": "2013-07-09T03:43:35.570Z", "answer_score": 184 }
Please answer the following Stack Overflow question: Title: AccessDenied for ListObjects for S3 bucket when permissions are s3:* <p>I am getting: </p> <blockquote> <p>An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied </p> </blockquote> <p>When I try to get folder from my S3 bucket.</p> <p>Using this command: </p> <pre><code>aws s3 cp s3://bucket-name/data/all-data/ . --recursive </code></pre> <p>The IAM permissions for the bucket look like this:</p> <pre><code>{ "Version": "version_id", "Statement": [ { "Sid": "some_id", "Effect": "Allow", "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::bucketname/*" ] } ] } </code></pre> <p>What do I need to change to be able to <code>copy</code> and <code>ls</code> successfully?</p>
<p>You have given permission to perform commands on objects inside the S3 bucket, but you have not given permission to perform any actions on the bucket itself.</p> <p>Slightly modifying your policy would look like this:</p> <pre><code>{ "Version": "version_id", "Statement": [ { "Sid": "some_id", "Effect": "Allow", "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::bucketname", "arn:aws:s3:::bucketname/*" ] } ] } </code></pre> <p>However, that probably gives more permission than is needed. Following the AWS IAM best practice of <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege" rel="noreferrer">Granting Least Privilege</a> would look something like this:</p> <pre><code>{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::bucketname" ] }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::bucketname/*" ] } ] } </code></pre>
{ "question_id": 38774798, "question_date": "2016-08-04T18:26:08.907Z", "question_score": 207, "tags": "amazon-web-services|amazon-s3|amazon-iam", "answer_id": 38775442, "answer_date": "2016-08-04T19:04:31.160Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: Detect if value is number in MySQL <p>Is there a way to detect if a value is a number in a MySQL query? Such as</p> <pre><code>SELECT * FROM myTable WHERE isANumber(col1) = true </code></pre>
<p>This should work in most cases.</p> <pre><code>SELECT * FROM myTable WHERE concat('',col1 * 1) = col1 </code></pre> <p>It doesn't work for non-standard numbers like</p> <ul> <li><code>1e4</code></li> <li><code>1.2e5</code></li> <li><code>123.</code> (trailing decimal)</li> </ul>
{ "question_id": 5064977, "question_date": "2011-02-21T10:44:29.397Z", "question_score": 207, "tags": "mysql|sql|where-clause", "answer_id": 5065007, "answer_date": "2011-02-21T10:47:30.920Z", "answer_score": 292 }
Please answer the following Stack Overflow question: Title: How to center div vertically inside of absolutely positioned parent div <p>I am trying to get blue container in the middle of pink one, however seems <code>vertical-align: middle;</code> doesn't do the job in that case.</p> <pre><code>&lt;div style="display: block; position: absolute; left: 50px; top: 50px;"&gt; &lt;div style="text-align: left; position: absolute;height: 56px;vertical-align: middle;background-color: pink;"&gt; &lt;div style="background-color: lightblue;"&gt;test&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/s663O.png" alt="enter image description here"></p> <p>Expectation:</p> <p><img src="https://i.stack.imgur.com/OOIIO.png" alt="enter image description here"></p> <p>Please suggest how can I achieve that. </p> <p><a href="http://jsfiddle.net/kqmp1z9m/">Jsfiddle</a></p>
<p>First of all note that <code>vertical-align</code> is only applicable to table cells and inline-level elements.</p> <p>There are couple of ways to achieve vertical alignments which may or may not meet your needs. However I'll show you <a href="https://stackoverflow.com/questions/8508275/how-to-center-a-position-absolute-element/25776315#25776315">two</a> <a href="https://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a-div-with-responsive-height/18516474#18516474">methods</a> from my favorites:</p> <h1>1. Using <code>transform</code> and <code>top</code></h1> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.valign { position: relative; top: 50%; transform: translateY(-50%); /* vendor prefixes omitted due to brevity */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="position: absolute; left: 50px; top: 50px;"&gt; &lt;div style="text-align: left; position: absolute;height: 56px;background-color: pink;"&gt; &lt;div class="valign" style="background-color: lightblue;"&gt;test&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The key point is that a percentage value on <code>top</code> is relative to the <code>height</code> of the containing block; While a percentage value on <code>transform</code>s is relative to the size of the box itself (the bounding box).</p> <p>If you experience <a href="http://www.useragentman.com/blog/2014/05/04/fixing-typography-inside-of-2-d-css-transforms/" rel="noreferrer">font rendering issues</a> (blurry font), the fix is to add <code>perspective(1px)</code> to the <code>transform</code> declaration so it becomes:</p> <pre><code>transform: perspective(1px) translateY(-50%); </code></pre> <p>It's worth noting that CSS <code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform#Browser_compatibility" rel="noreferrer">is supported in IE9+</a>.</p> <h1>2. Using <code>inline-block</code> (pseudo-)elements</h1> <p>In this method, we have two sibling <code>inline-block</code> elements which are aligned vertically at the middle by <code>vertical-align: middle</code> declaration.</p> <p>One of them has a <code>height</code> of <code>100%</code> of its parent and the other is our desired element whose we wanted to align it at the middle.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { text-align: left; position: absolute; height: 56px; background-color: pink; white-space: nowrap; font-size: 0; /* remove the gap between inline level elements */ } .dummy-child { height: 100%; } .valign { font-size: 16px; /* re-set the font-size */ } .dummy-child, .valign { display: inline-block; vertical-align: middle; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="position: absolute; left: 50px; top: 50px;"&gt; &lt;div class="parent"&gt; &lt;div class="dummy-child"&gt;&lt;/div&gt; &lt;div class="valign" style="background-color: lightblue;"&gt;test&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Finally, we should use one of the <a href="https://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements">available methods to remove the gap between inline-level elements</a>.</p>
{ "question_id": 28455100, "question_date": "2015-02-11T13:03:26.117Z", "question_score": 207, "tags": "html|css|vertical-alignment|absolute", "answer_id": 28456704, "answer_date": "2015-02-11T14:24:22.990Z", "answer_score": 470 }
Please answer the following Stack Overflow question: Title: How can I use getSystemService in a non-activity class (LocationManager)? <p>I'm having trouble offloading tasks from the main Activities OnCreate method onto another class to do the heavy lifting.</p> <p>When I try to call getSystemService from the non-Activity class an exception is thrown.</p> <p>Any help would be greatly appreciated :)</p> <p>lmt.java:</p> <pre><code>package com.atClass.lmt; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.location.Location; public class lmt extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fyl lfyl = new fyl(); Location location = lfyl.getLocation(); String latLongString = lfyl.updateWithNewLocation(location); TextView myLocationText = (TextView)findViewById(R.id.myLocationText); myLocationText.setText("Your current position is:\n" + latLongString); } } </code></pre> <p>fyl.java</p> <pre><code>package com.atClass.lmt; import android.app.Activity; import android.os.Bundle; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.content.Context; public class fyl { public Location getLocation(){ LocationManager locationManager; String context = Context.LOCATION_SERVICE; locationManager = (LocationManager)getSystemService(context); String provider = LocationManager.GPS_PROVIDER; Location location = locationManager.getLastKnownLocation(provider); return location; } public String updateWithNewLocation(Location location) { String latLongString; if (location != null){ double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat:" + lat + "\nLong:" + lng; }else{ latLongString = "No Location"; } return latLongString; } } </code></pre>
<p>You need to pass your context to your fyl class..<br> One solution is make a constructor like this for your <code>fyl</code> class:</p> <pre><code>public class fyl { Context mContext; public fyl(Context mContext) { this.mContext = mContext; } public Location getLocation() { -- locationManager = (LocationManager)mContext.getSystemService(context); -- } } </code></pre> <p>So in your activity class create the object of fyl in <code>onCreate</code> function like this:</p> <pre><code>package com.atClass.lmt; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.location.Location; public class lmt extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fyl lfyl = new fyl(this); //Here the context is passing Location location = lfyl.getLocation(); String latLongString = lfyl.updateWithNewLocation(location); TextView myLocationText = (TextView)findViewById(R.id.myLocationText); myLocationText.setText("Your current position is:\n" + latLongString); } } </code></pre>
{ "question_id": 4870667, "question_date": "2011-02-02T04:03:46.923Z", "question_score": 207, "tags": "android", "answer_id": 4870714, "answer_date": "2011-02-02T04:14:12.133Z", "answer_score": 307 }
Please answer the following Stack Overflow question: Title: How do I create a random alpha-numeric string in C++? <p>I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string.</p> <p>How do I do this in C++?</p>
<p>Mehrdad Afshari's <a href="https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c#440147">answer</a> would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:</p> <pre><code>#include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;unistd.h&gt; std::string gen_random(const int len) { static const char alphanum[] = &quot;0123456789&quot; &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot; &quot;abcdefghijklmnopqrstuvwxyz&quot;; std::string tmp_s; tmp_s.reserve(len); for (int i = 0; i &lt; len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } return tmp_s; } int main(int argc, char *argv[]) { srand((unsigned)time(NULL) * getpid()); std::cout &lt;&lt; gen_random(12) &lt;&lt; &quot;\n&quot;; return 0; } </code></pre> <p>Note that <code>rand</code> <a href="https://stackoverflow.com/a/19666713/6243352">generates poor-quality random numbers</a>.</p>
{ "question_id": 440133, "question_date": "2009-01-13T18:16:30.373Z", "question_score": 207, "tags": "c++|string|random", "answer_id": 440240, "answer_date": "2009-01-13T18:41:30.260Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: scrollIntoView Scrolls just too far <p>I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.</p> <p>When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.</p> <p>I am using this code to make it move the selected option to the top of the div:</p> <pre><code>var pathArray = window.location.pathname.split( '/' ); var el = document.getElementById(pathArray[5]); el.scrollIntoView(true); </code></pre> <p>It moves it to the top of the div but about 10 pixels too far up. Anyone know how to fix that?</p>
<p>If it's about 10px, then I guess you could simply manually adjust the containing <code>div</code>'s scroll offset like that:</p> <pre><code>el.scrollIntoView(true); document.getElementById("containingDiv").scrollTop -= 10; </code></pre>
{ "question_id": 24665602, "question_date": "2014-07-10T00:09:42.543Z", "question_score": 207, "tags": "javascript|dom|scroll", "answer_id": 24665651, "answer_date": "2014-07-10T00:16:18.780Z", "answer_score": 70 }
Please answer the following Stack Overflow question: Title: Using GPU from a docker container? <p>I'm searching for a way to use the GPU from inside a docker container.</p> <p>The container will execute arbitrary code so i don't want to use the privileged mode.</p> <p>Any tips? </p> <p>From previous research i understood that <code>run -v</code> and/or LXC <code>cgroup</code> was the way to go but i'm not sure how to pull that off exactly</p>
<p>Writing an updated answer since most of the already present answers are obsolete as of now.</p> <p>Versions earlier than <code>Docker 19.03</code> used to require <code>nvidia-docker2</code> and the <code>--runtime=nvidia</code> flag. </p> <p>Since <strong><code>Docker 19.03</code></strong>, you need to install <code>nvidia-container-toolkit</code> package and then use the <code>--gpus all</code> flag.</p> <p>So, here are the basics,</p> <p><strong>Package Installation</strong></p> <p>Install the <code>nvidia-container-toolkit</code> package as per <a href="https://github.com/NVIDIA/nvidia-docker" rel="noreferrer">official documentation at Github</a>.</p> <p>For Redhat based OSes, execute the following set of commands:</p> <pre><code>$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID) $ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo $ sudo yum install -y nvidia-container-toolkit $ sudo systemctl restart docker </code></pre> <p>For Debian based OSes, execute the following set of commands:</p> <pre><code># Add the package repositories $ distribution=$(. /etc/os-release;echo $ID$VERSION_ID) $ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - $ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list $ sudo apt-get update &amp;&amp; sudo apt-get install -y nvidia-container-toolkit $ sudo systemctl restart docker </code></pre> <p><strong>Running the docker with GPU support</strong></p> <pre><code>docker run --name my_all_gpu_container --gpus all -t nvidia/cuda </code></pre> <p>Please note, the flag <code>--gpus all</code> is used to assign all available gpus to the docker container.</p> <p>To assign specific gpu to the docker container (in case of multiple GPUs available in your machine)</p> <pre><code>docker run --name my_first_gpu_container --gpus device=0 nvidia/cuda </code></pre> <p>Or</p> <pre><code>docker run --name my_first_gpu_container --gpus '"device=0"' nvidia/cuda </code></pre>
{ "question_id": 25185405, "question_date": "2014-08-07T14:41:34.047Z", "question_score": 207, "tags": "cuda|docker", "answer_id": 58432877, "answer_date": "2019-10-17T12:39:03.790Z", "answer_score": 122 }
Please answer the following Stack Overflow question: Title: Find the IP address of the client in an SSH session <p>I have a script that is to be run by a person that logs in to the server with <a href="http://en.wikipedia.org/wiki/Secure_Shell" rel="noreferrer">SSH</a>.</p> <p>Is there a way to find out automatically what IP address the user is connecting from?</p> <p>Of course, I could ask the user (it is a tool for programmers, so no problem with that), but it would be cooler if I just found out.</p>
<p>Check if there is an environment variable called:</p> <pre><code>$SSH_CLIENT </code></pre> <p>OR</p> <pre><code>$SSH_CONNECTION </code></pre> <p>(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.</p> <p>Extract the IP:</p> <pre><code>$ echo $SSH_CLIENT | awk '{ print $1}' 1.2.3.4 $ echo $SSH_CONNECTION | awk '{print $1}' 1.2.3.4 </code></pre>
{ "question_id": 996231, "question_date": "2009-06-15T13:50:16.823Z", "question_score": 207, "tags": "linux|networking|ssh|ip-address", "answer_id": 996286, "answer_date": "2009-06-15T14:01:47.590Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Detect URLs in text with JavaScript <p>Does anyone have suggestions for detecting URLs in a set of strings?</p> <pre><code>arrayOfStrings.forEach(function(string){ // detect URLs in strings and do something swell, // like creating elements with links. }); </code></pre> <p><strong>Update:</strong> I wound up using this regex for link detection… Apparently several years later.</p> <pre><code>kLINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&amp;amp;]*)?)?(#[a-zA-Z0-9!$&amp;'()*+.=-_~:@/?]*)?)(\s+|$)/gi </code></pre> <p>The full helper (with optional Handlebars support) is at <a href="https://gist.github.com/1654670" rel="noreferrer">gist #1654670</a>.</p>
<p>First you need a good regex that matches urls. This is hard to do. See <a href="https://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript/1411800#1411800">here</a>, <a href="https://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python/827621#827621">here</a> and <a href="https://stackoverflow.com/questions/226505/question-about-url-validation-with-regex/226709#226709">here</a>:</p> <blockquote> <p>...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.</p> <p>Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible. </p> <p>For example <code>:::::</code> is a valid URL. The path is <code>":::::"</code>. A pretty stupid filename, but a valid filename.</p> <p>Also, <code>/////</code> is a valid URL. The netloc ("hostname") is <code>""</code>. The path is <code>"///"</code>. Again, stupid. Also valid. This URL normalizes to <code>"///"</code> which is the equivalent.</p> <p>Something like <code>"bad://///worse/////"</code> is perfectly valid. Dumb but valid.</p> </blockquote> <p>Anyway, this answer is not meant to give you the best regex but rather a proof of how to do the string wrapping inside the text, with JavaScript.</p> <p>OK so lets just use this one: <code>/(https?:\/\/[^\s]+)/g</code></p> <p>Again, <em>this is a bad regex</em>. It will have many false positives. However it's good enough for this example.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function urlify(text) { var urlRegex = /(https?:\/\/[^\s]+)/g; return text.replace(urlRegex, function(url) { return '&lt;a href="' + url + '"&gt;' + url + '&lt;/a&gt;'; }) // or alternatively // return text.replace(urlRegex, '&lt;a href="$1"&gt;$1&lt;/a&gt;') } var text = 'Find me at http://www.example.com and also at http://stackoverflow.com'; var html = urlify(text); console.log(html)</code></pre> </div> </div> </p> <pre><code>// html now looks like: // "Find me at &lt;a href="http://www.example.com"&gt;http://www.example.com&lt;/a&gt; and also at &lt;a href="http://stackoverflow.com"&gt;http://stackoverflow.com&lt;/a&gt;" </code></pre> <p>So in sum try:</p> <pre><code>$$('#pad dl dd').each(function(element) { element.innerHTML = urlify(element.innerHTML); }); </code></pre>
{ "question_id": 1500260, "question_date": "2009-09-30T19:41:40.497Z", "question_score": 207, "tags": "javascript|regex|url", "answer_id": 1500501, "answer_date": "2009-09-30T20:34:22.300Z", "answer_score": 290 }
Please answer the following Stack Overflow question: Title: What are .NET Assemblies? <p>What are .NET Assemblies? I browsed over the net and I am not able to understand the definition.</p>
<p>In more simple terms: A chunk of (precompiled) code that can be executed by the .NET runtime environment. A .NET program consists of one or more assemblies. </p>
{ "question_id": 2972732, "question_date": "2010-06-04T09:03:49.287Z", "question_score": 207, "tags": "c#|.net", "answer_id": 2972763, "answer_date": "2010-06-04T09:08:18.293Z", "answer_score": 181 }
Please answer the following Stack Overflow question: Title: Age from birthdate in python <p>How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.</p>
<p>That can be done much simpler considering that int(True) is 1 and int(False) is 0:</p> <pre><code>from datetime import date def calculate_age(born): today = date.today() return today.year - born.year - ((today.month, today.day) &lt; (born.month, born.day)) </code></pre>
{ "question_id": 2217488, "question_date": "2010-02-07T17:10:02.327Z", "question_score": 207, "tags": "python", "answer_id": 9754466, "answer_date": "2012-03-17T22:46:32.377Z", "answer_score": 397 }
Please answer the following Stack Overflow question: Title: RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol <p>What is the regex to make sure that a given string contains at least one character from each of the following categories. </p> <ul> <li>Lowercase character</li> <li>Uppercase character</li> <li>Digit </li> <li>Symbol</li> </ul> <p>I know the patterns for individual sets namely <code>[a-z]</code>, <code>[A-Z]</code>, <code>\d</code> and <code>_|[^\w]</code> (I got them correct, didn't I?). </p> <p>But how do I combine them to make sure that the string contains all of these in any order?</p>
<p>If you need one single regex, try:</p> <pre><code>(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W) </code></pre> <p>A short explanation:</p> <pre><code>(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists (?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists (?=.*\d) // use positive look ahead to see if at least one digit exists (?=.*\W) // use positive look ahead to see if at least one non-word character exists </code></pre> <p>And I agree with SilentGhost, <code>\W</code> might be a bit broad. I'd replace it with a character set like this: <code>[-+_!@#$%^&amp;*.,?]</code> (feel free to add more of course!)</p>
{ "question_id": 1559751, "question_date": "2009-10-13T11:55:30.943Z", "question_score": 207, "tags": "regex", "answer_id": 1559788, "answer_date": "2009-10-13T12:03:19.037Z", "answer_score": 427 }
Please answer the following Stack Overflow question: Title: Valid to use <a> (anchor tag) without href attribute? <p>I've been using Twitter Bootstrap to build a site, and a lot of its functionality depends on wrapping things in <code>&lt;a&gt;</code>, even if they're just going to execute Javascript. I've had problems with the <code>href="#"</code> tactic that Bootstrap's documentation recommends, so I was trying to find a different solution.</p> <p>But then I tried just removing the <code>href</code> attribute altogether. I've been using <code>&lt;a class='bunch of classes' data-whatever='data'&gt;</code>, and having Javascript handle the rest. And it works.</p> <p>Yet something's telling me I shouldn't be doing this. Right? I mean, technically <code>&lt;a&gt;</code> is supposed to be a link to something, but I'm not entirely sure <em>why</em> this is a problem. Or is it?</p>
<p>The <code>&lt;a&gt;</code>nchor element is simply an anchor to or from some content. Originally the HTML specification allowed for named anchors (<code>&lt;a name="foo"&gt;</code>) and linked anchors (<code>&lt;a href="#foo"&gt;</code>).</p> <p>The named anchor format is less commonly used, as the fragment identifier is now used to specify an <code>[id]</code> attribute (although for backwards compatibility you can still specify <code>[name]</code> attributes). <a href="http://www.w3.org/TR/2011/WD-html5-20110525/text-level-semantics.html#the-a-element" rel="noreferrer">An <code>&lt;a&gt;</code> element without an <code>[href]</code> attribute is still valid</a>.</p> <p>As far as semantics and styling is concerned, the <code>&lt;a&gt;</code> element isn't a link (<code>:link</code>) unless it has an <code>[href]</code> attribute. A side-effect of this is that an <code>&lt;a&gt;</code> element without <code>[href]</code> won't be in the tabbing order by default.</p> <p>The real question is whether the <code>&lt;a&gt;</code> element alone is an appropriate representation of a <code>&lt;button&gt;</code>. On a semantic level, there is a distinct difference between a <code>link</code> and a <code>button</code>.</p> <p>A button is something that when clicked causes an action to occur.</p> <p>A link is a button that causes a change in navigation in the current document. The navigation that occurs could be moving within the document in the case of fragment identifiers (<code>#foo</code>) or moving to a new document in the case of urls (<code>/bar</code>).</p> <p>As links are a special type of button, they have often had their actions overridden to perform alternative functions. Continuing to use an anchor as a button is ok from a consistency standpoint, although it's not quite accurate semantically.</p> <p>If you're concerned about the semantics and accessibility of using an <code>&lt;a&gt;</code> element (or <code>&lt;span&gt;</code>, or <code>&lt;div&gt;</code>) as a button, you should add the following attributes:</p> <pre><code>&lt;a role="button" tabindex="0" ...&gt;...&lt;/a&gt; </code></pre> <p>The <a href="https://www.w3.org/WAI/PF/aria/roles#button" rel="noreferrer">button role</a> tells the user that the particular element is being treated as a button as an override for whatever semantics the underlying element may have had.</p> <p>For <code>&lt;span&gt;</code> and <code>&lt;div&gt;</code> elements, you may want to add JavaScript key listeners for <kbd>Space</kbd> or <kbd>Enter</kbd> to trigger the <code>click</code> event. <code>&lt;a href&gt;</code> and <code>&lt;button&gt;</code> elements do this by default, but non-button elements do not. Sometimes it makes more sense to bind the <code>click</code> trigger to a different key. For example, a "help" button in a web app might be bound to <kbd>F1</kbd>.</p>
{ "question_id": 10510191, "question_date": "2012-05-09T05:15:40.073Z", "question_score": 207, "tags": "html|anchor|semantic-markup", "answer_id": 10510353, "answer_date": "2012-05-09T05:34:30.790Z", "answer_score": 322 }
Please answer the following Stack Overflow question: Title: Picking a random element from a set <p>How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome. </p>
<pre><code>int size = myHashSet.size(); int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this int i = 0; for(Object obj : myhashSet) { if (i == item) return obj; i++; } </code></pre>
{ "question_id": 124671, "question_date": "2008-09-24T00:12:17.747Z", "question_score": 207, "tags": "java|algorithm|language-agnostic|random|set", "answer_id": 124693, "answer_date": "2008-09-24T00:17:08.267Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: How to add custom method to Spring Data JPA <p>I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder then that can be also done easily in the interface itself.</p> <pre><code>@Transactional(readOnly = true) public interface AccountRepository extends JpaRepository&lt;Account, Long&gt; { @Query("&lt;JPQ statement here&gt;") List&lt;Account&gt; findByCustomer(Customer customer); } </code></pre> <p>I would like to know how can I add a complete custom method with its implementation for the above AccountRepository? Since its an Interface I cannot implement the method there.</p>
<p>You need to create a separate interface for your custom methods:</p> <pre><code>public interface AccountRepository extends JpaRepository&lt;Account, Long&gt;, AccountRepositoryCustom { ... } public interface AccountRepositoryCustom { public void customMethod(); } </code></pre> <p>and provide an implementation class for that interface:</p> <pre><code>public class AccountRepositoryImpl implements AccountRepositoryCustom { @Autowired @Lazy AccountRepository accountRepository; /* Optional - if you need it */ public void customMethod() { ... } } </code></pre> <p><strong>See also:</strong></p> <ul> <li><p><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations" rel="noreferrer">4.6 Custom Implementations for Spring Data Repositories</a></p></li> <li><p>Note that the naming scheme has changed between versions. See <a href="https://stackoverflow.com/a/52624752/66686">https://stackoverflow.com/a/52624752/66686</a> for details.</p></li> </ul>
{ "question_id": 11880924, "question_date": "2012-08-09T10:00:07.573Z", "question_score": 207, "tags": "java|spring-data|spring-data-jpa", "answer_id": 11881203, "answer_date": "2012-08-09T10:18:05.200Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: android: move a view on touch move (ACTION_MOVE) <p>I'd like to do a simple control: a container with a view inside. If I touch the container and I move the finger, I want to move the view to follow my finger. </p> <p>What kind of container (layout) should I use? How to do this?</p> <p>I don't need to use a surface, but a simple layout.</p>
<p>Something like this:</p> <pre><code>public class MyActivity extends Activity implements View.OnTouchListener { TextView _view; ViewGroup _root; private int _xDelta; private int _yDelta; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _root = (ViewGroup)findViewById(R.id.root); _view = new TextView(this); _view.setText("TextView!!!!!!!!"); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 50); layoutParams.leftMargin = 50; layoutParams.topMargin = 50; layoutParams.bottomMargin = -250; layoutParams.rightMargin = -250; _view.setLayoutParams(layoutParams); _view.setOnTouchListener(this); _root.addView(_view); } public boolean onTouch(View view, MotionEvent event) { final int X = (int) event.getRawX(); final int Y = (int) event.getRawY(); switch (event.getAction() &amp; MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); _xDelta = X - lParams.leftMargin; _yDelta = Y - lParams.topMargin; break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_POINTER_DOWN: break; case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_MOVE: RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); layoutParams.leftMargin = X - _xDelta; layoutParams.topMargin = Y - _yDelta; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; view.setLayoutParams(layoutParams); break; } _root.invalidate(); return true; }} </code></pre> <p>In <code>main.xml</code> just <code>RelativeLayout</code> with <code>@+id/root</code> </p>
{ "question_id": 9398057, "question_date": "2012-02-22T15:45:23.980Z", "question_score": 207, "tags": "android|touch", "answer_id": 9398861, "answer_date": "2012-02-22T16:29:46.907Z", "answer_score": 250 }
Please answer the following Stack Overflow question: Title: Install Node.js on Ubuntu <p>I'm trying install Node.js on <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_12.10_.28Quantal_Quetzal.29" rel="noreferrer">Ubuntu 12.10</a> (Quantal Quetzal), but the terminal shows me an error about lost packages. I tried with this:</p> <pre><code>sudo apt-get install python-software-properties sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs npm </code></pre> <p>But when I came to the last line <code>sudo apt-get install nodejs npm</code> shows this error:</p> <pre class="lang-none prettyprint-override"><code>Failed to install some packages. This may mean that you requested an impossible situation or if you are using the distribution distribution that some required packages have not yet been created or been been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: nodejs: Conflicts: npm E: Failed to correct problems, you have held broken packages. </code></pre> <p>Then I uninstalled the <code>ppa:chris-lea/node.js</code> and I was trying a second option:</p> <pre><code>sudo apt-get install node.js sudo apt-add-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs npm </code></pre> <p>The same error, the terminal says <code>npm is the latest version</code>, but it also shows me the text I shown in the top. I think the problem is <code>ppa:chris-lea/node.js</code>, but I don't know how solve it.</p>
<p>Simply follow the instructions given <a href="https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager#ubuntu-mint-elementary-os" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>Example install:</p> <pre><code>sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs </code></pre> <p>It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the <code>add-apt-repository</code> command to work: <code>sudo apt-get install software-properties-common</code></p> <p>As of Node.js v0.10.0, the nodejs package from Chris Lea's repo includes both npm and nodejs-dev.</p> </blockquote> <p>Don't give <code>sudo apt-get install nodejs npm</code>. Just <code>sudo apt-get install nodejs</code>.</p>
{ "question_id": 16302436, "question_date": "2013-04-30T14:31:55.943Z", "question_score": 207, "tags": "node.js|ubuntu|npm", "answer_id": 16303380, "answer_date": "2013-04-30T15:18:41.863Z", "answer_score": 477 }
Please answer the following Stack Overflow question: Title: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory <p>Node version is <code>v0.11.13</code></p> <p>Memory usage during crash according to <code>sudo top</code> not raises over <code>3%</code></p> <p>Code that reproduces this error:</p> <pre><code>var request = require('request') var nodedump = require('nodedump') request.get("http://pubapi.cryptsy.com/api.php?method=marketdatav2",function(err,res) { var data console.log( "Data received." ); data = JSON.parse(res.body) console.log( "Data parsed." ); data = nodedump.dump(data) console.log( "Data dumped." ); console.log( data ) }) </code></pre> <p>To check if that a recursion stack size problem I have ran next code with --stack-size=60000 parameter</p> <pre><code>var depth = 0; (function recurse() { // log at every 500 calls (++depth % 500) || console.log(depth); recurse(); })(); </code></pre> <p>and have got</p> <pre><code>264500 Segmentation fault </code></pre> <p>Then I ran code which gives me FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory with the same --stack-size=60000 parameter and haven't got <code>Segmentation fault</code>. </p> <p>So I conclude <code>CALL_AND_RETRY_LAST</code> has nothing common with the recursion stack size.</p> <p>How could I solve this problem? I believe there is enough free memory on my computer to finish this task successfully.</p> <p>There are similar questions on stackoverflow but none of this questions are about <code>CALL_AND_RETRY_LAST</code> that's why I created separate question.</p>
<p>If you have a look at the source: <a href="https://github.com/v8/v8-git-mirror/blob/master/src/heap/heap-inl.h" rel="noreferrer">github/v8</a>, it seems that you try to reserve a very big object.According to my experience it happens if you try to parse a huge JSON object, but when I try to parse your output with JSON and node0.11.13, it just works fine.</p> <p>You don't need more <code>--stack-size</code>, you need more memory: <code>--max_new_space_size</code> and/or <code>--max_old_space_size</code>.</p> <p>The only hint I can give you beside that is trying another JSON-parser and/or try to change the input format to JSON line instead of JSON only.</p>
{ "question_id": 26094420, "question_date": "2014-09-29T07:17:05.430Z", "question_score": 207, "tags": "node.js", "answer_id": 26094800, "answer_date": "2014-09-29T07:40:38.157Z", "answer_score": 125 }
Please answer the following Stack Overflow question: Title: What is the HtmlSpecialChars equivalent in JavaScript? <p>Apparently, this is harder to find than I thought it would be. And it even is so simple...</p> <p>Is there a function equivalent to PHP's <a href="https://www.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer">htmlspecialchars</a> built into JavaScript? I know it's fairly easy to implement that yourself, but using a built-in function, if available, is just nicer.</p> <p>For those unfamiliar with PHP, htmlspecialchars translates stuff like <code>&lt;htmltag/&gt;</code> into <code>&amp;lt;htmltag/&amp;gt;</code></p> <p>I know that <code>escape()</code> and <code>encodeURI()</code> do not work this way.</p>
<p>There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:</p> <pre><code>escapeHtml('Kip\'s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code\'s here'); Actual: Kip&amp;#039;s &amp;lt;b&amp;gt;evil&lt;/b&gt; &amp;quot;test&quot; code's here Expected: Kip&amp;#039;s &amp;lt;b&amp;gt;evil&amp;lt;/b&amp;gt; &amp;quot;test&amp;quot; code&amp;#039;s here </code></pre> <p>Here is code that works properly:</p> <pre><code>function escapeHtml(text) { return text .replace(/&amp;/g, &quot;&amp;amp;&quot;) .replace(/&lt;/g, &quot;&amp;lt;&quot;) .replace(/&gt;/g, &quot;&amp;gt;&quot;) .replace(/&quot;/g, &quot;&amp;quot;&quot;) .replace(/'/g, &quot;&amp;#039;&quot;); } </code></pre> <hr /> <h3>Update</h3> <p>The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks <a href="https://stackoverflow.com/users/861178/jbo5112">jbo5112</a>).</p> <pre><code>function escapeHtml(text) { var map = { '&amp;': '&amp;amp;', '&lt;': '&amp;lt;', '&gt;': '&amp;gt;', '&quot;': '&amp;quot;', &quot;'&quot;: '&amp;#039;' }; return text.replace(/[&amp;&lt;&gt;&quot;']/g, function(m) { return map[m]; }); } </code></pre>
{ "question_id": 1787322, "question_date": "2009-11-24T01:59:20.400Z", "question_score": 207, "tags": "javascript|html|escaping|html-encode", "answer_id": 4835406, "answer_date": "2011-01-29T05:48:48.727Z", "answer_score": 375 }
Please answer the following Stack Overflow question: Title: Best way to store date/time in mongodb <p>I've seen using strings, integer timestamps and mongo datetime objects. </p>
<p>The best way is to store native JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer">Date objects</a>, which map onto <a href="http://docs.mongodb.org/manual/reference/bson-types/#document-bson-type-date" rel="noreferrer">BSON native Date objects</a>.</p> <pre><code>&gt; db.test.insert({date: ISODate()}) &gt; db.test.insert({date: new Date()}) &gt; db.test.find() { "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") } { "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") } </code></pre> <p>The native type supports a whole range of <strong>useful methods</strong> out of the box, which you can use in your map-reduce jobs, for example.</p> <p>If you need to, you can easily convert <code>Date</code> objects to and from Unix timestamps<sup>1)</sup>, using the <code>getTime()</code> method and <code>Date(milliseconds)</code> constructor, respectively.</p> <p><sup>1)</sup> Strictly speaking, the Unix timestamp is measured in <em>seconds</em>. The JavaScript Date object measures in <em>milliseconds</em> since the Unix epoch.</p>
{ "question_id": 3778428, "question_date": "2010-09-23T12:38:42.253Z", "question_score": 207, "tags": "datetime|date|mongodb", "answer_id": 3778820, "answer_date": "2010-09-23T13:28:14.583Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: How to distinguish mouse "click" and "drag" <p>I use <code>jQuery.click</code> to handle the mouse click event on Raphael graph, meanwhile, I need to handle mouse <code>drag</code> event, mouse drag consists of <code>mousedown</code>, <code>mouseup</code>and <code>mousemove</code> in Raphael. </p> <p>It is difficult to distinguish <code>click</code> and <code>drag</code> because <code>click</code> also contain <code>mousedown</code> &amp; <code>mouseup</code>, How can I distinguish mouse "click" &amp; mouse "drag" then in Javascript?</p>
<p>I think the difference is that there is a <code>mousemove</code> between <code>mousedown</code> and <code>mouseup</code> in a drag, but not in a click.</p> <p>You can do something like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const element = document.createElement('div') element.innerHTML = 'test' document.body.appendChild(element) let moved let downListener = () =&gt; { moved = false } element.addEventListener('mousedown', downListener) let moveListener = () =&gt; { moved = true } element.addEventListener('mousemove', moveListener) let upListener = () =&gt; { if (moved) { console.log('moved') } else { console.log('not moved') } } element.addEventListener('mouseup', upListener) // release memory element.removeEventListener('mousedown', downListener) element.removeEventListener('mousemove', moveListener) element.removeEventListener('mouseup', upListener)</code></pre> </div> </div> </p>
{ "question_id": 6042202, "question_date": "2011-05-18T09:00:30.803Z", "question_score": 207, "tags": "javascript|dom-events", "answer_id": 6042235, "answer_date": "2011-05-18T09:03:17.413Z", "answer_score": 221 }