id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
4,374,730
How to check if a record exists using JPA
<p>I want to know whether a given record is present in a database or not. so far I have achieved this by writing a JPA query and the running it by <code>getSingleResult()</code> method. this would throw a <code>NoResultException</code> if the record with the given parameter does not exist. Of course, it's not a must for the record to exist, so it's the normal behaviour sometimes, that's why I asked to myself, is it neccessary to throw an Exception which I have to handle by a catch block? As far as I know the cost of Exception handling is quite big, so I'm not very satisfied with this solution, also, I don't even need the object, I only need to know it's existence in the DB.</p> <p>Is there a better way to check whether an object exist or not? eg. using <code>getResultList()</code> and checking it's size maybe? </p>
4,374,774
7
3
null
2010-12-07 08:35:55.247 UTC
7
2022-05-18 16:04:20.237 UTC
2012-03-04 15:20:38.033 UTC
null
313,758
null
427,321
null
1
34
java|jpa
86,595
<p>If you just want to know whether the object exists, send a <code>SELECT COUNT</code> to your database. That will return 0 or 1.</p> <p>The cost of the exception handling isn't that big (unless you do that millions of times during a normal operation), so I wouldn't bother.</p> <p>But the code doesn't really reflect your intention. Since <code>getSingleResult()</code> calls <code>getResultList()</code> internally, it's clearer like so:</p> <pre><code>public boolean objExists(...) { return getResultList(...).size() == 1; } </code></pre> <p>If you query by object id and you have caching enabled, that will become a simple lookup in the cache if the object has already been loaded.</p>
4,631,774
Coordinating parallel execution in node.js
<p>The event-driven programming model of node.js makes it somewhat tricky to coordinate the program flow.</p> <p>Simple sequential execution gets turned into nested callbacks, which is easy enough (though a bit convoluted to write down). </p> <p>But how about parallel execution? Say you have three tasks A,B,C that can run in parallel and when they are done, you want to send their results to task D.</p> <p>With a fork/join model this would be</p> <ul> <li>fork A</li> <li>fork B</li> <li>fork C</li> <li>join A,B,C, run D</li> </ul> <p>How do I write that in node.js ? Are there any best practices or cookbooks? Do I have to <a href="https://stackoverflow.com/questions/4496403/extjs-two-parallel-ajax-call">hand-roll a solution</a> every time, or is there some library with helpers for this?</p>
4,631,909
7
0
null
2011-01-08 01:21:23.613 UTC
68
2018-06-18 14:59:49.173 UTC
2017-05-23 12:18:24.63 UTC
null
-1
null
14,955
null
1
79
javascript|concurrency|node.js|parallel-processing|fork-join
37,331
<p>Nothing is truly parallel in node.js since it is single threaded. However, multiple events can be scheduled and run in a sequence you can't determine beforehand. And some things like database access are actually "parallel" in that the database queries themselves are run in separate threads but are re-integrated into the event stream when completed.</p> <p>So, how do you schedule a callback on multiple event handlers? Well, this is one common technique used in animations in browser side javascript: use a variable to track the completion.</p> <p>This sounds like a hack and it is, and it sounds potentially messy leaving a bunch of global variables around doing the tracking and in a lesser language it would be. But in javascript we can use closures:</p> <pre><code>function fork (async_calls, shared_callback) { var counter = async_calls.length; var callback = function () { counter --; if (counter == 0) { shared_callback() } } for (var i=0;i&lt;async_calls.length;i++) { async_calls[i](callback); } } // usage: fork([A,B,C],D); </code></pre> <p>In the example above we keep the code simple by assuming the async and callback functions require no arguments. You can of course modify the code to pass arguments to the async functions and have the callback function accumulate results and pass it to the shared_callback function.</p> <hr> <h2>Additional answer:</h2> <p>Actually, even as is, that <code>fork()</code> function can already pass arguments to the async functions using a closure:</p> <pre><code>fork([ function(callback){ A(1,2,callback) }, function(callback){ B(1,callback) }, function(callback){ C(1,2,callback) } ],D); </code></pre> <p>the only thing left to do is to accumulate the results from A,B,C and pass them on to D.</p> <hr> <h2>Even more additional answer:</h2> <p>I couldn't resist. Kept thinking about this during breakfast. Here's an implementation of <code>fork()</code> that accumulates results (usually passed as arguments to the callback function):</p> <pre><code>function fork (async_calls, shared_callback) { var counter = async_calls.length; var all_results = []; function makeCallback (index) { return function () { counter --; var results = []; // we use the arguments object here because some callbacks // in Node pass in multiple arguments as result. for (var i=0;i&lt;arguments.length;i++) { results.push(arguments[i]); } all_results[index] = results; if (counter == 0) { shared_callback(all_results); } } } for (var i=0;i&lt;async_calls.length;i++) { async_calls[i](makeCallback(i)); } } </code></pre> <p>That was easy enough. This makes <code>fork()</code> fairly general purpose and can be used to synchronize multiple non-homogeneous events.</p> <p>Example usage in Node.js:</p> <pre><code>// Read 3 files in parallel and process them together: function A (c){ fs.readFile('file1',c) }; function B (c){ fs.readFile('file2',c) }; function C (c){ fs.readFile('file3',c) }; function D (result) { file1data = result[0][1]; file2data = result[1][1]; file3data = result[2][1]; // process the files together here } fork([A,B,C],D); </code></pre> <hr> <h2>Update</h2> <p>This code was written before the existence of libraries like async.js or the various promise based libraries. I'd like to believe that async.js was inspired by this but I don't have any proof of it. Anyway.. if you're thinking of doing this today take a look at async.js or promises. Just consider the answer above a good explanation/illustration of how things like async.parallel work.</p> <p>For completeness sake the following is how you'd do it with <code>async.parallel</code>:</p> <pre><code>var async = require('async'); async.parallel([A,B,C],D); </code></pre> <p>Note that <code>async.parallel</code> works exactly the same as the <code>fork</code> function we implemented above. The main difference is it passes an error as the first argument to <code>D</code> and the callback as the second argument as per node.js convention.</p> <p>Using promises, we'd write it as follows:</p> <pre><code>// Assuming A, B &amp; C return a promise instead of accepting a callback Promise.all([A,B,C]).then(D); </code></pre>
4,412,945
Case-insensitive search and replace with sed
<p>I'm trying to use SED to extract text from a log file. I can do a search-and-replace without too much trouble:</p> <pre><code>sed 's/foo/bar/' mylog.txt </code></pre> <p>However, I want to make the search case-insensitive. From what I've googled, it looks like appending <code>i</code> to the end of the command should work:</p> <pre><code>sed 's/foo/bar/i' mylog.txt </code></pre> <p>However, this gives me an error message:</p> <pre><code>sed: 1: "s/foo/bar/i": bad flag in substitute command: 'i' </code></pre> <p>What's going wrong here, and how do I fix it?</p>
12,887,319
9
8
null
2010-12-10 20:20:43.513 UTC
14
2022-04-24 09:58:40.853 UTC
2019-08-24 05:17:09.547 UTC
null
608,639
null
3,488
null
1
96
macos|replace|sed|case-insensitive
82,975
<p><strong>Update</strong>: Starting with <strong>macOS Big Sur (11.0)</strong>, <strong><code>sed</code> now <em>does</em> support the <code>I</code> flag for case-insensitive matching</strong>, so the command in the question should now work (BSD <code>sed</code> doesn't reporting its version, but you can go by the date at the bottom of the <code>man</code> page, which should be <code>March 27, 2017</code> or more recent); a simple example:</p> <pre class="lang-sh prettyprint-override"><code># BSD sed on macOS Big Sur and above (and GNU sed, the default on Linux) $ sed 's/ö/@/I' &lt;&lt;&lt;'FÖO' F@O # `I` matched the uppercase Ö correctly against its lowercase counterpart </code></pre> <p><sup>Note: <code>I</code> (uppercase) is the documented form of the flag, but <code>i</code> works as well.</sup></p> <p>Similarly, starting with <strong>macOS Big Sur (11.0)</strong> <strong><code>awk</code> now <em>is</em> locale-aware</strong> (<code>awk --version</code> should report <code>20200816</code> or more recent):</p> <pre class="lang-sh prettyprint-override"><code># BSD awk on macOS Big Sur and above (and GNU awk, the default on Linux) $ awk 'tolower($0)' &lt;&lt;&lt;'FÖO' föo # non-ASCII character Ö was properly lowercased </code></pre> <hr /> <p>The following applies to <strong>macOS <em>up to Catalina</em> (10.15)</strong>:</p> <p>To be clear: On macOS, <strong><code>sed</code> - which is the <em>BSD</em> implementation - does NOT support case-insensitive matching</strong> - hard to believe, but true. The <a href="https://stackoverflow.com/a/4412964/45375">formerly accepted answer</a>, which itself shows a <em>GNU</em> <code>sed</code> command, gained that status because of the <code>perl</code>-based solution mentioned in the comments.</p> <p>To make that <strong>Perl solution</strong> work with <strong>foreign characters</strong> as well, via UTF-8, use something like:</p> <pre><code>perl -C -Mutf8 -pe 's/öœ/oo/i' &lt;&lt;&lt; &quot;FÖŒ&quot; # -&gt; &quot;Foo&quot; </code></pre> <ul> <li><code>-C</code> turns on UTF-8 support for streams and files, assuming the current locale is UTF-8-based.</li> <li><code>-Mutf8</code> tells Perl to interpret the <em>source code</em> as UTF-8 (in this case, the string passed to <code>-pe</code>) - this is the shorter equivalent of the more verbose <code>-e 'use utf8;'.</code><sup>Thanks, <a href="https://stackoverflow.com/users/797049/mark-reed">Mark Reed</a></sup></li> </ul> <p>(Note that <strong>using <code>awk</code> is not an option either</strong>, as <code>awk</code> on macOS (i.e., <em>BWK awk</em> and <em>BSD awk</em>) appears to be completely unaware of locales altogether - its <code>tolower()</code> and <code>toupper()</code> functions ignore foreign characters (and <code>sub()</code> / <code>gsub()</code> don't have case-insensitivity flags to begin with).)</p> <hr /> <p>A note on the relationship of <code>sed</code> and <code>awk</code> to the POSIX standard:</p> <p>BSD <code>sed</code> and <code>awk</code> limit their functionality <em>mostly</em> to what the <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html" rel="noreferrer">POSIX <code>sed</code></a> and <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html" rel="noreferrer">POSIX <code>awk</code></a> specs mandate, whereas their GNU counterparts implement many more extensions.</p>
4,731,364
Internal Error 500 Apache, but nothing in the logs?
<p>I'm getting 500 Internal Server errors when I try to make an HTTP POST to a specific address in my app. I've looked into the server logs in the custom log directory specified in the virtual hosts file, but the error doesn't show up there so debugging this has been a pain in the ass.</p> <p>How do I cause Apache to log Internal 500 errors into the error log?</p>
4,731,661
11
2
null
2011-01-19 03:04:00.18 UTC
22
2021-08-26 11:31:44.423 UTC
2013-12-11 06:05:15.65 UTC
null
445,131
null
159,715
null
1
145
apache|error-logging
377,713
<p><strong>Please Note:</strong> The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.</p> <p>The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.</p> <p>This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.</p> <p>in perl if you forget </p> <pre><code>print "content-type: text/html\r\n\r\n"; </code></pre> <p>you will get this error</p> <p>There are many reasons for it. so please first check your error log and then provide some more information.</p> <p>The default error log is often in <code>/var/log/httpd/error_log</code> or <code>/var/log/apache2/error.log</code>.</p> <p>The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.</p> <p>Assumes linux and not necessarily perl</p>
14,570,857
Retrieve an xpath text contains using text()
<p>I've been hacking away at this one for hours and I just can't figure it out. Using XPath to find text values is tricky and this problem has too many moving parts.</p> <p>I have a webpage with a large table and a section in this table contains a list of users (assignees) that are assigned to a particular unit. There is nearly always multiple users assigned to a unit and I need to make sure a particular user is assigned to any of the units on the table. I've used XPath for nearly all of my selectors and I'm half way there on this one. I just can't seem to figure out how to use <code>contains</code> with <code>text()</code> in this context.</p> <p>Here's what I have so far:</p> <pre><code>//td[@id='unit']/span [text()='asdfasdfasdfasdfasdf (Primary); asdfasdfasdfasdfasdf, asdfasdfasdfasdf; 456, 3456'; testuser] </code></pre> <p>The XPath Query above captures all text in the particular section I am looking at, which is great. However, I only need to know if testuser is in that section.</p>
14,570,976
1
0
null
2013-01-28 20:42:26.587 UTC
15
2016-01-12 16:11:41.703 UTC
2016-01-12 16:11:41.703 UTC
null
4,909,923
null
1,361,524
null
1
32
xpath
98,135
<p><code>text()</code> gets you a set of text nodes. I tend to use it more in a context of //span//text() or something.</p> <p>If you are trying to check if the text inside an element contains something you should use <code>contains</code> on the element rather than the result of <code>text()</code> like this:</p> <pre><code>span[contains(., 'testuser')] </code></pre> <p>XPath is pretty good with context. If you know exactly what text a node should have you can do:</p> <pre><code>span[.='full text in this span'] </code></pre> <p>But if you want to do something like regular expressions (using exslt for example) you'll need to use the string() function:</p> <pre><code>span[regexp:test(string(.), 'testuser')] </code></pre>
14,797,046
Python syntax for an empty while loop
<p>I have written this:</p> <pre><code> while file.readline().startswith("#"): continue </code></pre> <p>But I suspect the <code>continue</code> is unnecessary? What is the correct syntax for what i'm trying to achieve?</p>
14,797,055
2
2
null
2013-02-10 11:06:07.757 UTC
3
2022-05-23 01:44:37.54 UTC
null
null
null
null
694,195
null
1
44
python|while-loop
59,073
<pre><code>while file.readline().startswith("#"): pass </code></pre> <p>This uses the pass statement :</p> <blockquote> <p>The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.</p> </blockquote> <p><a href="http://www.network-theory.co.uk/docs/pytut/passStatements.html" rel="noreferrer">http://www.network-theory.co.uk/docs/pytut/passStatements.html</a></p>
14,363,085
Invalid multibyte string in read.csv
<p>I am trying to import a csv that is in Japanese. This code:</p> <pre><code>url &lt;- 'http://www.mof.go.jp/international_policy/reference/itn_transactions_in_securities/week.csv' x &lt;- read.csv(url, header=FALSE, stringsAsFactors=FALSE) </code></pre> <p>returns the following error:</p> <pre><code>Error in type.convert(data[[i]], as.is = as.is[i], dec = dec, na.strings = character(0L)) : invalid multibyte string at '&lt;91&gt;ΊO&lt;8b&gt;y&lt;82&gt;ёΓ&lt;e0&gt;&lt;8f&gt;،&lt;94&gt;&lt;94&gt;&lt;84&gt;&lt;94&gt;&lt;83&gt;&lt;8c&gt;_&lt;96&gt;̏@(&lt;8f&gt;T&lt;8e&gt;&lt;9f&gt;&lt;81&gt;E&lt;8e&gt;w&lt;92&gt;&lt;e8&gt;&lt;95&gt;@&lt;8a&gt;փx&lt;81&gt;[&lt;83&gt;X&lt;81&gt;j' </code></pre> <p>I tried changing the encoding (<code>Encoding(url) &lt;- 'UTF-8'</code> and also to latin1) and tried removing the read.csv parameters, but received the same "invalid multibyte string" message in each case. Is there a different encoding that should be used, or is there some other problem?</p>
14,363,274
9
2
null
2013-01-16 16:29:39.107 UTC
11
2020-01-01 12:49:35.5 UTC
2015-01-11 16:35:31.43 UTC
null
2,125,442
null
1,721,321
null
1
57
r|read.csv
127,356
<p><code>Encoding</code> sets the encoding of a character string. It doesn't set the encoding of the file represented by the character string, which is what you want.</p> <p>This worked for me, after trying <code>"UTF-8"</code>:</p> <pre><code>x &lt;- read.csv(url, header=FALSE, stringsAsFactors=FALSE, fileEncoding="latin1") </code></pre> <p>And you may want to skip the first 16 lines, and read in the headers separately. Either way, there's still quite a bit of cleaning up to do.</p> <pre><code>x &lt;- read.csv(url, header=FALSE, stringsAsFactors=FALSE, fileEncoding="latin1", skip=16) # get started with the clean-up x[,1] &lt;- gsub("\u0081|`", "", x[,1]) # get rid of odd characters x[,-1] &lt;- as.data.frame(lapply(x[,-1], # convert to numbers function(d) type.convert(gsub(d, pattern=",", replace="")))) </code></pre>
2,914,375
Getting file path in java
<p>Is there a way for java program to determine its location in the file system?</p>
2,914,393
3
0
null
2010-05-26 15:28:23.46 UTC
3
2014-02-20 11:19:02.947 UTC
null
null
null
null
181,150
null
1
10
java|file
38,136
<p>You can use <a href="http://java.sun.com/javase/6/docs/api/java/security/CodeSource.html#getLocation%28%29" rel="noreferrer"><code>CodeSource#getLocation()</code></a> for this. The <a href="http://java.sun.com/javase/6/docs/api/java/security/CodeSource.html" rel="noreferrer"><code>CodeSource</code></a> is available by <a href="http://java.sun.com/javase/6/docs/api/java/security/ProtectionDomain.html#getCodeSource%28%29" rel="noreferrer"><code>ProtectionDomain#getCodeSource()</code></a>. The <a href="http://java.sun.com/javase/6/docs/api/java/security/ProtectionDomain.html" rel="noreferrer"><code>ProtectionDomain</code></a> in turn is available by <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getProtectionDomain%28%29" rel="noreferrer"><code>Class#getProtectionDomain()</code></a>.</p> <pre><code>URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); File file = new File(location.getPath()); // ... </code></pre> <p>This returns the exact location of the <code>Class</code> in question.</p> <p><strong>Update</strong>: as per the comments, it's apparently already in the classpath. You can then just use <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29" rel="noreferrer"><code>ClassLoader#getResource()</code></a> wherein you pass the root-package-relative path. </p> <pre><code>ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL resource = classLoader.getResource("filename.ext"); File file = new File(resource.getPath()); // ... </code></pre> <p>You can even get it as an <code>InputStream</code> using <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29" rel="noreferrer"><code>ClassLoader#getResourceAsStream()</code></a>.</p> <pre><code>InputStream input = classLoader.getResourceAsStream("filename.ext"); // ... </code></pre> <p>That's also the normal way of using packaged resources. If it's located inside a package, then use for example <code>com/example/filename.ext</code> instead.</p>
38,737,880
Uncaught Error/Exception Handling in Swift
<p>I know there is an <a href="https://stackoverflow.com/questions/12215012/register-uncaughtexceptionhandler-in-objective-c-using-nssetuncaughtexceptionhan">UncaughtExceptionHandler</a> in Cocoa, However I am looking for same thing for Swift. i.e. whenever there is any error/exception in application which is not caught locally there due to any mistake, it should bubble all the way to the top level application object where I should be able to gracefully handle it and respond to user appropriately.</p> <p><a href="https://stackoverflow.com/questions/19897628/need-to-handle-uncaught-exception-and-send-log-file">Android</a> has it. <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/UncaughtErrorEvent.html" rel="noreferrer">Flex</a> has it. <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html" rel="noreferrer">Java</a> has it. Wondering why Swift is missing this key feature.</p>
38,738,365
2
5
null
2016-08-03 08:06:46.063 UTC
13
2019-06-28 09:47:20.38 UTC
2017-05-23 12:32:35.137 UTC
null
-1
null
1,091,026
null
1
16
swift|uncaughtexceptionhandler
10,207
<p>Swift has no mechanism to catch all arbitrary runtime exceptions. The reasons are explained in</p> <ul> <li><a href="https://forums.swift.org/t/prototyping-what-swift-can-look-like-in-educational-settings/929/59" rel="noreferrer">[swift-users] "business applications market" flame</a></li> </ul> <p>in the swift-users forum. Extract:</p> <blockquote> <p>Swift made a conscious choice not to include exceptions thrown through arbitrary stack frames not because it was technically impossible, but because its designers judged the costs to be too high.</p> <p>The problem is this: if a piece of code is going to exit early because of an error, it has to be written to handle that early exit. Otherwise it will misbehave—fail to deallocate memory, fail to close file handles/sockets/database connections/whatever, fail to release locks, etc. In a language like Java, writing truly exception-safe code requires a ridiculous quantity of try/finally blocks. That's why nobody does it. They make judgements about which exceptions they're likely to see and which resources are dangerous to leak, and only protect their code against those specific anticipated conditions. Then something unforeseen happens and their program breaks.</p> <p>This is even worse in a reference-counted language like Swift because correctly balancing the reference counts in the presence of exceptions basically requires every function to include an implicit finally block to balance all the retain counts. This means the compiler has to generate lots of extra code on the off chance that some call or another throws an exception. The vast majority of this code is never, ever used, but it has to be there, bloating the process.</p> <p>Because of these problems, Swift chose not to support traditional exceptions; instead, it only allows you to throw errors in specially-marked regions of code. But as a corollary, that means that, if something goes really wrong in code that can't throw, all it can really do to prevent a disaster is crash. And currently, the only thing you can crash is the entire process.</p> </blockquote> <p>For more information, see</p> <ul> <li><a href="https://github.com/apple/swift/blob/master/docs/ErrorHandlingRationale.rst" rel="noreferrer">Error Handling Rationale and Proposal</a></li> </ul>
44,364,916
How to open/run YML compose file?
<p>How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how.</p>
44,365,017
2
0
null
2017-06-05 08:36:40.603 UTC
8
2018-07-13 16:53:09.097 UTC
null
null
null
null
55,818
null
1
38
docker|docker-compose|docker-for-windows
123,512
<p>To manage <code>.yml</code> files you have to install and use Docker Compose.</p> <p>Installation instructions can be found here: <a href="https://docs.docker.com/compose/install/" rel="noreferrer">https://docs.docker.com/compose/install/</a></p> <p>After the installation, go to your <code>docker-compose.yml</code> directory and then execute <code>docker-compose up</code> to create and start services in your <code>docker-compose.yml</code> file.</p> <p>If you need more information, take a look to Docker Compose docs: <a href="https://docs.docker.com/compose" rel="noreferrer">https://docs.docker.com/compose</a></p>
64,299,247
"No Ad Config." on onAdFailedToLoad() Method While trying to Load Ads
<p>I am trying to load interstitial advertisements for my app. Whenever I try to load these ads I get a Error saying &quot;No Ads Config&quot; from Domain &quot;com.google.android.gms.ads&quot;.</p> <p>Here is the code:</p> <p>My AndroidManifest.xml</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.ayush.torch&quot;&gt; &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@drawable/ic_ico&quot; android:label=&quot;@string/app_name&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/AppTheme&quot;&gt; &lt;activity android:name=&quot;.main&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;meta-data android:name=&quot;com.google.android.gms.ads.APPLICATION_ID&quot; android:value=&quot;i_have_put_my_app_id_here&quot;/&gt; &lt;/application&gt; &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.FLASHLIGHT&quot; /&gt; &lt;/manifest&gt; </code></pre> <p><strong>onCreate()</strong> in main.java</p> <pre><code> // Creating the InterstitialAd and setting the adUnitId. interstitialAd = new InterstitialAd(this); interstitialAd.setAdUnitId(&quot;i have also put my interstitial ad id here&quot;); interstitialAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { Toast.makeText(main.this, &quot;Ad Loaded&quot;, Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(LoadAdError loadAdError) { String error = String.format(&quot;domain: %s, code: %d, message: %s&quot;, loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage()); Toast.makeText(main.this, &quot;onAdFailedToLoad() with error: &quot; + error, Toast.LENGTH_SHORT).show(); } }); </code></pre> <p>When I load my ad in a <strong>on</strong> function it gives me error &quot;No Ad Config.&quot;</p> <pre><code> Log.d(&quot;[Ads]&quot;,&quot;Ad Load State For on(): &quot; + interstitialAd.isLoaded()); if (interstitialAd.isLoaded()) { interstitialAd.show(); } </code></pre>
64,311,609
11
0
null
2020-10-10 23:26:22.51 UTC
2
2022-09-02 18:04:24.243 UTC
null
null
null
null
13,266,368
null
1
40
android-studio|admob|ads|interstitial
46,006
<p>Fixed It and it works.</p> <p>Found a resource from google. And It cleared all my doubts. <a href="https://developers.google.com/admob/android/test-ads" rel="noreferrer">For Test Ad Resource Click Me</a></p> <p>The <strong>Advertisement</strong> works in two ways.</p> <ol> <li>While The App Is In Development.</li> <li>While The App Is In Production.</li> </ol> <hr /> <p>Scenario 1: <strong>While the App Is In Devlopment</strong></p> <p>For this case, we need to use Test Advertisements. Admob and &quot;com.google.android.gms.ads&quot; doesnt allow user to use Advertisements in Development Phase due to false impressions.</p> <p>To enable Test Advertisement. There are two ways: You can either use google ad unit id's which are available on the link adove. Or You can use your own ad unit id, but you will be needing to register your device as a test device and use your own request configuration. Here is a simple Example: Search for your &quot;Device Id&quot; In &quot;Logcat&quot;</p> <p>It will look something like</p> <p>I/ADS: Use Requested Configuration......Arrays.asList(&quot;Your device Id will be here&quot;);</p> <p>Then Just Copy Paste This(i can read your mind..)</p> <pre><code>// Change your Id RequestConfiguration configuration = new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList(&quot;your device id should go here&quot;)).build(); MobileAds.setRequestConfiguration(configuration); </code></pre> <p>Now just load the ad and it will pop up. Congratz. :)</p> <hr /> <p>Scenario 2: <strong>While the App Is In Production</strong></p> <p>This is pretty simple part...</p> <ol> <li>Just remove the .setTestDeviceIds(Arrays.asList(&quot;your device id should go here&quot;)) part from the code...</li> <li>Link your AdMob App to PlayStore. [Is your app published? Yes...yes...and on...]</li> <li>Just opt for ad.</li> <li>And check if Ads are enabled in your app settings on play console.</li> <li>It should work now. Congratz.</li> </ol>
31,379,795
How to apply plugin to only one flavor in gradle?
<p>I have a multi-flavored, multi-build-typed android project and I want to integrate the NewRelic plugin. But I have to apply it only for one of the customers, thus only for one product flavor.<br> NewRelic uses instrumentation and the plugin would generate code in other flavors if I applied the plugin there, and that is not permitted for us.</p> <p>So my question is: How can I use the <code>apply plugin: something</code> command in the gradle file to be applied to only one of my flavors?</p>
43,336,869
7
0
null
2015-07-13 09:31:10.297 UTC
11
2022-02-09 06:17:57.117 UTC
2015-07-13 09:41:20.26 UTC
null
2,545,756
null
2,545,756
null
1
71
android|android-studio|gradle|newrelic|android-productflavors
12,666
<p>Use this code:</p> <pre><code>if (!getGradle().getStartParameter().getTaskRequests() .toString().contains("Develop")){ apply plugin: 'com.google.gms.google-services' } </code></pre> <p><code>getGradle().getStartParameter().getTaskRequests().toString()</code> returns something like <code>[DefaultTaskExecutionRequest{args=[:app:generateDevelopDebugSources],projectPath='null'}]</code> so as stated in the comments <code>Develop</code> must start with an uppercase.</p>
40,570,985
ListView in BottomSheet
<p>I ran into a problem where I had a simple <code>ListView</code> in a <code>BottomSheet</code> and <code>ListView</code> had enough items to fill the screen and scroll even more.</p> <p>When I scroll down, everything seems to work however when I tried to scroll back up, it was scrolling the <code>BottomSheet</code> itself and closing the view instead of just scrolling the <code>ListView</code>.</p> <p>I was able to find a solution after a while and since I couldn't find it anywhere here, I figured I would post it here.</p>
40,570,986
9
0
null
2016-11-13 05:47:02.353 UTC
12
2022-09-14 06:41:20.857 UTC
null
null
null
null
3,866,010
null
1
24
android|listview|bottom-sheet
18,354
<p>The solution is to extend the <code>ListView</code> like this: </p> <pre><code>public class BottomSheetListView extends ListView { public BottomSheetListView (Context context, AttributeSet p_attrs) { super (context, p_attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { if (canScrollVertically(this)) { getParent().requestDisallowInterceptTouchEvent(true); } return super.onTouchEvent(ev); } public boolean canScrollVertically (AbsListView view) { boolean canScroll = false; if (view !=null &amp;&amp; view.getChildCount ()&gt; 0) { boolean isOnTop = view.getFirstVisiblePosition() != 0 || view.getChildAt(0).getTop() != 0; boolean isAllItemsVisible = isOnTop &amp;&amp; view.getLastVisiblePosition() == view.getChildCount(); if (isOnTop || isAllItemsVisible) { canScroll = true; } } return canScroll; } } </code></pre> <p>Then in your layout file <code>bottom_sheet_view.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;com.mypackage.name.BottomSheetListView android:id="@+id/listViewBtmSheet" android:divider="@color/colorPrimary" android:dividerHeight="1dp" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Then finally, in your <code>Activity</code>/<code>Fragment</code>:</p> <pre><code>BottomSheetDialog dialog = new BottomSheetDialog(context); dialog.setContentView(R.layout.bottom_sheet_view); BottomSheetListView listView = (BottomSheetListView) dialog.findViewById(R.id.listViewBtmSheet); // apply some adapter - add some data to listview dialog.show(); </code></pre> <p>This will provide a <code>BottomSheet</code> that is fully working with <code>ListView</code> scroll.</p>
38,702,032
Android Studio: Gradle Refresh Failed - Could not find com.android.tools.build:gradle:2.2.0-alpha6
<p>I've just pulled down an Android project from git, and Android Studio is giving me the following error whenever I attempt to open it;</p> <pre><code>Error:Could not find com.android.tools.build:gradle:2.2.0-alpha6. Searched in the following locations: https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0-alpha6/gradle-2.2.0-alpha6.pom https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.0-alpha6/gradle-2.2.0-alpha6.jar https://maven.fabric.io/public/com/android/tools/build/gradle/2.2.0-alpha6/gradle-2.2.0-alpha6.pom https://maven.fabric.io/public/com/android/tools/build/gradle/2.2.0-alpha6/gradle-2.2.0-alpha6.jar Required by: newApp_Android:app:unspecified </code></pre> <p>I've installed Gradle locally, and set up environment paths via System.</p> <p>Under Project Structure/Project, the following setup is in use;</p> <pre><code>Gradle Version : 2.10 Android Plugin Version : 2.2.0-alpha6 Android Plugin Repository : jcenter Default Library Repository : jcenter </code></pre> <p>Could anyone point me in the right direction on this?</p>
39,654,136
7
1
null
2016-08-01 14:56:19.61 UTC
11
2018-12-10 14:19:57.59 UTC
null
null
null
null
1,478,715
null
1
56
android|android-studio|gradle
53,016
<p>This is because the build process is unable to find the dependency in Maven repository. Add <strong>jcenter()</strong> along with <strong>mavenCentral()</strong> in your project level <strong>build.gradle</strong> file.</p> <pre><code>buildscript { repositories { mavenCentral() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.0' } } </code></pre>
38,913,163
How to change the default target branch for merges in Gitlab
<p>we are using Gitlab 8.10.1 with many groups and projects. Many of the projects happen to be forks of other projects. Our problem is that whenever somebody opens a merge request for a project the default target branch is NOT the default branch of the project but from one very specific other project. Is there a way to override this setting somehow? Just to make it clear, I know how to set the default branch of a project and those settings appear to be correct, however gitlab doesn't seem to use them when creating merge requests. This issue is very annoying and has led to weird situations when people didn't pay attention and made merge requests with a completely different "master" as target.</p>
44,804,117
5
1
null
2016-08-12 08:16:27.233 UTC
8
2021-04-24 16:19:10.92 UTC
null
null
null
null
4,328,372
null
1
40
git|merge|settings|gitlab
23,898
<p>The default MR target depends on whether or not the repository is a <a href="https://docs.gitlab.com/ce/user/project/repository/forking_workflow.html" rel="noreferrer">GitLab fork</a>.</p> <h1>Forks</h1> <p>If the repository is a <a href="https://docs.gitlab.com/ce/user/project/repository/forking_workflow.html" rel="noreferrer">GitLab fork</a>, then the default MR target will be the default branch of the upstream repository. This relationship can be removed via the &quot;Remove fork relationship&quot; option on the Project settings page, after which the default MR target will be determined as normal for a non-fork repository (described below).</p> <p>At time of writing, it is not possible to override the default MR target without removing the fork relationship, but that functionality has been requested in gitlab issue <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/14522" rel="noreferrer">#14522</a>.</p> <h1>Non-Forks</h1> <p>If the repository has no fork relationship, then the Default Branch setting on the Project settings page sets both (1) the default MR target, and (2) the HEAD reference of the repo on the GitLab server (which determines the branch that's checked out when the repo is cloned). Note that, due to a <a href="https://stackoverflow.com/a/8841024/1009155">bug/quirk in git</a>, <a href="https://gitlab.com/gitlab-org/gitlab-foss/-/issues/14835" rel="noreferrer">problems can occur</a> if a branch that was once the Default Branch is later deleted from GitLab.</p> <p>At time of writing, it is not possible to change the default MR target independently of the Default Branch, but this functionality has been requested in gitlab issue <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/17909" rel="noreferrer">#17909</a>.</p>
27,425,852
What uses / respects the .node-version file?
<p>I've searched Stack Overflow and GitHub (for both node and nvm) for an answer, but to no avail.</p> <p>In some repos (<a href="https://github.com/atom/atom/blob/master/.node-version">like GitHub's Atom text editor</a>, for instance), I've come across a <code>.node-version</code> file. It seems to be analogous to the <code>.ruby-version</code> standard file that works with any Ruby version manager to set the current version of Ruby correctly for the project.</p> <p><a href="https://github.com/creationix/nvm#usage">But as far as I can tell from its documentation</a>, nvm (Node Version Manager) only respects a <code>.nvmrc</code> file - it mentions nothing about a more general <code>.node-version</code> file. And there's no mention of <code>.node-version</code> in node's documentation (and I wouldn't expect there to be, since it doesn't ship with a version manager out of the box). I'm not aware of any other node version manager in heavy use.</p> <p>So my question is, what is <code>.node-version</code>? What tools actually use it? Is it just an alias for <code>.nvmrc</code>, or am I missing something here?</p>
27,460,959
7
0
null
2014-12-11 15:01:11.993 UTC
19
2022-05-28 04:22:00.29 UTC
null
null
null
null
1,459,498
null
1
60
node.js|nvm
29,537
<p>There are a few version managers for node.js respecting <code>.node-version</code> file:</p> <ul> <li><a href="https://www.npmjs.com/package/avn" rel="nofollow noreferrer">avn</a> - Automatic Node Version Switching</li> <li><a href="https://github.com/OiNutter/nodenv" rel="nofollow noreferrer">nodenv</a> - Yet another version managers</li> <li><a href="https://github.com/asdf-vm/asdf" rel="nofollow noreferrer">asdf</a> - Extendable version manager with support for Ruby, Node.js, Elixir, Erlang &amp; more, provided you <a href="https://asdf-vm.com/#/core-configuration?id=tool-versions" rel="nofollow noreferrer">configure it accordingly</a></li> <li><a href="https://github.com/jasongin/nvs" rel="nofollow noreferrer">nvs</a> - Node Version Switcher</li> </ul> <p>There may be some other version managers, but I'm not aware of them.</p> <p>I don't know which particular version manager Atom uses. <a href="https://github.com/OiNutter/nodenv" rel="nofollow noreferrer">nodenv</a> have more stars on GitHub, but <a href="https://www.npmjs.com/package/avn" rel="nofollow noreferrer">avn</a> looks more mature and better maintained for me, not to mention its compatibility with both <a href="https://github.com/tj/n" rel="nofollow noreferrer">n</a> and <a href="https://github.com/creationix/nvm" rel="nofollow noreferrer">nvm</a>.</p>
34,929,630
onEnter Transitions with React Router and Redux Simple Router Dont Render New Route's Component
<p>I have an app using react @0.14, redux @3.05, react-router @1.0.3, and redux-simple-router @2.0.2. I'm trying to configure onEnter transitions for some of my routes based on store state. The transition hooks successfully fire and push new state to my store, which changes the url. However, the actual component that is rendered on the page is the original component handler from the route match, not the new component handler for the new url.</p> <p>Here is what my <code>routes.js</code> file looks like</p> <pre><code>export default function configRoutes(store) { const authTransition = function authTransition(location, replaceWith) { const state = store.getState() const user = state.user if (!user.isAuthenticated) { store.dispatch(routeActions.push('/login')) } } return ( &lt;Route component={App}&gt; &lt;Route path="/" component={Home}/&gt; &lt;Route path="/login" component={Login}/&gt; &lt;Route path="/dashboard" component={Dashboard} onEnter={authTransition}/&gt; &lt;Route path="/workouts" component={Workout} onEnter={authTransition}&gt; &lt;IndexRoute component={WorkoutsView}/&gt; &lt;Route path="/workouts/create" component={WorkoutCreate}/&gt; &lt;/Route&gt; &lt;/Route&gt; ) } </code></pre> <p>Here is my <code>Root.js</code> component that gets inserted into the DOM</p> <pre><code>export default class Root extends React.Component { render() { const { store, history } = this.props const routes = configRoutes(store) return ( &lt;Provider store={store}&gt; &lt;div&gt; {isDev ? &lt;DevTools /&gt; : null} &lt;Router history={history} children={routes} /&gt; &lt;/div&gt; &lt;/Provider&gt; ) } } </code></pre> <p>To clarify, if I go to '/workouts', it will fire the onEnter authTransition hook, dispatch the redux-simple-router push action, change the url to '/login', but will display the Workout component on the page. Looking in Redux DevTools shows that <code>state -&gt; router -&gt; location -&gt; pathname</code> is '/login'.</p> <p>The state flow is</p> <ol> <li>@@INIT</li> <li>@@ROUTER/UPDATE_LOCATION (/workouts)</li> <li>@@ROUTER/UPDATE_LOCATION (/login)</li> </ol> <p>Am I passing the store to the routes incorrectly? I can't figure out why the next Router/Update_Location doesn't work</p>
34,938,629
1
0
null
2016-01-21 16:52:33.66 UTC
9
2016-03-09 23:59:32.003 UTC
2016-03-09 23:59:32.003 UTC
null
1,114
null
4,086,590
null
1
7
javascript|reactjs|react-router|redux|react-router-redux
15,979
<p>Turns out you want to use the react-router api (replace), not the redux-simple-router to control your transitions.</p> <pre><code>const authTransition = function authTransition(nextState, replace, callback) { const state = store.getState() const user = state.user // todo: in react-router 2.0, you can pass a single object to replace :) if (!user.isAuthenticated) { replace({ nextPathname: nextState.location.pathname }, '/login', nextState.location.query) } callback() } </code></pre> <p>Also, be careful. I saw a lot of documentation out there for the react-router replace where you pass a single object. That's for react-router 2.0-rc*. If you're using react-router 1.0, you're going to want to pass replace 3 separate arguments.</p>
53,794,754
Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView
<p>I got this error just after converted the adapter code to Kotlin:</p> <pre><code>java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView at ...MyAdapter.getView(Unknown Source:35) at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:220) at android.widget.AbsListView.obtainView(AbsListView.java:2366) </code></pre> <p>The error fires when inflating the row:</p> <pre><code>class LegalAdapter internal constructor(private val activity: Activity, private val list: ArrayList&lt;Item&gt;) : BaseAdapter() { override fun getView(position: Int, convertView: View, parent: ViewGroup): View { val layoutInflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater @SuppressLint("ViewHolder") val row = layoutInflater.inflate(R.layout.legal_list_item, parent, false) //exception is throw here </code></pre> <p>Apparently, some parameter that shouldn't be null is null, and kotlin check it. Problem is i can't even debug the new kotlin code.</p>
53,794,852
4
0
null
2018-12-15 15:49:09.383 UTC
3
2020-11-04 06:42:22.25 UTC
null
null
null
null
2,700,303
null
1
31
android|kotlin|adaptor
29,494
<p>The <code>getView()</code> method is a part of the <code>Adapter</code> interface, and is defined in Java. <a href="https://developer.android.com/reference/android/widget/Adapter#getView(int,%20android.view.View,%20android.view.ViewGroup)" rel="noreferrer">Documentation here</a>. The important part is this note about the <code>convertView</code> parameter:</p> <blockquote> <p><strong>View</strong>: The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using.</p> </blockquote> <p>This means that it's quite valid for the framework to pass <code>null</code> values for <code>convertView</code> to this method (meaning that you need to create a new view and return that, rather than recycling an old view).</p> <p>In turn, this means that the Kotlin definition of <code>convertView</code> must be of type <code>View?</code>, not just <code>View</code>. So change your function signature to this:</p> <pre><code>override fun getView(position: Int, convertView: View?, parent: ViewGroup): View </code></pre>
63,432,473
Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS
<p>I'm am trying to fetch a serverless function from a react app in development mode with the following code.</p> <pre><code>let response = await fetch(url, { method: 'POST', mode: 'cors', body: &quot;param=&quot; + paramVar, }) .then(response =&gt; response.json()); </code></pre> <p>The backend function is a Python Cloud function with the following code:</p> <pre><code>def main(request): # CORS handling if request.method == 'OPTIONS': # Allows GET requests from any origin with the Content-Type # header and caches preflight response for an 3600s headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } return ('', 204, headers) # Set CORS headers for the main request headers = { 'Content-Type':'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', } # Process request return (json.dumps(response), 200, headers) </code></pre> <p>But I keep getting the following error:</p> <pre><code>Access to fetch at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. </code></pre> <p>When I try to perform the same request using curl I get a proper response. Using curl to get the options gives me the following:</p> <pre><code>HTTP/2 204 access-control-allow-headers: Content-Type access-control-allow-methods: GET, POST access-control-allow-origin: * access-control-max-age: 3600 content-type: text/html; charset=utf-8 date: Sun, 16 Aug 2020 01:29:41 GMT </code></pre> <p>Anyone can help me understand why I'm not able to get a response at my front-end? The 'Access-Control-Allow-Origin' is present in the headers so I really don't understand what is the cause of this error.</p>
64,192,273
3
2
null
2020-08-16 02:07:52.24 UTC
1
2020-10-04 07:49:10.767 UTC
null
null
null
null
3,193,886
null
1
10
javascript|python|reactjs|google-cloud-functions|fetch-api
44,309
<p>There was actually a bug in the backend that was only triggered by some additional headers added by the browser. In that particular case, the server was returning a 404 error which wouldn't contain my header definitions and would cause the CORS policy block.</p> <p>I was only able to identify the bug after I used devtools to track the request sent by the browser and replicated all the headers in my curl request. After fixing the function logic the problem was fixed.</p>
28,329,185
How to prevent screen lock on my application with swift on iOS
<p>How can I prevent screen lock only when using Navigation?</p> <p>Waze has the option to do that, how can I do this in my App?</p>
28,332,647
5
0
null
2015-02-04 18:55:33.533 UTC
29
2021-12-30 19:02:56.407 UTC
2020-01-07 02:32:48.66 UTC
null
1,265,393
null
2,336,714
null
1
134
ios|swift|locking|screen
60,162
<p>Use this:</p> <p><strong>Objective-C:</strong></p> <pre><code>[[UIApplication sharedApplication] setIdleTimerDisabled: YES]; </code></pre> <p><strong>Swift (legacy):</strong></p> <pre><code>UIApplication.sharedApplication().idleTimerDisabled = true </code></pre> <p><strong>Swift 3 and above:</strong></p> <pre><code>UIApplication.shared.isIdleTimerDisabled = true </code></pre> <p>Make sure to import <code>UIKit</code>.</p> <p><a href="https://developer.apple.com/documentation/uikit/uiapplication/1623070-isidletimerdisabled" rel="noreferrer">Here</a> is the link to the documentation from developer.apple.com.</p>
3,071,891
Guice and properties files
<p>Does anybody have an example of how to use Google Guice to inject properties from a .properties file. I was told Guice was able to validate that all needed properties exist when the injector starts up.</p> <p>At this time I cannot find anything on the guice wiki about this.</p>
3,072,210
1
0
null
2010-06-18 17:36:55.89 UTC
18
2018-12-18 08:12:51.717 UTC
null
null
null
null
97,901
null
1
43
java|dependency-injection|guice
19,218
<p>You can bind properties using <code>Names.bindProperties(binder(), getProperties())</code>, where <code>getProperties</code> returns a <code>Properties</code> object or a <code>Map&lt;String, String&gt;</code> (reading the properties file as a <code>Properties</code> object is up to you).</p> <p>You can then inject them by name using <code>@Named</code>. If you had a properties file:</p> <pre><code>foo=bar baz=true </code></pre> <p>You could inject the values of those properties anywhere you wanted, like this:</p> <pre><code>@Inject public SomeClass(@Named("foo") String foo, @Named("baz") boolean baz) {...} </code></pre> <p>Guice can convert values from strings to the type being injected, such as the <code>boolean</code> above, automatically (assuming the string is an appropriate format). This works for primitive types, enums and class literals. </p>
21,293,456
Scroll horizontally starting from right to left with CSS overflow:scroll
<p>So I am wondering if there is a possibility to have a different starting position with the <code>overflow:scroll</code> value;</p> <p>When you start scrolling in a <code>div</code> the default behaviour is to scroll from left to right:</p> <pre><code>|&lt;--Scrollbar-Starting-Left--&gt;_________________________________________________| </code></pre> <p>would it possible that it starts at the right?</p> <pre><code>|_________________________________________________&lt;--Scrollbar-Starting-Right--&gt;| </code></pre> <p><a href="http://jsfiddle.net/marczking/HyRTx/" rel="nofollow noreferrer">In my example</a> the <code>red</code> and <code>green</code> items are first visible, I'd like the <code>green</code> and <code>blue</code> item to be visible first :)</p> <p>I've tried <code>direction:rtl;</code> but no luck</p>
21,293,594
6
0
null
2014-01-22 20:37:17.883 UTC
4
2020-08-11 23:09:26.207 UTC
2020-08-11 23:09:26.207 UTC
null
8,112,776
null
2,102,463
null
1
22
javascript|jquery|html|css|scroll
55,558
<h3>You can of course use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/direction" rel="noreferrer"><code>direction:rtl</code></a></h3> <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>document.querySelector('input').addEventListener('input', function(){ document.querySelector('.box').scrollLeft = this.value; })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.box{ width: 320px; height: 100px; border:1px solid red; overflow: scroll; direction: rtl; /* &lt;-- the trick */ } .box::before{ content:''; display:block; width:400%; height:1px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='box'&gt;&lt;/div&gt; &lt;br&gt; &lt;input placeholder='scrollLeft value'&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/4d9C5/" rel="noreferrer"><strong>FiddleDemo</strong></a></p> <p>This may be useful using direction <a href="http://css-tricks.com/almanac/properties/d/direction/" rel="noreferrer">http://css-tricks.com/almanac/properties/d/direction/</a></p>
38,821,631
CAGradientLayer diagonal gradient
<p><a href="https://i.stack.imgur.com/UYqru.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UYqru.png" alt="enter image description here"></a></p> <p>I use the following CAGradientLayer:</p> <pre><code>let layer = CAGradientLayer() layer.colors = [ UIColor.redColor().CGColor, UIColor.greenColor().CGColor, UIColor.blueColor().CGColor ] layer.startPoint = CGPointMake(0, 1) layer.endPoint = CGPointMake(1, 0) layer.locations = [0.0, 0.6, 1.0] </code></pre> <p>But when I set bounds property for the layer, it just stretches a square gradient. I need a result like in Sketch 3 app image (see above).</p> <p>How can I achieve this?</p>
43,176,174
3
2
null
2016-08-08 05:05:27.64 UTC
21
2018-09-05 10:28:58.63 UTC
null
null
null
null
3,574,762
null
1
26
ios|swift|calayer|cagradientlayer
8,327
<p><strong>Update:</strong> Use context.drawLinearGradient() instead of CAGradientLayer in a <a href="https://stackoverflow.com/a/40345259">manner similar to the following</a>. It will draw gradients that are consistent with Sketch/Photoshop.</p> <p>If you absolutely must use CAGradientLayer, then here is the math you'll need to use...</p> <hr> <p>It took some time to figure out, but from careful observation, I found out that Apple's implementation of gradients in CAGradientLayer is pretty odd:</p> <ol> <li>First it converts the view to a square.</li> <li>Then it applies the gradient using start/end points.</li> <li>The middle gradient will indeed form a 90 degree angle in this resolution.</li> <li>Finally, it squishes the view down to the original size.</li> </ol> <p>This means that the middle gradient will no longer form a 90 degree angle in the new size. This contradicts the behavior of virtually every other paint application: Sketch, Photoshop, etc.</p> <p>If you want to implement start/end points as it works in Sketch, you'll need to translate the start/end points to account for the fact that Apple is going to squish the view.</p> <hr> <h1>Steps to perform (Diagrams)</h1> <p><a href="https://i.stack.imgur.com/rKwDc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rKwDc.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/u7pI1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u7pI1.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/HtJcc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HtJcc.png" alt="enter image description here"></a></p> <h1>Code</h1> <pre><code>import UIKit /// Last updated 4/3/17. /// See https://stackoverflow.com/a/43176174 for more information. public enum LinearGradientFixer { public static func fixPoints(start: CGPoint, end: CGPoint, bounds: CGSize) -&gt; (CGPoint, CGPoint) { // Naming convention: // - a: point a // - ab: line segment from a to b // - abLine: line that passes through a and b // - lineAB: line that passes through A and B // - lineSegmentAB: line segment that passes from A to B if start.x == end.x || start.y == end.y { // Apple's implementation of horizontal and vertical gradients works just fine return (start, end) } // 1. Convert to absolute coordinates let startEnd = LineSegment(start, end) let ab = startEnd.multiplied(multipliers: (x: bounds.width, y: bounds.height)) let a = ab.p1 let b = ab.p2 // 2. Calculate perpendicular bisector let cd = ab.perpendicularBisector // 3. Scale to square coordinates let multipliers = calculateMultipliers(bounds: bounds) let lineSegmentCD = cd.multiplied(multipliers: multipliers) // 4. Create scaled perpendicular bisector let lineSegmentEF = lineSegmentCD.perpendicularBisector // 5. Unscale back to rectangle let ef = lineSegmentEF.divided(divisors: multipliers) // 6. Extend line let efLine = ef.line // 7. Extend two lines from a and b parallel to cd let aParallelLine = Line(m: cd.slope, p: a) let bParallelLine = Line(m: cd.slope, p: b) // 8. Find the intersection of these lines let g = efLine.intersection(with: aParallelLine) let h = efLine.intersection(with: bParallelLine) if let g = g, let h = h { // 9. Convert to relative coordinates let gh = LineSegment(g, h) let result = gh.divided(divisors: (x: bounds.width, y: bounds.height)) return (result.p1, result.p2) } return (start, end) } private static func unitTest() { let w = 320.0 let h = 60.0 let bounds = CGSize(width: w, height: h) let a = CGPoint(x: 138.5, y: 11.5) let b = CGPoint(x: 151.5, y: 53.5) let ab = LineSegment(a, b) let startEnd = ab.divided(divisors: (x: bounds.width, y: bounds.height)) let start = startEnd.p1 let end = startEnd.p2 let points = fixPoints(start: start, end: end, bounds: bounds) let pointsSegment = LineSegment(points.0, points.1) let result = pointsSegment.multiplied(multipliers: (x: bounds.width, y: bounds.height)) print(result.p1) // expected: (90.6119039567129, 26.3225059181603) print(result.p2) // expected: (199.388096043287, 38.6774940818397) } } private func calculateMultipliers(bounds: CGSize) -&gt; (x: CGFloat, y: CGFloat) { if bounds.height &lt;= bounds.width { return (x: 1, y: bounds.width/bounds.height) } else { return (x: bounds.height/bounds.width, y: 1) } } private struct LineSegment { let p1: CGPoint let p2: CGPoint init(_ p1: CGPoint, _ p2: CGPoint) { self.p1 = p1 self.p2 = p2 } init(p1: CGPoint, m: CGFloat, distance: CGFloat) { self.p1 = p1 let line = Line(m: m, p: p1) let measuringPoint = line.point(x: p1.x + 1) let measuringDeltaH = LineSegment(p1, measuringPoint).distance let deltaX = distance/measuringDeltaH self.p2 = line.point(x: p1.x + deltaX) } var length: CGFloat { let dx = p2.x - p1.x let dy = p2.y - p1.y return sqrt(dx * dx + dy * dy) } var distance: CGFloat { return p1.x &lt;= p2.x ? length : -length } var midpoint: CGPoint { return CGPoint(x: (p1.x + p2.x)/2, y: (p1.y + p2.y)/2) } var slope: CGFloat { return (p2.y-p1.y)/(p2.x-p1.x) } var perpendicularSlope: CGFloat { return -1/slope } var line: Line { return Line(p1, p2) } var perpendicularBisector: LineSegment { let p1 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: -distance/2).p2 let p2 = LineSegment(p1: midpoint, m: perpendicularSlope, distance: distance/2).p2 return LineSegment(p1, p2) } func multiplied(multipliers: (x: CGFloat, y: CGFloat)) -&gt; LineSegment { return LineSegment( CGPoint(x: p1.x * multipliers.x, y: p1.y * multipliers.y), CGPoint(x: p2.x * multipliers.x, y: p2.y * multipliers.y)) } func divided(divisors: (x: CGFloat, y: CGFloat)) -&gt; LineSegment { return multiplied(multipliers: (x: 1/divisors.x, y: 1/divisors.y)) } } private struct Line { let m: CGFloat let b: CGFloat /// y = mx+b init(m: CGFloat, b: CGFloat) { self.m = m self.b = b } /// y-y1 = m(x-x1) init(m: CGFloat, p: CGPoint) { // y = m(x-x1) + y1 // y = mx-mx1 + y1 // y = mx + (y1 - mx1) // b = y1 - mx1 self.m = m self.b = p.y - m*p.x } init(_ p1: CGPoint, _ p2: CGPoint) { self.init(m: LineSegment(p1, p2).slope, p: p1) } func y(x: CGFloat) -&gt; CGFloat { return m*x + b } func point(x: CGFloat) -&gt; CGPoint { return CGPoint(x: x, y: y(x: x)) } func intersection(with line: Line) -&gt; CGPoint? { // Line 1: y = mx + b // Line 2: y = nx + c // mx+b = nx+c // mx-nx = c-b // x(m-n) = c-b // x = (c-b)/(m-n) let n = line.m let c = line.b if m-n == 0 { // lines are parallel return nil } let x = (c-b)/(m-n) return point(x: x) } } </code></pre> <h1>Proof it works regardless of rectangle size</h1> <p>I tried this with a view <code>size=320x60</code>, <code>gradient=[red@0,[email protected],blue@1]</code>, <code>startPoint = (0,1)</code>, and <code>endPoint = (1,0)</code>.</p> <h3>Sketch 3:</h3> <p><a href="https://i.stack.imgur.com/5xP2D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5xP2D.png" alt="enter image description here"></a></p> <h3>Actual generated iOS screenshot using the code above:</h3> <p><a href="https://i.stack.imgur.com/KwuXZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KwuXZ.png" alt="enter image description here"></a></p> <p>Note that the angle of the green line looks 100% accurate. The difference lies in how the red and blue are blended. I can't tell if that's because I'm calculating the start/end points incorrectly, or if it's just a difference in how Apple blends gradients vs. how Sketch blends gradients.</p>
32,189,590
Is it possible to rename an Azure App Service plan using the Azure Portal?
<p>Is it possible to rename an <strong>App Service Plan</strong>? </p> <p>I have already tried in both the old and new portals and can't find any rename options.</p>
32,192,304
2
0
null
2015-08-24 18:50:44.543 UTC
5
2021-07-29 08:42:25.2 UTC
2021-07-29 08:42:25.2 UTC
null
382,177
null
75,594
null
1
89
azure|azure-functions|azure-web-app-service|rename
32,598
<p>No, you can't. </p> <p>However, if you create a new App Service Plan in the same region and resource group then you can move all your sites to the new App Service Plan and delete the old one.</p>
31,234,621
Variation on "How to plot decision boundary of a k-nearest neighbor classifier from Elements of Statistical Learning?"
<p>This is a question related to <a href="https://stats.stackexchange.com/questions/21572/how-to-plot-decision-boundary-of-a-k-nearest-neighbor-classifier-from-elements-o">https://stats.stackexchange.com/questions/21572/how-to-plot-decision-boundary-of-a-k-nearest-neighbor-classifier-from-elements-o</a></p> <p>For completeness, here's the original example from that link:</p> <pre><code>library(ElemStatLearn) require(class) x &lt;- mixture.example$x g &lt;- mixture.example$y xnew &lt;- mixture.example$xnew mod15 &lt;- knn(x, xnew, g, k=15, prob=TRUE) prob &lt;- attr(mod15, "prob") prob &lt;- ifelse(mod15=="1", prob, 1-prob) px1 &lt;- mixture.example$px1 px2 &lt;- mixture.example$px2 prob15 &lt;- matrix(prob, length(px1), length(px2)) par(mar=rep(2,4)) contour(px1, px2, prob15, levels=0.5, labels="", xlab="", ylab="", main= "15-nearest neighbour", axes=FALSE) points(x, col=ifelse(g==1, "coral", "cornflowerblue")) gd &lt;- expand.grid(x=px1, y=px2) points(gd, pch=".", cex=1.2, col=ifelse(prob15&gt;0.5, "coral", "cornflowerblue")) box() </code></pre> <p>I've been playing with that example, and would like to try to make it work with three classes. I can change some values of g with something like</p> <pre><code>g[8:16] &lt;- 2 </code></pre> <p>just to pretend that there are some samples which are from a third class. I can't make the plot work, though. I guess I need to change the lines that deal with the proportion of votes for winning class:</p> <pre><code>prob &lt;- attr(mod15, "prob") prob &lt;- ifelse(mod15=="1", prob, 1-prob) </code></pre> <p>and also the levels on the contour:</p> <pre><code>contour(px1, px2, prob15, levels=0.5, labels="", xlab="", ylab="", main= "15-nearest neighbour", axes=FALSE) </code></pre> <p>I am also not sure contour is the right tool for this. One alternative that works is to create a matrix of data that covers the region I'm interested, classify each point of this matrix and plot those with a large marker and different colors, similar to what is being done with the points(gd...) bit.</p> <p>The final purpose is to be able to show different decision boundaries generated by different classifiers. Can someone point me to the right direction?</p> <p>thanks Rafael</p>
31,236,327
1
0
null
2015-07-05 20:20:26.917 UTC
8
2015-08-08 19:38:45.88 UTC
2017-04-13 12:44:14 UTC
null
-1
null
5,030,105
null
1
11
r|visualization|cluster-analysis|nearest-neighbor
8,657
<p>Separating the main parts in the code will help outlining how to achieve this:</p> <p><strong>Test data with 3 classes</strong></p> <pre><code> train &lt;- rbind(iris3[1:25,1:2,1], iris3[1:25,1:2,2], iris3[1:25,1:2,3]) cl &lt;- factor(c(rep("s",25), rep("c",25), rep("v",25))) </code></pre> <p><strong>Test data covering a grid</strong></p> <pre><code> require(MASS) test &lt;- expand.grid(x=seq(min(train[,1]-1), max(train[,1]+1), by=0.1), y=seq(min(train[,2]-1), max(train[,2]+1), by=0.1)) </code></pre> <p><strong>Classification for that grid</strong></p> <p>3 classes obviously</p> <pre><code> require(class) classif &lt;- knn(train, test, cl, k = 3, prob=TRUE) prob &lt;- attr(classif, "prob") </code></pre> <p><strong>Data structure for plotting</strong></p> <pre><code> require(dplyr) dataf &lt;- bind_rows(mutate(test, prob=prob, cls="c", prob_cls=ifelse(classif==cls, 1, 0)), mutate(test, prob=prob, cls="v", prob_cls=ifelse(classif==cls, 1, 0)), mutate(test, prob=prob, cls="s", prob_cls=ifelse(classif==cls, 1, 0))) </code></pre> <p><strong>Plot</strong></p> <pre><code> require(ggplot2) ggplot(dataf) + geom_point(aes(x=x, y=y, col=cls), data = mutate(test, cls=classif), size=1.2) + geom_contour(aes(x=x, y=y, z=prob_cls, group=cls, color=cls), bins=2, data=dataf) + geom_point(aes(x=x, y=y, col=cls), size=3, data=data.frame(x=train[,1], y=train[,2], cls=cl)) </code></pre> <p><img src="https://i.stack.imgur.com/xf3ZC.png" alt="plot"></p> <p>We can also be a little fancier and plot the probability of class membership as a indication of the "confidence".</p> <pre><code> ggplot(dataf) + geom_point(aes(x=x, y=y, col=cls, size=prob), data = mutate(test, cls=classif)) + scale_size(range=c(0.8, 2)) + geom_contour(aes(x=x, y=y, z=prob_cls, group=cls, color=cls), bins=2, data=dataf) + geom_point(aes(x=x, y=y, col=cls), size=3, data=data.frame(x=train[,1], y=train[,2], cls=cl)) + geom_point(aes(x=x, y=y), size=3, shape=1, data=data.frame(x=train[,1], y=train[,2], cls=cl)) </code></pre> <p><img src="https://i.stack.imgur.com/rlWOa.png" alt="enter image description here"></p>
41,764,312
Combining Bar and Line chart (double axis) in ggplot2
<p>I have <code>double-y-axis</code> chart made in <code>Excel</code>. In Excel it requires only basic skills. What I'd like to do is to replicate this chart using the <code>ggplot2</code> library in <code>R</code>.</p> <p><a href="https://i.stack.imgur.com/izWo5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/izWo5.png" alt="enter image description here"></a></p> <p>I have already done this, but I need to plot Response on <code>2nd-y-axis</code>.</p> <p><a href="https://i.stack.imgur.com/ICfNi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ICfNi.png" alt="enter image description here"></a></p> <p>I enclose reproducible code I've used:</p> <pre><code>#Data generation Year &lt;- c(2014, 2015, 2016) Response &lt;- c(1000, 1100, 1200) Rate &lt;- c(0.75, 0.42, 0.80) df &lt;- data.frame(Year, Response, Rate) #Chart library(ggplot2) ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.9*Response), colour="black") </code></pre>
41,764,433
2
0
null
2017-01-20 12:59:28.343 UTC
10
2021-06-15 14:18:18.91 UTC
2017-03-20 12:19:12.767 UTC
null
636,987
null
2,969,277
null
1
23
r|ggplot2|bar-chart|linechart|yaxis
65,874
<p>First, scale <code>Rate</code> by <code>Rate*max(df$Response)</code> and modify the <code>0.9</code> scale of Response text.</p> <p>Second, include a second axis via <code>scale_y_continuous(sec.axis=...)</code>:</p> <pre><code>ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate*max(df$Response)),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate*max(df$Response)), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+ scale_y_continuous(sec.axis = sec_axis(~./max(df$Response))) </code></pre> <p>Which yields:</p> <p><a href="https://i.stack.imgur.com/47SZJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/47SZJ.png" alt="enter image description here"></a></p>
35,665,903
How to write Helper class in typescript?
<p>I have a problem when use <code>typeScript</code> with <code>angular2</code>.<br> I want create one <code>helper.ts</code> file exports many classed/functions common to re-use.<br> But <code>Helper class</code> need import others service in constructor, so that when another class import <code>Helper class</code>, It have to set param is those service. I don't want this. </p> <p>How I can write <code>Helper class</code>, that I can use anywhere when <code>import {Helper} from ..</code> </p> <p>This is my sample: Helper.ts</p> <pre><code>import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate'; import {Inject, Component} from 'angular2/core'; @Component({ providers: [TranslateService] }) export class Helpper { public trans; public lang; public properties; constructor(trans: TranslateService) { this.trans = trans; //This is variable for translate function this.lang = this.trans.currentLang; this.properties = this.trans.translations[this.lang]; } translate(key) { return this.properties[key]; } } </code></pre> <p>RenderTab.ts</p> <pre><code>import {Component, Inject, Injectable} from 'angular2/core'; import {Helper} from './helpper' @Component({ providers: [Helper] }) export class RenderTab { public helper; constructor(helper: Helper) { this.helper = helper; } render() { var test = this.helper.translate('string'); } } </code></pre> <p>HomePage.ts</p> <pre><code>import {Component, Inject, Injectable} from 'angular2/core'; import {RenderTab} from './RenderTab' @Component({ selector: 'div', templateUrl: './HomePage.html', providers: [RenderTab] }) export class ColorPicker { public renderTab; constructor(renderTab: RenderTab) { this.renderTab = renderTab; var test = this.renderTab.render(); } } </code></pre> <p>Please help me, thanks.</p>
35,666,878
3
0
null
2016-02-27 05:00:23.54 UTC
9
2020-06-03 21:21:11.463 UTC
null
null
null
null
4,732,036
null
1
46
typescript|angular
91,960
<p>First of all <code>class Helper</code> should be a service <code>class HelperClass</code>, which should be injectable.</p> <pre><code>import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; import {TranslateService} from "ng2-translate"; @Injectable() export class HelperService { constructor(private http: Http, private translateService: TranslateService) { } } </code></pre> <p>Now you can simply inject this helper and use it in any component you like.</p> <pre><code>import {HelperService} from "./helper.service.ts"; @Component({ ... }) export class MyComponent{ constructor(public helperService: HelperService) {} } </code></pre> <p>Update: You need to add the service in providers array of the root module for it to work, or for angular6+, the service can be provided as follows</p> <pre><code>@Injectable({ providedIn: 'root' }) export class HelperService { ... } </code></pre>
23,617,129
Matplotlib: How to make two histograms have the same bin width?
<p>I've spent some time searching the interwebs for an answer for this, and I have tried looking all over SO for an answer too, but I think I do not have the correct terminology down... Please excuse me if this is a duplicate of some known problem, I'd happily delete my post and refer to that post instead!</p> <p>In any case, I am trying to plot two histograms on the same figure in Matplotlib. My two data sources are lists of 500 elements long. To provide an illustration of the problem I am facing, please see the following image:</p> <p><img src="https://i.stack.imgur.com/4etRp.png" alt="Uneven histograms"></p> <p>As you can see, the histogram has uneven bin sizes under default parameters, even though the number of bins is the same. I would like to guarantee that the bin widths for both histograms are the same. Is there any way I can do this?</p> <p>Thanks in advance!</p>
23,617,505
3
0
null
2014-05-12 19:19:50.823 UTC
6
2018-11-16 19:12:02.323 UTC
null
null
null
null
1,274,908
null
1
37
python|matplotlib
23,563
<p>I think a consistent way that will easily work for most cases, without having to worry about what is the distribution range for each of your datasets, will be to put the datasets together into a big one, determine the bins edges and then plot:</p> <pre><code>a=np.random.random(100)*0.5 #a uniform distribution b=1-np.random.normal(size=100)*0.1 #a normal distribution bins=np.histogram(np.hstack((a,b)), bins=40)[1] #get the bin edges plt.hist(a, bins) plt.hist(b, bins) </code></pre> <p><img src="https://i.stack.imgur.com/rsPG0.png" alt="enter image description here"></p>
2,824,302
How to make Regular expression into non-greedy?
<p>I'm using jQuery. I have a string with a block of special characters (begin and end). I want get the text from that special characters block. I used a regular expression object for in-string finding. But how can I tell jQuery to find multiple results when have two special character or more?</p> <p>My HTML:</p> <pre><code>&lt;div id="container"&gt; &lt;div id="textcontainer"&gt; Cuộc chiến pháp lý giữa [|cơ thử|nghiệm|] thị trường [|test2|đây là test lần 2|] chứng khoán [|Mỹ|day la nuoc my|] và ngân hàng đầu tư quyền lực nhất Phố Wall mới chỉ bắt đầu. &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and my JavaScript code:</p> <pre><code>$(document).ready(function() { var takedata = $("#textcontainer").text(); var test = 'abcd adddb'; var filterdata = takedata.match(/(\[.+\])/); alert(filterdata); //end write js }); </code></pre> <p>My result is: <strong>[|cơ thử|nghiệm|] thị trường [|test2|đây là test lần 2|] chứng khoán [|Mỹ|day la nuoc my|]</strong> . But this isn't the result I want :(. How to get [text] for times 1 and [demo] for times 2 ?</p> <hr> <p>I've just done my work after searching info on internet ^^. I make code like this:</p> <pre><code>var filterdata = takedata.match(/(\[.*?\])/g); </code></pre> <ul> <li>my result is : <strong>[|cơ thử|nghiệm|],[|test2|đây là test lần 2|]</strong> this is right!. but I don't really understand this. Can you answer my why?</li> </ul>
2,824,314
3
0
null
2010-05-13 03:46:30.557 UTC
54
2017-07-23 20:31:25.553 UTC
2017-07-23 20:31:25.553 UTC
null
3,885,376
null
336,497
null
1
273
javascript|regex|filter|expression|regex-greedy
138,370
<p>The non-greedy regex modifiers are like their greedy counter-parts but with a <code>?</code> immediately following them:</p> <pre><code>* - zero or more *? - zero or more (non-greedy) + - one or more +? - one or more (non-greedy) ? - zero or one ?? - zero or one (non-greedy) </code></pre>
2,989,560
How to get the fields in an Object via reflection?
<p>I have an object (basically a VO) in Java and I don't know its type.<br> I need to get values which are not null in that object. </p> <p>How can this be done?</p>
2,989,585
3
0
null
2010-06-07 12:45:24.48 UTC
19
2022-05-20 16:27:56.8 UTC
2010-06-07 13:51:51.03 UTC
null
157,882
null
123,535
null
1
74
java|reflection
134,512
<p>You can use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Class.html#getDeclaredFields()" rel="noreferrer"><code>Class#getDeclaredFields()</code></a> to get all declared fields of the class. You can use <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)" rel="noreferrer"><code>Field#get()</code></a> to get the value.</p> <p>In short:</p> <pre><code>Object someObject = getItSomehow(); for (Field field : someObject.getClass().getDeclaredFields()) { field.setAccessible(true); // You might want to set modifier to public first. Object value = field.get(someObject); if (value != null) { System.out.println(field.getName() + &quot;=&quot; + value); } } </code></pre> <p>To learn more about reflection, check the <a href="https://docs.oracle.com/javase/tutorial/reflect/" rel="noreferrer">Oracle tutorial on the subject</a>.</p> <p>That said, if that VO is a fullworthy Javabean, then the fields do not necessarily represent <strong>real</strong> properties of a VO. You would rather like to determine the public methods starting with <code>get</code> or <code>is</code> and then invoke it to grab the real property values.</p> <pre><code>for (Method method : someObject.getClass().getDeclaredMethods()) { if (Modifier.isPublic(method.getModifiers()) &amp;&amp; method.getParameterTypes().length == 0 &amp;&amp; method.getReturnType() != void.class &amp;&amp; (method.getName().startsWith(&quot;get&quot;) || method.getName().startsWith(&quot;is&quot;)) ) { Object value = method.invoke(someObject); if (value != null) { System.out.println(method.getName() + &quot;=&quot; + value); } } } </code></pre> <p>That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, <em>many</em> tools available to massage javabeans. There's even a built-in one provided by Java SE in the <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.desktop/java/beans/package-summary.html" rel="noreferrer"><code>java.beans</code></a> package.</p> <pre><code>BeanInfo beanInfo = Introspector.getBeanInfo(someObject.getClass()); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { Method getter = property.getReadMethod(); if (getter != null) { Object value = getter.invoke(someObject); if (value != null) { System.out.println(property.getName() + &quot;=&quot; + value); } } } </code></pre>
2,909,558
best way to store 1:1 user relationships in relational database
<p>What is the best way to store user relationships, e.g. friendships, that must be bidirectional (you're my friend, thus I'm your friend) in a rel. database, e.g. MYSql? </p> <p>I can think of two ways:</p> <ol> <li>Everytime a user friends another user, I'd add two rows to a database, row A consisting of the user id of the innitiating user followed by the UID of the accepting user in the next column. Row B would be the reverse.</li> <li>You'd only add one row, UID(initiating user) followed by UID(accepting user); and then just search through both columns when trying to figure out whether user 1 is a friend of user 2.</li> </ol> <p>Surely there is something better?</p>
2,909,594
4
1
null
2010-05-26 01:00:00.567 UTC
9
2016-01-12 10:37:21.743 UTC
null
null
null
null
251,162
null
1
11
mysql|database|database-design|relational-database
4,422
<p>I would have a link table for friends, or whatever, with 2 columns both being PK's, and both being FK's to the User table. </p> <p>Both columns would be the UID, and you would have two rows per friend relationship (A,B and B,A). As long as both columns are PK's, it should still be in normal format (although others are free to correct me on this)</p> <p>Its a little more complex of a query, but nothing that can't be abstracted away by a stored procedure or some business logic, and its in Normal Format, which is usually nice to have.</p>
2,558,695
Javadoc reuse for overloaded methods
<p>I'm developing an API with many identically named methods that just differ by signature, which I guess is fairly common. They all do the same thing, except that they initialize various values by defaults if the user does not want to specify. As a digestible example, consider</p> <pre><code>public interface Forest { public Tree addTree(); public Tree addTree(int amountOfLeaves); public Tree addTree(int amountOfLeaves, Fruit fruitType); public Tree addTree(int amountOfLeaves, int height); public Tree addTree(int amountOfLeaves, Fruit fruitType, int height); } </code></pre> <p>The essential action performed by all of these methods is the same; a tree is planted in the forest. Many important things users of my API need to know about adding trees hold for all these methods.</p> <p>Ideally, I would like to write one Javadoc block that is used by all methods:</p> <pre><code> /** * Plants a new tree in the forest. Please note that it may take * up to 30 years for the tree to be fully grown. * * @param amountOfLeaves desired amount of leaves. Actual amount of * leaves at maturity may differ by up to 10%. * @param fruitType the desired type of fruit to be grown. No warranties * are given with respect to flavour. * @param height desired hight in centimeters. Actual hight may differ by * up to 15%. */ </code></pre> <p>In my imagination, a tool could magically choose which of the @params apply to each of the methods, and thus generate good docs for all methods at once.</p> <p>With Javadoc, if I understand it correctly, all I can do is essentially copy&amp;paste the same javadoc block five times, with only a slightly differing parameter list for each method. This sounds cumbersome to me, and is also difficult to maintain.</p> <p>Is there any way around that? Some extension to javadoc that has this kind of support? Or is there a good reason why this is not supported that I missed?</p>
2,558,727
4
2
null
2010-04-01 07:08:00.16 UTC
10
2020-08-25 06:59:42.433 UTC
2020-08-25 06:59:42.433 UTC
null
895,245
null
103,395
null
1
95
java|javadoc
20,471
<p>I don't know of any support, but, I would fully javadoc the method with the most arguments, and then refer to it in other javadoc like so. I think it's sufficiently clear, and avoids redundancy.</p> <pre><code>/** * {@code fruitType} defaults to {@link FruitType#Banana}. * * @see Forest#addTree(int, Fruit, int) */ </code></pre>
46,404,236
Failed to verify bitcode while exporting archive for ad hoc distribution - tried Xcode 8.3.3 & Xcode 9
<p>Apps containing our framework complains about missing bitcode while exporting archive for Ad-hoc distribution.</p> <p>I have gone through the documentation provided by Apple in this regard <a href="https://developer.apple.com/library/content/technotes/tn2432/_index.html" rel="noreferrer">Technical Note TN2432</a>. The documentations' listed possible root causes do not resemble our scenario. (We are not using assembly instructions or have malformed info.plist file)</p> <p>I have gone through following similar questions posted on SO</p> <p><a href="https://stackoverflow.com/questions/43141793/error-while-exporting-with-bitcode-enabled-symbol-not-found-for-architecture-ar">Error while exporting with Bitcode enabled (symbol not found for architecture armv7)</a></p> <p><a href="https://stackoverflow.com/questions/35586516/is-it-possible-to-create-a-universal-ios-framework-using-bitcode">Is it possible to create a universal iOS framework using bitcode?</a></p> <p><a href="https://stackoverflow.com/questions/30848208/new-warnings-in-ios-9">New warnings in iOS 9</a></p> <p>But the provided solutions do not seem to work.</p> <p>I have tried adding <code>BITCODE_GENERATION_MODE</code> flag in User-Defined build settings. I also tried adding <code>-fembed-bitcode</code>-marker &amp; <code>-fembed-bitcode</code> in Other C flags in framework target.</p> <p>I check if bitcode segments are present in my generated framework using the <a href="https://stackoverflow.com/questions/35586516/is-it-possible-to-create-a-universal-ios-framework-using-bitcode">suggested</a> command </p> <pre><code>otool -l -arch arm64 &lt;framework_name&gt; | grep __LLVM </code></pre> <p>It shows 2 segments</p> <blockquote> <p>segname __LLVM</p> <p>segname __LLVM</p> </blockquote> <p>But while exporting the archive, Xcode still complains about absent bitcode. </p> <p>I tried to upload app on App store to verify if this issue is due to Xcode versions (I tried 8.3.3. and 9.0), but I get following email about build import error from iTunes Store.</p> <blockquote> <p>While processing your iOS app, APP_NAME 1.0(4), errors occurred in the app thinning process, and your app couldn’t be thinned. If your app contains bitcode, bitcode processing may have failed. Because of these errors, this build of your app will not be able to be submitted for review or placed on the App Store. For information that may help resolve this issue, see Tech Note 2432.</p> </blockquote> <p>PS: Disabling bitcode is not an option for us as host app need to support bitcode.</p> <p><a href="https://i.stack.imgur.com/bbTLU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bbTLU.png" alt="Error while exporting the Archieve"></a></p>
46,710,698
3
0
null
2017-09-25 11:34:41.59 UTC
17
2018-10-23 07:00:08.423 UTC
2017-09-25 12:34:24.283 UTC
null
966,086
null
966,086
null
1
26
ios|xcode|app-store-connect|bitcode
20,966
<p>The error description took me in the wrong direction to find the solution.</p> <p><strong>This error is not related to bitcode.</strong> It appeared when the framework contained simulator slices (<code>i386 x86_64</code>)</p> <p>Removing them before archiving resolved the issue. </p> <p>Adding a run script phase to build phases of the target with following code helped in getting rid of the error.</p> <pre><code>APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}" # This script loops through the frameworks embedded in the application and # removes unused architectures. find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK do FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable) FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME" echo "Executable is $FRAMEWORK_EXECUTABLE_PATH" EXTRACTED_ARCHS=() for ARCH in $ARCHS do echo "Extracting $ARCH from $FRAMEWORK_EXECUTABLE_NAME" lipo -extract "$ARCH" "$FRAMEWORK_EXECUTABLE_PATH" -o "$FRAMEWORK_EXECUTABLE_PATH-$ARCH" EXTRACTED_ARCHS+=("$FRAMEWORK_EXECUTABLE_PATH-$ARCH") done echo "Merging extracted architectures: ${ARCHS}" lipo -o "$FRAMEWORK_EXECUTABLE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}" rm "${EXTRACTED_ARCHS[@]}" echo "Replacing original executable with thinned version" rm "$FRAMEWORK_EXECUTABLE_PATH" mv "$FRAMEWORK_EXECUTABLE_PATH-merged" "$FRAMEWORK_EXECUTABLE_PATH" done </code></pre> <p>Credits: <a href="http://ikennd.ac/blog/2015/02/stripping-unwanted-architectures-from-dynamic-libraries-in-xcode/" rel="noreferrer">http://ikennd.ac/blog/2015/02/stripping-unwanted-architectures-from-dynamic-libraries-in-xcode/</a></p> <p>If you don't know how to add a run script phase to your Xcode project, because maybe you're building a project with Cordova or Ionic and you never were taught much about Xcode, here's how you do that:</p> <ul> <li>Open your project in Xcode.</li> <li>Make sure you're looking at your project in the "Project Navigator" by clicking on the left-most icon in the left pane of Xcode (the one that says "show Project Navigator" when you point at it.</li> <li>Click on your project at the top of the navigator window, so that it is selected as your target</li> <li>At that point, in the middle portion of the Xcode window, you'll see several things appear near the top. General, Capabilities, Resource Tags, Info, among others. One of them is Build Phases -- click on it.</li> <li>Click the + that's near the top-left of the middle portion of the Xcode Window. It will say Add New Build Phase if you point at it long enough.</li> <li>Select "New Run Script Phase" from the menu that popped up when you clicked on the +</li> <li>Click on the arrow next to the Run Script that just appeared.</li> <li>Copy and paste the above script into the appropriate area just below the word "Shell". You shouldn't have to change anything else.</li> <li>Build/Archive your project like normal, only now you won't get those annoying "failed to verify bitcode" errors. :-)</li> </ul>
56,488,202
How to persist svelte store
<p>Is there any direct option to persist svelte store data so that even when the page is refreshed, data will be available. </p> <p>I am not using local storage since I want the values to be reactive. </p>
56,489,832
12
0
null
2019-06-07 05:00:57.173 UTC
22
2022-07-06 10:21:35.607 UTC
null
null
null
null
139,352
null
1
53
svelte|svelte-store
18,354
<p>You can manually create a subscription to your store and persist the changes to localStorage and also use the potential value in localStorage as default value.</p> <p><strong>Example</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;script&gt; import { writable } from "svelte/store"; const store = writable(localStorage.getItem("store") || ""); store.subscribe(val =&gt; localStorage.setItem("store", val)); &lt;/script&gt; &lt;input bind:value={$store} /&gt; </code></pre>
1,263,702
How to do a wiredump of XMLRPC::Client in ruby?
<p>I'm working on some code using XML RPC in ruby and need to see some debug info, how do you do that? </p>
1,263,735
2
0
null
2009-08-12 00:38:50.74 UTC
9
2016-06-01 08:35:12.937 UTC
null
null
null
null
136,259
null
1
9
xml|ruby|xml-rpc
2,059
<p>Reading the source of the package, XMLRPC::Client uses Net::HTTP in turn as its transport.</p> <p>So I think you should be able to monkey-patch a method into the XMLRPC::Client accordingly:</p> <pre><code>require 'pp' # the magic happens here class XMLRPC::Client def set_debug @http.set_debug_output($stderr); end end server = XMLRPC::Client.new2("http://rpc.technorati.com/rpc/ping") server.set_debug result = server.call("weblogUpdates.ping", "Copenhagen.rb", "http://www.copenhagenrb.dk/") pp result </code></pre> <p>(sample for XMLRPC snarfed from <a href="http://snippets.dzone.com/posts/show/2597" rel="noreferrer">here</a>).</p>
533,931
Convert double to string
<p>i have three double variable a ,b and c</p> <pre><code>a = 0.000006 b = 6 c = a/b; </code></pre> <p>so C should be 0.000001</p> <p>i want to show this value in text box so i wrote</p> <pre><code>textbox.text = c.tostring(); </code></pre> <p>but it's give result as "1E-06"..</p> <p>Can anybody help me out how can i put correct value in textbox ?</p> <p>Thanks</p>
533,969
2
1
null
2009-02-10 20:01:50.823 UTC
0
2020-12-22 11:02:19.433 UTC
2009-02-10 20:05:20.3 UTC
Ed Swangren
1,053
null
64,739
null
1
29
c#|typeconverter
149,519
<pre><code>a = 0.000006; b = 6; c = a/b; textbox.Text = c.ToString("0.000000"); </code></pre> <p>As you requested:</p> <pre><code>textbox.Text = c.ToString("0.######"); </code></pre> <p>This will only display out to the 6th decimal place if there are 6 decimals to display.</p>
529,921
Guide in organizing large Django projects
<p>Anyone could recommend a good guide/tutorial/article with tips/guidelines in how to organize and partition a large Django project? </p> <p>I'm looking for advices in what to do when you need to start factorizing the initial unique files (models.py, urls.py, views.py) and working with more than a few dozens of entities.</p>
530,363
2
0
null
2009-02-09 20:58:23.03 UTC
20
2009-02-09 22:39:50.523 UTC
null
null
null
Sam
48,721
null
1
32
python|django|projects
7,807
<p>Each "application" should be small -- a single reusable entity plus a few associated tables. We have about 5 plus/minus 2 tables per application model. Most of our half-dozen applications are smaller than 5 tables. One has zero tables in the model. </p> <p>Each application should be designed to be one reusable concept. In our case, each application is a piece of the overall site; the applications could be removed and replaced separately.</p> <p>Indeed, that's our strategy. As our requirements expand and mature, we can remove and replace applications independently from each other.</p> <p>It's okay to have applications depend on each other. However, the dependency has to be limited to the obvious things like "models" and "forms". Also, applications can depend on the names in each other's URL's. Consequently, your named URL's must have a form like "application-view" so the <code>reverse</code> function or the <code>{% url %}</code> tag can find them properly.</p> <p>Each application should contain it's own batch commands (usually via a formal Command that can be found by the <code>django-admin</code> script.</p> <p>Finally, anything that's more complex than a simple model or form that's shared probably doesn't belong to either application, but needs to be a separate shared library. For example, we use <a href="http://www.lexicon.net/sjmachin/xlrd.htm" rel="noreferrer">XLRD</a>, but wrap parts of it in our own class so it's more like the built-in <code>csv</code> module. This wrapper for XLRD isn't a proper part of any one application, to it's a separate module, outside the Django applications.</p>
3,008,267
SQL Server Text Datatype Maxlength = 65,535?
<p>Software I'm working with uses a text field to store XML. From my searches online, the text datatype is supposed to hold 2^31 - 1 characters. Currently SQL Server is truncating the XML at 65,535 characters every time. I know this is caused by SQL Server, because if I add a 65,536th character to the column directly in Management Studio, it states that it will not update because characters will be truncated.</p> <p>Is the max length really 65,535 or could this be because the database was designed in an earlier version of SQL Server (2000) and it's using the legacy <code>text</code> datatype instead of 2005's? </p> <p>If this is the case, will altering the datatype to <code>Text</code> in SQL Server 2005 fix this issue?</p>
3,008,332
5
1
null
2010-06-09 17:30:06.06 UTC
2
2022-02-24 10:16:12.997 UTC
2012-07-10 05:40:52.057 UTC
null
13,302
null
21,717
null
1
11
sql-server|text|types
53,063
<p>that is a limitation of SSMS not of the text field, but you should use varchar(max) since text is deprecated</p> <p><img src="https://imgur.com/RxHjy.png" alt="alt text"></p> <p>Here is also a quick test</p> <pre><code>create table TestLen (bla text) insert TestLen values (replicate(convert(varchar(max),'a'), 100000)) select datalength(bla) from TestLen </code></pre> <p>Returns 100000 for me</p>
3,039,254
WPF: Aligning the base line of a Label and its TextBox
<p>Let's say I have a simple TextBox next to a Label:</p> <pre><code>&lt;StackPanel&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Label Margin="3"&gt;MyLabel&lt;/Label&gt; &lt;TextBox Margin="3" Width="100"&gt;MyText&lt;/TextBox&gt; &lt;/StackPanel&gt; ... &lt;/StackPanel&gt; </code></pre> <p>This yields the following result:</p> <p><a href="https://i.stack.imgur.com/IxF8P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IxF8P.png" alt="result"></a></p> <p>As you can see, the base lines of MyLabel and MyText are not aligned, which looks ugly. Of course, I could start playing around with the margins until they match up, but since this is such a common requirement I'm sure that WPF provides a much easier and more elegant solution, which I just haven't found yet...</p>
3,039,341
5
0
null
2010-06-14 17:05:20.337 UTC
6
2020-06-17 21:33:32.05 UTC
2017-06-27 14:16:29.37 UTC
null
87,698
null
87,698
null
1
39
wpf|layout|alignment|baseline
28,236
<p>This behaviour is, I think, caused by the fact that the <code>TextBox</code> defaults to a vertical alignment of <code>Stretch</code>, which causes it to fill the available space and have the extra couple of pixels under the text. If you use this instead:</p> <pre><code>&lt;StackPanel&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Label &gt;MyLabel&lt;/Label&gt; &lt;TextBox VerticalAlignment="Center" Width="100"&gt;MyText&lt;/TextBox&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; </code></pre> <p>... you should see a cleaner result.</p>
2,507,337
How to determine a terminal's background color?
<p>I'd like to know if there is any way to determine a terminal's background color ?</p> <p>In my case, using gnome-terminal.<br> It might matter, since it's entirety up to the terminal application to draw the background of its windows, which may even be something else than a plain color.</p>
30,540,928
6
0
null
2010-03-24 11:52:46.697 UTC
8
2022-09-08 17:25:46.73 UTC
2019-07-28 20:03:16.79 UTC
null
1,663,462
null
286,182
null
1
33
unix|terminal|x11|gnome-terminal
11,732
<p>I've came up with the following:</p> <pre><code>#!/bin/sh # # Query a property from the terminal, e.g. background color. # # XTerm Operating System Commands # "ESC ] Ps;Pt ST" oldstty=$(stty -g) # What to query? # 11: text background Ps=${1:-11} stty raw -echo min 0 time 0 # stty raw -echo min 0 time 1 printf "\033]$Ps;?\033\\" # xterm needs the sleep (or "time 1", but that is 1/10th second). sleep 0.00000001 read -r answer # echo $answer | cat -A result=${answer#*;} stty $oldstty # Remove escape at the end. echo $result | sed 's/[^rgb:0-9a-f/]\+$//' </code></pre> <p>Source/Repo/Gist: <a href="https://gist.github.com/blueyed/c8470c2aad3381c33ea3" rel="noreferrer">https://gist.github.com/blueyed/c8470c2aad3381c33ea3</a></p>
2,533,476
What will happen when I call a member function on a NULL object pointer?
<p>I was given the following as an interview question:</p> <pre><code>class A { public: void fun() { std::cout &lt;&lt; &quot;fun&quot; &lt;&lt; std::endl; } }; A* a = NULL; a-&gt;fun(); </code></pre> <p>What will happen when this code is executed, and why?</p> <hr /> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-behav">When does invoking a member function on a null instance result in undefined behavior?</a></li> </ul>
2,533,500
6
15
null
2010-03-28 15:46:26.95 UTC
38
2018-05-17 14:45:47.283 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
277,734
null
1
58
c++
13,673
<p>It's undefined behavior, so anything might happen.</p> <p>A possible result would be that it just prints <code>"fun"</code> since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).</p>
2,640,877
How to set the color of an Android ScrollView fading edge?
<p>I have an Android scrollview with a white background. The fading edge is a white translucent gradient. I would like to change it be black instead of white. I have a ListView in the same project with a white background that has a black fading edge by default, but I can't find where (if anywhere) that was set.</p>
3,021,192
7
0
null
2010-04-14 20:41:01.3 UTC
14
2017-08-30 15:05:30.097 UTC
2012-02-09 12:58:04.24 UTC
null
1,164,929
null
186,501
null
1
42
android|scrollview|fading
45,422
<p>Just found it out by trial and error.</p> <p>Simply set <code>android:background="@color/yourColor"</code> for the <code>&lt;ScrollView&gt;</code>. It will set the shadow to the given colour.</p>
3,152,497
VHDL/Verilog related programming forums?
<p>Hardware design with VHDL or Verilog is more like programming nowadays. However, I see SO members are not so actively talking about VHDL/Verilog programming.</p> <p>Is there any forum dealing with hardware design with Verilog/VHDL/SystemVerilog or SystemC?</p>
5,564,577
8
0
null
2010-06-30 19:03:27.857 UTC
14
2020-09-16 15:41:27.177 UTC
2011-04-25 00:18:25.327 UTC
Roger Pate
260,127
null
260,127
null
1
26
vhdl|verilog|system-verilog|systemc
10,243
<p><a href="http://area51.stackexchange.com/proposals/45270/logic-design">Logic Design</a> was closed because of too little attention. It's now reopened, but interest remains low.</p>
2,940,064
Studies of relative costs for development in different languages
<p>Has anyone seen a recent (and fairly balanced) study into the relative costs for software development using differing languages ? I would particular like to see the relative costs of Java Vs. C# Vs. Delphi.</p>
2,940,469
8
0
null
2010-05-30 19:54:54.697 UTC
16
2014-01-26 20:21:36.483 UTC
2012-02-19 10:10:58.763 UTC
null
21,234
null
85,592
null
1
60
c#|java|delphi
5,576
<p>Quantitative comparisons of this sort would be very hard to pin down, due to the number of complicating variables: developers' experience with the language, suitability of the language to the target domain, developers' overall quality (it's been argued that non-mainstream languages attract higher quality developers), tradeoffs with the resulting product (is a Ruby or Python app as fast as a well-written Delphi or C++ app?), etc.</p> <p>In <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="noreferrer" rel="nofollow noreferrer"><i>Code Complete, 2nd Ed.</i></a>, Steve McConnell lists several languages in terms of their expressive power (how many lines of equivalent C code can be expressed in a single statement of each language). It's been suggested that programmers' productivity in lines of code is relatively constant regardless of language; if this is true, then the expressive power of each language should give a rough estimate of the relative cost of development in each language. From Table 4.1, page 62:</p> <pre> LANGUAGE LEVEL RELATIVE TO C C 1 C++ 2.5 Fortran 95 2 Java 2.5 Perl 6 Python 6 Smalltalk 6 Visual Basic 4.5 </pre> <p>He lists several sources for this table: <a href="https://rads.stackoverflow.com/amzn/click/com/0071483004" rel="noreferrer" rel="nofollow noreferrer"><i>Estimating Software Costs</i></a>, <a href="https://rads.stackoverflow.com/amzn/click/com/0137025769" rel="noreferrer" rel="nofollow noreferrer"><i>Software Cost Estimation with Cocomo II</i></a>, and "An Empirical Comparison of Seven Programming Languages" (by Prechelt, from <i>IEEE Computer</i>, October 2000).</p> <p>The figures that McConnell cites are all several years old, but from what I understand, the Cocomo II model is ridiculously detailed, so current Cocomo II material may offer current numbers on Delphi and C#.</p>
2,803,772
Turn off deprecated errors in PHP 5.3
<p>My server is running PHP 5.3 and my WordPress install is spitting these errors out on me, causing my session_start() to break. </p> <pre><code>Deprecated: Assigning the return value of new by reference is deprecated in /home//public_html/hub/wp-settings.php on line 647 Deprecated: Assigning the return value of new by reference is deprecated in /home//public_html/hub/wp-settings.php on line 662 Deprecated: Assigning the return value of new by reference is deprecated in /home//public_html/hub/wp-settings.php on line 669 Deprecated: Assigning the return value of new by reference is deprecated in /home//public_html/hub/wp-settings.php on line 676 Deprecated: Assigning the return value of new by reference is deprecated in /home//public_html/hub/wp-settings.php on line 712 </code></pre> <p>This is annoying, but I do not want to turn off on screen error reporting. How do I disable these bothersome deprecated warnings?</p> <p>I am running WordPress 2.9.2.</p>
2,803,783
9
2
null
2010-05-10 15:12:11.85 UTC
19
2021-06-16 11:51:59.407 UTC
2019-11-24 00:51:12.567 UTC
null
63,550
null
323,434
null
1
149
php|wordpress|deprecation-warning
265,048
<p>You can do it in code by calling the following functions.</p> <pre><code>error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); </code></pre> <p>or</p> <pre><code>error_reporting(E_ALL ^ E_DEPRECATED); </code></pre>
2,454,161
Benchmarking PHP page load times
<p>How could I measure the time taken to load a page (with various different PHP statements)?</p> <p>Somewhat like the stats available here - <a href="http://talks.php.net/show/drupal08/24" rel="noreferrer">http://talks.php.net/show/drupal08/24</a></p>
2,454,183
10
0
null
2010-03-16 12:12:50.533 UTC
11
2018-01-15 10:54:40.04 UTC
null
null
null
null
275,372
null
1
18
php|benchmarking
28,614
<p>The most simple too is <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">Apache Bench</a> <em>(called <code>ab</code>)</em>, which is provided with Apache :</p> <ul> <li>It's a command-line tool</li> <li>That can send many requests, in parallel, to and URL</li> <li>And reports timings, errors, ...</li> </ul> <p>Seems to fit the kind of very simple reporting that's presented on your slide. <br><em>(It does actually report more than that)</em></p> <p><br> If your needs ar ea bit more complex, <a href="http://www.joedog.org/index/siege-home" rel="noreferrer">Siege</a> can be a good alternative.</p> <p>An interesting thing with Siege is that it can take a list of URLs from a file, instead of working with just one.</p> <p><br> An interesting thing with those tools is that you are not measuring only the time taken to execute a specific portion of code <em>(like you would if using <a href="http://fr2.php.net/microtime" rel="noreferrer"><code>microtime</code></a> directly in your PHP code)</em>, but you're getting the whole time that was required to serve the page.</p> <p>Also, it can benchmark more than just PHP code, as it's working on the HTTP request, and not the code itself.</p>
2,952,667
Find all CSS rules that apply to an element
<p>Many tools/APIs provide ways of selecting elements of specific classes or IDs. There's also possible to inspect the raw stylesheets loaded by the browser.</p> <p>However, for browsers to render an element, they'll compile all CSS rules (possibly from different stylesheet files) and apply it to the element. This is what you see with Firebug or the WebKit Inspector - the full CSS inheritance tree for an element.</p> <p>How can I reproduce this feature in pure JavaScript without requiring additional browser plugins?</p> <p>Perhaps an example can provide some clarification for what I'm looking for:</p> <pre><code>&lt;style type="text/css"&gt; p { color :red; } #description { font-size: 20px; } &lt;/style&gt; &lt;p id="description"&gt;Lorem ipsum&lt;/p&gt; </code></pre> <p>Here the p#description element have two CSS rules applied: a red color and a font size of 20 px.</p> <p>I would like to find the source from where these computed CSS rules originate from (color comes the p rule and so on).</p>
2,953,122
10
2
null
2010-06-01 19:30:14.593 UTC
52
2021-04-27 17:30:01.683 UTC
null
null
null
null
51,308
null
1
94
javascript|css
56,517
<p>EDIT: This answer is now deprecated and <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=437569&amp;desc=2" rel="nofollow noreferrer">no longer works in Chrome 64+</a>. Leaving for historical context. In fact that bug report links back to this question for alternative solutions to using this.</p> <hr> <p>Seems I managed to answer my own question after another hour of research.</p> <p>It's as simple as this:</p> <pre><code>window.getMatchedCSSRules(document.getElementById("description")) </code></pre> <p>(Works in WebKit/Chrome, possibly others too)</p>
2,772,701
Address already in use: JVM_Bind java
<p>Some times whenever I restart the application, which is built on Java Struts Mysql and Jboss 4.05 Version I get the error as <strong>Address already in use: JVM_Bind</strong></p> <p>Only fix that i know is to restart the machine and try again, it will work. Else Some times I do Ctrl-Alt-Del and Stop all the process related to Java, some times this also works.</p> <p>But what is the exact reason and how can we prevent this problem ?</p>
2,772,758
17
1
null
2010-05-05 11:25:19.18 UTC
12
2022-04-28 08:18:12.43 UTC
null
null
null
null
238,052
null
1
58
java|web-applications|jboss|struts
296,663
<blockquote> <p>Address already in use: JVM_Bind</p> </blockquote> <p>means that some other application is already listening on the port your current application is trying to bind.</p> <p>what you need to do is, either change the port for your current application or better; just find out the already running application and kill it.</p> <p>on Linux you can find the application pid by using, </p> <pre><code>netstat -tulpn </code></pre>
25,032,284
Migrate Global.asax to Startup.cs
<p>For better test job with <code>Microsoft.Owin.Testing.TestServer</code>, I found that Global.asax is not loaded with Owin TestServer.</p> <p>So, I try to move my Global.asax configurations to Startup.cs as below,</p> <pre><code>public partial class Startup { public void Configuration(IAppBuilder app) { // pasted Global.asax things start. GlobalConfiguration.Configuration.Formatters.Clear(); var jsonSerializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, }; GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter() { SerializerSettings = jsonSerializerSettings }); GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // pasted Global.asax things end. ConfigureAuth(app); } } </code></pre> <p>But <code>TestServer</code> <strong>failed</strong> to initialize in every point of configuration such as <code>AreaRegistration.RegisterAllAreas</code>, <code>FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)</code>, so on...</p> <p>Minimum viable migration(successful test with TestServer) for me is as below.</p> <pre><code>public partial class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.Formatters.Clear(); var jsonSerializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, }; config.Formatters.Add(new JsonMediaTypeFormatter() { SerializerSettings = jsonSerializerSettings }); config.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter()); WebApiConfig.Register(config); // moved from GlobalConfiguration.Configure(WebApiConfig.Register) app.UseWebApi(config); ConfigureAuth(app); } } </code></pre> <p>Is there anyway to move all configurations to Startup.cs?</p>
25,080,611
1
0
null
2014-07-30 08:40:10.63 UTC
22
2016-07-05 12:25:33.853 UTC
null
null
null
null
361,100
null
1
32
c#|asp.net|asp.net-mvc-4|unit-testing|asp.net-web-api2
34,261
<p>As you are already aware, <code>OwinContext</code> consumed by <code>Startup.Configuration()</code> is different from the traditional ASP.NET <code>HttpContext</code> consumed by <code>MvcApplication.Application_Start()</code>. Both are using different context pipelines. More specifically, ASP.NET MVC still relies on <code>System.Web.dll</code> while ASP.NET Web API doesn't.</p> <p>Therefore, based on your code, some methods usually laid in <code>MvcApplication.Application_Start()</code> can't be run within <code>Startup.Configuration()</code>:</p> <ul> <li><code>AreaRegistration.RegisterAllAreas();</code>: This method relies on <code>System.Web.dll</code>.</li> <li><code>RouteConfig.RegisterRoutes(RouteTable.Routes);</code>: <code>RouteCollection</code> is a part of <code>System.Web.dll</code>.</li> <li><code>GlobalConfiguration.Configure(WebApiConfig.Register)</code>: Again, <code>RouteCollection</code> within <code>WebApiConfig.Register()</code> is a part of <code>System.Web.dll</code>.</li> </ul> <p>For URL routing within OWIN context, <code>AttributeRouting</code> is recommended. So, instead of this, try <code>config.MapHttpAttributeRoutes();</code> That will give you much freedom.</p> <p>If you still want to run <code>AreaRegistration.RegisterAllAreas();</code> within OWIN context, <code>Startup.Configuration()</code>, I'd better recommend to import <a href="http://www.nuget.org/packages/Microsoft.Owin.Host.SystemWeb">Katana library</a>. This integrates OWIN with <code>System.Web.dll</code> so that you probably archieve your goal.</p> <p>HTH</p>
10,630,311
Make a table fill the entire window
<p>How can I make a HTML table fill the entire browser window horizontally and vertically?</p> <p>The page is simply a title and a score which should fill the entire window. (I realise the fixed font sizes are a separate issue.)</p> <pre><code>&lt;table style="width: 100%; height: 100%;"&gt; &lt;tr style="height: 25%; font-size: 180px;"&gt; &lt;td&gt;Region&lt;/td&gt; &lt;/tr&gt; &lt;tr style="height: 75%; font-size: 540px;"&gt; &lt;td&gt;100.00%&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>When I use the above code, the table width is correct, but the height shrinks to fit the two rows of text.</p> <p>I'm likely to be forced to use <em>Internet Explorer 8</em> or <em>9</em> to present this page.</p>
10,630,352
6
0
null
2012-05-17 05:31:26.353 UTC
5
2021-06-07 05:52:52.313 UTC
null
null
null
null
740,923
null
1
20
html|css|internet-explorer|stylesheet
120,881
<p>You can use position like this to stretch an element across the parent container.</p> <pre><code>&lt;table style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;"&gt; &lt;tr style="height: 25%; font-size: 180px;"&gt; &lt;td&gt;Region&lt;/td&gt; &lt;/tr&gt; &lt;tr style="height: 75%; font-size: 540px;"&gt; &lt;td&gt;100.00%&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
10,733,080
'position: absolute; bottom: 0' does not work when parent position is relative
<p>I have a css code.</p> <p>Why the <code>bottom: 0</code> does not work when the <code>position: relative;</code>?</p> <p>If I give up <code>position: relative;</code>, the <code>bottom</code> works but <code>float: left</code> and <code>float: right</code> are not at <code>width: 930px;</code>.</p> <p>sorry my bad english</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#main { position: relative; width: 930px; padding: 10px; margin: 0 auto; } #left { position: absolute; left: 0; } #right { position: absolute; right: 0; } #bottom { position: absolute; bottom: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="main"&gt; &lt;div id="left"&gt; Left &lt;/div&gt; &lt;div id="right"&gt; Right &lt;/div&gt; &lt;div id="bottom"&gt; Bottom &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
10,733,115
2
0
null
2012-05-24 07:33:20.24 UTC
2
2021-04-13 11:56:21.25 UTC
2021-04-13 11:56:21.25 UTC
null
4,720,018
null
1,414,360
null
1
21
css|position
65,565
<p>That's because when you're setting <code>position:relative</code> on main, then <code>position:absolute</code> will be <em>relative</em> to the parent. And your <code>#main</code> div has no height, which causes the <code>#bottom</code> to not be at the bottom of the page.</p>
10,734,025
logback: Two appenders, multiple loggers, different levels
<p>I want to have two log files in my application (Spring Integration), debug.log and main.log. I want to run main.log at an INFO level and debug.log at a DEBUG level. This is doable with filters on the appenders. I want to log different levels to the appenders based on the source. In other words</p> <pre><code>&lt;logger name="org.springframework" level="ERROR"&gt; &lt;appender-ref ref="main" /&gt; &lt;/logger&gt; &lt;logger name="org.springframework" level="DEBUG"&gt; &lt;appender-ref ref="debug" /&gt; &lt;/logger&gt; &lt;logger name="com.myapp" level="INFO"&gt; &lt;appender-ref ref="main" /&gt; &lt;/logger&gt; &lt;logger name="com.myapp" level="DEBUG"&gt; &lt;appender-ref ref="debug" /&gt; &lt;/logger&gt; </code></pre> <p>So to summarise:</p> <ol> <li>Spring logger <ul> <li>main -> ERROR</li> <li>debug -> DEBUG</li> </ul></li> <li>com.myapp logger <ul> <li>main -> INFO</li> <li>debug -> DEBUG</li> </ul></li> </ol> <p>Because of this I have to have the loggers running at DEBUG and a threshold filter on an appender isn't fine grained enough.</p> <p><strong>Update</strong> Added clarity to the question</p>
10,734,257
6
0
null
2012-05-24 08:44:13.34 UTC
25
2021-08-31 15:26:14.603 UTC
2014-05-14 13:12:22.703 UTC
null
24,108
null
24,108
null
1
66
java|logging|logback
93,958
<p>Create a ThresholdLoggerFilter class which can be put on an appender like:</p> <pre><code>&lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"&gt; &lt;filter class="ch.qos.logback.classic.filter.ThresholdFilter"&gt; &lt;level&gt;INFO&lt;/level&gt; &lt;/filter&gt; &lt;filter class="com.myapp.ThresholdLoggerFilter"&gt; &lt;logger&gt;org.springframework&lt;/logger&gt; &lt;level&gt;ERROR&lt;/level&gt; &lt;/filter&gt; &lt;/appender&gt; </code></pre> <p>The following code works</p> <pre><code>package com.myapp; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; public class ThresholdLoggerFilter extends Filter&lt;ILoggingEvent&gt; { private Level level; private String logger; @Override public FilterReply decide(ILoggingEvent event) { if (!isStarted()) { return FilterReply.NEUTRAL; } if (!event.getLoggerName().startsWith(logger)) return FilterReply.NEUTRAL; if (event.getLevel().isGreaterOrEqual(level)) { return FilterReply.NEUTRAL; } else { return FilterReply.DENY; } } public void setLevel(Level level) { this.level = level; } public void setLogger(String logger) { this.logger = logger; } public void start() { if (this.level != null &amp;&amp; this.logger != null) { super.start(); } } } </code></pre>
6,177,200
JavaScript/jQuery: replace part of string?
<p>With text like this:</p> <pre><code>&lt;div class="element"&gt; &lt;span&gt;N/A, Category&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I want to get rid of every occurrence of <code>N/A</code>.</p> <p>Here is my attempt:</p> <pre><code>$('.element span').each(function() { console.log($(this).text()); $(this).text().replace('N/A, ', ''); }); </code></pre> <p>The logged text is the text inside of the span so the selector is okay.</p> <p>What am I doing wrong here?</p>
6,177,210
2
1
null
2011-05-30 13:54:23.063 UTC
17
2019-10-01 19:45:29.6 UTC
2015-09-11 18:39:11.977 UTC
null
1,832,942
null
1,444,475
null
1
46
javascript|jquery|replace
168,923
<p>You need to set the text after the replace call:</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>$('.element span').each(function() { console.log($(this).text()); var text = $(this).text().replace('N/A, ', ''); $(this).text(text); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="element"&gt; &lt;span&gt;N/A, Category&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr /> <p>Here's another cool way you can do it (hat tip @Felix King):</p> <pre><code>$(".element span").text(function(index, text) { return text.replace("N/A, ", ""); }); </code></pre>
23,035,085
php return to page after form submission
<p>I've created a html form </p> <pre><code>&lt;form action="http://localhost/php/insert.php" method="post"&gt; Barcode: &lt;input type="text" name="barcode" /&gt;&lt;br&gt;&lt;br&gt; Serial: &lt;input type="text" name="serial" /&gt;&lt;br&gt;&lt;br&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>which saves into my database using this php:</p> <pre><code>&lt;?php $con = mysql_connect("example","example",""); if ( ! $con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database", $con); $sql = "INSERT INTO asset (barcode, serial) VALUES ('$_POST[barcode]','$_POST[serial]')"; if ( ! mysql_query($sql, $con)) { die('Error: ' . mysql_error()); } mysql_close($con) ?&gt; </code></pre> <p>the form saves to the DB but the page just goes to <code>http://localhost/php/insert.php</code> when you press submit, which is a blank page. how can I make it stay on the same page and just show a message or something?</p>
23,035,123
4
0
null
2014-04-12 19:27:20.313 UTC
null
2017-02-08 14:26:37.903 UTC
2014-04-12 19:44:55.63 UTC
null
1,300,892
null
1,161,520
null
1
9
php|html|mysql|forms
38,045
<p>Note that redirecting with <code>HTTP_REFERER</code> is flaky and untrustworthy in general, so the best way is to have a URL sent with the request or, if it's coming from another server, you could build a specific pass-through to use for specific sites/URLs. The best is to know the URL by having it be submitted with the request; the other two are probably less than optimal.</p> <p>After your form processing is done, do this before outputting anything (which will throw an error):</p> <pre><code>header("Location: {$_SERVER['HTTP_REFERER']}"); exit; </code></pre> <p>Depending on what your processing outcomes could be, you could append an error to the URL:</p> <pre><code>if ($query_does_not_execute) { $errcode = "error_code=003"; } $referer = $_SERVER['HTTP_REFERER']; if ($errcode) { if (strpos($referer, '?') === false) { $referer .= "?"; } header("Location: $referer&amp;$errcode"); } else { header("Location: $referer"); } exit; </code></pre> <p>Then on the page, you could show the error. Or, alternatively, you could redirect to a page to handler errors of different kinds. This is wide-open to a number of different interpretations.</p>
19,530,585
Pushing repo branch to local AOSP mirror
<p>I'm trying to create a new branch of the AOSP (on my development machine) and push it to a local mirror (on a server on the same LAN). I can't find documentation of the "repo" tool that explains how to do this.</p> <p>I've created a mirror of the AOSP source on my server using:</p> <pre><code>$ mkdir -p ~/aosp/mirror $ cd ~/aosp/mirror $ repo init -u https://android.googlesource.com/mirror/manifest --mirror </code></pre> <p>Then I sync'd on a different computer:</p> <pre><code> $ repo init -u &lt;USERNAME&gt;@&lt;IP_OF_SERVER&gt;:/home/&lt;USERNAME&gt;/aosp/mirror/platform/manifest.git -b android-4.2.2_1 $ repo sync </code></pre> <p>So far so good. I'm using "-b android-4.2.2_1" because I need my development to use this version of JellyBean as a baseline.</p> <p>Then I create a new branch using "repo start":</p> <pre><code>$ repo start my-branch-name --all </code></pre> <p>Still good. The problem is, I can't figure out how to "push" this branch to the remote server.</p> <p>When I do <code>repo info</code> I see:</p> <pre><code>Manifest branch: refs/tags/android-4.2.2_r1 Manifest merge branch: android-4.2.2_r1 Manifest groups: all,-notdefault ---------------------------- Project: platform/abi/cpp Mount path: /home/&lt;username&gt;/&lt;project_name&gt;/android/abi/cpp Current revision: refs/tags/android-4.2.2_r1 Local Branches: 1 [my-branch-name] --------------------------- .... </code></pre> <p>When I try <code>repo upload</code> I get:</p> <pre><code>no branches ready for upload </code></pre> <p>I then tried <code>repo forall -c "git push aosp my-branch-name"</code> which <em>does</em> push the local branches to each remote repository, but it seems like this is not the proper way to do it. In particular, if I try creating a new client, and try syncing to the branch it doesn't work.</p> <pre><code>$ repo init -u &lt;USERNAME&gt;@&lt;IP_OF_SERVER&gt;:/home/&lt;USERNAME&gt;/aosp/mirror/platform/manifest.git -b my-branch-name error: revision my-branch-name in manifests not found </code></pre> <p>What is the proper way to create a "Manifest branch"?</p>
19,761,697
1
0
null
2013-10-23 00:16:11.127 UTC
11
2015-03-30 11:46:59.997 UTC
null
null
null
null
2,565,950
null
1
8
android|android-manifest|repository
8,360
<p>The <code>repo start</code> command creates a local branch based on the current upstream branch. Running <code>repo upload</code> will upload any local commits on the currently checked-out branch for review to the upstream branch hosted by the Gerrit server listed in the manifest file. If the type of push you want to do doesn't match this use case you'll have to use the underlying Git commands for the pushing. You can still use <code>repo start</code> though (but you don't have to).</p> <p>To create a manifest branch, <code>repo start</code> and <code>repo upload</code> aren't useful. Unlike other gits that Repo manages, you should make all changes to the manifest git on the <code>default</code> branch which Repo checks out for you. Then, use plain Git commands to push your changes.</p> <p>The following example shows how to create a new manifest branch called <code>mybranch</code>, identical to the current upstream.</p> <pre><code>cd .repo/manifests git push origin default:refs/heads/mybranch </code></pre> <p>Now, this by itself isn't very useful since the contents of your manifest is identical to the upstream branch – we've just cloned that branch of the manifest so while you <em>can</em> run</p> <pre><code>repo init -u ssh://git.example.com/platform/manifest -b mybranch </code></pre> <p>the results will be identical to what you started with:</p> <pre><code>repo init -u ssh://git.example.com/platform/manifest -b android-4.2.2_1 </code></pre> <p>For your mirror to be useful you also have to branch each git listed in the manifest so that you get a branch on your server where you can make changes.</p> <p>Theoretically you could make changes to the same branches that you downloaded from your upstream, but that would create a mess when you attempt to sync from the upstream the next time. Don't do that.</p> <p>To create branches on the server you can follow the same pattern as for the manifest:</p> <pre><code>cd build git push ssh://git.example.com/platform/build HEAD:refs/heads/mybranch </code></pre> <p>Note the use of HEAD, the symbolic name of the currently checked out commit. Doing this for each and every git is tedious, so use the <code>repo forall</code> command:</p> <pre><code>repo forall -c 'git push aosp HEAD:refs/heads/mybranch' </code></pre> <p>Note that the remote name is different from the manifest git (IIRC).</p> <p>See <code>repo help forall</code> for a list of environment variables available for commands run by <code>repo forall</code> (<code>REPO_PROJECT</code>, <code>$REPO_LREV</code>, and <code>$REPO_RREV</code> are probably the most useful ones).</p> <p>It's easy to screw up with <code>repo forall</code>, so make it a good habit to prepend your command with <code>echo</code> first to have the commands that <em>would have been run</em> echoed to your terminal. If you're happy with the results, remove <code>echo</code> to run the commands for real.</p> <p>By now you'll have a <code>mybranch</code> branch in all your gits, including the manifest. What remains is to change the manifest so that</p> <pre><code>repo init -u ssh://git.example.com/platform/manifest -b mybranch </code></pre> <p>will actually check out <code>mybranch</code> in all the gits.</p> <pre><code>cd .repo/manifests vi default.xml [ Change the default revision from refs/tags/android-4.2.2_1 or whatever it says to 'mybranch'. ] git commit -a -m 'Changed default revision to mybranch.' git push origin default:refs/heads/mybranch </code></pre> <p>Note that all gits don't necessarily use the default revision (which you just changed to <code>mybranch</code>). It's probably the case for the android-4.2.2_1 manifest branch, but in other cases some gits won't use the default revision but instead override it with their own revision attribute. That's perfectly fine, but it'll require you to make additional manifest changes.</p>
19,587,323
What does Thread Affinity mean?
<p>Somewhere I have heard about Thread Affinity and Thread Affinity Executor. But I cannot find a proper reference for it at least in java. Can someone please explain to me what is it all about?</p>
19,587,552
4
0
null
2013-10-25 10:27:29.94 UTC
18
2021-09-08 11:54:32.44 UTC
2021-09-08 11:54:32.44 UTC
null
527,702
null
313,245
null
1
53
java|multithreading|concurrency|terminology
20,140
<p>There are two issues. First, it’s preferable that threads have an affinity to a certain CPU (core) to make the most of their CPU-local caches. This must be handled by the operating system. This <a href="https://en.wikipedia.org/wiki/Processor_affinity" rel="noreferrer">CPU affinity</a> for threads is often also called “thread affinity”. In case of Java, there is no standard API to get control over this. But there are 3rd party libraries, as mentioned by other answers.</p> <p>Second, in Java there is the observation that in typical programs objects are thread-affine, i.e. typically used by only one thread most of the time. So it’s the task of the JVM’s optimizer to ensure, that objects affine to one thread are placed close to each other in memory to fit into one CPU’s cache but place objects affine to different threads not too close to each other to avoid that they share a cache line as otherwise two CPUs/Cores have to synchronize them too often.</p> <p>The ideal situation is that a CPU can work on some objects independently to another CPU working on other objects placed in an unrelated memory region.</p> <p>Practical examples of optimizations considering Thread Affinity of Java objects are</p> <ul> <li><a href="https://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf" rel="noreferrer">Thread-Local Allocation Buffers (TLABs)</a> <p>With TLABs, each object starts its lifetime in a memory region dedicated to the thread which created it. According to the main hypothesis behind generational garbage collectors (“the majority of all objects will die young”), most objects will spent their entire lifetime in such a thread local buffer.</p> </li> <li><a href="https://blogs.oracle.com/dave/biased-locking-in-hotspot" rel="noreferrer">Biased Locking</a> <p>With Biased Locking, JVMs will perform locking operations with the optimistic assumption that the object will be locked by the same thread only, switching to a more expensive locking implementation only when this assumption does not hold.</p> </li> <li><a href="https://blogs.oracle.com/dave/java-contended-annotation-to-help-reduce-false-sharing" rel="noreferrer">@Contended</a> <p>To address the other end, fields which are known to be accessed by multiple threads, HotSpot/OpenJDK has an annotation, currently not part of a public API, to mark them, to direct the JVM to move these data away from the other, potentially unshared data.</p> </li> </ul>
34,357,252
docker data volume vs mounted host directory
<p>We can have a data volume in docker:</p> <pre><code>$ docker run -v /path/to/data/in/container --name test_container debian $ docker inspect test_container ... Mounts": [ { "Name": "fac362...80535", "Source": "/var/lib/docker/volumes/fac362...80535/_data", "Destination": "/path/to/data/in/container", "Driver": "local", "Mode": "", "RW": true } ] ... </code></pre> <p>But if the data volume lives in <code>/var/lib/docker/volumes/fac362...80535/_data</code>, is it any different from having the data in a folder mounted using <code>-v /path/to/data/in/container:/home/user/a_good_place_to_have_data</code>?</p>
34,357,861
4
0
null
2015-12-18 13:53:29.26 UTC
36
2020-12-19 19:25:45.45 UTC
null
null
null
null
159,149
null
1
109
docker
84,406
<blockquote> <p>is it any different from having the data in a folder mounted using -v /path/to/data/in/container:/home/user/a_good_place_to_have_data?</p> </blockquote> <p>It is because, as mentioned in &quot;<a href="https://docs.docker.com/engine/userguide/dockervolumes/#mount-a-host-directory-as-a-data-volume" rel="noreferrer">Mount a host directory as a data volume</a>&quot;</p> <blockquote> <p>The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile because built images should be portable. A host directory wouldn’t be available on all potential hosts.</p> <p>If you have some persistent data that you want to share between containers, or want to use from non-persistent containers, it’s best to create a named Data Volume Container, and then to mount the data from it.</p> </blockquote> <p>You can combine both approaches:</p> <pre><code> docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata </code></pre> <blockquote> <p>Here we’ve launched a new container and mounted the volume from the <code>dbdata</code> container.<br /> We’ve then mounted a local host directory as <code>/backup</code>.<br /> Finally, we’ve passed a command that uses <code>tar</code> to backup the contents of the <code>dbdata</code> volume to a <code>backup.tar</code> file inside our <code>/backup</code> directory. When the command completes and the container stops we’ll be left with a backup of our <code>dbdata</code> volume.</p> </blockquote>
18,886,708
hide img tag if src is empty but without javascript/jQuery or css3
<p>I am designing templates in Channel Advisor for eBay store and it doesn't allow <code>javascript/jQuery</code>. Also, the <code>CSS3</code> doesn't work in various <code>IE</code> versions specially the <code>img[src=]</code> implementation is broken. </p> <p>When I use template tags in img like: </p> <pre><code>&lt;img src="{{THUMB(ITEMIMAGEURL1)}}"/&gt; </code></pre> <p>where {{THUMB(ITEMIMAGEURL1)}} is the image path, if the image is missing and the template is posted to eBay then the end result would be like this:</p> <pre><code>&lt;img src=""/&gt; </code></pre> <p>and this shows a broken image. </p> <p>Is there a way to hide <code>&lt;img src=""/&gt;</code> with HTML or CSS that works in IE7+</p>
18,886,735
3
0
null
2013-09-19 05:20:40.9 UTC
2
2022-05-11 14:04:04.637 UTC
2014-02-06 04:42:52.643 UTC
null
1,542,290
user2793981
null
null
1
35
html|css|image|css-selectors
41,615
<p>You can use <code>[attr=val]</code> selector</p> <pre><code>img[src=""] { display: none; } </code></pre> <p>The above selector will simply match, if the <code>src</code> attribute has no value. This selector is a general one and will match all the <code>img</code> tag in the document with an empty <code>src</code>, if you want to target specific ones, than use more specific selector like</p> <pre><code>.class_name img[src=""] { display: none; } </code></pre> <p><kbd><a href="http://jsfiddle.net/Tqj7P/"><strong>Demo</strong></a></kbd></p> <p><kbd><s><a href="http://jsfiddle.net/Tqj7P/1/"><strong>Demo</strong></a></s></kbd> (Without the above selector, see that red line?)</p> <p>Alternatively, if you want to reserve the space taken by <code>img</code> tag, you might like to use <code>visibility: hidden;</code> instead of <code>display: none;</code> as <code>display: none;</code> will simply mess your layout where <code>visibility: hidden;</code> will reserve the space, it will just hide the <code>img</code></p> <p>See the difference between <code>display: none;</code> and <code>visibility: hidden;</code></p> <p><kbd><a href="http://jsfiddle.net/Tqj7P/2/"><strong>Demo</strong></a></kbd> (<code>visibility: hidden;</code>, reserves space)</p> <p><kbd><a href="http://jsfiddle.net/Tqj7P/3/"><strong>Demo 2</strong></a></kbd> (<code>display: none;</code>, won't reserve space)</p> <hr> <blockquote> <p>Note: None of the above selectors will REMOVE the <code>img</code> tag from the DOM, it will simply hide it from the front end</p> </blockquote>
19,265,889
turn off confimation of mailchimp
<p>i want to turn off confirmation mail of mail-chimp. I have wondered every where but not getting any response from any site. How i disable . Not any mail just user click subscribe the newsletter and redirect to current site. No need to any confirmation mail from mail chimp. Is this possible.</p>
19,283,575
3
0
null
2013-10-09 07:39:29.743 UTC
2
2020-12-06 12:19:38.69 UTC
2015-11-27 14:00:39.78 UTC
null
1,609,496
null
998,983
null
1
15
mailchimp
38,042
<p>You cannot disable MailChimp's "double opt-in" feature if you are serving one of their proprietary subscription forms. The only way to disable the confirmation email is to create a custom subscription form that invokes the MailChimp API using the <code>'double_optin' =&gt; false</code> parameter. </p> <p>See <a href="http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php">MailChimp API v2.0 documentation</a> for more info.</p>
19,259,518
How to use a Bootstrap 3 glyphicon in an html select
<p>I need to make a subset of the Bootstrap 3 glyphicons selectable in my ui by the user.</p> <p>I tried this:</p> <pre><code>&lt;select class="form-control"&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-cutlery"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-eye-open"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-heart-empty"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-leaf"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-music"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-send"&gt;&lt;/span&gt;&lt;/option&gt; &lt;option&gt;&lt;span class="glyphicon glyphicon-star"&gt;&lt;/span&gt;&lt;/option&gt; &lt;/select&gt; </code></pre> <p>However all I get are blank lines. Any help or alternative suggestions appreciated.</p>
19,259,814
4
0
null
2013-10-08 22:19:08.63 UTC
4
2018-12-11 09:55:44.68 UTC
2013-10-09 02:55:42.03 UTC
null
1,926,343
null
8,939
null
1
20
twitter-bootstrap|twitter-bootstrap-3|html-select|glyphicons
103,874
<p>I don't think the standard HTML select will display HTML content. I'd suggest checking out Bootstrap select: <a href="http://silviomoreto.github.io/bootstrap-select/" rel="noreferrer">http://silviomoreto.github.io/bootstrap-select/</a></p> <p>It has several options for displaying icons or other HTML markup in the select.</p> <pre><code>&lt;select id="mySelect" data-show-icon="true"&gt; &lt;option data-content="&lt;i class='glyphicon glyphicon-cutlery'&gt;&lt;/i&gt;"&gt;-&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-eye-open'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-heart-empty'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-leaf'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-music'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-send'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;option data-subtext="&lt;i class='glyphicon glyphicon-star'&gt;&lt;/i&gt;"&gt;&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Here is a demo: <a href="https://www.codeply.com/go/l6ClKGBmLS" rel="noreferrer">https://www.codeply.com/go/l6ClKGBmLS</a></p>
36,772,098
Recovering from Consul "No Cluster leader" state
<p>I have:</p> <ul> <li>one mesos-master in which I configured a consul server;</li> <li>one mesos-slave in which I configure consul client, and;</li> <li>one bootstrap server for consul.</li> </ul> <p>When I hit start I am seeing the following error:</p> <blockquote> <p>2016/04/21 19:31:31 [ERR] agent: failed to sync remote state: rpc error: No cluster leader 2016/04/21 19:31:44 [ERR] agent: coordinate update error: rpc error: No cluster leader</p> </blockquote> <p>How do I recover from this state?</p>
36,925,545
6
0
null
2016-04-21 14:05:53.383 UTC
2
2021-10-01 18:04:59.173 UTC
2016-04-28 21:38:02.687 UTC
null
909,882
null
4,849,270
null
1
15
mesos|consul
50,403
<p>Did you look at the <a href="https://learn.hashicorp.com/consul/day-2-operations/outage" rel="nofollow noreferrer">Consul docs</a> ?</p> <p>It looks like you have performed a ungraceful stop and now need to clean your <code>raft/peers.json</code> file by removing all entries there to perform an outage recovery. See the above link for more details.</p>
46,907,506
Can't start my virtual Box machine after installing Docker on Windows
<p>To learn ArchLinux, I installed and using ArchLinux in a VirtualBox machine. It runs perfectly. Now I installed Docker on my pc (Windows environment). During the installation of Docker I got a warning, that if I install Docker on Windows, that VirtualBox cant boot my machine's anymore cause of ...</p> <p>I uninstalled Docker and hoped that I could still use my ArchLinux. But I cant!</p> <p>Do anyone know what to do, to run VirtualBox and the machines inside correctly again?</p>
46,908,090
5
0
null
2017-10-24 09:57:19.563 UTC
13
2022-02-15 04:21:58.447 UTC
2017-10-24 11:04:07.147 UTC
null
1,199,464
null
4,186,122
null
1
46
windows|docker|virtual-machine|virtualbox|archlinux
27,317
<p>VirtualBox can't run anymore because Docker for Windows activates Hyper-V during its installation (with your permission). So you have to disable this feature again. You have to uncheck <code>Hyper-V</code> in <code>Control Panel -&gt; Programs -&gt; Programs and Features -&gt; Turn Windows features on or off</code>. After a reboot, VirtualBox should be able to run again.</p>
29,878,137
nameof with Generics
<p>I was experimenting with <code>nameof</code> with generics. I didn't get the result I was expecting. I'm not sure if this is part of the spec or not.</p> <pre><code>class MainClass { public static void Main (string[] args) { Console.WriteLine ($"Hello { nameof(FooBar&lt;string&gt;)! }"); } } class FooBar&lt;T&gt; { } </code></pre> <p>The output I get is</p> <blockquote> <p>Hello FooBar!</p> </blockquote> <p>I would expect some details about the type parameters.</p> <p>I tried it with a method and that fails with a compiler error:</p> <pre><code>class MainClass { public static void Main (string[] args) { Console.WriteLine ($"Hello { nameof(Do&lt;string&gt;) }"); } public static T Do&lt;T&gt;() {} } </code></pre> <blockquote> <p>Error CS8084: An argument to nameof operator cannot be method group with type arguments (CS8084) (foo)</p> </blockquote> <p>Is this because <code>nameof</code> is a compile-time construct and generics are types initialized at runtime? Or is there some other limitation?</p>
29,878,933
1
1
null
2015-04-26 13:19:06.457 UTC
2
2019-12-28 09:06:45.51 UTC
2015-04-26 14:45:44.037 UTC
null
1,870,803
null
23,528
null
1
30
c#|generics|mono|c#-6.0
15,023
<blockquote> <p>I would expect some details about the type parameters</p> </blockquote> <p>From the design docs:</p> <blockquote> <p><strong>Result of nameof.</strong> The result of nameof depends on the symbols that its argument bound to:</p> <p>One or more members: if all members have the same metadata name then the result of nameof is that name; otherwise it is an error "This argument refers to multiple elements with different names". The metadata name of a member <strong>I<code>or</code>I&lt; isA1...AK>` is simply "I" after standard identifier transformations have been applied.</strong></p> </blockquote> <p>The <code>&lt;T&gt;</code> parameter is removed due to standard identifier transformations (section §2.4.2 in the C# specification) which doesn't permit <code>&lt;&gt;</code> as valid identifiers. First any leading @ is removed, then Unicode escape sequences are transformed, and then any formatting characters are removed. This of course still happens at compile-time. You can also see this when you try to print out the name of a generic type:</p> <pre><code>typeof(List&lt;string&gt;).Name; </code></pre> <p>Will result in:</p> <pre><code>List`1 </code></pre> <blockquote> <p>Is this because nameof is a compile-time construct and generics are types initialized at runtime? Or is there some other limitation?</p> </blockquote> <p>The second error is specified as invalid by design to avoid overload resolution complications inside <code>nameof</code>:</p> <blockquote> <p><strong>Allow generic type arguments?</strong> Presumably 'yes' when naming a type since that's how expression binding already works. And <strong>presumably 'no.' when naming a method-group since type arguments are used/inferred during overload resolution, and it would be confusing also to have to deal with that in nameof.</strong></p> </blockquote> <p>We can see that clearly in the roslyn codebase:</p> <pre><code>private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, DiagnosticBag diagnostics) { CheckFeatureAvailability(node.GetLocation(), MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; string name = ""; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); if (!boundArgument.HasAnyErrors &amp;&amp; CheckSyntaxForNameofArgument(argument, out name, diagnostics) &amp;&amp; boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } </code></pre> <p>For the full specification, see: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions</a></p>
8,848,383
Is there such a method call "getBackgroundColor"?
<p>Is there such a method call "getBackgroundColor" in TextView? if I got 2 textViews: tv1 and tv2 in one LinearLayout. What I did:tv1.setBackgroundColor(Color.BLUE) </p> <p>Now if I wanna setBackgroundColor of tv2 as the same as tv1, how can I <strong>get the backgroundColor</strong> in tv1 first and then setBackgroundColor of tv2?</p>
8,848,494
5
0
null
2012-01-13 09:30:55.91 UTC
null
2017-08-24 21:27:16.7 UTC
2017-08-24 21:27:16.7 UTC
null
3,885,376
null
1,099,077
null
1
28
android|textview
22,383
<p>You will find the solution here : <a href="http://groups.google.com/group/android-developers/browse_thread/thread/4910bae94510ef77/59d4bb35e811e396?pli=1" rel="noreferrer">http://groups.google.com/group/android-developers/browse_thread/thread/4910bae94510ef77/59d4bb35e811e396?pli=1</a></p> <p>It will be something like that :</p> <pre><code>((PaintDrawable) tv.getBackground()).getPaint() </code></pre>
8,809,943
How to select from MySQL where Table name is Variable
<p>I have a case where getting the table name should be from a set variable like: </p> <pre><code>SET @ID_1 = (SELECT ID FROM `slider` LIMIT 0,1); SET @Cat = (SELECT Category FROM `slider` LIMIT 0,1); select * from @Cat where ID = @ID_1 </code></pre> <p>but doing that way MySQL outputs an error, so could someone show me how I can achieve that, because these are my baby steps in MySQL.</p>
8,810,027
2
0
null
2012-01-10 20:19:01.337 UTC
13
2020-04-06 19:40:52.277 UTC
2018-02-28 18:19:37.987 UTC
null
3,979,906
null
497,255
null
1
57
mysql|set|tablename
68,152
<p>You'd have to do this with a <a href="http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html" rel="noreferrer">prepared statement</a>. Something like:</p> <pre><code>SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1); PREPARE stmt1 FROM @s; EXECUTE stmt1; DEALLOCATE PREPARE stmt1; </code></pre>
8,680,752
How to open a file in new tab by default in NERDTree?
<p>I want a file to be opened in a new tab when I enter or double click it. I know there is <kbd>t</kbd> shortcut but I always open a file in a new tab and enter is more confortable for me.</p>
8,684,124
7
0
null
2011-12-30 15:00:49.3 UTC
12
2021-12-11 01:03:03.147 UTC
2011-12-30 21:02:25.567 UTC
null
11,621
null
615,789
null
1
60
vim|nerdtree
44,616
<p>Try adding</p> <pre><code>let NERDTreeMapOpenInTab='\r' </code></pre> <p>or</p> <pre><code>let NERDTreeMapOpenInTab='&lt;ENTER&gt;' </code></pre> <p>to your <code>.vimrc</code>.</p>
8,452,961
Convert string to ASCII value python
<p>How would you convert a string to ASCII values?</p> <p>For example, &quot;hi&quot; would return <code>[104 105]</code>.</p> <p>I can individually do ord('h') and ord('i'), but it's going to be troublesome when there are a lot of letters.</p>
8,452,992
9
0
null
2011-12-09 23:23:49.287 UTC
18
2021-04-13 03:51:52.727 UTC
2021-04-08 01:56:58.967 UTC
null
6,501,141
null
1,090,555
null
1
90
python|ascii
292,093
<p>You can use a list comprehension:</p> <pre><code>&gt;&gt;&gt; s = 'hi' &gt;&gt;&gt; [ord(c) for c in s] [104, 105] </code></pre>
26,436,009
Eclipse Luna crashes on new project in Ubuntu
<p>I'm having some trouble getting Eclipse Luna to work. I downloaded the tar.gz from the eclipse site and I downloaded the tar.gz for the Java JDK. I extracted everything and Eclipse opens properly, but when I try to make a new project, it crashes on me. In the terminal I ran <code>java -version</code> and it tells me I have version 1.8.0_25 so I don't think I have an issue with java. Now, this happens if I try to make any kind of project. Eclipse opens the wizard for creating a new project of a particular type and then the whole application crashes. When I started doing this, I installed it under the KDE desktop. When Eclipse crashes, I get the message <code>java: /build/buildd/gtk2-engines-oxygen-1.4.5/src/animations/oxygencomboboxdata.cpp:87‌​: void Oxygen::ComboBoxData::setButton(GtkWidget*): Assertion '!_button._widget' failed</code>. So, I decided to install the xfce desktop to get around it, since oxygen is a KDE theme. I uninstalled eclipse and reinstalled it under xfce and I have the same behavior and the same errors. When I run eclipse from the command line, I get this exception on startup: </p> <pre><code>java.lang.ClassCastException: org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 cannot be cast to java.lang.String at org.eclipse.m2e.logback.configuration.LogHelper.logJavaProperties(LogHelper.java:26) at org.eclipse.m2e.logback.configuration.LogPlugin.loadConfiguration(LogPlugin.java:189) at org.eclipse.m2e.logback.configuration.LogPlugin.configureLogback(LogPlugin.java:144) at org.eclipse.m2e.logback.configuration.LogPlugin.access$2(LogPlugin.java:107) at org.eclipse.m2e.logback.configuration.LogPlugin$1.run(LogPlugin.java:62) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) </code></pre> <p>Does anyone have any ideas on what else to try?</p>
26,590,329
2
0
null
2014-10-18 03:25:08.703 UTC
8
2015-05-24 15:14:54.043 UTC
null
null
null
null
3,794,177
null
1
21
eclipse|ubuntu|crash
10,127
<p>According to comment 20 in this bug report: <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=440660#c20" rel="noreferrer">https://bugs.eclipse.org/bugs/show_bug.cgi?id=440660#c20</a></p> <blockquote> <p>This seems to be a bug in GTK according to <a href="https://bugs.launchpad.net/ubuntu/+source/gtk2-engines-oxygen/+bug/1242801" rel="noreferrer">https://bugs.launchpad.net/ubuntu/+source/gtk2-engines-oxygen/+bug/1242801</a> (there a similar problem for Meld was reported).</p> <p>Another workaround mentioned there is for Oxygen, edit the normally already existing file <code>/usr/share/themes/oxygen-gtk/gtk-2.0/gtkrc</code> and change</p> <pre><code>`GtkComboBox::appears-as-list = 1` </code></pre> <p>into</p> <pre><code>`GtkComboBox::appears-as-list = 0` </code></pre> <p>This workaround is working for me.</p> </blockquote>
30,710,550
Node JS NPM modules installed but command not recognized
<p>Node JS and NPM were working well before. Recently I have re-installed the Node JS, NPM and the problem started. After I install a module like an example <code>npm install -g bower</code>, the module gets installed successfully but <code>bower -v</code> gives</p> <blockquote> <p>'bower' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>I have checked the installation path <code>C:\Users\XXXXX\AppData\Roaming\npm\node_modules</code> has all the old installed modules. I have tried to uninstall them and reinstall the modules, but still, I am getting the same error.</p> <p>Even I have deleted the entire folder and installed all the modules again but the result is the same.</p> <p>I don't know why I am getting this error after reinstalling NodeJS NPM.</p>
30,716,060
7
0
null
2015-06-08 13:33:49.8 UTC
18
2021-06-22 07:13:31.46 UTC
2021-04-10 03:03:51.343 UTC
null
11,573,842
null
1,981,728
null
1
67
node.js|npm|bower
106,702
<p>I had this same problem and fixed it by adding the 'npm' directory to my PATH:</p> <p>Right-click 'My Computer' and go to 'Properties &gt; Advanced System Settings &gt; Environment Variables'.</p> <p>Double click on PATH under the 'User variables for Username' section, and add <code>C:\Users\username\AppData\Roaming\npm</code> obviously replacing 'username' with yours. <em>Based on the comments below, you may need to add it to the top/front of your path.</em></p> <p>Restart your console window or IDE and you should get a response from the bower command.</p>
214,426
How to compare dates in LINQ?
<p>I want to check if a given date is more than a month earlier than today's date using LINQ.</p> <p>What is the syntax for this?</p> <p>Thanks in advance.</p>
214,442
3
0
null
2008-10-18 02:26:55.297 UTC
2
2017-05-23 17:38:03.37 UTC
null
null
null
TedH
8,783
null
1
16
.net|linq
46,855
<p>I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.</p> <pre><code>using (DataContext context = new DataContext()) { var query = from t in context.table where t.CreateDate.Date &lt; DateTime.Today.AddMonths(-1) select t; } </code></pre>
401,561
How to open a multi-frame TIFF imageformat image in .NET 2.0?
<pre><code>Image.FromFile(@"path\filename.tif") </code></pre> <p>or</p> <pre><code>Image.FromStream(memoryStream) </code></pre> <p>both produce image objects with only one frame even though the source is a multi-frame TIFF file. <strong>How do you load an image file that retains these frames?</strong> The tiffs are saved using the Image.SaveAdd methods frame by frame. They work in other viewers but .NET Image methods will not load these frames, only the first. </p> <p><strong>Does this mean that there is no way to return a multi-frame TIFF from a method where I am passing in a collection of bitmaps to be used as frames?</strong></p>
401,579
3
0
null
2008-12-30 21:25:33.79 UTC
9
2016-12-28 16:53:58.68 UTC
2008-12-30 21:37:47.307 UTC
alram
35,286
alram
35,286
null
1
16
c#|tiff|system.drawing
31,931
<p>Here's what I use:</p> <pre><code>private List&lt;Image&gt; GetAllPages(string file) { List&lt;Image&gt; images = new List&lt;Image&gt;(); Bitmap bitmap = (Bitmap)Image.FromFile(file); int count = bitmap.GetFrameCount(FrameDimension.Page); for (int idx = 0; idx &lt; count; idx++) { // save each frame to a bytestream bitmap.SelectActiveFrame(FrameDimension.Page, idx); MemoryStream byteStream = new MemoryStream(); bitmap.Save(byteStream, ImageFormat.Tiff); // and then create a new Image from it images.Add(Image.FromStream(byteStream)); } return images; } </code></pre>
256,172
What is the most secure method for uploading a file?
<p>The company I work for has recently been hit with many header injection and file upload exploits on the sites we host and while we have fixed the problem with respect to header injection attacks, we have yet to get the upload exploits under control.</p> <p>I'm trying to set up a plug-and-play-type series of upload scripts to use in-house that a designer can copy into their site's structure, modify a few variables, and have a ready-to-go upload form on their site. We're looking to limit our exposure as much as possible (we've already shut down fopen and shell commands).</p> <p>I've searched the site for the last hour and found many different answers dealing with specific methods that rely on outside sources. What do you all think is the best script-only solution that is specific enough to use as a reliable method of protection? Also, I'd like to keep the language limited to PHP or pseudo-code if possible.</p> <p><strong>Edit:</strong> I've found my answer (posted below) and, while it does make use of the shell command exec(), if you block script files from being uploaded (which this solution does very well), you won't run into any problems.</p>
256,279
3
0
2008-11-01 22:00:30.933 UTC
2008-11-01 22:00:30.933 UTC
44
2018-08-09 08:05:36.04 UTC
2008-11-14 15:59:26.83 UTC
Stephen
25,375
Stephen
25,375
null
1
40
php|security|file-upload
36,612
<p>The best solution, IMHO, is to put the directory containing the uploaded files outside of the "web" environment and use a script to make them downloadable. In this way, even if somebody uploads a script it can not be executed by calling it from the browser and you don't have to check the type of the uploaded file.</p>
548,029
How much overhead does SSL impose?
<p>I know there's no single hard-and-fast answer, but is there a generic <strike>order-of-magnitude estimate</strike> approximation for the encryption overhead of SSL versus unencrypted socket communication? I'm talking only about the comm processing and wire time, not counting application-level processing.</p> <p><strong>Update</strong></p> <p>There is <a href="https://stackoverflow.com/questions/149274/http-vs-https-performance">a question about HTTPS versus HTTP</a>, but I'm interested in looking lower in the stack.</p> <p>(I replaced the phrase "order of magnitude" to avoid confusion; I was using it as informal jargon rather than in the formal CompSci sense. Of course if I <em>had</em> meant it formally, as a true geek I would have been thinking binary rather than decimal! ;-)</p> <p><strong>Update</strong></p> <p>Per request in comment, assume we're talking about good-sized messages (range of 1k-10k) over persistent connections. So connection set-up and packet overhead are not significant issues.</p>
548,042
3
3
null
2009-02-13 23:00:00.353 UTC
61
2017-07-05 11:16:31.083 UTC
2017-05-23 12:34:25.273 UTC
joel.neely
-1
joel.neely
3,525
null
1
171
performance|sockets|ssl|overhead
108,479
<p>Order of magnitude: zero.</p> <p>In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the <a href="https://stackoverflow.com/questions/149274/http-vs-https-performance">"duplicate" question</a> focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.</p> <p>The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.</p> <hr> <p>Here's <a href="http://www.imperialviolet.org/2010/06/25/overclocking-ssl.html" rel="noreferrer">an interesting anecdote.</a> When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.</p>
41,803,856
Set timeout in Alamofire
<p>I am using Alamofire 4.0.1 and <strong>I want to set a timeout for my request</strong>. I tried the solutions gived in this <a href="https://stackoverflow.com/questions/36626075/handle-timeout-with-alamofire">question</a>:</p> <p><strong>In the first case</strong>, it throws a <strong><em>NSURLErrorDomain</em></strong> (timeout is set correctly):</p> <pre><code>let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 10 let sessionManager = Alamofire.SessionManager(configuration: configuration) sessionManager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"]) .responseJSON { response in switch (response.result) { case .success: //do json stuff break case .failure(let error): if error._code == NSURLErrorTimedOut { //timeout here } print("\n\nAuth request failed with error:\n \(error)") break } } </code></pre> <p><strong>In the second case</strong>, the time out is not replaced and still set as 60 seconds.</p> <pre><code>let manager = Alamofire.SessionManager.default manager.session.configuration.timeoutIntervalForRequest = 10 manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"]) </code></pre> <p><strong>I am running in ios 10.1</strong></p> <p><strong>My code:</strong> (it doesn't work)</p> <pre><code> let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 10 // seconds configuration.timeoutIntervalForResource = 10 let alamoFireManager = Alamofire.SessionManager(configuration: configuration) alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in switch (response.result) { case .success: //Success.... break case .failure(let error): // failure... break } } </code></pre> <p><strong>Solved Alamofire github thread:</strong> <a href="https://github.com/Alamofire/Alamofire/issues/1931#issuecomment-274826417" rel="noreferrer">Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931</a></p>
44,300,926
15
2
null
2017-01-23 10:15:17.71 UTC
12
2021-11-04 12:08:26.45 UTC
2017-08-23 10:40:39.87 UTC
null
1,826,257
null
1,826,257
null
1
63
ios|swift|alamofire
67,290
<p>Based in @kamal-thakur response.</p> <p><strong>Swift 3</strong>:</p> <pre><code>var request = URLRequest(url: NSURL.init(string: "YOUR_URL") as! URL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.timeoutInterval = 10 // 10 secs let postString = "param1=\(var1)&amp;param2=\(var2)" request.httpBody = postString.data(using: .utf8) Alamofire.request(request).responseJSON { response in // do whatever you want here } </code></pre>
28,762,376
Laravel 5: Best way to validate form with Javascript
<p>I want to validate forms in the client side in Laravel. It's there any easy way to do it?</p>
29,099,790
4
2
null
2015-02-27 10:05:37.377 UTC
2
2019-04-05 15:04:57.23 UTC
null
null
null
null
1,651,152
null
1
12
laravel|laravel-5
38,420
<p>You can use the package <a href="https://github.com/proengsoft/laravel-jsvalidation" rel="noreferrer">Laravel 5 Javascript Validation</a>. This package enables transparent Javascript Valditaion in your views based on <a href="http://jqueryvalidation.org/" rel="noreferrer">JQuery Validation Plugin</a></p> <p>This is a basic example of how to reuse your validation rules in the controller.</p> <p><strong>PostController.php</strong></p> <pre><code>namespace App\Http\Controllers; class PostController extends Controller { /** * Define your validation rules in a property in * the controller to reuse the rules. */ protected $validationRules=[ 'title' =&gt; 'required|unique|max:255', 'body' =&gt; 'required' ]; /** * Show the edit form for blog post * We create a JsValidator instance based on shared validation rules * @param string $post_id * @return Response */ public function edit($post_id) { $validator = JsValidator::make($this-&gt;validationRules); $post = Post::find($post_id); return view('edit_post')-&gt;with([ 'validator' =&gt; $validator, 'post' =&gt; $post ]); } /** * Store the incoming blog post. * @param Request $request * @return Response */ public function store(Request $request) { $v = Validator::make($request-&gt;all(), $this-&gt;validationRules]); if ($v-&gt;fails()) { return redirect()-&gt;back()-&gt;withErrors($v-&gt;errors()); } // do store stuff } } </code></pre> <p>In the view you simply should print the <em>validator</em> object passed to the view. <strong>Remember</strong> that this package depends of JQuery and you have to include before that <em>jsvalidation.js</em></p> <p><strong>edit_post.blade.php</strong></p> <pre><code> &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-10 col-md-offset-1"&gt; &lt;form class="form-horizontal" role="form" method="POST" action="" id="ddd"&gt; &lt;div class="form-group"&gt; &lt;label class="col-md-4 control-label"&gt;Title&lt;/label&gt; &lt;div class="col-md-6"&gt; &lt;input type="text" class="form-control" name="title"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-md-4 control-label"&gt;Array&lt;/label&gt; &lt;div class="col-md-6"&gt; &lt;textarea name="body"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Scripts --&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;!-- Laravel Javascript Validation --&gt; &lt;script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"&gt;&lt;/script&gt; {!! $validator !!} </code></pre>
24,060,379
What is the difference between != and <> operators?
<p>I don't like not knowing this as there may be situations when I need to use one instead of the other. It seems in most cases they produce the same results but I am taking a guess they have subtle difference, maybe to do with NULL values or one does strict comparisons like the extra = in PHP does.</p> <p>Thanks</p>
24,060,451
4
0
null
2014-06-05 12:34:37.41 UTC
1
2020-06-15 07:15:18.683 UTC
2020-06-15 06:16:24.857 UTC
null
12,833,205
null
3,484,341
null
1
29
postgresql
20,430
<p>From the <a href="http://www.postgresql.org/docs/current/static/functions-comparison.html" rel="noreferrer">manual</a>:</p> <blockquote> <p>Note: The != operator is converted to &lt;> in the parser stage. It is not possible to implement != and &lt;> operators that do different things.</p> </blockquote> <p>So no, there is no difference between the two.</p>
24,148,048
How to use function in Kendo Grid Column Template with AngularJS
<p>I have a column in a Kendo grid that I want to perform some specific logic for when rendering, and am using Angular. I have the grid columns set up using the k-columns directive.</p> <p>After looking at <a href="http://docs.telerik.com/kendo-ui/documentation/api/web/grid#configuration-columns-template">the documentation</a>, it seemed simple: I could add the template option to my column, define the function to perform my logic, and pass the dataItem value in. What I have looks something like this:</p> <pre><code>k-columns='[{ field: "Name", title: "Name", template: function (dataItem){ // Perform logic on value with dataItem.Name // Return a string } }]' </code></pre> <p>However, running this causes a syntax error complaining about the character '{' that forms the opening of the block in my function. </p> <p>I have seen several examples of defining a template function in this format. Is there something else that needs to be done for this to work? Am I doing something incorrectly? Is there another way of defining the template as a function and passing the column data to it? (I tried making a function on my $scope, which worked, except I couldn't figure out how to get data passed into the function.) </p> <p>Thank you for your help.</p>
24,163,734
6
0
null
2014-06-10 18:09:52.007 UTC
null
2022-08-11 14:29:48.73 UTC
2014-06-11 12:57:48.193 UTC
null
1,447,559
null
1,447,559
null
1
10
javascript|angularjs|templates|kendo-ui|grid
40,406
<p>It appears that defining a column template in this fashion isn't supported when using AngularJS and Kendo. This approach works for projects that do not use Angular (standard MVVM), but fails with its inclusion.</p> <p>The workaround that a colleague of mine discovered is to build the template using ng-bind to specify a templating function on the $scope, all inside of a span:</p> <pre><code>template: "&lt;span ng-bind=templateFunction(dataItem.Name)&gt;#: data.Name# &lt;/span&gt;" </code></pre> <p>This is the default column templating approach that is implemented by Telerik in their Kendo-Angular source code. I don't know yet if the data.Name value is required or not, but this works for us.</p>
35,988,990
How to enable php7 module in apache?
<p>When I try to run <code>a2enmod php7.0</code> - I got message "Considering conflict php5 for php7.0". </p> <p>After restarting apache - apache can't start.</p> <p>How to solve this?</p> <p>Maybe some already enabled modules links to php5?</p> <p>Params: Ubuntu Wily, Apache 2.4.18, PHP 7.0.4 (works only cli)</p>
35,990,093
3
1
null
2016-03-14 13:34:16.37 UTC
12
2020-02-12 14:30:30.093 UTC
2017-07-05 13:15:15.523 UTC
null
3,810,453
null
3,231,773
null
1
39
php|apache|ubuntu
179,011
<p>First, disable the <code>php5</code> module:</p> <pre><code>a2dismod php5 </code></pre> <p>then, enable the <code>php7</code> module:</p> <pre><code>a2enmod php7.0 </code></pre> <p>Next, reload/restart the Apache service:</p> <pre><code>service apache2 restart </code></pre> <hr> <h2>Update 2018-09-04</h2> <p>wrt <a href="https://stackoverflow.com/questions/35988990/how-to-enable-php7-module-in-apache/35990093?noredirect=1#comment91260001_35990093">the comment</a>, you need to specify exact installed <a href="/questions/tagged/php-7.x" class="post-tag" title="show questions tagged &#39;php-7.x&#39;" rel="tag">php-7.x</a> version.</p>
36,173,983
Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'
<p>I get this error when I try to Build Signed APK. I recently upgraded to API 23 but Generated APK:s successfully after that. Im confused. Asking for help and advise how to solve this problem. Here's the error</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:validateExternalOverrideSigning'. &gt; Keystore file /Users/me/Desktop/final apps/keystore.jks not found for signing config 'externalOverride'. * Try: Run with --stacktrace option to get the stack trace. Run with --info or -- debug option to get more log output. </code></pre> <p>And the log</p> <pre><code>Information:Gradle tasks [:app:assembleRelease] :app:preBuild UP-TO-DATE :app:preReleaseBuild UP-TO-DATE :app:checkReleaseManifest :app:preDebugBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing810Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBasement810Library UP-TO-DATE :app:prepareReleaseDependencies :app:compileReleaseAidl UP-TO-DATE :app:compileReleaseRenderscript UP-TO-DATE :app:generateReleaseBuildConfig UP-TO-DATE :app:generateReleaseAssets UP-TO-DATE :app:mergeReleaseAssets UP-TO-DATE :app:generateReleaseResValues UP-TO-DATE :app:generateReleaseResources UP-TO-DATE :app:mergeReleaseResources UP-TO-DATE :app:processReleaseManifest UP-TO-DATE :app:processReleaseResources UP-TO-DATE :app:generateReleaseSources UP-TO-DATE :app:compileReleaseJavaWithJavac Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details. :app:compileReleaseNdk UP-TO-DATE :app:compileReleaseSources :app:lintVitalRelease :app:transformClassesWithDexForRelease :app:mergeReleaseJniLibFolders :app:transformNative_libsWithMergeJniLibsForRelease :app:processReleaseJavaRes UP-TO-DATE :app:transformResourcesWithMergeJavaResForRelease :app:validateExternalOverrideSigning FAILED Error:Execution failed for task ':app:validateExternalOverrideSigning'. &gt; Keystore file /Users/me/Desktop/final apps/keystore.jks not found for signing config 'externalOverride'. </code></pre> <p>Here is my Gradle</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.waffles.vatsandbats" minSdkVersion 14 targetSdkVersion 23 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile files('libs/acra-4.7.0-javadoc.jar') compile files('libs/acra-4.7.0-sources.jar') compile files('libs/acra-4.7.0.jar') compile 'com.google.android.gms:play-services-appindexing:8.1.0' compile files('libs/activation.jar') compile files('libs/mail.jar') compile files('libs/additionnal.jar') compile 'com.android.support:support-v4:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1' } </code></pre>
36,176,437
13
1
null
2016-03-23 09:16:00.517 UTC
13
2021-12-20 16:03:45.257 UTC
2019-06-28 09:40:41.367 UTC
null
1,000,551
null
5,414,894
null
1
121
android|android-studio|build|apk|android-signing
135,760
<p>I found the solution. I misplaced the path to the <code>keystore.jks</code> file. Searched for the file on my computer used that path and everything worked great.</p>
36,151,981
Local hostnames for Docker containers
<p>Beginner Docker question here,</p> <p>So I have a development environment in which I'm running a modular app, it is working using Docker Compose to run 3 containers: server, client, database.</p> <p>The <code>docker-compose.yml</code> looks like this:</p> <pre><code>############################# # Server ############################# server: container_name: server domainname: server.dev hostname: server build: ./server working_dir: /app ports: - "3000:3000" volumes: - ./server:/app links: - database ############################# # Client ############################# client: container_name: client domainname: client.dev hostname: client image: php:5.6-apache ports: - "80:80" volumes: - ./client:/var/www/html ############################# # Database ############################# database: container_name: database domainname: database.dev hostname: database image: postgres:9.4 restart: always environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=root - POSTGRES_DB=dbdev - PG_TRUST_LOCALNET=true ports: - "5432:5432" volumes: - ./database/scripts:/docker-entrypoint-initdb.d # init scripts </code></pre> <p>You can see I'm assigning a .dev domainname to each one, this works fine to see one machine from another one (Docker internal network), for example here I'm pinging <code>server.dev</code> from <code>client.dev</code>'s CLI:</p> <pre><code> root@client:/var/www/html# ping server.dev PING server.dev (127.0.53.53): 56 data bytes 64 bytes from 127.0.53.53: icmp_seq=0 ttl=64 time=0.036 ms </code></pre> <p><strong>This works great internally, but not on my host OS network.</strong></p> <p>For convenience, I would like to assigns domains in MY local network, not the Docker containers network so that I can for example type: client.dev on my browsers URL and load the Docker container.</p> <p>Right now, I can only access if I use the Docker IP, which is dynamic:</p> <pre><code>client: 192.168.99.100:80 server: 192.168.99.100:3000 database: 192.168.99.100:5432 </code></pre> <p>Is there an automated/convenient way to do this that doesn't involve me manually adding the IP to my /etc/hosts file ?</p> <p>BTW I'm on OSX if that has any relevance.</p> <p>Thanks!</p> <p><strong>Edit:</strong> I found this Github issue which seems to be related: <a href="https://github.com/docker/docker/issues/2335">https://github.com/docker/docker/issues/2335</a></p> <p>As far as I understood, they seem to say that it is something that is not available outside of the box and they suggest external tools like: </p> <ul> <li><a href="https://github.com/jpetazzo/pipework">https://github.com/jpetazzo/pipework</a></li> <li><a href="https://github.com/bnfinet/docker-dns">https://github.com/bnfinet/docker-dns</a></li> <li><a href="https://github.com/gliderlabs/resolvable">https://github.com/gliderlabs/resolvable</a></li> </ul> <p>Is that correct? And if so, which one should I go for in my particular scenario?</p>
36,156,395
5
2
null
2016-03-22 10:31:52.807 UTC
27
2021-06-15 23:03:54.913 UTC
2016-03-22 15:39:30.183 UTC
null
3,480,821
null
3,480,821
null
1
57
docker|docker-compose
54,899
<p>OK,</p> <p>so since <a href="https://github.com/docker/docker/issues/2335#issuecomment-152359554" rel="noreferrer">it seems that there is no native way to do this with Docker</a>, I finally opted for this <a href="http://cavaliercoder.com/blog/update-etc-hosts-for-docker-machine.html" rel="noreferrer">alternate solution</a> from Ryan Armstrong, which consists in dynamically updating the <code>/etc/hosts</code> file.</p> <p>I chose this since it was convenient for me since this works as a script, and I already had a startup script, so I could just append this function in to it.</p> <blockquote> <p>The following example creates a hosts entry named docker.local which will resolve to your docker-machine IP:</p> <pre><code>update-docker-host(){ # clear existing docker.local entry from /etc/hosts sudo sed -i '' '/[[:space:]]docker\.local$/d' /etc/hosts # get ip of running machine export DOCKER_IP="$(echo ${DOCKER_HOST} | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')" # update /etc/hosts with docker machine ip [[ -n $DOCKER_IP ]] &amp;&amp; sudo /bin/bash -c "echo \"${DOCKER_IP} docker.local\" &gt;&gt; /etc/hosts" } update-docker-host </code></pre> </blockquote> <p>This will automatically add or udpate the <code>/etc/hosts</code> line on my host OS when I start the Docker machine through my startup script.</p> <p>Anyways, as I found out during my research, apart from editing the hosts file, you could also solve this problem by <a href="https://engineering.salesforceiq.com/2015/10/08/up-the-rabbit-hole-part-i-a-docker-machine-dns-server.html" rel="noreferrer">setting up a custom DNS server</a>:</p> <p>Also found several projects on Github which apparently aim to solve this problem, although I didn't try them:</p> <ul> <li><a href="https://github.com/jpetazzo/pipework" rel="noreferrer">https://github.com/jpetazzo/pipework</a></li> <li><a href="https://github.com/bnfinet/docker-dns" rel="noreferrer">https://github.com/bnfinet/docker-dns</a></li> <li><a href="https://github.com/gliderlabs/resolvable" rel="noreferrer">https://github.com/gliderlabs/resolvable</a></li> </ul>
41,620,937
Implicit return from lambda in Kotlin
<p>It seems that the last line of a lambda always returns that value even if you omit the <code>return</code> statement. Is this correct? Is it documented anywhere?</p> <pre><code>fun main(args: Array&lt;String&gt;) { val nums = arrayOf(1, 2, 3) val numsPlusOne = nums.map { it -&gt; val r = it + 1 r } // numsPlusOne = [2, 3, 4] } </code></pre>
41,621,349
1
1
null
2017-01-12 19:01:00.163 UTC
4
2017-04-25 09:14:58.817 UTC
null
null
null
null
1,287,550
null
1
35
kotlin
15,376
<p>Yes, this is correct, if the last statement of a lambda is an expression, it is considered its return value.</p> <p>Here's <a href="http://kotlinlang.org/docs/reference/lambdas.html#lambda-expression-syntax" rel="noreferrer">what the reference says</a> (thanks <a href="https://stackoverflow.com/users/615306/kirill-rakhman">@KirillRakhman</a>):</p> <blockquote> <p>We can explicitly return a value from the lambda using the <a href="http://kotlinlang.org/docs/reference/returns.html#return-at-labels" rel="noreferrer">qualified return</a> syntax. Otherwise, the value of the last expression is implictly returned. Therefore, the two following snippets are equivalent:</p> <pre><code>ints.filter { val shouldFilter = it &gt; 0 shouldFilter } </code></pre> <p><sup> </sup></p> <pre><code>ints.filter { val shouldFilter = it &gt; 0 return@filter shouldFilter } </code></pre> </blockquote> <p>The last statement semantics is also true for <a href="https://kotlinlang.org/docs/reference/control-flow.html#if-expression" rel="noreferrer"><code>if</code> (that's why there's no ternary operator)</a>, <code>when</code> and <a href="https://kotlinlang.org/docs/reference/exceptions.html#try-is-an-expression" rel="noreferrer"><code>try</code>-<code>catch</code></a> blocks, and these statements are expressions themselves:</p> <pre><code>val foo = if (bar) { doSomething() baz } else { doSomethingElse() qux } </code></pre> <p><sup>See also: <a href="http://try.kotlinlang.org/#/UserProjects/rrdg9fn46rg3563uvigo8o2bp6/dvqkeha0alvsaqjvl6hppb1n90" rel="noreferrer">examples for <code>when</code> and <code>try</code>-<code>catch</code></a>.</sup></p> <p>So, lambdas are consistent with the language constructs in this respect.</p> <hr> <p>If you want to make an explicit <code>return</code> statement in a lambda, use the <a href="https://kotlinlang.org/docs/reference/returns.html#return-at-labels" rel="noreferrer"><code>return@label</code> syntax</a> (also, <a href="https://stackoverflow.com/questions/40160489/kotlin-whats-does-return-mean">another answer with examples</a>). Non-labeled <code>return</code>, on contrary, works with the nearest <code>fun</code> (ignoring lambdas) and thus can only occur in those lambdas which are <a href="https://kotlinlang.org/docs/reference/inline-functions.html#non-local-returns" rel="noreferrer">inlined</a>.</p> <p>There was a <a href="https://youtrack.jetbrains.com/issue/KT-8695" rel="noreferrer">language proposal</a> to add special syntax for <em>emitting</em> a value from a code block, but it was rejected.</p>
19,894,939
Calculate Arbitrary Percentile on Pandas GroupBy
<p>Currently there is a <code>median</code> method on the Pandas's <code>GroupBy</code> objects.</p> <p>Is there is a way to calculate an arbitrary <code>percentile</code> (see: <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html" rel="noreferrer">http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.percentile.html</a>) on the groupings? </p> <p>Median would be the calcuation of percentile with <code>q=50</code>.</p>
19,895,152
3
0
null
2013-11-10 20:43:40.7 UTC
11
2020-09-30 16:24:24.9 UTC
null
null
null
null
2,638,485
null
1
33
pandas
48,027
<p>You want the <code>quantile</code> method:</p> <pre><code>In [47]: df Out[47]: A B C 0 0.719391 0.091693 one 1 0.951499 0.837160 one 2 0.975212 0.224855 one 3 0.807620 0.031284 one 4 0.633190 0.342889 one 5 0.075102 0.899291 one 6 0.502843 0.773424 one 7 0.032285 0.242476 one 8 0.794938 0.607745 one 9 0.620387 0.574222 one 10 0.446639 0.549749 two 11 0.664324 0.134041 two 12 0.622217 0.505057 two 13 0.670338 0.990870 two 14 0.281431 0.016245 two 15 0.675756 0.185967 two 16 0.145147 0.045686 two 17 0.404413 0.191482 two 18 0.949130 0.943509 two 19 0.164642 0.157013 two In [48]: df.groupby('C').quantile(.95) Out[48]: A B C one 0.964541 0.871332 two 0.826112 0.969558 </code></pre>
6,129,581
In maven - how to rename the output .war file based on the name of the profile in use
<p>I have three profiles in my pom.xml for our application...</p> <ol> <li>dev (for use on a developer's)</li> <li>qa (for use on our internal qa server)</li> <li>prod (production).</li> </ol> <p>When we run our maven build all three profiles ouput a war file with the same name. I would like to output <code>$profilename-somearbitraryname.war</code></p> <p>Any ideas?</p>
6,130,047
3
1
null
2011-05-25 19:12:42.893 UTC
12
2017-11-23 20:34:41.637 UTC
2014-03-15 16:19:08.263 UTC
null
1,521,627
null
97,901
null
1
36
maven|war
60,602
<p>You've answered yourself correctly:</p> <pre class="lang-xml prettyprint-override"><code>&lt;profiles&gt; &lt;profile&gt; &lt;id&gt;dev&lt;/id&gt; &lt;properties&gt; &lt;rp.build.warname&gt;dev&lt;/rp.build.warname&gt; &lt;/properties&gt; &lt;/profile&gt; &lt;profile&gt; &lt;id&gt;qa&lt;/id&gt; &lt;properties&gt; &lt;rp.build.warname&gt;qa&lt;/rp.build.warname&gt; &lt;/properties&gt; &lt;/profile&gt; &lt;profile&gt; &lt;id&gt;prod&lt;/id&gt; &lt;properties&gt; &lt;rp.build.warname&gt;prod&lt;/rp.build.warname&gt; &lt;/properties&gt; &lt;/profile&gt; &lt;/profiles&gt; </code></pre> <p>but there is a simpler way to redefine WAR name:</p> <pre class="lang-xml prettyprint-override"><code>&lt;build&gt; &lt;finalName&gt;${rp.build.warname}-somearbitraryname&lt;/finalName&gt; &lt;!-- ... --&gt; &lt;/build&gt; </code></pre> <p>No <code>maven-war-plugin</code> is needed.</p>
6,171,865
Retrieve jQuery Cookie value
<p>Example, I have this cookie:</p> <pre><code>$.cookie("foo", "500", { path: '/', expires: 365 }); </code></pre> <p>How do I get the value of that cookie and put it into a variable?</p> <p>For example (I know this is not correct):</p> <pre><code>var foo = $.cookie("foo").val(); </code></pre>
6,171,872
4
0
null
2011-05-30 02:50:21.577 UTC
null
2019-10-15 12:52:56.5 UTC
null
null
null
null
633,424
null
1
15
javascript|jquery|cookies
52,698
<p>It's just <code>var foo = $.cookie("foo")</code>.</p> <p>There's no need for a <code>.val()</code> call as you're not accessing the <em>value</em> of a DOM element.</p>
5,808,923
filter values from an array similar to SQL LIKE '%search%' using PHP
<p>I created an autocomplete field using JQueryUI and I've stored my data in a flat doc. I can read the values into an array... but I would like to be able to return the alphabetic matches based on the user input. So if the array contains <code>[orange,blue,green,red,pink,brown,black]</code> and the user types bl then I only return <code>[blue,black]</code>.</p> <p>Looking at <code>array_diff()</code> but without complete matches on the entire value of the array, I'm not sure how to use it... maybe a regular expression thrown in? My two weakest skills array manipulation and regex Thanks for the help!</p>
5,809,221
4
1
null
2011-04-27 18:42:51.233 UTC
14
2021-12-28 05:17:47.513 UTC
null
null
null
null
249,355
null
1
34
php|arrays
70,913
<p>You don't need to use <code>array_filter</code> and a custom / lambda function, <a href="http://php.net/manual/en/function.preg-grep.php"><code>preg_grep</code></a> does the trick:</p> <pre><code>$input = preg_quote('bl', '~'); // don't forget to quote input string! $data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black'); $result = preg_grep('~' . $input . '~', $data); </code></pre>
34,512,437
Simplest method to check whether unordered_map of unordered_maps contains key
<p>I am using an unordered_map of unordered_maps, such that I can reference an element using the "multi key" syntax:</p> <p><code>my_map[k1][k2]</code>. </p> <p>Is there a convenient way to use the same "multi-key" syntax to check whether an element exists before trying to access it? If not, what is the simplest way?</p>
34,512,483
7
1
null
2015-12-29 13:49:13.15 UTC
5
2021-07-13 08:21:38.42 UTC
2015-12-29 14:15:25.76 UTC
null
997,112
null
997,112
null
1
34
c++|c++11|unordered-map
47,218
<p>If your intention is to test for the existence of the key, I would not use</p> <pre><code>my_map[k1][k2] </code></pre> <p>because <a href="http://en.cppreference.com/w/cpp/container/unordered_map/operator_at" rel="noreferrer"><code>operator[]</code></a> will default construct a new value for that key if it does not already exist.</p> <p>Rather I would prefer to use <a href="http://en.cppreference.com/w/cpp/container/unordered_map/find" rel="noreferrer"><code>std::unordered_map::find</code></a>. So if you are certain the first key exists, but not the second you could do</p> <pre><code>if (my_map[k1].find(k2) != my_map[k1].end()) { // k2 exists in unordered_map for key k1 } </code></pre> <p>If you would like to make a function that checks for the existence of <strong>both</strong> keys, then you could write something like</p> <pre><code>//------------------------------------------------------------------------------ /// \brief Determines a nested map contains two keys (the outer containing the inner) /// \param[in] data Outer-most map /// \param[in] a Key used to find the inner map /// \param[in] b Key used to find the value within the inner map /// \return True if both keys exist, false otherwise //------------------------------------------------------------------------------ template &lt;class key_t, class value_t&gt; bool nested_key_exists(std::unordered_map&lt;key_t, std::unordered_map&lt;key_t, value_t&gt;&gt; const&amp; data, key_t const a, key_t const b) { auto itInner = data.find(a); if (itInner != data.end()) { return itInner-&gt;second.find(b) != itInner-&gt;second.end(); } return false; } </code></pre>
32,174,317
How to set default Checked in checkbox ReactJS?
<p>I'm having trouble to update the checkbox state after it's assigned with default value <code>checked=&quot;checked&quot;</code> in React.</p> <pre><code>var rCheck = React.createElement('input', { type: 'checkbox', checked: 'checked', value: true }, 'Check here'); </code></pre> <p>After assigning <code>checked=&quot;checked&quot;</code>, I cannot interact the checkbox state by clicking to uncheck/check.</p>
32,220,316
18
1
null
2015-08-24 04:10:01.23 UTC
35
2022-03-01 20:33:39.47 UTC
2020-10-20 09:30:26.323 UTC
null
2,637,261
null
5,023,461
null
1
249
reactjs|checkbox
502,086
<p>If the checkbox is created only with <code>React.createElement</code> then the property <code>defaultChecked</code> is used.</p> <pre><code>React.createElement('input',{type: 'checkbox', defaultChecked: false}); </code></pre> <p>Credit to @nash_ag</p>
6,006,689
Where can I download precompiled GTK+ 3 binaries or windows installer?
<p>I have taken a look at GTK+3 and I like it. But unfortunately compiling from source has never worked for me. Is there any okace with decent binaries or even better, a windows installer?</p>
6,008,390
5
0
null
2011-05-15 05:32:49.017 UTC
15
2021-03-22 14:56:56.687 UTC
2011-05-27 08:41:18.22 UTC
null
518,853
null
753,341
null
1
28
windows|gtk|gtk3
32,330
<p><strong>2020-03-19 update:</strong></p> <p>GTK+ dropped the + and their website has been rewritten. So the install instructions for GTK on Windows are now at <a href="https://www.gtk.org/docs/installations/windows/" rel="nofollow noreferrer">https://www.gtk.org/docs/installations/windows/</a></p> <p><strong>2017-04-07 update:</strong></p> <p>To make it clear, since 2017-06-23, the GTK+ project doesn't provide binary bundles for Windows. These are now provided by the MSYS2 project, with the blessing of the GTK+ team.</p> <p>MSYS2 provides the most up-to-date versions of GTK+ for Windows, as well as a complete toolchain, and other useful GTK-related development tools like:</p> <ul> <li><strong>Glade</strong>, the GUI designer</li> <li><strong>Devhelp</strong>, the offline documentation browser</li> </ul> <p>The official GTK+ website contains <a href="https://www.gtk.org/download/windows.php" rel="nofollow noreferrer">GTK+ installation instructions for Windows</a>.</p> <p><strong>2013-10-27 update:</strong></p> <p>There's now an officially supported version of GTK 3 for Windows (GTK 3.6.4 as of today). You'll find it on the <a href="http://www.gtk.org" rel="nofollow noreferrer">official GTK+ website</a>, in the <em>Downloads</em> section. Thanks to the GTK team, and to tarnyko for his work in this regard.</p> <p><strong>2013-02-01 update:</strong></p> <p>There's a French dude (tarnyko) providing an <a href="http://www.tarnyko.net/en/?q=node/20" rel="nofollow noreferrer">(unofficial) GTK 3 installer for Windows</a>, based on the OpenSUSE binaries, and another guy providing <a href="https://mail.gnome.org/archives/gtk-list/2012-December/msg00046.html" rel="nofollow noreferrer">another (unofficial, again) build</a>. Might help. The <a href="http://mail.gnome.org/archives/gtk-list" rel="nofollow noreferrer">gtk-list</a> mailing list is the best place to check how this evolves through time.</p> <p><strong>2011-05-15 original content:</strong></p> <p>There is currently no installer for GTK3 on Windows. However, the OpenSUSE Build System provides the <a href="http://download.opensuse.org/repositories/windows:/mingw:/win32/openSUSE_Factory/noarch/" rel="nofollow noreferrer">Windows binaries for GTK3</a>. On a <a href="http://mail.gnome.org/archives/gtk-list/2011-March/msg00057.html" rel="nofollow noreferrer">GTK3 on Windows</a> thread of the GTK devel mailing list, Maarten Bosmans provided the <a href="http://www.bosmans.ch/pulseaudio/download-mingw-rpm.py" rel="nofollow noreferrer">download-mingw-rpm.py</a> python script, which automates the download of a package and its dependencies, and then uses 7-zip to unzip the content of the packages. See the post he explains <a href="http://lists.opensuse.org/opensuse-mingw/2011-03/msg00020.html" rel="nofollow noreferrer">how to use download-mingw-rpm.py</a>.</p>
5,684,157
How to detect if NSString is null?
<p>I have a piece of code that detects if a <code>NSString</code> is <code>NULL</code>, <code>nil</code>, etc. However, it crashes. Here is my code:</p> <pre><code>NSArray *resultstwo = [database executeQuery:@"SELECT * FROM processes WHERE ready='yes' LIMIT 0,1"]; for (NSDictionary *rowtwo in resultstwo) { NSString *getCaption = [rowtwo valueForKey:@"caption"]; if (getCaption == NULL) { theCaption = @"Photo uploaded..."; } else if (getCaption == nil) { theCaption = @"Photo uploaded..."; } else if ([getCaption isEqualToString:@""]) { theCaption = @"Photo uploaded..."; } else if ([getCaption isEqualToString:@" "]) { theCaption = @"Photo uploaded..."; } } </code></pre> <p>And here's the error:</p> <blockquote> <p>Terminating app due to uncaught exception '<code>NSInvalidArgumentException</code>', reason: '<code>-[NSNull isEqualToString:]</code>: unrecognized selector sent to instance <code>0x3eba63d4</code>'</p> </blockquote> <p>Am I doing something wrong? Do I need to do it a different way?</p>
5,684,166
5
9
null
2011-04-16 02:42:39.437 UTC
41
2017-08-09 14:10:26.693 UTC
2013-06-06 00:03:49.437 UTC
null
227,536
null
613,860
null
1
56
objective-c|null|nsnull
85,666
<p>The <code>NULL</code> value for <strong>Objective-C objects</strong> (type <code>id</code>) is <code>nil</code>.</p> <p>While <code>NULL</code> is used for <strong>C pointers</strong> (type <code>void *</code>).</p> <p>(In the end both end up holding the same value (<code>0x0</code>). They differ in type however.)</p> <p>In <strong>Objective-C</strong>:</p> <ul> <li><code>nil</code> <em>(all lower-case)</em> is a null pointer to an <strong>Objective-C object</strong>.</li> <li><code>Nil</code> <em>(capitalized)</em> is a null pointer to an <strong>Objective-C class</strong>. </li> <li><code>NULL</code> <em>(all caps)</em> is a null pointer to anything else <em>(<strong>C pointers</strong>, that is)</em>.</li> <li><code>[NSNull null]</code> is a <strong>singleton</strong> for situations where <strong>use of nil is not possible</strong> (adding/receiving nil to/from <code>NSArray</code>s e.g.)</li> </ul> <p>In <strong>Objective-C++</strong>:</p> <ul> <li><strong>All of the above</strong>, plus:</li> <li><code>null</code> <em>(lowercase)</em> or <code>nullptr</code> (<strong>C++11</strong> or later) is a null pointer to <strong>C++ objects</strong>.</li> </ul> <hr> <p>So to check against <code>nil</code> you should either compare against <code>nil</code> (or <code>NULL</code> respectively) <strong>explicitly</strong>:</p> <pre><code>if (getCaption == nil) ... </code></pre> <p>or let <strong>ObjC</strong> / <strong>C</strong> do it <strong>implicitly</strong> for you:</p> <pre><code>if (!getCaption) ... </code></pre> <p>This works as every expression in <strong>C</strong> (and with <strong>Objective-C</strong> being a superset thereof) has an implicit boolean value:</p> <pre><code>expression != 0x0 =&gt; true expression == 0x0 =&gt; false </code></pre> <hr> <p>Now when checking for <code>NSNull</code> this obviously wouldn't work as <code>[NSNull null]</code> returns a pointer to a singleton instance of <code>NSNull</code>, and not <code>nil</code>, and therefore it is not equal to <code>0x0</code>.</p> <p>So to check against <code>NSNull</code> one can either use:</p> <pre><code>if ((NSNull *)getCaption == [NSNull null]) ... </code></pre> <p>or (preferred, see comments):</p> <pre><code>if ([getCaption isKindOfClass:[NSNull class]]) ... </code></pre> <hr> <p>Keep in mind that the latter (utilising a message call) will return <code>false</code> if <code>getCaption</code> happens to be <code>nil</code>, which, while formally correct, might not be what you expect/want.</p> <p>Hence if one (for whatever reason) needed to <strong>check against both</strong> <code>nil</code>/<code>NULL</code> <strong>and</strong> <code>NSNull</code>, one would have to combine those two checks:</p> <pre><code>if (!getCaption || [getCaption isKindOfClass:[NSNull class]]) ... </code></pre> <hr> <p>For help on forming <strong>equivalent positive checks</strong> see <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="noreferrer">De Morgan's laws</a> and <a href="http://en.wikipedia.org/wiki/Negation" rel="noreferrer">boolean negation</a>.</p> <p><strong>Edit:</strong> <a href="http://nshipster.com/nil/" rel="noreferrer">NSHipster.com</a> just published a great article on the subtle differences between nil, null, etc.</p>
6,014,544
Which is more "semantic HTML" for error messages?
<p>We were discussing with a co-worker and trying to decide on what HTML element to use for a form validation error message. </p> <p>One of us is saying that we should use a span or a div because it is a part of an input field, and the other is saying that it should be a p element because it is a text.</p> <p>What do you guys think?</p>
6,014,665
6
0
null
2011-05-16 07:57:01.233 UTC
4
2020-07-29 23:34:48.32 UTC
2011-05-16 07:59:06.407 UTC
null
79,061
null
755,311
null
1
29
html|semantic-markup
13,959
<p>I believe you should use a <code>&lt;label&gt;</code> which directly associates the error message with the input element.</p> <p>quoting the <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.9.1" rel="noreferrer">W3 <sup>specs</sup></a></p> <blockquote> <p>The LABEL element may be used to attach information to controls. </p> </blockquote> <p>and</p> <blockquote> <p>More than one LABEL may be associated with the same control by creating multiple references via the for attribute.</p> </blockquote> <hr> <p>See also <a href="https://stackoverflow.com/questions/4707936/error-message-span-vs-label">Error Message: &lt;span&gt; vs &lt;label&gt;</a></p>
5,608,685
Using RequireJS, how do I pass in global objects or singletons around?
<p>Let's say I am writing code at the main page level and 2 dependencies require the same instance of an object and also state that as a dependency. What is the appropriate way to go about this?</p> <p>Basically what I want to do is say, "If this dependency isn't loaded... then load it. Otherwise, use the same instance that was already loaded and just pass that one."</p>
5,608,744
6
0
null
2011-04-09 23:41:01.47 UTC
31
2016-02-03 21:00:33.227 UTC
2011-04-09 23:53:11.12 UTC
null
331,439
null
331,439
null
1
54
javascript|singleton|requirejs
32,306
<p>You would make that a module-level variable. For example,</p> <pre><code>// In foo.js define(function () { var theFoo = {}; return { getTheFoo: function () { return theFoo; } }; }); // In bar.js define(["./foo"], function (foo) { var theFoo = foo.getTheFoo(); // save in convenience variable return { setBarOnFoo: function () { theFoo.bar = "hello"; } }; } // In baz.js define(["./foo"], function (foo) { // Or use directly. return { setBazOnFoo: function () { foo.getTheFoo().baz = "goodbye"; } }; } // In any other file define(["./foo", "./bar", "./baz"], function (foo, bar, baz) { bar.setBarOnFoo(); baz.setBazOnFoo(); assert(foo.getTheFoo().bar === "hello"); assert(foo.getTheFoo().baz === "goodbye"); }; </code></pre>
5,914,020
javascript date to string
<p>Here is what I need to do. </p> <p>Get Date, convert to string and pass it over to a third party utility. The response from the library will have date in string format as I passed it. So, I need to convert the date to string like 20110506105524 (YYYYMMDDHHMMSS)</p> <pre><code>function printDate() { var temp = new Date(); var dateStr = temp.getFullYear().toString() + temp.getMonth().toString() + temp.getDate().toString() + temp.getHours().toString() + temp.getMinutes().toString() + temp.getSeconds().toString(); debug (dateStr ); } </code></pre> <p>The problem with above is that for months 1-9, it prints one digit. How can I change it to print exactly 2 digits for month, date ...</p>
5,914,086
6
2
null
2011-05-06 16:04:59.907 UTC
11
2017-10-31 02:32:49.07 UTC
null
null
null
null
322,933
null
1
59
javascript|string|date
111,273
<p>You will need to pad with "0" if its a single digit &amp; note <code>getMonth</code> returns 0..11 not 1..12</p> <pre><code>function printDate() { var temp = new Date(); var dateStr = padStr(temp.getFullYear()) + padStr(1 + temp.getMonth()) + padStr(temp.getDate()) + padStr(temp.getHours()) + padStr(temp.getMinutes()) + padStr(temp.getSeconds()); debug (dateStr ); } function padStr(i) { return (i &lt; 10) ? "0" + i : "" + i; } </code></pre>
5,695,623
Remove characters from a String in Java
<p>I am trying to remove the <code>.xml</code> part of a file name with the following code:</p> <pre><code>String id = fileR.getName(); id.replace(".xml", ""); idList.add(id); </code></pre> <p>The problem is that it is not removing it and I have no clue why it won't remove the target text. </p> <p><em><strong>EDIT</em></strong>: Actually I realize that the replace function won't find the <code>.xml</code>, so I guess the question is, how do I get rid of those last 4 characters? </p> <p>Here is the string that is being passed in:</p> <p><code>0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e.xml</code></p> <p>Thanks, </p>
5,695,638
8
1
null
2011-04-17 18:47:42.263 UTC
6
2020-01-25 00:56:09.73 UTC
2011-04-17 19:22:53.113 UTC
null
45,935
anon
null
null
1
29
java|string
134,930
<p>Strings in java are immutable. That means you need to create a new string or overwrite your old string to achieve the desired affect:</p> <pre><code>id = id.replace(".xml", ""); </code></pre>
6,054,832
Getting MYSQL Error: "Error Code: 2006 - MySQL server has gone away"
<p>I am getting following error, when I try to import MYSQL database:</p> <pre><code>Error Code: 2013 - Lost connection to MySQL server during queryQuery: Error Code: 2006 - MySQL server has gone away </code></pre> <p>Can someone let me know what is wrong?</p>
6,054,848
14
3
null
2011-05-19 06:46:23.06 UTC
7
2021-12-15 10:13:24.29 UTC
2011-06-29 17:01:48.493 UTC
null
135,152
null
480,346
null
1
27
mysql|sql|mysql-error-2006|mysql-error-2013
88,475
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/gone-away.html" rel="noreferrer">Here</a> you can read more about this error and various ways to avoid/solve it</p> <p>From the docs: </p> <blockquote> <p>The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection</p> </blockquote>
46,480,221
Flutter floating action button with speed dial
<p>Is there any ready made widget or where to get started <a href="https://material.io/guidelines/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions" rel="noreferrer">floating action button with speed dial actions</a> in <a href="https://flutter.io" rel="noreferrer">Flutter</a>.</p>
46,480,722
2
1
null
2017-09-29 00:47:50.147 UTC
19
2020-01-12 23:24:21.623 UTC
2019-02-06 05:39:24.533 UTC
null
6,618,622
null
824,275
null
1
36
dart|floating-action-button|flutter
34,993
<p>Here's a sketch of how to implement a <strong>Speed dial</strong> using <code>FloatingActionButton</code>.</p> <p><a href="https://i.stack.imgur.com/uF0CO.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/uF0CO.gif" alt="video"></a></p> <pre><code>import 'package:flutter/material.dart'; import 'dart:math' as math; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override State createState() =&gt; new MyHomePageState(); } class MyHomePageState extends State&lt;MyHomePage&gt; with TickerProviderStateMixin { AnimationController _controller; static const List&lt;IconData&gt; icons = const [ Icons.sms, Icons.mail, Icons.phone ]; @override void initState() { _controller = new AnimationController( vsync: this, duration: const Duration(milliseconds: 500), ); } Widget build(BuildContext context) { Color backgroundColor = Theme.of(context).cardColor; Color foregroundColor = Theme.of(context).accentColor; return new Scaffold( appBar: new AppBar(title: new Text('Speed Dial Example')), floatingActionButton: new Column( mainAxisSize: MainAxisSize.min, children: new List.generate(icons.length, (int index) { Widget child = new Container( height: 70.0, width: 56.0, alignment: FractionalOffset.topCenter, child: new ScaleTransition( scale: new CurvedAnimation( parent: _controller, curve: new Interval( 0.0, 1.0 - index / icons.length / 2.0, curve: Curves.easeOut ), ), child: new FloatingActionButton( heroTag: null, backgroundColor: backgroundColor, mini: true, child: new Icon(icons[index], color: foregroundColor), onPressed: () {}, ), ), ); return child; }).toList()..add( new FloatingActionButton( heroTag: null, child: new AnimatedBuilder( animation: _controller, builder: (BuildContext context, Widget child) { return new Transform( transform: new Matrix4.rotationZ(_controller.value * 0.5 * math.pi), alignment: FractionalOffset.center, child: new Icon(_controller.isDismissed ? Icons.share : Icons.close), ); }, ), onPressed: () { if (_controller.isDismissed) { _controller.forward(); } else { _controller.reverse(); } }, ), ), ), ); } } </code></pre>
39,390,838
How to get order items ids to get some product meta data?
<p>I'm trying to extract item meta value from Woocommerce's orders by using:</p> <pre><code>$data = wc_get_order_item_meta( $item, '_tmcartepo_data', true ); </code></pre> <p>However, I can't find a way to get order_item_id as the first parameter (using get_items)</p> <pre><code>global $woocommerce, $post, $wpdb; $order = new WC_Order($post-&gt;ID); $items = $order-&gt;get_items(); foreach ( $items as $item ) { $item_id = $item['order_item_id']; //??? $data = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true ); $a = $data[0]['value']; $b = $data[1]['value']; echo $a; echo $b; } </code></pre> <p>And I mean this order item_id (1 and 2)</p> <p><a href="http://i.stack.imgur.com/8OJ7U.jpg" rel="noreferrer">Order_item_id in database - Image</a></p> <p>How can I don that?</p> <p>Thanks.</p>
39,394,661
6
1
null
2016-09-08 12:23:29.267 UTC
5
2018-02-25 15:16:11.82 UTC
2016-09-09 11:39:30.787 UTC
null
3,730,754
null
6,443,928
null
1
19
php|wordpress|woocommerce|product|orders
69,995
<blockquote> <p><strong>2018 Update:</strong> </p> <ul> <li>Clarifying the answer with 2 possible cases</li> <li>Added compatibility for woocommerce 3+</li> </ul> </blockquote> <p><strong>So There can be 2 cases:</strong></p> <p><strong>1) Get product meta data</strong> (not set in order item meta data):</p> <p>You will need to get the product ID in the foreach loop for a <code>WC_Order</code> and to get some metadata for this product you wil use <strong><code>get_post_meta()</code></strong> function <em>( but NOT <strong><code>wc_get_order_item_meta()</code></strong> )</em>.</p> <p>So here is your code:</p> <pre><code>global $post; $order = wc_get_order( $post-&gt;ID ); $items = $order-&gt;get_items(); foreach ( $order-&gt;get_items() =&gt; $item ) { // Compatibility for woocommerce 3+ $product_id = version_compare( WC_VERSION, '3.0', '&lt;' ) ? $item['product_id'] : $item-&gt;get_product_id(); // Here you get your data $custom_field = get_post_meta( $product_id, '_tmcartepo_data', true); // To test data output (uncomment the line below) // print_r($custom_field); // If it is an array of values if( is_array( $custom_field ) ){ echo implode( '&lt;br&gt;', $custom_field ); // one value displayed by line } // just one value (a string) else { echo $custom_field; } } </code></pre> <hr> <p><strong>2) Get order item meta data</strong> (custom field value):</p> <pre><code>global $post; $order = wc_get_order( $post-&gt;ID ); $items = $order-&gt;get_items(); foreach ( $order-&gt;get_items() as $item_id =&gt; $item ) { // Here you get your data $custom_field = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true ); // To test data output (uncomment the line below) // print_r($custom_field); // If it is an array of values if( is_array( $custom_field ) ){ echo implode( '&lt;br&gt;', $custom_field ); // one value displayed by line } // just one value (a string) else { echo $custom_field; } } </code></pre> <hr> <p>If the custom field data is an array, you can access the data in a foreach loop:</p> <pre><code>// Iterating in an array of keys/values foreach( $custom_field as $key =&gt; $value ){ echo '&lt;p&gt;key: '.$key.' | value: '.$value.'&lt;/p&gt;'; } </code></pre> <p><strong>All code is tested and works.</strong></p> <p>Reference related to data in orders:</p> <ul> <li><a href="https://stackoverflow.com/questions/39401393/how-to-get-woocommerce-order-details/39409201#39409201">How to get WooCommerce order details</a> <em>(also for woocommerce 3)</em></li> <li><a href="https://stackoverflow.com/questions/45706007/get-order-items-and-wc-order-item-product-in-woocommerce-3/45706318#45706318">Get Order items and WC_Order_Item_Product in Woocommerce 3</a></li> </ul>
38,971,994
Detect if the application in background or foreground in swift
<p>is there any way to know the state of my application if it is in background mode or in foreground . Thanks </p>
38,972,081
6
1
null
2016-08-16 10:03:58.943 UTC
14
2021-12-13 20:57:14.19 UTC
2017-03-08 08:26:07.557 UTC
null
2,783,370
null
4,047,835
null
1
67
ios|iphone|swift|swift3|lifecycle
77,038
<p><code>[UIApplication sharedApplication].applicationState</code> will return current state of applications such as:</p> <ul> <li>UIApplicationStateActive </li> <li>UIApplicationStateInactive</li> <li>UIApplicationStateBackground</li> </ul> <p>or if you want to access via notification see <a href="https://stackoverflow.com/questions/3639859/handling-applicationdidbecomeactive-how-can-a-view-controller-respond-to-the">UIApplicationDidBecomeActiveNotification</a></p> <p><strong>Swift 3+</strong></p> <pre><code>let state = UIApplication.shared.applicationState if state == .background || state == .inactive { // background } else if state == .active { // foreground } switch UIApplication.shared.applicationState { case .background, .inactive: // background case .active: // foreground default: break } </code></pre> <p><strong>Objective C</strong></p> <pre><code>UIApplicationState state = [[UIApplication sharedApplication] applicationState]; if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) { // background } else if (state == UIApplicationStateActive) { // foreground } </code></pre>
44,245,790
Join a list of object's properties into a String
<p>I'm learning lambda right now, and I wonder how can I write this code by a single line with lambda.</p> <p>I have a <code>Person</code> class which includes an <code>ID</code> and <code>name</code> fields</p> <p>Currently, I have a <code>List&lt;Person&gt;</code> which stores these <code>Person</code> objects. What I want to accomplish is to get a string consisting of person's id just like.</p> <p><strong>"id1,id2,id3"</strong>. </p> <p>How can I accomplish this with lambda?</p>
44,245,853
4
0
null
2017-05-29 15:16:10.677 UTC
5
2017-05-29 23:08:14.26 UTC
2017-05-29 15:49:45.123 UTC
null
5,862,071
null
3,803,891
null
1
35
java|lambda|java-8|java-stream
21,430
<p>To retrieve a <code>String</code> consisting of all the ID's separated by the delimiter <code>","</code> you first have to <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-" rel="noreferrer"><code>map</code></a> the <code>Person</code> ID's into a new stream which you can then apply <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining-java.lang.CharSequence-" rel="noreferrer"><code>Collectors.joining</code></a> on.</p> <pre><code>String result = personList.stream().map(Person::getId) .collect(Collectors.joining(",")); </code></pre> <p>if your ID field is not a <code>String</code> but rather an <code>int</code> or some other primitive numeric type then you should use the solution below:</p> <pre><code>String result = personList.stream().map(p -&gt; String.valueOf(p.getId())) .collect(Collectors.joining(",")); </code></pre>
10,183,980
How to select table rows/complete table?
<p>The setup: I have an excel doc with a form for entering data, the data for that form is entered in a table to allow for easy entering of multiple rows of data. At least i thought so. </p> <p>So right now i am trying to select the table to insert its data in the appropriate places. My question, i think, is this: do i select one table row at a time, or the whole table and deal with each row separately. And how do i do that?</p> <p>I tried <code>Sheets("Form").Range("dataForm[#ALL]").Select</code> and several variations thereof and none worked.</p> <p>If i select the table as a whole i need to be able to deal with each row seperately and if i select each row individually i need to be able to be able to start at the top of the table as the data must be in order.</p> <p>Any ideas?</p> <p>EDit: To add detail. I have a form as stated above and its data must be inserted in different tables dependent on the value of certain cells in the form. For ease of discussion we will name that cell type, it has three possible values, as defined in a dropdown. Those values are income, expense and transfer. Based on those values we decide which table to add the data to. Income to the income table expense to the expense, etc.</p> <p>So what i am trying to do is select as many rows as there are and insert each one into the correct table. The sorting is slightly more complicated than i have explained but if i can figure out the initial sort then it should be simple to sort it a few more times.</p>
10,184,127
2
2
null
2012-04-17 01:39:49.053 UTC
1
2012-08-12 03:04:14.097 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
1,017,545
null
1
2
excel|excel-2010|vba
43,870
<p>This should help answer your questions.</p> <pre><code>Sub TableStuff() Dim lo As Excel.ListObject Dim loRow As Excel.ListRow Dim i As Long Set lo = ActiveSheet.ListObjects(1) With lo 'this is the address of the whole table Debug.Print .Range.Address For i = 1 To 10 Set loRow = .ListRows.Add(i) loRow.Range.Cells(1).Value = "test" &amp; i Next i Debug.Print .Range.Address 'address of data rows Debug.Print .DataBodyRange.Address End With End Sub </code></pre> <p>I have two posts on my blog about tables. A <a href="http://yoursumbuddy.com/copy-table-data-while-not-breaking-references/" rel="nofollow">recent one</a> might also provide some insights.</p> <p>EDIT: Based on comments below and edit to OP:</p> <p>This assumes two tables on Activesheet, tblSource and tblIncome. It filters the source table to Income, copies copies the visible rows and inserts them at the end of tblIncome. Finally, it deletes the source rows (all but one).</p> <p>You'll want to add a loop to have it work for the other two categories:</p> <pre><code>Sub MoveTableStuff() Dim loSource As Excel.ListObject Dim loTarget As Excel.ListObject Dim SourceDataRowsCount As Long Dim TargetDataRowsCount As Long Set loSource = ActiveSheet.ListObjects("tblSource") Set loTarget = ActiveSheet.ListObjects("tblIncome") With loSource .Range.AutoFilter Field:=1, Criteria1:="income" SourceDataRowsCount = .ListColumns(1).DataBodyRange.SpecialCells(xlCellTypeVisible).Count End With With loTarget TargetDataRowsCount = .DataBodyRange.Rows.Count .Resize .Range.Resize(.Range.Rows.Count + SourceDataRowsCount, .Range.Columns.Count) loSource.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy .DataBodyRange.Cells(TargetDataRowsCount + 1, 1).PasteSpecial (xlPasteValues) Application.CutCopyMode = False End With With loSource .Range.AutoFilter .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete End With End Sub </code></pre>
51,539,586
How do I use the `If` `then` `else` condition in json schema?
<p>A relatively new addition to JSON Schema (draft-07) adds the if, then and else keywords. I cannot work out how to use these new key words correctly. Here is my JSON Schema so far:</p> <pre><code>{ "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "string" } }, "if": { "properties": { "foo": { "enum": [ "bar" ] } } }, "then": { "required": [ "bar" ] } } </code></pre> <p>If the "foo" property equals "bar", Then the "bar" property is required. This works as expected.</p> <p>However, if the "foo" property does not exist or input is empty then I don't want anything. how to acheive this?</p> <pre><code>empty input {}. </code></pre> <p>Found Errors:<br> Required properties are missing from object: bar. Schema path: #/then/required</p> <p>I use online validation tool:</p> <p><a href="https://www.jsonschemavalidator.net/" rel="noreferrer">https://www.jsonschemavalidator.net/</a></p>
51,539,952
3
2
null
2018-07-26 13:05:44.69 UTC
4
2022-08-06 07:14:41.643 UTC
2018-07-26 13:31:17.2 UTC
null
89,211
null
8,694,566
null
1
21
jsonschema
45,330
<p>The <code>if</code> keyword means that, if the result of the value schema passes validation, apply the <code>then</code> schema, otherwise apply the <code>else</code> schema.</p> <p>Your schema didn't work because you needed to require <code>"foo"</code> in your <code>if</code> schema, otherwise an empty JSON instance would pass validation of the <code>if</code> schema, and therefore apply the <code>then</code> schema, which requires <code>"bar"</code>.</p> <p>Second, you want <code>"propertyNames":false</code>, which prevents having any keys in the schema, unlike if you were to set <code>"else": false</code> which would make anything always fail validation.</p> <pre><code>{ "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "string" } }, "if": { "properties": { "foo": { "enum": [ "bar" ] } }, "required": [ "foo" ] }, "then": { "required": [ "bar" ] }, "else": false } </code></pre>