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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,239,430 | Cannot set property 'innerHTML' of null | <p>Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?
I thought I understood innerHTML and had it working before.</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type ="text/javascript">
what();
function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>
</head>
<body>
<div id="hello"></div>
</body>
</html>
</code></pre> | 18,239,533 | 21 | 0 | null | 2013-08-14 18:25:51.933 UTC | 32 | 2022-04-18 05:38:28.457 UTC | 2013-08-14 19:01:04.23 UTC | null | 219,136 | null | 2,541,145 | null | 1 | 135 | javascript|onload|innerhtml | 584,271 | <p>You have to place the <code>hello</code> div before the script, so that it exists when the script is loaded. </p> |
15,141,115 | How to add custom header to AFNetworking on a JSONRequestOperation | <p>Hi, I have the following code accessing a URL:</p>
<pre><code>NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
completionHandler(nil, error);
}];
</code></pre>
<p>But I want to pass the user token as a parameter on <code>HEADER</code>, like <code>X-USER-TOKEN</code>.</p>
<p>Cant find it on <code>AFNetworking documentation</code>, should I change the operation type?</p> | 15,141,212 | 4 | 0 | null | 2013-02-28 16:50:39.52 UTC | 8 | 2015-05-21 03:28:36.43 UTC | 2014-04-07 19:51:43.643 UTC | null | 3,275,134 | null | 1,165,337 | null | 1 | 19 | ios|objective-c|json|afnetworking|nsurlrequest | 31,017 | <p>Use <code>AFHTTPClient</code> or subclass it!</p>
<p>You can set default headers with <code>-setDefaultHeader:value:</code> like this :</p>
<pre><code>[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];
</code></pre>
<p>You can check the <a href="http://cocoadocs.org/docsets/AFNetworking/1.3.3/Classes/AFHTTPClient.html#//api/name/setDefaultHeader:value:" rel="noreferrer">documentation</a></p> |
15,269,161 | in Python, How to join a list of tuples into one list? | <p>Following on my previous question <a href="https://stackoverflow.com/questions/15266593/how-to-group-list-items-into-tuple">How to group list items into tuple?</a></p>
<p>If I have a list of tuples, for example</p>
<pre><code>a = [(1,3),(5,4)]
</code></pre>
<p>How can I unpack the tuples and reformat it into one single list</p>
<pre><code>b = [1,3,5,4]
</code></pre>
<p>I think this also has to do with the <code>iter</code> function, but I really don't know how to do this. Please enlighten me.</p> | 15,269,211 | 5 | 3 | null | 2013-03-07 10:48:43.627 UTC | 6 | 2013-03-07 11:05:31.987 UTC | 2017-05-23 12:10:39.227 UTC | null | -1 | null | 1,382,745 | null | 1 | 29 | python|tuples | 46,003 | <pre><code>b = [i for sub in a for i in sub]
</code></pre>
<p>That will do the trick.</p> |
14,929,422 | Should implicit classes always extend AnyVal? | <p>Say I'm writing an extension method</p>
<pre><code>implicit class EnhancedFoo(foo: Foo) {
def bar() { /* ... */ }
}
</code></pre>
<p>Should you always include <code>extends AnyVal</code> in the class defininition? Under what circumstances would you not want to make an implicit class a value class?</p> | 14,931,302 | 2 | 0 | null | 2013-02-18 04:18:13.763 UTC | 11 | 2013-02-18 11:38:02.513 UTC | null | null | null | null | 770,361 | null | 1 | 60 | scala|implicit-conversion | 12,750 | <p>Let's look at the <a href="http://docs.scala-lang.org/overviews/core/value-classes.html#summary_of_limitations">limitations listed for value classes</a> and think when they may not be suitable for implicit classes:</p>
<ol>
<li><p>"must have only a primary constructor with exactly one public, val parameter whose type is not a value class." So if the class you are wrapping is itself a value class, you can't use an <code>implicit class</code> as a wrapper, but you can do this:</p>
<pre><code>// wrapped class
class Meters(val value: Int) extends AnyVal { ... }
// wrapper
class RichMeters(val value: Int) extends AnyVal { ... }
object RichMeters {
implicit def wrap(m: Meter) = new RichMeter(m.value)
}
</code></pre>
<p>If your wrapper has implicit parameters as well, you can try to move them to the method declarations. I.e. instead of</p>
<pre><code>implicit class RichFoo[T](foo: Foo[T])(implicit ord: Ordering[T]) {
def bar(otherFoo: Foo[T]) = // something using ord
}
</code></pre>
<p>you have</p>
<pre><code>implicit class RichFoo[T](foo: Foo[T]) extends AnyVal {
def bar(otherFoo: Foo[T])(implicit ord: Ordering[T]) = // something using ord
}
</code></pre></li>
<li><p>"may not have specialized type parameters." You may want the wrapper to be specialized when wrapping a class which itself has specialized type parameters.</p></li>
<li>"may not have nested or local classes, traits, or objects" Again, something which may well be useful for implementing a wrapper.</li>
<li>"may not define a <code>equals</code> or <code>hashCode</code> method." Irrelevant, since implicit classes also shouldn't have <code>equals/hashCode</code>.</li>
<li>"must be a top-level class or a member of a statically accessible object" This is also where you'd normally define implicit classes, but not required.</li>
<li>"can only have defs as members. In particular, it cannot have lazy vals, vars, or vals as members." Implicit classes can have all of those, though I can't think of a sensible usecase for <code>var</code>s or <code>lazy val</code>s.</li>
<li>"cannot be extended by another class." Again, implicit classes can be extended, but there is probably no good reason to.</li>
</ol>
<p>In addition, making your implicit class a value class could possibly change some behavior of code using reflection, but reflection shouldn't normally see implicit classes.</p>
<p>If your implicit class does satisfy all of those limitations, I can't think of a reason not to make it a value class.</p> |
28,013,318 | Mongo count occurrences of each value for a set of documents | <p>I have some documents like this:</p>
<pre><code>{
"user": '1'
},
{ "user": '1'
},
{
"user": '2'
},
{
"user": '3'
}
</code></pre>
<p>I'd like to be able to get a set of all the different users and their respective counts, sorted in decreasing order. So my output would be something like this:</p>
<pre><code>{
'1': 2,
'2': 1,
'3': 1
}
</code></pre>
<p>I think this can be done with a Mongo aggregate(), but I'm having a lot of trouble figuring out the right flow for this.</p> | 28,013,417 | 4 | 3 | null | 2015-01-18 18:36:17.513 UTC | 22 | 2020-07-15 15:10:00.677 UTC | null | null | null | null | 2,247,416 | null | 1 | 61 | mongodb|mongodb-query | 63,609 | <p>You can get result (not in your required format) via <strong><a href="http://docs.mongodb.org/manual/applications/aggregation/">aggregation</a></strong></p>
<pre><code>db.collection.aggregate(
{$group : { _id : '$user', count : {$sum : 1}}}
).result
</code></pre>
<p>the output for your sample documents is:</p>
<pre><code>"0" : {
"_id" : "2",
"count" : 1
},
"1" : {
"_id" : "3",
"count" : 1
},
"2" : {
"_id" : "1",
"count" : 2
}
</code></pre> |
28,238,042 | Setting CSS top percent not working as expected | <p>I tried a responsive css layout,but "top:50%" can't work and the "left:50%" can.
Why it happened?</p>
<pre><code><div style="position:relative;top:0%;left:0%;height:100%;width:100%">
<div style="position:absolute;top:50%;left:50%;">
</div>
</div>
</code></pre> | 28,238,276 | 4 | 4 | null | 2015-01-30 14:30:00.54 UTC | 2 | 2020-12-12 12:40:12.087 UTC | 2015-01-30 15:06:00.64 UTC | null | 564,353 | null | 3,761,095 | null | 1 | 19 | css | 40,294 | <p>Define a dimension for the parent container, e.g. div:</p>
<pre><code><div style="border: 2px solid red;position:relative;top:0%;left:0%;height:200px;width:300px">
<div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
</div>
</div>
</code></pre>
<p>Or</p>
<p>Another way is to just stretch the parent container, i.e. div, by its top, bottom, left, and right properties. Like this:</p>
<pre><code><div style="border: 2px solid red;position: absolute;top: 0px;bottom: 0px;left:0px;right:0px;">
<div style="border: 2px solid green;position:absolute;top:50%;left:50%;height:50%;width:50%">
</div>
</div>
</code></pre> |
8,312,132 | Vim: Editing the python.vim syntax file to highlight like Textmate | <p>I'm trying to edit the python.vim syntax file to duplicate the syntax highlighting for python in Textmate. The attached image illustrates the highlighting of function parameters which i'm struggling to achieve.</p>
<p><img src="https://imgur.com/HVLSg.png" alt="imgur pic of code"></p>
<p>The self, a, b is highlighted in Textmate but not in Vim. I figured that I have to do the following.</p>
<ol>
<li><p>Match a new region</p>
<pre><code>syn region pythonFunction start="(" end=")" contains=pythonParameters skipwhite transparent
</code></pre></li>
<li><p>Try to match a string followed by a comma</p>
<pre><code>syn match pythonParameters ".*" contained
</code></pre></li>
</ol>
<p>So in point 2 the ".*" will match any string at the moment and must be expanded further to be correct. However i'm not sure if i'm on the right path since the match in 2 is not constrained
to region between the brackets (). Any tips or input will be appreciated.</p>
<p><strong>EDIT 1: If anyone wondered how it turned out eventually.</strong></p>
<p>Here is my vim syntax highlighting for python.</p>
<p><img src="https://i.imgur.com/AD9Vt.png" alt="imgur pic of code"></p>
<p><strong>EDIT 2: So just for ultimate thoroughness I created a github page for it.</strong></p>
<p><a href="http://pfdevilliers.github.com/Pretty-Vim-Python/" rel="noreferrer">http://pfdevilliers.github.com/Pretty-Vim-Python/</a></p> | 8,312,932 | 2 | 3 | null | 2011-11-29 14:10:09.23 UTC | 9 | 2015-04-27 14:58:53.303 UTC | 2011-12-05 06:55:04.283 UTC | null | 268,088 | null | 268,088 | null | 1 | 10 | regex|vim | 2,131 | <p>Ok, you've got a couple problems.</p>
<ol>
<li>There is already a region called pythonFunction, for highlighting def and function names.</li>
<li>This region will match any parenthesis, anywhere</li>
</ol>
<p>So, find the pythonFunction match, and change it to this:</p>
<pre><code>syn match pythonFunction
\ "\%(\%(def\s\|class\s\|@\)\s*\)\@<=\h\%(\w\|\.\)*" contained nextgroup=pythonVars
</code></pre>
<p>Adding nextgroup tells vim to match pythonVars after a function definition.</p>
<p>Then add:</p>
<pre><code>syn region pythonVars start="(" end=")" contained contains=pythonParameters transparent keepend
syn match pythonParameters "[^,]*" contained skipwhite
</code></pre>
<p>Finally, to actually highlight it, find the <code>HiLink</code> section, and add:</p>
<pre><code>HiLink pythonParameters Comment
</code></pre>
<p>Change <code>Comment</code> to the grouping you want, or add your own. I'm using <code>Statement</code> myself.</p> |
7,728,436 | How to add a new column to an existing sheet and name it? | <p>Suppose I have the worksheet below:</p>
<pre><code>Empid EmpName Sal
1 david 100
2 jhon 200
3 steve 300
</code></pre>
<p>How can I insert a new column named "Loc"?</p>
<pre><code>Empid EmpName Loc Sal
1 david uk 100
2 jhon us 200
3 steve nj 300
</code></pre> | 7,728,521 | 2 | 0 | null | 2011-10-11 15:22:09.087 UTC | 3 | 2020-03-25 19:24:26.863 UTC | 2020-03-25 19:24:26.863 UTC | null | 2,756,409 | null | 896,839 | null | 1 | 21 | excel|vba | 108,116 | <p>Use insert method from range, for example</p>
<pre><code>Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
</code></pre> |
9,220,440 | How do I change the location of a canvas element? | <p>Can I change the x and y position of a canvas element in Javascript without using CSS? I cannot seem to find anyone who even asks it on the Internet.</p>
<p>EDIT: Can it be done in HTML?</p>
<pre><code><html>
<title>Testing</title>
<canvas id="main" width="200" height="200" style="border:1px solid #c3c3c3;">
Error: Browser does not support canvas element.
</canvas>
<script type="text/javascript">
var main = document.getElementById("main");
var render = main.getContext("2d");
main.width = 200;
main.height = 200;
main.style.left = 100x;
main.style.top = 100px;
</script>
</html>
</code></pre> | 9,220,588 | 2 | 9 | null | 2012-02-09 23:15:14.183 UTC | 1 | 2012-02-09 23:41:15.043 UTC | 2012-02-09 23:41:15.043 UTC | null | 405,017 | null | 1,072,445 | null | 1 | 6 | javascript|css|canvas | 47,092 | <pre><code><html>
<title>Testing</title>
<canvas id="main" width="200" height="200" style="border:1px solid #c3c3c3;">
Error: Browser does not support canvas element.
</canvas>
<script type="text/javascript">
var main = document.getElementById("main");
var render = main.getContext("2d");
main.width = 200;
main.height = 200;
main.style.left = "100px";
main.style.top = "100px";
main.style.position = "absolute";
</script>
</html>
</code></pre> |
8,597,595 | Can you trigger custom HTML5 form errors with JavaScript? | <p>If i have an input like <code><input type="text"></code> and i want to trigger a native error on the input, can you do that? Like (faux code) <code>ele.triggerError('Error Message');</code></p>
<p>It would then look like:</p>
<p><a href="https://i.stack.imgur.com/k49nh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k49nh.jpg" alt="error" /></a><br />
<sub>(source: <a href="http://tylergaw.com/storage/post_image_htmlFormErrors_defaultChrome.jpg" rel="nofollow noreferrer">tylergaw.com</a>)</sub></p>
<p>But with a custom message and for it's own validation function. Needed for AJAX validations for example.</p> | 8,597,819 | 2 | 4 | null | 2011-12-21 23:08:11.853 UTC | 7 | 2019-12-06 08:33:59.9 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 144,833 | null | 1 | 32 | javascript|html|forms | 30,051 | <p>The only way to trigger the native error is to submit the form. Although you can set a custom message with <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-setcustomvalidity" rel="noreferrer"><code>setCustomValidity</code></a> (<a href="https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message/5276722#5276722">as described in my answer here</a>) and you can trigger the <code>invalid</code> event with <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-checkvalidatity" rel="noreferrer"><code>checkValidity</code></a>, this only provides hooks for you to create your own validation UI. <a href="http://jsfiddle.net/robertc/cPRpg/" rel="noreferrer">Here's a simple example</a> you can play around with to verify.</p>
<p>Note that if you submit the form with the <code>submit()</code> method that will bypass the validation API. But if you <a href="http://jsfiddle.net/robertc/cPRpg/1/" rel="noreferrer">trigger the <code>click</code> event of the submit</a> button that will work in Firefox and Opera, but not Chrome. I'd avoid doing it right now.</p> |
30,829,916 | How can I center my ul li list in css? | <p>I have the following html code:</p>
<pre><code><section class="video">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<ul class="footer-nav">
<li><a href="#">Contact</a></li>
<li><a href="#">Press</a></li>
<li><a href="#">Careers</a></li>
<li><a href="#">Business</a></li>
<li><a href="#">Careers</a></li>
<li><a href="#">Business</a></li>
</ul>
</div>
</div>
</div>
</section>
</code></pre>
<p>and with my CSS included (in the <a href="http://jsfiddle.net/tfLz08vd/1/" rel="noreferrer">jsfiddle</a>) I get the result that the text is aligned to the left... How can I center everything, so the result says:</p>
<pre><code> Contact Press Careers Business Careers Bussiness
</code></pre>
<p>?
Thanks.</p> | 30,830,043 | 4 | 5 | null | 2015-06-14 13:25:15.943 UTC | 1 | 2018-05-28 11:53:01.07 UTC | null | null | null | null | 4,662,074 | null | 1 | 12 | html|css | 53,720 | <p><a href="http://jsfiddle.net/tfLz08vd/2/">http://jsfiddle.net/tfLz08vd/2/</a></p>
<p>just add </p>
<pre><code>ul {
text-align: center;
}
li {
display: inline-block;
}
</code></pre>
<p>Good luck! ;)</p> |
5,030,094 | Problems with Android's UriMatcher | <p>In an answer to a previous question of mine someone indicated that there is some flakiness (for lack of a better word) inherent in the Android class UriMatcher. Can anyone pinpoint the known issues with UriMatcher? I'm designing a Content Provider that relies on UriMatcher to match my Uris correctly (as opposed to incorrectly I suppose). Are there workarounds to the known issues? Or is there a better strategy for matching Uris? </p>
<p>Example:</p>
<p>Here is the code setting my UriMatcher</p>
<pre><code>private static final int MEMBER_COLLECTION_URI = 1;
private static final int MEMBER_SINGLE_URI = 2;
private static final int SUBMATERIAL_COLLECTION_URI = 3;
private static final int SUBMATERIAL_SINGLE_URI = 4;
private static final int JOBNAME_COLLECTION_URI = 5;
private static final int JOBNAME_SINGLE_URI = 6;
private static final int ALL_MEMBERS_URI = 7;
private static final int ALL_SUBMATERIAL_URI = 8;
static
{
//return the job and fab for anything matching the provided jobName
// JobNames/jobName
uriMatcher.addURI(JobMetaData.AUTHORITY, "JobNames/*/",
JOBNAME_SINGLE_URI);
//return a collection of members
// jobName/member/attribute/value
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/member/*/*/",
MEMBER_COLLECTION_URI);
//return a single member
// jobName/member/memberNumber
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/member/*/",
MEMBER_SINGLE_URI);
//return a collection of submaterial
// jobName/submaterial/attribute/value
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/submaterial/*/*",
SUBMATERIAL_COLLECTION_URI);
//return a single piece of submaterial
// jobName/submaterial/GUID
//GUID is the only way to uniquely identify a piece of submaterial
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/submaterial/*",
SUBMATERIAL_SINGLE_URI);
//Return everything in the member and submaterial tables
//that has the provided attribute that matches the provided value
// jobName/attribute/value
//not currently used
uriMatcher.addURI(JobMetaData.AUTHORITY, "JobNames/",
JOBNAME_COLLECTION_URI);
//return all members in a job
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/members/",
ALL_MEMBERS_URI);
}
</code></pre>
<p>Add another Uri:</p>
<pre><code>private static final int MEMBER_COLLECTION_URI = 1;
private static final int MEMBER_SINGLE_URI = 2;
private static final int SUBMATERIAL_COLLECTION_URI = 3;
private static final int SUBMATERIAL_SINGLE_URI = 4;
private static final int JOBNAME_COLLECTION_URI = 5;
private static final int JOBNAME_SINGLE_URI = 6;
private static final int ALL_MEMBERS_URI = 7;
private static final int ALL_SUBMATERIAL_URI = 8;
//ADDITIONAL URI
private static final int REVERSE_URI = 9;
static
{
//return the job and fab for anything matching the provided jobName
// JobNames/jobName
uriMatcher.addURI(JobMetaData.AUTHORITY, "JobNames/*/",
JOBNAME_SINGLE_URI);
//return a collection of members
// jobName/member/attribute/value
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/member/*/*/",
MEMBER_COLLECTION_URI);
//return a single member
// jobName/member/memberNumber
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/member/*/",
MEMBER_SINGLE_URI);
//return a collection of submaterial
// jobName/submaterial/attribute/value
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/submaterial/*/*",
SUBMATERIAL_COLLECTION_URI);
//return a single piece of submaterial
// jobName/submaterial/GUID
//GUID is the only way to uniquely identify a piece of submaterial
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/submaterial/*",
SUBMATERIAL_SINGLE_URI);
//Return everything in the member and submaterial tables
//that has the provided attribute that matches the provided value
// jobName/attribute/value
//not currently used
uriMatcher.addURI(JobMetaData.AUTHORITY, "JobNames/",
JOBNAME_COLLECTION_URI);
//return all members in a job
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/members/",
ALL_MEMBERS_URI);
//ADDITIONAL URI
uriMatcher.addURI(JobMetaData.AUTHORITY, "*/reverse/*",
REVERSE_URI);
}
</code></pre>
<p>And the last Uri is not recognized using:
uriMatcher.match(uri)</p>
<p>On the previous question (mentioned earlier) it was recommended that I move the offending Uri to the top of the calls to UriMatcher.put(String, int). That solved the previous problem (and left me with a bad taste in my mouth). Trying the same solution with this code results in the current first Uri (JOBNAME_SINGLE_URI) going unrecognized. I'm fairly sure that the issue isn't in my code (I've managed to create a working ContentProvider utilizing Uris and debug all of the problems with them prior to this issue), but rather is an issue with Uri matching in Android.</p>
<p>UPDATE: </p>
<pre><code>public final static String AUTHORITY = "dsndata.sds2mobile.jobprovider";
</code></pre>
<p>Sample Uri:<br>
content://dsndata.sds2mobile.jobprovider/SDS2MobileDemo/reverse/C_1</p> | 15,015,687 | 4 | 6 | null | 2011-02-17 14:17:11.597 UTC | 9 | 2013-02-22 02:06:39.67 UTC | 2011-03-24 20:23:46.817 UTC | null | 543,677 | null | 543,677 | null | 1 | 19 | android|uri|android-contentprovider | 10,530 | <p>There are three rules that aren't well documented but that are crucial to understanding the matching mechanism of UriMatcher:</p>
<ol>
<li>UriMatcher tries to match the entire Uri against the pattern. Much like the matches() method of java.util.regex.Matcher that returns true only if the entire region sequence matches the matcher's pattern (compared to the find() method that returns true for partial matches).</li>
<li>Wildcards are applied to one path segment only, meaning * or SDS2MobileDemo/* will never match SDS2MobileDemo/reverse/C_1 but */*/* or */*/C_1 will.</li>
<li>Once it finds a match for a path segment it won't find any alternative match for that particular path segment.</li>
</ol>
<p>Here are some examples using the following url: content://dsndata.sds2mobile.jobprovider/SDS2MobileDemo/reverse/C_1</p>
<p>The first two rules are easy to understand:</p>
<ul>
<li>SDS2MobileDemo/*/* will match</li>
<li>*/reverse/* will match</li>
<li>*/* won't match because it matches only two path segments</li>
<li>SDS2MobileDemo won't match because it matches only one path segment</li>
</ul>
<p>The third rule is a little harder to understand.
If you add the following Uris in this exact order:</p>
<ul>
<li>*/wrong/C_1</li>
<li>SDS2MobileDemo/reverse/C_1</li>
</ul>
<p>then it won't find a match because that translates into the following (pseudo) code:</p>
<pre><code>if ("*".matches("SDS2MobileDemo")) {
// tries to match the other parts but fails
}
else if ("SDS2MobileDemo".matches("SDS2MobileDemo")) {
// will never be executed
}
</code></pre>
<p>If you reverse the order the (pseudo) code becomes:</p>
<pre><code>if ("SDS2MobileDemo".matches("SDS2MobileDemo")) {
// tries to match the other parts and succeeds
}
else if ("*".matches("SDS2MobileDemo")) {
// will never be executed
}
</code></pre>
<p>Now as far as the original question goes.
SDS2MobileDemo/reverse/C_1 will get matched by */reverse/* but not e.g. JobNames/reverse/C_1 because that one will go down the JobNames/* path...
Also it's clear that moving */reverse/* to the top isn't the solution because all other patterns not starting with * won't match any more.
There's really no telling what the correct solution is as long as it's unknown which patterns should match which Uris.</p> |
5,418,560 | mysql adding hours to datetime | <p>In MYSQL DB I need to check if a "datetime" field is more than 24hours (or whatever) ago in which case delete the row.</p>
<p><strong>How to add hours to datetime in mysql?</strong></p>
<p>thanks</p>
<p>Luca </p> | 5,418,591 | 4 | 0 | null | 2011-03-24 11:42:19.82 UTC | 3 | 2015-02-24 12:20:42.703 UTC | null | null | null | null | 505,762 | null | 1 | 27 | mysql|datetime | 54,150 | <p>What about something like this :</p>
<pre><code>delete
from your_table
where your_field <= date_sub(now(), INTERVAL 1 day)
</code></pre>
<p><br>
With :</p>
<ul>
<li><a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_now"><strong><code>now()</code></strong></a> : the current date time</li>
<li><a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub"><strong><code>date_sub()</code></strong></a> to substract 1 day to that date</li>
</ul>
<p><br>
Or, if you want o use 24 hours instead of 1 day :</p>
<pre><code>delete
from your_table
where your_field <= date_sub(now(), INTERVAL 24 hour)
</code></pre> |
5,109,343 | @Transactional method called from another method doesn't obtain a transaction | <p>In Spring, a method that is annotated with <code>@Transactional</code> will obtain a new transaction if there isn't one already, but I noticed that a transactional method does not obtain any transaction if it is called from a non-transactional one. Here's the code.</p>
<pre><code>@Component
public class FooDao {
private EntityManager entityManager;
@PersistenceContext
protected void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Transactional
public Object save(Object bean) {
return this.entityManager.merge(bean);
}
public Object saveWrap(Object bean) {
return save(bean);
}
}
@Component
public class FooService {
private FooDao fooDao;
public void save(Object bean) {
this.fooDao.saveWrap(bean); // doesn't work.
this.fooDao.save(bean); // works
}
}
</code></pre>
<p><code>saveWrap()</code> is a regular method that calls <code>save()</code> which is transactional, but <code>saveWrap()</code> won't persist any changes. </p>
<p>I'm using Spring 3 and Hibernate 3. What am I doing wrong here? Thanks.</p> | 5,109,419 | 4 | 0 | null | 2011-02-24 19:16:05.793 UTC | 13 | 2021-05-28 08:50:07.93 UTC | 2011-02-24 19:22:33.197 UTC | null | 407,236 | null | 407,236 | null | 1 | 29 | java|hibernate|spring|jpa | 19,763 | <p>It is one of the limitations of Springs AOP. Because the dao bean is in fact a proxy when it is created by spring, it means that calling a method from within the same class will not call the advice (which is the transaction). The same goes for any other pointcut</p> |
5,126,721 | Rails not reloading session on ajax post | <p>I'm experiencing a very strange problem with Rails and ajax using jQuery (although I don't think it's specific to jQuery).</p>
<p>My Rails application uses the cookie session store, and I have a very simple login that sets the user id in the session. If the user_id isn't set in the session, it redirects to a login page. This works with no problems. JQuery GET requests work fine too. The problem is when I do a jQuery POST - the browser sends the session cookie ok (I confirmed this with Firebug and dumping request.cookies to the log) but the session is blank, i.e. session is {}.</p>
<p>I'm doing this in my application.js:</p>
<pre><code>$(document).ajaxSend(function(e, xhr, options) {
var token = $("meta[name='csrf-token']").attr('content');
xhr.setRequestHeader('X-CSRF-Token', token);
});
</code></pre>
<p>and here is my sample post:</p>
<pre><code>$.post('/test/1', { _method: 'delete' }, null, 'json');
</code></pre>
<p>which should get to this controller method (_method: delete):</p>
<pre><code>def destroy
respond_to do |format|
format.json { render :json => { :destroyed => 'ok' }.to_json }
end
end
</code></pre>
<p>Looking at the log and using Firebug I can confirm that the correct cookie value is sent in the request header when the ajax post occurs, but it seems that at some point Rails loses this value and therefore loses the session, so it redirects to the login page and never gets to the method.</p>
<p>I've tried everything I can think of to debug this but I'm coming around to the idea that this might be a bug in Rails. I'm using Rails 3.0.4 and jQuery 1.5 if that helps. I find it very strange that regular (i.e. non-ajax) get and post requests work, and ajax get requests work with no problems, it's just the ajax posts that don't.</p>
<p>Any help in trying to fix this would be greatly appreciated!</p>
<p>Many thanks,<br>
Dave</p> | 5,127,927 | 4 | 0 | null | 2011-02-26 11:52:04.767 UTC | 37 | 2020-07-31 10:53:43.27 UTC | null | null | null | null | 185,553 | null | 1 | 62 | ruby-on-rails|ajax|jquery | 17,803 | <p>I'm going to answer my own question as I've managed to work out what was going on. I'll post it here in case it's useful to anyone else!</p>
<p>After investigating further, I worked out that the code that was <em>supposed</em> to be setting the request header with the CSRF token, wasn't. This was the original code:</p>
<pre><code>$(document).ajaxSend(function(e, xhr, options) {
var token = $("meta[name='csrf-token']").attr('content');
xhr.setRequestHeader('X-CSRF-Token', token);
});
</code></pre>
<p>What was happening was that this code wasn't setting the header, Rails was receiving an Ajax request, the token didn't match and it was resetting the session. This used to raise an ActionController::InvalidAuthenticityToken error (I suppose I would have caught this earlier if an error was raised... oh well), but since Rails 3.0.4 it now just quietly resets the session.</p>
<p>So to send the token in the header, you have to do this (many thanks to <a href="http://jasoncodes.com/posts/rails-csrf-vulnerability" rel="noreferrer">this marvellous blog post</a>):</p>
<pre><code>$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
</code></pre>
<p>And now it all works as it should. Which is nice.</p> |
4,913,343 | What is the difference between URI, URL and URN? | <p>What's the difference between an URI, URL and URN? I have read a lot of sites (even Wikipedia) but I don't understand it.</p>
<p>URI: <a href="http://www.foo.com/bar.html" rel="noreferrer">http://www.foo.com/bar.html</a><br>
URL: <a href="http://www.foo.com/bar.html" rel="noreferrer">http://www.foo.com/bar.html</a><br>
URN: bar.html</p>
<p>Is this correct?</p> | 4,913,371 | 4 | 1 | null | 2011-02-06 12:40:30.91 UTC | 134 | 2021-05-25 09:40:08.43 UTC | 2011-02-06 12:48:12.293 UTC | null | 313,758 | null | 605,259 | null | 1 | 325 | http|url|uri|urn | 344,316 | <p>A Uniform Resource Identifier (<code>URI</code>) is a string of characters used to identify a name or a resource on the Internet.</p>
<p>A URI identifies a resource either by location, or a name, or both. <strong>A URI has two specializations known as URL and URN.</strong></p>
<p>A Uniform Resource Locator (<code>URL</code>) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it. A URL defines how the resource can be obtained. It does not have to be a HTTP URL (<code>http://</code>), a URL can also start with <code>ftp://</code> or <code>smb://</code>, specifying the protocol that's used to get the resource.</p>
<p>A Uniform Resource Name (<code>URN</code>) is a Uniform Resource Identifier (URI) that uses the URN scheme, and <strong>does not imply availability of the identified resource</strong>. Both URNs (names) and URLs (locators) are URIs, and a particular URI may be both a name and a locator at the same time.</p>
<p>This diagram (<a href="https://quintupledev.wordpress.com/2016/02/29/difference-between-uri-url-and-urn/" rel="noreferrer">source</a>) visualizes the relationship between URI, URN, and URL:</p>
<p><img src="https://quintupledev.files.wordpress.com/2016/02/eyevn.jpg" alt="URI, URN, URL diagram" /></p>
<p>The URNs are part of a larger Internet information architecture which is composed of URNs, <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Characteristic" rel="noreferrer">URCs</a> and URLs.</p>
<p><strong>bar.html is not a URN</strong>. A URN is similar to a person's name, while a URL is like a street address. The URN defines something's identity, while the URL provides a location. Essentially URN vs. URL is "what" vs. "where". A URN has to be of this form <code><URN> ::= "urn:" <NID> ":" <NSS></code> where <code><NID></code> is the Namespace Identifier, and <code><NSS></code> is the Namespace Specific String.</p>
<p><strong>To put it differently:</strong></p>
<ul>
<li>A URL is a URI that identifies a resource and also provides the means of locating the resource by describing the way to access it</li>
<li>A URL is a URI</li>
<li>A URI is not necessarily a URL</li>
</ul>
<p>I'd say the only thing left to make it 100% clear would be to have an example of an URI that is not an URL. We can use the examples in <a href="https://www.rfc-editor.org/rfc/rfc3986#section-1.1.2" rel="noreferrer">RFC3986</a>:</p>
<pre><code>URL: ftp://ftp.is.co.za/rfc/rfc1808.txt
URL: http://www.ietf.org/rfc/rfc2396.txt
URL: ldap://[2001:db8::7]/c=GB?objectClass?one
URL: mailto:[email protected]
URL: news:comp.infosystems.www.servers.unix
URL: telnet://192.0.2.16:80/
URN (not URL): urn:oasis:names:specification:docbook:dtd:xml:4.1.2
URN (not URL): tel:+1-816-555-1212 (disputed, see comments)
</code></pre> |
5,501,142 | Get max value for identity column without a table scan | <p>I have a table with an Identity column <code>Id</code>.</p>
<p>When I execute:</p>
<pre><code> select max(Id) from Table
</code></pre>
<p>SQL Server does a table scan and stream aggregate.</p>
<p>My question is, why can it not simply look up the last value assigned to Id? It's an <code>identity</code>, so the information must be tracked, right?</p>
<p>Can I look this up manually?</p> | 5,501,195 | 6 | 1 | null | 2011-03-31 14:03:50.227 UTC | 3 | 2019-12-23 17:19:51.973 UTC | null | null | null | null | 369 | null | 1 | 9 | sql|sql-server|sql-server-2008 | 38,338 | <p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms175098.aspx" rel="noreferrer">IDENT_CURRENT</a> to look up the last identity value to be inserted, e.g.</p>
<pre><code>IDENT_CURRENT('MyTable')
</code></pre>
<p>However, be cautious when using this function. A failed transaction can still increment this value, and, as <code>Quassnoi</code> states, this row might have been deleted.</p>
<p>It's likely that it does a table scan because it can't guarantee that the last identity value is the MAX value. For example the identity might not be a simple incrementing integer. You could be using a decrementing integer as your identity.</p> |
5,393,847 | How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC | <p>I want to convert the timestamp 2011-03-10T11:54:30.207Z to 10/03/2011 11:54:30.207. How can I do this? I want to convert ISO8601 format to UTC and then that UTC should be location aware. Please help</p>
<pre><code>String str_date="2011-03-10T11:54:30.207Z";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
date = (Date)formatter.parse(str_date);
System.out.println("output: " +date );
</code></pre>
<p>Exception :java.text.ParseException: Unparseable date: "2011-03-10T11:54:30.207Z"</p> | 5,395,998 | 6 | 0 | null | 2011-03-22 15:44:00.097 UTC | 12 | 2017-06-29 15:53:42.727 UTC | 2011-03-22 16:15:47.813 UTC | null | 617,966 | null | 617,966 | null | 1 | 26 | java|datetime | 113,824 | <p>Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.</p>
<p>However, here's a sample program using Joda Time which parses the text into a <code>DateTime</code> and then formats it. I've guessed at <em>a</em> format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the <em>local</em> time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.</p>
<pre><code>import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2011-03-10T11:54:30.207Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTime();
DateTime dt = parser.parseDateTime(text);
DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
System.out.println(formatter.print(dt));
}
}
</code></pre> |
5,034,781 | JS regex to split by line | <p>How do you split a long piece of text into separate lines? Why does this return <em>line1</em> twice?</p>
<pre><code>/^(.*?)$/mg.exec('line1\r\nline2\r\n');
</code></pre>
<blockquote>
<p>["line1", "line1"]</p>
</blockquote>
<p>I turned on the multi-line modifier to make <code>^</code> and <code>$</code> match beginning and end of lines. I also turned on the global modifier to capture <em>all</em> lines.</p>
<p>I wish to use a regex split and not <code>String.split</code> because I'll be dealing with both Linux <code>\n</code> and Windows <code>\r\n</code> line endings. </p> | 5,035,058 | 7 | 0 | null | 2011-02-17 21:17:45.123 UTC | 12 | 2021-06-24 11:23:58.173 UTC | null | null | null | null | 459,987 | null | 1 | 92 | javascript|regex|newline | 112,489 | <pre><code>arrayOfLines = lineString.match(/[^\r\n]+/g);
</code></pre>
<p>As Tim said, it is both the entire match and capture. It appears <code>regex.exec(string)</code> returns on finding the first match regardless of global modifier, wheras <code>string.match(regex)</code> is honouring global.</p> |
5,141,437 | Filtering os.walk() dirs and files | <p>I'm looking for a way to include/exclude files patterns and exclude directories from a <code>os.walk()</code> call.</p>
<p>Here's what I'm doing by now:</p>
<pre><code>import fnmatch
import os
includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']
def _filter(paths):
for path in paths:
if os.path.isdir(path) and not path in excludes:
yield path
for pattern in (includes + excludes):
if not os.path.isdir(path) and fnmatch.fnmatch(path, pattern):
yield path
for root, dirs, files in os.walk('/home/paulo-freitas'):
dirs[:] = _filter(map(lambda d: os.path.join(root, d), dirs))
files[:] = _filter(map(lambda f: os.path.join(root, f), files))
for filename in files:
filename = os.path.join(root, filename)
print(filename)
</code></pre>
<p>Is there a better way to do this? How?</p> | 5,141,829 | 8 | 0 | null | 2011-02-28 11:36:53.923 UTC | 25 | 2020-06-24 12:43:24.49 UTC | 2020-06-24 12:43:24.49 UTC | null | 222,758 | null | 222,758 | null | 1 | 51 | python|filtering|os.walk | 103,350 | <p>This solution uses <code>fnmatch.translate</code> to convert glob patterns to regular expressions (it assumes the includes only is used for files):</p>
<pre><code>import fnmatch
import os
import os.path
import re
includes = ['*.doc', '*.odt'] # for files only
excludes = ['/home/paulo-freitas/Documents'] # for dirs and files
# transform glob patterns to regular expressions
includes = r'|'.join([fnmatch.translate(x) for x in includes])
excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'
for root, dirs, files in os.walk('/home/paulo-freitas'):
# exclude dirs
dirs[:] = [os.path.join(root, d) for d in dirs]
dirs[:] = [d for d in dirs if not re.match(excludes, d)]
# exclude/include files
files = [os.path.join(root, f) for f in files]
files = [f for f in files if not re.match(excludes, f)]
files = [f for f in files if re.match(includes, f)]
for fname in files:
print fname
</code></pre> |
5,503,091 | Is there clean syntax for checking if multiple variables all have the same value? | <p>We have n variables <code>X = {x1,x2,...xn}</code> they are not in any structures whatsoever.</p>
<p>In python for example I can do that: <code>if (x1 == x2 == x3 == xn):</code></p>
<p>In java I must do: <code>if((x1 == x2) && (x2 == x3) && (x3 == xn)):</code></p>
<p>Do you know a simple way to improve this syntax? (Imagine very long variable name and lot of them)</p>
<p>Thanks.</p> | 5,503,148 | 13 | 6 | null | 2011-03-31 16:23:31.41 UTC | 9 | 2020-10-23 04:38:23.14 UTC | 2011-03-31 17:31:57.193 UTC | Aryabhatta | null | null | 192,468 | null | 1 | 29 | java | 32,377 | <p>If you have lots of these variables, have you considered putting them in a collection instead of having them as separate variables? There are various options at that point.</p>
<p>If you find yourself doing this a lot, you might want to write helper methods, possibly using varargs syntax. For example:</p>
<pre><code>public static boolean areAllEqual(int... values)
{
if (values.length == 0)
{
return true; // Alternative below
}
int checkValue = values[0];
for (int i = 1; i < values.length; i++)
{
if (values[i] != checkValue)
{
return false;
}
}
return true;
}
</code></pre>
<p>An alternative as presented by glowcoder is to force there to be at least one value:</p>
<pre><code>public static boolean areAllEqual(int checkValue, int... otherValues)
{
for (int value : otherValues)
{
if (value != checkValue)
{
return false;
}
}
return true;
}
</code></pre>
<p>In either case, use with:</p>
<pre><code>if (HelperClass.areAllEqual(x1, x2, x3, x4, x5))
{
...
}
</code></pre> |
17,065,378 | How to add elements of list to another list? | <p>I have two sql queries, which returning lists. My code:</p>
<pre><code>List<String> list = em.createNativeQuery(query1).getResultList();
list.addAll(em.createNativeQuery(query2).getResultList());
</code></pre>
<p>What I have: List with two sublists - sublist from query1 and sublist from query2.
<br>
What I need: One list with all elements from query1 and query2.
<br>
Any idea?</p>
<hr>
<p>Problem was in first sql query. Result was adding in object array, therefore addAll method not solves my problem.</p> | 17,065,983 | 3 | 10 | null | 2013-06-12 12:21:25.94 UTC | 2 | 2013-06-12 20:46:13.653 UTC | 2013-06-12 20:46:13.653 UTC | null | 1,799,747 | null | 1,799,747 | null | 1 | 11 | java|sql|list|collections | 39,075 | <p>addAll() will work. code is correct to get data from both the query</p> |
12,528,365 | Why is glReadPixels() failing in this code in iOS 6.0? | <p>The following is code I use for reading an image from an OpenGL ES scene:</p>
<pre><code>-(UIImage *)getImage{
GLint width;
GLint height;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
NSLog(@"%d %d",width,height);
NSInteger myDataLength = width * height * 4;
// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width * 4; x++)
{
buffer2[((height - 1) - y) * width * 4 + x] = buffer[y * 4 * width + x];
}
}
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpaceRef);
free(buffer);
free(buffer2);
return myImage;
}
</code></pre>
<p>This is working in iOS 5.x and lower versions, but on iOS 6.0 this is now returning a black image. Why is <code>glReadPixels()</code> failing on iOS 6.0?</p> | 12,569,942 | 2 | 8 | null | 2012-09-21 10:02:33.51 UTC | 10 | 2012-10-09 17:02:09.097 UTC | 2012-10-09 17:02:09.097 UTC | null | 19,679 | null | 563,848 | null | 1 | 18 | ios|opengl-es|ios6 | 9,169 | <pre><code>CAEAGLLayer *eaglLayer = (CAEAGLLayer *) self.layer;
eaglLayer.drawableProperties = @{
kEAGLDrawablePropertyRetainedBacking: [NSNumber numberWithBool:YES],
kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8
};
</code></pre>
<p>set </p>
<pre><code>kEAGLDrawablePropertyRetainedBacking = YES
</code></pre>
<p>(I do not know why this tip is going well..///)</p> |
12,417,378 | Cast from char * to int loses precision | <p>I am reading numbers from a file.When I try to put each number into an double dimensional array it gives me below error.How do I get rid of this message?
My variables:
FILE *fp;
char line[80];</p>
<p><strong>Error: Cast from char * to int loses precision</strong></p>
<p>Code:-</p>
<pre><code>#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char line[80],*pch;
int points[1000][10];
int centroid[1000][10];
float distance[1000][10];
int noofpts=0,noofvar=0,noofcentroids=0;
int i=0,j=0,k;
fp=fopen("kmeans.dat","r");
while(fgets(line,80,fp)!=NULL)
{
j=0;
pch=strtok(line,",");
while(pch!=NULL)
{
points[i][j]=(int)pch;
pch=strtok(NULL,",");
noofvar++;
j++;
}
noofpts++;
i++;
}
noofvar=noofvar/noofpts;
printf("No of points-%d\n",noofpts);
printf("No of variables-%d\n",noofvar);
return 0;
}
</code></pre> | 12,417,409 | 2 | 5 | null | 2012-09-14 02:29:51.373 UTC | 2 | 2013-06-13 08:04:31.75 UTC | null | null | null | null | 1,049,893 | null | 1 | 19 | c|casting|compiler-errors | 39,689 | <p>This is the offending line:</p>
<pre><code>points[i][j]=(int)pch;
</code></pre>
<p>You should replace it with</p>
<pre><code>points[i][j]=atoi(pch);
</code></pre>
<p><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/"><code>atoi</code></a> is a function that converts a C string representing an integer number in decimal representation to an <code>int</code>.</p> |
12,544,142 | Git - error: RPC failed; result=22, HTTP code = 401 fatal: The remote end hung up unexpectedly | <p>I am using ubuntu 11.10 machine. I have installed git of version 1.7.7.1. I am using git-cola to push and pull my code and I was able to commit and push my changes successfully.</p>
<p>Now, I have changed my machine and my new system is with the same above configurations. (Ubuntu 11.10 machine and git version 1.7.7.1).</p>
<p>In the new machine, I have issues on <strong>git push</strong>. I got the following error message when I tried to push my code:</p>
<pre><code>error: RPC failed; result=22, HTTP code = 401
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
</code></pre>
<p>On internet, I found it may due to any one of the following reason:</p>
<ul>
<li>Wrong git user password (In my case, I fee that I am using the correct password to push the code. Because, even now I was successful, when I push workspace code from my old system (with the same password!). But the problem is only from my new system.</li>
<li><p>To increase buffer size using the following command:</p>
<p>git config --system http.postBuffer 52428800</p></li>
</ul>
<p>I tried this, but no luck. Even tried to increase my buffer size more than 52428800, but still same error.</p>
<p>Stucked on this issue. Can anyone please suggest me a solution.</p>
<p>Thank you.</p> | 12,544,382 | 11 | 8 | null | 2012-09-22 13:21:46.543 UTC | 7 | 2020-09-19 16:43:11.957 UTC | 2012-09-22 13:57:50.503 UTC | null | 11,343 | user915303 | null | null | 1 | 24 | git|git-remote | 47,049 | <p>You must have made a mistake in the remote URL, double-check the output with <code>git remote -v</code> and fix it with </p>
<pre><code> git remote set-url origin <new-url>
</code></pre>
<p>assuming the remote name is <code>origin</code></p> |
12,068,558 | Use MongoEngine and PyMongo together | <p>I want to use <a href="http://mongoengine.org/" rel="noreferrer">MongoEngine</a> for my next project. Now I'm wondering whether I could also use <a href="http://api.mongodb.org/python/current/" rel="noreferrer">PyMongo</a> directly in the same project. Just for the case that I need something very special that is not supported directly via mongoengine.</p>
<p>Are there any doubts that this would work, or that I should not do that!?</p> | 12,068,819 | 1 | 0 | null | 2012-08-22 07:50:55.743 UTC | 11 | 2019-10-13 17:56:11.22 UTC | null | null | null | null | 237,690 | null | 1 | 26 | mongodb|pymongo|mongoengine | 9,816 | <p>Author of MongoEngine here - MongoEngine is built upon pymongo so of course you can drop into pymongo - or use raw pymongo in your code!</p>
<p>There are some document helpers that allow you to access raw pymongo methods in MongoEngine eg:</p>
<pre class="lang-py prettyprint-override"><code>class Person(Document):
name = StringField()
# Access the pymongo collection for the Person document
collection = Person._get_collection()
collection.find_one() # Use raw pymongo to query data
</code></pre> |
12,504,559 | ZeroMQ/ZMQ Push/Pull pattern usefulness | <p>In experimenting with the <code>ZeroMQ</code> <code>Push/Pull</code> (what they call <code>Pipeline</code>) socket type, I'm having difficulty understanding the utility of this pattern. It's billed as a "load-balancer".</p>
<p>Given a single server sending tasks to a number of workers, Push/Pull will evenly hand out the tasks between all the clients. 3 clients and 30 tasks, each client gets 10 tasks: client1 gets tasks 1, 4, 7,... client2, 2, 5,... and so on. Fair enough. Literally. </p>
<p>However, in practice there is often a non-homogeneous mix of task complexity or client compute resources (or availability), then this pattern breaks badly. All the tasks seem to be scheduled in advance, and the server has no knowledge of the progress of the clients or if they are even available. If client1 goes down, its remaining tasks are not sent to the other clients, but remain queued for client1. If client1 remains down, then those tasks are never handled. Conversely, if a client is faster at processing its tasks, it doesn't get further tasks and remains idle, as they remain scheduled for the other clients. </p>
<p>Using <code>REQ/REP</code> is one possible solution; tasks are then only given to an available resource . </p>
<p>So am I missing something? How is <code>Push/Pull</code> to be used effectively?
Is there a way to handle the asymmetry of clients, tasks, etc, with this socket type?</p>
<p>Thanks!</p>
<p>Here's a simple Python example:</p>
<pre><code># server
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.PUSH)
#socket = context.socket(zmq.REP) # uncomment for Req/Rep
socket.bind("tcp://127.0.0.1:5555")
i = 0
time.sleep(1) # naive wait for clients to arrive
while True:
#msg = socket.recv() # uncomment for Req/Rep
socket.send(chr(i))
i += 1
if i == 100:
break
time.sleep(10) # naive wait for tasks to drain
</code></pre>
<p>.</p>
<pre><code># client
import zmq
import time
import sys
context = zmq.Context()
socket = context.socket(zmq.PULL)
#socket = context.socket(zmq.REQ) # uncomment for Req/Rep
socket.connect("tcp://127.0.0.1:5555")
delay = float(sys.argv[1])
while True:
#socket.send('') # uncomment for Req/Rep
message = socket.recv()
print "recv:", ord(message)
time.sleep(delay)
</code></pre>
<p>Fire up 3 clients with a delay parameter on the command line (ie, 1, 1, and 0.1) and then the server, and see how all the tasks are evenly distributed. Then kill one of the clients to see that its remaining tasks aren't handled.</p>
<p>Uncomment the lines indicated to switch it to a <code>Req/Rep</code> type socket and watch a more effective load-balancer.</p> | 12,528,091 | 1 | 0 | null | 2012-09-20 00:13:47.52 UTC | 21 | 2018-09-14 04:45:24.29 UTC | 2018-09-14 04:45:24.29 UTC | null | 3,702,377 | null | 1,046,653 | null | 1 | 51 | zeromq|pyzmq | 26,025 | <p>It's not a load balancer, this was a faulty explanation that stayed in the 0MQ docs for a while. To do load-balancing, you have to get some information back from the workers about their availability. PUSH, like DEALER, is a round-robin distributor. It's useful for its raw speed, and simplicity. You don't need any kind of chatter, just pump tasks down the pipeline and they're sprayed out to all available workers as rapidly as the network can handle them.</p>
<p>The pattern is useful when you are doing really high numbers of small tasks, and where workers come and go infrequently. The pattern is not good for larger tasks that take time to complete because then you want a single queue that sends new tasks only to available workers. It also suffers from an anti-pattern where if a client sends many tasks and then workers connect, the first worker will grab 1,000 or so messages while the others are still busy connecting.</p>
<p>You can make your own higher-level routing in several ways. Look at the LRU patterns in the Guide: in this the workers explicitly tell the broker 'ready'. You can also do credit-based flow control, and this is what I'd do in any real load-balancing situation. It's a generalization of the LRU pattern. See <a href="http://hintjens.com/blog:15" rel="noreferrer">http://hintjens.com/blog:15</a></p> |
12,297,024 | How to delete all files from a specific folder? | <p>I save files in a specific folder at run time. After some time, I want to delete them programmatically. How do I delete all files from a specific folder?</p> | 12,297,060 | 6 | 1 | null | 2012-09-06 09:30:50.567 UTC | 10 | 2015-10-19 04:05:29.467 UTC | 2015-03-23 16:56:17.463 UTC | null | 63,550 | null | 1,067,943 | null | 1 | 59 | c#|.net | 138,258 | <pre><code>string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);
</code></pre>
<p>Or in a single line:</p>
<pre><code>Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);
</code></pre> |
12,527,191 | iOS AutoLayout - get frame size width | <p>I am developing using iOS 6 auto layout</p>
<p>I would like to log a message displaying the frame width of the view.</p>
<p>I can see the textView on the screen.</p>
<p>But I get the width and height as zero, am I missing something ?</p>
<pre><code>NSLog(@"textView = %p", self.textView);
NSLog(@"height = %f", self.textView.frame.size.height);
NSLog(@"width = %f", self.textView.frame.size.width);
textView = 0x882de00
height = 0.000000
width = 0.000000
</code></pre> | 12,527,242 | 9 | 0 | null | 2012-09-21 08:49:07.133 UTC | 23 | 2020-11-09 17:58:15.133 UTC | null | null | null | null | 1,046,037 | null | 1 | 59 | ios|nslog|autolayout | 69,947 | <p>I think auto layout hasn't had the time to layout your views by the time you call this. Auto layout hasn't happened by the time <code>viewDidLoad</code> is called, because it's called just after the views are loaded and it's only after that that the views are placed into the view controller's view hierarchy and eventually laid out (in the view's <code>layoutSubviews</code> method).</p>
<p>Edit: this answer points out why the scenario in the question doesn't work. <a href="https://stackoverflow.com/a/14147303/573976">@dreamzor's answer</a> points out where to place your code in order to solve it.</p> |
12,339,650 | Why is `vapply` safer than `sapply`? | <p>The documentation says</p>
<blockquote>
<p><code>vapply</code> is similar to <code>sapply</code>, but has a pre-specified type of return value, so it can be safer [...] to use.</p>
</blockquote>
<p>Could you please elaborate as to why it is generally safer, maybe providing examples?</p>
<hr>
<p>P.S.: I know the answer and I already tend to avoid <code>sapply</code>. I just wish there was a nice answer here on SO so I can point my coworkers to it. Please, no "read the manual" answer.</p> | 12,340,888 | 3 | 2 | null | 2012-09-09 13:51:11.273 UTC | 29 | 2021-06-04 15:19:34.53 UTC | 2015-08-31 00:12:48.897 UTC | null | 3,576,984 | null | 1,201,032 | null | 1 | 87 | r|apply|r-faq | 26,509 | <p>As has already been noted, <code>vapply</code> does two things:</p>
<ul>
<li>Slight speed improvement</li>
<li>Improves consistency by providing limited return type checks.</li>
</ul>
<p>The second point is the greater advantage, as it helps catch errors before they happen and leads to more robust code. This return value checking could be done separately by using <code>sapply</code> followed by <code>stopifnot</code> to make sure that the return values are consistent with what you expected, but <code>vapply</code> is a little easier (if more limited, since custom error checking code could check for values within bounds, etc.).</p>
<p>Here's an example of <code>vapply</code> ensuring your result is as expected. This parallels something I was just working on while PDF scraping, where <code>findD</code> would use a <a href="/questions/tagged/regex" class="post-tag" title="show questions tagged 'regex'" rel="tag">regex</a> to match a pattern in raw text data (e.g. I'd have a list that was <code>split</code> by entity, and a regex to match addresses within each entity. Occasionally the PDF had been converted out-of-order and there would be two addresses for an entity, which caused badness).</p>
<pre><code>> input1 <- list( letters[1:5], letters[3:12], letters[c(5,2,4,7,1)] )
> input2 <- list( letters[1:5], letters[3:12], letters[c(2,5,4,7,15,4)] )
> findD <- function(x) x[x=="d"]
> sapply(input1, findD )
[1] "d" "d" "d"
> sapply(input2, findD )
[[1]]
[1] "d"
[[2]]
[1] "d"
[[3]]
[1] "d" "d"
> vapply(input1, findD, "" )
[1] "d" "d" "d"
> vapply(input2, findD, "" )
Error in vapply(input2, findD, "") : values must be length 1,
but FUN(X[[3]]) result is length 2
</code></pre>
<p>Because two there are two d's in the third element of input2, vapply produces an error. But sapply changes the class of the output from a character vector to a list, which could break code downstream.</p>
<p>As I tell my students, part of becoming a programmer is changing your mindset from "errors are annoying" to "errors are my friend."</p>
<p><strong>Zero length inputs</strong><br />
One related point is that if the input length is zero, <code>sapply</code> will always return an empty list, regardless of the input type. Compare:</p>
<pre><code>sapply(1:5, identity)
## [1] 1 2 3 4 5
sapply(integer(), identity)
## list()
vapply(1:5, identity, integer(1))
## [1] 1 2 3 4 5
vapply(integer(), identity, integer(1))
## integer(0)
</code></pre>
<p>With <code>vapply</code>, you are guaranteed to have a particular type of output, so you don't need to write extra checks for zero length inputs.</p>
<p><strong>Benchmarks</strong></p>
<p><code>vapply</code> can be a bit faster because it already knows what format it should be expecting the results in.</p>
<pre><code>input1.long <- rep(input1,10000)
library(microbenchmark)
m <- microbenchmark(
sapply(input1.long, findD ),
vapply(input1.long, findD, "" )
)
library(ggplot2)
library(taRifx) # autoplot.microbenchmark is moving to the microbenchmark package in the next release so this should be unnecessary soon
autoplot(m)
</code></pre>
<p><img src="https://i.stack.imgur.com/pW6qV.png" alt="autoplot" /></p> |
3,519,565 | Find the indexes of all regex matches? | <p>I'm parsing strings that could have any number of quoted strings inside them (I'm parsing code, and trying to avoid PLY). I want to find out if a substring is quoted, and I have the substrings index. My initial thought was to use re to find all the matches and then figure out the range of indexes they represent.</p>
<p>It seems like I should use re with a regex like <code>\"[^\"]+\"|'[^']+'</code> (I'm avoiding dealing with triple quoted and such strings at the moment). When I use findall() I get a list of the matching strings, which is somewhat nice, but I need indexes.</p>
<p>My substring might be as simple as <code>c</code>, and I need to figure out if this particular <code>c</code> is actually quoted or not.</p> | 3,519,601 | 3 | 1 | null | 2010-08-19 07:14:56.88 UTC | 29 | 2021-10-26 16:51:00.01 UTC | 2021-10-26 16:51:00.01 UTC | null | 967,621 | null | 212,348 | null | 1 | 100 | python|regex|indexing | 118,676 | <p>This is what you want: (<a href="http://docs.python.org/2/library/re.html#re.finditer">source</a>)</p>
<blockquote>
<pre><code>re.finditer(pattern, string[, flags])
</code></pre>
<p>Return an iterator yielding MatchObject instances over all
non-overlapping matches for the RE pattern in string. The string is
scanned left-to-right, and matches are returned in the order found. Empty
matches are included in the result unless they touch the beginning of
another match.</p>
</blockquote>
<p>You can then get the start and end positions from the MatchObjects.</p>
<p>e.g.</p>
<pre><code>[(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]
</code></pre> |
20,525,820 | CSS3 simple donut chart | <p>What I'm trying to do is create a simple donut chart. I'm currently using CSS(3) only but I don't know if it's possible without javascript.</p>
<p>What I have so far:
<a href="http://jsfiddle.net/aBP5Q/">http://jsfiddle.net/aBP5Q/</a></p>
<p>HTML:</p>
<pre><code><div class="donut-container" style="background: #9C0;">
<div class="donut-inner">
<div class="donut-label">HTML</div>
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>.donut-container {
width: 150px;
height: 150px;
float: left;
-webkit-border-radius: 75px;
-moz-border-radius: 75px;
border-radius: 75px;
margin-right: 20px;
}
.donut-inner {
width: 134px;
height: 134px;
position: relative;
top: 8px;
left: 8px;
background: #FFF;
-webkit-border-radius: 65px;
-moz-border-radius: 65px;
border-radius: 65px;
}
.donut-label {
line-height: 130px;
text-align: center;
font-size: 20px;
}
</code></pre>
<p>I would like to display the green and blue colors as the precentage. So no green is 0% and full green (360 degrees) is 100%. Maybe even with a simple animation when the chart is loaded if its possible.</p>
<p>Your help is much appreciated. </p> | 28,345,637 | 5 | 4 | null | 2013-12-11 17:22:54.193 UTC | 12 | 2021-04-06 11:36:54.41 UTC | 2013-12-11 17:24:28.297 UTC | null | 2,641,519 | null | 2,876,105 | null | 1 | 24 | css|donut-chart | 66,429 | <p>SVG for the win!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
position: relative;
float: left;
}
.item h2 {
text-align:center;
position: absolute;
line-height: 125px;
width: 100%;
}
svg {
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.circle_animation {
stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
stroke-dashoffset: 440;
}
.html .circle_animation {
-webkit-animation: html 1s ease-out forwards;
animation: html 1s ease-out forwards;
}
.css .circle_animation {
-webkit-animation: css 1s ease-out forwards;
animation: css 1s ease-out forwards;
}
@-webkit-keyframes html {
to {
stroke-dashoffset: 80; /* 50% would be 220 (half the initial value specified above) */
}
}
@keyframes html {
to {
stroke-dashoffset: 80;
}
}
@-webkit-keyframes css {
to {
stroke-dashoffset: 160;
}
}
@keyframes css {
to {
stroke-dashoffset: 160;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item html">
<h2>HTML</h2>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
</g>
</svg>
</div>
<div class="item css">
<h2>CSS</h2>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#69aff4" fill="none"/>
</g>
</svg>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/4azpfk3r/" rel="noreferrer">JSFiddle version</a></p>
<hr>
<p>Here is a version with background circles as requested in the comments:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
position: relative;
float: left;
}
.item h2 {
text-align:center;
position: absolute;
line-height: 125px;
width: 100%;
}
svg {
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
}
.circle_animation {
stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
stroke-dashoffset: 440;
}
.html .circle_animation {
-webkit-animation: html 1s ease-out forwards;
animation: html 1s ease-out forwards;
}
.css .circle_animation {
-webkit-animation: css 1s ease-out forwards;
animation: css 1s ease-out forwards;
}
@-webkit-keyframes html {
to {
stroke-dashoffset: 80; /* 50% would be 220 (half the initial value specified above) */
}
}
@keyframes html {
to {
stroke-dashoffset: 80;
}
}
@-webkit-keyframes css {
to {
stroke-dashoffset: 160;
}
}
@keyframes css {
to {
stroke-dashoffset: 160;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item html">
<h2>HTML</h2>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#f2f2f2" fill="none"/>
<circle class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#6fdb6f" fill="none"/>
</g>
</svg>
</div>
<div class="item css">
<h2>CSS</h2>
<svg width="160" height="160" xmlns="http://www.w3.org/2000/svg">
<g>
<title>Layer 1</title>
<circle r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#f2f2f2" fill="none"/>
<circle class="circle_animation" r="69.85699" cy="81" cx="81" stroke-width="8" stroke="#69aff4" fill="none"/>
</g>
</svg>
</div></code></pre>
</div>
</div>
</p>
<hr>
<h2>How does it work?</h2>
<p><code>stroke-dasharray</code> is used to define the 'pattern' a dashed line uses (<a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray" rel="noreferrer">MDN</a>). By providing a single value you create a pattern with a dash of 440px and a space of 440px. (440px is roughly the circumference of the circle). </p>
<p><code>stroke-dashoffset</code> effectively moves the starting point of the dash pattern (<a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset" rel="noreferrer">MDN</a>). </p>
<p>A <code>dash-offset</code> of 220 (half of the <code>stroke-dasharray</code>) would produce a half-circle. 110 = quarter circle etc.</p> |
20,618,355 | How to write a countdown timer in JavaScript? | <p>Just wanted to ask how to create the simplest possible countdown timer.</p>
<p>There'll be a sentence on the site saying: </p>
<blockquote>
<p>"Registration closes in 05:00 minutes!"</p>
</blockquote>
<p>So, what I want to do is to create a simple js countdown timer that goes from "05:00" to "00:00" and then resets to "05:00" once it ends.</p>
<p>I was going through some answers before, but they all seem too intense (Date objects, etc.) for what I want to do.</p> | 20,618,517 | 3 | 5 | null | 2013-12-16 18:41:08.45 UTC | 155 | 2021-03-11 22:06:05.843 UTC | 2021-03-11 22:06:05.843 UTC | null | 278,842 | null | 3,104,868 | null | 1 | 301 | javascript|timer|countdown|countdowntimer | 750,532 | <p>I have two demos, one with <code>jQuery</code> and one without. Neither use date functions and are about as simple as it gets.</p>
<p><a href="https://jsfiddle.net/wr1ua0db/17/" rel="noreferrer"><strong>Demo with vanilla JavaScript</strong></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 startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/df773p9m/4/" rel="noreferrer"><strong>Demo with jQuery</strong></a> </p>
<pre><code>function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
</code></pre>
<p><strong>However if you want a more accurate timer that is only slightly more complicated:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body></code></pre>
</div>
</div>
</p>
<p>Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"</p>
<ul>
<li>Should a count down timer count down? <strong>Yes</strong> </li>
<li>Should a count down timer know how to display itself on the DOM? <strong>No</strong> </li>
<li>Should a count down timer know to restart itself when it reaches 0? <strong>No</strong> </li>
<li>Should a count down timer provide a way for a client to access how much time is left? <strong>Yes</strong></li>
</ul>
<p>So with these things in mind lets write a better (but still very simple) <code>CountDownTimer</code></p>
<pre><code>function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
</code></pre>
<p>So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the <code>startTimer</code> functions.</p>
<p><a href="https://jsfiddle.net/robbmj/czu6scth/2/" rel="noreferrer">An example that displays the time in XX:XX format and restarts after reaching 00:00</a></p>
<p><a href="https://jsfiddle.net/robbmj/vpq5toeq/2/" rel="noreferrer">An example that displays the time in two different formats</a></p>
<p><a href="https://jsfiddle.net/robbmj/vpq5toeq/4/" rel="noreferrer">An example that has two different timers and only one restarts</a></p>
<p><a href="https://jsfiddle.net/robbmj/Lzyxnaoq/2/" rel="noreferrer">An example that starts the count down timer when a button is pressed</a></p> |
26,032,364 | Send notification to all the devices connected to a Wi-Fi network | <p>Is there any way to send a notification to the devices which are connected to a particular Wi-Fi network?</p>
<p>Say, I have a Wi-Fi network named "My Wi-Fi", which is not secured, that is any one can connect. A public network.</p>
<p>There may be N-number of users connected to "My Wi-Fi". These users can perform any kind of transaction, say online payment. </p>
<p>Now if I want to turn off or shut down "My Wi-Fi" router or access point, these transactions may fail.</p>
<p>So before shutting down, I want to send a text notification to all the users connected to "My Wi-Fi" network. (User does not have any kind of app in their device, to push the notification.)</p>
<p>Is this possible?</p> | 26,195,669 | 4 | 7 | null | 2014-09-25 06:51:11.763 UTC | 9 | 2021-04-07 14:46:46.55 UTC | 2014-09-25 07:11:54.887 UTC | null | 2,147,481 | null | 2,147,481 | null | 1 | 21 | java|android|ios|networking|wifi | 46,453 | <p>There is no standard method of sending (pushing) a message to all devices attached to a Wi-Fi network. If there was a way, it would be easy to find the specification and point to how it is to be done. Unfortunately, it is difficult to prove the absence of something.</p>
<p>As you clearly realized, it would be possible to do so if an appropriate page which you control was open in a browser, or application running, on their device. You could develop a framework where users have to sign on and keep a page open, or application running, in order to connect to your Wi-Fi.</p>
<p>Given that you control the router, it would be physically possible for you to write code which intercepted the packets being transmitted through the router and inserted such a warning within the HTTP of pages being sent to the various connected devices. This assumes that they are using HTTP to view normal pages. You could, of course, also insert a warning in other protocols. Depending on your jurisdiction this might be illegal, or have other legal issues. I would consider doing so to be a Bad Idea™.</p> |
11,057,839 | Set the css class of a div using code behind | <p>I understand that we can set the various style attributes from code behind using :</p>
<pre><code>divControl.Style("height") = "200px"
</code></pre>
<p>But how to set it's class instead of declaring each of the styles from code?</p> | 11,057,882 | 2 | 0 | null | 2012-06-15 20:35:32.013 UTC | 3 | 2012-06-16 00:52:48.593 UTC | 2012-06-16 00:52:48.593 UTC | null | 477,420 | null | 1,140,766 | null | 1 | 10 | c#|asp.net|vb.net | 70,152 | <p><strong>C#</strong></p>
<pre><code>divControl.Attributes["class"] = "myClass";
</code></pre>
<p><strong>VB</strong></p>
<pre><code>divControl.Attributes("class") = "myClass"
</code></pre>
<p>You'll need to have a rule like this one on your css file</p>
<pre><code>.myClass
{
height:200px;
/*...more styles*/
}
</code></pre> |
10,865,006 | How to save a Chart control picture to a file? | <p>Having a chart displayed with a <code>System.Windows.Forms.DataVisualization.Charting.Chart</code> control in a .Net 4.0 WinForms application, can I save its render into a picture file?</p> | 10,865,022 | 2 | 0 | null | 2012-06-02 18:50:28.883 UTC | 7 | 2015-09-21 08:27:00.293 UTC | 2012-06-02 18:53:40.893 UTC | null | 266,143 | null | 274,627 | null | 1 | 15 | c#|.net|winforms|charts|mschart | 49,051 | <p>How about the <a href="http://msdn.microsoft.com/en-us/library/dd456181.aspx"><code>Chart.SaveImage()</code></a> method?</p> |
11,015,912 | How do I get IP_ADDRESS in IPV4 format | <p>I am trying to get the IP address of an device i.e using WIFI or 3G connection. I am getting the ip address in IPV6 format which is not understandable. I want in IPV4 format IP address.I have done google but dint found any proper solutions.</p>
<p>here is code which I am using to get IP address of an device</p>
<pre><code>public String getLocalIpAddress() {
try {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress()) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
</code></pre>
<p>I am getting this ouput :</p>
<pre><code>ip1--:/fe80::5054:ff:fe12:3456%eth0%2
ip2--:fe80::5054:ff:fe12:3456%eth0
</code></pre>
<p>It should be displayed like this :</p>
<pre><code>192.168.1.1
</code></pre>
<p>please help me out..</p> | 11,026,705 | 4 | 0 | null | 2012-06-13 13:29:23.917 UTC | 13 | 2020-01-16 14:01:54.337 UTC | 2012-06-13 13:32:26.983 UTC | null | 57,135 | null | 1,208,510 | null | 1 | 23 | android|ip-address|android-4.0-ice-cream-sandwich|android-networking | 34,979 | <p>After trying many tricks.. finally I can get the IP address in IPV4 format.. Here is my code.. </p>
<pre><code>public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
// for getting IPV4 format
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
// return inetAddress.getHostAddress().toString();
return ip;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
</code></pre>
<p>Added <strong>if</strong> condition as shown below </p>
<pre><code> /**This shows IPV4 format IP address*/
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())){}
</code></pre>
<p>instead of this</p>
<pre><code> /**This shows IPV6 format IP address*/
if (!inetAddress.isLoopbackAddress()){}
</code></pre>
<p>Many Thanks..
Rahul</p>
<p>An alternative for checking if the address is a version 4 address is:</p>
<pre><code>if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)
</code></pre> |
11,074,228 | GPS Manifest: GPS in App is optional, want to make it available to GPS less devices too | <p>On uploading my App onto the market today, I saw that it is only available to devices with GPS, so this excludes some tablets.</p>
<p>GPS in my App is optional. Is it possible to release one App for devices with and without GPS or do I need to make an extra version (would be no problem, though)?</p>
<p>If it is possible, I guess there is some sort of method to check if(deviceHasGPS()){...}.
Is there one ?</p>
<p>This is the part of my manifest:</p>
<pre><code><uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
</code></pre>
<p>Edit: thanks for the Answer <a href="https://stackoverflow.com/users/1069068/raghav-sood">Raghav Sood</a>!</p>
<p>Add to Manifest:</p>
<pre><code><uses-feature android:name="android.hardware.location.gps"
android:required="false" />
</code></pre>
<p>Implement the following:</p>
<pre><code>locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean deviceHasGPS = false;
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
deviceHasGPS = true;
}
</code></pre>
<p>to test it on a device with gps, just surround the gps things with if(deviceHasGPS){...}
then remove in the manifest:</p>
<pre><code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code></pre>
<p>set deviceHasGPS to always false and see if the App force closes.</p> | 11,074,257 | 1 | 2 | null | 2012-06-17 19:37:11.423 UTC | 5 | 2012-06-18 11:37:31.21 UTC | 2017-05-23 11:54:12.947 UTC | null | -1 | null | 1,386,748 | null | 1 | 28 | android|gps|android-manifest | 9,009 | <p>Add the following to your manifest</p>
<pre><code><uses-feature android:name="android.hardware.location.gps" android:required="false" />
</code></pre>
<p>This will tell Google Play that while your app has the GPS, it's absolute requirement isn't true. However, you should handle the lack of GPS in your app gracefully, instead of letting it crash.</p>
<p>To check is the device has GPS you can call <code>LocationManager.getAllProviders()</code> and check whether <code>LocationManager.GPS_PROVIDER</code> is included in the list.</p> |
11,172,742 | Can't set foreign key relationship | <p>I have some problem with MySQL Workbench in that I sometimes can't set foreign keys when creating tables. I say sometimes cause it's not always like this. The thing is when I enter a FK and choose a reference table I can't pick a referenced column. I can't click the check box and the drop down list is empty. I can't really figure out what the problem is cause I see no real difference from the FK's that are working. I have checked data type, name etc and they are correct. I'll provide a SS to elaborate. The green marked key (id_hem) is working ok and the red marks are those that don't.<br><br>
<img src="https://i.stack.imgur.com/3vOI8.jpg" alt="Screenshot of WB"></p> | 11,172,794 | 13 | 1 | null | 2012-06-23 20:30:48.817 UTC | 3 | 2021-02-09 19:17:55.547 UTC | null | null | null | null | 1,399,283 | null | 1 | 38 | mysql-workbench | 34,777 | <p>I had the same problem and the issue was in foreign key indexes. MySQL workbench generates too long names for fk indexes sometimes. Manual correction helps.</p> |
12,905,763 | get post by post name instead of id | <p>Ok i have this code currently.</p>
<pre><code><?php
$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max- width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id);
echo "<div class='thewidgets'>";
echo substr($queried_post->post_content, 0, 500);
echo "<a href='".get_permalink( 26 )."' title='Read the whole post' class='rm'>Read More</a>";
echo "</div>";
echo "</div></div>";
?>
</code></pre>
<p>As you can see to the above code, the routine is to get the post by ID, but my permalinks change into post name instead of post id for SEO purposes. How do I get the post by post name?</p>
<p>Hope someone here could figure it out. Thank you.</p> | 67,398,947 | 3 | 3 | null | 2012-10-16 00:09:14.16 UTC | 1 | 2022-03-09 21:34:30.943 UTC | 2012-10-16 00:16:18.497 UTC | null | 319,403 | null | 1,292,042 | null | 1 | 17 | php|wordpress | 47,456 | <p>Use <code>WP_Query</code>. This function will retrieve the first post with the given name, or <code>null</code> if nothing is found:</p>
<pre class="lang-php prettyprint-override"><code>function get_post_by_name(string $name, string $post_type = "post") {
$query = new WP_Query([
"post_type" => $post_type,
"name" => $name
]);
return $query->have_posts() ? reset($query->posts) : null;
}
</code></pre>
<p>By default this will search for an item of the type <code>post</code>:</p>
<p><code>get_post_by_name("my-post")</code></p>
<p>As a second argument you can set that to something else:</p>
<p><code>get_post_by_name("my-page", "page")</code></p> |
13,150,486 | Get integer part of number | <p>So I have a table with numbers in decimals, say</p>
<pre><code>id value
2323 2.43
4954 63.98
</code></pre>
<p>And I would like to get</p>
<pre><code>id value
2323 2
4954 63
</code></pre>
<p>Is there a simple function in T-SQL to do that?</p> | 13,150,519 | 3 | 0 | null | 2012-10-31 02:37:53.44 UTC | 1 | 2019-06-20 14:19:16.587 UTC | null | null | null | null | 1,479,269 | null | 1 | 26 | tsql | 61,204 | <pre><code>SELECT FLOOR(value)
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms178531.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms178531.aspx</a></p>
<p>FLOOR returns the largest integer less than or equal to the specified numeric expression.</p> |
12,678,389 | Rails - How to refresh an association after a save | <p>I have a category with a list of items. The items have a position and the category has a relationship has_many :items, :order => "position". When a user updates a position value, I want to see its position. My position is a float to allow moving between rounded numbers.</p>
<pre><code>pos=item.category.items.map(&:id)
current_position=pos.index(id.to_i)
item.save # want to refresh the relationship here
pos_new=item.categoty.items.map(&:id)
# grabbing this since just accessing item isn't updated if positioning has changed
item_new=Item.find(id)
pos_new=item_new.category.items.map(&:id)
new_position=pos_new.index(id)
if current_position!=new_position
is_moved=true # sent back in JSON to propagate a dynamic change.
end
</code></pre>
<p>The above works but it seems really verbose. Is there a way for me to tell on item save that the category relationship needs to be refreshed since the order could be changed?</p> | 12,678,422 | 3 | 0 | null | 2012-10-01 17:53:07.91 UTC | 2 | 2021-12-13 20:47:17.16 UTC | 2021-12-13 20:47:17.16 UTC | null | 278,842 | null | 152,825 | null | 1 | 30 | ruby-on-rails|ruby-on-rails-3|activerecord | 32,082 | <p>You can use <code>item.reload</code> that will refetch the model from the database and next time you call an association, it will refetch it.</p> |
13,220,743 | Implement paging (skip / take) functionality with this query | <p>I have been trying to understand a little bit about how to implement custom paging in SQL, for instance reading <a href="https://stackoverflow.com/questions/548475/efficient-way-to-implement-paging">articles like this one</a>.</p>
<p>I have the following query, which works perfectly. But I would like to implement paging with this one.</p>
<pre><code>SELECT TOP x PostId FROM ( SELECT PostId, MAX (Datemade) as LastDate
from dbForumEntry
group by PostId ) SubQueryAlias
order by LastDate desc
</code></pre>
<p><strong>What is it I want</strong></p>
<p>I have forum posts, with related entries. I want to get the posts with the latest added entries, so I can select the recently debated posts.</p>
<p>Now, I want to be able to get the "top 10 to 20 recently active posts", instead of "top 10".</p>
<p><strong>What have I tried</strong></p>
<p>I have tried to implement the ROW functions as the one in the article, but really with no luck. </p>
<p>Any ideas how to implement it?</p> | 13,221,574 | 6 | 0 | null | 2012-11-04 17:00:54.207 UTC | 37 | 2020-09-21 22:43:55.42 UTC | 2017-05-23 12:18:15.267 UTC | null | -1 | null | 197,304 | null | 1 | 176 | sql|sql-server|join|pagination | 200,987 | <p>In <strong>SQL Server 2012</strong> it is very very easy </p>
<pre><code>SELECT col1, col2, ...
FROM ...
WHERE ...
ORDER BY -- this is a MUST there must be ORDER BY statement
-- the paging comes here
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
</code></pre>
<p>If we want to skip ORDER BY we can use</p>
<pre><code>SELECT col1, col2, ...
...
ORDER BY CURRENT_TIMESTAMP
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
</code></pre>
<p><em>(I'd rather mark that as a hack - but it's used, e.g. by NHibernate. To use a wisely picked up column as ORDER BY is preferred way)</em></p>
<p>to answer the question:</p>
<pre><code>--SQL SERVER 2012
SELECT PostId FROM
( SELECT PostId, MAX (Datemade) as LastDate
from dbForumEntry
group by PostId
) SubQueryAlias
order by LastDate desc
OFFSET 10 ROWS -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows
</code></pre>
<p>New key words <code>offset</code> and <code>fetch next</code> (just following SQL standards) were introduced.</p>
<p><em>But I guess, that you are not using <strong>SQL Server 2012</strong>, right</em>? In previous version it is a bit (little bit) difficult. Here is comparison and examples for all SQL server versions: <a href="http://www.mssqltips.com/sqlservertip/2696/comparing-performance-for-different-sql-server-paging-methods/">here</a></p>
<p>So, this could work in <strong>SQL Server 2008</strong>:</p>
<pre><code>-- SQL SERVER 2008
DECLARE @Start INT
DECLARE @End INT
SELECT @Start = 10,@End = 20;
;WITH PostCTE AS
( SELECT PostId, MAX (Datemade) as LastDate
,ROW_NUMBER() OVER (ORDER BY PostId) AS RowNumber
from dbForumEntry
group by PostId
)
SELECT PostId, LastDate
FROM PostCTE
WHERE RowNumber > @Start AND RowNumber <= @End
ORDER BY PostId
</code></pre> |
12,702,561 | Iterate through a C++ Vector using a 'for' loop | <p>I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter of the <code>for</code> loop is always something based on the vector. In Java I might do something like this with an ArrayList:</p>
<pre><code>for(int i=0; i < vector.size(); i++){
vector[i].doSomething();
}
</code></pre>
<p>Is there a reason I don't see this in C++? Is it bad practice?</p> | 12,702,643 | 14 | 9 | null | 2012-10-03 05:50:18.17 UTC | 66 | 2022-04-18 19:47:09.363 UTC | 2017-04-22 01:58:52.883 UTC | null | 63,550 | null | 1,801,220 | null | 1 | 246 | c++|coding-style|for-loop|iterator | 856,785 | <blockquote>
<p><strong>Is there any reason I don't see this in C++? Is it bad practice?</strong></p>
</blockquote>
<p>No. It is not a bad practice, but the following approach renders your code certain <strong>flexibility</strong>.</p>
<p>Usually, pre-C++11 the code for iterating over container elements uses iterators, something like:</p>
<pre><code>std::vector<int>::iterator it = vector.begin();
</code></pre>
<p>This is because it makes the code more flexible.</p>
<p>All standard library containers support and provide iterators. If at a later point of development you need to switch to another container, then this code does not need to be changed.</p>
<p><strong>Note:</strong> Writing code which works with every possible standard library container is not as easy as it might seem to be.</p> |
16,606,872 | Calling python method from C++ (or C) callback | <p>I am trying to call methods in a python class from C++. The C++ method from which this is called is a C++ callback.</p>
<p>Within this method when I am trying to call python method, it was giving <code>segmentation fault</code>.</p>
<p>I have saved an instance of python function in a global variable like </p>
<pre><code>// (pFunc is global variable of type PyObject*)
pFunc = PyDict_GetItemString(pDict, "PlxMsgWrapper");
</code></pre>
<p>where <code>PlxMsgWrapper</code> is a python method, which will be used in the callback.</p>
<p>In the callback, the arguments are created as </p>
<pre><code>PyObject* args = PyTuple_Pack(2, PyString_FromString(header.c_str()),
PyString_FromString(payload.c_str()));
</code></pre>
<p>When creating the </p>
<pre><code>PyObject * pInstance = PyObject_CallObject(pFunc, args);
</code></pre>
<p>In this line its giving segmentation fault. After this the actual python method is called as</p>
<pre><code>PyObject* recv_msg_func = PyObject_GetAttrString(module, (char *)"recvCallback");
args = PyTuple_Pack(1, pInstance);
PyObject_CallObject(recv_msg_func, args);
</code></pre> | 16,609,899 | 3 | 7 | null | 2013-05-17 10:31:23.323 UTC | 13 | 2014-01-08 21:45:29.973 UTC | 2014-01-08 21:45:29.973 UTC | null | 2,371,054 | null | 539,472 | null | 1 | 18 | c++|python|c|callback|python-c-api | 14,618 | <p>There are a few things you need to do if you are invoking a Python function from a C/C++ callback. First when you save off your python function object, you need to increment the reference count with:</p>
<pre><code>Py_INCREF(pFunc)
</code></pre>
<p>Otherwise Python has no idea you are holding onto an object reference, and it may garbage collect it, resulting in a segmentation fault when you try to use it from your callback.</p>
<p>Then next thing you need to be concerned about is what thread is running when your C/C++ callback is invoked. If you are getting called back from another non-Python created thread (i.e. a C/C++ thread receiving data on a socket), then you <strong>MUST</strong> acquire Python's Global Interpreter Lock (GIL) before calling any Python API functions. Otherwise your program's behavior is undefined. To acquire the GIL you do:</p>
<pre><code>void callback() {
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
// Get args, etc.
// Call your Python function object
PyObject * pInstance = PyObject_CallObject(pFunc, args);
// Do any other needed Python API operations
// Release the thread. No Python API allowed beyond this point.
PyGILState_Release(gstate);
}
</code></pre>
<p>Also, in your extension module's init function, you should do the following to ensure that threading is properly initialized:</p>
<pre><code>// Make sure the GIL has been created since we need to acquire it in our
// callback to safely call into the python application.
if (! PyEval_ThreadsInitialized()) {
PyEval_InitThreads();
}
</code></pre>
<p>Otherwise, crashes and strange behavior may ensue when you attempt to acquire the GIL from a non-Python thread.</p>
<p>See <a href="http://docs.python.org/2/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="noreferrer">Non-Python Created Threads</a> for more detail on this.</p> |
17,060,177 | Yii2 dropdown empty option | <p>How to implement the following Yii code to Yii2:</p>
<pre><code><?php
echo $form->dropDownList($model,
'project',
$model->getProjectOptions(),
array('empty' => 'Empty string')
);
?>
</code></pre> | 17,061,487 | 5 | 0 | null | 2013-06-12 07:44:09.083 UTC | 3 | 2020-03-31 16:00:32.377 UTC | 2017-02-22 08:05:40.003 UTC | null | 3,296,607 | null | 2,477,346 | null | 1 | 19 | php|drop-down-menu|yii2 | 41,907 | <p>Why not </p>
<pre><code><?
dropDownList($model,
'project',
$model->getProjectOptions(),
array('prompt'=>'Empty string')
); ?>
</code></pre>
<ul>
<li>prompt: string, a prompt text to be displayed as the first option;</li>
</ul>
<p>Here is old CHtml <a href="https://github.com/yiisoft/yii2/blob/master/framework/yii/helpers/base/Html.php" rel="nofollow noreferrer">https://github.com/yiisoft/yii2/blob/master/framework/yii/helpers/base/Html.php</a></p>
<p>Can find there if you need something more.</p> |
16,837,704 | Angularjs Normal Links with html5Mode | <p>I am working with angularjs in html 5 mode. Which appears to take control of all href's on the page. But what if I want to have a link to something within the same domain of the app but not actually in the app. An example would be a pdf.</p>
<p>If i do <code><a href="/pdfurl"></code> angular will just try to use the html5mode and use the route provider to determine which view should be loaded. But I actually want the browser to go to that page the normal way.</p>
<p>Is the only way to do this is to make a rule with the route provider and have that redirect to the correct page with window.location?</p> | 16,838,013 | 4 | 0 | null | 2013-05-30 13:35:22.503 UTC | 26 | 2016-11-08 09:15:04.593 UTC | null | null | null | null | 803,495 | null | 1 | 77 | angularjs | 21,893 | <p>in HTML5 mode, there are three situations in which the A tag is not rewritten:
from the <a href="https://docs.angularjs.org/guide/$location#html-link-rewriting">angular docs</a></p>
<ul>
<li>Links that contain a <code>target</code> attribute. Example: <code><a href="/ext/link?a=b" target="_self">link</a></code></li>
<li>Absolute links that point to a different domain <code>Example: <a href="http://angularjs.org/">link</a></code></li>
<li>Links starting with '/' that lead to a different base path when <code>base</code> is defined <code>Example: <a href="/not-my-base/link">link</a></code></li>
</ul>
<p>so your case would be 1. add <code>target="_self"</code></p> |
17,014,713 | How to change UINavigationBar background color from the AppDelegate | <p>I know how to change the <code>UINavigationBar</code> background image by doing </p>
<pre><code>[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"nabbar"] forBarMetrics:UIBarMetricsDefault];
</code></pre>
<p>and I know how to set the bar to different colors within each <code>Views</code>..... Now I want to change the background color <em>without using an image</em> to a solid color from the <code>app delegate</code>. I do not want to set it each time from each view and I do not want to write a <code>CGRect</code>.</p>
<p>I tried <code>[[UINavigationBar appearance] setBackgroundColor:[UIColor colorWithRed:33/255.0 green:34/255.0 blue:36/255.0 alpha:1.0]];</code> but I doesn't work and I cant find a code anywhere that works in the app delegate. </p>
<p>Could anyone please point me in the right direction?</p> | 17,014,723 | 12 | 0 | null | 2013-06-09 22:17:04.567 UTC | 13 | 2021-11-13 15:42:44.813 UTC | 2021-11-08 08:27:17.233 UTC | null | 8,090,893 | null | 1,535,747 | null | 1 | 92 | ios|objective-c|xcode|cocoa-touch|uinavigationbar | 111,755 | <p>You can use <code>[[UINavigationBar appearance] setTintColor:myColor];</code></p>
<p>Since iOS 7 you need to set <code>[[UINavigationBar appearance] setBarTintColor:myColor];</code> and also <code>[[UINavigationBar appearance] setTranslucent:NO]</code>.</p>
<pre><code>[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];
</code></pre> |
4,584,442 | Enable/disable textbox based on checkbox selection in WPF using MVVM | <p>I have a WPF form with as many as 40 textboxes, with a checkbox for each. Each textbox should be enabled/disabled based on the value of its corresponding checkbox. I've seen solutions where we can use <code>ICommand</code> to achieve this, but how do I handle 40 individual cases without having 40 <code>ICommand</code> implementations?</p> | 4,584,494 | 2 | 0 | null | 2011-01-03 12:32:00.65 UTC | 12 | 2019-03-27 13:10:26.857 UTC | 2014-12-13 11:58:39.93 UTC | null | 250,725 | null | 31,622 | null | 1 | 58 | wpf|mvvm | 70,114 | <p>Just bind the <code>IsEnabled</code> property of the <code>TextBox</code> to the <code>IsChecked</code> property of the <code>CheckBox</code>:</p>
<pre><code><CheckBox Name="checkBox1" />
<TextBox IsEnabled="{Binding ElementName=checkBox1, Path=IsChecked}" />
</code></pre> |
41,608,131 | Is there a difference between Exception and RuntimeException in PHP? | <p>What is the exact semantic difference between <code>\Exception</code> and <code>\RuntimeException</code> in PHP? When we should use the former and when the latter?</p> | 41,608,370 | 4 | 11 | null | 2017-01-12 08:17:37.803 UTC | 2 | 2022-08-23 11:48:13.463 UTC | 2022-02-02 14:31:02.747 UTC | null | 209,139 | null | 1,420,625 | null | 1 | 30 | php|exception | 17,362 | <p>Exception is a base class of all exceptions in PHP (including <a href="http://php.net/manual/en/class.runtimeexception.php" rel="noreferrer">RuntimeException</a>).
As the documentation says: </p>
<blockquote>
<p>RuntimeException is thrown if an error which can only be found on
runtime occurs.</p>
</blockquote>
<p>It means that whenever You are expecting something that normally should work, to go wrong eg: division by zero or array index out of range etc. You can throw RuntimeException. </p>
<p>As for <a href="http://php.net/manual/en/class.exception.php" rel="noreferrer">Exception</a>, it is a very generic exception and I would call it a "last resort". You can add it as a last one in "try" just to be sure You are handling all exceptions. </p>
<p>Example: </p>
<pre><code>try {
//code...
} catch(RuntimeException $e) {
echo ("RuntimeException...");
} catch(Exception $e) {
echo ("Error something went wrong!");
var_dump($e);
}
</code></pre>
<p>Hope it is a clear now.</p> |
26,625,311 | Is 0 an octal or a decimal in C? | <p>I have read <a href="https://stackoverflow.com/questions/6895522/is-0-a-decimal-literal-or-an-octal-literal">this</a>. It's octal in C++ and decimal in Java. But no description about C?</p>
<p>Is it going to make any difference if 0 is octal or decimal? This is the question asked by my interviewer. I said no and I explained that it is always 0 regardless whether it is octal or decimal.</p>
<p>Then he asked why is it considered as octal in C++ and decimal in Java. I said it's the standard. Please let me know what is it in C? Will it make any difference? Why are they different in different standards?</p> | 26,625,392 | 6 | 18 | null | 2014-10-29 08:02:03.227 UTC | 2 | 2014-10-31 13:56:04.773 UTC | 2017-05-23 12:32:52.177 UTC | null | -1 | null | 2,694,184 | null | 1 | 62 | c|language-lawyer|literals|octal | 8,019 | <p>It makes little difference, but formally the integer constant <code>0</code> is octal in C. From the C99 and C11 standards, <strong>6.4.4.1 Integer constants</strong></p>
<blockquote>
<p><em>integer-constant</em>:<br>
<em>decimal-constant</em> <em>integer-suffix<sub>opt</sub></em><br>
<em>octal-constant</em> <em>integer-suffix<sub>opt</sub></em><br>
<em>hexadecimal-constant</em> <em>integer-suffix<sub>opt</sub></em> </p>
<p><em>decimal-constant</em>:<br>
<em>nonzero-digit</em><br>
<em>decimal-constant</em> <em>digit</em> </p>
<p><em>octal-constant</em>:<br>
<code>0</code><br>
<em>octal-constant</em> <em>octal-digit</em> </p>
<p><em>hexadecimal-constant</em>:<br>
...<br>
... </p>
</blockquote> |
9,738,658 | How do I create one Preference with an EditTextPreference and a Togglebutton? | <p>What I'm trying to implement is basically and exact replica of the image below (the preferences that I've squared). Pressing anything to the left of the preference should open up a dialog. Pressing the togglebutton will disable/enable whatever I'm setting in this preference.</p>
<p>I've been trying for hours now and I've come up empty-handed. How do I implement this in a PreferenceActivity?</p>
<p><img src="https://i.stack.imgur.com/gU1Jr.png" alt="Preference"></p>
<p><em>EDIT: It seems people are misunderstanding my question. It is very important that I figure out how to solve my problem using a PreferenceActivity. NOT an Activity. I don't care whether I need to do it in XML or programatically. Just please refrain from providing me with answers that I cannot use within a or something similar.</em></p>
<p><em>EDIT 2 : Added a bounty - I really need an answer to this</em></p> | 9,850,727 | 6 | 1 | null | 2012-03-16 14:02:07.683 UTC | 13 | 2019-04-10 18:30:25.05 UTC | 2012-03-23 22:41:33.553 UTC | null | 1,105,277 | null | 1,126,097 | null | 1 | 12 | android|preferences|togglebutton|preferenceactivity | 14,970 | <p>Hell man, I like your idea :-)</p>
<p>This is just same as @MH's answer, but more concise.</p>
<p>I tested with <code>ToggleButton</code>, not <code>Switch</code>.</p>
<pre><code>package android.dumdum;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
public class TogglePreference extends Preference {
public TogglePreference(Context context) {
super(context);
}
public TogglePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TogglePreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public View getView(View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new LinearLayout(getContext());
((LinearLayout) convertView)
.setOrientation(LinearLayout.HORIZONTAL);
TextView txtInfo = new TextView(getContext());
txtInfo.setText("Test");
((LinearLayout) convertView).addView(txtInfo,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1));
ToggleButton btn = new ToggleButton(getContext());
((LinearLayout) convertView).addView(btn);
}
return convertView;
}
}
</code></pre>
<p>And the <code>preferences.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Test custom preferences" >
<android.dumdum.EncryptorEditTextPreference />
<android.dumdum.TogglePreference />
</PreferenceCategory>
</PreferenceScreen>
</code></pre>
<p><code>EncryptorEditTextPreference</code> is not related to your question, but it uses same technique (extending <code>EditTextPreference</code>).</p> |
9,796,843 | move up a frame, debug R environment | <p>When debugging a function, I would like to move up to the parent frame and look at some variables there. How do I do this?</p>
<p>Here is a sample:</p>
<pre><code>f <- function() {
x <-1
g(x+1)
}
g <- function(z) {
y = z+2
return(y)
}
</code></pre>
<p>I then debug both functions using <code>debug("g")</code> and <code>debug("f")</code>. When I end up in <code>g</code> at the <code>Browser></code>, I would like to move back up to <code>f</code> to examine x. </p>
<p>Thanks</p> | 9,798,219 | 3 | 0 | null | 2012-03-21 00:07:08.61 UTC | 12 | 2020-08-07 21:43:07.367 UTC | 2012-03-21 03:16:03.497 UTC | null | 271,616 | null | 714,319 | null | 1 | 21 | debugging|r|frame | 3,001 | <p>In R terminology, you are wanting to investigate the parent frame of <code>g()</code>'s evaluation environment (i.e. the environment in which <code>g</code> was called). The functions for doing that are documented in the help page for <code>?sys.parent</code>.</p>
<p>Once your browser indicates that you are <code>'debugging in g(x + 1)'</code>, you can do the following. (Thanks to Joshua Ulrich for suggesting <code>where</code> to help locate ones position in the call stack .)</p>
<pre><code># Confirm that you are where you think you are
where
# where 1 at #3: g(x + 1)
# where 2: f()
# Get a reference to g()'s parent frame (an environment object)
pframe <- parent.frame()
pframe
# <environment: 0x019b9174>
# Examine the contents of the parent frame
ls(env=pframe)
# [1] "x"
# Get the value of 'x' in the parent frame
get("x", env = pframe)
# [1] 1
</code></pre>
<p><strong>EDIT</strong>: To understand the collection of functions described in <code>?sys.parent</code>, it's probably worth noting that <code>parent.frame()</code> is (basically) shorthand for <code>sys.frame(sys.parent(1))</code>. If you find yourself in an evaluation environment farther down a call stack (as revealed by <code>where</code>, for instance), you can reach into environments farther back up the call stack (say two steps up) by either <code>parent.frame(2)</code> or <code>sys.frame(sys.parent(2))</code>. </p> |
9,719,003 | SpinWait vs Sleep waiting. Which one to use? | <p>Is it efficient to </p>
<pre><code>SpinWait.SpinUntil(() => myPredicate(), 10000)
</code></pre>
<p>for a timeout of 10000ms </p>
<p>or </p>
<p>Is it more efficient to use <code>Thread.Sleep</code> polling for the same condition
For example something along the lines of the following <code>SleepWait</code> function:</p>
<pre><code>public bool SleepWait(int timeOut)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (!myPredicate() && stopwatch.ElapsedMilliseconds < timeOut)
{
Thread.Sleep(50)
}
return myPredicate()
}
</code></pre>
<p>I'm concerned that all the yielding of SpinWait may not be a good usage pattern if we are talking about timeouts over 1sec? Is this a valid assumption? </p>
<p>Which approach do you prefer and why? Is there another even better approach?</p>
<hr>
<p><strong>Update</strong> - Becoming more specific: </p>
<p>Is there a way to Make BlockingCollection Pulse a sleeping thread when it reaches bounded capacity? I rather avoid a busy waits alltogether as Marc Gravel suggests. </p> | 9,719,062 | 2 | 0 | null | 2012-03-15 11:44:42.053 UTC | 30 | 2015-11-12 13:50:28.203 UTC | 2013-07-03 20:54:38.86 UTC | null | 626,442 | null | 138,767 | null | 1 | 80 | c#|multithreading | 74,849 | <p>The <em>best</em> approach is to have some mechanism to <strong>actively detect</strong> the thing becoming true (rather than passively polling for it having <em>become</em> true); this could be any kind of wait-handle, or maybe a <code>Task</code> with <code>Wait</code>, or maybe an <code>event</code> that you can subscribe to to unstick yourself. Of course, if you do that kind of "wait until something happens", that is <strong>still</strong> not as efficient as simply having the next bit of work done <em>as a callback</em>, meaning: you don't need to use a thread to wait. <code>Task</code> has <code>ContinueWith</code> for this, or you can just do the work in an <code>event</code> when it gets fired. The <code>event</code> is probably the simplest approach, depending on the context. <code>Task</code>, however, already provides most-everything you are talking about here, including both "wait with timeout" and "callback" mechanisms.</p>
<p>And yes, spinning for 10 seconds is not great. If you want to use something like your current code, and if you have reason to expect a short delay, but need to allow for a longer one - maybe <code>SpinWait</code> for (say) 20ms, and use <code>Sleep</code> for the rest?</p>
<hr>
<p>Re the comment; here's how I'd hook an "is it full" mechanism:</p>
<pre><code>private readonly object syncLock = new object();
public bool WaitUntilFull(int timeout) {
if(CollectionIsFull) return true; // I'm assuming we can call this safely
lock(syncLock) {
if(CollectionIsFull) return true;
return Monitor.Wait(syncLock, timeout);
}
}
</code></pre>
<p>with, in the "put back into the collection" code:</p>
<pre><code>if(CollectionIsFull) {
lock(syncLock) {
if(CollectionIsFull) { // double-check with the lock
Monitor.PulseAll(syncLock);
}
}
}
</code></pre> |
8,146,676 | Google Maps API V3: Offset panTo() by x pixels | <p>I have a some UI elements on the right of my map (sometimes), and I'd like to offset my panTo() calls (sometimes).</p>
<p>So I figured:</p>
<ol>
<li>get the original latlng </li>
<li>convert it to screen pixels </li>
<li>add an offset</li>
<li>convert it back to latlng.</li>
</ol>
<p>But I must misunderstand what Google Maps API refers to as the "Point Plane":
<a href="http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection" rel="noreferrer">http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection</a></p>
<p>Here is my code that seems to offset by lat-long: </p>
<pre class="lang-js prettyprint-override"><code> function getCentreOffset( alatlng ) {
var PIXEL_OFFSET= 100;
var aPoint = me.gmap.getProjection().fromLatLngToPoint(alatlng);
aPoint.x=aPoint.x + OFFSET;
return me.gmap.getProjection().fromPointToLatLng(aPoint);
}
</code></pre> | 12,608,127 | 3 | 1 | null | 2011-11-16 04:19:25.097 UTC | 9 | 2016-08-05 14:10:39.303 UTC | 2011-11-29 01:42:19.93 UTC | null | 225,813 | null | 225,813 | null | 1 | 19 | google-maps-api-3 | 12,948 | <p>Here's a simpler version of Ashley's solution:</p>
<pre><code>google.maps.Map.prototype.panToWithOffset = function(latlng, offsetX, offsetY) {
var map = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function() {
var proj = this.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(latlng);
aPoint.x = aPoint.x+offsetX;
aPoint.y = aPoint.y+offsetY;
map.panTo(proj.fromContainerPixelToLatLng(aPoint));
};
ov.draw = function() {};
ov.setMap(this);
};
</code></pre>
<p>You can then use it like this:</p>
<pre><code>var latlng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng
});
setTimeout(function() { map.panToWithOffset(latlng, 0, 150); }, 1000);
</code></pre>
<p>Here is a working <a href="http://jsfiddle.net/3rtJX/" rel="noreferrer">example</a>.</p>
<p>Let me explain in detail. This extends the Map object itself. So you can use it just like <code>panTo()</code> with extra parameters for offsets. This uses the <code>fromLatLngToContainerPixel()</code> and <code>fromContainerPixelToLatLng()</code> methods of the <a href="https://developers.google.com/maps/documentation/javascript/reference#MapCanvasProjection" rel="noreferrer">MapCanvasProjecton</a> class. This object has no contructor and has to be gotten from the <code>getProjection()</code> method of the <a href="https://developers.google.com/maps/documentation/javascript/reference#OverlayView" rel="noreferrer">OverlayView</a> class; the OverlayView class is used for the creation of custom overlays by implementing its interface, but here we just use it directly. Because <code>getProjection()</code> is only available after <code>onAdd()</code> has been called. The <code>draw()</code> method is called after <code>onAdd()</code> and is defined for our instance of OverlayView to be a function that does nothing. Not doing so will otherwise cause an error.</p> |
7,792,622 | Manual retain with ARC | <p>Before ARC I had the following code that retains the delegate while an async operation is in progress:</p>
<pre><code>- (void)startAsyncWork
{
[_delegate retain];
// calls executeAsyncWork asynchronously
}
- (void)executeAsyncWork
{
// when finished, calls stopAsyncWork
}
- (void)stopAsyncWork
{
[_delegate release];
}
</code></pre>
<p>What is the equivalent to this pattern with ARC?</p> | 7,792,687 | 3 | 0 | null | 2011-10-17 10:46:06.827 UTC | 9 | 2014-04-01 23:55:48.51 UTC | null | null | null | null | 393,863 | null | 1 | 24 | objective-c|ios|memory-management|ios5|automatic-ref-counting | 9,452 | <p>Why not just assign your delegate object to a strong ivar for the duration of the asynchronous task?</p>
<p>Or have a local variable in <code>executeAsyncWork</code></p>
<pre><code>- (void)executeAsyncWork
{
id localCopy = _delegate;
if (localCopy != nil) // since this method is async, the delegate might have gone
{
// do work on local copy
}
}
</code></pre> |
11,709,410 | Regex to detect invalid UTF-8 string | <p>In PHP, we can use <a href="http://us2.php.net/mb_check_encoding" rel="nofollow noreferrer"><code>mb_check_encoding()</code></a> to determine if a string is valid UTF-8. But that's not a portable solution as it requires the mbstring extension to be compiled in and enabled. Additionally, it won't tell us <em>which</em> character is invalid.</p>
<p>Is there a regular expression (or another other 100% portable method) that can match invalid UTF-8 bytes in a given string?</p>
<p>That way, those bytes can be replaced if needed (keeping the binary information, such as when building a test output XML file that includes binary data). So converting the characters to UTF-8 would lose information. So, we may want to convert:</p>
<pre><code>"foo" . chr(128) . chr(255)
</code></pre>
<p>Into</p>
<pre><code>"foo<128><255>"
</code></pre>
<p>So just "detecting" that the string is not good enough, we'd need to be able to detect which characters are invalid.</p> | 11,709,412 | 4 | 0 | null | 2012-07-29 12:53:39.397 UTC | 15 | 2021-07-30 23:11:20.56 UTC | 2021-07-26 21:25:56.503 UTC | null | 63,550 | null | 338,665 | null | 1 | 21 | php|regex|validation|utf-8 | 22,489 | <p>You can use this PCRE regular expression to check for a valid UTF-8 in a string. If the regex matches, the string contains invalid byte sequences. It's 100% portable because it doesn't rely on PCRE_UTF8 to be compiled in.</p>
<pre><code>$regex = '/(
[\xC0-\xC1] # Invalid UTF-8 Bytes
| [\xF5-\xFF] # Invalid UTF-8 Bytes
| \xE0[\x80-\x9F] # Overlong encoding of prior code point
| \xF0[\x80-\x8F] # Overlong encoding of prior code point
| [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
| [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
| [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
| (?<=[\x00-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
| (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]|[\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
| (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
| (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
| (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
)/x';
</code></pre>
<p>We can test it by creating a few variations of text:</p>
<pre><code>// Overlong encoding of code point 0
$text = chr(0xC0) . chr(0x80);
var_dump(preg_match($regex, $text)); // int(1)
// Overlong encoding of 5 byte encoding
$text = chr(0xF8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80);
var_dump(preg_match($regex, $text)); // int(1)
// Overlong encoding of 6 byte encoding
$text = chr(0xFC) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80);
var_dump(preg_match($regex, $text)); // int(1)
// High code-point without trailing characters
$text = chr(0xD0) . chr(0x01);
var_dump(preg_match($regex, $text)); // int(1)
</code></pre>
<p>etc...</p>
<p>In fact, since this matches invalid bytes, you could then use it in preg_replace to replace them away:</p>
<pre><code>preg_replace($regex, '', $text); // Remove all invalid UTF-8 code-points
</code></pre> |
11,628,859 | How can I determine browser window size on server side C# | <p>How can I get the exact height and width of the currently open browser screen window?</p> | 11,629,035 | 6 | 3 | null | 2012-07-24 10:25:31.15 UTC | 13 | 2020-09-08 11:28:41.25 UTC | 2014-02-04 16:03:48.757 UTC | null | 759,866 | null | 1,065,365 | null | 1 | 37 | c#|asp.net|.net | 106,770 | <p>You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.</p>
<h2>At its simplest</h2>
<pre><code>var width = $(window).width();
var height = $(window).height();
</code></pre>
<h2>Complete method using hidden form inputs</h2>
<p>Assuming you have: <a href="http://jquery.com/" rel="noreferrer">JQuery framework</a>.</p>
<p>First, add these hidden form inputs to store the width and height until postback.</p>
<pre><code><asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />
</code></pre>
<p>Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().</p>
<p>Add the following code to your .aspx file within the head element.</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$("#width").val() = $(window).width();
$("#height").val() = $(window).height();
});
</script>
</code></pre>
<p><strong>Result</strong></p>
<p>This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:</p>
<pre><code>var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;
</code></pre>
<p>This method provides the height and width upon postback, but not on the intial page load. </p>
<p><strong><em>Note on UpdatePanels:</strong> If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.</em></p>
<p>Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.</p>
<p><strong>Update for jquery 3.1.1</strong></p>
<p>I had to change the JavaScript to:</p>
<pre><code>$("#width").val($(window).width());
$("#height").val($(window).height());
</code></pre> |
11,625,351 | What is test harness? | <p>I am facing some difficulties in understanding test <code>harness</code> and related common terms like test case, test scripts in automation testing.</p>
<p>So this is what I got so far:</p>
<blockquote>
<p>Automation testing is the use of a special software (other than the software being tested) to control the execution of tests and compare the actual results with the expected results. It also involves the setting up of test pre-conditions. This kind of testing is most suitable for tests that are frequently carried out.</p>
</blockquote>
<p>Now, I am having some problems with <em>test harness</em>. I read that it consists of a <em>test suite</em> of <em>test cases</em>, <em>input files</em>, <em>output files</em>, and <em>test scripts</em>.
Now my question is what is the difference between test case and test script?</p>
<p>How do you use the software to test the different functions of the Acceptance Unit Testing (AUT)? I also came across some terms like <em>suite master</em> and <em>case agents</em>.</p> | 11,628,329 | 4 | 1 | null | 2012-07-24 06:32:22.073 UTC | 28 | 2021-03-01 15:02:05.65 UTC | 2021-03-01 15:02:05.65 UTC | null | 6,045,800 | null | 1,109,363 | null | 1 | 71 | testing|automation | 69,667 | <p>Several broad questions there, will try to answer based on my experience.</p>
<p>Think of a <a href="http://en.wikipedia.org/wiki/Test_harness" rel="noreferrer"><strong>Test Harness</strong></a> as an 'enabler' that actually does all the work of (1)<strong>executing tests</strong> using a (2)<strong>test library</strong> and (3)<strong>generating reports</strong>. It would require that your test scripts are designed to handle different (4)<strong>test data</strong> and (5)<strong>test scenarios</strong>. Essentially, when the test harness is in place and prerequisite data is prepared (aka <em>data prep</em>) someone should be able to click a button or run one command to execute all your tests and generate reports.</p>
<p>A test harness is most likely a collection of different things that make all of the above happen. If you wrote unit tests while developing your application, that would be part of a test harness. You would also have other tests for the functionality of your app, like: user logs in to site, sees favourites pane, recent messages and notifications. Then you add in a 'runner' of sorts that goes through all of your "<strong>test scripts</strong>" and runs them <em>(instead of you having to execute tests one at a time)</em>. If it feels like a test harness is more of a conceptual collection rather than a single piece of software, then you're understanding this correctly :-)</p>
<blockquote>
<p>Now my question is what is the difference between test case and test script?</p>
</blockquote>
<p>Simple but not entirely correct answer: A <strong>Test Case</strong> defines test objectives, description, pre-conditions, steps (descriptive or specific), expected results. A <strong>Test Script</strong> would then be the actual automated script that you execute to do that test. That's in an Automation context. And it changes. A lot.</p>
<p>What certifications like ISTQB define as <strong>test scenarios</strong> is usually referred to as <strong>test cases</strong> in some companies and countries. In others, test cases are flipped with test scripts when referring to manual testing (when the steps are given in detail but not part of an automation harness). Others say that test scripts exclusively mean automated tests. On the other hand, one can also argue that several test cases can be combined in a test script and vice-versa. So that begs the question, how does a <strong>test procedure</strong> fit in?</p>
<p>A <a href="http://en.wikipedia.org/wiki/Software_testing#A_sample_testing_cycle" rel="noreferrer">test development</a> stage can have: <em>"Test procedures, test scenarios, test cases, test datasets, test scripts to use in testing software."</em></p>
<p>If you assume a <strong>> (is larger than/collection of)</strong> relation, how would you relate those? Rhetorical question - that differs based on where you work, who your client is, etc. Best thing is to define it with your colleagues/clients and <strong>agree on the understanding of the terms rather than the definition</strong>. I currently go with test script = automated script, based on a pre-existing manual test case or a test scenario.</p>
<blockquote>
<p>Also, how do you use the software to test the different functions of the AUT?</p>
</blockquote>
<p>You write different tests to test different things. Each test does certain actions and checks if the AUT's output matches what you expected - <code>If displayed_value == expected_value</code>. An <strong>input file</strong> could be used to provide data for the test- list of test usernames and passwords, for instance. Or run the same test with different data - login as a different user with different messages, etc.</p>
<p>Take a look at <a href="https://github.com/robotframework/robotframework" rel="noreferrer">RobotFramework</a> and the <a href="http://seleniumhq.org/" rel="noreferrer">Selenium</a>. A robot framework test (written in text or html files) combined with the Selenium library would allow you to write an automated test which tests something specific...like a home page validation. You would write a separate test to ensure that a user can see all his/her messages. Another to test clearing notifications. And so on.</p> |
12,007,781 | Why doesn't await on Task.WhenAll throw an AggregateException? | <p>In this code:</p>
<pre><code>private async void button1_Click(object sender, EventArgs e) {
try {
await Task.WhenAll(DoLongThingAsyncEx1(), DoLongThingAsyncEx2());
}
catch (Exception ex) {
// Expect AggregateException, but got InvalidTimeZoneException
}
}
Task DoLongThingAsyncEx1() {
return Task.Run(() => { throw new InvalidTimeZoneException(); });
}
Task DoLongThingAsyncEx2() {
return Task.Run(() => { throw new InvalidOperation();});
}
</code></pre>
<p>I expected <code>WhenAll</code> to create and throw an <code>AggregateException</code>, since at least one of the tasks it was awaiting on threw an exception. Instead, I'm getting back a single exception thrown by one of the tasks. </p>
<p>Does <code>WhenAll</code> not always create an <code>AggregateException</code>?</p> | 12,007,893 | 9 | 5 | null | 2012-08-17 14:33:25.2 UTC | 25 | 2022-07-14 10:46:40.257 UTC | 2016-09-07 11:28:27.82 UTC | null | 44,264 | null | 1,106,734 | null | 1 | 146 | .net|exception|asynchronous|tap | 71,965 | <p>I don't exactly remember where, but I read somewhere that with new <em>async/await</em> keywords, they unwrap the <code>AggregateException</code> into the actual exception.</p>
<p>So, in catch block, you get the actual exception and not the aggregated one. This helps us write more natural and intuitive code.</p>
<p>This was also needed for easier conversion of existing code into using <em>async/await</em> where the a lot of code expects specific exceptions and not aggregated exceptions.</p>
<p><strong>-- Edit --</strong></p>
<p>Got it:</p>
<h2><a href="http://download.microsoft.com/download/5/4/B/54B83DFE-D7AA-4155-9687-B0CF58FF65D7/async-primer.pdf" rel="noreferrer">An Async Primer by Bill Wagner</a></h2>
<blockquote>
<p>Bill Wagner said: (in <strong>When Exceptions Happen</strong>)</p>
<p>...When you use await, the code generated by the compiler unwraps the
AggregateException and throws the underlying exception. By leveraging
await, you avoid the extra work to handle the AggregateException type
used by Task.Result, Task.Wait, and other Wait methods defined in the
Task class. That’s another reason to use await instead of the
underlying Task methods....</p>
</blockquote> |
11,598,840 | Keyboard shortcut to comment lines in Sublime Text 2 | <p>In <strong><a href="https://www.sublimetext.com/2" rel="noreferrer">Sublime Text 2</a></strong>, how do I enclose a selection in a <strong>comment</strong>?<br>
Is there a keyboard shortcut for this action?</p> | 11,598,860 | 15 | 1 | null | 2012-07-22 08:40:38.023 UTC | 38 | 2018-03-29 19:16:32.327 UTC | 2018-02-18 03:35:56.737 UTC | null | 8,623,417 | null | 1,419,762 | null | 1 | 159 | sublimetext2 | 255,045 | <p>By default on Linux/Windows for an English keyboard the shortcut is <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>/</kbd> to toggle a block comment, and <kbd>Ctrl</kbd>+<kbd>/</kbd> to toggle a line comment.</p>
<p>If you go into <code>Preferences->Key Bindings - Default</code>, you can find all the shortcuts, below are the lines for commenting.</p>
<pre><code>{ "keys": ["ctrl+/"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+/"], "command": "toggle_comment", "args": { "block": true } },
</code></pre> |
11,591,854 | Format date to MM/dd/yyyy in JavaScript | <p>I have a dateformat like this <code>'2010-10-11T00:00:00+05:30'</code>. I have to format in to <code>MM/dd/yyyy</code> using JavaScript or jQuery . Anyone help me to do the same.</p> | 11,591,900 | 3 | 4 | null | 2012-07-21 11:41:07.247 UTC | 22 | 2022-02-10 08:23:19.22 UTC | 2017-07-23 11:46:03.04 UTC | null | 438,581 | null | 343,148 | null | 1 | 185 | javascript|jquery | 965,394 | <p>Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var date = new Date('2010-10-11T00:00:00+05:30');
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());</code></pre>
</div>
</div>
</p> |
20,072,696 | What is different between exec(), shell_exec, system() and passthru() functions in PHP? | <p>Anybody please tell me. I want know the different between the <code>exec()</code>, <code>shell_exec</code>, <code>system()</code> and <code>passthru()</code> function?</p>
<p>I search from <a href="http://php.net" rel="noreferrer">php.net</a> unable to get the answers I need.</p> | 20,072,886 | 2 | 4 | null | 2013-11-19 13:22:50.223 UTC | 15 | 2013-11-19 13:33:28.797 UTC | 2013-11-19 13:33:28.797 UTC | null | 472,495 | null | 2,663,157 | null | 1 | 47 | php | 37,198 | <ul>
<li><a href="http://us1.php.net/manual/en/function.exec.php"><code>exec</code></a> only returns the last line of the generated output.</li>
<li><a href="http://php.net/shell_exec"><code>shell_exec</code></a> returns the full output of the command, when the command finished running. </li>
<li><a href="http://php.net/system"><code>system</code></a> immediately shows all output, and is used to show text. </li>
<li><a href="http://php.net/passthru"><code>passthru</code></a> also returns output immediately, but is used for binary data. <code>passthru</code> displays raw data. </li>
</ul>
<p>With both <code>exec</code> and <code>shell_exec</code> it is possible to handle the output yourself, while <code>system</code> and <code>passthru</code> won't let you customize it and immediately display the output. </p>
<p>A more detailed comparison can be found <a href="http://chipmunkninja.com/Program-Execution-in-PHP%3a-exec-m@">here</a>. </p> |
19,973,203 | Strategy Pattern with different parameters | <p>I came across a problem when using the strategy pattern. I am implementing a service for creating tasks. This service also resolves the responsible clerk for this task. Resolving the clerk is done by using the strategy pattern because there are different ways of doing this. The point is that every strategy could need different parameters to resolve the clerk.</p>
<p>For example:</p>
<pre><code>interface ClerkResolver {
String resolveClerk(String department);
}
class DefaultClerkResolver implements ClerkResolver {
public String resolveClerk(String department) {
// some stuff
}
}
class CountryClerkResolver implements ClerkResolver {
public String resolveClerk(String department) {
// I do not need the department name here. What I need is the country.
}
}
</code></pre>
<p>The problem is that every resolver may depend on different parameters to resolve the responsible clerk. For me this sounds like a design issue in my code. I also tried to have a class as a parameter to keep all values that could be needed by the strategies, like:</p>
<pre><code>class StrategyParameter {
private String department;
private String country;
public String getDepartment() ...
}
interface ClerkResolver {
String resolveClerk(StrategyParameter strategyParameter);
}
</code></pre>
<p>But to be honest, I am not satisfied with this solution because I have to change the parameter class everytime a strategy needs a new / different argument. And secondly the caller of the strategy must set all parameters because he does not know which strategy will resolve the clerk, therefore he has to provide all parameters (but this isn't that bad).</p>
<p>Again, for me this sounds like a design issue in my code, but I can't find a better solution. </p>
<p><strong>--- EDIT</strong></p>
<p>The main problem with this solution is when creating the task. The task service looks like this:</p>
<pre><code>class TaskService {
private List<ClerkResolver> clerkResolvers;
Task createTask(StrategyParamter ...) {
// some stuff
for(ClerkResolver clerkResolver : clerkResolvers) {
String clerk = clerkResolver.resolveClerk(StrategyParameter...)
...
}
// some other stuff
}
}
</code></pre>
<p>As you can see when the TaskService is used, the caller must provide the necessary information to resolve the clerk, i.e. the department name and/or the country, because the TaskService itself doesn't have these information. </p>
<p>When a task has to be created, the caller must provide the StrategyParameter, because they are necessary to resolve the clerk. Again, the problem is, that the caller doesn't have all the information, i.e. he has no knowledge of the country. He can only set the department name. That's why I added a second method to the interface to ensure that the strategy can handle the clerk resolution:</p>
<pre><code>interface ClerkResolver {
String resolveClerk(StrategyParameter strategyParameter);
boolean canHandle(StrategyParameter strategyParameter);
}
</code></pre>
<p>At the risk of repeating me, this solution doesn't sound right to me.</p>
<p>So, if anybody has a better solution for this problem I would appreciate to hear it.</p>
<p>Thanks for your comments! </p> | 19,974,456 | 5 | 6 | null | 2013-11-14 08:50:36.113 UTC | 10 | 2021-01-14 10:17:34.11 UTC | 2013-11-14 09:33:13.01 UTC | null | 2,645,877 | null | 2,645,877 | null | 1 | 30 | java|design-patterns|strategy-pattern|taskservice | 20,620 | <p>I think there is some confusion about what the task actually is. In my thinking a task is something that is done by a clerk. So you are able to create a task itself without knowing about a clerk.</p>
<p>Based on that task you can choose an appropriate clerk for it. The assignment of the task to the clerk can itself be wrapped to some other kind of task. So a common interface for choosing a clerk would be:</p>
<pre><code>interface ClerkResolver {
String resolveClerk(Task task);
}
</code></pre>
<p>For implementing this kind of clerk resolver you can use the strategy pattern based on the actual type of the task for example.</p> |
19,938,003 | How to turn off notice reporting in xampp? | <p>On a remote server there is no problem, but in localhost (xampp 3.1.) I cannot turn off reporting notices.</p>
<pre><code><?php
$Fname = $_POST["Fname"];
...
</code></pre>
<p>result:</p>
<pre><code>Notice: Undefined index: Fname in D:\xampp\htdocs\xx\php01\form01.php on line 6
</code></pre>
<p>php.ini</p>
<pre><code>; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_NOTICE //shouldn't this line turn off notice reporting ?
</code></pre>
<p>Any suggestion ?</p> | 19,938,305 | 5 | 24 | null | 2013-11-12 19:19:22.837 UTC | 1 | 2020-06-23 16:45:58.883 UTC | 2013-11-12 19:25:40.947 UTC | null | 1,303,868 | null | 3,044,737 | null | 1 | 5 | php|xampp | 44,529 | <p>Try to do a <code>phpinfo();</code> just before your <code>$Fname = $_POST["Fname"];</code> line. What's the error_reporting property value ? See <a href="http://php.net/manual/en/errorfunc.constants.php" rel="nofollow noreferrer">this</a> or <a href="https://stackoverflow.com/a/3758466/2806497">this</a> to understand the value displayed in the table. </p>
<p>If it's not what you expected, check that the property is not changed by php.
It's also possible you edited the wrong php.ini file : XAMPP tends to copy the original php.ini file and create his own. Use <code>phpinfo();</code>, search for 'php.ini' string in the table : you will find the path of the php.ini file used.</p>
<p>Last thing, maybe the problem is that you did not properly restarted apache after you changed php.ini file. The thing is that xamp is a distinct process of the apache service. Closing XAMP do not make apache service to be stopped, you better use XAMPP Control Panel to stop/start apache. </p> |
3,797,819 | Clear array of strings | <p>What is the easiest way to clear an array of strings?</p> | 3,797,827 | 7 | 1 | null | 2010-09-26 12:43:31.75 UTC | 2 | 2019-09-02 01:12:13.203 UTC | null | null | null | null | 404,651 | null | 1 | 16 | c#|string | 59,794 | <p>Have you tried <a href="http://msdn.microsoft.com/en-us/library/system.array.clear.aspx" rel="noreferrer"><code>Array.Clear</code></a>?</p>
<pre><code>string[] foo = ...;
Array.Clear(foo, 0, foo.Length);
</code></pre>
<p>Note that this <em>won't</em> change the size of the array - nothing will do that. Instead, it will set each element to null.</p>
<p>If you need something which can <em>actually</em> change size, use a <code>List<string></code> instead:</p>
<pre><code>List<string> names = new List<string> { "Jon", "Holly", "Tom" };
names.Clear(); // After this, names will be genuinely empty (Count==0)
</code></pre> |
3,400,759 | How can I list all cookies for the current page with Javascript? | <p>Is there any way to, with help of Javascript, list all cookies associated with the current page? That is, if I don't know the names of the cookies but want to retrieve all the information they contain.</p> | 3,400,787 | 10 | 4 | null | 2010-08-03 21:08:17.207 UTC | 14 | 2022-07-16 03:06:40.517 UTC | 2010-08-03 22:04:34.613 UTC | null | 73,297 | null | 410,137 | null | 1 | 94 | javascript|cookies | 179,679 | <p>You can list cookies for current domain:</p>
<pre><code>function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</code></pre>
<p>But you cannot list cookies for other domains for security reasons</p> |
3,507,498 | Reading CSV files using C# | <p>I'm writing a simple import application and need to read a CSV file, show result in a <code>DataGrid</code> and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:</p>
<pre><code>StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
row = line.Split(',');
importingData.Add(new Transaction
{
Date = DateTime.Parse(row[0]),
Reference = row[1],
Description = row[2],
Amount = decimal.Parse(row[3]),
Category = (Category)Enum.Parse(typeof(Category), row[4])
});
}
</code></pre>
<p>but it's very difficult to operate on arrays in this case. Is there a better way to split the values?</p> | 3,508,572 | 12 | 2 | null | 2010-08-17 22:30:21.97 UTC | 89 | 2021-02-10 15:00:22.29 UTC | 2020-04-21 20:25:49.353 UTC | null | 3,739,391 | null | 304,083 | null | 1 | 195 | c#|csv | 337,644 | <p>Don't reinvent the wheel. Take advantage of what's already in .NET BCL. </p>
<ul>
<li>add a reference to the <code>Microsoft.VisualBasic</code> (yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)</li>
<li>use the <code>Microsoft.VisualBasic.FileIO.TextFieldParser</code> class to parse CSV file</li>
</ul>
<p>Here is the sample code:</p>
<pre><code>using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
}
}
}
</code></pre>
<p>It works great for me in my C# projects. </p>
<p>Here are some more links/informations:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/cakac7e6.aspx" rel="noreferrer">MSDN: Read From Comma-Delimited Text Files in Visual Basic</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx" rel="noreferrer">MSDN: TextFieldParser Class</a></li>
</ul> |
3,731,968 | Is there a way to delete a line in Visual Studio without cutting it? | <p>I want to delete a line just like hitting <kbd>Ctrl</kbd> + <kbd>X</kbd> without anything selected, but without saving the line to the copy stack. Is this possible?</p>
<p>I'm using Visual Studio 2010.</p> | 3,731,992 | 13 | 0 | null | 2010-09-17 00:49:09.967 UTC | 26 | 2022-06-28 09:55:10.15 UTC | 2011-09-15 06:26:52.603 UTC | null | 321,366 | null | 127,905 | null | 1 | 202 | visual-studio|visual-studio-2010|keyboard-shortcuts | 77,555 | <p><code>Edit.LineDelete</code> is the name of the command. By default it's bound to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd>, but you can give it whatever you like in Tools | Options | Keyboard. </p>
<p><strong>Edit</strong>: Corrected default shortcut info.</p> |
7,796,127 | How to get class name through JavaScript | <p>How do I get the class name through JavaScript given no id with this <code>span</code>.</p>
<p>Like: <code><span class="xyz"></span></code> </p>
<p>I want to change the background color of this <code>span</code>.</p>
<p>How can I solve this? Please help me.</p>
<p>tympanus.net/Tutorials/CSS3PageTransitions/index3.html#contact</p> | 7,796,178 | 4 | 2 | null | 2011-10-17 15:38:44.14 UTC | 1 | 2021-10-14 01:16:02.33 UTC | 2013-10-30 08:29:29.153 UTC | null | 998,983 | null | 998,983 | null | 1 | 6 | javascript | 78,790 | <p>Something like this should work:</p>
<pre><code>var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
if (spans[i].className == 'xyz') {
spans[i].style.backgroundColor = '#000';
}
}
</code></pre> |
8,352,372 | How to add load more button for a HTML/CSS page? | <p>I want to make a single page website and it will have huge content. Suppose it has 1000 photos on it. I don't want people to wait 5 minutes to load my page. So I wanna add LOAD MORE button on the page bottom.</p>
<p>How to do that with HTML/CSS/JS?</p> | 8,352,551 | 5 | 9 | null | 2011-12-02 06:02:31.697 UTC | 14 | 2021-02-10 00:10:46.243 UTC | 2011-12-02 06:07:54.02 UTC | null | 824,280 | null | 1,073,289 | null | 1 | 5 | jquery|html|css | 57,561 | <p>You could set all the <code>div</code>s' to <code>display:none;</code> at first and then use jQuery to show the first 10 (or however many you wish to show):</p>
<pre><code>$(function(){
$("div").slice(0, 10).show(); // select the first ten
$("#load").click(function(e){ // click event for load more
e.preventDefault();
$("div:hidden").slice(0, 10).show(); // select next 10 hidden divs and show them
if($("div:hidden").length == 0){ // check if any hidden divs still exist
alert("No more divs"); // alert if there are none left
}
});
});
</code></pre>
<p><a href="http://jsfiddle.net/purmou/bEdfX/">Example</a>.</p>
<p>This saves you the trouble of including an entire plugin when what you want can be achieved in a few lines of code.</p> |
8,270,441 | Go language how detect file changing? | <p>I need to know how to detect when a file changes using Go. I know that Unix provides a function named <code>fcntl()</code> which notifies when a specific file is changed but I have not found this one in Go.
Please help me.</p> | 22,672,784 | 5 | 0 | null | 2011-11-25 14:24:47.443 UTC | 9 | 2017-01-20 09:16:52.32 UTC | 2016-08-03 06:08:14.757 UTC | user6169399 | null | null | 535,561 | null | 1 | 29 | go | 28,942 | <p>There is currently an experimental package <a href="https://github.com/fsnotify/fsnotify" rel="nofollow">here</a>. It should be merged into core as <code>os/fsnotify</code> in go1.3</p> |
8,045,970 | How to do copy/paste function programmatically in iphone? | <p>I have a text-view with some text and a copy button in that view,</p>
<p>When the user enters some text and presses the copy button, it needs to copy that text and paste that text wherever he wants.</p>
<p>I know there is a default copy/paste menu-controller in iOS, but I want to do this functionality in a button click. I think there is <code>UIPasteboard</code> to do this functionality, but I don't know how to use it.</p> | 8,046,299 | 5 | 0 | null | 2011-11-08 04:29:13.16 UTC | 18 | 2017-12-07 03:33:05.55 UTC | 2017-06-14 08:22:16.79 UTC | user7219949 | 3,681,880 | null | 1,017,667 | null | 1 | 44 | ios|iphone|copy-paste | 28,116 | <p>To copy from a button click:</p>
<pre><code>- (IBAction)copy {
UIPasteboard *pb = [UIPasteboard generalPasteboard];
[pb setString:[textView text]];
}
</code></pre>
<p>To paste from a button click:</p>
<pre><code>- (IBAction)paste {
UIPasteboard *pb = [UIPasteboard generalPasteboard];
textView.text = [pb string];
}
</code></pre> |
7,846,980 | How do I switch my CSS stylesheet using jQuery? | <p>What I'm working on is simple.</p>
<p>You click on a button <code>(id="themes")</code> and it opens up a div <code>(id="themedrop")</code> that slides down and lists the themes. (I only have two at this point)</p>
<pre><code><button id="original">Original</button><br />
<button id="grayscale">Grayscale</button>
</code></pre>
<p>Now when the site is loaded it loads with style1.css (main/original theme)</p>
<pre><code><link rel="stylesheet" type="text/css" href="style1.css">
</code></pre>
<p>Now what I'm trying to figure out is...
How can I have it that when the grayscale button is clicked to change the stylesheet from style1.css to style2.css (note: files are in the same directory)</p>
<p>Any help would be much appreciated.</p> | 7,847,009 | 5 | 0 | null | 2011-10-21 08:40:23.45 UTC | 30 | 2021-04-14 06:24:31.843 UTC | 2012-05-17 21:09:25.633 UTC | null | 47,529 | null | 710,887 | null | 1 | 46 | jquery|css|themes|stylesheet | 82,077 | <pre><code>$('#grayscale').click(function (){
$('link[href="style1.css"]').attr('href','style2.css');
});
$('#original').click(function (){
$('link[href="style2.css"]').attr('href','style1.css');
});
</code></pre>
<p>Give this a try but not sure if it will work I have not tested it but gd luck.</p> |
8,093,961 | Record and replay Javascript | <p>I know it is possible to record mouse movements, scrolling and keystrokes. But what about changes to the document? How can I record changes to the document?</p>
<p>Here is my try out. There must be a better more simple way to store all events?</p>
<p>I am thankful for all tips I can get!</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Record And replay javascript</title>
</head>
<body id="if_no_other_id_exist">
<div style="height:100px;background:#0F0" id="test1">click me</div>
<div style="height:100px;background:#9F9" class="test2">click me</div>
<div style="height:100px;background:#3F9" id="test3">click me</div>
<div style="height:100px;background:#F96" id="test4">click me</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var the_time_document_is_redy = new Date().getTime();
var the_replay = '';
$('div').live("click", function (){
var the_length_of_visit = new Date().getTime() - the_time_document_is_redy;
// check if the element that is clicked has an id
if (this.id)
{
the_replay =
the_replay
+
"setTimeout(\"$('#"
+
this.id
+
"').trigger('click')\","
+
the_length_of_visit
+
");"
;
alert (
"The following javascript will be included in the file in the replay version:\n\n"
+
the_replay
) // end alert
} // end if
// if it does not have an id, check if the element that is clicked has an class
else if (this.className)
{
// find the closest id to better target the element (needed in my application)
var closest_div_with_id = $(this).closest('[id]').attr('id');
the_replay =
the_replay
+
"setTimeout(\"$('#"
+
closest_div_with_id
+
" ."
+
this.className
+
"').trigger('click')\","
+
the_length_of_visit
+
");"
;
alert (
"The following javascript will be included in the file in the replay version:\n\n"
+
the_replay
) // end alert
} // end if
});
// fall back if there are no other id's
$('body').attr('id','if_no_other_id_exist');
// example of how it will work in the replay version
setTimeout("$('#test1').trigger('click')",10000);
});
</script>
</body>
</html>
</code></pre> | 8,094,844 | 6 | 0 | null | 2011-11-11 12:25:43.987 UTC | 16 | 2020-11-21 15:37:10.97 UTC | 2019-08-26 11:43:05.677 UTC | null | 4,370,109 | null | 673,108 | null | 1 | 22 | javascript|dom-events | 25,908 | <p>Replaying user actions with just Javascript is a <strong>complex problem</strong>. </p>
<p>First of all, you can't move mouse cursor, you can't emulate mouseover/hovers also. So there goes away a big part of user interactions with a page.</p>
<p>Second of all, actions, once recorded, for most of the time they have to be replayed in different environment than they were recorded in the first place. I mean you can replay the actions on screen with smaller resolutions, different client browser, different content served based on replaying browser cookies etc.</p>
<p>If you take a time to study available services that enable you to record website visitors actions ( <a href="http://clicktale.com">http://clicktale.com</a>, <a href="http://userfly.com/">http://userfly.com/</a> to name a few), you'll see that <strong>none of them are capable of fully replaying users actions</strong>, especially when it comes to mouseovers, ajax, complex JS widgets.</p>
<p>As to your question for detecting changes made to the DOM - as Chris Biscardi stated in his answer, there are <a href="http://en.wikipedia.org/wiki/DOM_events">mutation events</a>, that are designed for that. However, keep in mind, that they are not implemented in every browser. Namely, the IE doesn't support them (they will be supported as of IE 9, according to this blog entry on msdn <a href="http://blogs.msdn.com/b/ie/archive/2010/03/26/dom-level-3-events-support-in-ie9.aspx">http://blogs.msdn.com/b/ie/archive/2010/03/26/dom-level-3-events-support-in-ie9.aspx</a>).</p>
<p>Relying on those events may be suitable for you, depending on use case.</p>
<p>As to "<em>better more simple way to store all events</em>". There are other ways (syntax wise), of listening for events of your choice, however handling (= storing) them can't be handled in simple way, unless you want to serialize whole event objects which wouldn't be a good idea, if you were to send information about those event to some server to store them. You have to be aware of the fact, that there are massive amount of events popping around while using website, hence massive amount of potential data to be stored/send to the server.</p>
<p>I hope I made myself clear and you find some of those information useful. I myself have been involved in project that aimed to do what you're trying to achive, so I know how complicated can it get once you start digging into the subject.</p> |
7,715,485 | How to only find files in a given directory, and ignore subdirectories using bash | <p>I'm running the <code>find</code> command to find certain files, but some files in sub-directories have the same name which I want to ignore.</p>
<p>I'm interested in files/patterns like this:</p>
<pre><code>/dev/abc-scanner, /dev/abc-cash ....
</code></pre>
<p>The command:</p>
<pre><code>find /dev/ -name 'abc-*'
</code></pre>
<p>What's being returned:</p>
<pre><code>/dev/abc-scanner
/dev/abc-cash
...
...
...
/dev/.udev/names/abc-scanner
/dev/.udev/names/abc-cash
</code></pre>
<p>I want to ignore the latter files: <code>/dev/.udev/...</code></p> | 7,715,567 | 6 | 3 | null | 2011-10-10 15:56:24.75 UTC | 26 | 2022-09-18 09:33:17.093 UTC | 2021-01-14 17:44:27.483 UTC | null | 3,474,146 | null | 706,808 | null | 1 | 166 | bash|unix | 219,921 | <p>If you just want to limit the find to the first level you can do:</p>
<pre><code> find /dev -maxdepth 1 -name 'abc-*'
</code></pre>
<p>... or if you particularly want to exclude the <code>.udev</code> directory, you can do:</p>
<pre><code> find /dev -name '.udev' -prune -o -name 'abc-*' -print
</code></pre> |
7,897,630 | Why does the Contains() operator degrade Entity Framework's performance so dramatically? | <p>UPDATE 3: According to <a href="http://blogs.msdn.com/b/adonet/archive/2012/12/10/ef6-alpha-2-available-on-nuget.aspx" rel="noreferrer">this announcement</a>, this has been addressed by the EF team in EF6 alpha 2.</p>
<p>UPDATE 2: I've created a suggestion to fix this problem. To vote for it, <a href="http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/2598644-improve-the-performance-of-the-contains-operator" rel="noreferrer">go here</a>.</p>
<p>Consider a SQL database with one very simple table.</p>
<pre><code>CREATE TABLE Main (Id INT PRIMARY KEY)
</code></pre>
<p>I populate the table with 10,000 records.</p>
<pre><code>WITH Numbers AS
(
SELECT 1 AS Id
UNION ALL
SELECT Id + 1 AS Id FROM Numbers WHERE Id <= 10000
)
INSERT Main (Id)
SELECT Id FROM Numbers
OPTION (MAXRECURSION 0)
</code></pre>
<p>I build an EF model for the table and run the following query in LINQPad (I am using "C# Statements" mode so LINQPad doesn't create a dump automatically).</p>
<pre><code>var rows =
Main
.ToArray();
</code></pre>
<p>Execution time is ~0.07 seconds. Now I add the Contains operator and re-run the query.</p>
<pre><code>var ids = Main.Select(a => a.Id).ToArray();
var rows =
Main
.Where (a => ids.Contains(a.Id))
.ToArray();
</code></pre>
<p>Execution time for this case is <strong>20.14 seconds</strong> (288 times slower)!</p>
<p>At first I suspected that the T-SQL emitted for the query was taking longer to execute, so I tried cutting and pasting it from LINQPad's SQL pane into SQL Server Management Studio.</p>
<pre><code>SET NOCOUNT ON
SET STATISTICS TIME ON
SELECT
[Extent1].[Id] AS [Id]
FROM [dbo].[Primary] AS [Extent1]
WHERE [Extent1].[Id] IN (1,2,3,4,5,6,7,8,...
</code></pre>
<p>And the result was</p>
<pre><code>SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 88 ms.
</code></pre>
<p>Next I suspected LINQPad was causing the problem, but performance is the same whether I run it in LINQPad or in a console application.</p>
<p>So, it appears that the problem is somewhere within Entity Framework.</p>
<p>Am I doing something wrong here? This is a time-critical part of my code, so is there something I can do to speed up performance?</p>
<p>I am using Entity Framework 4.1 and Sql Server 2008 R2.</p>
<p>UPDATE 1:</p>
<p>In the discussion below there were some questions about whether the delay occurred while EF was building the initial query or while it was parsing the data it received back. To test this I ran the following code,</p>
<pre><code>var ids = Main.Select(a => a.Id).ToArray();
var rows =
(ObjectQuery<MainRow>)
Main
.Where (a => ids.Contains(a.Id));
var sql = rows.ToTraceString();
</code></pre>
<p>which forces EF to generate the query without executing it against the database. The result was that this code required ~20 secords to run, so it appears that almost all of the time is taken in building the initial query.</p>
<p>CompiledQuery to the rescue then? Not so fast ... CompiledQuery requires the parameters passed into the query to be fundamental types (int, string, float, and so on). It won't accept arrays or IEnumerable, so I can't use it for a list of Ids.</p> | 7,936,350 | 8 | 7 | null | 2011-10-26 01:02:52.593 UTC | 44 | 2022-01-19 05:08:38.873 UTC | 2019-06-08 08:39:32.86 UTC | null | 665,783 | null | 85,196 | null | 1 | 81 | c#|sql|performance|entity-framework-4|contains | 48,392 | <p><strong>UPDATE: With the addition of InExpression in EF6, the performance of processing Enumerable.Contains improved dramatically. The approach described in this answer is no longer necessary.</strong></p>
<p>You are right that most of the time is spent processing the translation of the query. EF's provider model doesn't currently include an expression that represents an IN clause, therefore ADO.NET providers can't support IN natively. Instead, the implementation of Enumerable.Contains translates it to a tree of OR expressions, i.e. for something that in C# looks like like this:</p>
<pre><code>new []{1, 2, 3, 4}.Contains(i)
</code></pre>
<p>... we will generate a DbExpression tree that could be represented like this:</p>
<pre><code>((1 = @i) OR (2 = @i)) OR ((3 = @i) OR (4 = @i))
</code></pre>
<p>(The expression trees have to be balanced because if we had all the ORs over a single long spine there would be more chances that the expression visitor would hit a stack overflow (yes, we actually did hit that in our testing)) </p>
<p>We later send a tree like this to the ADO.NET provider, which can have the ability to recognize this pattern and reduce it to the IN clause during SQL generation. </p>
<p>When we added support for Enumerable.Contains in EF4, we thought it was desirable to do it without having to introduce support for IN expressions in the provider model, and honestly, 10,000 is much more than the number of elements we anticipated customers would pass to Enumerable.Contains. That said, I understand that this is an annoyance and that the manipulation of expressions trees makes things too expensive in your particular scenario.</p>
<p>I discussed this with one of our developers and we believe that in the future we could change the implementation by adding first-class support for IN. I will make sure this is added to our backlog, but I cannot promise when it will make it given there are many other improvements we would like to make. </p>
<p>To the workarounds already suggested in the thread I would add the following:</p>
<p>Consider creating a method that balances the number of database roundtrips with the number of elements you pass to Contains. For instance, in my own testing I observed that computing and executing against a local instance of SQL Server the query with 100 elements takes 1/60 of a second. If you can write your query in such a way that executing 100 queries with 100 different sets of ids would give you equivalent result to the query with 10,000 elements, then you can get the results in aproximately 1.67 seconds instead of 18 seconds. </p>
<p>Different chunk sizes should work better depending on the query and the latency of the database connection. For certain queries, i.e. if the sequence passed has duplicates or if Enumerable.Contains is used in a nested condition you may obtain duplicate elements in the results. </p>
<p>Here is a code snippet (sorry if the code used to slice the input into chunks looks a little too complex. There are simpler ways to achieve the same thing, but I was trying to come up with a pattern that preserves streaming for the sequence and I couldn't find anything like it in LINQ, so I probably overdid that part :) ):</p>
<p>Usage:</p>
<pre><code>var list = context.GetMainItems(ids).ToList();
</code></pre>
<p>Method for context or repository:</p>
<pre><code>public partial class ContainsTestEntities
{
public IEnumerable<Main> GetMainItems(IEnumerable<int> ids, int chunkSize = 100)
{
foreach (var chunk in ids.Chunk(chunkSize))
{
var q = this.MainItems.Where(a => chunk.Contains(a.Id));
foreach (var item in q)
{
yield return item;
}
}
}
}
</code></pre>
<p>Extension methods for slicing enumerable sequences:</p>
<pre><code>public static class EnumerableSlicing
{
private class Status
{
public bool EndOfSequence;
}
private static IEnumerable<T> TakeOnEnumerator<T>(IEnumerator<T> enumerator, int count,
Status status)
{
while (--count > 0 && (enumerator.MoveNext() || !(status.EndOfSequence = true)))
{
yield return enumerator.Current;
}
}
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> items, int chunkSize)
{
if (chunkSize < 1)
{
throw new ArgumentException("Chunks should not be smaller than 1 element");
}
var status = new Status { EndOfSequence = false };
using (var enumerator = items.GetEnumerator())
{
while (!status.EndOfSequence)
{
yield return TakeOnEnumerator(enumerator, chunkSize, status);
}
}
}
}
</code></pre>
<p>Hope this helps!</p> |
4,327,416 | JavaScript- find text within a page and jump to location in page | <p>I have a webpage with a large list of records (say 250+ rows of data in a table) and want to be able to just visit the page, immediately start typing, and have it jump me to the first row that matches the text I have typed. </p>
<p>Ideally, if I then continued to type more characters so the first match doesn't match anymore, it could then continue to respond to my input and jump me to the new match. </p>
<p>I've tried with window.find() but haven't had much success... can anyone reccomend a working solution? </p>
<p>I'm essentially looking for the equivalent to hitting 'CTRL-F' on my keyboard... except without the need to hit CTRL-F to make it happen.</p> | 4,328,068 | 3 | 0 | null | 2010-12-01 17:57:08.48 UTC | 3 | 2021-07-19 10:42:07.493 UTC | null | null | null | null | 26,133 | null | 1 | 16 | javascript|jquery|html | 49,834 | <p>I think the tricky part of this is actually the accepting of user input intelligently. Therefore, I'd say the best thing to do is to pass off your searching to an autocomplete-type plugin. Once the page is ready, you pass the focus to an input text box, and then let the plugin do its magic as you search...</p>
<p>For example, you could use the <a href="https://github.com/riklomas/quicksearch" rel="noreferrer">quicksearch</a> plugin. </p>
<p>Then given a table of data and an input like this:</p>
<pre><code><input id="searcher" type="text" name="searcher">
</code></pre>
<p>You could have a ready function that looks like this:</p>
<pre><code>$('#searcher').quicksearch('table tbody tr', {
'delay': 100,
'bind': 'keyup keydown',
'show': function() {
if ($('#searcher').val() === '') {
return;
}
$(this).addClass('show');
},
'onAfter': function() {
if ($('#searcher').val() === '') {
return;
}
if ($('.show:first').length > 0){
$('html,body').scrollTop($('.show:first').offset().top);
}
},
'hide': function() {
$(this).removeClass('show');
},
'prepareQuery': function(val) {
return new RegExp(val, "i");
},
'testQuery': function(query, txt, _row) {
return query.test(txt);
}
});
$('#searcher').focus();
</code></pre>
<p>Try it out here: <a href="http://jsfiddle.net/ZLhAd/369/" rel="noreferrer">http://jsfiddle.net/ZLhAd/369/</a></p>
<p><strong>EDIT</strong>: other answer/comment added in to make the input fixed and stop the scollbar jumping around so ridiculously.</p> |
4,294,039 | How can I store an array of strings in a Django model? | <p>I am building a Django data model and I want to be able to store an array of strings in one of the variables; how can I do that?</p>
<p>e.g.</p>
<pre><code>class myClass(models.Model):
title = models.CharField(max_length=50)
stringArr = models.???
</code></pre>
<p>Thanks for the help.</p> | 4,294,050 | 6 | 0 | null | 2010-11-27 21:36:10.023 UTC | 3 | 2022-05-27 04:30:55.087 UTC | null | null | null | null | 487,060 | null | 1 | 32 | python|django|django-models | 32,601 | <p>Make another model that holds a string with an optional order, give it a <code>ForeignKey</code> back to <code>myClass</code>, and store your array in there.</p> |
4,411,457 | How do I verify/check/test/validate my SSH passphrase? | <p>I think I forgot the passphrase for my SSH key, but I have a hunch what it might be. How do I check if I'm right?</p> | 4,411,507 | 6 | 0 | null | 2010-12-10 17:13:55.66 UTC | 89 | 2021-11-29 20:05:24.69 UTC | 2020-04-28 23:24:38.32 UTC | null | 10,559 | null | 187,581 | null | 1 | 408 | ssh|ssh-keys|openssh | 297,102 | <p>You can verify your SSH key passphrase by attempting to load it into your SSH agent. With <a href="https://en.wikipedia.org/wiki/OpenSSH" rel="noreferrer">OpenSSH</a> this is done via <code>ssh-add</code>.</p>
<p>Once you're done, remember to unload your SSH passphrase from the terminal by running <code>ssh-add -d</code>.</p> |
4,583,285 | Change jsp on button click | <p>I have a question.</p>
<p>I have 3 jsp page.
The first is a menu with 2 button.
When I click the first button I want to open the second jsp page.
When I click the second button I want to open the third jsp page.</p>
<p>Can you help me? I must use a servlet(it's not a problem, i know it)?</p>
<pre><code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="TrainerMenu" action="TrainerMenu" method="get">
<h1>Benvenuto in LESSON! Scegli l'operazione da effettuare:</h1>
<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />
<input type="button" value="Gestione Autorizzazioni"
name="AuthorizationManager" />
</form>
</body>
</html>
</code></pre> | 4,583,345 | 8 | 0 | null | 2011-01-03 09:17:51.357 UTC | 5 | 2021-10-18 22:16:38.397 UTC | 2017-03-15 14:32:26.343 UTC | null | -1 | null | 315,378 | null | 1 | 10 | java|jsp|servlets | 193,633 | <p>You have several options, I'll start from the easiest:</p>
<p>1- Change the input buttons to links, you can style them with css so they look like buttons:</p>
<pre><code><a href="CreateCourse.jsp">Creazione Nuovo Corso</a>
</code></pre>
<p>instead of </p>
<pre><code><input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />
</code></pre>
<p>2- Use javascript to change the action of the form depending on the button you click:</p>
<pre><code><input type="button" value="Creazione Nuovo Corso" name="CreateCourse"
onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />
</code></pre>
<p>3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.</p> |
14,370,636 | Sorting a List of 3d coplanar points to be clockwise or counterclockwise | <p>I have a list of 3D points. I know they are all coplanar. I have the center that I want to sort them around and the normal to the plane on which the points and the center lie. How can I test if one point is right (or left) of another point?</p>
<p>I understand how to do it in 2D. <a href="https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order">Sort points in clockwise order?</a> explains how to compare 2d points. So I think I need to somehow covert all the points and the center to local 2d plane coordinates. How can I do that? Is it the most efficient way to solve this problem?</p>
<pre><code>//from link:
// a and b are points
//center is the center around which to determine order
//int num = (a.x-center.x) * (b.y-center.y) - (b.x - center.x) * (a.y - center.y);
//if num=0 then they're on the same line
//if num <0 or num>0 then a is to the left or right of b
</code></pre>
<p>How would I adapt this to handle 3d coplanar points?</p> | 14,371,081 | 1 | 4 | null | 2013-01-17 01:06:34.497 UTC | 10 | 2016-05-09 22:16:27.557 UTC | 2017-05-23 12:15:02.963 UTC | null | -1 | null | 1,772,595 | null | 1 | 12 | math|geometry|linear-algebra | 6,459 | <p>There's no need to convert everything to 2D.</p>
<p>You have the center <b>C</b> and the normal <b>n</b>. To determine whether point <b>B</b> is clockwise or counterclockwise from point <b>A</b>, calculate dot(<b>n</b>, cross(<b>A</b>-<b>C</b>, <b>B</b>-<b>C</b>)). If the result is positive, <b>B</b> is counterclockwise from <b>A</b>; if it's negative, <b>B</b> is clockwise from <b>A</b>.</p> |
14,823,772 | java math library for BigDecimal which allows null values | <p>Is there a BigDecimal library with the basic operations of BigDecimal which allows null values?</p>
<p>Null should be treated as 0 for mathematical purpose.</p>
<p>I don't want to do all the null checks for possible null values.</p>
<p>You either never allow null values in database, application or view and initialize everything with <code>new BigDecimal(0)</code> or perform null checks on every usage for nullable values.</p>
<p>Something like:</p>
<pre><code>public static BigDecimal add(final BigDecimal value, final BigDecimal augend)
{
if (value == null)
return augend;
else if (augend == null)
return value;
else
return value.add(augend);
}
public static BigDecimal multiply(final BigDecimal value, final BigDecimal multiplicand)
{
if (value == null || multiplicand == null)
return null;
return value.multiply(multiplicand);
}
</code></pre> | 14,823,899 | 5 | 0 | null | 2013-02-12 00:55:52.947 UTC | 5 | 2022-03-27 19:25:14.843 UTC | 2013-02-12 01:42:57.363 UTC | null | 1,085,958 | null | 1,085,958 | null | 1 | 27 | java|bigdecimal | 115,504 | <p>Save the coding, just don't allow null values in the database. Make the default value zero.</p>
<p>As for <code>new BigDecimal(0)</code>: no, use <code>BigDecimal.ZERO</code>.</p> |
14,660,091 | Xcode 4.6, used as the name of the previous parameter rather than as part of the selector | <p>I'm getting the following warning from Xcode 4.6.</p>
<pre><code>.. used as the name of the previous parameter rather than as part of the selector
</code></pre>
<p>I know I can disable this warning, but I'd rather fix it.</p>
<p>I have 109 such warnings, so I'm obviously writing methods badly.</p>
<p>Here's a couple of my methods.</p>
<pre><code>+(NSString*)addFormatPrice:(double)dblPrice:(BOOL)booRemoveCurSymbol;
-(void)showHelpChoices:(UIView *)vw:(id)dg;
</code></pre>
<p>So, whats the correct way to write these methods ?</p> | 14,660,141 | 4 | 1 | null | 2013-02-02 08:29:43.733 UTC | 6 | 2013-02-05 14:44:28.31 UTC | null | null | null | null | 450,456 | null | 1 | 31 | iphone|objective-c|xcode|cocoa-touch | 30,307 | <p>Your first method is declaring the selector <code>+addFormatPrice::</code>. With spaces, it looks like</p>
<pre><code>+ (NSString *)addFormatPrice:(double)dblPrice :(BOOL)booRemoveCurSymbol;
</code></pre>
<p>This is invoked like <code>[NSString addFormatPrice:0.3 :YES]</code>.</p>
<p>What you should do is actually give a name to the previous parameter, such as</p>
<pre><code>+ (NSString *)addFormatPrice:(double)dblPrice removeCurSymbol:(BOOL)booRemoveCurSymbol;
</code></pre>
<p>Which would then be invoked like <code>[NSString addFormatPrice:0.3 removeCurSymbol:YES]</code>.</p> |
14,794,599 | How to change line width in ggplot? | <p>Datalink:
<a href="https://www.dropbox.com/s/yt4l10nel5bwxoq/GTAP_ConsIndex.csv">the data used</a></p>
<p>My code:</p>
<pre><code>ccfsisims <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_ConsIndex.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
ccfsirsts <- as.data.frame(ccfsisims)
ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric)
ccfsirsts <- droplevels(ccfsirsts)
ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres)))
library(ggplot2)
#------------------------------------------------------------------------------------------
#### Plot of food security index for Morocco and Turkey by sector
#------------------------------------------------------------------------------------------
#_Code_Begin...
datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c("TUR","MAR"), ]) # Selecting regions of interest
datamortur1 <- datamortur[datamortur$variable %in% c("pFSI2"), ] # Selecting the food security index of interest
datamortur2 <- datamortur1[datamortur1$sector %in% c("wht","gro","VegtFrut","osd","OthCrop","VegtOil","XPrFood"), ] # Selecting food sectors of interest
datamortur3 <- subset(datamortur2, tradlib !="BASEDATA") # Eliminating the "BASEDATA" scenario results
allfsi.f <- datamortur3
fsi.wht <- allfsi.f[allfsi.f$sector %in% c("wht"), ]
Figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib)))
Figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsFull~., scales="free_y", labeller=reg_labeller) + scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))
</code></pre>
<p>My result:
<img src="https://i.stack.imgur.com/oSMtm.png" alt="Result_Figure"> </p>
<p>Newresult with aes(size=2):
<img src="https://i.stack.imgur.com/ZZ0Tu.png" alt="NewResult-Figure"></p>
<p>My question:
Is there a way to control for line width more precisely to avoid the result in the second plot? I particularly find it document-unfriendly, and more so for publishing purposes to include the plot with the newly defined line width.</p>
<p>best,
ismail </p> | 14,804,381 | 5 | 2 | null | 2013-02-10 04:07:03.97 UTC | 36 | 2020-07-20 14:21:06.057 UTC | 2018-03-07 07:38:58.053 UTC | null | 2,204,410 | null | 1,978,243 | null | 1 | 169 | r|ggplot2|line-plot | 480,426 | <p>Whilst @Didzis has the <a href="https://stackoverflow.com/a/14796845/1385941">correct answer</a>, I will expand on a few points</p>
<p>Aesthetics can be set or mapped within a ggplot call.</p>
<ul>
<li><p>An aesthetic defined within aes(...) is mapped from the data, and a legend created.</p></li>
<li><p>An aesthetic may also be set to a single value, by defining it outside aes().</p></li>
</ul>
<p>As far as I can tell, what you want is to <em>set</em> size to a single value, not <em>map</em> within the call to <code>aes()</code></p>
<p>When you call <code>aes(size = 2)</code> it creates a variable called <code>`2`</code> and uses that to create the size, mapping it from a constant value as it is within a call to <code>aes</code> (thus it appears in your legend).</p>
<p>Using size = 1 (and without <code>reg_labeller</code> which is perhaps defined somewhere in your script)</p>
<pre><code>Figure29 +
geom_line(aes(group=factor(tradlib)),size=1) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(
colour = 'black', angle = 90, size = 13,
hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
</code></pre>
<p><img src="https://i.stack.imgur.com/AQUoz.png" alt="enter image description here"></p>
<p>and with size = 2</p>
<pre><code> Figure29 +
geom_line(aes(group=factor(tradlib)),size=2) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90,
size = 13, hjust = 0.5, vjust =
0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
</code></pre>
<p><img src="https://i.stack.imgur.com/yEbG5.png" alt="enter image description here"></p>
<p>You can now define the size to work appropriately with the final image size and device type.</p> |
44,488,357 | Equal height rows in CSS Grid Layout | <p>I gather that this is impossible to achieve using Flexbox, as each row can only be the minimal height required to fit its elements, but can this be achieved using the newer CSS Grid?</p>
<p>To be clear, I want equal height for all elements in a grid across all rows, not just per each row. Basically, the highest "cell" should dictate the height of all cells, not just the cells in its row. </p> | 44,490,047 | 2 | 0 | null | 2017-06-11 20:16:49.367 UTC | 51 | 2021-05-18 04:55:37.923 UTC | 2017-06-12 18:32:34.603 UTC | null | 3,597,276 | null | 6,609,930 | null | 1 | 190 | css|flexbox|grid-layout|css-grid | 240,611 | <h2>Short Answer</h2>
<p>If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:</p>
<ul>
<li>Set the container to <code>grid-auto-rows: 1fr</code></li>
</ul>
<hr>
<h2>How it works</h2>
<p>Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the <a href="https://www.w3.org/TR/css3-grid-layout/#fr-unit" rel="noreferrer"><strong><code>fr</code></strong></a> unit. It is designed to distribute free space in the container and is somewhat analogous to the <code>flex-grow</code> property in flexbox.</p>
<p>If you set all rows in a grid container to <code>1fr</code>, let's say like this:</p>
<pre><code>grid-auto-rows: 1fr;
</code></pre>
<p>... then all rows will be equal height.</p>
<p>It doesn't really make sense off-the-bat because <code>fr</code> is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.</p>
<p><strong><em>Except</em></strong>, buried deep in the grid spec is this little nugget:</p>
<blockquote>
<p><a href="https://www.w3.org/TR/css3-grid-layout/#fr-unit" rel="noreferrer"><strong>7.2.3. Flexible Lengths: the <code>fr</code>
unit</strong></a></p>
<p>...</p>
<p>When the available space is infinite (which happens when the grid
container’s width or height is indefinite), flex-sized (<code>fr</code>) grid tracks are
sized to their contents while retaining their respective proportions.</p>
<p>The used size of each flex-sized grid track is computed by determining
the <code>max-content</code> size of each flex-sized grid track and dividing that
size by the respective flex factor to determine a “hypothetical <code>1fr</code>
size”.</p>
<p>The maximum of those is used as the resolved <code>1fr</code> length (the
flex fraction), which is then multiplied by each grid track’s flex
factor to determine its final size.</p>
</blockquote>
<p>So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.</p>
<p>The height of each row is determined by the tallest (<a href="https://www.w3.org/TR/css3-grid-layout/#valdef-grid-template-columns-max-content" rel="noreferrer"><code>max-content</code></a>) grid item.</p>
<p>The maximum height of those rows becomes the length of <code>1fr</code>.</p>
<p>That's how <code>1fr</code> creates equal height rows in a grid container.</p>
<hr>
<h2>Why flexbox isn't an option</h2>
<p>As noted in the question, equal height rows are not possible with flexbox.</p>
<p>Flex items can be equal height on the same row, but not across multiple rows.</p>
<p>This behavior is defined in the flexbox spec:</p>
<blockquote>
<p><a href="https://www.w3.org/TR/css3-flexbox/#flex-lines" rel="noreferrer"><strong>6. Flex Lines</strong></a></p>
<p>In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.</p>
</blockquote>
<p>In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.</p> |
56,436,345 | How to upload to App Store from command line with Xcode 11? | <p>Previously, with Xcode 10, we were using <code>altool</code> to upload to App Store:</p>
<pre class="lang-sh prettyprint-override"><code>ALTOOL="/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Support/altool"
"$ALTOOL" --upload-app --file "$IPA_PATH" --username "$APP_STORE_USERNAME" --password @keychain:"Application Loader: $APP_STORE_USERNAME"
</code></pre>
<p>But with Xcode 11, "Application Loader.app" doesn't exist anymore, as part of <a href="https://developer.apple.com/documentation/xcode_release_notes/xcode_11_beta_release_notes/" rel="noreferrer">the Xcode 11 changes</a>:</p>
<blockquote>
<p>Xcode supports uploading apps from the Organizer window or from the command line with xcodebuild or xcrun altool. Application Loader is no longer included with Xcode. (29008875)</p>
</blockquote>
<p>So how do we upload from command line to TestFlight or App Store now?</p> | 56,436,346 | 4 | 0 | null | 2019-06-04 01:38:27.153 UTC | 12 | 2020-06-05 04:50:45.327 UTC | null | null | null | null | 1,033,581 | null | 1 | 47 | ios|xcode|app-store-connect|xcode11 | 20,958 | <p>With Xcode 11 as command line tools, to validate or upload an ipa, replace <code>altool</code> with <code>xcrun altool</code>:</p>
<pre class="lang-sh prettyprint-override"><code>xcrun altool --validate-app --file "$IPA_PATH" --username "$APP_STORE_USERNAME" --password @keychain:"Application Loader: $APP_STORE_USERNAME"
xcrun altool --upload-app --file "$IPA_PATH" --username "$APP_STORE_USERNAME" --password @keychain:"Application Loader: $APP_STORE_USERNAME"
</code></pre>
<p>Get more help with <code>xcrun altool --help</code>.</p> |
41,742,046 | Is there a list of all cfg features? | <p>Rust has the ability to <a href="https://doc.rust-lang.org/book/conditional-compilation.html" rel="noreferrer">check configuration at build</a> time with, e.g., <code>#[cfg(target_os = "linux")]</code> or <code>if cfg!(target_os = "linux") {...}</code>, where <code>target_os</code> is a <em>feature</em>.</p>
<p>Is there a list of all (or, at least, commonly used) features that can be checked in Rust?</p>
<hr>
<p>See related question regarding <em>attributes</em> <a href="https://stackoverflow.com/questions/37900513/is-there-an-exhaustive-list-of-standard-attributes-anywhere?noredirect=1&lq=1">Is there an exhaustive list of standard attributes anywhere?</a>.</p> | 41,743,950 | 3 | 0 | null | 2017-01-19 12:39:58.267 UTC | 15 | 2019-04-11 09:36:57.297 UTC | 2018-02-15 14:30:17.11 UTC | null | 3,924,118 | null | 432,509 | null | 1 | 33 | rust|rust-cargo | 17,851 | <p>The <a href="https://doc.rust-lang.org/reference/conditional-compilation.html" rel="noreferrer">"Conditional compilation" section of the Reference</a> has a list of configurations that must be defined <em>(as of Rust 1.14)</em>:</p>
<ul>
<li><code>target_arch</code> with values like:
<ul>
<li><code>x86</code> </li>
<li><code>x86_64</code></li>
<li><code>mips</code></li>
<li><code>powerpc</code></li>
<li><code>powerpc64</code></li>
<li><code>arm</code></li>
<li><code>aarch64</code></li>
</ul></li>
<li><code>target_os</code> with values like:
<ul>
<li><code>windows</code></li>
<li><code>macos</code></li>
<li><code>ios</code></li>
<li><code>linux</code></li>
<li><code>android</code></li>
<li><code>freebsd</code></li>
<li><code>dragonfly</code></li>
<li><code>bitrig</code></li>
<li><code>openbsd</code></li>
<li><code>netbsd</code></li>
</ul></li>
<li><code>target_family</code> with values like:
<ul>
<li><code>unix</code></li>
<li><code>windows</code></li>
</ul></li>
<li><code>unix</code> (shortcut for <code>target_family</code>)</li>
<li><code>windows</code> (shortcut for <code>target_family</code>)</li>
<li><code>target_env</code> with values like:
<ul>
<li><code>gnu</code></li>
<li><code>msvc</code></li>
<li><code>musl</code></li>
<li><code>""</code> (empty string)</li>
</ul></li>
<li><code>target_endian</code> with values:
<ul>
<li><code>little</code></li>
<li><code>big</code></li>
</ul></li>
<li><code>target_pointer_width</code> with values like:
<ul>
<li><code>32</code></li>
<li><code>64</code></li>
</ul></li>
<li><code>target_has_atomic</code> with values like:
<ul>
<li><code>8</code></li>
<li><code>16</code></li>
<li><code>32</code></li>
<li><code>64</code></li>
<li><code>ptr</code></li>
</ul></li>
<li><code>target_vendor</code> with values like:
<ul>
<li><code>apple</code></li>
<li><code>pc</code></li>
<li><code>unknown</code></li>
</ul></li>
<li><code>test</code></li>
<li><code>debug_assertions</code></li>
</ul> |
2,508,773 | Jquery delay on fadeout | <p>I have this code that changes the opacity of the div on hover.</p>
<pre><code>$("#navigationcontainer").fadeTo("slow",0.6);
$("#navigationcontainer").hover(function(){ $("#navigationcontainer").fadeTo("slow",
1.0); // This sets the opacity to 100% on hover },function(){
$("#navigationcontainer").fadeTo("slow",
0.6); // This sets the opacity back to 60% on mouseout });
</code></pre>
<p>I want to have a delay before setting the div back to 0.6 opacity how would i do this</p> | 2,508,794 | 3 | 0 | null | 2010-03-24 15:06:22.563 UTC | 3 | 2010-03-24 15:19:46.56 UTC | 2010-03-24 15:08:14.383 UTC | null | 265,143 | null | 272,899 | null | 1 | 13 | jquery|delay|fadeout | 44,831 | <p>With jQuery 1.4, you have a method called <a href="http://api.jquery.com/delay/" rel="noreferrer"><code>delay</code></a>, which takes an integer representing ms you want to delay</p>
<pre><code>$("#navigationcontainer").delay(500).fadeTo("slow", 0.6);
</code></pre>
<p>Half a second delay</p> |
2,913,160 | Hibernate count collection size without initializing | <p>Is there a way I can count the size of an associated collection without initializing?</p>
<p>e.g.</p>
<pre><code>Select count(p.children) from Parent p
</code></pre>
<p>(there is a good reason why I cant do this any other way as my where clause is more complicated and my from clause is a polymorphic query)</p>
<p>Thanks.</p> | 2,913,876 | 3 | 1 | null | 2010-05-26 13:04:58.807 UTC | 14 | 2015-04-06 11:11:35.463 UTC | 2010-08-02 11:27:10.85 UTC | null | 265,143 | null | 249,571 | null | 1 | 41 | java|hibernate|lazy-loading | 25,300 | <p>A possible solution other than queries might be mapping <code>children</code> with <code>lazy="extra"</code> (in XML notation). This way, you can fetch the Parent with whatever query you need, then call <code>parent.getChildren().size()</code> without loading the whole collection (only a <code>SELECT COUNT</code> type query is executed).</p>
<p>With annotations, it would be</p>
<pre><code>@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Child> children = new HashSet<Child>();
</code></pre>
<p><strong>Update:</strong> Quote from <a href="http://www.manning.com/bauer2/" rel="noreferrer">Java Persistence with Hibernate</a>, ch. 13.1.3:</p>
<blockquote>
<p>A proxy is initialized if you call any method that is not the identifier getter
method, a collection is initialized if you start iterating through its elements or if
you call any of the collection-management operations, such as <code>size()</code> and <code>contains()</code>.
Hibernate provides an additional setting that is mostly useful for large collections; they can be mapped as <em>extra lazy</em>. [...]</p>
<p>[Mapped as above,] the collection is no longer initialized if you call <code>size()</code>, <code>contains()</code>, or <code>isEmpty()</code> — the database is queried to retrieve the necessary information. If it’s a <code>Map</code> or a <code>List</code>, the operations <code>containsKey()</code>
and <code>get()</code> also query the database directly.</p>
</blockquote>
<p>So with an entity mapped as above, you can then do</p>
<pre><code>Parent p = // execute query to load desired parent
// due to lazy loading, at this point p.children is a proxy object
int count = p.getChildren().size(); // the collection is not loaded, only its size
</code></pre> |
2,509,635 | How to call outer function's return from inner function? | <p>I have such code:</p>
<pre><code>function allValid() {
$('input').each(function(index) {
if(something) {
return false;
}
});
return true;
}
</code></pre>
<p>which always returns true as <code>return false;</code> affects anonymous inner function. Is there an easy way to call outer function's return?</p>
<p><strong>PS.</strong> I am not looking for a workaround, just want to know the answer to original question. If the answer is "not possible" it is fine.</p> | 2,509,651 | 4 | 0 | null | 2010-03-24 16:49:49.787 UTC | 5 | 2018-07-30 07:20:20.83 UTC | 2018-07-30 07:20:20.83 UTC | null | 479,156 | null | 20,128 | null | 1 | 41 | javascript|jquery | 21,844 | <p>Yeah, store it in a local variable.</p>
<pre><code>function allValid() {
var allGood = true;
$('input').each(function (index) {
if (something) {
allGood = false;
}
});
return allGood;
}
</code></pre> |
3,213,531 | Creating a new Location object in javascript | <p>Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.</p>
<p>Here's an example of what I'm talking about (I know this doesn't work):</p>
<pre><code>var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
</code></pre>
<p>Is anything like this possible or would I essentially have to create this object myself?</p> | 3,213,643 | 4 | 0 | null | 2010-07-09 14:23:58.363 UTC | 22 | 2022-01-25 21:50:32.983 UTC | 2011-05-29 15:05:13.8 UTC | null | 172,322 | null | 235,179 | null | 1 | 77 | javascript|url-parsing | 31,105 | <p>Well, you could use an anchor element to extract the url parts, for example:</p>
<pre><code>var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
</code></pre>
<p>It works on all modern browsers and even on IE 5.5+.</p>
<p>Check an example <a href="http://jsbin.com/atije3/2/" rel="noreferrer">here</a>.</p> |
49,797,264 | Full Width Material-UI Grid not working as it should | <p>I am trying to understand Material-UI@next grid layout system. </p>
<p>My goal is to have two papers that expand through the whole width screen and break whenever the screen gets smaller to just one paper. The <a href="https://material-ui-next.com/layout/grid/" rel="noreferrer">documentation</a> has the following code snippet:</p>
<pre><code> <Container>
<Grid container spacing={24}>
<Grid item xs={12}>
<Paper>xs=12</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper>xs=6 sm=3</Paper>
</Grid>
</Grid>
</Container>
</code></pre>
<p>This results in the following:
<a href="https://i.stack.imgur.com/rVdfw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rVdfw.png" alt="enter image description here"></a></p>
<p>I then modified the code to try to achieve my goal of just two papers, as this:</p>
<pre><code> <Container>
<Grid container spacing={24}>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
</Grid>
</Container>
</code></pre>
<p>But as you can see, this results into two papers which are not taking the whole screen:
<a href="https://i.stack.imgur.com/XHYwA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XHYwA.png" alt="enter image description here"></a></p>
<p>Can someone point me to a working example snippet that allows me to have two elements that take the full width?</p> | 49,797,882 | 4 | 0 | null | 2018-04-12 12:59:53.737 UTC | 8 | 2021-07-27 16:23:05.173 UTC | null | null | null | null | 5,979,642 | null | 1 | 35 | css|reactjs|material-design|material-ui | 97,840 | <p>I suspect the Container component is causing you problems. Since you haven't linked its implementation, see below for a working example of what you want.</p>
<p>Since Material uses <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">flexbox</a> they make use of property <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow" rel="noreferrer">flexGrow</a></p>
<blockquote>
<p>The flex-grow CSS property specifies the flex grow factor of a flex item. It specifies what amount of space inside the flex container the item should take up. The flex grow factor of a flex item is relative to the size of the other children in the flex-container.</p>
</blockquote>
<p>This is the property that governs the growth of elements in the grid. </p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
const styles = theme => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing.unit * 2,
textAlign: 'center',
color: theme.palette.text.secondary,
},
});
function CenteredGrid(props) {
const { classes } = props;
return (
<div className={classes.root}>
<Grid container spacing={24}>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper>xs=12 sm=6</Paper>
</Grid>
</Grid>
</div>
);
}
CenteredGrid.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(CenteredGrid);
</code></pre> |
33,943,943 | Clear Recent Projects list in Visual Studio 2015 | <p>Does anyone know how to clear the Recent Projects list on the start page of VS2015? Apparently VS2015 doesn't have an MRU file in the registry and I can't find any tutorials on how to clear the list for the 2015 version. Thanks!</p> | 33,945,037 | 3 | 0 | null | 2015-11-26 17:08:00.037 UTC | 9 | 2020-02-10 14:35:49.917 UTC | null | null | null | null | 2,757,398 | null | 1 | 33 | visual-studio|visual-studio-2015 | 37,400 | <p>The MRU list just moved for VS 2015. It's still stored in the registry, it's just in a different place.</p>
<p>Open regedit and delete the items in:</p>
<p><strong>Recent Projects</strong><br/>
<code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\MRUItems\{a9c4a31f-f9cb-47a9-abc0-49ce82d0b3ac}\Items</code></p>
<p><strong>Recent Files</strong><br/>
<code>HKEY_CURRENT_USER\SOFTWARE\Microsoft\VisualStudio\14.0\MRUItems\{01235aad-8f1b-429f-9d02-61a0101ea275}\Items</code></p>
<p>Restart Visual Studio and that should do it.</p> |
27,884,404 | Printing test execution times and pinning down slow tests with py.test | <p>I am running unit tests on a CI server using py.test. Tests use external resources fetched over network. Sometimes test runner takes too long, causing test runner to be aborted. I cannot repeat the issues locally.</p>
<p>Is there a way to make py.test print out execution times of (slow) test, so pinning down problematic tests become easier?</p> | 27,899,853 | 2 | 0 | null | 2015-01-11 05:54:22.32 UTC | 17 | 2020-02-21 13:49:43.433 UTC | null | null | null | null | 315,168 | null | 1 | 195 | python|pytest | 40,743 | <p>I'm not sure this will solve your problem, but you can pass <code>--durations=N</code> to print the slowest <code>N</code> tests after the test suite finishes.</p>
<p>Use <code>--durations=0</code> to print all.</p> |
50,289,355 | Google material design library error Program type already present: android.support.v4.app.INotificationSideChannel$Stub$Proxy | <p>Whenever i add <code>implemntation 'com.google.android.material:material:1.0.0-alpha1'</code> when i try to build my project Android Studio says:</p>
<blockquote>
<p>Program type already present: android.support.v4.app.INotificationSideChannel$Stub$Proxy
Message{kind=ERROR, text=Program type already present: android.support.v4.app.INotificationSideChannel$Stub$Proxy, sources=[Unknown source file], tool name=Optional.of(D8)}</p>
</blockquote>
<p>This is my gradle script:</p>
<pre><code> apply plugin: 'com.android.application'
android {
compileSdkVersion 'android-P'
defaultConfig {
applicationId "it.smart.bab3"
minSdkVersion 21
targetSdkVersion 'p'
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.google.android.material:material:1.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:design:28.0.0-alpha1'
implementation 'com.android.support:support-v4:28.0.0-alpha1'
}
</code></pre>
<p>I'm new ith this type of errors, and i didn't find anithing with this error. Thanks</p> | 50,301,692 | 14 | 0 | null | 2018-05-11 09:36:36.267 UTC | 10 | 2020-11-07 20:54:01.09 UTC | null | null | null | null | 6,454,820 | null | 1 | 39 | java|android|android-gradle-plugin | 52,819 | <p>I've been struggling all day with this issue too. Finally I managed to compile and run the project successfully.</p>
<p>First of all, get rid of this:</p>
<pre><code>implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0-alpha1'
implementation 'com.android.support:support-v4:28.0.0-alpha1'
</code></pre>
<p>Add the following in your gradle.properties file:</p>
<pre><code>android.useAndroidX = true
android.enableJetifier = false
</code></pre>
<p>And finally, sync the project and then compile.</p>
<p>If it doesn't work, clean the project and then rebuild.</p>
<p>PS: I can't get targetSdkVersion 'p' to work. My build.gradle file end up as follows:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 'android-P'
defaultConfig {
applicationId "com.github.alvarosct02.demo"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.android.material:material:1.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code></pre>
<p>Hope it works for you too.</p> |
53,728,230 | Cannot re-export a type when using the --isolatedModules with TS 3.2.2 | <p>I probably need to rethink the way we structure our React components. We are using the latest react-scripts that allow Typescript to be used and by default, the <code>isolatedModules</code> is being enabled which currently bugs me a bit.</p>
<p>We used to structure a component like this:</p>
<pre><code>Component
|_ Component.tsx
|_ index.ts
|_ types.ts
</code></pre>
<ul>
<li><code>Component.tsx</code> holds the actual component without declarations</li>
<li><p><code>index.ts</code> is just re-exporting everything so we can have a singular entry point and can do something like <code>import Component, { ComponentType } from '@/Component';</code></p></li>
<li><p><code>types.ts</code> holds the actual type definitions and exports most or all of them.</p></li>
</ul>
<p>So far so good and that works without the <code>isolatedModules</code>. However, we also export some of the type definitions, effectively re-exporting the interfaces that were specified within <code>Component/types.ts</code>. This won't work as TypeScript itself would not transpile the code any longer.</p>
<p>How can I re-export this without having a separate import statement going to <code>@/Component/types</code> (which might be actual the simpler way anyway)?</p> | 59,600,601 | 2 | 0 | null | 2018-12-11 16:17:55.067 UTC | 7 | 2020-04-18 10:05:08.453 UTC | 2018-12-11 16:31:46.817 UTC | null | 881,032 | null | 881,032 | null | 1 | 28 | typescript|webpack|webpack-4 | 15,452 | <h3>TS 3.8+</h3>
<p>You can use <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-type-only-imports-and-export" rel="noreferrer">type-only imports and exports</a> with <code>--isolatedModules</code>:</p>
<pre><code>// types.ts
export type MyType = { a: string; b: number; };
</code></pre>
<pre><code>// main.ts
// named import/export
import type { MyType } from './types'
export type { MyType }
// re-export
export type { MyType } from './types'
// namespace import
import type * as MyTypes from "./types";
export type RenamedType = MyTypes.MyType;
export { MyTypes };
// ^ Note the "type" keyword in statements above
</code></pre>
<p><a href="https://www.typescriptlang.org/play/#code/PTAECcFMFpIDwA4HtwBcBQ9ltKgngpKAN6gBiArgHYDGqAlklQMJIC2yVkVqoAvqABm4dqABEUAIZ0x6dCFBVJbSABNQ9DilTAs29Juy98hEqFZauPACoEiA4aImRpqWXpwmipC526pbUz45BSUVAGcEaSJDfVjPO1AAKlBJcNAAJRc6QMh0xzZxKRl0L1BrAEZQAF5M7IC7cIA6MmYgA" rel="noreferrer">Example Playground</a>; Take a look at the <a href="https://github.com/microsoft/TypeScript/pull/35200" rel="noreferrer">PR</a> for possible extension forms and proposals.</p>
<hr>
<h3>TS 3.7 or older</h3>
<p>In previous versions, the following is not possible:</p>
<pre><code>import { MyType } from './types';
export { MyType }; // error: Cannot re-export a type with --isolatedModules
export { MyType } from "./types"; // error, like above
</code></pre>
<p>Type re-exports have to use a <a href="https://github.com/babel/babel-loader/issues/603#issuecomment-418472968" rel="noreferrer">workaround</a>:</p>
<pre><code>import { MyType as MyType_ } from "./types";
export type MyType = MyType_;
// or
export * from "./types"
</code></pre> |
39,088,876 | Firebase Convert Anonymous User Account to Permanent Account Error | <p>Using Firebase for web I can successfully create an anonymous user. I can also create a new email/password user. But when trying to convert an anonymous user to a email/password user I get error:</p>
<pre><code>auth/provider-already-linked
User can only be linked to one identity for the given provider.
</code></pre>
<p>Firebase documents the procedure here under section "Convert an anonymous account to a permanent account" here:
<a href="https://firebase.google.com/docs/auth/web/anonymous-auth" rel="noreferrer">https://firebase.google.com/docs/auth/web/anonymous-auth</a></p>
<p>Here's the account link code. Anonymous user is signed in.</p>
<pre><code>return firebase.auth().createUserWithEmailAndPassword(email, password).then(newUser => {
// Credential is being successfully retrieved. Note "any" workaround until typescript updated.
let credential = (<any>firebase.auth.EmailAuthProvider).credential(email, password);
firebase.auth().currentUser.link(credential)
.then(user => { return user; })
.catch(err => console.log(err)); // Returns auth/provider-already-linked error.
});
</code></pre> | 39,092,993 | 3 | 0 | null | 2016-08-22 21:17:54.397 UTC | 12 | 2022-02-25 19:46:38.89 UTC | 2016-08-22 21:42:52.877 UTC | null | 209,103 | null | 464,435 | null | 1 | 35 | firebase|firebase-authentication | 14,672 | <p>You should not call <code>createUserWithEmailAndPassword</code> to upgrade the anonymous user. This will sign up a new user, signing out the currently signed in anonymous user.</p>
<p>All you need is the email and password of the user. IDP providers (e.g. Google, Facebook), on the contrary, will require to complete their full sign in flow to get their tokens to identify the user. We do recommend to use <a href="https://firebase.google.com/docs/reference/js/firebase.User#linkWithPopup" rel="noreferrer"><code>linkWithPopup</code></a> or <a href="https://firebase.google.com/docs/reference/js/firebase.User#linkWithRedirect" rel="noreferrer"><code>linkWithRedirect</code></a> for these, though.</p>
<p>Example:</p>
<pre class="lang-js prettyprint-override"><code>// (Anonymous user is signed in at that point.)
// 1. Create the email and password credential, to upgrade the
// anonymous user.
var credential = firebase.auth.EmailAuthProvider.credential(email, password);
// 2. Links the credential to the currently signed in user
// (the anonymous user).
firebase.auth().currentUser.linkWithCredential(credential).then(function(user) {
console.log("Anonymous account successfully upgraded", user);
}, function(error) {
console.log("Error upgrading anonymous account", error);
});
</code></pre>
<p>Let me know if that works!</p> |
2,373,544 | ClearFix vs Overflow | <p>Its the standard float issue. You have a bunch of floating elements inside a parent container div. Since the childs are floating, the parent doesnt expand to include all of them.</p>
<p>I know about the clearfix solution as well as setting the overflow property on the parent container div to "auto" or "hidden".<a href="http://www.quirksmode.org/css/clearing.html" rel="noreferrer">http://www.quirksmode.org/css/clearing.html</a>
To me setting the overflow method seems much nicer as its just one property. What I want to understand is when does the clearfix approach has advantage over this method cause I see it being used extremely often.</p>
<p>P.S. I am not concerned about IE6.</p> | 2,373,566 | 1 | 0 | null | 2010-03-03 17:37:10.353 UTC | 13 | 2010-03-03 17:40:14.32 UTC | null | null | null | null | 111,683 | null | 1 | 32 | css|clearfix | 11,186 | <p>The only time you should bother using the "clearfix" method that inserts invisible content to clear is if you need an element to be visible when it overflows the element you're applying it to, otherwise triggering hasLayout + overflow is golden.</p>
<p>Note that in IE7 overflow hidden triggers hasLayout. Not sure about IE8.</p>
<pre><code>#wrapper { width:80em; overflow:hidden; }
</code></pre>
<p>The method above will work fine in most all cases unless you need say, #header to overflow past #wrapper..</p>
<pre><code>#wrapper { width:80em; position:relative; }
#wrapper:after { content:"."; clear:both; display:block; height:0; visibility:hidden; }
#header { position:absolute; top:-15px; left:-15px; }
</code></pre> |
46,357,533 | How to Add, Delete new Columns in Sequelize CLI | <p>I've just started using Sequelize and Sequelize CLI</p>
<p>Since it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?</p>
<p>For example, I want to a new column '<strong>completed</strong>' to <strong>Todo</strong> model. I'll add this column to models/todo.js. Whats the next step?</p>
<p>I tried <code>sequelize db:migrate</code></p>
<p>not working: <em>"No migrations were executed, database schema was already up to date."</em></p> | 46,357,631 | 7 | 0 | null | 2017-09-22 05:37:38.77 UTC | 27 | 2020-07-20 12:04:06.39 UTC | null | null | null | null | 3,392,772 | null | 1 | 71 | node.js|sequelize.js|psql|sequelize-cli | 113,992 | <p>If you are using <a href="https://github.com/sequelize/cli" rel="noreferrer">sequelize-cli</a> you need to create the migration first. This is just a file that tells the engine how to update the database and how to roll back the changes in case something goes wrong. You should always commit this file to your repository</p>
<pre><code>$ sequelize migration:create --name name_of_your_migration
</code></pre>
<p>The migration file would look like this:</p>
<pre><code>module.exports = {
up: function(queryInterface, Sequelize) {
// logic for transforming into the new state
return queryInterface.addColumn(
'Todo',
'completed',
Sequelize.BOOLEAN
);
},
down: function(queryInterface, Sequelize) {
// logic for reverting the changes
return queryInterface.removeColumn(
'Todo',
'completed'
);
}
}
</code></pre>
<p>And then, run it:</p>
<pre><code>$ sequelize db:migrate
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.