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,628,290 | Pairs from single list | <p>Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:</p>
<pre><code>pairs = zip(t[::2], t[1::2])
</code></pre>
<p>I thought that was pythonic enough, but after a recent discussion involving <a href="https://stackoverflow.com/questions/4619367/avoid-object-aliasing-in-python/4619575#4619575">idioms versus efficiency</a>, I decided to do some tests:</p>
<pre><code>import time
from itertools import islice, izip
def pairs_1(t):
return zip(t[::2], t[1::2])
def pairs_2(t):
return izip(t[::2], t[1::2])
def pairs_3(t):
return izip(islice(t,None,None,2), islice(t,1,None,2))
A = range(10000)
B = xrange(len(A))
def pairs_4(t):
# ignore value of t!
t = B
return izip(islice(t,None,None,2), islice(t,1,None,2))
for f in pairs_1, pairs_2, pairs_3, pairs_4:
# time the pairing
s = time.time()
for i in range(1000):
p = f(A)
t1 = time.time() - s
# time using the pairs
s = time.time()
for i in range(1000):
p = f(A)
for a, b in p:
pass
t2 = time.time() - s
print t1, t2, t2-t1
</code></pre>
<p>These were the results on my computer:</p>
<pre><code>1.48668909073 2.63187503815 1.14518594742
0.105381965637 1.35109519958 1.24571323395
0.00257992744446 1.46182489395 1.45924496651
0.00251388549805 1.70076990128 1.69825601578
</code></pre>
<p>If I'm interpreting them correctly, that should mean that the implementation of lists, list indexing, and list slicing in Python is very efficient. It's a result both comforting and unexpected.</p>
<p><strong>Is there another, "better" way of traversing a list in pairs?</strong></p>
<p>Note that if the list has an odd number of elements then the last one will not be in any of the pairs. </p>
<p><strong>Which would be the right way to ensure that all elements are included?</strong></p>
<p>I added these two suggestions from the answers to the tests:</p>
<pre><code>def pairwise(t):
it = iter(t)
return izip(it, it)
def chunkwise(t, size=2):
it = iter(t)
return izip(*[it]*size)
</code></pre>
<p>These are the results: </p>
<pre><code>0.00159502029419 1.25745987892 1.25586485863
0.00222492218018 1.23795199394 1.23572707176
</code></pre>
<h2>Results so far</h2>
<p>Most pythonic and very efficient:</p>
<pre><code>pairs = izip(t[::2], t[1::2])
</code></pre>
<p>Most efficient and very pythonic:</p>
<pre><code>pairs = izip(*[iter(t)]*2)
</code></pre>
<p>It took me a moment to grok that the first answer uses two iterators while the second uses a single one.</p>
<p>To deal with sequences with an odd number of elements, the suggestion has been to augment the original sequence adding one element (<code>None</code>) that gets paired with the previous last element, something that can be achieved with <code>itertools.izip_longest()</code>.</p>
<h2>Finally</h2>
<p>Note that, in Python 3.x, <code>zip()</code> behaves as <code>itertools.izip()</code>, and <code>itertools.izip()</code> is gone.</p> | 4,628,446 | 10 | 12 | null | 2011-01-07 17:20:04.5 UTC | 24 | 2022-02-16 17:25:20.9 UTC | 2017-05-23 12:10:02.173 UTC | null | -1 | null | 545,637 | null | 1 | 117 | python|list|zip|slice|idioms | 78,043 | <p>My favorite way to do it:</p>
<pre><code>def pairwise(t):
it = iter(t)
return zip(it,it)
# for "pairs" of any length
def chunkwise(t, size=2):
it = iter(t)
return zip(*[it]*size)
</code></pre>
<p>When you want to pair all elements you obviously might need a fillvalue:</p>
<pre><code>from itertools import izip_longest
def blockwise(t, size=2, fillvalue=None):
it = iter(t)
return izip_longest(*[it]*size, fillvalue=fillvalue)
</code></pre>
<p>With Python 3, <code>itertools.izip</code> is now simply <code>zip</code> .. to work with an older Python, use</p>
<pre class="lang-py prettyprint-override"><code>from itertools import izip as zip
</code></pre> |
4,725,241 | What's the difference between Event Listeners & Handlers in Java? | <p>In general terms of java, there are listeners & handlers for events.<br>
I mean I use them unknowingly, just whichever is available in the API. </p>
<p>My question is, in what case do we use listeners and in what case do we use handlers for events?</p>
<p>What's the difference between them? Characteristics??</p>
<p>I've searched for reasons and I couldn't find a proper explanation for Java. </p> | 4,725,342 | 12 | 1 | null | 2011-01-18 14:33:00.917 UTC | 28 | 2021-08-20 13:05:47.02 UTC | 2014-12-13 09:29:54.91 UTC | null | 1,031,939 | null | 580,082 | null | 1 | 87 | java|events|listener|handler | 95,036 | <p>There's no formally defined difference between listeners and handlers. Some people would probably argue that they are interchangeable. To me however, they have slightly different meaning.</p>
<p><strong>A listener</strong> is an object that subscribes for events from a source. Cf. the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="noreferrer">observer pattern</a>. Usually you can have many listeners subscribing for each type of event, and they are <em>added</em> through <code><b>add</b>XyzListener</code> methods.</p>
<p><em>Example:</em> The <a href="http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html" rel="noreferrer"><code>MouseListener</code></a> in the Java API.</p>
<p><strong>A handler</strong> is an object that is responsible for handling certain events. A typical scenario would be to provide a handler for a specific event/task as an argument to a constructor, or <em>set</em> the handler through a <code><b>set</b>XyzHandler</code> method. In other words, you usually have <em>one</em> handler for each type of event.</p>
<p><em>Example:</em> The <a href="http://docs.oracle.com/javase/7/docs/api/java/util/logging/MemoryHandler.html" rel="noreferrer"><code>MemoryHandler</code></a> in the Java API.</p> |
14,443,808 | Java reflection API: Invoking a method without parameters | <p>The method I want to invoke (I know it's public but I need to use reflection):</p>
<pre><code>public byte[] myMethod()
</code></pre>
<p>I get the <code>Method</code> object like this and <code>m</code> contains <code>myMethod()</code> (I checked with the debugger)</p>
<pre><code>Method m = Class.forName(MyClass.class.getName()).getDeclaredMethod("myMethod");
</code></pre>
<p>Finally I need to invoke m and pass the result to an object:</p>
<pre><code>byte[] myBytes = null;
m.invoke(myBytes);
</code></pre>
<p>No exception is thrown but <code>myBytes</code> stays null... I also tried the following without more success:</p>
<pre><code>m.invoke(myBytes, (Object[])null);
</code></pre>
<p>How can I get the result of the invocation to myBytes?</p> | 14,443,855 | 3 | 0 | null | 2013-01-21 17:14:16.83 UTC | 4 | 2014-11-30 17:11:34.297 UTC | null | null | null | null | 990,616 | null | 1 | 24 | java|reflection | 57,120 | <blockquote>
<p>No exception is thrown but myBytes stays null</p>
</blockquote>
<p>Correct, what you wanted there was:</p>
<pre><code>byte[] myBytes = (byte[])m.invoke(yourInstance);
</code></pre>
<p>More in <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke%28java.lang.Object,%20java.lang.Object...%29">the documentation</a>. Notes:</p>
<ul>
<li>The return value of the method is the return value of <code>invoke</code>.</li>
<li>The first argument to <code>invoke</code> is the instance on which to call the method (since you've listed an instance method, not a static method; if it were static, the first argument would be <code>null</code>). You haven't shown a variable referring to the instance anywhere, so I called it <code>yourInstance</code> in the above.</li>
</ul> |
14,710,061 | Is it valid to combine a form POST with a query string? | <p>I know that in most MVC frameworks, for example, both query string params and form params will be made available to the processing code, and usually merged into one set of params (often with POST taking precedence). However, is it a valid thing to do according to the HTTP specification? Say you were to POST to:</p>
<pre><code>http://1.2.3.4/MyApplication/Books?bookCode=1234
</code></pre>
<p>... and submit some update like a change to the book name whose book code is 1234, you'd be wanting the processing code to take both the <code>bookCode</code> query string param into account, and the POSTed form params with the updated book information. Is this valid, and is it a good idea?</p> | 14,710,450 | 2 | 0 | null | 2013-02-05 14:39:35.983 UTC | 8 | 2019-12-18 16:25:52.787 UTC | null | null | null | null | 178,757 | null | 1 | 36 | http|post|query-string | 28,638 | <blockquote>
<p>Is it valid according HTTP specifications ?</p>
</blockquote>
<p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="noreferrer">Yes</a>.</p>
<p>Here is the general <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.2" rel="noreferrer">syntax of URL as defined in those specs</a></p>
<pre><code>http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
</code></pre>
<p>There is no additional constraints on the form of the http_URL. In particular, the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9" rel="noreferrer">http method</a> (i.e. POST,GET,PUT,HEAD,...) used don't add any restriction on the http URL format.</p>
<p>When using the GET method : the server can consider that the request body is empty.</p>
<p>When using the POST method : the server must handle the request body.</p>
<blockquote>
<p>Is it a good idea ?</p>
</blockquote>
<p>It depends what you need to do. I suggest you this <a href="http://www.w3.org/2001/tag/doc/whenToUseGet.html" rel="noreferrer">link</a> explaining the ideas behind GET and POST.</p>
<p>I can think that in some situation it can be handy to always have some parameters like the user language in the <em>query</em> part of the url.</p> |
14,491,906 | Changing year in mysql date | <p>I have a bunch of dates in our database stored in the standard mysql date type. </p>
<p>How can I covert a year to 2013, regardless of original date. </p>
<p>So if a date is 2009-01-01 it would be 2013-01-01, but if it's 2012-01-04, it'd convert to 2013-01-14.</p>
<p>I figured it'd be simple and obvious, but I couldn't figure it out =/</p> | 14,492,209 | 5 | 1 | null | 2013-01-24 00:29:17.113 UTC | 2 | 2019-06-13 10:29:34.243 UTC | null | null | null | null | 193,763 | null | 1 | 39 | mysql|date | 33,399 | <p>That's simple:</p>
<p>for DATETIME:
</p>
<pre><code>UPDATE table_name
SET date_col=DATE_FORMAT(date_col,'2013-%m-%d %T');
</code></pre>
<p>for DATE:</p>
<pre><code>UPDATE table_name
SET date_col=DATE_FORMAT(date_col,'2013-%m-%d');
</code></pre> |
14,612,192 | Detecting a cross in an image with OpenCV | <p>I'm trying to detect a shape (a cross) in my input video stream with the help of <a href="http://en.wikipedia.org/wiki/OpenCV" rel="noreferrer">OpenCV</a>. Currently I'm thresholding to get a binary image of my cross which works pretty good. Unfortunately my algorithm to decide whether the extracted blob is a cross or not doesn't perform very good. As you can see in the image below, not all corners are detected under certain perspectives.</p>
<p><img src="https://i.stack.imgur.com/NHLoA.jpg" alt="Enter image description here"></p>
<p>I'm using <code>findContours()</code> and <code>approxPolyDP()</code> to get an approximation of my contour. If I'm detecting 12 corners / vertices in this approximated curve, the blob is assumed to be a cross.</p>
<p>Is there any better way to solve this problem? I thought about <a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">SIFT</a>, but the algorithm has to perform in real-time and I read that SIFT is not really suitable for real-time.</p> | 14,612,877 | 2 | 1 | null | 2013-01-30 19:33:27.413 UTC | 7 | 2013-10-26 17:32:24.917 UTC | 2013-10-26 17:32:24.917 UTC | null | 411,022 | null | 1,976,996 | null | 1 | 42 | c++|opencv|video|feature-detection | 8,699 | <p>I have a couple of suggestions that might provide some interesting results although I am not certain about either. </p>
<p>If the cross is always near the center of your image and always lies on a planar surface you could try to find a homography between the camera and the plane upon which the cross lies. This would enable you to transform a sample image of the cross (at a selection of different in plane rotations) to the coordinate system of the visualized cross. You could then generate templates which you could match to the image. You could do some simple pixel agreement tests to determine if you have a match.</p>
<p>Alternatively you could try to train a <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html?highlight=haar#haar-feature-based-cascade-classifier-for-object-detection" rel="noreferrer">Haar-based classifier</a> to recognize the cross. This type of classifier is often used in face detection and detects oriented edges in images, classifying faces by the relative positions of several oriented edges. It has good classification accuracy on faces and is extremely fast. Although I cannot vouch for its accuracy in this particular situation it might provide some good results for simple shapes such as a cross.</p> |
3,071,532 | How does instance_eval work and why does DHH hate it? | <p>At about the 19:00 mark in <a href="http://www.youtube.com/watch?v=b0iKYRKtAsA#t=19m0s" rel="noreferrer">his RailsConf presentation</a>, David Heinemeier Hansson talks about the downsides of <code>instance_eval</code>:</p>
<blockquote>
<p>For a long time I ranted and raved
against <code>instance_eval</code>, which is the
concept of not using a yielded
parameter (like <code>do |people|</code>) and
just straight <code>do something</code> and then
evaluate what's in that block within
the scope of where you came from (I
don't even know if that's a coherent
explanation)</p>
<p>For a long time I didn't like that
because it felt more complex in some
sense. If you wanted to put your own
code in there were you going to
trigger something that was already
there? Were you going to override
something? When you're yielding a
specific variable you can chain
everything off that and you can know
[you're] not messing with anybody
else's stuff</p>
</blockquote>
<p>This sounded interesting, but a) I don't know how how <code>instance_eval</code> works in the first place and b) I don't understand why it can be bad / increase complexity.</p>
<p>Can someone explain?</p> | 3,071,983 | 3 | 0 | null | 2010-06-18 16:43:49.96 UTC | 10 | 2019-02-09 05:22:10.667 UTC | null | null | null | null | 25,068 | null | 1 | 23 | ruby-on-rails|ruby | 5,546 | <p>The thing that <code>instance_eval</code> does is that it runs the block in the context of a different instance. In other words, it changes the meaning of <code>self</code> which means it changes the meaning of instance methods and instance variables.</p>
<p>This creates a cognitive disconnect: the context in which the block runs is not the context in which it appears on the screen.</p>
<p>Let me demonstrate that with a slight variation of @Matt Briggs's example. Let's say we're building an email instead of a form:</p>
<pre><code>def mail
builder = MailBuilder.new
yield builder
# executed after the block
# do stuff with builder
end
mail do |f|
f.subject @subject
f.name name
end
</code></pre>
<p>In this case, <code>@subject</code> is an instance variable of <em>your</em> object and <code>name</code> is a method of <em>your</em> class. You can use nice object-oriented decomposition and store your subject in a variable.</p>
<pre><code>def mail &block
builder = MailBuilder.new
builder.instance_eval &block
# do stuff with builder
end
mail do
subject @subject
name name # Huh?!?
end
</code></pre>
<p>In <em>this</em> case, <code>@subject</code> is an instance variable of the <em>mail builder</em> object! It might not even <em>exist</em>! (Or even worse, it <em>might</em> exist and contain some completely stupid value.) There is <em>no way</em> for you to get access to <em>your</em> object's instance variables. And how do you even <em>call</em> the <code>name</code> method of your object? Everytime you try to call it, you get the <em>mail builder's</em> method.</p>
<p>Basically, <code>instance_eval</code> makes it hard to use your own code inside the DSL code. So, it should really only be used in cases where there is very little chance that this might be needed.</p> |
2,880,713 | Time difference in seconds (as a floating point) | <pre><code>>>> from datetime import datetime
>>> t1 = datetime.now()
>>> t2 = datetime.now()
>>> delta = t2 - t1
>>> delta.seconds
7
>>> delta.microseconds
631000
</code></pre>
<p>Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to do it with datettime, that would be great. Otherwise it'll look ugly:</p>
<pre><code>t1 = datetime.now()
_t1 = time.time()
t2 = datetime.now()
diff = time.time() - _t1
</code></pre> | 2,880,735 | 3 | 0 | null | 2010-05-21 08:55:52.15 UTC | 6 | 2018-12-18 06:35:01.293 UTC | 2012-05-10 13:09:52.3 UTC | null | 44,390 | null | 304,796 | null | 1 | 30 | python|datetime|floating-point | 53,053 | <p><code>combined = delta.seconds + delta.microseconds/1E6</code></p> |
2,552,416 | How can I find the user's home dir in a cross platform manner, using C++? | <p>How can I find the user's home directory in a cross platform manner in C++? i.e. /home/user in Linux, C:\Users\user\ on Windows Vista, C:\Documents And Settings\user\ on Windows XP, and whatever it is that Macs use. (I think it's /User/user)</p>
<p>Basically, what I'm looking for is a C++ way of doing this (example in python)</p>
<pre><code>os.path.expanduser("~")
</code></pre> | 2,552,458 | 3 | 3 | null | 2010-03-31 11:23:46.203 UTC | 13 | 2022-05-07 20:44:42.507 UTC | 2018-07-19 03:13:20.607 UTC | null | 8,815,948 | null | 67,366 | null | 1 | 32 | c++|cross-platform|home-directory | 22,687 | <p>I don't think it's possible to completely hide the Windows/Unix divide with this one (unless, maybe, Boost has something).</p>
<p>The most portable way would have to be <code>getenv("HOME")</code> on Unix and concatenating the results of <code>getenv("HOMEDRIVE")</code> and <code>getenv("HOMEPATH")</code> on Windows.</p> |
2,611,980 | Return value from nested function in Javascript | <p>I have a function that is set up as follows</p>
<pre><code>function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
}
var test = mainFunction();
alert(test);
</code></pre>
<p>To my logic, that alert should return 'foo', but instead it returns undefined. What am I doing wrong?</p>
<p><strong>UPDATE</strong>: Here's my actual code (it's a function for reverse-geocoding with the Google API)</p>
<pre><code>function reverseGeocode(latitude,longitude){
var address = "";
var country = "";
var countrycode = "";
var locality = "";
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
return geocoder.getLocations(latlng, function(addresses) {
address = addresses.Placemark[0].address;
country = addresses.Placemark[0].AddressDetails.Country.CountryName;
countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
return country;
});
}
</code></pre> | 2,611,984 | 3 | 1 | null | 2010-04-10 02:15:30.003 UTC | 16 | 2015-11-03 14:29:57.723 UTC | 2010-04-10 02:24:57.52 UTC | null | 145,750 | null | 145,750 | null | 1 | 64 | javascript|function|nested|return-value|return | 124,301 | <p>you have to call a function before it can return anything.</p>
<pre><code>function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction();
}
var test = mainFunction();
alert(test);
</code></pre>
<p>Or:</p>
<pre><code>function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction;
}
var test = mainFunction();
alert( test() );
</code></pre>
<p>for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the <code>getLocations</code> method and hence its return value is not recieved inside your main function.</p>
<pre><code>function reverseGeocode(latitude,longitude){
var address = "";
var country = "";
var countrycode = "";
var locality = "";
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
address = addresses.Placemark[0].address;
country = addresses.Placemark[0].AddressDetails.Country.CountryName;
countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
});
return country
}
</code></pre> |
2,579,995 | Control the size of points in an R scatterplot? | <p>In R, the <code>plot()</code> function takes a <code>pch</code> argument that controls the appearance of the points in the plot. I'm making scatterplots with tens of thousands of points and prefer a small, but not too small dot. Basically, I find <code>pch='.'</code> to be too small, but <code>pch=19</code> to be too fat. Is there something in the middle or some way to scale the dots down somehow?</p> | 2,580,113 | 3 | 5 | null | 2010-04-05 17:54:33.243 UTC | 20 | 2019-02-26 21:58:24.753 UTC | 2019-02-26 21:58:24.753 UTC | null | 4,685,471 | null | 5,222 | null | 1 | 136 | r|plot|scatter-plot | 356,429 | <p>Try the <code>cex</code> argument:</p>
<p><code>?par</code></p>
<ul>
<li><code>cex</code><br>
A numerical value giving the
amount by which plotting text and
symbols should be magnified relative
to the default. Note that some
graphics functions such as
plot.default have an argument of this
name which multiplies this graphical
parameter, and some functions such as
points accept a vector of values
which are recycled. Other uses will
take just the first value if a vector
of length greater than one is
supplied.</li>
</ul> |
29,070,505 | How to create new core in Solr 5? | <p>Currently we are using <em>Apache Solr 4.10.3</em> OR <strong><em>H</strong>eliosearch <strong>D</strong>istribution for <strong>S</strong>olr [HDS]</em> as a search engine to index our data.</p>
<p>Now after that, I got the news about <em>Apache Solr 5.0.0</em> release in last month. I'd successfully installed <em>Apache Solr 5.0.0</em> version and now its running properly on <code>8983</code> port (means only running solr but unable to create core). In that UI, I'm unable to find the example core as well as schema or config files under it. So, I started creating new core as we create in old versions but unable to create one. Following is the error, I'm getting it:</p>
<blockquote>
<p>Error CREATEing SolrCore 'testcore1': Unable to create core [testcore1] Caused by: Could not find configName for collection testcore1 found:null</p>
</blockquote>
<p><strong>Note:</strong> I also seen <strong>Cloud</strong> tab on (ie. <a href="http://localhost:8983/solr/" rel="noreferrer">http://localhost:8983/solr/</a>) left side of Solr UI and also don't know how it works? Meaning I don't know the location of the <code>schema.xml</code>, <code>solrconfig.xml</code> files due to lack of example folder (<strong>Collection1</strong>) and how to update those files?</p>
<p>Is there any useful document or solution available to solve this error?</p> | 29,077,908 | 7 | 0 | null | 2015-03-16 06:06:24.883 UTC | 6 | 2022-03-07 07:27:18.283 UTC | 2022-03-07 07:27:18.283 UTC | null | 7,329,832 | null | 1,534,964 | null | 1 | 20 | solr|lucene | 54,741 | <p>In Solr 5, creation of cores is supported by the bin/solr script provided in the distribution. Try</p>
<pre><code>bin/solr create -help
</code></pre>
<p>for a quick introduction.</p>
<p>From the above help doc, you may find:</p>
<pre><code>bin/solr create [-c name] [-d confdir] [-n configName] [-shards #] [-replicationFactor #] [-p port]
</code></pre> |
31,913,967 | How to set ChartJS Y axis title? | <p>I am using <a href="http://www.chartjs.org" rel="noreferrer">Chartjs</a> for showing diagrams and I need to set title of y axis, but there are no information about it in documentation. </p>
<p>I need y axis to be set like on picture, or on top of y axis so someone could now what is that parameter</p>
<p><img src="https://js.devexpress.com/Content/images/doc/15_1/ChartJS/fullStackedSplineArea.png" alt=""></p>
<p>I have looked on official website but there was no information about it</p> | 31,918,380 | 7 | 1 | null | 2015-08-10 07:34:46.367 UTC | 15 | 2021-04-04 19:09:38.317 UTC | 2018-02-27 16:49:34.287 UTC | null | 771,496 | null | 1,306,105 | null | 1 | 64 | javascript|jquery|charts|chart.js | 113,190 | <p>For Chart.js 2.x refer to andyhasit's answer - <a href="https://stackoverflow.com/a/36954319/360067">https://stackoverflow.com/a/36954319/360067</a></p>
<p>For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so</p>
<pre><code>Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
// text alignment and color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = this.options.scaleFontColor;
// position
var x = this.scale.xScalePaddingLeft * 0.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
</code></pre>
<p>calling it like this</p>
<pre><code>var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
</code></pre>
<p>Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals</p>
<hr>
<p>Fiddle - <a href="http://jsfiddle.net/wyox23ga/" rel="noreferrer">http://jsfiddle.net/wyox23ga/</a></p>
<hr>
<p><a href="https://i.stack.imgur.com/7qtsB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7qtsB.png" alt="enter image description here"></a></p> |
48,631,769 | Pandas str.contains - Search for multiple values in a string and print the values in a new column | <p>I just started coding in Python and want to build a solution where you would search a string to see if it contains a given set of values.</p>
<p>I've find a similar solution in R which uses the stringr library: <a href="https://stackoverflow.com/questions/42707348/search-for-a-value-in-a-string-and-if-the-value-exists-print-it-all-by-itself-i">Search for a value in a string and if the value exists, print it all by itself in a new column</a></p>
<p>The following code seems to work but i also want to output the three values that i'm looking for and this solution will only output one value:</p>
<pre><code>#Inserting new column
df.insert(5, "New_Column", np.nan)
#Searching old column
df['New_Column'] = np.where(df['Column_with_text'].str.contains('value1|value2|value3', case=False, na=False), 'value', 'NaN')
</code></pre>
<p>------ Edit ------</p>
<p>So i realised i didn't give that good of an explanation, sorry about that.</p>
<p>Below is an example where i match fruit names in a string and depending on if it finds any matches in the string it will print out either true or false in a new column. Here's my question: Instead of printing out true or false i want to print out the name it found in the string eg. apples, oranges etc.</p>
<pre><code>import pandas as pd
import numpy as np
text = [('I want to buy some apples.', 0),
('Oranges are good for the health.', 0),
('John is eating some grapes.', 0),
('This line does not contain any fruit names.', 0),
('I bought 2 blueberries yesterday.', 0)]
labels = ['Text','Random Column']
df = pd.DataFrame.from_records(text, columns=labels)
df.insert(2, "MatchedValues", np.nan)
foods =['apples', 'oranges', 'grapes', 'blueberries']
pattern = '|'.join(foods)
df['MatchedValues'] = df['Text'].str.contains(pattern, case=False)
print(df)
</code></pre>
<p>Result</p>
<pre><code> Text Random Column MatchedValues
0 I want to buy some apples. 0 True
1 Oranges are good for the health. 0 True
2 John is eating some grapes. 0 True
3 This line does not contain any fruit names. 0 False
4 I bought 2 blueberries yesterday. 0 True
</code></pre>
<p>Wanted result</p>
<pre><code> Text Random Column MatchedValues
0 I want to buy some apples. 0 apples
1 Oranges are good for the health. 0 oranges
2 John is eating some grapes. 0 grapes
3 This line does not contain any fruit names. 0 NaN
4 I bought 2 blueberries yesterday. 0 blueberries
</code></pre> | 48,773,173 | 2 | 0 | null | 2018-02-05 21:27:19.503 UTC | 6 | 2018-02-26 20:43:12.157 UTC | 2018-02-12 20:48:48.947 UTC | user5431582 | null | user5431582 | null | null | 1 | 9 | python|string|pandas | 41,304 | <p>Here is one way:</p>
<pre><code>foods =['apples', 'oranges', 'grapes', 'blueberries']
def matcher(x):
for i in foods:
if i.lower() in x.lower():
return i
else:
return np.nan
df['Match'] = df['Text'].apply(matcher)
# Text Match
# 0 I want to buy some apples. apples
# 1 Oranges are good for the health. oranges
# 2 John is eating some grapes. grapes
# 3 This line does not contain any fruit names. NaN
# 4 I bought 2 blueberries yesterday. blueberries
</code></pre> |
42,954,454 | Can't add Team ID in Firebase Project settings | <p>I am trying to add dynamic links to my app and I am following this guide: </p>
<p><a href="https://www.youtube.com/watch?v=sFPo296OQqk" rel="noreferrer">https://www.youtube.com/watch?v=sFPo296OQqk</a></p>
<p>At around 3:20 he explains how to add team ID in the project settings but for me this option simply isn't there. I have checked all my projects and none of them has this option in project settings. This is a problem since dynamic links does not work without that added since I've seen people around with similar problem as me (that was solved by adding the Team ID they had forgot). </p>
<p>Is there any solution to this? </p>
<p>I'm working on a iOS project and my location is Sweden if that somehow matters. </p>
<p>Any help is very much appreciated. </p> | 42,970,607 | 7 | 0 | null | 2017-03-22 14:25:25.71 UTC | 4 | 2021-02-10 15:30:25.527 UTC | null | null | null | null | 6,404,863 | null | 1 | 34 | ios|swift|firebase|firebase-dynamic-links | 16,508 | <p>I resolved this by instead adding the team ID to the <strong>App ID Prefix</strong> field. </p>
<p>Seems to be working in the exact same way. </p> |
36,553,129 | What is the shortest way to modify immutable objects using spread and destructuring operators | <p>I'm looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with frameworks like <a href="https://github.com/reactjs/redux" rel="noreferrer">Redux</a> and makes working with <a href="https://facebook.github.io/immutable-js/" rel="noreferrer">immutable</a> object in javascript much easier. Especially since working with the object spread operator using <a href="https://babeljs.io/" rel="noreferrer">Babel</a> is already possible.</p>
<p>I did not found anything better than first copy the object, and than assign/delete the property I want like this:</p>
<pre><code>function updateState(state, item) {
newState = {...state};
newState[item.id] = item;
return newState;
}
function deleteProperty(state, id) {
var newState = {...state};
delete newState[id];
return newState;
}
</code></pre>
<p>I feel like it could be shorter</p> | 36,553,130 | 6 | 0 | null | 2016-04-11 15:36:53.41 UTC | 13 | 2019-03-29 19:30:22.077 UTC | 2016-05-03 15:35:16.797 UTC | null | 86,388 | null | 86,388 | null | 1 | 27 | javascript|destructuring|ecmascript-next | 17,465 | <p>Actions on state, where state is considered immutable.</p>
<p><strong>Adding or Updating the value of a property</strong>:</p>
<pre><code>// ES6:
function updateState(state, item) {
return Object.assign({}, state, {[item.id]: item});
}
// With Object Spread:
function updateState(state, item) {
return {
...state,
[item.id]: item
};
}
</code></pre>
<p><strong>Deleting a property</strong> </p>
<pre><code>// ES6:
function deleteProperty(state, id) {
var newState = Object.assign({}, state);
delete newState[id];
return newState;
}
// With Object Spread:
function deleteProperty(state, id) {
let {[id]: deleted, ...newState} = state;
return newState;
}
// Or even shorter as helper function:
function deleteProperty({[id]: deleted, ...newState}, id) {
return newState;
}
// Or inline:
function deleteProperty(state, id) {
return (({[id]: deleted, ...newState}) => newState)(state);
}
</code></pre> |
32,063,985 | Deleting a div with a particlular class using BeautifulSoup | <p>I want to delete the specific <code>div</code> from <code>soup</code> object.
<br>I am using <code>python 2.7</code> and <code>bs4</code>. </p>
<p>According to documentation we can use <code>div.decompose()</code>. </p>
<p>But that would delete all the <code>div</code>. How can I delete a <code>div</code> with specific class?</p> | 32,064,299 | 4 | 0 | null | 2015-08-18 05:10:59.253 UTC | 13 | 2018-03-28 12:37:46.387 UTC | 2015-08-18 05:21:32.133 UTC | null | 4,198,139 | null | 5,047,436 | null | 1 | 51 | python|python-2.7|beautifulsoup | 49,679 | <p>Sure, you can just <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="noreferrer"><code>select</code></a>, <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="noreferrer"><code>find</code></a>, or <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="noreferrer"><code>find_all</code></a> the <code>div</code>s of interest in the usual way, and then call <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#decompose" rel="noreferrer"><code>decompose()</code></a> on those divs.</p>
<p>For instance, if you want to remove all divs with class <code>sidebar</code>, you could do that with</p>
<pre><code># replace with `soup.findAll` if you are using BeautifulSoup3
for div in soup.find_all("div", {'class':'sidebar'}):
div.decompose()
</code></pre>
<p>If you want to remove a div with a specific <code>id</code>, say <code>main-content</code>, you can do that with</p>
<pre><code>soup.find('div', id="main-content").decompose()
</code></pre> |
40,598,942 | Swift 3 : How to get path of file saved in Documents folder | <pre><code>path = Bundle.main.path(forResource: "Owl.jpg", ofType: "jpg")
</code></pre>
<p>returns nil, however, using <code>NSHomeDirectory()</code> I'm able to verify that is under <code>Documents/</code> folder. </p> | 40,598,962 | 3 | 2 | null | 2016-11-14 22:32:02.503 UTC | 11 | 2022-02-21 12:02:17.863 UTC | null | null | null | null | 419,730 | null | 1 | 13 | ios|swift3 | 27,564 | <p>First, separate name and extension:</p>
<pre><code>Bundle.main.path(forResource: "Owl", ofType: "jpg")
</code></pre>
<p>Second, separate (mentally) your bundle and the Documents folder. They are two completely different things. If this file is the Documents folder, it absolutely is not in your main bundle! You probably want something like this:</p>
<pre><code>let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("Owl.jpg")
</code></pre>
<p>Third, if Owl is an image asset in the asset catalog, then say</p>
<pre><code>let im = UIImage(named:"Owl") // or whatever its name is
</code></pre> |
31,509,299 | Adding Trusted Location to Access Run Time | <p>I have created a Microsoft Access file.</p>
<p>How do I add this file to the trusted locations on my client's PC where there is only the runtime version of Access installed?</p> | 31,509,300 | 5 | 0 | null | 2015-07-20 05:23:39.337 UTC | 4 | 2021-12-18 14:38:18.617 UTC | 2020-09-10 19:10:32.073 UTC | null | 2,779,697 | null | 4,050,261 | null | 1 | 10 | ms-access|runtime|ms-access-2010|ms-access-2013 | 42,643 | <p>Access 2007:</p>
<pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Access\Security\Trusted Locations]
[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Access\Security\Trusted Locations\Location(n)]
</code></pre>
<p>Access 2010:</p>
<pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\Trusted Locations]
[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\Trusted Locations\Location(n)]
</code></pre>
<p>Access 2013:</p>
<pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Access\Security\Trusted Locations]
[HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Access\Security\Trusted Locations\Location(n)]
</code></pre>
<p>Access 2016 & Access 2019 & Office 365:</p>
<pre><code>[HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Access\Security\Trusted Locations]
[HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Access\Security\Trusted Locations\Location(n)]
</code></pre>
<p>Example of how it will look</p>
<pre><code>"Path"="C:\PathToDB\"
"AllowSubfolders"=dword:00000001
"Description"="The description"
"Date"="01.01.2007 12:00"
</code></pre>
<p>If editing Reg is not cup of your Tea, then use AddPath
<a href="http://www.accessribbon.de/en/?Trust_Center:Trusted_Locations" rel="noreferrer">http://www.accessribbon.de/en/?Trust_Center:Trusted_Locations</a></p> |
25,100,449 | MATLAB error: Subscript indices must either be real positive integers or logicals | <p>I'm currently running my code, and found an annoying problem that I really haven't got any idea to solve.</p>
<p>The function that I'm working out is as follows;</p>
<pre><code>function out = CointPairs(PriceMat, Symbols)
out=[];
NofStocks = size(PriceMat, 2);
CointMatrix= zeros(NofStocks);
[rows, cols] = find(CointMatrix);
CointPairs = [rows, cols];
**cf= (CointPairs(:,1)-CointPairs(:,2))==0;**
CointPairs(cf,:) = [];
if(isempty(CointPairs))
warning('No Cointegrated Pairs Found')
return
end
end
</code></pre>
<p>And the bloody problem occurs at this line:</p>
<pre><code>cf= (CointPairs(:,1)-CointPairs(:,2))==0;
</code></pre>
<p>saying that "Subscript indices must either be real positive integers or logicals."
well, the input variable "PriceMat" is the price matrix 60x10, and "Symbols" is 10x1 string.</p>
<p>One more question :)
what's exactly meant by "subscript indices"?</p>
<p>MUCH appreciated in advance xx</p> | 25,100,980 | 4 | 0 | null | 2014-08-03 00:05:35.7 UTC | null | 2017-10-22 21:39:15.047 UTC | 2014-08-07 17:30:58.98 UTC | null | 3,903,050 | null | 3,903,050 | null | 1 | 4 | matlab | 62,542 | <p>Let's tackle your questions one at a time:</p>
<blockquote>
<p>"Subscript indices must either be real positive integers or logicals." well, the input variable "PriceMat" is the price matrix 60x10, and "Symbols" is 10x1 string.</p>
</blockquote>
<p>Take a look at your <code>CointPairs</code> variable. This is the result from using the <code>find</code> command. There may be a case where <code>CointPairs</code> produces the <strong>empty</strong> matrix. This is because when you run <code>find</code>, there may be a case where there is <strong>no entry</strong> in your <code>CointMatrix</code> where it's equal to 1 (or non-zero actually). If this is the case, then <code>CointPairs</code> will actually be empty as there are no elements that meet the requirements.</p>
<p>As such, the reason why you're getting that error is because you are trying to do operations on an <strong>empty</strong> matrix when that's not allowed. You need to move your <code>if</code> statement <strong>before</strong> you do <code>CointPairs = [rows, cols];</code>. That way, you won't get any accessing errors. In other words, do this:</p>
<pre><code>[rows, cols] = find(CointMatrix);
CointPairs = [rows, cols];
%// Move here
if(isempty(CointPairs))
warning('No Cointegrated Pairs Found');
out = []; %// Make output empty - Must return something or you get an error
return
end
%// Continue here
cf= (CointPairs(:,1)-CointPairs(:,2))==0;
CointPairs(cf,:) = [];
%// More code here...
%// ...
</code></pre>
<p>One minor comment I have is that your output variable is <code>out</code>, but you are not assigning it anywhere in your code. Is this intentional?</p>
<hr>
<blockquote>
<p>One more question :) what's exactly meant by "subscript indices"?</p>
</blockquote>
<p>Subscript indices are those values you use to access elements in your array / matrix. For example, suppose your matrix is:</p>
<pre><code>A = [1 2 3; 4 5 6; 7 8 9];
</code></pre>
<p>By doing <code>A(2,2)</code>, we get the element 5. The row 2 and the column 2 is known as <strong>subscript index</strong>. Indices implies more than one, so instead of just a single pair of row and column locations, you can use two arrays of elements to access the rows and columns of your matrix. Each pair of corresponding elements in the pair is a subscript index. </p>
<p>Basically, they are numbers that you use to access the rows and columns of your matrix. You can only access elements in matrices / arrays using <strong>positive numbers</strong> (a.k.a. 1, 2, 3, 4...) or <strong>logical operators</strong> (i.e. <code>true / false</code>). The empty matrix, 0, negative integers or floating point numbers are not allowed.</p>
<p>Because you are accessing your matrix using neither of the above valid inputs, you get that error.</p>
<hr>
<p>Hope this helps!</p> |
25,437,817 | "Don't run bundler as root" - what is the exact difference made by using root? | <p>If you run ruby bundler from the command line while logged in as root, you get the following warning:</p>
<blockquote>
<p>Don't run Bundler as root. Bundler can ask for sudo if it is needed,
and installing your bundle as root will break this application for all
non-root users on this machine.</p>
</blockquote>
<p>What is this exact difference that running bundler as root makes to the gems it installs? </p>
<p>Is it to do with the permissions of the actual files that it installs for each gem? Will Ruby try to access the gem files as a non-root user (and if so, what user / group would Ruby use and how would I find out)?</p>
<p>What would be the symptoms of an application that is broken due to bundler being used as root?</p>
<hr>
<p>My specific reason for asking is because I'm trying to use bundler on a very basic Centos VPS where I have no need to set up any non-root users. I'm <a href="https://stackoverflow.com/questions/25438186/what-could-cause-one-gem-in-a-gemset-to-be-unavailable-while-all-the-others-are">having other problems with gems installed via bundler</a> (<code>Error: file to import not found or unreadable: gemname</code> despite the gem in question being present in <code>gem list</code>), and I'm wondering if installing the gems via bundler as root might have made the files unreadable to Ruby.</p>
<p>I want to work out if I do need to set up a non-root user account purely for running bundler, and if I do, what groups and privileges this user will need to allow Ruby to run the gems bundler installs.</p>
<p>Or can I just <code>chown</code> or <code>chgrp</code> the gem folders? If so, does it depend on anything to do with how Ruby is installed? (I used RVM and my gems end up in <code>/usr/local/rvm/gems/</code> which is owned by root in group rvm) <a href="https://stackoverflow.com/questions/16376995/bundler-cannot-install-any-gems-without-sudo">This loosely related question's answer implies that unspecified aspects of how Ruby is installed influence bundler's permissions requirements</a>.</p>
<p>Researching the "Don't run bundler as root" message only comes up with <a href="https://stackoverflow.com/questions/25210957/dont-run-bundler-as-root-error">an unanswered question</a> and <a href="http://www.coldplaysucks.com/blogs/news/13799949-dont-run-bundler-as-root" rel="noreferrer">complaints that this warning is apparently "like it saying to go to sleep at 8PM" (link contains NSFW language)</a>.</p> | 34,318,529 | 1 | 0 | null | 2014-08-22 00:11:09.93 UTC | 6 | 2015-12-16 17:36:21.197 UTC | 2017-05-23 11:55:13.833 UTC | null | -1 | null | 568,458 | null | 1 | 28 | ruby|gem|bundler | 40,736 | <p>So I had to dig into the git log history of bundler's repo, because GitHub <a href="https://stackoverflow.com/questions/18122628/how-to-search-for-a-commit-message-on-github">doesn't allow search</a> in git commits messages anymore.</p>
<p>The commit <code>c1b3fd165b2ec97fb254a76eaa3900bc4857a357</code> says :</p>
<blockquote>
<p>Print warning when bundler is run by root. When a user runs bundle install with sudo bundler will print a warning, letting
them know of potential consequences.</p>
<p>closes <a href="https://github.com/bundler/bundler/issues/2936" rel="noreferrer">#2936</a></p>
</blockquote>
<p>Reading this issue, you understand the real reason you should not use the <code>root</code> user:</p>
<blockquote>
<p>Running sudo bundle install can cause huge and cascading problems for
users trying to install gems on OS X into the system gems. We should
print a warning and explain that Bundler will prompt for sudo if it's
needed. We should also warn people that sudo bundle will break git
gems, because they have to be writable by the user that Bundler runs
as.</p>
</blockquote> |
43,444,752 | How to round up to whole number in R? | <p>Is it possible to round up to the nearest whole number in R? I have time-stamped data and I want to round up to the nearest whole minute, to represent activities during this minute.</p>
<p>For example, if time is presented in <code>minutes.seconds</code> format:</p>
<pre><code>x <- c(5.56, 7.39, 12.05, 13.10)
round(x, digits = 0)
[1] 6 7 12 13
</code></pre>
<p>My anticipated output would instead be:</p>
<pre><code>round(x, digits = 0)
[1] 6 8 13 14
</code></pre>
<p>I understand this is confusing but when I am calculating activity per minute data, rounding up to the nearest minute makes sense. Is this possible?</p> | 43,444,765 | 1 | 0 | null | 2017-04-17 03:34:38.023 UTC | 4 | 2021-04-21 07:03:03.613 UTC | 2017-04-17 04:56:50.563 UTC | null | 4,497,050 | null | 2,716,568 | null | 1 | 38 | r|rounding | 72,257 | <p>We can use <code>ceiling</code> to do the specified rounding</p>
<pre><code>ceiling(x)
#[1] 6 8 13 14
</code></pre> |
857,414 | Dynamically create an enum | <p>I have an enum of the following structure:</p>
<pre><code>public enum DType
{
LMS = 0,
DNP = -9,
TSP = -2,
ONM = 5,
DLS = 9,
NDS = 1
}
</code></pre>
<p>I'm using this enum to get the names and the values.
Since there is a requirement to add more types, I need to read the type and the values from an XML file. Is there any way by which I can create this enum dynamically from <strong>XML</strong> file so that I can retain the program structure.</p> | 857,421 | 2 | 0 | null | 2009-05-13 11:26:12.927 UTC | 10 | 2018-10-10 06:58:29.743 UTC | 2018-10-10 06:58:29.743 UTC | null | 6,908,525 | null | 93,974 | null | 1 | 36 | c# | 74,970 | <p>Probably, you should consider using a <code>Dictionary<string, int></code> instead.</p>
<p>If you want to generate the <code>enum</code> at <strong>compile-time</strong> dynamically, you might want to consider <a href="http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx" rel="noreferrer">T4</a>.</p> |
2,336,474 | In-place progress output in the terminal or console | <p>When you run <code>git clone</code>, it updates progress in place. For example, the percentage of the objects received changes in place.</p>
<pre><code>user@athena:~/cloj/src$ git clone git://git.boinkor.net/slime.git
Initialized empty Git repository in /home/user/cloj/src/slime/.git/
remote: Counting objects: 15936, done.
remote: Compressing objects: 100% (5500/5500), done.
Receiving objects: 28% (4547/15936), 3.16 MiB | 165 KiB/s
</code></pre>
<p>How is this acccomplished? Does it use ncurses or something even simpler, like some combination of backspace characters and regular character output?</p>
<p>I'm especially interested in how this kind of console output could be accomplished from Ruby. </p>
<p>EDIT</p>
<p>My original question is answered. But here's an addendum. When you use MPlayer, for example, it not only updates a line to show current progress, but also the <em>previous</em> line (e.g. when you press pause). </p>
<pre><code> ===== PAUSE =====
A: 79.9 (01:19.9) of 4718.0 ( 1:18:38.0) 0.3%
</code></pre>
<p>How would you update two lines of output in-place?</p> | 2,336,607 | 5 | 2 | null | 2010-02-25 18:13:17.957 UTC | 11 | 2017-02-10 12:51:43.157 UTC | 2010-02-28 19:54:56.57 UTC | null | 232,417 | null | 232,417 | null | 1 | 33 | ruby|unix|terminal|ncurses | 9,637 | <p>Use carriage return. '\r' should usually work.</p> |
2,544,454 | Get the currency format for a country that does not have a Locale constant | <p>I want to get the currency format of India, so I need a <code>Locale</code> object for India. But there exists only few a countries that have a <code>Locale</code> constant (a <code>static final Locale</code>), and India is not one of them.</p>
<p>To get the currency symbols for the US and UK, I can do the following:</p>
<pre><code>public void displayCurrencySymbols() {
Currency currency = Currency.getInstance(Locale.US);
System.out.println("United States: " + currency.getSymbol());
currency = Currency.getInstance(Locale.UK);
System.out.println("United Kingdom: " + currency.getSymbol());
}
</code></pre>
<p>That uses the constants <code>Locale.US</code> and <code>Locale.UK</code>. If i want to get the Indian currency format, what can I do?</p> | 2,544,488 | 6 | 5 | null | 2010-03-30 10:34:35.923 UTC | 7 | 2020-06-12 15:27:43.177 UTC | 2013-08-30 12:24:23.67 UTC | null | 545,127 | null | 277,516 | null | 1 | 45 | java|currency | 53,272 | <p>According to the <a href="https://docs.oracle.com/javase/1.5.0/docs/guide/intl/locale.doc.html" rel="noreferrer">JDK release notes</a>, you have locale codes <code>hi_IN</code> (Hindi) and <code>en_IN</code> (English).</p>
<pre><code>System.out.println(Currency.getInstance(new Locale("hi", "IN")).getSymbol());
</code></pre> |
2,943,548 | How to reset / remove chrome's input highlighting / focus border? | <p>I have seen that chrome puts a thicker border on <code>:focus</code> but it kind of looks off in my case where I've used border-radius also. Is there anyway to remove that? </p>
<p><img src="https://farm5.static.flickr.com/4029/4655472389_c68d1216f0_b.jpg" alt="image: chrome :focus border"></p> | 2,943,582 | 8 | 1 | null | 2010-05-31 12:37:24.313 UTC | 60 | 2020-06-10 17:51:28.763 UTC | 2017-09-08 14:44:45.377 UTC | null | 497,397 | null | 292,291 | null | 1 | 414 | css|google-chrome|focus|border | 500,880 | <p>You should be able to remove it using </p>
<pre><code>outline: none;
</code></pre>
<p>but keep in mind this is potentially bad for usability: It will be hard to tell whether an element is focused, which can suck when you walk through all a form's elements using the <kbd>Tab</kbd> key - you should reflect somehow when an element is focused.</p> |
2,431,732 | Checking if a bit is set or not | <p>How to check if a certain bit in a byte is set?</p>
<pre><code>bool IsBitSet(Byte b,byte nPos)
{
return .....;
}
</code></pre> | 2,431,759 | 9 | 2 | null | 2010-03-12 09:45:27.433 UTC | 14 | 2021-05-20 08:41:43.46 UTC | 2012-01-27 07:35:24.493 UTC | null | 41,956 | null | 150,174 | null | 1 | 70 | c#|.net|bit-manipulation | 112,860 | <p>sounds a bit like homework, but:</p>
<pre><code>bool IsBitSet(byte b, int pos)
{
return (b & (1 << pos)) != 0;
}
</code></pre>
<p>pos 0 is least significant bit, pos 7 is most.</p> |
3,094,866 | Trimming a huge (3.5 GB) csv file to read into R | <p>So I've got a data file (semicolon separated) that has a lot of detail and incomplete rows (leading Access and SQL to choke). It's county level data set broken into segments, sub-segments, and sub-sub-segments (for a total of ~200 factors) for 40 years. In short, it's huge, and it's not going to fit into memory if I try to simply read it.</p>
<p>So my question is this, given that I want all the counties, but only a single year (and just the highest level of segment... leading to about 100,000 rows in the end), what would be the best way to go about getting this rollup into R?</p>
<p>Currently I'm trying to chop out irrelevant years with Python, getting around the filesize limit by reading and operating on one line at a time, but I'd prefer an R-only solution (CRAN packages OK). Is there a similar way to read in files a piece at a time in R?</p>
<p>Any ideas would be greatly appreciated.</p>
<p><strong>Update:</strong></p>
<ul>
<li>Constraints</li>
<ul>
<li>Needs to use <em>my</em> machine, so no EC2 instances</li>
<li>As R-only as possible. Speed and resources are not concerns in this case... provided my machine doesn't explode...</li>
<li>As you can see below, the data contains mixed types, which I need to operate on later</li></ul>
<li>Data</li>
<ul>
<li>The data is 3.5GB, with about 8.5 million rows and 17 columns</li>
<li>A couple thousand rows (~2k) are malformed, with only one column instead of 17</li>
<ul><li>These are entirely unimportant and can be dropped</li></ul>
<li>I only need ~100,000 rows out of this file (See below)</li></ul>
</ul>
<p><strong>Data example:</strong></p>
<pre><code>County; State; Year; Quarter; Segment; Sub-Segment; Sub-Sub-Segment; GDP; ...
Ada County;NC;2009;4;FIRE;Financial;Banks;80.1; ...
Ada County;NC;2010;1;FIRE;Financial;Banks;82.5; ...
NC [Malformed row]
[8.5 Mill rows]
</code></pre>
<p>I want to chop out some columns and pick two out of 40 available years (2009-2010 from 1980-2020), so that the data can fit into R:</p>
<pre><code>County; State; Year; Quarter; Segment; GDP; ...
Ada County;NC;2009;4;FIRE;80.1; ...
Ada County;NC;2010;1;FIRE;82.5; ...
[~200,000 rows]
</code></pre>
<p><strong>Results:</strong></p>
<p>After tinkering with all the suggestions made, I decided that readLines, suggested by JD and Marek, would work best. I gave Marek the check because he gave a sample implementation.</p>
<p>I've reproduced a slightly adapted version of Marek's implementation for my final answer here, using strsplit and cat to keep only columns I want.</p>
<p>It should also be noted this is <em>MUCH</em> less efficient than Python... as in, Python chomps through the 3.5GB file in 5 minutes while R takes about 60... but if all you have is R then this is the ticket.</p>
<pre><code>## Open a connection separately to hold the cursor position
file.in <- file('bad_data.txt', 'rt')
file.out <- file('chopped_data.txt', 'wt')
line <- readLines(file.in, n=1)
line.split <- strsplit(line, ';')
# Stitching together only the columns we want
cat(line.split[[1]][1:5], line.split[[1]][8], sep = ';', file = file.out, fill = TRUE)
## Use a loop to read in the rest of the lines
line <- readLines(file.in, n=1)
while (length(line)) {
line.split <- strsplit(line, ';')
if (length(line.split[[1]]) > 1) {
if (line.split[[1]][3] == '2009') {
cat(line.split[[1]][1:5], line.split[[1]][8], sep = ';', file = file.out, fill = TRUE)
}
}
line<- readLines(file.in, n=1)
}
close(file.in)
close(file.out)
</code></pre>
<p><strong>Failings by Approach:</strong></p>
<ul>
<li>sqldf</li>
<ul><li>This is definitely what I'll use for this type of problem in the future if the data is well-formed. However, if it's not, then SQLite chokes.</li></ul>
<li>MapReduce</li>
<ul><li>To be honest, the docs intimidated me on this one a bit, so I didn't get around to trying it. It looked like it required the object to be in memory as well, which would defeat the point if that were the case.</li></ul>
<li>bigmemory</li>
<ul><li>This approach cleanly linked to the data, but it can only handle one type at a time. As a result, all my character vectors dropped when put into a big.table. If I need to design large data sets for the future though, I'd consider only using numbers just to keep this option alive.</li></ul>
<li>scan</li>
<ul><li>Scan seemed to have similar type issues as big memory, but with all the mechanics of readLines. In short, it just didn't fit the bill this time.</li></ul>
</ul> | 3,108,397 | 13 | 7 | null | 2010-06-22 16:00:09.23 UTC | 62 | 2017-09-26 03:39:49.857 UTC | 2014-11-13 00:43:07.4 UTC | null | 239,923 | null | 274,689 | null | 1 | 88 | r|csv | 24,796 | <p>My try with <code>readLines</code>. This piece of a code creates <code>csv</code> with selected years.</p>
<pre><code>file_in <- file("in.csv","r")
file_out <- file("out.csv","a")
x <- readLines(file_in, n=1)
writeLines(x, file_out) # copy headers
B <- 300000 # depends how large is one pack
while(length(x)) {
ind <- grep("^[^;]*;[^;]*; 20(09|10)", x)
if (length(ind)) writeLines(x[ind], file_out)
x <- readLines(file_in, n=B)
}
close(file_in)
close(file_out)
</code></pre> |
2,563,632 | How can I merge two commits into one if I already started rebase? | <p>I am trying to merge 2 commits into 1, so I followed <a href="http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html" rel="noreferrer">“squashing commits with rebase” from git ready</a>.</p>
<p>I ran</p>
<pre><code>git rebase --interactive HEAD~2
</code></pre>
<p>In the resulting editor, I change <code>pick</code> to <code>squash</code> and then save-quit, but the rebase fails with the error</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote>
<p>Now that my work tree has reached this state, I’m having trouble recovering. </p>
<p>The command <code>git rebase --interactive HEAD~2</code> fails with:</p>
<blockquote>
<p>Interactive rebase already started</p>
</blockquote>
<p>and <code>git rebase --continue</code> fails with</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote> | 2,568,581 | 14 | 5 | null | 2010-04-01 20:56:53.747 UTC | 560 | 2021-10-13 13:16:05.867 UTC | 2020-04-19 11:31:06.043 UTC | null | 806,202 | null | 286,802 | null | 1 | 1,295 | git|git-merge | 980,250 | <h3>Summary</h3>
<p>The error message</p>
<blockquote>
<p>Cannot 'squash' without a previous commit</p>
</blockquote>
<p>means you likely attempted to “squash downward.” <strong>Git always squashes a newer commit into an older commit</strong> or “upward” as viewed on the interactive rebase todo list, that is into a commit on a previous line. Changing the command on your todo list’s very first line to <code>squash</code> will always produce this error as there is nothing for the first commit to squash into.</p>
<h3>The Fix</h3>
<p>First get back to where you started with</p>
<pre><code>$ git rebase --abort
</code></pre>
<p>Say your history is</p>
<pre><code>$ git log --pretty=oneline
a931ac7c808e2471b22b5bd20f0cad046b1c5d0d c
b76d157d507e819d7511132bdb5a80dd421d854f b
df239176e1a2ffac927d8b496ea00d5488481db5 a
</code></pre>
<p>That is, a was the first commit, then b, and finally c. After committing c we decide to squash b and c together:</p>
<p><em>(Note: Running <code>git log</code> pipes its output into a pager, <a href="https://www.gnu.org/software/less/" rel="noreferrer"><code>less</code></a> by default on most platforms. To quit the pager and return to your command prompt, press the <code>q</code> key.)</em></p>
<p>Running <code>git rebase --interactive HEAD~2</code> gives you an editor with</p>
<pre><code>pick b76d157 b
pick a931ac7 c
# Rebase df23917..a931ac7 onto df23917
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
</code></pre>
<p>(Notice that this todo list is in the reverse order as compared with the output of <code>git log</code>.)</p>
<p>Changing b’s <code>pick</code> to <code>squash</code> will result in the error you saw, but if instead you squash c into b (newer commit into the older or “squashing upward”) by changing the todo list to</p>
<pre><code>pick b76d157 b
squash a931ac7 c
</code></pre>
<p>and save-quitting your editor, you'll get another editor whose contents are</p>
<pre><code># This is a combination of 2 commits.
# The first commit's message is:
b
# This is the 2nd commit message:
c
</code></pre>
<p>When you save and quit, the contents of the edited file become commit message of the new combined commit:</p>
<pre><code>$ git log --pretty=oneline
18fd73d3ce748f2a58d1b566c03dd9dafe0b6b4f b and c
df239176e1a2ffac927d8b496ea00d5488481db5 a
</code></pre>
<h3>Note About Rewriting History</h3>
<p>Interactive rebase rewrites history. Attempting to push to a remote that contains the old history will fail because it is not a fast-forward.</p>
<p>If the branch you rebased is a topic or feature branch <em>in which you are working by yourself</em>, no big deal. Pushing to another repository will require the <code>--force</code> option, or alternatively you may be able, depending on the remote repository’s permissions, to first delete the old branch and then push the rebased version. Examples of those commands that will potentially destroy work is outside the scope of this answer.</p>
<p>Rewriting already-published history on a branch in which you are working with other people without <em>very</em> good reason such as leaking a password or other sensitive details forces work onto your collaborators and is antisocial and will annoy other developers. The <a href="https://git-scm.com/docs/git-rebase#_recovering_from_upstream_rebase" rel="noreferrer">“Recovering From an Upstream Rebase” section in the <code>git rebase</code> documentation</a> explains, with added emphasis.</p>
<blockquote>
<p>Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history. This section explains how to do the fix from the downstream’s point of view. <strong>The real fix, however, would be to avoid rebasing the upstream in the first place.</strong> …</p>
</blockquote> |
25,161,774 | What are conventions for filenames in Go? | <p>I could find the conventions for naming packages in Go: no underscore between words, everything lowercase.</p>
<p>Does this convention apply to the filenames too?</p>
<p>Do you also put one struct in one file as if you did for a java class and then name the file after the struct?</p>
<p>Currently, if I have a struct WebServer, I put it in a file web_server.go.</p> | 25,162,021 | 6 | 0 | null | 2014-08-06 13:32:54.743 UTC | 17 | 2022-05-09 16:39:13.363 UTC | null | null | null | null | 3,802,013 | null | 1 | 167 | go|naming-conventions | 107,189 | <p>There's a few guidelines to follow.</p>
<ol>
<li>File names that begin with "." or "_" are ignored by the go tool</li>
<li>Files with the suffix <code>_test.go</code> are only compiled and run by the <code>go test</code> tool.</li>
<li>Files with os and architecture specific suffixes automatically follow those same constraints, e.g. <code>name_linux.go</code> will only build on linux, <code>name_amd64.go</code> will only build on amd64. This is the same as having a <code>//+build amd64</code> line at the top of the file</li>
</ol>
<p>See the <code>go</code> docs for more details: <a href="https://pkg.go.dev/cmd/go" rel="noreferrer">https://pkg.go.dev/cmd/go</a></p> |
23,805,772 | How to MongoDB aggregation in Node.js | <pre><code>var mongoose = require('mongoose');
var membersModel = require('./model_member.js');
exports.request_friend_list = function(req, res){
var userid=req.body.userid;
console.log(userid);
// membersModel.find({_id: userid,friends:{status:0}},{_id:0,'friends':1,},function(err,data)
membersModel.aggregate(
{$match: {_id:userid}},
{$project: {friends: 1}},
{$unwind: "$friends"},
{$match: {"friends.status": 0}}
,function(err,data){
if(err){
res.json({status:"error"});
throw err;
}else{
if(JSON.stringify(data).length > 0){
console.log(JSON.stringify(data));
res.json(data);
}
else{
res.json({status: "Data is not Exist."});
console.log("Data is not Exist.");
}
}
});
</code></pre>
<p><code>membersModel.find({...})</code> is operating normally, but <code>memberModel.Aggregation({...})</code> is not working. This also works in MongoDB:</p>
<pre><code>db.members.aggregate({$match:_id: ObjectId("532b4729592f81596d000001"),$project:"friends":1,$unwind:"$friends",$match:"friends.status": 0})
</code></pre>
<p>What is the problem?</p> | 23,820,986 | 1 | 0 | null | 2014-05-22 11:38:58.973 UTC | null | 2020-03-13 12:17:01.103 UTC | 2014-05-23 08:29:53.8 UTC | null | 2,313,887 | null | 3,664,775 | null | 1 | 9 | node.js|mongodb|mongoose | 38,652 | <p>The likely problem here is that your <code>userid</code> value is not actually a correct <code>ObjectID</code> type when it is being passed into the pipeline. This results in nothing being "matched" in the initial stage.</p>
<p>Therefore as a more complete example:</p>
<pre><code>var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectID = require("mongodb").ObjectID;
mongoose.connect("mongodb://localhost/test");
friendSchema = new Schema({
"name": String,
"status": Number
});
memberSchema = new Schema({
friends: [friendSchema]
});
var Member = mongoose.model("Members", memberSchema );
var userid = new ObjectID("537ec520e98bcb378e811d54");
console.log( userid );
Member.aggregate([
{ "$match": { "_id": userid } },
{ "$unwind": "$friends" },
{ "$match": { "friends.status": 0 } }],
function( err, data ) {
if ( err )
throw err;
console.log( JSON.stringify( data, undefined, 2 ) );
}
);
</code></pre>
<p>Which then will match data as expected:</p>
<pre><code>[
{
"_id": "537ec520e98bcb378e811d54",
"friends": [{
"name": "Ted",
"status": 0
}]
}
]
</code></pre>
<p>So be careful to make sure this is of the correct type. The aggregate method does not automatically wrap a string value such as "537ec520e98bcb378e811d54" into an <code>ObjectID</code> type when it is mentioned in a pipeline stage against <code>_id</code> in the way that Mongoose does this with other find and update methods.</p> |
40,238,574 | Selenium Python wait for text to be present in element error shows takes 3 arguments 2 given | <p>I am using WebdriverWait to wait for some text to be present in an element on a webpage. I am using Selenium with Python. My syntax is not correct.
I am getting the error:
TypeError: <strong>init</strong>() takes exactly 3 arguments (2 given):</p>
<p>Error trace:</p>
<pre><code>Traceback (most recent call last):
File "E:\test_runners 2 edit project\selenium_regression_test_5_1_1\Regression_TestCase\RegressionProjectEdit_TestCase.py", line 2714, in test_000057_run_clean_and_match_process
process_lists_page.wait_for_run_process_to_finish()
File "E:\test_runners 2 edit project\selenium_regression_test_5_1_1\Pages\operations.py", line 334, in wait_for_run_process_to_finish
EC.text_to_be_present_in_element("No data to display"))
TypeError: __init__() takes exactly 3 arguments (2 given)
</code></pre>
<p>My code snippet is:</p>
<pre><code>def wait_for_run_process_to_finish(self): # When the process is running use WebdriverWait to check until the process has finished. No data to display is shown when process has completed.
try:
WebDriverWait(self.driver, 900).until(
EC.text_to_be_present_in_element("No data to display"))
no_data_to_display_element = self.get_element(By.ID, 'operations_monitoring_tab_current_ct_fields_no_data')
print "no_data_to_display_element ="
print no_data_to_display_element.text
if no_data_to_display_element.text == "No data to display":
return True
except NoSuchElementException, e:
print "Element not found "
print e
self.save_screenshot("wait_for_run_process_to_finish")
</code></pre>
<p>The scenario is the user clicks the run button and it starts of a process.
When the process completes the text "No data to display" will be shown.
I would like to wait until this text is displayed then I know the process has completed.
Before I was using time.sleep(900) which is not good as it explicitly waits the full 15 mins. The process could complete in 8 mins, sometimes 12 mins.</p>
<p>I have also tried:</p>
<pre><code>WebDriverWait(self.driver, 900).until(
EC.text_to_be_present_in_element(By.ID, 'operations_monitoring_tab_current_ct_fields_no_data', "No data to display"))
</code></pre>
<p>The error shows: TypeError: <strong>init</strong>() takes exactly 3 arguments (4 given)</p>
<p>What is the correct syntax to wait for the text to be present?
Thanks, Riaz</p> | 40,238,766 | 2 | 0 | null | 2016-10-25 11:19:39.283 UTC | 2 | 2018-11-21 10:14:11.373 UTC | 2016-10-25 11:27:40.793 UTC | null | 358,378 | null | 358,378 | null | 1 | 13 | python|selenium|selenium-webdriver | 40,664 | <p>The syntax you used for <code>EC.text_to_be_present_in_element("No data to display"))</code> is wrong.</p>
<p>The syntax is:</p>
<pre><code>class selenium.webdriver.support.expected_conditions.text_to_be_present_in_element(locator, text_)
</code></pre>
<blockquote>
<p>An expectation for checking if the given text is present in the
specified element. locator, text</p>
</blockquote>
<p>So, clearly, the locator is missing in your code in which the text to be checked. putting parenthesis also the issue you are facing (in the second edit).</p>
<p>Use as follows (to add locator with correct parenthesis ):</p>
<pre><code>EC.text_to_be_present_in_element((By.ID, "operations_monitoring_tab_current_ct_fields_no_data"), "No data to display")
</code></pre>
<p>Note: By.id is just an example. you can use any locator to identify the element supported by selenium</p> |
10,307,496 | Is there a way or tutorial for converting Arduino code to C code? | <p>I know that this question is general, but I couldn't find a tutorial or a good coding way to convert Arduino code (I mean the code that we are writing on Arduino software and it doesn't matter for <a href="http://arduino.cc/en/Main/ArduinoBoardUno">Arduino Uno</a> or <a href="http://en.wikipedia.org/wiki/List_of_Arduino_compatibles#Official_Arduino_versions">Mega</a> or ... ) even if a small sample.</p>
<p>Is there a tutorial?</p>
<p>I just want to learn the technique, and I know that it depends on the project.</p> | 10,307,530 | 3 | 0 | null | 2012-04-24 23:40:13.853 UTC | 6 | 2020-07-07 00:22:26.477 UTC | 2012-09-17 04:33:49.22 UTC | null | 893 | user1354921 | null | null | 1 | 9 | c|embedded|arduino | 38,052 | <p>Arduino code <em>is</em>, more or less, C code.</p>
<p>The unique things that happen with Arduino is that the code is preprocessed (for example, they give simple hooks by establishing the <code>setup</code> and <code>loop</code> functions) and has a managed build/upload process that takes care of board limits, includes, libraries, etc...</p>
<p>It is certainly possible to use the same toolkit yourself to build and run the code, that's how I do it. <em><a href="http://www.ashleymills.com/node/327" rel="noreferrer">Arduino and GCC, compiling and uploading programs using only makefiles</a></em> is the most useful link I've found covering the steps you need to get started.</p>
<p>As I said, I've left the Arduino IDE and taken up the <code>avr-gcc</code> route myself, because if you know the GNU tools, you can do much more powerful things - like use the C++ standard libraries. I missed my <code>vector</code>s, what can I say. <a href="http://www.nongnu.org/avr-libc/" rel="noreferrer">avr-libc</a> is lagging quite a bit when it comes to full C++ functionality, making it hard to cram in the <a href="http://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>, but <a href="http://andybrown.me.uk/ws/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/" rel="noreferrer">Andy Brown has gotten much of it working</a>.</p>
<p>Throw those things together and you have quite a powerful development environment.</p> |
5,966,817 | Difference between square brackets and curly brackets in Matlab? | <p>A bit of a newbie question: whats the difference between square brackets <code>[]</code> and curly brackets <code>{}</code> in Matlab? When is it appropriate to use either?</p>
<p>Update: its actually in the Matlab docs under "Special Characters".</p> | 5,966,949 | 2 | 1 | null | 2011-05-11 15:33:02.627 UTC | 11 | 2019-12-05 08:47:49.583 UTC | 2015-09-17 23:06:41.807 UTC | user616736 | 107,409 | null | 107,409 | null | 1 | 31 | matlab | 56,281 | <p>A square bracket creates a vector or matrix, whereas curly brackets creates a cell array.</p>
<p>When working with numbers, I'd say that 99% of the time, you will use square brackets. Cell arrays allow you to store different types of data at each location, e.g. a 10x5 matrix at (1,1), a string array at (1,2), ...</p>
<pre><code>x = [1 2 3]; #% matrix with values 1, 2, 3
y = {1, 'a', x}; #% cell array storing a number, a character, and 1x3 matrix
</code></pre>
<p>Here is the MATLAB documentation on cell arrays: <a href="http://www.mathworks.com/help/matlab/cell-arrays.html" rel="noreferrer">http://www.mathworks.com/help/matlab/cell-arrays.html</a></p> |
19,423,827 | write an ng-pattern to disallow whitespaces and special characters | <p>I am trying to get an angular ng-pattern to check that a username has no whitespaces or special characters. The following form return false if you enter whitespaces or special characters. However, it becomes true as soon as you enter a-z, A-z or 0-9. I have tried ng-pattern="/[^\s]+/" and \S and [^ ] but they make no difference.</p>
<pre><code><form name="myform">
valid? {{ myform.$valid }}
<input type="text" name="username" ng-model="username" ng-pattern="/[a-zA-Z0-9^ ]/" required/>
</form>
</code></pre>
<p>Here's the form in a plunk: <a href="http://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ?p=preview">http://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ?p=preview</a></p> | 19,424,059 | 3 | 0 | null | 2013-10-17 10:09:42.55 UTC | 7 | 2018-09-11 12:56:20.987 UTC | null | null | null | null | 2,326,620 | null | 1 | 22 | regex|angularjs | 64,731 | <p>Try the following pattern:</p>
<pre><code>/^[a-zA-Z0-9]*$/
</code></pre>
<p>This allows only alphanumeric characters.</p> |
21,607,745 | specific config by environment in Scala | <p>What is a good way to set up a project in Scala which uses different configuration depending on environments.</p>
<p>I need to specifically have different databases for <strong>development</strong>, <strong>test</strong> and <strong>production</strong> environment (similar to what is done in Rails)</p> | 33,261,928 | 3 | 0 | null | 2014-02-06 15:56:52.35 UTC | 17 | 2018-05-08 22:08:36.737 UTC | null | null | null | null | 105,514 | null | 1 | 34 | scala|configuration|environment-variables|config|development-environment | 29,119 | <p>Another strategy I'm using consists of using <a href="https://github.com/typesafehub/config/blob/master/HOCON.md#includes" rel="noreferrer"><em>includes</em></a>.
I usually store my DEV settings in the <a href="https://github.com/typesafehub/config#standard-behavior" rel="noreferrer">default</a> <code>application.conf</code> file then I create a new conf file for other environments and include the default one.</p>
<p>Let's say my DEV conf <code>application.conf</code> looks like this:</p>
<pre><code>myapp {
server-address = "localhost"
server-port = 9000
some-other-setting = "cool !"
}
</code></pre>
<p>Then for the PROD, I could have another file called <code>prod.conf</code>:</p>
<pre><code>include "application"
# override default (DEV) settings
myapp {
server-address = ${PROD_SERVER_HOSTNAME}
server-port = ${PROD_SERVER_PORT}
}
</code></pre>
<p>Note that I override <em>only</em> the settings that change in the PROD environment (<code>some-other-setting</code> is thus the same as in DEV).</p>
<p>The config bootstrap code doesn't test anything</p>
<pre><code>...
val conf = ConfigFactory.load()
...
</code></pre>
<p>To switch from the DEV to the PROD conf, simply pass a system property with the name of the config file to load:</p>
<pre><code>java -Dconfig.resource=prod.conf ...
</code></pre>
<p>In DEV, no need to pass it since <code>application.conf</code> will be loaded by <a href="https://github.com/typesafehub/config#standard-behavior" rel="noreferrer">default</a>.</p>
<p>So here we're using <a href="https://lightbend.github.io/config" rel="noreferrer">Typesafe Config</a>'s default loading mechanism to achieve this.</p>
<p>I've created a simple <a href="https://github.com/ozeebee/test-scala-config" rel="noreferrer">project</a> to demonstrate this technique. Feel free to clone and experiment.</p> |
48,869,915 | Angular - Material: Progressbar custom color? | <p>I am now trying for hours. I use Material2 and simply want to change the color of the progress-bar. I know there are those themes (primary/accent/warn) but I want to have a custom color (green) for my progressbar.</p>
<p>I already tried the weirdest css-combinations.. but with no effort. Maybe someone had the same problem?</p> | 48,870,180 | 12 | 2 | null | 2018-02-19 16:06:45.13 UTC | 9 | 2022-06-10 06:09:35.65 UTC | 2021-10-29 19:52:42.177 UTC | null | 114,029 | null | 9,177,588 | null | 1 | 27 | css|angular|angular-material|progress-bar | 58,988 | <p>I can suggest to change one of the premade primary/warn/accent colors to your custom color.</p>
<p>In your <code>styles.scss</code> (if your style file is css you will have to change it to support scss):</p>
<pre><code> @import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();
// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue.
$mat-blue: (
50: #e3f2fd,
100: #bbdefb,
200: #90caf9,
300: #64b5f6,
400: #42a5f5,
500: #2196f3,
600: #1e88e5,
700: #1976d2,
800: #1565c0,
900: #0d47a1,
A100: #82b1ff,
A200: #448aff,
A400: #2979ff,
A700: #2B66C3,
contrast: (
50: $black-87-opacity,
100: $black-87-opacity,
200: $black-87-opacity,
300: $black-87-opacity,
400: $black-87-opacity,
500: white,
600: white,
700: white,
800: $white-87-opacity,
900: $white-87-opacity,
A100: $black-87-opacity,
A200: white,
A400: white,
A700: white,
)
);
$candy-app-primary: mat-palette($mat-blue, A700);
$candy-app-accent: mat-palette($mat-orange, A200, A100, A400);
// The warn palette is optional (defaults to red).
$candy-app-warn: mat-palette($mat-red);
// Create the theme object (a Sass map containing all of the palettes).
$candy-a-theme($candy-app-theme);
pp-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material
</code></pre> |
8,493,978 | CommandArgument in the Gridview | <p>I have a gridview like this. </p>
<pre><code><asp:GridView ID="grdMerchant" runat="server" GridLines="None"
HeaderStyle-Font-Bold="True" AutoGenerateColumns="False" AllowSorting="True" ShowHeader="false" OnRowDataBound="grdMerchant_RowDataBound" OnRowCommand="grdMerchant_RowCommand" DataKeyNames="OrderID" style="table-layout:auto;width:100%;" >
<asp:TemplateField >
<ItemTemplate>
<asp:Linkbutton ID= "btnView" runat="server" Text="View" OnClick="btnView_OnClick" CommandArgument='<%#Eval("OrderID")%>' ></asp:Linkbutton>
</code></pre>
<p>
</p>
<p>How do i have to get the OrderID of the selected row. I tried using </p>
<pre><code>int OrderID = (int)grdMerchant.DataKeys[row.RowIndex][2];
</code></pre>
<p>But it gets null and i know this is not the way. Help me. </p>
<p>Thank you in advance!</p> | 8,494,074 | 1 | 0 | null | 2011-12-13 18:07:11.36 UTC | null | 2016-05-15 08:58:24.983 UTC | null | null | null | null | 397,062 | null | 1 | 12 | c#|asp.net|gridview | 45,346 | <p>try like this</p>
<pre><code> <asp:GridView ID="grd1" runat="Server" width="500px" AutoGenerateColumns="false" DataKeyNames="StateID" OnRowEditing="grd1_RowEditing">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandArgument='<%#Eval("StateID")%>' OnCommand="lnkDelete" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</code></pre>
<p></p>
<pre><code> protected void lnkDelete(Object sender, CommandEventArgs e)
{
int iStID=int32.Parse(e.CommandArgument.ToString());
}
//iStID has the DataKey value which you can use.
</code></pre> |
8,591,887 | jQuery get parent sibling for this element only | <p>I cant figure out how to write this.</p>
<p>See my mark up structure, which is repeated multiple times on a page.</p>
<pre><code><div class="module">
<div class="archive-info">
<span class="archive-meta">
open
</span>
</div>
<div class="archive-meta-slide">
</div>
</div>
</code></pre>
<p>As you can see inside my mark-up, I have a <code><span></code> which is my <code>$metaButton</code> - when this is clicked, it runs the animation on the <code>div.archive-meta-slide</code> - this is simple enough, but I'm trying to run the animation only on the current <code>div.module</code> it animates all the divs with the class <code>"archive-meta-slide"</code>, and I'm really struggling to animate only the current <code>div.archive-meta-slide</code> using <code>this</code></p>
<p>It would be easy if the <code>div.archive-meta-slide</code> was inside the parent div of <code>$metaButton</code>, but because it's outside this parent div, I can't get the traversing right.</p>
<p>See my script</p>
<pre><code>var $metaButton = $("span.archive-meta"),
$metaSlide = $(".archive-meta-slide");
$metaButton.toggle(
function() {
$(this).parent().siblings().find(".archive-meta-slide").animate({ height: "0" }, 300);
$(this).parent().siblings().find(".archive-meta-slide").html("close");
},
function() {
$(this).parent().siblings().find(".archive-meta-slide").animate({ height: "43px" }, 300);
$(this).parent().siblings().find(".archive-meta-slide").html("open");
});
</code></pre>
<p>Can anyone help?</p>
<p>Thanks
Josh</p> | 8,591,924 | 6 | 0 | null | 2011-12-21 15:02:51.133 UTC | 4 | 2015-07-22 13:45:28.613 UTC | null | null | null | null | 801,773 | null | 1 | 23 | javascript|jquery|traversal | 55,050 | <pre><code>$(this).parent().siblings().find(".archive-meta-slide")
</code></pre>
<p>This is <em>really</em> close. This actually says "find elements with the class <code>archive-meta-slide</code> that are descendants of siblings of this element's parent". You want to say "find elements with the class <code>archive-meta-slide</code> that <em>are</em> siblings of this element's parent". For that, use a selector on the <code>siblings</code> call:</p>
<pre><code>$(this).parent().siblings(".archive-meta-slide")
</code></pre>
<p>Note that, if the markup is always this structure, you could even do <code>$(this).parent().next()</code>.</p>
<p>See the jQuery API:</p>
<ul>
<li><a href="http://api.jquery.com/siblings" rel="noreferrer"><code>siblings</code></a></li>
<li><a href="http://api.jquery.com/find" rel="noreferrer"><code>find</code></a></li>
<li><a href="http://api.jquery.com/next" rel="noreferrer"><code>next</code></a></li>
</ul> |
8,857,705 | Deleting the first two lines of a file using BASH or awk or sed or whatever | <p>I'm trying to delete the first two lines of a file by just not printing it to another file. I'm not looking for something fancy. Here's my (failed) attempt at awk:</p>
<pre><code>awk '{ (NR > 2) {print} }' myfile
</code></pre>
<p>That throws out the following error:</p>
<pre><code>awk: { NR > 2 {print} }
awk: ^ syntax error
</code></pre>
<p>Example:</p>
<p>contents of 'myfile':</p>
<pre><code>blah
blahsdfsj
1
2
3
4
</code></pre>
<p>What I want the result to be:</p>
<pre><code>1
2
3
4
</code></pre> | 8,857,734 | 4 | 0 | null | 2012-01-13 21:51:24.043 UTC | 10 | 2014-10-26 18:26:44.163 UTC | 2014-10-26 18:26:44.163 UTC | null | 2,246,344 | null | 381,798 | null | 1 | 39 | bash|awk|sed|lines | 75,230 | <p>Use tail:</p>
<pre><code>tail -n+3 file
</code></pre>
<p>from the man page:</p>
<pre><code> -n, --lines=K
output the last K lines, instead of the last 10; or use -n +K
to output lines starting with the Kth
</code></pre> |
8,545,553 | Best way to debug third-party gems in ruby | <p>Since there may be a lot of <strong>Ghost Methods</strong> inside a ruby gem, I don't think it is a good idea to study the inner mechanism of a ruby gem just by reading its source code statically. Is there a way to attach the source file of a third-part gem to a running ruby process for debugging so that I can set break point and see how things work dynamically ?<br>
BTW,I've tried to navigate to the source file of a third-part gem in RubyMine by clicking on the context menu "Go To->Implementations" of the 'require' statement or other symbol of an third-part gem( <code>require 'watir'</code> for example ), without success. Is it normal for an IDE of a dynamic typing language such as Ruby to fail a symbol navigation?</p> | 8,545,814 | 5 | 0 | null | 2011-12-17 14:58:07.96 UTC | 18 | 2020-11-27 18:12:58.627 UTC | 2013-07-31 18:49:44.093 UTC | null | 167,614 | null | 872,319 | null | 1 | 42 | ruby|debugging|ide | 18,471 | <p>I would love to know if there's a better way to do this, but how I usually do it is:</p>
<ol>
<li>Add the ruby-debug gem to your Gemfile (or ruby-debug19 if you're on Ruby 1.9.2)</li>
<li>Find the Gem by doing <code>bundle show gemname</code>. I'm on a Mac so I usually pipe this to pbcopy so it gets copied to my clipboard. <code>bundle show rails | pbcopy</code></li>
<li>Open the gem directory in your favorite editor. <code>mvim /path/to/gem/directory</code></li>
<li>Navigate to the file and line where you want to put the breakpoint* and insert <code>debugger</code> above the line in question.</li>
<li>Reload page, run test, or do whatever you would to get the Gem file to execute</li>
<li>When execution stops at debugger, you can inspect variables (<code>p variable_name</code>), and move line by line with the <a href="http://bashdb.sourceforge.net/ruby-debug.html#Command-Index">ruby debugger commands</a>.</li>
</ol>
<p>*Knowing where to put the breakpoint can take some understanding of the code, but you should start in lib/gemname.rb</p> |
8,867,496 | Get last image from Photos.app? | <p>I have seen other apps do it where you can import the last photo from the Photos app for quick use but as far as I know, I only know how to get A image and not the last (most recent one). Can anyone show me how to get the last image?</p> | 8,872,425 | 13 | 0 | null | 2012-01-15 04:17:38.977 UTC | 52 | 2016-12-02 14:12:15.687 UTC | 2012-01-20 17:05:01.23 UTC | null | 237,838 | null | 394,736 | null | 1 | 55 | ios|image|camera|photos | 25,845 | <p>This code snippet will get the latest image from the camera roll <strong>(iOS 7 and below)</strong>:</p>
<pre><code>ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
// Chooses the photo at the last index
[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullScreenImage]];
// Stop the enumerations
*stop = YES; *innerStop = YES;
// Do something interesting with the AV asset.
[self sendTweet:latestPhoto];
}
}];
} failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(@"No groups");
}];
</code></pre>
<p><strong>iOS 8 and above:</strong></p>
<pre><code>PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];
[[PHImageManager defaultManager] requestImageForAsset:lastAsset
targetSize:self.photoLibraryButton.bounds.size
contentMode:PHImageContentModeAspectFill
options:PHImageRequestOptionsVersionCurrent
resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
[[self photoLibraryButton] setImage:result forState:UIControlStateNormal];
});
}];
</code></pre> |
47,556,287 | May a destructor be final? | <p>Does the C++ standard allow a destructor to be declared as <code>final</code>? Like this:</p>
<pre><code> class Derived: public Base
{
...
virtual ~Derived() final;
}
</code></pre>
<p>And if so, does that prevent the declaration of a derived class:</p>
<pre><code> class FurtherDerived: public Derived {// allowed?
}
</code></pre>
<p>If it <em>is</em> allowed, is a compiler likely to issue a warning? Is declaring a destructor to be <code>final</code> a workable idiom for indicating that a class is not intended to be used as a base class?</p>
<p>(There is <a href="https://stackoverflow.com/questions/11704406/whats-the-point-of-a-final-virtual-function">no point in doing this in a ultimate base class</a>, only a derived class.)</p> | 47,556,411 | 1 | 2 | null | 2017-11-29 15:27:11.947 UTC | 6 | 2017-11-29 16:02:28.21 UTC | 2017-11-29 16:02:28.21 UTC | null | 545,127 | null | 545,127 | null | 1 | 41 | c++|c++11|inheritance|destructor | 5,570 | <blockquote>
<p>May a C++ destructor be declared as <code>final</code>?</p>
</blockquote>
<p>Yes.</p>
<blockquote>
<p>And if so, does that prevent declaration of a derived class:</p>
</blockquote>
<p>Yes, because the derived class would have to declare a destructor (either explicitly by you or implicitly by the compiler), and that destructor would be overriding a function declared <code>final</code>, which is ill-formed.</p>
<p>The rule is <a href="http://eel.is/c++draft/class.derived#class.virtual-4.sentence-1" rel="noreferrer">[class.virtual]/4</a>:</p>
<blockquote>
<p>If a virtual function <code>f</code> in some class B is marked with the <em>virt-specifier</em> <code>final</code> and in a class D derived from B a function <code>D::f</code> overrides <code>B::f</code>, the program is ill-formed.</p>
</blockquote>
<p>It's the derivation itself that is ill-formed, it doesn't have to be used. </p>
<blockquote>
<p>Is declaring a destructor to be final a workable idiom for indicating that a class is not intended to be used as a base class?</p>
</blockquote>
<p>Effectively, but you should just mark the class <code>final</code>. It's quite a bit more explicit. </p> |
1,090,274 | How can I set the default value in a SharePoint list field, based on the value in another field? | <p>I have a custom list in SharePoint (specifically, MOSS 2007.) One field is a yes/no checkbox titled "Any defects?" Another field is "Closed by" and names the person who has closed the ticket.</p>
<p>If there are no defects then I want the ticket to be auto-closed. If there are, then the "Closed by" field ought to be filled in later on.</p>
<p>I figured I could set a calculated default value for "Closed by" like this:</p>
<pre><code>=IF([Any defects?],"",[Me])
</code></pre>
<p>but SharePoint complains I have referenced a field. I suppose this makes sense; the default values fire when the new list item is first opened for entry and there are no values in any fields yet.</p>
<p>I understand it is possible to make a calculated field based on a column value but in that case the field cannot be edited later.</p>
<p>Does anyone have any advice how to achieve what I am trying to do?</p>
<p>Is it possible to have a "OnSubmit" type event that allows me to execute some code at the point the list item is saved?</p>
<p>Thank you.</p> | 1,090,638 | 3 | 0 | null | 2009-07-07 03:42:41.993 UTC | 2 | 2009-10-02 12:04:23.11 UTC | null | null | null | null | 74,068 | null | 1 | 3 | sharepoint | 53,954 | <p>Include a content editor web part in the page (newform.aspx / editform.aspx) and use jQuery (or just plain javascript) to handle the setting of default values.</p>
<p>Edit: some example code:</p>
<p>In the lists newform.aspx, include a reference to jquery. If you look at the html code, you can see that each input tag gets an id based on the field's GUID, and a title that's set to the fields display name.</p>
<p>now, using jquery we can get at these fields using the jQuery selector like this:</p>
<p>By title:</p>
<pre><code>$("input[title='DISPLAYNAMEOFFIELD']");
</code></pre>
<p>by id (if you know the field's internal guid, the dashes will ahve to be replaced by underscores:</p>
<pre><code>// example field id, notice the guid and the underscores in the guid ctl00_m_g_054db6a0_0028_412d_bdc1_f2522ac3922e_ctl00_ctl04_ctl15_ctl00_ctl00_ctl04_ctl00_ctl00_TextField
$("input[id*='GUID']"); //this will get all input elements of which the id contains the specified GUID, i.e. 1 element
</code></pre>
<p>We wrap this in the <code>ready()</code> function of jQuery, so all calls will only be made when the document has fully loaded:</p>
<pre><code>$(document).ready(function(){
// enter code here, will be executed immediately after page has been loaded
});
</code></pre>
<p>By combining these 2 we could now set your dropdown's <code>onchange</code> event to the following</p>
<pre><code>$(document).ready(function(){
$("input[title='DISPLAYNAMEOFFIELD']").change(function()
{
//do something to other field here
});
});
</code></pre> |
695,802 | Using SSL and SslStream for peer to peer authentication? | <p>I need to provide secure communication between various processes that are using TCP/IP sockets for communication. I want both authentication and encryption. Rather than re-invent the wheel I would really like to use SSL and the SslStream class and self-signed certificates. What I want to do is validate the remote process's certificate against a known copy in my local application. (There doesn't need to be a certificate authority because I intend for the certificates to be copied around manually).</p>
<p>To do this, I want the application to be able to automatically generate a new certifiate the first time it is run. In addition to makecert.exe, it looks like <a href="http://blogs.msdn.com/dcook/archive/2008/11/25/creating-a-self-signed-certificate-in-c.aspx" rel="noreferrer">this link</a> shows a way to automatically generate self-signed certificates, so that's a start.</p>
<p>I've looked at the AuthenticateAsServer and AuthenticateAsClient methods of SslStream. You can provide call-backs for verification, so it looks like it's possible. But now that I'm into the details of it, I really don't think it's possible to do this.</p>
<p>Am I going in the right direction? Is there a better alternative? Has anyone done anything like this before (basically peer-to-peer SSL rather than client-server)?</p> | 699,922 | 3 | 0 | null | 2009-03-30 01:56:43.483 UTC | 26 | 2014-03-03 18:08:52.623 UTC | null | null | null | Scott W. | 17,635 | null | 1 | 18 | c#|ssl|ssl-certificate|sslstream | 29,790 | <p><strong>Step 1:</strong> Generating a self-signed certificate:</p>
<ul>
<li>I downloaded the <a href="http://blogs.msdn.com/dcook/archive/2008/11/25/creating-a-self-signed-certificate-in-c.aspx" rel="noreferrer">Certificate.cs class</a> posted by Doug Cook</li>
<li><p>I used this code to generate a .pfx certificate file:</p>
<pre><code>byte[] c = Certificate.CreateSelfSignCertificatePfx(
"CN=yourhostname.com", //host name
DateTime.Parse("2000-01-01"), //not valid before
DateTime.Parse("2010-01-01"), //not valid after
"mypassword"); //password to encrypt key file
using (BinaryWriter binWriter = new BinaryWriter(
File.Open(@"testcert.pfx", FileMode.Create)))
{
binWriter.Write(c);
}
</code></pre></li>
</ul>
<p><strong>Step 2:</strong> Loading the certificate</p>
<pre><code> X509Certificate cert = new X509Certificate2(
@"testcert.pfx",
"mypassword");
</code></pre>
<p><strong>Step 3:</strong> Putting it together</p>
<ul>
<li>I based it on <a href="http://leastprivilege.com/2005/02/28/sslstream-sample/" rel="noreferrer">this very simple SslStream example</a></li>
<li>You will get a compile time error about the SslProtocolType enumeration. Just change that from SslProtocolType.Default to SslProtocols.Default</li>
<li>There were 3 warnings about deprecated functions. I replaced them all with the suggested replacements.</li>
<li><p>I replaced this line in the Server Program.cs file with the line from Step 2:</p>
<p>X509Certificate cert = getServerCert();</p></li>
<li><p>In the Client Program.cs file, make sure you set serverName = yourhostname.com (and that it matches the name in the certificate)</p></li>
<li>In the Client Program.cs, the CertificateValidationCallback function fails because sslPolicyErrors contains a RemoteCertificateChainErrors. If you dig a little deeper, this is because the issuing authority that signed the certificate is not a trusted root.</li>
<li>I don`t want to get into having the user import certificates into the root store, etc., so I made a special case for this, and I check that certificate.GetPublicKeyString() is equal to the public key that I have on file for that server. If it matches, I return True from that function. That seems to work.</li>
</ul>
<p><strong>Step 4:</strong> Client Authentication</p>
<p>Here's how my client authenticates (it's a little different than the server):</p>
<pre><code>TcpClient client = new TcpClient();
client.Connect(hostName, port);
SslStream sslStream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(CertificateValidationCallback),
new LocalCertificateSelectionCallback(CertificateSelectionCallback));
bool authenticationPassed = true;
try
{
string serverName = System.Environment.MachineName;
X509Certificate cert = GetServerCert(SERVER_CERT_FILENAME, SERVER_CERT_PASSWORD);
X509CertificateCollection certs = new X509CertificateCollection();
certs.Add(cert);
sslStream.AuthenticateAsClient(
serverName,
certs,
SslProtocols.Default,
false); // check cert revokation
}
catch (AuthenticationException)
{
authenticationPassed = false;
}
if (authenticationPassed)
{
//do stuff
}
</code></pre>
<p>The CertificateValidationCallback is the same as in the server case, but note how AuthenticateAsClient takes a collection of certificates, not just one certificate. So, you have to add a LocalCertificateSelectionCallback, like this (in this case, I only have one client cert so I just return the first one in the collection):</p>
<pre><code>static X509Certificate CertificateSelectionCallback(object sender,
string targetHost,
X509CertificateCollection localCertificates,
X509Certificate remoteCertificate,
string[] acceptableIssuers)
{
return localCertificates[0];
}
</code></pre> |
1,080,479 | How to make DockPanel fill available space | <p>I'm trying the content of a shopping cart in an <code>ItemsControl(ListBox)</code>. To do so, I've created the following <code>DataTemplate</code>:</p>
<pre><code><DataTemplate x:Key="Templates.ShoppingCartProduct"
DataType="{x:Type viewModel:ProductViewModel}">
<DockPanel HorizontalAlignment="Stretch">
<TextBlock DockPanel.Dock="Left"
Text="{Binding Path=Name}"
FontSize="10"
Foreground="Black" />
<TextBlock DockPanel.Dock="Right"
Text="{Binding Path=Price, StringFormat=\{0:C\}}"
FontSize="10"
Foreground="Black" />
</DockPanel>
</DataTemplate>
</code></pre>
<p>When the items are displayed in my shopping cart however, the Name and Price <code>TextBlocks</code> are sitting right beside one another, and there is an extremely large amount of whitespace on the right hand side.</p>
<p>Was wondering what the best method to force the <code>DockPanel</code> to stretch to fill all the space made available by the <code>ListItem</code> was?</p> | 1,080,488 | 3 | 0 | null | 2009-07-03 18:59:52.163 UTC | 6 | 2015-03-03 13:49:36.46 UTC | 2011-08-04 21:14:11.823 UTC | null | 305,637 | null | 5,086 | null | 1 | 24 | .net|wpf|autosize|dockpanel | 63,003 | <p>Bind the <code>Width</code> of the <code>DockPanel</code> to the <code>ActualWidth</code> of the <code>ListBoxItem</code>:</p>
<pre><code><DockPanel Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}">
...
</code></pre>
<p>Another option: you could just redefine the <code>ItemContainerStyle</code> so that the <code>ListBoxItem</code> is stretched horizontally:</p>
<pre><code><ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</code></pre> |
28,643,573 | How to set an environment variable in Amazon EC2 | <p>I created a tag on the AWS console for one of my EC2 instances.</p>
<p><img src="https://i.stack.imgur.com/1MxjO.png" alt="enter image description here"></p>
<p>However, when I look on the server, no such environment variable is set.</p>
<p>The same thing works with elastic beanstalk. <code>env</code> shows the tags I created on the console.</p>
<pre><code>$ env
[...]
DB_PORT=5432
</code></pre>
<p>How can I set environment variables in Amazon EC2?</p> | 28,649,865 | 5 | 1 | null | 2015-02-21 08:02:26.133 UTC | 16 | 2021-11-05 12:01:01.93 UTC | null | null | null | null | 1,514,990 | null | 1 | 49 | amazon-web-services|amazon-ec2|debian|environment-variables | 107,421 | <p>Following the instructions given by <a href="https://stackoverflow.com/users/179529/guy">Guy</a>, I wrote a small shell script. This script uses AWS CLI and <code>jq</code>. It lets you import your AWS instance and AMI tags as shell environment variables.</p>
<p>I hope it can help a few people.</p>
<p><a href="https://github.com/12moons/ec2-tags-env" rel="nofollow">https://github.com/12moons/ec2-tags-env</a></p> |
24,409,703 | How to uninstall java from command line independent of version currently installed in machine? | <p>hi i have to write a command line to uninstall java where it get current version already installed in system ?(suppose one system having jre-6u29 where other having jre-7).But i want single command line to uninstall existing version.please help me. </p> | 24,410,295 | 2 | 0 | null | 2014-06-25 13:12:47.953 UTC | 4 | 2020-08-07 07:41:46.247 UTC | null | null | null | null | 3,770,462 | null | 1 | 5 | cmd | 43,430 | <p><strong><em>I have not tested this.</em></strong></p>
<p><strong><em>Use with EXTREME caution. It WILL NOT prompt for confirmation, and it WILL NOT let you cancel your action</em></strong></p>
<p>Open a command prompt using administrator rights, and type in:</p>
<pre><code>wmic product where "name like 'Java%'" call uninstall
</code></pre>
<p>What this simple command is doing is:</p>
<ul>
<li>Find all the products installed on your computer which name starts with "Java"</li>
<li>Uninstalls them without asking for confirmation, nor showing any kind of user interface</li>
</ul> |
24,248,098 | AngularJS dynamic form from json data (different types) | <p>I try to create a dynamic form in AngularJS using the data from a JSON. I have this working:</p>
<p><strong>HTML</strong></p>
<pre><code> <p ng-repeat="field in formFields">
<input
dynamic-name="field.name"
type="{{ field.type }}"
placeholder="{{ field.name }}"
ng-model="field.value"
required
>
<span ng-show="myForm.{{field.name}}.$dirty && myForm.{{field.name}}.$error.required">Required!</span>
<span ng-show="myForm.{{field.name}}.$dirty && myForm.{{field.name}}.$error.email">Not email!</span>
</p>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>angular.module('angularTestingApp').controller('DynamicFormCtrl', function ($scope) {
$scope.formFields = [
{
name: 'firstName',
type: 'text'
},
{
name: 'email',
type: 'email'
},
{
name: 'password',
type: 'password'
},
{
name: 'secondName',
type: 'text'
}
];}).directive("dynamicName",function($compile){
return {
restrict:"A",
terminal:true,
priority:1000,
link:function(scope,element,attrs){
element.attr('name', scope.$eval(attrs.dynamicName));
element.removeAttr("dynamic-name");
$compile(element)(scope);
}
}});
</code></pre>
<p>This code works, but the question is that <strong>I dont know how to add dynamic checkbox or checklist</strong> and how can I <strong>validate</strong> inside the form, something like this:</p>
<pre><code>angular.module('angularTestingApp')
</code></pre>
<p>.controller('DynamicFormCtrl', function ($scope) {</p>
<pre><code>$scope.formFields = [
{
name: 'firstName',
type: 'text'
},
{
name: 'email',
type: 'email'
},
{
name: 'password',
type: 'password'
},
{
name: 'city',
type: 'checkbox',
choices: [
{ name: "red" },
{ name: "blue" },
{ name: "green" },
]
}
];})
</code></pre>
<p>Thank you in advance for your attention.
Best Regards!</p> | 24,290,468 | 3 | 0 | null | 2014-06-16 16:19:10.527 UTC | 16 | 2018-04-10 07:46:19.227 UTC | null | null | null | null | 3,593,067 | null | 1 | 28 | javascript|json|forms|angularjs|dynamic-data | 46,526 | <p>I have solved my problem. </p>
<p>This a plunkr link with one example of Dynamic Forms with Validation in AngularJS</p>
<p><a href="http://plnkr.co/edit/kqiheTEoGDQxAoQV3wxu?p=preview" rel="noreferrer">http://plnkr.co/edit/kqiheTEoGDQxAoQV3wxu?p=preview</a></p>
<p><strong>.html</strong></p>
<pre><code> <form name="myForm" class="form-horizontal" role="form" ng-submit="submitForm()">
<div ng-repeat="field in entity.fields">
<ng-form name="form">
<!-- TEXT FIELDS -->
<div ng-if="field.type=='text'" class="form-group">
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<input type="{{ field.type }}" dynamic-name="field.name" id="{{field.name}}" data-ng-model="field.data" class="form-control" required/>
<!--<span ng-show="myForm.{{field.name}}.$dirty && myForm.{{field.name}}.$error.required">Required!</span>.-->
<span data-ng-show=" {{'form.'+field.name+'.$dirty && form.'+field.name+'.$error.required'}}">Required!</span>
</div>
</div>
<!-- EMAIL FIELDS -->
<div ng-if="field.type=='email'" class="form-group">
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<input type="{{ field.type }}" dynamic-name="field.name" data-ng-model="field.data" class="form-control" required/>
<span data-ng-show=" {{'form.'+field.name+'.$dirty && form.'+field.name+'.$error.required'}}">Required!</span>
<span data-ng-show=" {{'form.'+field.name+'.$dirty && form.'+field.name+'.$error.email'}}">Not email!</span>
</div>
</div>
<!-- PASSWORD FIELDS -->
<div ng-if="field.type=='password'" class="form-group" >
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<input type="{{ field.type }}" dynamic-name="field.name" data-ng-model="field.data" ng-minlength={{field.min}} ng-maxlength={{field.max}} class="form-control" required/>
<span data-ng-show=" {{'form.'+field.name+'.$dirty && form.'+field.name+'.$error.required'}}">Required!</span>
<span data-ng-show=" {{'!form.'+field.name+'.required && (form.'+field.name+'.$error.minlength || form.'+field.name+'.$error.maxlength)' }}">Passwords must be between 8 and 20 characters.</span>
</div>
</div>
<!-- SELECT FIELDS -->
<div ng-if="field.type=='select'" class="form-group" >
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<select data-ng-model="field.data" ng-options="option.name for option in field.options" class="form-control" required/>
</div>
</div>
<!-- RADIO FIELDS -->
<div ng-if="field.type=='radio'" class="form-group">
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<div class="checkbox" ng-repeat="option in field.options" >
<label>
<input type="radio" data-ng-model="field.data" name="taskGroup" id="{{option.name}}" value="{{option.id}}">{{option.name}}
</label>
</div>
</div>
</div>
<!-- CHECKBOX FIELDS -->
<div ng-if="field.type=='checkbox'" class="form-group" >
<label class="col-sm-2 control-label">{{field.label}}</label>
<div class="col-sm-6">
<div class="checkbox" ng-repeat="option in field.options" >
<label>
<input type="checkbox" data-ng-model="option.data" name="taskGroup" id="{{option.name}}" value="{{option.id}}" >{{option.name}}
</label>
</div>
</div>
</div>
</ng-form>
</div>
<br/>
<button ng-disabled="myForm.$invalid" type="submit" id="submit">Submit</button>
<br/>
<pre>{{entity|json}}</pre>
<br/>
</form>
</code></pre>
<p><strong>.js</strong></p>
<pre><code>app.controller('DynamicFormController', function ($scope, $log) {
// we would get this from the api
$scope.entity = {
name : "Course",
fields :
[
{type: "text", name: "firstname", label: "Name" , required: true, data:""},
{type: "radio", name: "color_id", label: "Colors" , options:[{id: 1, name: "orange"},{id: 2, name: "pink"},{id: 3, name: "gray"},{id: 4, name: "cyan"}], required: true, data:""},
{type: "email", name: "emailUser", label: "Email" , required: true, data:""},
{type: "text", name: "city", label: "City" , required: true, data:""},
{type: "password", name: "pass", label: "Password" , min: 6, max:20, required: true, data:""},
{type: "select", name: "teacher_id", label: "Teacher" , options:[{name: "Mark"},{name: "Claire"},{name: "Daniel"},{name: "Gary"}], required: true, data:""},
{type: "checkbox", name: "car_id", label: "Cars" , options:[{id: 1, name: "bmw"},{id: 2, name: "audi"},{id: 3, name: "porche"},{id: 4, name: "jaguar"}], required: true, data:""}
]
};
$scope.submitForm = function(){
$log.debug($scope.entity);
}
})
.directive("dynamicName",function($compile){
return {
restrict:"A",
terminal:true,
priority:1000,
link:function(scope,element,attrs){
element.attr('name', scope.$eval(attrs.dynamicName));
element.removeAttr("dynamic-name");
$compile(element)(scope);
}
}
})
</code></pre> |
36,119,358 | React Native: Command `run-ios` unrecognized | <p>I have two different ReactNative-Projects:</p>
<ul>
<li>a) a project from januar 2016 </li>
<li>b) a complete new react-native project
from now (march 20th 2016)</li>
</ul>
<p>Within the new project the cli tool of react-native contains the command "run-ios" next two "run-android", but not on the older project from januar 2016. On the older one there is not "run-ios" command available:</p>
<pre><code>$ react-native run-ios
Command `run-ios` unrecognized
Usage: react-native <command>
</code></pre>
<p>I already ran "react-native upgrade" without any issues.</p>
<p>How can i get the command "run-ios" also in older projects?</p> | 36,126,924 | 15 | 1 | null | 2016-03-20 20:45:54.333 UTC | 15 | 2021-07-28 00:30:54.113 UTC | null | null | null | null | 4,769,503 | null | 1 | 72 | react-native | 59,864 | <p>Just update the version of react native in your project with the following command:</p>
<pre><code>$> npm install --save react-native@latest
</code></pre> |
6,240,330 | Memory alignment check | <p>I want to check whether an allocated memory is aligned or not. I am using <code>_aligned_malloc(size, align);</code> And it returns a pointer. Can I check it by simply dividing the pointer content by 16 for example? If the the pointer content is divisible by 16, does it mean that the memory is aligned by 16 bytes?</p> | 6,240,348 | 3 | 4 | null | 2011-06-05 00:54:41.017 UTC | 9 | 2011-06-06 01:11:41.227 UTC | null | null | null | null | 659,401 | null | 1 | 19 | c|visual-studio | 13,644 | <p>An "aligned" pointer by definition means that the numeric value of the pointer is evenly divisible by N (where N is the desired alignment). To check this, cast the pointer to an integer of suitable size, take the modulus N, and check whether the result is zero. In code:</p>
<pre><code>bool is_aligned(void *p, int N)
{
return (int)p % N == 0;
}
</code></pre>
<p>If you want to check the pointer value by hand, just look at the hex representation of the pointer and see whether it ends with the required number of 0 bits. A 16 byte aligned pointer value will always end in four zero bits, for example.</p> |
5,901,661 | wget + JavaScript? | <p>I have this webpage that uses client-side JavaScript to format data on the page before it's displayed to the user.</p>
<p>Is it possible to somehow use <code>wget</code> to download the page and use some sort of client-side JavaScript engine to format the data as it would be displayed in a browser?</p> | 5,901,700 | 3 | 3 | null | 2011-05-05 17:16:06.01 UTC | 6 | 2015-12-09 09:52:21.84 UTC | 2015-12-02 20:42:31.443 UTC | null | 1,245,190 | null | 172,350 | null | 1 | 35 | javascript|html|browser|wget | 62,618 | <p>You could probably make that happen with something like <a href="http://phantomjs.org/" rel="noreferrer">PhantomJS</a></p>
<p>You can write a phantomjs script that will load the page like a browser would, and then either take screenshots or use JS to inspect the page and pull out data.</p> |
5,614,739 | Is there some "Feature Graphic" generator for Google Play? | <p>I'm looking for some "Feature Graphic" online generator. Feature Graphic is the big image displayed in the web-based Android Market. </p>
<p>It could be something simple and it could look like one for this app: <a href="https://market.android.com/details?id=menion.android.locus" rel="noreferrer">https://market.android.com/details?id=menion.android.locus</a></p>
<p>I would input screenshots, title and some slogan and it would generate nice feature graphic. I think many Android developers would appreciate such service.</p> | 25,624,308 | 3 | 3 | null | 2011-04-10 21:08:09.53 UTC | 11 | 2014-09-03 13:30:18.153 UTC | 2014-09-03 13:30:18.153 UTC | null | 560,358 | null | 560,358 | null | 1 | 52 | android|google-play | 41,930 | <p>As of 31st Aug 2014 feature graphic is mandatory and handily there's a generator Created by Litrik De Roy <a href="http://www.norio.be/android-feature-graphic-generator/">here</a>. </p>
<blockquote>
<p>The Android Feature Graphic Generator allows you to easily create a
simple yet attractive feature graphic for your Android application. It
will generate a PNG image file according to Google's guidelines.
Afterwards you can upload the image to the Google Play Developer
Console to spice up the listing of your Android app.</p>
</blockquote> |
5,953,263 | Setting a height in CSS for an unordered list? | <p>I've got a list here for my page's footer, that I want displayed horizontally.</p>
<p>But because I've turned it into an inline list to go horizontally, the background images get cut off vertically. The biggest one is 27px high.</p>
<p>So I'm stuck.. I know why the following is doing what it's doing. But how do I get around it?</p>
<p>Here's the html:</p>
<pre><code><div id="footer">
<ul>
<li id="footer-tmdb"><a href="">Film data courtesy of TMDB</a></li>
<li id="footer-email"><a href="">Contact Us</a></li>
<li id="footer-twitter"><a href="">Follow Us</a></li>
</ul>
</div>
</code></pre>
<p>and the CSS:</p>
<pre><code>#footer ul {
height: 27px;
}
#footer ul li {
display: inline;
list-style: none;
margin-right: 20px;
}
#footer-tmdb {
background: url('../images/logo-tmdb.png') no-repeat 0 0;
padding-left: 140px;
}
#footer-email {
background: url('../images/icon-email.png') no-repeat 0 3px;
padding-left: 40px;
}
#footer-twitter {
background: url('../images/icon-twitter.png') no-repeat 0 0;
padding-left: 49px;
}
</code></pre>
<p>Here's what it looks like:
<img src="https://i.stack.imgur.com/uXVVH.jpg" alt="footer"></p>
<p>As you can see, half of the images are cut off.</p>
<p>The simpler the solution, the better, please.</p> | 5,953,378 | 4 | 2 | null | 2011-05-10 16:29:26.047 UTC | null | 2011-05-10 16:37:46.887 UTC | 2011-05-10 16:34:31.32 UTC | null | 311,941 | null | 2,089,192 | null | 1 | 4 | css | 42,268 | <pre><code>#footer ul li {
display: block;
float: left;
height: 27px;
list-style: none;
margin-right: 20px;
}
</code></pre> |
6,295,161 | How to build a DataTable from a DataGridView? | <p>I may well be looking at this problem backwards but I am curious none the less. Is there a way to build a <code>DataTable</code> from what is currently displayed in the <code>DataGridView</code>? </p>
<p>To be clear, I know you can do this <code>DataTable data = (DataTable)(dgvMyMembers.DataSource);</code> however that includes hidden columns. I would like to build it from the displayed columns only. </p>
<p>Hope that makes sense.</p>
<hr>
<p>So I ended up trying a combination of a couple of answers as that seemed best. Below is what I am trying. Basically I am creating the DataTable from the DataSource and then working backwards based on if a column is visible or not. However, after it removes a column I get a <code>Collection was modified; enumeration operation may not execute</code> on the next iteration of the <code>foreach</code>. </p>
<p>I am confused as I am not <strong><em>trying</em></strong> to modify the <code>DataGridView</code>, only the <code>DataTable</code> so what's up?</p>
<pre><code>DataTable data = GetDataTableFromDGV(dgvMyMembers);
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = ((DataTable)dgv.DataSource).Copy();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible)
{
dt.Columns.Remove(column.Name);
}
}
return dt;
}
</code></pre> | 6,295,819 | 4 | 1 | null | 2011-06-09 15:16:56.21 UTC | 3 | 2018-03-18 08:08:38.263 UTC | 2011-06-10 15:27:50.507 UTC | null | 46,724 | null | 46,724 | null | 1 | 16 | c#|.net|datagridview|datatable | 111,206 | <p>Well, you can do </p>
<pre><code>DataTable data = (DataTable)(dgvMyMembers.DataSource);
</code></pre>
<p>and then use </p>
<pre><code>data.Columns.Remove(...);
</code></pre>
<p>I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that <code>DataGridView.DataSource</code> is not necessarily of <code>DataTable</code> type.</p> |
5,714,117 | Errors using rspec, missing libraries after installing Homebrew and uninstalling MacPorts | <p>I may have taken one step too far beyond my knowledge. I installed <a href="https://en.wikipedia.org/wiki/Homebrew_%28package_management_software%29" rel="nofollow">Homebrew</a> and after it continued to give me warnings about having <a href="http://en.wikipedia.org/wiki/MacPorts" rel="nofollow">MacPorts</a> installed I uninstalled that. But now my rspec tests don't run.</p>
<p>These are the errors I get:</p>
<pre><code>/Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri.rb:13:in `require': dlopen(/Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle, 9): Library not loaded: /opt/local/lib/libiconv.2.dylib (LoadError)
Referenced from: /Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle
Reason: Incompatible library version: nokogiri.bundle requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0 - /Users/mark/.rvm/gems/ruby-1.9.2-p180/gems/nokogiri-1.4.4/lib/nokogiri/nokogiri.bundle
.....
.....
</code></pre>
<p>I've installed libiconv through Homebrew, but that didn't fix it. It's complaining about libiconv version numbers. Is this the problem?</p>
<p>What is going on here and what do I need to do?</p> | 5,783,919 | 4 | 1 | null | 2011-04-19 09:14:17.613 UTC | 3 | 2016-02-18 20:38:47.107 UTC | 2016-02-18 20:36:27.423 UTC | null | 63,550 | null | 334,304 | null | 1 | 35 | nokogiri|rsync|macports|homebrew|libiconv | 5,969 | <p>I got things working again for anyone interested. I removed and re-installed nokogiri gem and everything seems to be working again.</p> |
6,272,702 | should Modernizr file be placed in head? | <p>Should the reference to the Modernizr JavaScript file be in the head of the page? I always try and place all scripts on the bottom of the page and would like to preserve this. And if it needs to be in the head, why?</p> | 6,272,728 | 4 | 0 | null | 2011-06-07 23:24:38.193 UTC | 15 | 2015-04-22 20:20:21.27 UTC | 2015-04-22 20:20:21.27 UTC | null | 55,965 | null | 373,674 | null | 1 | 63 | javascript|modernizr|html-head | 32,360 | <p>If you want <a href="http://www.modernizr.com/" rel="noreferrer">Modernizr</a> to download and execute as soon as possible to prevent a <a href="http://en.wikipedia.org/wiki/Flash_of_unstyled_content" rel="noreferrer">FOUC</a>, put it in the <code><head></code></p>
<p>From their <a href="http://www.modernizr.com/docs/#installing" rel="noreferrer">installation guide</a>:</p>
<blockquote>
<p>Drop the script tags in the <code><head></code> of
your HTML. For best performance, you
should have them follow after your
stylesheet references. The reason we
recommend placing Modernizr in the
head is two-fold: the HTML5 Shiv (that
enables HTML5 elements in IE) must
execute before the <code><body></code>, and if
you’re using any of the CSS classes
that Modernizr adds, you’ll want to
prevent a FOUC.</p>
</blockquote> |
1,940,528 | Django index page best/most common practice | <p>I am working on a site currently (first one solo) and went to go make an index page. I have been attempting to follow django best practices as I go, so naturally I go search for this but couldn't a real standard in regards to this.</p>
<p>I have seen folks creating apps to serve this purpose named various things (main, home, misc) and have seen a views.py in the root of the project. I am really just looking for what the majority out there do for this.</p>
<p>The index page is not static, since I want to detect if the user is logged in and such.</p>
<p>Thanks.</p> | 1,940,720 | 2 | 0 | null | 2009-12-21 14:51:08.237 UTC | 10 | 2009-12-21 15:33:37.277 UTC | null | null | null | null | 230,614 | null | 1 | 21 | python|django|indexing | 12,381 | <p>If all of your dynamic content is handled in the template (for example, if it's just simple checking if a user is present on the request), then I recommend using a generic view, specificially the <a href="http://docs.djangoproject.com/en/1.1/ref/generic-views/#django-views-generic-simple-direct-to-template" rel="noreferrer">direct to template</a> view:</p>
<pre><code>urlpatterns = patterns('django.views.generic.simple',
(r'^$', 'direct_to_template', {'template': 'index.html'}),
)
</code></pre>
<p>If you want to add a few more bits of information to the template context, there is another argument, <code>extra_context</code>, that you can pass to the generic view to include it:</p>
<pre><code>extra_context = {
'foo': 'bar',
# etc
}
urlpatterns = patterns('django.views.generic.simple',
(r'^$', 'direct_to_template', {'template': 'index.html', 'extra_context': extra_context }),
)
</code></pre> |
19,615,760 | Groupby with User Defined Functions Pandas | <p>I understand that passing a function as a group key calls the function once per index value with the return values being used as the group names. What I can't figure out is how to call the function on column values. </p>
<p>So I can do this:</p>
<pre><code>people = pd.DataFrame(np.random.randn(5, 5),
columns=['a', 'b', 'c', 'd', 'e'],
index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
def GroupFunc(x):
if len(x) > 3:
return 'Group1'
else:
return 'Group2'
people.groupby(GroupFunc).sum()
</code></pre>
<p>This splits the data into two groups, one of which has index values of length 3 or less, and the other with length three or more. But how can I pass one of the column values? So for example if column d value for each index point is greater than 1. I realise I could just do the following:</p>
<pre><code>people.groupby(people.a > 1).sum()
</code></pre>
<p>But I want to know how to do this in a user defined function for future reference. </p>
<p>Something like: </p>
<pre><code>def GroupColFunc(x):
if x > 1:
return 'Group1'
else:
return 'Group2'
</code></pre>
<p>But how do I call this?
I tried </p>
<pre><code>people.groupby(GroupColFunc(people.a))
</code></pre>
<p>and similar variants but this does not work.</p>
<p>How do I pass the column values to the function?
How would I pass multiple column values e.g. to group on whether people.a > people.b for example?</p> | 19,616,072 | 1 | 0 | null | 2013-10-27 07:41:51.357 UTC | 13 | 2018-12-11 06:32:11.963 UTC | 2018-12-11 06:32:11.963 UTC | null | 2,745,140 | null | 2,484,720 | null | 1 | 35 | python|pandas | 25,905 | <p>To group by a > 1, you can define your function like:</p>
<pre><code>>>> def GroupColFunc(df, ind, col):
... if df[col].loc[ind] > 1:
... return 'Group1'
... else:
... return 'Group2'
...
</code></pre>
<p>An then call it like</p>
<pre><code>>>> people.groupby(lambda x: GroupColFunc(people, x, 'a')).sum()
a b c d e
Group2 -2.384614 -0.762208 3.359299 -1.574938 -2.65963
</code></pre>
<p>Or you can do it only with anonymous function:</p>
<pre><code>>>> people.groupby(lambda x: 'Group1' if people['b'].loc[x] > people['a'].loc[x] else 'Group2').sum()
a b c d e
Group1 -3.280319 -0.007196 1.525356 0.324154 -1.002439
Group2 0.895705 -0.755012 1.833943 -1.899092 -1.657191
</code></pre>
<p>As said in <a href="http://pandas.pydata.org/pandas-docs/dev/groupby.html" rel="noreferrer">documentation</a>, you can also group by passing Series providing a label -> group name mapping:</p>
<pre><code>>>> mapping = np.where(people['b'] > people['a'], 'Group1', 'Group2')
>>> mapping
Joe Group2
Steve Group1
Wes Group2
Jim Group1
Travis Group1
dtype: string48
>>> people.groupby(mapping).sum()
a b c d e
Group1 -3.280319 -0.007196 1.525356 0.324154 -1.002439
Group2 0.895705 -0.755012 1.833943 -1.899092 -1.657191
</code></pre> |
2,465,675 | Custom keys for Google App Engine models (Python) | <p>First off, I'm relatively new to Google App Engine, so I'm probably doing something silly.</p>
<p>Say I've got a model Foo:</p>
<pre><code>class Foo(db.Model):
name = db.StringProperty()
</code></pre>
<p>I want to use <code>name</code> as a unique key for every <code>Foo</code> object. How is this done?</p>
<p>When I want to get a specific <code>Foo</code> object, I currently query the datastore for all <code>Foo</code> objects with the target unique name, but queries are slow (plus it's a pain to ensure that <code>name</code> is unique when each new <code>Foo</code> is created).</p>
<p>There's got to be a better way to do this!</p>
<p>Thanks.</p> | 2,466,007 | 2 | 0 | null | 2010-03-17 20:34:22.01 UTC | 11 | 2010-12-25 15:30:05.41 UTC | 2010-12-25 15:30:05.41 UTC | null | 21,475 | null | 21,475 | null | 1 | 12 | python|google-app-engine|google-cloud-datastore|primary-key | 4,308 | <p>I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required.</p>
<pre><code>class NamedModel(db.Model):
"""A Model subclass for entities which automatically generate their own key
names on creation. See documentation for _generate_key function for
requirements."""
def __init__(self, *args, **kwargs):
kwargs['key_name'] = _generate_key(self, kwargs)
super(NamedModel, self).__init__(*args, **kwargs)
def _generate_key(entity, kwargs):
"""Generates a key name for the given entity, which was constructed with
the given keyword args. The entity must have a KEY_NAME property, which
can either be a string or a callable.
If KEY_NAME is a string, the keyword args are interpolated into it. If
it's a callable, it is called, with the keyword args passed to it as a
single dict."""
# Make sure the class has its KEY_NAME property set
if not hasattr(entity, 'KEY_NAME'):
raise RuntimeError, '%s entity missing KEY_NAME property' % (
entity.entity_type())
# Make a copy of the kwargs dict, so any modifications down the line don't
# hurt anything
kwargs = dict(kwargs)
# The KEY_NAME must either be a callable or a string. If it's a callable,
# we call it with the given keyword args.
if callable(entity.KEY_NAME):
return entity.KEY_NAME(kwargs)
# If it's a string, we just interpolate the keyword args into the string,
# ensuring that this results in a different string.
elif isinstance(entity.KEY_NAME, basestring):
# Try to create the key name, catching any key errors arising from the
# string interpolation
try:
key_name = entity.KEY_NAME % kwargs
except KeyError:
raise RuntimeError, 'Missing keys required by %s entity\'s KEY_NAME '\
'property (got %r)' % (entity.entity_type(), kwargs)
# Make sure the generated key name is actually different from the
# template
if key_name == entity.KEY_NAME:
raise RuntimeError, 'Key name generated for %s entity is same as '\
'KEY_NAME template' % entity.entity_type()
return key_name
# Otherwise, the KEY_NAME is invalid
else:
raise TypeError, 'KEY_NAME of %s must be a string or callable' % (
entity.entity_type())
</code></pre>
<p>You could then modify your example model like so:</p>
<pre><code>class Foo(NamedModel):
KEY_NAME = '%(name)s'
name = db.StringProperty()
</code></pre>
<p>Of course, this could be dramatically simplified in your case, changing the first line of the <code>NamedModel</code>'s <code>__init__</code> method to something like:</p>
<pre><code>kwargs['key_name'] = kwargs['name']
</code></pre> |
41,194,726 | python generator thread safety using Keras | <p>I am using Keras for some ML and have this generator for the data and labels:</p>
<pre><code>def createBatchGenerator(driving_log,batch_size=32):
batch_images = np.zeros((batch_size, 66, 200, 3))
batch_steering = np.zeros(batch_size)
while 1:
for i in range(batch_size):
x,y = get_preprocessed_row(driving_log)
batch_images[i]=x
batch_steering[i]=y
yield batch_images, batch_steering
</code></pre>
<p>When I use it locally it runs fine, but when I run it on an AWS g2.2xlarge with a GPU, I get this error "ValueError: generator already executing". Can someone please help me resolve this?</p> | 41,645,042 | 1 | 0 | null | 2016-12-17 02:07:40.267 UTC | 8 | 2018-01-01 23:01:04.223 UTC | null | null | null | null | 1,628,347 | null | 1 | 17 | python|generator | 10,326 | <p>You need to make a <a href="http://anandology.com/blog/using-iterators-and-generators/" rel="noreferrer">generator that can support multi-threading</a> to make sure the generator is called by two threads at once:</p>
<pre><code>import threading
class createBatchGenerator:
def __init__(self, driving_log,batch_size=32):
self.driving_log = driving_log
self.batch_size = batch_size
self.lock = threading.Lock()
def __iter__(self):
return self
def __next__(self):
with self.lock:
batch_images = np.zeros((batch_size, 66, 200, 3))
batch_steering = np.zeros(batch_size)
for i in range(self.batch_size):
x,y = get_preprocessed_row(self.driving_log)
batch_images[i]=x
batch_steering[i]=y
return batch_images, batch_steering
</code></pre> |
52,737,078 | How can you use axios interceptors? | <p>I have seen axios documentation, but all it says is</p>
<pre><code>// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
</code></pre>
<p>Also many tutorials only show this code but I am confused what it is used for, can someone please give me simple example to follow.</p> | 52,737,325 | 7 | 0 | null | 2018-10-10 09:35:57.5 UTC | 55 | 2022-09-20 14:23:39.417 UTC | 2018-10-10 10:21:42.693 UTC | null | 3,076,424 | null | 7,563,926 | null | 1 | 142 | javascript|axios | 197,947 | <p>To talk in simple terms, it is more of a checkpoint for every HTTP action. Every API call that has been made, is passed through this interceptor.</p>
<p><strong>So, why two interceptors?</strong></p>
<p>An API call is made up of two halves, a request, and a response. Since it behaves like a checkpoint, the request and the response have separate interceptors.</p>
<p><strong>Some request interceptor use cases -</strong></p>
<p>Assume you want to check before making a request if your credentials are valid. So, instead of actually making an API call, you can check at the interceptor level that your credentials are valid.</p>
<p>Assume you need to attach a token to every request made, instead of duplicating the token addition logic at every Axios call, you can make an interceptor that attaches a token on every request that is made.</p>
<p><strong>Some response interceptor use cases -</strong></p>
<p>Assume you got a response, and judging by the API responses you want to deduce that the user is logged in. So, in the response interceptor, you can initialize a class that handles the user logged in state and update it accordingly on the response object you received.</p>
<p>Assume you have requested some API with valid API credentials, but you do not have the valid role to access the data. So, you can trigger an alert from the response interceptor saying that the user is not allowed. This way you'll be saved from the unauthorized API error handling that you would have to perform on every Axios request that you made.</p>
<p>Here are some code examples</p>
<p><strong>The request interceptor</strong></p>
<ul>
<li><p>One can print the configuration object of axios (if need be) by doing (in this case, by checking the environment variable):</p>
<pre class="lang-js prettyprint-override"><code>const DEBUG = process.env.NODE_ENV === "development";
axios.interceptors.request.use((config) => {
/** In dev, intercepts request and logs it into console for dev */
if (DEBUG) { console.info("✉️ ", config); }
return config;
}, (error) => {
if (DEBUG) { console.error("✉️ ", error); }
return Promise.reject(error);
});
</code></pre>
</li>
<li><p>If one wants to check what headers are being passed/add any more generic headers, it is available in the <code>config.headers</code> object. For example:</p>
<pre class="lang-js prettyprint-override"><code>axios.interceptors.request.use((config) => {
config.headers.genericKey = "someGenericValue";
return config;
}, (error) => {
return Promise.reject(error);
});
</code></pre>
</li>
<li><p>In case it's a <code>GET</code> request, the query parameters being sent can be found in <code>config.params</code> object.</p>
</li>
</ul>
<p><strong>The response interceptor</strong></p>
<ul>
<li><p>You can even <strong>optionally</strong> parse the API response at the interceptor level and pass the parsed response down instead of the original response. It might save you the time of writing the parsing logic again and again in case the API is used in the same way in multiple places. One way to do that is by passing an extra parameter in the <code>api-request</code> and use the same parameter in the response interceptor to perform your action. For example:</p>
<pre class="lang-js prettyprint-override"><code>//Assume we pass an extra parameter "parse: true"
axios.get("/city-list", { parse: true });
</code></pre>
<p>Once, in the response interceptor, we can use it like:</p>
<pre class="lang-js prettyprint-override"><code>axios.interceptors.response.use((response) => {
if (response.config.parse) {
//perform the manipulation here and change the response object
}
return response;
}, (error) => {
return Promise.reject(error.message);
});
</code></pre>
<p>So, in this case, whenever there is a <code>parse</code> object in <code>response.config</code>, the manipulation is done, for the rest of the cases, it'll work as-is.</p>
</li>
<li><p>You can even view the arriving <code>HTTP</code> codes and then make the decision. For example:</p>
<pre class="lang-js prettyprint-override"><code>axios.interceptors.response.use((response) => {
if(response.status === 401) {
alert("You are not authorized");
}
return response;
}, (error) => {
if (error.response && error.response.data) {
return Promise.reject(error.response.data);
}
return Promise.reject(error.message);
});
</code></pre>
</li>
</ul> |
39,597,925 | How do I set environment variables during the build in docker | <p>I'm trying to set environment variables in docker container during the build but without success. Setting them when using run command works but I need to set them during the build.</p>
<p>Dockerfile</p>
<pre><code>FROM ubuntu:latest
ARG TEST_ENV=something
</code></pre>
<p>Command I'm using to build</p>
<pre><code>docker build -t --build-arg TEST_ENV="test" myimage .
</code></pre>
<p>Running</p>
<pre><code>docker run -dit myimage
</code></pre>
<p>I'm checking available environment variables by using</p>
<pre><code>docker exec containerid printenv
</code></pre>
<p>and the result is</p>
<pre><code>PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=e49c1abfd58b
TERM=xterm
no_proxy=*.local, 169.254/16
HOME=/root
</code></pre>
<p>TEST_ENV is not present</p> | 39,598,751 | 2 | 0 | null | 2016-09-20 15:20:39.973 UTC | 37 | 2021-03-30 07:24:53.907 UTC | null | null | null | null | 6,599,814 | null | 1 | 184 | docker|dockerfile | 236,584 | <p><code>ARG</code> is for setting environment variables which are used during the <code>docker build</code> process - they are not present in the final image, which is why you don't see them when you use <code>docker run</code>.</p>
<p>You use <code>ARG</code> for settings that are only relevant when the image is being built, and aren't needed by containers which you run from the image. You can use <code>ENV</code> for environment variables to use during the build and in containers.</p>
<p>With this Dockerfile:</p>
<pre><code>FROM ubuntu
ARG BUILD_TIME=abc
ENV RUN_TIME=123
RUN touch /env.txt
RUN printenv > /env.txt
</code></pre>
<p>You can override the build arg as you have done with <code>docker build -t temp --build-arg BUILD_TIME=def .</code>. Then you get what you expect:</p>
<pre><code>> docker run temp cat /env.txt
HOSTNAME=b18b9cafe0e0
RUN_TIME=123
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
BUILD_TIME=def
PWD=/
</code></pre> |
33,176,336 | Need an example about RecyclerView.Adapter.notifyItemChanged(int position, Object payload) | <p>According to <code>RecyclerView</code> documentation about medthod <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyItemChanged(int,%20java.lang.Object)" rel="noreferrer">notifyItemChanged(int position, Object payload)</a> </p>
<blockquote>
<p>Notify any registered observers that the item at position has changed with an optional payload object.</p>
</blockquote>
<p>I don't understand how to use second paramenter <code>payload</code> in this method. I have searched many document about "payload" but everything was ambiguous.</p>
<p>So, If you know about this method, please show me a clear example about it. Thank you very much.</p> | 33,968,779 | 4 | 0 | null | 2015-10-16 17:34:19.73 UTC | 17 | 2019-04-12 09:42:32.88 UTC | 2018-07-31 06:48:32.08 UTC | null | 1,551,475 | null | 5,192,252 | null | 1 | 73 | android|android-recyclerview|payload | 58,175 | <p>Check out this sample code that demonstrates the feature. It's a <code>RecyclerView</code> that calls <code>notifyItemChanged(position, payload)</code> when the item at position <code>position</code> is clicked. You can verify that <code>onBindViewHolder(holder, position, payload)</code> was called by looking for the logcat statement.</p>
<p>Make sure you are using at least version <code>23.1.1</code> of the support libraries, like so:</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
}
</code></pre>
<p>HelloActivity.java</p>
<pre><code>package com.formagrid.hellotest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class HelloActivity extends Activity {
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mRecyclerView.setAdapter(new HelloAdapter());
DefaultItemAnimator animator = new DefaultItemAnimator() {
@Override
public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
return true;
}
};
mRecyclerView.setItemAnimator(animator);
}
private static class HelloAdapter extends RecyclerView.Adapter<HelloAdapter.HelloViewHolder> {
public class HelloViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public HelloViewHolder(CardView cardView) {
super(cardView);
textView = (TextView) cardView.findViewById(R.id.text_view);
}
}
@Override
public HelloViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CardView cardView = (CardView) LayoutInflater.from(parent.getContext()).inflate(
R.layout.card_item, parent, false);
return new HelloViewHolder(cardView);
}
@Override
public void onBindViewHolder(HelloViewHolder holder, int position) {
bind(holder);
}
@Override
public void onBindViewHolder(HelloViewHolder holder, int position, List<Object> payload) {
Log.d("butt", "payload " + payload.toString());
bind(holder);
}
@Override
public int getItemCount() {
return 20;
}
private void bind(final HelloViewHolder holder) {
holder.textView.setText("item " + holder.getAdapterPosition());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
Log.d("butt", "click " + position);
HelloAdapter.this.notifyItemChanged(position, "payload " + position);
}
});
}
}
}
</code></pre>
<p>activity_main.xml</p>
<pre><code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".HelloActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</code></pre>
<p>card_item.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="100dip"
android:layout_margin="5dip"
card_view:cardElevation="5dip">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v7.widget.CardView>
</code></pre> |
38,390,177 | What is a NoReverseMatch error, and how do I fix it? | <p>I have some code and when it executes, it throws a NoReverseMatch, saying:</p>
<blockquote>
<p>NoReverseMatch at /my_url/ Reverse for 'my_url_name' with arguments '()' and keyword arguments '{}' not found. n pattern(s) tried: []</p>
</blockquote>
<p>What does this mean, and what can I do about it?</p> | 38,390,178 | 5 | 0 | null | 2016-07-15 07:22:59.38 UTC | 68 | 2022-03-11 11:16:27.43 UTC | null | null | null | null | 1,324,033 | null | 1 | 154 | django|django-urls | 190,040 | <p>The <a href="https://docs.djangoproject.com/en/dev/ref/exceptions/#noreversematch" rel="noreferrer"><code>NoReverseMatch</code></a> error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.</p>
<blockquote>
<p>The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.</p>
</blockquote>
<p>To start debugging it, you need to start by disecting the error message given to you.</p>
<ul>
<li><p>NoReverseMatch at /my_url/</p>
<p>This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched</p>
</li>
<li><p>Reverse for 'my_url_name'</p>
<p>This is the name of the url that it cannot find</p>
</li>
<li><p>with arguments '()' and</p>
<p>These are the non-keyword arguments its providing to the url</p>
</li>
<li><p>keyword arguments '{}' not found.</p>
<p>These are the keyword arguments its providing to the url</p>
</li>
<li><p>n pattern(s) tried: []</p>
<p>These are the patterns that it was able to find in your urls.py files that it tried to match against</p>
</li>
</ul>
<p>Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.</p>
<p>Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your <code>my_url_name</code>. Again, this is probably in a place you've recently changed.</p>
<p>Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.</p>
<h2>The url name</h2>
<ul>
<li>Are there any typos?</li>
<li>Have you provided the url you're trying to access the given name?</li>
<li>If you have set app_name in the app's <code>urls.py</code> (e.g. <code>app_name = 'my_app'</code>) or if you included the app with a namespace (e.g. <code>include('myapp.urls', namespace='myapp')</code>, then you need to include the namespace when reversing, e.g. <code>{% url 'myapp:my_url_name' %}</code> or <code>reverse('myapp:my_url_name')</code>.</li>
</ul>
<h2>Arguments and Keyword Arguments</h2>
<p>The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding <code>()</code> brackets in the url pattern.</p>
<p>Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.</p>
<p>If they aren't correct:</p>
<ul>
<li><p>The value is missing or an empty string</p>
<p>This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.</p>
</li>
<li><p>The keyword argument has a typo</p>
<p>Correct this either in the url pattern, or in the url you're constructing.</p>
</li>
</ul>
<p>If they are correct:</p>
<ul>
<li><p>Debug the regex</p>
<p>You can use a website such as <a href="http://regexr.com/" rel="noreferrer">regexr</a> to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.</p>
<p>Common Mistakes:</p>
<ul>
<li><p>Matching against the <code>.</code> wild card character or any other regex characters</p>
<p>Remember to escape the specific characters with a <code>\</code> prefix</p>
</li>
<li><p>Only matching against lower/upper case characters</p>
<p>Try using either <code>a-Z</code> or <code>\w</code> instead of <code>a-z</code> or <code>A-Z</code></p>
</li>
</ul>
</li>
<li><p>Check that pattern you're matching is included within the patterns tried</p>
<p>If it isn't here then its possible that you have forgotten to include your app within the <code>INSTALLED_APPS</code> setting (or the ordering of the apps within <code>INSTALLED_APPS</code> may need looking at)</p>
</li>
</ul>
<h2>Django Version</h2>
<p>In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.</p>
<hr />
<p>If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the <code>INSTALLED_APPS</code> setting if applicable.</p> |
41,665,902 | how do I style an Alert element in react-native? | <p>I'm working with react-native and I have created an Alert element.</p>
<pre><code>Alert.alert(
'Warning',
'bla bla bla',
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
]
)
</code></pre>
<p>Now I'd like to apply some style to it. Let's say I want to apply to it a red background color and white color for the text.</p>
<p>How can I achieve this? Is it possible?</p> | 41,674,279 | 4 | 0 | null | 2017-01-15 20:25:34.233 UTC | 1 | 2020-01-13 22:28:16.71 UTC | null | null | null | null | 4,188,968 | null | 1 | 27 | reactjs|react-native | 88,325 | <p>You can use a custom library like <a href="https://github.com/maxs15/react-native-modalbox" rel="noreferrer">react-native-modalbox</a>.</p>
<p>You'll be able to style the modal as you like:</p>
<pre><code> <Modal style={{background: 'red'}} ref={"modal1"}>
<Text style={{color: 'white'}}>Basic modal</Text>
<Button onPress={this.toggleSwipeToClose} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
</Modal>
</code></pre>
<p>You can open the modal using</p>
<pre><code>openModal1(id) {
this.refs.modal1.open();
}
</code></pre>
<p>Check out <a href="https://github.com/maxs15/react-native-modalbox/blob/master/Example/index.ios.js" rel="noreferrer">the example</a> to see more options.</p>
<p><strong>Bonus</strong>: If you want to find a good library for react-native, try <a href="https://js.coach/react-native" rel="noreferrer">js.coach</a></p> |
41,446,362 | Hide columns in bootstrap table at startup | <p>I have the following table, where I use <code>Bootstrap-table</code></p>
<pre><code><div class="row mystyle" >
<div class="col-md-12">
<table id="mytable" data-row-style="rowStyle" class="table table-hover" id="table-pagination "
data-url="labels.json"
data-toggle="table"
data-pagination="true"
data-show-pagination-switch="true"
data-sort-order="desc"
data-search="true"
data-show-refresh="true"
data-show-columns="true"
data-page-list="[10, 25, 50, 100, ALL]"
>
<thead>
<tr>
<th data-field="customer.name" data-align="center" data-sortable="true">customer</th>
<th data-field="type" data-align="center" data-sortable="true">type</th>
<th data-field="description" data-align="center" data-sortable="true">description</th>
<th data-field="cutter" data-align="center" data-sortable="true">cutter</th>
<th data-field="valid_s" data-align="center" data-sortable="true">valid</th>
</tr>
</thead>
</table>
</div>
</div>
</code></pre>
<p>Is there a way to define which columns will be hidden at startup? For example, I want to show only <code>customer</code> and <code>description</code> column.</p> | 41,539,875 | 7 | 0 | null | 2017-01-03 15:01:30.137 UTC | 3 | 2021-04-29 22:40:13.07 UTC | 2017-06-12 16:20:48.863 UTC | null | 4,281,779 | null | 2,594,961 | null | 1 | 20 | twitter-bootstrap|bootstrap-table | 55,347 | <p>You can use <code>data-visible="false"</code>:</p>
<pre><code><thead>
<tr>
<th data-field="customer.name" data-align="center" data-sortable="true">customer</th>
<th data-field="type" data-align="center" data-sortable="true" data-visible="false">type</th>
<th data-field="description" data-align="center" data-sortable="true">description</th>
<th data-field="cutter" data-align="center" data-sortable="true" data-visible="false">cutter</th>
<th data-field="valid_s" data-align="center" data-sortable="true" data-visible="false">valid</th>
</tr>
</thead>
</code></pre> |
41,301,627 | How to update git commit author, but keep original date when amending? | <p>If the commits are already made and pushed to the repository, and if want to change an author for some particular commit I can do it like this:</p>
<pre><code>git commit --amend --reset-author
</code></pre>
<p>But, that will change the original committed date.</p>
<p>How can I reset author, but keep the original committer date?</p> | 41,303,384 | 6 | 0 | null | 2016-12-23 12:33:35.733 UTC | 15 | 2022-08-11 01:23:57.78 UTC | null | null | null | null | 1,612,469 | null | 1 | 19 | git | 9,571 | <p>Hm, at the end, I have found a bit easier solution for me. I have created a script in directory containing the git project <code>gitrewrite.sh</code>, and modified its permissions so it could be exectured:</p>
<pre><code>$ chmod 700 gitrewrite.sh
</code></pre>
<p>Then I placed in the shell script:</p>
<pre><code>#!/bin/sh
git filter-branch --env-filter '
NEW_NAME="MyName"
NEW_EMAIL="[email protected]"
if [ "$GIT_COMMIT" = "afdkjh1231jkh123hk1j23" ] || [ "$GIT_COMMIT" = "43hkjwldfpkmsdposdfpsdifn" ]
then
export GIT_COMMITTER_NAME="$NEW_NAME"
export GIT_COMMITTER_EMAIL="$NEW_EMAIL"
export GIT_AUTHOR_NAME="$NEW_NAME"
export GIT_AUTHOR_EMAIL="$NEW_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
</code></pre>
<p>And then run the script in terminal:</p>
<pre><code>$ ./gitrewrite.sh
</code></pre>
<p>And that's it. The history has been rewritten.</p>
<p>Push the code to the repository and add a <code>force</code> flag.</p>
<p><code>$ git push -f</code></p>
<p><strong>Important note:</strong></p>
<p>For the others reading it, keep in mind that this is going to create new references in the git history so do this only in private repository or the one which is still not shared with others as it could cause broken references!</p>
<p>Mine was a private repo, so no worries there for that part. If it is public, then perhaps using the other suggested answer could be a better option.</p> |
1,667,720 | HTTP, 408 Request timeout | <p>I have an application, written in C++.
This app dispatches a certain info to a script located on a remote website using HTTP POST requests. The app sends requests with a period from several seconds to several minutes.</p>
<p>The problem is that after about a half an hour of working without errors, the app starts to get a 408 Request timeout error from the web server. Then the app starts to retry posting but the server keeps on responding with 408 Request timeout.</p>
<p>An interesting observation: the error disappears after I access the website using a browser and the app works OK for about 30 minutes after that, then the issue comes back.</p>
<p>What could be the reason and is there any workaround to this?</p>
<p>PS: the app works on a usual PC with XP Workstation. The website is on GoDaddy web server.</p>
<p>thanks in advance</p> | 12,069,718 | 1 | 3 | null | 2009-11-03 14:38:06.843 UTC | 4 | 2015-03-29 17:36:20.897 UTC | 2015-03-29 17:36:20.897 UTC | null | 201,751 | null | 201,751 | null | 1 | 21 | http|http-status-code-408 | 47,449 | <p>I know this is an old post but thought this might help someone since this problem cause me hours of frustration.</p>
<p>I was experiencing the same issue with a GoDaddy webserver. My Android app sent POST requests to the server and would work as expected but I started experiencing 408 Request timeout errors after 30 mins or so. I also noticed that the problem went away if I opened up a browser and opened my home page (PHP Wordpress site) from a PC or the Android device. The website was in test so web traffic was minimal and I was able to confirm this behaviour in the server logs fairly easily.</p>
<p>I logged a support call to GoDaddy but whilst their staff were responsive and helpful, they did not provide any useful information to explain the behaviour.</p>
<p>I was however able to work around the issue by simply executing a dummy GET request before my POST request and this 'woke up' the web server and it responded to all subsequent POST requests.</p> |
21,695,520 | -tsa or -tsacert timestamp for applet jar self-signed | <p>When I was trying to self-sign in the jar like below.</p>
<pre><code>jarsigner -keystore my keystore myjar.jar myalias
</code></pre>
<p>It gives warning like:</p>
<blockquote>
<p>No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not be able to validate this jar after the signer certificate's expiration date (2014-05-08) or after any future revocation date.</p>
</blockquote>
<p>Please help to resolve the problem.</p> | 24,178,906 | 4 | 0 | null | 2014-02-11 07:18:35.727 UTC | 10 | 2018-07-19 21:44:48.513 UTC | 2014-07-25 14:15:30.05 UTC | null | 334,493 | null | 998,676 | null | 1 | 50 | java|jar|applet|signed-applet | 37,717 | <p>The recent Java 7 provides a (courtesy?) warning about something which has been in place for a decade...</p>
<p>Trusted Timestamping was introducing in Java 5 (2004). The motivation was so that developers would not be forced "to re-sign deployed JAR files annually" when the certificates expired.</p>
<p>→ <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/security/time-of-signing.html" rel="noreferrer">http://docs.oracle.com/javase/1.5.0/docs/guide/security/time-of-signing.html</a><br></p>
<p>A URL-based Time Stamp Authority (TSA) is usually provided by the issuing Certificate Authority (CA) <strong>to work with the same certificates</strong> the CA issued. For example, the digicert tsa url can be access as follows: </p>
<p><code>jarsigner -tsa http://timestamp.digicert.com [.. other options]</code></p>
<p>→ <a href="http://www.digicert.com/code-signing/java-code-signing-guide.htm" rel="noreferrer">http://www.digicert.com/code-signing/java-code-signing-guide.htm</a></p>
<p>Time stamping with self-signed certificate <em>may be</em> an elusive goal since (1) a TSA timestamp needs to be an trusted arms-length transaction (which rules out "self timestamping"), and (2) typical TSA URLs are setup to work with the certificates provided by the same CA organization (i.e. the TSA URL does not process a self-signed certificate)</p>
<p><strong>Update:</strong> </p>
<p>URLs to try for timestamping self-signed certificates:</p>
<ul>
<li>Symantec: <code>-tsa http://sha256timestamp.ws.symantec.com/sha256/timestamp</code> (per comment by brad-turek)</li>
</ul>
<p><em>For a private network, one could consider an internal Timestamp Authority such as such as Thales (nCipher) Time Stamp Server (or historically OpenTSA)</em> </p> |
39,983,391 | Adding Folder to Xcode Project is not Properly added | <p>Team,</p>
<p>I created the new Project, on project folder right click open show in finder there I created "ViewControllers" Folder and again right click Add files to "ProjectName" then I added the created folder i.e., "ViewControllers" which is in blue colour "Expected yellow colour folder" that is reference to my project folder the blue colour folder is not.
In blue colour folder when i try to added new file its added an empty File.</p>
<p>How can i reference my added folder to the Xcode project?
how to avoid this blue colour folder class in my project?</p>
<p>Your inputs are highly appreciable.</p> | 39,984,526 | 2 | 0 | null | 2016-10-11 17:43:46.977 UTC | 3 | 2021-02-28 13:48:37.203 UTC | 2016-10-11 17:58:35.523 UTC | null | 1,226,963 | null | 406,457 | null | 1 | 20 | xcode|reference|directory|project | 128,332 | <p>If your Xcode project looks like this…</p>
<p><a href="https://i.stack.imgur.com/dUSxU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dUSxU.png" alt="Xcode project with folder reference"></a></p>
<p>…then you've added your <code>ViewControllers</code> folder as folder reference.</p>
<p><strong>To change this folder to a group follow these steps:</strong></p>
<ul>
<li>Right click on <code>ViewControllers</code></li>
<li>Choose <code>Delete</code> in the context menu</li>
<li>Choose <code>Remove Reference</code> in the dialog that popped up. The folder will be removed from your Xcode project but not from the file system.</li>
<li>Then choose <code>Add Files to <YourProjectName>…</code> in the <code>File</code> menu</li>
<li>Find your <code>ViewControllers</code> in the file system</li>
<li>Before clicking <code>Add</code> make sure that the option <code>Create groups</code> is selected</li>
<li>Click <code>Add</code></li>
</ul>
<p>You've added your <code>ViewControllers</code> folder as group:</p>
<p><a href="https://i.stack.imgur.com/0prSF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0prSF.png" alt="Xcode project with folder group"></a></p>
<hr>
<p><strong>Important note regarding Xcode 8:</strong></p>
<p>The option <code>Create groups</code> might not be visible right away. Apple moved this in Xcode 8 to the bottom of the <code>Add Files to…</code> dialog:</p>
<p><a href="https://i.stack.imgur.com/Rz3pn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rz3pn.png" alt="Collapsed options"></a></p>
<p>This reveals the option <code>Create groups</code>:</p>
<p><a href="https://i.stack.imgur.com/LobJt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LobJt.png" alt="Expanded options"></a></p> |
20,504,348 | How to collapse all issues in the Xcode issue navigator | <p>I am porting a huge C++ project to OS X. After my initial compile with Xcode I have multiple errors in many files I want to investigate.</p>
<p>Problem is that the issue navigator shows all files non collapsed after each compile:</p>
<p><img src="https://i.stack.imgur.com/6V1g4.png" width="358"></p>
<p>So I have to collapse all of them by hand (there a a lot of files) after each compile to have an overview of a files which need fixing.</p>
<p>Is there a hotkey or a setting to collapse all files?</p> | 20,504,397 | 3 | 0 | null | 2013-12-10 20:17:35.603 UTC | 10 | 2022-07-06 02:31:12.993 UTC | 2013-12-10 20:29:19.4 UTC | null | 343,340 | null | 783,000 | null | 1 | 49 | xcode|macos | 5,930 | <p><kbd>cmd ⌘</kbd>-click one of the little disclosure triangles to collapse (or expand) all rows.
<a href="https://i.stack.imgur.com/ay9X8l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ay9X8l.png" alt="enter image description here"></a></p> |
20,832,769 | How to obtain the absolute value of numbers? | <p>I have a list of numbers that looks like the one below:</p>
<pre><code>[2, 3, -3, -2]
</code></pre>
<p>How can I obtain a list of values that contain the absolute value of every value in the above list? In this case it would be:</p>
<pre><code>[2, 3, 3, 2]
</code></pre> | 20,832,775 | 3 | 0 | null | 2013-12-30 03:10:10.163 UTC | 2 | 2021-09-28 14:45:32.78 UTC | 2021-09-28 14:45:32.78 UTC | null | 792,066 | null | 2,832,224 | null | 1 | 16 | python | 54,635 | <ol>
<li><p>You can use <a href="http://docs.python.org/2/library/functions.html#abs"><code>abs</code></a> and <a href="http://docs.python.org/2/library/functions.html#map"><code>map</code></a> functions like this</p>
<pre><code>myList = [2,3,-3,-2]
print map(abs, myList)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[2, 3, 3, 2]
</code></pre></li>
<li><p>Or you can use list comprehension like this</p>
<pre><code>[abs(number) for number in myList]
</code></pre></li>
<li><p>Or you can use list comprehension and a simple if else condition like this</p>
<pre><code>[-number if number < 0 else number for number in myList]
</code></pre></li>
</ol> |
18,970,265 | Is there an easy way to stub out time.Now() globally during test? | <p>Part of our code is time sensitive and we need to able to reserve something and then release it in 30-60 seconds etc, which we can just do a <code>time.Sleep(60 * time.Second)</code></p>
<p>I have just implemented time interface and during test use a stubbed implementation of the time interface, similar to <a href="https://groups.google.com/forum/#!topic/golang-nuts/Mkonfn4j4jo" rel="noreferrer">this golang-nuts discussion</a>.</p>
<p>However, <code>time.Now()</code> is called in multiple sites which means we need to pass a variable around to keep track of how much time we have actually slept. </p>
<p>I was wondering if there is an alternative way to stub out <code>time.Now()</code> globally. Maybe making a system call to change the system clock?</p>
<p>Maybe we can write our own time package which basically wraps around the time package but allows us to change it? </p>
<p>Our current implementation works well, I am a go beginner and I am curious to see if anyone has other ideas?</p> | 18,970,352 | 11 | 0 | null | 2013-09-23 22:58:43.29 UTC | 13 | 2022-07-01 06:20:30.46 UTC | 2019-09-06 16:14:17.97 UTC | null | 13,860 | null | 2,521,225 | null | 1 | 75 | unit-testing|go | 69,136 | <p>With implementing a custom interface you <strong>are already on the right way</strong>. I take it you use the following advise from the golang nuts thread you've posted:</p>
<hr>
<pre><code>type Clock interface {
Now() time.Time
After(d time.Duration) <-chan time.Time
}
</code></pre>
<blockquote>
<p>and provide a concrete implementation</p>
</blockquote>
<pre><code>type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func (realClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
</code></pre>
<blockquote>
<p>and a testing implementation. </p>
</blockquote>
<hr>
<p><sup><a href="https://groups.google.com/d/msg/golang-nuts/Mkonfn4j4jo/0ZhWPUwul7gJ" rel="noreferrer">Original</a></sup></p>
<p><strong>Changing the system time while making tests (or in general) is a bad idea</strong>.
You don't know what depends on the system time while executing tests and you don't want to find out the hard way by spending days of debugging into that. Just don't do it.</p>
<p><strong>There is also no way to shadow the time package globally</strong> and doing that would not do
anything more you couldn't do with the interface solution. You can write your own time package
which uses the standard library and provides a function to switch to a mock time library for
testing if it is the time object you need to pass around with the interface solution that is bothering you.</p>
<p>The best way to design and test your code would probably be to make as much code stateless as possible.
Split your functionality in testable, stateless parts. Testing these components separately is much easier then. Also, less side effects means that it is much easier to make the code run concurrently.</p> |
26,607,330 | CSS display none and opacity animation with keyframes not working | <p>I have a very basic piece of HTML with the objective of animating from <code>display: none;</code> to <code>display: block</code> with opacity changing from 0 to 1. </p>
<p>I'm using Chrome browser, which uses the <code>-webkit</code> prefixes as preference and did a <code>-webkit-keyframes</code> transition set to make the animation possible. However, it does not work and just changes the <code>display</code> without fading.</p>
<p>I have a JSFiddle <a href="http://jsfiddle.net/5g4yLcym/" rel="noreferrer">here</a>.</p>
<pre><code><html>
<head>
<style type="text/css">
#myDiv
{
display: none;
opacity: 0;
padding: 5px;
color: #600;
background-color: #CEC;
-webkit-transition: 350ms display-none-transition;
}
#parent:hover>#myDiv
{
opacity: 1;
display: block;
}
#parent
{
background-color: #000;
color: #FFF;
width: 500px;
height: 500px;
padding: 5px;
}
@-webkit-keyframes display-none-transition
{
0% {
display: none;
opacity: 0;
}
1%
{
display: block;
opacity: 0;
}
100%
{
display: block;
opacity: 1;
}
}
</style>
<body>
<div id="parent">
Hover on me...
<div id="myDiv">
Hello!
</div>
</div>
</body>
</head>
</html>
</code></pre> | 26,607,526 | 9 | 0 | null | 2014-10-28 11:35:38.72 UTC | 10 | 2021-09-30 06:16:37.087 UTC | 2016-10-26 15:54:24.523 UTC | null | 5,982,110 | null | 3,476,093 | null | 1 | 23 | html|css|animation | 86,027 | <p>If you are using <code>@keyframes</code> you should use <code>-webkit-animation</code> instead of <code>-webkit-transition</code>. Here is the doc for <code>@keyframes</code> animation: <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations</a>.</p>
<p>See code snippet below:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
background-color: #000;
color: #fff;
width: 500px;
height: 500px;
padding: 5px;
}
.myDiv {
display: none;
opacity: 0;
padding: 5px;
color: #600;
background-color: #cec;
}
.parent:hover .myDiv {
display: block;
opacity: 1;
/* "both" tells the browser to use the above opacity
at the end of the animation (best practice) */
-webkit-animation: display-none-transition 1s both;
animation: display-none-transition 1s both;
}
@-webkit-keyframes display-none-transition {
0% {
opacity: 0;
}
}
@keyframes display-none-transition {
0% {
opacity: 0;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
Hover on me...
<div class="myDiv">Hello!</div>
</div></code></pre>
</div>
</div>
</p>
<hr>
<h2>2016 UPDATED ANSWER</h2>
<p>To reflect today's best practices, I would use a transition instead of an animation. Here is the updated code:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
background-color: #000;
color: #fff;
width: 500px;
height: 500px;
padding: 5px;
}
.myDiv {
opacity: 0;
padding: 5px;
color: #600;
background-color: #cec;
-webkit-transition: opacity 1s;
transition: opacity 1s;
}
.parent:hover .myDiv {
opacity: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
Hover on me...
<div class="myDiv">Hello!</div>
</div></code></pre>
</div>
</div>
</p> |
38,611,124 | Git commit not possible. There are no staged files | <p>I am using EGits with Eclipse and running into some issues.</p>
<p>I have one change from head; I have made one new class.</p>
<p>When I right click on this class and click "push", the following dialog shows and I cannot get past it : </p>
<p><a href="https://i.stack.imgur.com/Ar7tg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ar7tg.png" alt="Dialog box with "Committing is not posssible. There are no staged files"."></a></p>
<p>Anyway, I need to push this file because I can't commit in real life, and now I cannot commit in Eclipse either and it's taking it's toll mentally.</p>
<p>Thanks.</p>
<p>PS I have googled this extensively looking for an easy fix (like a "stage" button) and found nothing.</p> | 38,611,322 | 2 | 4 | null | 2016-07-27 11:01:37.913 UTC | 0 | 2020-09-22 06:40:18.743 UTC | null | null | null | null | 963,156 | null | 1 | 24 | eclipse|git|commit|egit|eclipse-mars | 55,563 | <p>using EGit:
Right click it and navigate to Team => Add. </p>
<p>after then Push the code</p>
<p>Before pushing the file add that new file on git using terminal</p>
<p>git add after then </p>
<p>git push origin branch</p> |
34,585,453 | How to bind raw html in Angular2 | <p>I use Angular 2.0.0-beta.0 and I want to create and bind some simple HTML directly. Is is possible and how?</p>
<p>I tried to use</p>
<pre><code>{{myField}}
</code></pre>
<p>but the text in myField will get escaped.</p>
<p>For Angular 1.x i found hits for ng-bind-html, but this seems not be supported in 2.x</p>
<p>thx
Frank </p> | 34,585,513 | 1 | 0 | null | 2016-01-04 05:58:57.673 UTC | 13 | 2019-07-29 11:51:39.933 UTC | null | null | null | null | 2,436,083 | null | 1 | 99 | angular | 105,679 | <p>Bind to the <code>innerHTML</code> attribute </p>
<p><em>There is 2 way to achieve:</em></p>
<pre class="lang-ts prettyprint-override"><code><div [innerHTML]="myField"></div>
<div innerHTML="{{myField}}"></div>
</code></pre>
<p>To mark the passed HTML as trusted so that Angulars DOM sanitizer doesn't strip parts of </p>
<pre class="lang-ts prettyprint-override"><code><div [innerHTML]="myField | safeHtml"></div>
</code></pre>
<p>with a pipe like</p>
<pre class="lang-ts prettyprint-override"><code>@Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:DomSanitizer){}
transform(value: any, args?: any): any {
return this.sanitizer.bypassSecurityTrustHtml(value);
// return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
}
}
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868">In RC.1 some styles can't be added using binding syntax</a></p> |
26,274,415 | How can I find out, whether a specific package is already installed in Arch Linux | <p>I want to write a bash script allowing me to check, whether a certain package is already installed in arch linux.</p>
<p>How can I do that?</p> | 26,278,282 | 5 | 0 | null | 2014-10-09 09:03:49.213 UTC | 7 | 2022-01-12 10:01:22.433 UTC | null | null | null | null | 2,301,866 | null | 1 | 36 | linux|bash|archlinux | 39,318 | <p>You should use Pacman, the package manager of Arch Linux. </p>
<p>You want to use the <code>-Q</code> operation to query the installed local package database and the <code>-i</code> option to get information on the package.</p>
<p>This gives you</p>
<pre><code>pacman -Qi <packageName>
</code></pre>
<p>You can then use the exit code to determine if the packages existes on the system or not (0 the package exists, 1 it doesn't)</p>
<p>The usage of <code>-i</code> rather than <code>-s</code> ensures you will check for exactly that package and not for the presence of a a package containing the package name in its name.</p>
<p>For example if I search for <code>chromium</code> (the web browser) on a system where only <code>chromium-bsu</code> (the game) is installed,</p>
<pre><code># This exits with 1 because chromium is not installed
pacman -Qi chromium
# This exits with 0 because chromium-bsu is installed
pacman -Qs chromium
</code></pre>
<p>As <a href="https://stackoverflow.com/a/26274416/829676">Random Citizen</a> pointed out, you certainly want to redirect any output to <code>/dev/null</code> if you are writing a script and don't want Pacman to pollute your output: </p>
<pre><code>pacman -Qi <packageName> > /dev/null
</code></pre> |
22,158,530 | Is it possible to train Stanford NER system to recognize more named entities types? | <p>I'm using some NLP libraries now, (stanford and nltk)
Stanford I saw the demo part but just want to ask if it possible to use it to identify more entity types.</p>
<p>So currently stanford NER system (as the demo shows) can recognize entities as person(name), organization or location. But the organizations recognized are limited to universities or some, big organizations. I'm wondering if I can use its API to write program for more entity types, like if my input is "Apple" or "Square" it can recognize it as a company.</p>
<p>Do I have to make my own training dataset?</p>
<p>Further more, if I ever want to extract entities and their relationships between each other, I feel I should use the stanford dependency parser.
I mean, extract first the named entities and other parts tagged as "noun" and find relations between them.</p>
<p>Am I correct.</p>
<p>Thanks.</p> | 22,170,509 | 3 | 0 | null | 2014-03-03 22:07:18.933 UTC | 17 | 2018-03-23 07:31:55.433 UTC | 2014-05-23 15:06:39.223 UTC | null | 2,180,785 | null | 2,209,904 | null | 1 | 28 | nlp|stanford-nlp|named-entity-recognition | 17,941 | <p>Yes, you need your own training set. The pre-trained Stanford models only recognise the word "Stanford" as a named entity because they have been trained on data that had that word (or very similar words according to the feature set they use, I don't know what that is) marked as a named entity. </p>
<p>Once you have more data, you need to put it in the right format described in <a href="https://stackoverflow.com/questions/15609324/training-n-gram-ner-with-stanford-nlp">this question</a> and the Stanford tutorial.</p> |
29,338,066 | Run Python Script at OS X Startup | <p>I am very new to python as well as MAC OSX. For my academic project I need to download a bunch of tweets from twitter using twitter streaming API. I need to download atleast 5000000 tweets. So I have written a python script and placed it in start-up. "System Preference -> Users and Groups -> Login items" and added my script there. But I see that the script is not executed when I login to the system ! Please help me resolve this issue.</p> | 29,338,130 | 4 | 0 | null | 2015-03-30 03:41:49.323 UTC | 12 | 2022-07-08 09:43:53.38 UTC | 2020-08-17 11:09:31.567 UTC | null | 4,494 | null | 1,323,577 | null | 1 | 19 | macos | 23,945 | <p>Adapt the following accordingly, name it something like <code>myscript_launcher.plist</code>, and put it in either one of three locations: <code>/System/Library/LaunchAgents</code>, <code>/System/Library/LaunchDaemons</code>, <code>/Users/<username>/Library/LaunchAgents</code>.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.python.script.name</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/python</string>
<string>/path/to/python/script.py</string>
</array>
<key>StandardErrorPath</key>
<string>/var/log/python_script.error</string>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
</code></pre>
<p>Also, let's assume you put the plist file in <code>~/Library/LaunchAgents</code>. You can start and stop it with the <code>launchctl</code>. To start, use <code>launchctl load ~/Library/LaunchAgents/myscript_launcher.plist</code>. To stop it, do the same but use the <code>unload</code> argument</p> |
32,073,971 | Stopping Docker containers by image name - Ubuntu | <p>On Ubuntu 14.04 (Trusty Tahr) I'm looking for a way to stop a running container and the only information I have is the image name that was used in the Docker run command. </p>
<p>Is there a command to find all the matching running containers that match that image name and stop them?</p> | 32,074,098 | 20 | 0 | null | 2015-08-18 13:35:17.657 UTC | 49 | 2022-05-02 08:22:50.28 UTC | 2019-05-02 17:53:11.953 UTC | null | 5,449,500 | null | 20,748 | null | 1 | 206 | docker|ubuntu|docker-image | 191,167 | <h2>If you know the <code>image:tag</code> exact container version</h2>
<p>Following <a href="https://github.com/docker/docker/issues/8959" rel="noreferrer">issue 8959</a>, a good start would be:</p>
<pre><code>docker ps -a -q --filter="name=<containerName>"
</code></pre>
<p>Since <code>name</code> refers to the <em>container</em> and not the image name, you would need to use the more recent <a href="https://github.com/docker/docker/commit/b1cb1b1df493b3e0b739b9f374b6c82e306dede8" rel="noreferrer">Docker 1.9 filter ancestor</a>, mentioned in <a href="https://stackoverflow.com/users/158288/koekiebox">koekiebox</a>'s <a href="https://stackoverflow.com/a/34899613/6309">answer</a>.</p>
<pre><code>docker ps -a -q --filter ancestor=<image-name>
</code></pre>
<hr />
<p>As commented below by <a href="https://stackoverflow.com/users/1919237/kiril">kiril</a>, to remove those containers:</p>
<blockquote>
<p><code>stop</code> returns the containers as well.</p>
</blockquote>
<p>So chaining <code>stop</code> and <code>rm</code> will do the job:</p>
<pre><code>docker rm $(docker stop $(docker ps -a -q --filter ancestor=<image-name> --format="{{.ID}}"))
</code></pre>
<hr />
<h2>If you know only the image name (not <code>image:tag</code>)</h2>
<p>As <a href="https://stackoverflow.com/users/986696/alex-jansen">Alex Jansen</a> points out in <a href="https://stackoverflow.com/questions/32073971/stopping-docker-containers-by-image-name-ubuntu/32074098#comment121207874_32074098">the comments</a>:</p>
<blockquote>
<p>The <a href="https://docs.docker.com/engine/reference/commandline/ps/#filtering" rel="noreferrer">ancestor option</a> does not support wildcard matching.</p>
</blockquote>
<p>Alex <a href="https://stackoverflow.com/a/68584752/6309">proposes a solution</a>, but the one I managed to run, when you have <em>multiple</em> containers running from the same image is (in your <code>~/.bashrc</code> for instance):</p>
<pre><code>dsi() { docker stop $(docker ps -a | awk -v i="^$1.*" '{if($2~i){print$1}}'); }
</code></pre>
<p>Then I just call in my bash session (after sourcing <code>~/.bashrc</code>):</p>
<pre><code>dsi alpine
</code></pre>
<p>And any container running from <code>alpine.*:xxx</code> would stop.</p>
<p>Meaning: any image whose name is <em>starting</em> with <code>alpine</code>.<br />
You might need to tweak the <code>awk -v i="^$1.*"</code> if you want <code>^$1.*</code> to be more precise.</p>
<p>From there, of course:</p>
<pre><code>drmi() { docker rm $(dsi $1 | tr '\n' ' '); }
</code></pre>
<p>And a <code>drmi alpine</code> would stop <em>and remove</em> any <code>alpine:xxx</code> container.</p> |
36,650,642 | did you specify the right host or port? error on Kubernetes | <p>I have followed the helloword tutorial on <a href="http://kubernetes.io/docs/hellonode/" rel="noreferrer">http://kubernetes.io/docs/hellonode/</a>.</p>
<p>When I run:</p>
<pre><code>kubectl run hello-node --image=gcr.io/PROJECT_ID/hello-node:v1 --port=8080
</code></pre>
<p>I get:</p>
<blockquote>
<p>The connection to the server localhost:8080 was refused - did you specify the right host or port?</p>
</blockquote>
<p>Why does the command line try to connect to the localhost?</p> | 37,188,830 | 27 | 0 | null | 2016-04-15 15:02:11.98 UTC | 28 | 2022-04-20 07:32:25.863 UTC | 2020-10-26 05:21:46.293 UTC | null | 6,463,558 | null | 112,976 | null | 1 | 129 | kubernetes|kubectl | 236,485 | <p>The issue is that your <code>kubeconfig</code> is not right.
To auto-generate it run:</p>
<pre><code>gcloud container clusters get-credentials "CLUSTER NAME"
</code></pre>
<p>This worked for me.</p> |
52,754,149 | Operation of the mkdir command with dockerfile | <p>I cannot create a directory with the mkdir command in a container with dockerfile.</p>
<p>My Dockerfile file is simply ; </p>
<pre><code>FROM php:fpm
WORKDIR /var/www/html
VOLUME ./code:/var/www/html
RUN mkdir -p /var/www/html/foo
</code></pre>
<p>In this way I created a simple php: fpm container.
and I wrote to create a directory called foo.</p>
<pre><code>docker build -t phpx .
</code></pre>
<p>I have built with the above code.</p>
<p>In my docker-compose file as follows.</p>
<pre><code>version: '3'
services:
web:
container_name: phpx
build : .
ports:
- "80:80"
volumes:
- ./code:/var/www/html
</code></pre>
<p>later; run the following code and I entered the container kernel.</p>
<pre><code>docker exec -it phpx /bin/bash
</code></pre>
<p><strong>but there is no a directory called foo in / var / www / html.</strong></p>
<p>I wonder where I'm doing wrong.
Can you help me?</p> | 52,754,409 | 2 | 0 | null | 2018-10-11 07:02:28.797 UTC | 6 | 2021-11-03 11:19:35.77 UTC | null | null | null | null | 2,363,892 | null | 1 | 47 | docker|docker-compose|dockerfile | 129,159 | <p>The reason is that you are mounting a volume from your host to <code>/var/www/html</code>.
Step by step:</p>
<ol>
<li><code>RUN mkdir -p /var/www/html/foo</code> creates the foo directory inside the filesystem of your container.</li>
<li>docker-compose.yml <code>./code:/var/www/html</code> "hides" the content of <code>/var/www/html</code> in the container filesystem behind the contents of <code>./code</code> on the host filesystem.</li>
</ol>
<p>So actually, when you exec into your container you see the contents of the <code>./code</code> directory on the host when you look at <code>/var/www/html</code>.</p>
<p><strong>Fix:</strong> Either you remove the volume from your docker-compose.yml or you create the <code>foo</code>-directory on the host before starting the container.</p>
<p><strong>Additional Remark</strong>: In your Dockerfile you declare a volume as <code>VOLUME ./code:/var/www/html</code>. This does not work and you should probably remove it. In a Dockerfile you cannot specify a path on your host.</p>
<p>Quoting from <a href="https://docs.docker.com/v17.09/engine/reference/builder/#volume" rel="noreferrer">docker</a>:</p>
<blockquote>
<p>The host directory is declared at container run-time: The host directory (the mountpoint) is, by its nature, host-dependent. This is to preserve image portability. since a given host directory can’t be guaranteed to be available on all hosts. For this reason, you can’t mount a host directory from within the Dockerfile. <strong>The VOLUME instruction does not support specifying a host-dir parameter</strong>. You must specify the mountpoint when you create or run the container.</p>
</blockquote> |
53,786,383 | Validate nested objects using class validator and nestjs | <p>I'm trying to validate nested objects using class-validator and NestJS. I've already tried following this <a href="https://stackoverflow.com/a/53685045/4694994">thread</a> by using the <code>@Type</code> decorator from class-transform and didn't have any luck. This what I have:</p>
<p><strong>DTO:</strong></p>
<pre><code>class PositionDto {
@IsNumber()
cost: number;
@IsNumber()
quantity: number;
}
export class FreeAgentsCreateEventDto {
@IsNumber()
eventId: number;
@IsEnum(FinderGamesSkillLevel)
skillLevel: FinderGamesSkillLevel;
@ValidateNested({ each: true })
@Type(() => PositionDto)
positions: PositionDto[];
}
</code></pre>
<p>I'm also using built-in nestjs validation pipe, this is my bootstrap:</p>
<pre><code>async function bootstrap() {
const app = await NestFactory.create(ServerModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(config.PORT);
}
bootstrap();
</code></pre>
<p>It's working fine for other properties, the array of objects is the only one not working.</p> | 53,786,899 | 3 | 3 | null | 2018-12-14 20:17:51.32 UTC | 9 | 2021-11-18 04:24:57.427 UTC | 2021-02-21 13:38:57.55 UTC | null | 74,089 | null | 2,662,054 | null | 1 | 42 | javascript|node.js|typescript|nestjs|class-validator | 74,554 | <p>You are expecting <code>positions: [1]</code> to throw a 400 but instead it is accepted.</p>
<p>According to this <a href="https://github.com/typestack/class-validator/issues/193#issuecomment-386877352" rel="noreferrer">Github issue</a>, this seems to be a bug in class-validator. If you pass in a primitive type (<code>boolean</code>, <code>string</code>, <code>number</code>,...) or an <code>array</code> instead of an object, it will accept the input as valid although it shouldn't.</p>
<hr>
<p>I don't see any standard workaround besides creating a <a href="https://github.com/typestack/class-validator#custom-validation-decorators" rel="noreferrer">custom validation decorator</a>:</p>
<pre><code>import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
export function IsNonPrimitiveArray(validationOptions?: ValidationOptions) {
return (object: any, propertyName: string) => {
registerDecorator({
name: 'IsNonPrimitiveArray',
target: object.constructor,
propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
return Array.isArray(value) && value.reduce((a, b) => a && typeof b === 'object' && !Array.isArray(b), true);
},
},
});
};
}
</code></pre>
<p>and then use it in your dto class:</p>
<pre><code>@ValidateNested({ each: true })
@IsNonPrimitiveArray()
@Type(() => PositionDto)
positions: PositionDto[];
</code></pre> |
6,188,197 | Problem Storing Latitude and Longitude values in MySQL database | <p>I want to store the values of latitude and longitude fetched from Google Maps GeoCoding API in a MySQL database. The values are in float format.</p>
<blockquote>
<p>12.9274529</p>
<p>77.5905970</p>
</blockquote>
<p>And when I want to store it in database (which is datatype float) it rounds up float and store it in following format:</p>
<blockquote>
<p>12.9275</p>
<p>77.5906</p>
</blockquote>
<p>Am I using the wrong datatype? If yes then what datatype should I be using to store latitude and longitude values?</p>
<p>Update : </p>
<p>here is the CREATE TABLE as requestted by Allin</p>
<pre><code>CREATE TABLE `properties` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`description` text,
`latitude` float DEFAULT NULL,
`longitude` float DEFAULT NULL,
`landmark` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `serial` (`serial`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
</code></pre> | 6,188,256 | 7 | 8 | null | 2011-05-31 13:17:39.703 UTC | 11 | 2014-09-13 21:44:21.417 UTC | 2012-05-11 14:43:23.657 UTC | null | 44,390 | null | 396,476 | null | 1 | 17 | php|mysql|types|floating-point | 28,059 | <p>You need to use <a href="http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html" rel="noreferrer">decimal</a> if you don't want the numbers to be approximated.</p>
<blockquote>
<p>Fixed-Point (Exact-Value) Types</p>
<p>The DECIMAL and NUMERIC types store
exact numeric data values. These types
are used when it is important to
preserve exact precision, for example
with monetary data.</p>
</blockquote>
<p><strong>And now the "here you go" answer:</strong></p>
<p>Use <code>DECIMAL(10,7)</code>. Where <code>10</code> is the total number of digits in the number and <code>7</code> is the number of digits after the <code>.</code>. (This means that before the dot will be <code>3</code> digits.)</p>
<p>Adjust these numbers as needed. Also <strong>please</strong> take a look at the manual entry I linked earlier in the answer.</p> |
6,036,793 | SQL: how to use UNION and order by a specific select? | <p>I have two selects:</p>
<pre><code>SELECT id FROM a -- returns 1,4,2,3
UNION
SELECT id FROM b -- returns 2,1
</code></pre>
<p>I'm receiving correct num of rows, like: <code>1,4,2,3</code>.</p>
<p>But I want <code>b</code> table results first: <code>2,1,4,3</code> or <code>2,1,3,4</code></p>
<p>How can I do this?</p>
<p>(I'm using Oracle)</p> | 6,037,367 | 7 | 0 | null | 2011-05-17 20:36:06.323 UTC | 5 | 2022-09-20 07:17:15.207 UTC | 2011-06-26 06:37:35.24 UTC | null | 570,191 | null | 411,247 | null | 1 | 26 | sql|oracle|select|union | 117,888 | <p>Using @Adrian tips, I found a solution:</p>
<p>I'm using <strong>GROUP BY</strong> and <strong>COUNT</strong>.
I tried to use <strong>DISTINCT</strong> with <strong>ORDER BY</strong> but I'm getting error message: <em>"not a SELECTed expression"</em></p>
<pre><code>select id from
(
SELECT id FROM a -- returns 1,4,2,3
UNION ALL -- changed to ALL
SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);
</code></pre>
<p>Thanks Adrian and <a href="http://oraclequirks.blogspot.com/2009/04/ora-01791-not-selected-expression.html" rel="noreferrer">this</a> blog.</p> |
5,735,791 | Parser for Oracle SQL | <p>For my current project I need a SQL parser that parses Oracle SQL statements.
Currently I've been using jsqlparser, which worked well for simple queries. But when specific functions occur (e.g. cast() or (+)) the parser fails.</p>
<p>Can anyone suggest a parser that is fully compliant to Oracle SQL?</p>
<p>Best,
Will</p> | 5,735,998 | 8 | 3 | null | 2011-04-20 19:48:09.573 UTC | 9 | 2022-08-24 07:09:15.897 UTC | null | null | null | null | 715,236 | null | 1 | 20 | sql|oracle|parsing | 35,174 | <p>Have you considered <a href="http://www.sqlparser.com/" rel="nofollow noreferrer">General SQL Parser</a>? I don't have any experience with it myself but browsing their website it has potential. Personally I have rolled my own built on the parser in Eclipse Data Tools Platform (sorry I can't share, it's proprietary), but now I will have to evaluate the one I linked above because it claims to have more coverage of Oracle SQL than my parser does.</p> |
5,867,834 | assert() with message | <p>I saw somewhere assert used with a message in the following way:</p>
<pre><code>assert(("message", condition));
</code></pre>
<p>This seems to work great, except that gcc throws the following warning:</p>
<pre><code>warning: left-hand operand of comma expression has no effect
</code></pre>
<p>How can I stop the warning?</p> | 5,868,001 | 9 | 1 | null | 2011-05-03 09:54:06.493 UTC | 13 | 2021-05-26 19:24:06.137 UTC | null | null | null | null | 88,622 | null | 1 | 53 | c|gcc|compiler-warnings|assert | 50,594 | <p>Use <code>-Wno-unused-value</code> to stop the warning; (the option <code>-Wall</code> includes <code>-Wunused-value</code>).</p>
<p>I think even better is to use another method, like</p>
<pre><code>assert(condition && "message");
</code></pre> |
5,839,327 | Custom form validation error message for Codeigniter 2 | <p>I have a drop down named "business_id".</p>
<pre><code><select name="business_id">
<option value="0">Select Business</option> More options...
</select>
</code></pre>
<p>Here comes the validation rule, user must select an option.</p>
<pre><code>$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]');
</code></pre>
<p>Problem being the error message says: The Business field must contain a number greater than 0. Not very intuitive! I want it to say "You must select a business".</p>
<p>I tried:</p>
<pre><code>$this->form_validation->set_message('Business', 'You must select a business');
</code></pre>
<p>But CI complete ignores this. Does anyone have a solution for this?</p> | 5,839,586 | 10 | 0 | null | 2011-04-30 03:39:37.773 UTC | 1 | 2016-03-31 10:50:25.44 UTC | 2011-04-30 03:42:24.64 UTC | null | 313,758 | null | 207,425 | null | 1 | 5 | php|codeigniter|validation | 38,828 | <p>Try not setting the value attribute on the default select...</p>
<pre><code><select name="business_id">
<option value>Select Business</option> More options...
</select>
</code></pre>
<p>and then just using required for your form validation rule...</p>
<pre><code>$this->form_validation->set_rules('business_id', 'Business', 'required');
</code></pre>
<p>I suppose you could try editing the way that you're trying to set the message also...</p>
<pre><code>$this->form_validation->set_message('business_id', 'You must select a business');
instead of
$this->form_validation->set_message('Business', 'You must select a business');
</code></pre>
<p>I'm not entirely sure if that will do the trick though.</p> |
17,755,996 | How to make a list as the default value for a dictionary? | <p>I have a Python code that looks like:</p>
<pre><code>if key in dict:
dict[key].append(some_value)
else:
dict[key] = [some_value]
</code></pre>
<p>but I figure there should be some method to get around this 'if' statement. I tried:</p>
<pre><code>dict.setdefault(key, [])
dict[key].append(some_value)
</code></pre>
<p>and</p>
<pre><code>dict[key] = dict.get(key, []).append(some_value)
</code></pre>
<p>but both complain about "TypeError: unhashable type: 'list'". Any recommendations?</p> | 17,756,005 | 1 | 5 | null | 2013-07-19 21:43:53.067 UTC | 10 | 2021-12-09 09:50:15.83 UTC | 2021-12-08 19:50:37.173 UTC | null | 6,045,800 | null | 522,044 | null | 1 | 42 | python|dictionary|default-value | 49,840 | <p>The best method is to use <a href="http://docs.python.org/2/library/collections.html#collections.defaultdict"><code>collections.defaultdict</code></a> with a <code>list</code> default:</p>
<pre><code>from collections import defaultdict
dct = defaultdict(list)
</code></pre>
<p>Then just use:</p>
<pre><code>dct[key].append(some_value)
</code></pre>
<p>and the dictionary will create a new list for you if the key is not yet in the mapping. <code>collections.defaultdict</code> is a subclass of <code>dict</code> and otherwise behaves just like a normal <code>dict</code> object.</p>
<p>When using a standard <code>dict</code>, <code>dict.setdefault()</code> correctly sets <code>dct[key]</code> for you to the default, so that version should have worked just fine. You can chain that call with <code>.append()</code>:</p>
<pre><code>>>> dct = {}
>>> dct.setdefault('foo', []).append('bar') # returns None!
>>> dct
{'foo': ['bar']}
</code></pre>
<p>However, by using <code>dct[key] = dct.get(...).append()</code> you <em>replace</em> the value for <code>dct[key]</code> with the output of <code>.append()</code>, which is <code>None</code>.</p> |
39,343,031 | Editorconfig: How to autofix all files in a project | <p>Given I have an .editorconfig file that dictates consistent indent, line endings, trailing whitespace, etc. </p>
<pre><code># http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
</code></pre>
<p>As a Developer, I want to fix all files consistently with a command line tool that understands .editorconfig files. I want to avoid tedious tasks, for instance, manually open and change files.</p>
<p>I imagine if there was a command like for example:</p>
<pre><code>editorconfix.sh --autofix .
</code></pre>
<p>Which tools exist for this purpose? What scripts do you use?</p> | 41,655,803 | 2 | 1 | null | 2016-09-06 07:29:02.04 UTC | 8 | 2020-05-07 08:28:44.71 UTC | null | null | null | null | 109,305 | null | 1 | 30 | editorconfig | 13,195 | <p>There is <a href="https://www.npmjs.com/package/eclint" rel="noreferrer">eclint</a> (and a fork called <a href="https://www.npmjs.com/package/editorconfig-tools" rel="noreferrer">editorconfig-tools</a>). Run</p>
<pre><code>eclint check 'src/**/*'
</code></pre>
<p>to check all files in the <code>src</code> directory, or </p>
<pre><code>eclint fix 'src/**/*'
</code></pre>
<p>to fix them. But please note that the tool can produce some surprises when it comes to indentation! The author of the tool <a href="https://github.com/jedmao/eclint/issues/43#issuecomment-242929632" rel="noreferrer">says in a GitHub comment</a> that he has stopped using the tool himself in favour of language-specific linters:</p>
<blockquote>
<p>To me, EditorConfig is all about – would you believe it – configuring your editor and nothing more. I don't think it should be responsible for linting or fixing, as there are language-specific tools to accomplish those goals (e.g., ESLint for JavaScript). The only way you can reliably lint or fix indentation is to be aware of the language in question and EditorConfig is language agnostic.</p>
</blockquote> |
9,708,656 | How can I create a SQL function with a parameter? | <p>The following code returns one field, a string, based on the input where it says "28". </p>
<pre><code>SELECT data.id, LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (
SELECT es.EVENT_ID as id, s.SERVICE_NAME as name FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = 28
)
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
</code></pre>
<p>How can I create a SQL function out of this so that I can pass in whatever number (instead of 28) and the function would return whatever the result of that select turns out to be?</p>
<p>I tried creating one but I keep getting compilation errors. </p>
<p>Current SQL to create function</p>
<pre><code>create or replace function "DT_SERVICE_STRING" (id in VARCHAR2)
return VARCHAR2 is
begin
DECLARE
result VARCHAR(200);
SELECT data.id, LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
INTO result
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (
SELECT es.EVENT_ID as id, s.SERVICE_NAME as name FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = id
)
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
return result;
end;
</code></pre>
<p>Error:<br>
Compilation failed,line 7 (15:22:21)
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: begin function pragma procedure subtype type current cursor delete exists prior</p> | 9,708,743 | 2 | 3 | null | 2012-03-14 19:16:24.327 UTC | null | 2015-11-18 09:35:18.823 UTC | 2015-11-18 09:35:18.823 UTC | null | 1,345,788 | null | 1,004,278 | null | 1 | 2 | sql|oracle|plsql|oracle-apex | 49,032 | <p>Assuming that you want a PL/SQL function that is callable from a SQL statement (you cannot have a function defined in SQL), it sounds like you want something like</p>
<pre><code>CREATE OR REPLACE FUNCTION get_conc_names( p_event_id IN dt_event_service.event_id%type )
RETURN VARCHAR2
IS
l_conc_names VARCHAR2(32676);
-- You may want a smaller variable if you know the result will be smaller
BEGIN
SELECT LTRIM(SYS_CONNECT_BY_PATH(name, ', '),',') conc_names
INTO l_conc_names
FROM (
SELECT id, name, ROW_NUMBER() OVER (order by name) rownumber, COUNT(*) OVER () cnt
FROM (SELECT es.EVENT_ID as id, s.SERVICE_NAME as name
FROM DT_SERVICES s
JOIN DT_EVENT_SERVICE es ON s.SERVICE_ID = es.SERVICE_ID
WHERE es.EVENT_ID = p_event_id )
) data
WHERE rownumber = cnt
START WITH rownumber = 1
CONNECT BY PRIOR rownumber = rownumber-1;
RETURN l_conc_names;
END;
</code></pre>
<p>Based on the code you just posted, it appears that you just need to get rid of the <code>DECLARE</code> and to move the declaration of the local variable <code>result</code> before the <code>BEGIN</code> and after the <code>IS</code>. </p> |
21,899,537 | Can I use a DIV in an email template? | <p>I am greatly confused about designing an email template for a mailchimp campaign. I want to know if I can use a <code>div</code> with a class of "Container" on my email template. Is using <code>div</code> tags supported by all mail clients? I am using DIV only for the container but in the inner part of the template I have used <code>table</code>, <code>tr</code> and <code>td</code> tags. Please let me know.</p>
<p>Thanks.</p> | 21,910,689 | 3 | 1 | null | 2014-02-20 06:05:29.09 UTC | 3 | 2018-09-25 06:01:49.34 UTC | 2014-07-02 07:28:51.79 UTC | null | 2,225,787 | null | 3,308,679 | null | 1 | 17 | html|email|templates|mailchimp | 51,769 | <p>You can use div, however tables are supported more consistently. If you try to go the div route, you'll find some of your CSS will fail.</p>
<p>Also, by going with tables, it opens up the old school html attributes that only work in tables. These include <code>align</code>, <code>valign</code>, <code>bgcolor</code> etc, all of which are 100% supported, while their CSS equivalents have partial support.</p>
<p>On a side note, here are <a href="https://stackoverflow.com/questions/2229822/best-practices-considerations-when-writing-html-emails/21437734#21437734">all the resources you will need</a> to get started in html email.</p> |
33,054,229 | Accessing attributes on literals work on all types, but not `int`; why? | <p>I have read that everything in python is an object, and as such I started to experiment with different types and invoking <em><code>__str__</code></em> on them — at first I was feeling really excited, but then I got confused.</p>
<pre><code>>>> "hello world".__str__()
'hello world'
>>> [].__str__()
'[]'
>>> 3.14.__str__()
'3.14'
>>> 3..__str__()
'3.0'
>>> 123.__str__()
File "<stdin>", line 1
123.__str__()
^
SyntaxError: invalid syntax
</code></pre>
<ul>
<li>Why does <code><em>something</em>.__str__()</code> work for "everything" besides <code>int</code>?</li>
<li>Is <code>123</code> not an <em>object</em> of type <code>int</code>?</li>
</ul> | 33,054,230 | 4 | 2 | null | 2015-10-10 12:55:24.207 UTC | 5 | 2015-10-14 14:35:00.08 UTC | 2015-10-14 07:46:25.2 UTC | null | 100,297 | null | 1,090,079 | null | 1 | 55 | python|python-2.7|python-3.x|language-lawyer | 2,639 | <h3>So you think you can <strike> dance </strike> floating-point?</h3>
<p><code>123</code> is just as much of an object as <code>3.14</code>, the "problem" lies within the grammar rules of the language; the parser thinks we are about to define a <em>float</em> — not an <em>int</em> with a trailing method call.</p>
<p>We will get the expected behavior if we wrap the number in parenthesis, as in the below.</p>
<pre><code>>>> <b>(123).__str__()</b>
'123'</code></pre>
<p>Or if we simply add some whitespace after <em><code>123</code></em>:</p>
<pre><code>>>> <b>123 .__str__()</b>
'123'</code></pre>
<p><br /></p>
<p>The reason it does not work for <code>123.__str__()</code> is that the <em>dot</em> following the <em><code>123</code></em> is interpreted as the <em>decimal-point</em> of some partially declared <em>floating-point</em>.</p>
<pre><code>>>> <b>123.__str__()</b>
File "", line 1
123.__str__()
^
SyntaxError: invalid syntax</code></pre>
<p>The parser tries to interpret <code>__str__()</code> as a sequence of digits, but obviously fails — and we get a <em>SyntaxError</em> basically saying that the parser stumbled upon something that it did not expect.</p>
<p><br /></p>
<hr>
<h3>Elaboration</h3>
<p>When looking at <code>123.__str__()</code> the python parser could use either <em>3</em> characters and interpret these <em>3</em> characters as an <em>integer</em>, <strong>or</strong> it could use <em>4</em> characters and interpret these as the <strong>start</strong> of a <em>floating-point</em>.</p>
<pre><code>123.__str__()
^^^ - int
</code></pre>
<pre><code>123.__str__()
^^^^- start of floating-point
</code></pre>
<p>Just as a little child would like as much cake as possible on their plate, the parser is greedy and would like to swallow as much as it can all at once — even if this isn't always the best of ideas —as such the latter ("better") alternative is chosen.</p>
<p>When it later realizes that <code>__str__()</code> can in no way be interpreted as the <em>decimals</em> of a <em>floating-point</em> it is already too late; <em>SyntaxError</em>.</p>
<blockquote>
<p><sup><strong>Note</strong></sup></p>
<pre><code> 123 .__str__() # works fine
</code></pre>
<p>In the above snippet, <code>123 </code> (note the space) must be interpreted as an <em>integer</em> since no <em>number</em> can contain spaces. This means that it is semantically equivalent to <code>(123).__str__()</code>.</p>
</blockquote>
<blockquote>
<p><sup><strong>Note</strong></sup></p>
<pre><code> 123..__str__() # works fine
</code></pre>
<p>The above also works because a <em>number</em> can contain at most one <em>decimal-point</em>, meaning that it is equivalent to <code>(123.).__str__()</code>.</p>
</blockquote>
<p><br /></p>
<hr>
<h3>For the <em>language-lawyers</em></h3>
<p>This section contains the lexical definition of the relevant literals.</p>
<p><sub><strong><a href="https://docs.python.org/3.5/reference/lexical_analysis.html#floating-point-literals">Lexical analysis - 2.4.5 Floating point literals</a></strong></sub>
</p>
<pre><code>floatnumber ::= pointfloat | exponentfloat
pointfloat ::= [intpart] fraction | intpart "."
exponentfloat ::= (intpart | pointfloat) exponent
intpart ::= digit+
fraction ::= "." digit+
exponent ::= ("e" | "E") ["+" | "-"] digit+
</code></pre>
<p><sub><strong><a href="https://docs.python.org/3.5/reference/lexical_analysis.html#integer-literals">Lexical analysis - 2.4.4 Integer literals</a></strong></sub>
</p>
<pre><code>integer ::= decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::= nonzerodigit digit* | "0"+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
octinteger ::= "0" ("o" | "O") octdigit+
hexinteger ::= "0" ("x" | "X") hexdigit+
bininteger ::= "0" ("b" | "B") bindigit+
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
bindigit ::= "0" | "1"
</code></pre> |
10,365,624 | "sys.getsizeof(int)" returns an unreasonably large value? | <p>I want to check the size of int data type in python:</p>
<pre><code>import sys
sys.getsizeof(int)
</code></pre>
<p>It comes out to be "436", which doesn't make sense to me.
Anyway, I want to know how many bytes (2,4,..?) int will take on my machine.</p> | 10,365,639 | 1 | 1 | null | 2012-04-28 16:59:15.863 UTC | 24 | 2021-10-18 16:13:39.48 UTC | 2012-04-28 17:31:59.44 UTC | user166390 | null | null | 1,040,752 | null | 1 | 60 | python | 53,841 | <h3>The short answer</h3>
<p>You're getting the size of the <em>class</em>, not of an instance of the class. Call <code>int</code> to get the size of an instance:</p>
<pre><code>>>> sys.getsizeof(int())
24
</code></pre>
<p>If that size still seems a little bit large, remember that a Python <code>int</code> is very different from an <code>int</code> in (for example) c. In Python, an <code>int</code> is a fully-fledged object. This means there's extra overhead.</p>
<p>Every Python object contains at least a refcount and a reference to the object's type in addition to other storage; on a 64-bit machine, that takes up 16 bytes! The <code>int</code> internals (as determined by the standard CPython implementation) have also changed over time, so that the amount of additional storage taken depends on your version.</p>
<h3>Some details about <code>int</code> objects in Python 2 and 3</h3>
<p>Here's the situation in Python 2. (Some of this is adapted from a blog post by <a href="http://www.laurentluce.com/posts/python-integer-objects-implementation/" rel="noreferrer">Laurent Luce</a>). Integer objects are represented as blocks of memory with the following structure:</p>
<pre class="lang-c prettyprint-override"><code>typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;
</code></pre>
<p><code>PyObject_HEAD</code> is a macro defining the storage for the refcount and the object type. It's described in some detail by the <a href="https://docs.python.org/c-api/structures.html" rel="noreferrer">documentation</a>, and the code can be seen in <a href="https://stackoverflow.com/questions/11736762/why-pyobject-can-point-to-any-object-in-python">this</a> answer.</p>
<p>The memory is allocated in large blocks so that there's not an allocation bottleneck for every new integer. The structure for the block looks like this:</p>
<pre class="lang-c prettyprint-override"><code>struct _intblock {
struct _intblock *next;
PyIntObject objects[N_INTOBJECTS];
};
typedef struct _intblock PyIntBlock;
</code></pre>
<p>These are all empty at first. Then, each time a new integer is created, Python uses the memory pointed at by <code>next</code> and increments <code>next</code> to point to the next free integer object in the block.</p>
<p>I'm not entirely sure how this changes once you exceed the storage capacity of an ordinary integer, but once you do so, the size of an <code>int</code> gets larger. On my machine, in Python 2:</p>
<pre><code>>>> sys.getsizeof(0)
24
>>> sys.getsizeof(1)
24
>>> sys.getsizeof(2 ** 62)
24
>>> sys.getsizeof(2 ** 63)
36
</code></pre>
<p>In Python 3, I think the general picture is the same, but the size of integers increases in a more piecemeal way:</p>
<pre><code>>>> sys.getsizeof(0)
24
>>> sys.getsizeof(1)
28
>>> sys.getsizeof(2 ** 30 - 1)
28
>>> sys.getsizeof(2 ** 30)
32
>>> sys.getsizeof(2 ** 60 - 1)
32
>>> sys.getsizeof(2 ** 60)
36
</code></pre>
<p>These results are, of course, all hardware-dependent! YMMV.</p>
<p>The variability in integer size in Python 3 is a hint that they may behave more like variable-length types (like lists). And indeed, this turns out to be true. Here's the definition of the <a href="https://github.com/python/cpython/blob/ba85d69a3e3610bdd05f0dd372cf4ebca178c7fb/Include/longintrepr.h#L85" rel="noreferrer">C <code>struct</code></a> for <code>int</code> objects in Python 3:</p>
<pre class="lang-c prettyprint-override"><code>struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
</code></pre>
<p>The <a href="https://github.com/python/cpython/blob/ba85d69a3e3610bdd05f0dd372cf4ebca178c7fb/Include/longintrepr.h#L70" rel="noreferrer">comments</a> that accompany this definition summarize Python 3's representation of integers. Zero is represented not by a stored value, but by an object with size zero (which is why <code>sys.getsizeof(0)</code> is <code>24</code> bytes while <code>sys.getsizeof(1)</code> is <code>28</code>). Negative numbers are represented by objects with a negative size attribute! So weird.</p> |
19,071,601 | How do I run multiple Python test cases in a loop? | <p>I am new to Python and trying to do something I do often in Ruby. Namely, iterating over a set of indices, using them as argument to function and comparing its results with an array of fixture outputs. </p>
<p>So I wrote it up like I normally do in Ruby, but this resulted in just one test case. </p>
<pre><code> def test_output(self):
for i in range(1,11):
....
self.assertEqual(fn(i),output[i])
</code></pre>
<p>I'm trying to get the test for every item in the range. How can I do that?</p> | 19,071,738 | 4 | 1 | null | 2013-09-28 20:58:11.2 UTC | 7 | 2018-08-24 12:14:22.177 UTC | null | null | null | null | 32,816 | null | 1 | 34 | python|python-unittest | 36,719 | <p>Using unittest you can show the difference between two sequences all in one test case.</p>
<pre><code>seq1 = range(1, 11)
seq2 = (fn(j) for j in seq1)
assertSequenceEqual(seq1, seq2)
</code></pre>
<p>If that's not flexible enough, using unittest, it is possible to generate multiple tests, but it's a bit tricky.</p>
<pre><code>def fn(i): ...
output = ...
class TestSequence(unittest.TestCase):
pass
for i in range(1,11):
testmethodname = 'test_fn_{0}'.format(i)
testmethod = lambda self: self.assertEqual(fn(i), output[i])
setattr(TestSequence, testmethodname, testmethod)
</code></pre>
<p>Nose makes the above easier through <a href="http://nose.readthedocs.org/en/latest/writing_tests.html#test-generators" rel="noreferrer">test generators</a>.</p>
<pre><code>import nose.tools
def test_fn():
for i in range(1, 11):
yield nose.tools.assert_equals, output[i], fn(i)
</code></pre>
<p>Similar questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2798956/python-unittest-generate-multiple-tests-programmatically">Python unittest: Generate multiple tests programmatically?</a></li>
<li><a href="https://stackoverflow.com/questions/32899/how-to-generate-dynamic-parametrized-unit-tests-in-python">How to generate dynamic (parametrized) unit tests in python?</a></li>
</ul> |
37,629,860 | Automatically resizing textarea in bootstrap | <p>I found the following very simple way to automatically adjust a textarea to the text height in this jsfiddle <a href="http://jsfiddle.net/tovic/gLhCk/" rel="noreferrer">http://jsfiddle.net/tovic/gLhCk/</a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function expandTextarea(id) {
document.getElementById(id).addEventListener('keyup', function() {
this.style.overflow = 'hidden';
this.style.height = 0;
this.style.height = this.scrollHeight + 'px';
}, false);
}
expandTextarea('txtarea');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding:50px;
}
textarea {
margin:0px 0px;
padding:5px;
height:16px;
line-height:16px;
width:96%;
display:block;
margin:0px auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="txtarea" spellcheck="false" placeholder="Statusku..."></textarea></code></pre>
</div>
</div>
</p>
<p>However, I'm using bootstrap in my project and this introduces problems.</p>
<ol>
<li>The textarea is only 4px high instead of 16. It seems like bootstrap changes the way margins and paddings and heights work?</li>
<li>When hitting enter, the text is jumping up and down, which is irritating to the eye.</li>
</ol>
<p>I tried to delete all bootstrap classes in the HTML inspector of my browser but the problem was still there. Does anyone have an idea how to resolve this?</p>
<p>Here's the code when bootstrap's CSS is added:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function expandTextarea(id) {
document.getElementById(id).addEventListener('keyup', function() {
this.style.overflow = 'hidden';
this.style.height = 0;
this.style.height = this.scrollHeight + 'px';
}, false);
}
expandTextarea('txtarea');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding:50px;
}
textarea {
margin:0px 0px;
padding:5px;
height:16px;
line-height:16px;
width:96%;
display:block;
margin:0px auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<textarea id="txtarea" spellcheck="false" placeholder="Statusku..."></textarea></code></pre>
</div>
</div>
</p> | 37,630,464 | 8 | 1 | null | 2016-06-04 11:47:18.797 UTC | 1 | 2020-09-25 10:21:37.777 UTC | 2018-12-04 06:36:56.797 UTC | null | 3,022,127 | null | 3,022,127 | null | 1 | 10 | css|twitter-bootstrap|textarea | 40,812 | <p>Thanks for all your answers, it gave me valuable insights into what I had to change. In the end, a bit more padding-bottom in the css did the trick.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function expandTextarea(id) {
document.getElementById(id).addEventListener('keyup', function() {
this.style.overflow = 'hidden';
this.style.height = 0;
this.style.height = this.scrollHeight + 'px';
}, false);
}
expandTextarea('txtarea');</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
padding:50px;
}
textarea {
/* margin:0px 0px; this is redundant anyways since its specified below*/
padding-top:10px;
padding-bottom:25px; /* increased! */
/* height:16px; */
/* line-height:16px; */
width:100%; /* changed from 96 to 100% */
display:block;
/* margin:0px auto; not needed since i have width 100% now */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<textarea id="txtarea" spellcheck="false" placeholder="Statusku..."></textarea></code></pre>
</div>
</div>
</p> |
3,988,995 | How can I filter a dictionary using LINQ and return it to a dictionary from the same type | <p>I have the following dictionary:</p>
<pre><code>Dictionary<int,string> dic = new Dictionary<int,string>();
dic[1] = "A";
dic[2] = "B";
</code></pre>
<p>I want to filter the dictionary's items and reassign the result to the same variable:</p>
<pre><code>dic = dic.Where (p => p.Key == 1);
</code></pre>
<p>How can I return the result as a dictionary from the same type [<code><int,string></code>] ?</p>
<p>I tried <code>ToDictionary</code>, but it doesn't work.</p> | 3,989,017 | 1 | 1 | null | 2010-10-21 15:13:39.973 UTC | 13 | 2021-11-17 22:48:13.843 UTC | 2021-11-17 22:48:13.843 UTC | null | 8,239,061 | null | 322,355 | null | 1 | 110 | c#|linq|dictionary|linq-to-objects | 76,814 | <p><code>ToDictionary</code> is the way to go. It <em>does</em> work - you were just using it incorrectly, presumably. Try this:</p>
<pre><code>dic = dic.Where(p => p.Key == 1)
.ToDictionary(p => p.Key, p => p.Value);
</code></pre>
<p>Having said that, I assume you <em>really</em> want a different <code>Where</code> filter, as your current one will only ever find one key...</p> |
18,547,855 | Permission Denied when writing log file | <p>I'm using ubuntu 13.04. I'm running uwsgi using <code>sudo service uwsgi start</code></p>
<p>I've configured log file in django as <code>/home/shwetanka/logs/mysite/mysite.log</code></p>
<p>But I'm getting this error - </p>
<pre><code>ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/home/shwetanka/logs/mysite/mysite.log'
</code></pre>
<p>How do I fix it? This should not happen when I run uwsgi as sudo.</p> | 18,547,916 | 2 | 0 | null | 2013-08-31 11:54:22.777 UTC | 5 | 2015-08-16 08:49:04.203 UTC | null | null | null | null | 390,230 | null | 1 | 22 | django|ubuntu|uwsgi | 50,986 | <p>You need to fix permissions with the <code>chmod</code> command, like this: <code>chmod 775 /home/shwetanka/logs/mysite/mysite.log</code>.</p>
<p>Take a look at the owner of the file with <code>ls -l /home/shwetanka/logs/mysite/mysite.log</code> and make it writable to <code>uwsgi</code>. If the file isn't owned by <code>uwsgi</code>, you'll have to use the <code>chown</code> command.</p>
<p>Take a look at the username under which your service is running with <code>ps aux | grep 'uwsgi'</code>.</p>
<p>If the security isn't so important to you at the moment, use <code>chmod 777 /home/shwetanka/logs/mysite/mysite.log</code> and that's it. But that's not the way how this is done.</p>
<p>The safest way to do this would be to check the owner and the group of the file and then change them if necessary and adjust the permissions accordingly.</p>
<p>Let's give an example.</p>
<p>If I have a file in <code>/home/shwetanka/logs/mysite/mysite.log</code> and the command <code>ls -l /home/shwetanka/logs/mysite/mysite.log</code> gives the following output:</p>
<pre><code>-rw-rw-r-- 1 shwetanka shwetanka 1089 Aug 26 18:15 /home/shwetanka/logs/mysite/mysite.log
</code></pre>
<p>it means that the owner of the file is <code>shwetanka</code> and the group is also <code>shwetanka</code>. Now let's read the <code>rwx</code> bits. First group is related to the file owner, so <code>rw-</code> means that the file is readable and writable by the owner, readable and writeable by the group and readable by the others. You must make sure that the owner of the file is the service that's trying to write something to it or that the file belongs to group of the service or you'll get a <code>permission denied</code> error.</p>
<p>Now if I have a username <code>uwsgi</code> that's used by the USWGI service and want the above file to be writable by that service, I have to change the owner of the file, like this:</p>
<p><code>chown uwsgi /home/shwetanka/logs/mysite/mysite.log</code>. Since the write bit for the owner (the first <code>rwx</code> group) is already set to <code>1</code>, that file will now be writable by the UWSGI service. For any further questions, please leave a comment.</p> |
8,650,007 | Regular expression for twitter username | <p>I need a javascript regular expression to match twitter usernames.</p>
<p>The username is entered by the user while signing up, so I don't want to distract them with too many error notifications. Because of that, I need the expression to match valid usernames regardles if they have the @ before the username or not.</p>
<p>Twitter usernames can contain latin characters, underscores and numbers, and the only limitation is the can be up to 15 characters long. ( but I need the regex to match 16 characters as well, in case someone enters the @ before the username ).</p> | 8,650,024 | 10 | 1 | null | 2011-12-27 22:37:07.307 UTC | 7 | 2022-01-02 17:53:41.43 UTC | null | null | null | null | 1,104,197 | null | 1 | 37 | javascript|regex | 34,256 | <p>This should do:
<code>^@?(\w){1,15}$</code></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.