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
22,622,459
Find Shelveset of Another User
<p>When I follow instructions to <a href="https://stackoverflow.com/questions/10244648/can-anybody-find-the-tfs-unshelve-option-in-visual-studio-2012">find a shelveset</a>, I'm given a list of all my personal shelvesets. But what I want is to view and unshelve from another user's selection. Other developers can simply change the user to whoever they want. No such option exists for me.</p> <p>I've told my TFS admin about this issue. The response I got was that "We haven’t locked anything down, you should be able to view others' shelvesets." Nevertheless, I can't see others' shelvesets.</p> <p>What could be causing this? What specific issue or permission(s) should the TFS admin check to confirm "we havn't locked anything down?"</p>
22,622,764
3
1
null
2014-03-24 23:09:11.4 UTC
3
2017-09-14 19:30:49.523 UTC
2017-05-23 12:17:33.887 UTC
null
-1
null
284,758
null
1
30
visual-studio-2012|tfs|team-explorer|shelveset
33,409
<p>You should be able to simply type in a different user name in the Find Shelvesets window and hit Enter (if that's not working whats the error message):</p> <p><img src="https://i.stack.imgur.com/XqMm9.png" alt="enter image description here"></p>
7,182,359
Template instantiation details of GCC and MS compilers
<p>Could anyone provide a comparison or specific details of how is template instantiation handled at compile and/or link time in GCC and MS compilers? Is this process different in the context of static libraries, shared libraries and executables? I found <a href="http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html" rel="noreferrer">this doc</a> about how GCC handles it but I'm not sure if the information is still referring to the current state of things. Should I use the flags they suggest there when compiling my libraries e.g. <em>-fno-implicit-templates</em>?</p> <p>What I know (might not necessarily be correct) is that:</p> <ul> <li>templates will be instantiated when actually used</li> <li>templates will be instantiated as a result of explicit instantiations</li> <li>duplicate instantiation is usually handled by folding duplicate instantiations, or by deferring instantiation until link time</li> </ul>
7,241,548
2
3
null
2011-08-24 21:14:45.913 UTC
35
2014-11-13 22:01:28.933 UTC
2011-08-24 21:30:50.943 UTC
null
198,536
null
59,775
null
1
45
c++|visual-studio|templates|gcc|compiler-construction
10,525
<hr> <h1>Point of instantiation</h1> <blockquote> <p>templates will be instantiated when actually used</p> </blockquote> <p>Not exactly, but roughly. The precise point of instantiation is a bit subtle, and I delegate you over to the section named <a href="http://books.google.de/books?id=yQU-NlmQb_UC&amp;lpg=PA146&amp;dq=vandevoorde%20point%20of%20instantiation&amp;pg=PA146#v=onepage&amp;q&amp;f=false" rel="noreferrer">Point of instantiation</a> in Vandevoorde's/Josuttis' fine book.</p> <p>However, compilers do not necessarily implement the POIs correctly: <a href="http://www.mail-archive.com/[email protected]/msg269802.html" rel="noreferrer">Bug c++/41995: Incorrect point of instantiation for function template</a></p> <hr> <h1>Partial instantiation</h1> <blockquote> <p>templates will be instantiated when actually used</p> </blockquote> <p>That is partially correct. It is true for function templates, but for class templates, only the member functions that are used are instantiated. The following is well-formed code:</p> <pre><code>#include &lt;iostream&gt; template &lt;typename&gt; struct Foo { void let_me_stay() { this-&gt;is-&gt;valid-&gt;code. get-&gt;off-&gt;my-&gt;lawn; } void fun() { std::cout &lt;&lt; "fun()" &lt;&lt; std::endl; } }; int main () { Foo&lt;void&gt; foo; foo.fun(); } </code></pre> <p><code>let_me_stay()</code> is checked syntactically (and the syntax there is correct), but not semantically (i.e. it is not interpreted).</p> <h2><br/></h2> <h1>Two phase lookup</h1> <p>However, only <em>dependent code</em> is interpreted later; clearly, within <code>Foo&lt;&gt;</code>, <code>this</code> is dependent upon the exact template-id with which <code>Foo&lt;&gt;</code> is instantiated, so we postponed error-checking of <code>Foo&lt;&gt;::let_me_alone()</code> until instantiation time.</p> <p>But if we do not use something that depends on the specific instantiation, the code must be good. Therefore, the following is <strong>not</strong> well-formed:</p> <pre><code>$ cat non-dependent.cc template &lt;typename&gt; struct Foo { void I_wont_compile() { Mine-&gt;is-&gt;valid-&gt;code. get-&gt;off-&gt;my-&gt;lawn; } }; int main () {} // note: no single instantiation </code></pre> <p><code>Mine</code> is a completely unknown symbol to the compiler, unlike <code>this</code>, for which the compiler could determine it's instance dependency.</p> <p>The key-point here is that C++ uses a model of <a href="http://books.google.de/books?id=yQU-NlmQb_UC&amp;lpg=PA146&amp;ots=EeiI89_BIV&amp;dq=vandevoorde%20two%20phase%20lookup&amp;pg=PA146#v=onepage&amp;q&amp;f=false" rel="noreferrer">two-phase-lookup</a>, where it does checking for non-dependent code in the first phase, and semantic checking for dependent code is done in phase two (and instantiation time) (this is also an often misunderstood or unknown concept, many C++ programmers assume that templates are not parsed at all until instantiation, but that's only myth coming from, ..., Microsoft C++).</p> <h2><br/></h2> <h1>Full instantiation of class templates</h1> <p>The definition of <code>Foo&lt;&gt;::let_me_stay()</code> worked because error checking was postponed to later, as for the <code>this</code> pointer, which is dependent. Except when you would have made use of</p> <blockquote> <p>explicit instantiations</p> </blockquote> <pre><code>cat &gt; foo.cc #include &lt;iostream&gt; template &lt;typename&gt; struct Foo { void let_me_stay() { this-&gt;is-&gt;valid-&gt;code. get-&gt;off-&gt;my-&gt;lawn; } void fun() { std::cout &lt;&lt; "fun()" &lt;&lt; std::endl; } }; template struct Foo&lt;void&gt;; int main () { Foo&lt;void&gt; foo; foo.fun(); } g++ foo.cc error: error: ‘struct Foo&lt;void&gt;’ has no member named ‘is’ </code></pre> <h2><br/></h2> <h1>Template definitions in different units of translation</h1> <p>When you explicitly instantiate, you instantiate explicitly. And make <em>all</em> symbols visible to the linker, which also means that the template definition may reside in different units of translation:</p> <pre><code>$ cat A.cc template &lt;typename&gt; struct Foo { void fun(); // Note: no definition }; int main () { Foo&lt;void&gt;().fun(); } $ cat B.cc #include &lt;iostream&gt; template &lt;typename&gt; struct Foo { void fun(); }; template &lt;typename T&gt; void Foo&lt;T&gt;::fun() { std::cout &lt;&lt; "fun!" &lt;&lt; std::endl; } // Note: definition with extern linkage template struct Foo&lt;void&gt;; // explicit instantiation upon void $ g++ A.cc B.cc $ ./a.out fun! </code></pre> <p>However, you must explicitly instantiate for all template arguments to be used, otherwise</p> <pre><code>$ cat A.cc template &lt;typename&gt; struct Foo { void fun(); // Note: no definition }; int main () { Foo&lt;float&gt;().fun(); } $ g++ A.cc B.cc undefined reference to `Foo&lt;float&gt;::fun()' </code></pre> <hr> <p>Small note about two-phase lookup: Whether a compiler actually implements two-phase lookup is not dictated by the standard. To be conformant, however, it should work as if it did (just like addition or multiplication do not necessarily have to be performed using addition or multiplication CPU instructions.</p>
23,215,311
Celery with RabbitMQ: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for'
<p>I'm running the <a href="http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html">First Steps with Celery Tutorial</a>.</p> <p>We define the following task:</p> <pre><code>from celery import Celery app = Celery('tasks', broker='amqp://guest@localhost//') @app.task def add(x, y): return x + y </code></pre> <p>Then call it:</p> <pre><code>&gt;&gt;&gt; from tasks import add &gt;&gt;&gt; add.delay(4, 4) </code></pre> <p>But I get the following error:</p> <pre><code>AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' </code></pre> <p>I'm running both the celery worker and the rabbit-mq server. Rather strangely, celery worker reports the task as succeeding:</p> <pre><code>[2014-04-22 19:12:03,608: INFO/MainProcess] Task test_celery.add[168c7d96-e41a-41c9-80f5-50b24dcaff73] succeeded in 0.000435483998444s: 19 </code></pre> <p>Why isn't this working?</p>
23,217,379
8
1
null
2014-04-22 09:15:30.53 UTC
9
2022-01-30 21:24:01.407 UTC
null
null
null
null
165,495
null
1
80
python|celery
41,776
<p>Just keep reading tutorial. It will be explained in <a href="http://celery.readthedocs.org/en/latest/getting-started/first-steps-with-celery.html#keeping-results" rel="noreferrer">Keep Results</a> chapter.</p> <p>To start Celery you need to provide just broker parameter, which is required to send messages about tasks. If you want to retrieve information about state and results returned by finished tasks you need to set backend parameter. You can find full list with description in <a href="http://celery.readthedocs.io/en/latest/userguide/configuration.html#std:setting-result_backend" rel="noreferrer">Configuration docs: CELERY_RESULT_BACKEND</a>.</p>
3,945,176
Talking to iFrame from ASP.NET code behind
<p>I found this really cool page that allows you to hook up facebook into your site: <a href="http://developers.facebook.com/docs/reference/plugins/like">See here</a> </p> <pre><code>&lt;iframe id="MyIframe" src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.EXAMPLE.com%2F&amp;amp;layout=button_count&amp;amp;show_faces=true&amp;amp;width=100&amp;amp;action=recommend&amp;amp;colorscheme=light&amp;amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"&gt;&lt;/iframe&gt; </code></pre> <p>I want to be able to call this iframe in my page (I am using ASP.NET) and I want to be able to set the visibilty based on a variable and most important I want to be able to change the src of the iframe based on a string that is build up by variables to change the "www.EXAMPLE.com" to another URL based on the location of the page.</p>
3,945,365
1
2
null
2010-10-15 18:50:48.89 UTC
1
2012-11-22 13:31:47.73 UTC
2010-10-15 19:12:07.823 UTC
null
33,584
null
33,584
null
1
8
c#|asp.net|vb.net|facebook|iframe
50,534
<p>Try adding the attribute runat="server". This should give you access to the tag via your codebehind, which will let you set other attributes according to your variable.:</p> <pre><code>&lt;iframe id="MyIframe" runat="server" src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.EXAMPLE.com%2F&amp;amp;layout=button_count&amp;amp;show_faces=true&amp;amp;width=100&amp;amp;action=recommend&amp;amp;colorscheme=light&amp;amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"&gt;&lt;/iframe&gt; </code></pre> <p>This will give you access to your iframe by name in code behind. You'll then be able to manipulate things by writing statements like:</p> <pre><code>MyIframe.Visible = true; </code></pre> <p>and</p> <pre><code>MyIframe.Attributes.Add("src", "http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.EXAMPLE.com%2F&amp;amp;layout=button_count&amp;amp;show_faces=true&amp;amp;width=100&amp;amp;action=recommend&amp;amp;colorscheme=light&amp;amp;height=21"); </code></pre>
28,359,730
Google Place API - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
<p>I am using Google Place API.</p> <p>What I want to get suggestion of place for type helping.</p> <p>So, what I have done is-</p> <pre><code>var Google_Places_API_KEY = "AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM"; //Get it from - https://code.google.com/apis/console/?noredirect#project:647731786600:access var language = "en"; //'en' for English, 'nl' for Nederland's Language var Auto_Complete_Link = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key="+Google_Places_API_KEY+"&amp;types=geocode&amp;language="+language+"&amp;input=Khu"; $.getJSON(Auto_Complete_Link , function(result) { $.each(result, function(i, field) { //$("div").append(field + " "); //alert(i + "=="+ field); console.error(i + "=="+ field); }); }); </code></pre> <p>So in what link I am requesting is -</p> <blockquote> <p><a href="https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM&amp;types=geocode&amp;language=en&amp;input=Khu" rel="noreferrer">https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM&amp;types=geocode&amp;language=en&amp;input=Khu</a></p> </blockquote> <p>And if I go to this link with browser, I can get output like it (please try to ck)-</p> <p><img src="https://i.stack.imgur.com/reAGm.jpg" alt="11"></p> <p>But if I try with jQuery's <strong>.getJSON</strong> or <strong>.ajax</strong>, I am getting my request blocked with this message-</p> <p><img src="https://i.stack.imgur.com/LvinM.jpg" alt="222">.</p> <p>SO the XMLHTTPRequest is blocked because of - </p> <blockquote> <p>No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.</p> </blockquote> <p>I have checked in <a href="https://stackoverflow.com/">StackOverflow</a> for this problem solution and go through <a href="https://stackoverflow.com/questions/20518524/no-access-control-allow-origin-header-is-present-on-the-requested-resource-or">here</a> and <a href="https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource">here</a>, but can't get my solution perfectly.</p> <p>Can anyone please enlighten me?</p>
28,360,045
8
2
null
2015-02-06 06:21:44.043 UTC
12
2019-12-24 06:31:03.81 UTC
2019-12-24 06:31:03.81 UTC
null
2,193,439
null
2,193,439
null
1
55
javascript|jquery|ajax|google-maps|google-places-api
120,950
<p>AJAX Requests are only possible if port, protocol and domain of sender and receiver are equal,if not might lead to CORS. CORS stands for Cross-origin resource sharing and has to be supported on the server side.</p> <blockquote> <p><strong>Solution</strong></p> </blockquote> <p><strong>JSONP</strong></p> <p>JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy.</p> <p>Something like this might help you mate.. :)</p> <pre><code>$.ajax({ url: Auto_Complete_Link, type: "GET", dataType: 'jsonp', cache: false, success: function(response){ alert(response); } }); </code></pre>
2,153,180
What is ?: in PHP 5.3?
<blockquote> <p><strong>Possible Duplicate:</strong> <a href="https://stackoverflow.com/questions/1080247">What are the PHP operators “?” and “:” called and what do they do?</a></p> </blockquote> <p>From <a href="http://twitto.org/" rel="noreferrer">http://twitto.org/</a></p> <pre><code>&lt;?PHP require __DIR__.'/c.php'; if (!is_callable($c = @$_GET['c'] ?: function() { echo 'Woah!'; })) throw new Exception('Error'); $c(); ?&gt; </code></pre> <p>Twitto uses several new features available as of PHP 5.3:</p> <ol> <li>The <strong>DIR</strong> constant</li> <li>The ?: operator</li> <li>Anonymous functions</li> </ol> <hr> <ol> <li><p>What does number 2 do with the <strong>?:</strong> in PHP 5.3?</p></li> <li><p>Also, what do they mean by anonymous functions? Wasn't that something that has existed for a while?</p></li> </ol>
2,153,189
3
7
null
2010-01-28 08:33:05.54 UTC
19
2015-12-14 18:11:20.597 UTC
2017-05-23 12:34:47.823 UTC
null
-1
null
143,030
null
1
85
php|php-5.3|ternary-operator|conditional-operator|language-construct
48,460
<p><code>?:</code> is a form of the conditional operator which was previously available only as:</p> <pre><code>expr ? val_if_true : val_if_false </code></pre> <p>In 5.3 it's possible to leave out the middle part, e.g. <code>expr ?: val_if_false</code> which is equivalent to:</p> <pre><code>expr ? expr : val_if_false </code></pre> <p>From the <a href="http://php.net/manual/en/language.operators.comparison.php" rel="noreferrer">manual</a>:</p> <blockquote> <p>Since PHP 5.3, it is possible to leave out the middle part of the conditional operator. Expression <code>expr1 ?: expr3</code> returns <code>expr1</code> if <code>expr1</code> evaluates to <code>TRUE</code>, and <code>expr3</code> otherwise.</p> </blockquote>
8,817,927
Ruby: divisible by 4
<p>This works fine, but I want to make it prettier - and accommodate all values that are divisible by 4:</p> <pre><code>if i==4 || i==8 || i==12 || i==16 || i==20 || i==24 || i==28 || i==32 # ... end </code></pre> <p>Any clever, short method to do this? </p>
8,817,942
3
1
null
2012-01-11 10:43:35.73 UTC
6
2019-02-18 15:18:58.12 UTC
2018-08-24 10:40:05.957 UTC
null
477,037
null
721,631
null
1
33
ruby|modulo
65,411
<p>Try this:</p> <pre><code>if i % 4 == 0 </code></pre> <p>This is called the "<a href="http://en.wikipedia.org/wiki/Modulo_operation" rel="noreferrer">modulo operator</a>".</p>
8,483,983
How to create the branch from specific commit in different branch
<p>I have made several commits in the master branch and then merged them to dev branch.</p> <p>I want to create a branch from a specific commit in dev branch, which was first committed in master branch.</p> <p>I used the commands:</p> <pre><code>git checkout dev git branch &lt;branch name&gt; &lt;commit id&gt; </code></pre> <p>However, this creates the branch from master branch, not the dev branch I expected. The commit id is same in master branch and dev branch. So, how can I distinguish same commit id in different branch?</p> <p>PS: I made an example in github here <a href="https://github.com/RolandXu/test_for_branch" rel="noreferrer">https://github.com/RolandXu/test_for_branch</a></p> <p>I used the commands:</p> <pre><code>git checkout dev git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8 </code></pre> <p>What I expect is that the test branch contains aa.txt bb.txt cc.txt. However, the test branch only contains aa.txt and cc.txt. It most likely created the branch from the master branch.</p>
8,491,176
5
1
null
2011-12-13 03:28:24.107 UTC
44
2019-05-11 06:15:08.617 UTC
2015-01-25 00:01:48.453 UTC
null
1,206
null
818,399
null
1
156
git|git-branch
209,370
<p>If you are using this form of the <code>branch</code> command (with start point), it does not matter where your <code>HEAD</code> is.</p> <p>What you are doing:</p> <pre><code>git checkout dev git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8 </code></pre> <ul> <li><p>First, you set your <code>HEAD</code> to the branch <code>dev</code>,</p></li> <li><p>Second, you start a new branch on commit <code>07aeec98</code>. There is no bb.txt at this commit (according to your github repo).</p></li> </ul> <p>If you want to start a new branch <em>at the location you have just checked out,</em> you can either run branch with no start point:</p> <pre><code>git branch test </code></pre> <p>or as other have answered, branch and checkout there in one operation:</p> <pre><code>git checkout -b test </code></pre> <hr> <p>I think that you might be confused by that fact that <code>07aeec98</code> is part of the branch <code>dev</code>. It is true that this commit is an ancestor of <code>dev</code>, its changes are needed to reach the latest commit in <code>dev</code>. However, they are other commits that are needed to reach the latest <code>dev</code>, and these are not necessarily in the history of <code>07aeec98</code>.</p> <p><code>8480e8ae</code> (where you added bb.txt) is for example not in the history of <code>07aeec98</code>. If you branch from <code>07aeec98</code>, you won't get the changes introduced by <code>8480e8ae</code>.</p> <p>In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.</p> <p>Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.</p> <hr> <p>If you want to <em>permanently</em> integrate new changes from master into your feature branches, you should merge <code>master</code> into them and go on. This will create merge commits in your feature branches, though.</p> <p>If you have not published your feature branches, you can also rebase them on the updated master: <code>git rebase master featureA</code>. Be prepared to solve possible conflicts.</p> <p>If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:</p> <ul> <li>base every new feature branch on a commit of master</li> <li>create a <code>dev</code> branch on a commit of master</li> <li>when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into <code>dev</code>.</li> </ul> <p>Do not commit into <code>dev</code> directly, use it only for merging other branches.</p> <p>For example, if you are working on feature A and B:</p> <pre><code>a---b---c---d---e---f---g -master \ \ \ \-x -featureB \ \-j---k -featureA </code></pre> <p>Merge branches into a <code>dev</code> branch to check if they work well with the new master:</p> <pre><code>a---b---c---d---e---f---g -master \ \ \ \ \ \--x'---k' -dev \ \ / / \ \-x---------- / -featureB \ / \-j---k--------------- -featureA </code></pre> <p>You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into <code>dev</code> regularly.</p> <pre><code>a---b---c---d---e---f---g---h---i----- -master \ \ \ \ \ \ \--x'---k'---i'---l' -dev \ \ / / / \ \-x---------- / / -featureB \ / / \-j---k-----------------l------ -featureA </code></pre> <p>When it is time to integrate the new features, merge the feature branches (not <code>dev</code>!) into master.</p>
27,266,901
Display JavaScript Object in HTML
<p>I have a object that looks like this:</p> <pre><code>var grocery_list = { "Banana": { category: "produce", price: 5.99 }, "Chocolate": { category: "candy", price: 2.75 }, "Wheat Bread": { category: "grains and breads", price: 2.99 } } </code></pre> <p>And I want to be able to display each item in the object in HTML like this:</p> <pre><code>&lt;div id="grocery_item" class="container"&gt; &lt;div class="item"&gt;Item Here&lt;/div&gt; &lt;div class="category"&gt;Category Here&lt;/div&gt; &lt;div class="price"&gt;Price Here&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I know how to loop through an Object in JS, but I'm not sure how to display those items in the DOM. I believe I could use the jQuery append function but I'm not sure how.</p> <p>Any help would be appreciated. thanks!</p>
27,267,319
5
3
null
2014-12-03 08:29:42.397 UTC
2
2021-07-27 22:07:49.247 UTC
2016-02-10 21:23:45.853 UTC
null
13,302
null
2,816,949
null
1
4
javascript|object|dom
40,416
<p>This is how you can do it using jQuery (as you mention you'd like to use jQuery first). But it's not the best way how to it. If you're open to learn better methods then check some of the MV* frameworks (AngularJS, Ember etc.). Anyway, here is just an example:</p> <pre><code>var grocery_list = { &quot;Banana&quot;: { category: &quot;produce&quot;, price: 5.99 }, &quot;Chocolate&quot;: { category: &quot;candy&quot;, price: 2.75 }, &quot;Wheat Bread&quot;: { category: &quot;grains and breads&quot;, price: 2.99 } } var wrapper = $('#wrapper'), container; for (var key in grocery_list){ container = $('&lt;div id=&quot;grocery_item&quot; class=&quot;container&quot;&gt;&lt;/div&gt;'); wrapper.append(container); container.append('&lt;div class=&quot;item&quot;&gt;' + key +'&lt;/div&gt;'); container.append('&lt;div class=&quot;category&quot;&gt;' + grocery_list[key].category +'&lt;/div&gt;'); container.append('&lt;div class=&quot;price&quot;&gt;' + grocery_list[key].price +'&lt;/div&gt;'); } </code></pre> <p>jsfiddle here: <a href="http://jsfiddle.net/5jhgbg9w/" rel="nofollow noreferrer">http://jsfiddle.net/5jhgbg9w/</a></p> <p><em>EDIT: Please, take this really as an example (which is OK since you're learning). As others pointed out - it's not the best method. Try to combine other examples, particularly the ones which do not compose HTML as a string. For easy tasks like this it's straightforward but the more code you would add, the messier the code becomes. I believe your &quot;learning evolution&quot; would get you there anyway :-) Cheers everyone</em></p> <p><strong>EDIT (2021):</strong> A lot of years have gone by since I answered this question. What about some more modern examples, just for fun? Without jQuery, just ES6:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const grocery_list = { "Banana": { category: "produce", price: 5.99 }, "Chocolate": { category: "candy", price: 2.75 }, "Wheat Bread": { category: "grains and breads", price: 2.99 } }; // since "grocery_list" is an object (not an array) we have do Object.keys() const generatedHtml = Object.keys(grocery_list).reduce((accum, currKey) =&gt; accum + `&lt;div class="grocery_item"&gt; &lt;div class="item"&gt;${currKey}&lt;/div&gt; &lt;div class="category"&gt;${grocery_list[currKey].category}&lt;/div&gt; &lt;div class="price"&gt;${grocery_list[currKey].price}&lt;/div&gt; &lt;/div&gt;`, ''); document.getElementById('container').innerHTML = generatedHtml;</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grocery_item{ padding: 5px; } .grocery_item:not(:last-child){ border-bottom: 1px solid #ccc; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
19,393,481
c# initialize a static list in a class
<p>What I'm trying to have is a 2D global list initialized with strings. If I only wanted a simple list I could just initialize the list with strings separated by a comma like this <br/></p> <pre class="lang-cs prettyprint-override"><code>public static readonly List&lt;string&gt; _architecturesName = new List&lt;string&gt;() {&quot;x86&quot;,&quot;x64&quot; }; </code></pre> <p>I have set up a static class <code>Globals</code>, in this class I'm adding a List based on another class <code>ArchitecturesClass</code> to be used as fields for the list similar to what was done <a href="https://stackoverflow.com/questions/665299/are-2-dimensional-lists-possible-in-c">here</a></p> <pre class="lang-cs prettyprint-override"><code>public class ArchecturesClass { public string Id { get; set; } public string Name { get; set; } } // test1 : public static readonly List&lt;ArchecturesClass&gt; ArchitectureList = new List&lt;ArchecturesClass&gt;() { &quot;2&quot;, &quot;9&quot;}; // test2 : public static readonly List&lt;ArchecturesClass&gt; ArchitectureList = new List&lt;ArchecturesClass&gt;() { architecturesId = &quot;2&quot;, architecturesName = &quot;3&quot; }; </code></pre> <p>The error on the strings is that the collection initialize has some invalid arguments and In the end, I want all classes in the project to be able to read something like Globals.ArchtecutreList.ID and a matching <code>Globals.ArchtecutreList.Name;</code> and I would like to initialize this in the global class without being in a method.</p>
19,393,506
1
1
null
2013-10-16 00:45:03.41 UTC
1
2022-06-03 17:17:16.68 UTC
2022-06-03 17:17:16.68 UTC
null
5,740,243
null
1,247,588
null
1
20
c#
107,024
<p>The syntax</p> <pre><code>new List&lt;ArchecturesClass&gt;() {architecturesId = "2", architecturesName = "3"}; </code></pre> <p>should probably be </p> <pre><code>new List&lt;ArchecturesClass&gt;() { new ArchecturesClass&gt;() { architecturesId = "2", architecturesName = "3"}}; </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx" rel="noreferrer">Collection initializers</a> expect you to provide instances of the type contained in your list.</p> <p>Your other attempt</p> <pre><code>public static readonly List&lt;ArchecturesClass&gt; ArchitectureList = new List&lt;ArchecturesClass&gt;() { "2", "9"}; </code></pre> <p>fails because "2" and "9" are strings, not instances of <code>ArchitecturesClass</code>.</p>
19,522,042
Invalid Image Path - No image found at the path. CFBundleIcons Xcode 5
<p>I'm trying to update my app for iOS 7 with Xcode 5.0.</p> <p>Everything works fine, but when I archive then validate I get these messages:</p> <p>Invalid Image Path - No image found at the path referenced under key <code>CFBundleIcons': 'APP-ICON-57'</code></p> <p>I've tried to remove and add the images, have manually edited my <code>info.plist</code>, renamed images, add <code>.png</code> to the key, etc. Nothing seems to work. Please help, I'm about one day into getting through this silly issue.</p>
19,522,327
14
1
null
2013-10-22 15:25:05.373 UTC
5
2021-03-04 18:51:00.617 UTC
2017-06-28 23:54:48.493 UTC
null
7,456,236
null
2,844,135
null
1
43
ios|xcode5
37,361
<p>Make sure that this image is a members of target you are building:</p> <p><img src="https://i.stack.imgur.com/f2rAM.jpg" alt="enter image description here"></p> <p>Also be aware that names are case sensitive.</p> <ol> <li>Click on the affected image in the Project Navigator</li> <li>In the utilities window, click the "Show the File Inspector" icon.</li> <li>Ensure the "Target Membership" app name has "v" next to it.</li> <li>Rebuild and archive.</li> </ol>
517,557
Meaning of (+) in SQL queries
<p>I've come across some SQL queries in Oracle that contain '(+)' and I have no idea what that means. Can someone explain its purpose or provide some examples of its use? Thanks</p>
517,567
4
3
null
2009-02-05 19:36:09.86 UTC
3
2020-06-10 14:01:21.113 UTC
null
null
null
Zabbala
54,789
null
1
32
sql|oracle
104,263
<p>It's Oracle's synonym for <code>OUTER JOIN</code>.</p> <pre><code>SELECT * FROM a, b WHERE b.id(+) = a.id </code></pre> <p>gives same result as</p> <pre><code>SELECT * FROM a LEFT OUTER JOIN b ON b.id = a.id </code></pre>
338,293
What are the differences between osql, isql, and sqlcmd?
<p>I am interested in using some kind of a command-line utility for SQL Server similar to Oracle's SQL*Plus. SQL Server seems to have several options: osql, isql, and sqlcmd. However, I am not quite certain which one to use.</p> <p>Do they all essentially do the same thing? Are there any situations where it is preferable to use one over the others?</p>
338,381
4
0
null
2008-12-03 18:45:47.69 UTC
10
2018-07-11 09:33:16.74 UTC
null
null
null
Ray Vega
4,872
null
1
34
sql-server|command-line
36,908
<p>Use sqlcmd-- it's the most fully featured product.</p> <ul> <li><strong>sqlcmd</strong>: The newest, fanciest command-line interface to SQL Server.</li> <li><strong>isql</strong> : The older, DB-Library (native SQL Server protocol) way of command-line communication with SQL Server.</li> <li><strong>osql</strong> : The older, ODBC-based way of command-line communication with SQL Server.</li> </ul> <p><strong>EDIT:</strong> Times have changed since I replied on this a couple of years ago. Nowadays, you can also use the <a href="http://technet.microsoft.com/en-us/library/cc281720.aspx" rel="noreferrer">invoke-sqlcmd</a> cmdlet in PowerShell. If you're used to PowerShell or plan to do any scripting of any sophistication, use this instead.</p>
257,936
.htaccess or .htpasswd equivalent on IIS?
<p>Does anyone know if there is an equivalent to .htaccess and .htpassword for IIS ? I am being asked to migrate an app to IIS that uses .htaccess to control access to sets of files in various URLs based on the contents of .htaccess files. </p> <p>I did a google search and didn't turn up anything conclusive. Is there a general approach or tool that I need to purchase that provides this capability ?</p>
1,833,832
4
0
null
2008-11-03 04:23:22.267 UTC
14
2015-03-04 14:15:34.683 UTC
2015-03-04 14:15:34.683 UTC
Greg Hewgill
324,216
MikeJ
10,676
null
1
51
iis|.htaccess
121,583
<p>For .htaccess rewrite: <a href="http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/" rel="noreferrer">http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/</a></p> <p>Or try aping .htaccess: <a href="http://www.helicontech.com/ape/" rel="noreferrer">http://www.helicontech.com/ape/</a></p>
720,429
How do I set the window / screen size in xna?
<p>How can I adjust the size of the window in XNA. </p> <p>Default it starts in a 800x600 resolution.</p>
720,436
4
0
null
2009-04-06 07:04:25.583 UTC
13
2014-04-21 20:24:55.017 UTC
2009-04-06 07:21:02.533 UTC
null
6,180
Sjors Miltenburg
null
null
1
55
xna|fullscreen
90,613
<p>I found out that you need to set the </p> <pre class="lang-cs prettyprint-override"><code>GraphicDevice.PreferredBackBufferHeight = height; GraphicDevice.PreferredBackBufferWidth = width; </code></pre> <p>When you do this in the constructor of the game class it works, but when you try do to this outside the constructor you also need to call </p> <pre class="lang-cs prettyprint-override"><code>GraphicsDevice.ApplyChanges(); </code></pre> <p>Furthermore to have fullscreen (which is not really working correctly while debugging) you can use</p> <pre class="lang-cs prettyprint-override"><code>if (!GraphicsDevice.IsFullScreen) GraphicsDevice.ToggleFullScreen(); </code></pre>
735,359
Update span tag value with JQuery
<p>I'm trying to update a span tag that is in a fieldset tag that is in a legend tag. The idea is to update the cost of a Software Item as components are selected. The code below works fine if I only have one software item (e.g. - Visual Studio 2008 Pro $2800), but if I add a second item in another fieldset, then when I try to update the span for that fieldset, it updates the span for the fieldset containing my Visual Studio Software. Any ideas what I'm doing wrong?</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; $(document).ready(function() { $("li").click(function() { var itemCost = 0; $("legend").each(function() { var SoftwareItem = $(this).text(); itemCost = GetItemCost(SoftwareItem); $("input:checked").each(function() { var Component = $(this).next("label").text(); itemCost += GetItemCost(Component); }); $("#ItemCostSpan").text("Item Cost = $ " + itemCost); }); function GetItemCost(text) { var start = 0; start = text.lastIndexOf("$"); var textCost = text.substring(start + 1); var itemCost = parseFloat(textCost); return itemCost; } }); }); &lt;/script&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;fieldset&gt; &lt;legend&gt;Visual Studio 2008 Pro $2800&lt;/legend&gt; &lt;ul class="AspNet-CheckBoxList-RepeatDirection-Vertical"&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBoxList1_0" type="checkbox" name="CheckBoxList1$0" value="first1" /&gt; &lt;label for="CheckBoxList1_0"&gt;Software Assurance $300.00&lt;/label&gt; &lt;/li&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBoxList1_1" type="checkbox" name="CheckBoxList1$1" value="second2" /&gt; &lt;label for="CheckBoxList1_1"&gt;Another Component $255.25&lt;/label&gt; &lt;/li&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBox1" type="checkbox" name="CheckBoxList1$1" value="second2" /&gt; &lt;label for="CheckBoxList1_1"&gt;A Second Component $15.25&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;span id="ItemCostSpan" style="background-color:White"&gt; &lt;/span&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;Visio 2008 Pro $415&lt;/legend&gt; &lt;ul class="AspNet-CheckBoxList-RepeatDirection-Vertical"&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBox2" type="checkbox" name="CheckBoxList1$0" value="first1" /&gt; &lt;label for="CheckBoxList1_0"&gt;Software Assurance $40.00&lt;/label&gt; &lt;/li&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBox3" type="checkbox" name="CheckBoxList1$1" value="second2" /&gt; &lt;label for="CheckBoxList1_1"&gt;Another Component $25.55&lt;/label&gt; &lt;/li&gt; &lt;li class="AspNet-CheckBoxList-Item"&gt; &lt;input id="CheckBox4" type="checkbox" name="CheckBoxList1$1" value="second2" /&gt; &lt;label for="CheckBoxList1_1"&gt;A Second Component $10.25&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;span id="ItemCostSpan" style="background-color:White"&gt;&lt;/span&gt; &lt;/fieldset&gt; &lt;span id="TotalCostSpan" style="background-color:White"&gt;&lt;/span&gt; &lt;/form&gt; </code></pre>
735,478
1
0
null
2009-04-09 18:21:24.267 UTC
3
2009-05-29 20:08:40.3 UTC
2009-04-09 18:42:04.577 UTC
null
89,054
null
89,054
null
1
17
jquery|html
100,565
<p>Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.</p> <pre><code> $("legend").each(function() { var SoftwareItem = $(this).text(); itemCost = GetItemCost(SoftwareItem); $("input:checked").each(function() { var Component = $(this).next("label").text(); itemCost += GetItemCost(Component); }); $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost); }); </code></pre>
57,385,125
Eslint does not recognize private field declaration using nodejs 12
<p>Eslint will not recognize private fields marked with # in class declarations, even though I'm using NodeJS version 12 (which supports them).</p> <p>I am running NodeJS v12.7.0. I have searched all DuckDuckGo and Google and I cannot find a plugin or option in eslint which will tell it to accept the private field notation (#). I have <code>emca</code> set to version <code>10</code>.</p> <pre class="lang-js prettyprint-override"><code>class MyClass { #foo = 'bar'; #bar = 'foo'; constructor(foo, bar) { this.#foo = foo; this.#bar = bar; } ... }; </code></pre> <p>When I run <code>eslint</code> on the above code, I get:</p> <p><code> 2:3 error Parsing error: Unexpected character '#'</code></p> <p>The project I'm working on does not use Babel, and I don't want to have to include it just to make private fields work. Any ideas how to make this work without having to resort to using Babel?</p> <p>(Nothing against Babel of course, it's just on this particular project I don't want it).</p>
69,926,705
5
0
null
2019-08-06 23:17:19.803 UTC
11
2021-11-11 19:29:58.673 UTC
2021-07-13 12:53:05.123 UTC
null
891,440
null
2,933,397
null
1
28
node.js|eslint|private|private-members
11,316
<h2>2021 Update: You do not need babel for this anymore!</h2> <p>You can simply update eslint to <code>v8.0.0</code> and above.</p> <p>See eslint release notes: <a href="https://eslint.org/blog/2021/10/eslint-v8.0.0-released#highlights" rel="noreferrer">https://eslint.org/blog/2021/10/eslint-v8.0.0-released#highlights</a></p> <p>Make sure this is in your <code>.eslintrc</code> file or similar:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;parserOptions&quot;: { &quot;ecmaVersion&quot;: 13 } } </code></pre> <p>You can also just use <code>latest</code> instead of specifically version 13.</p>
19,375,715
Parent div not expanding to children's height
<p>As you will see, I have a <code>div</code> (<code>#innerPageWrapper</code>) that wraps around the divs that contain the content. <code>#innerPageWrapper</code> also does act visually as a semi-transparent border in the layout.</p> <p>My problem is that <code>#innerPageWrapper</code> won't expand to fit the children inside, let alone expand to fill the rest of the page.</p> <p>This is the code for <code>#innerPageWrapper</code></p> <pre><code>#innerPageWrapper { width: 1100px; height: 100%; display: inline-block; padding: 0 50px 0 50px; background: rgba(0, 0, 0, 0.75) url(navShadow.png) repeat-x top; -webkit-border-top-left-radius: 20px; -webkit-border-top-right-radius: 20px; -moz-border-radius-topleft: 20px; -moz-border-radius-topright: 20px; border-top-left-radius: 20px; border-top-right-radius: 20px; } </code></pre> <p>I have tried many things (including using calc() for div heights) unsuccessfully. I want to avoid using jQuery.</p>
19,375,902
2
0
null
2013-10-15 07:40:50.93 UTC
9
2015-10-21 04:18:36.627 UTC
2013-10-15 11:48:46.547 UTC
null
2,131,371
null
2,131,371
null
1
27
css|html|height|expand
102,766
<p>Firstly, you are using <code>height:100%;</code> which <strong>in your case</strong> is wrong. For an explanation on why not to use <code>height:100%</code>, check <a href="http://webdesign.about.com/od/csstutorials/f/set-css-height-100-percent.htm" rel="noreferrer">this</a> article;</p> <blockquote> <p>To understand why, you need to understand how browsers interpret height and width. Web browsers calculate the total available width as a function of how wide the browser window is opened. If you don't set any width values on your documents, the browser will automatically flow the contents to fill the entire width of the window.</p> <p>But height is calculated differently. In fact, browsers don't evaluate height at all unless the content is so long that it goes outside of the view port (thus requiring scroll bars) or if the web designer sets an absolute height on an element on the page. Otherwise, the browser simply lets the content flow within the width of the view port until it comes to the end. The height is not calculated at all. The problem occurs when you set a percentage height on an element who's parent elements don't have heights set. In other words, the parent elements have a default height: auto;. You are, in effect, asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing.</p> </blockquote> <p>Secondly, to make the outer-div (in this case <em>#innerPageWrapper</em>) wrap around the child elements, you should use <code>overflow:hidden</code> on this wrapper.</p> <p>For this to successfully work, your child elements must <strong>not</strong> be <code>position:absolute</code> as you have for <em>#contentMain</em> and <em>#contentSidebar</em>, instead make these <em>floats</em> (<em>float:left</em> and <em>float:right</em>) and after the <em>#contentSidebar</em> div closes, add a <code>&lt;div style="clear:both"&gt;&lt;/div&gt;</code> to clear floats, allowing the parent to wrap around them perfectly.</p> <p>I have put the required CSS in <a href="http://pastebin.com/gv3q2tRx" rel="noreferrer">this</a> Pastebin, note that you must clear your floats using a div as I mentioned above.</p>
41,425,812
Laravel : Force the download of a string without having to create a file
<p>I'm generating a CSV, and I want Laravel to force its download, but <a href="https://laravel.com/docs/5.3/responses#file-downloads" rel="noreferrer">the documentation</a> only mentions I can download files that already exist on the server, and I want to do it without saving the data as a file.</p> <p>I managed to make this (which works), but I wanted to know if there was another, neater way.</p> <pre><code> $headers = [ 'Content-type' =&gt; 'text/csv', 'Content-Disposition' =&gt; 'attachment; filename="download.csv"', ]; return \Response::make($content, 200, $headers); </code></pre> <p>I also tried with a <a href="http://php.net/manual/en/class.spltempfileobject.php" rel="noreferrer">SplTempFileObject()</a>, but I got the following error : <code>The file "php://temp" does not exist</code></p> <pre><code> $tmpFile = new \SplTempFileObject(); $tmpFile-&gt;fwrite($content); return response()-&gt;download($tmpFile); </code></pre>
41,434,119
3
0
null
2017-01-02 11:17:02.11 UTC
6
2021-06-25 06:44:09.003 UTC
2017-01-02 21:50:20.237 UTC
null
4,834,168
null
4,834,168
null
1
47
laravel
28,731
<p>Make a <a href="https://laravel.com/docs/5.3/responses#response-macros" rel="noreferrer">response macro</a> for a cleaner content-disposition / laravel approach</p> <p>Add the following to your <code>App\Providers\AppServiceProvider</code> boot method</p> <pre><code>\Response::macro('attachment', function ($content) { $headers = [ 'Content-type' =&gt; 'text/csv', 'Content-Disposition' =&gt; 'attachment; filename="download.csv"', ]; return \Response::make($content, 200, $headers); }); </code></pre> <p>then in your controller or routes you can return the following</p> <pre><code>return response()-&gt;attachment($content); </code></pre>
30,798,329
Xcode 7 run on Mac OSX 10.10 Yosemite
<p>Am I missing something or Xcode 7 should run only on new(beta) OSX 10.11 El Capitan?</p> <p>I downloaded beta and after some code changes to comply with Swift 2.0 my project compiles and runs fine under OSX 10.10.3. Am I missing something or Apple changed the game somehow?</p>
30,798,434
2
0
null
2015-06-12 08:10:00.553 UTC
1
2016-12-13 09:01:01.343 UTC
null
null
null
null
1,472,337
null
1
13
swift|osx-yosemite|swift2|xcode7|osx-elcapitan
42,601
<h2>Edit:</h2> <p>Xcode 7 runs on OS X 10.10.4 </p> <h2>Old:</h2> <p>Yup Xcode 7 beta runs on OS X 10.10</p> <p>As stated in the release notes below </p> <blockquote> <p>About Xcode 7 beta </p> <p>Supported Configurations</p> <p>Xcode 7 beta requires a Mac running OS X 10.10. </p> <p>Xcode 7 beta includes SDKs for watchOS 2.0, iOS 9 and OS X version 10.11. To develop apps targeting prior versions of OS X or iOS, see the section “About SDKs and the Simulator” in What's New in Xcode available on developer.apple.com or from the Help > What's New in Xcode command when running Xcode.</p> </blockquote>
20,061,997
R - test if first occurrence of string1 is followed by string2
<p>I have an R string, with the format</p> <pre><code>s = `"[some letters and numbers]_[a number]_[more numbers, letters, punctuation, etc, anything]"` </code></pre> <p>I simply want a way of checking if <code>s</code> contains <code>"_2"</code> in the first position. In other words, after the first <code>_</code> symbol, is the single number a "2"? How do I do this in R?</p> <p>I'm assuming I need some complicated regex expresion?</p> <p>Examples:</p> <pre><code>39820432_2_349802j_32hfh = TRUE </code></pre> <p><code>43lda821_9_428fj_2f = FALSE</code> (notice there is a <code>_2</code> there, but not in the right spot)</p>
20,062,067
2
0
null
2013-11-19 02:29:42.82 UTC
8
2016-10-15 18:00:17.553 UTC
2016-10-15 18:00:17.553 UTC
null
184,212
null
825,630
null
1
52
r|contains
117,071
<pre><code>&gt; grepl("^[^_]+_1",s) [1] FALSE &gt; grepl("^[^_]+_2",s) [1] TRUE </code></pre> <p>basically, look for everything at the beginning except <code>_</code>, and then the <code>_2</code>.</p> <p>+1 to @Ananda_Mahto for suggesting <code>grepl</code> instead of <code>grep</code>.</p>
30,020,892
TagHelper for passing route values as part of a link
<p>When specifying <code>asp-controller</code> and <code>asp-action</code> on a link, what's the syntax for also passing an id attribute?</p> <p>E.g. If I wanted to link to the edit URL for a given object, the required URL would be <code>/user/edit/5</code> for example.</p> <p>Is there a method to achieve this using TagHelpers, or do we still have to fall back to <code>@Html.ActionLink()</code>?</p>
30,041,366
4
0
null
2015-05-04 00:14:12.69 UTC
11
2020-08-24 07:47:13.01 UTC
2015-05-20 11:58:58.067 UTC
null
1,833,612
null
65,890
null
1
73
asp.net-core|asp.net-core-mvc|tag-helpers
67,004
<p>You can use the attribute prefix <code>asp-route-</code> to prefix your route variable names.</p> <p>Example: <code>&lt;a asp-action="Edit" asp-route-id="10" asp-route-foo="bar"&gt;Edit&lt;/a&gt;</code></p>
36,787,603
What exactly is __weakref__ in Python?
<p>Surprisingly, there's no explicit documentation for <code>__weakref__</code>. Weak references are explained <a href="https://docs.python.org/2/library/weakref.html">here</a>. <code>__weakref__</code> is also shortly mentioned in the documentation of <code>__slots__</code>. But I could not find anything about <code>__weakref__</code> itself.</p> <p>What exactly is <code>__weakref__</code>? - Is it just a member acting as a flag: If present, the object may be weakly-referenced? - Or is it a function/variable that can be overridden/assigned to get a desired behavior? How?</p>
36,789,779
3
0
null
2016-04-22 07:28:38.66 UTC
34
2021-07-30 16:09:35.973 UTC
2016-10-23 17:48:48.18 UTC
null
2,867,928
null
2,109,064
null
1
95
python|python-3.x|python-internals
27,146
<p><code>__weakref__</code> is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of <a href="https://docs.python.org/3/library/weakref.html" rel="noreferrer"><code>weakref</code></a> (or sometimes <code>weakproxy</code>) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.</p> <p>It's just an implementation detail that allows the garbage collector to inform weak references that its referent has been collected, and to not allow access to its underlying pointer anymore.</p> <p>The weak reference can't rely on checking the reference count of the object it refers to. This is because that memory may have been reclaimed and is now being used by another object. Best case scenario the VM will crash, worst case the weak reference will allow access to an object it wasn't originally referring to. This is why the garbage collector must inform the weak reference its referent is no longer valid.</p> <p>See <a href="https://github.com/python/cpython/blob/master/Include/weakrefobject.h" rel="noreferrer">weakrefobject.h</a> for the structure and C-API for this object. And the implementation detail is <a href="https://github.com/python/cpython/blob/master/Objects/weakrefobject.c" rel="noreferrer">here</a></p>
20,731,487
phpmyadmin.pma_table_uiprefs doesn't exist
<p>I searched the internet but cannot find anything related to this specific error/table. It pops up when I try to view a table in phpMyAdmin. I am logged in as root and the installation (under ubuntu 13.10) of phpMyAdmin is fresh and untouched so far.</p> <p>Here is the whole message:</p> <pre><code>SELECT `prefs` FROM `phpmyadmin`.`pma_table_uiprefs` WHERE `username` = 'root' AND `db_name` = 'symfony' AND `table_name` = 'users' MySQL reports: #1146 - Table 'phpmyadmin.pma_table_uiprefs' doesn't exist </code></pre> <p>Is the installation just broken or am I missing something?</p>
20,731,569
23
0
null
2013-12-22 16:26:56.907 UTC
24
2022-06-20 09:43:14.073 UTC
2014-10-24 10:27:07.123 UTC
null
2,560,696
null
2,560,696
null
1
59
mysql|phpmyadmin
158,484
<p>You are missing at least one of the phpMyAdmin configuration storage tables, or the configured table name does not match the actual table name. </p> <p>See <a href="http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage">http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage</a>.</p> <p>A quick summary of what to do can be:</p> <ol> <li>On the shell: <code>locate create_tables.sql</code>.</li> <li>import <code>/usr/share/doc/phpmyadmin/examples/create_tables.sql.gz</code> using phpMyAdmin.</li> <li>open <code>/etc/phpmyadmin/config.inc.php</code> and edit lines 81-92: change <code>pma_bookmark</code> to <code>pma__bookmark</code> and so on.</li> </ol>
30,425,912
Is it safe to rename Django migrations file?
<p>Since Django 1.8 the <code>makemigrations</code> command has a <code>--name, -n</code> <a href="https://docs.djangoproject.com/en/1.8/ref/django-admin/#django-admin-option---name" rel="noreferrer">option</a> to specify custom name for the created migrations file. </p> <p>I'd like to know whether it's safe in older versions of Django to create the migrations file with the automatically generated name and then rename the file manually. It seems to work as expected. Are there any potential risks?</p>
30,427,833
2
0
null
2015-05-24 16:46:50.733 UTC
5
2017-05-10 09:51:15.38 UTC
null
null
null
null
4,408,382
null
1
46
django|django-migrations
11,582
<p>This works, with a minor caveat: Django will no longer know that the renamed migration is applied.</p> <p>So the steps to renaming a migration are:</p> <ol> <li>Rename the file.</li> <li>Repoint any dependencies to the new file.</li> <li>If the renamed migration was already applied, apply it again using <code>--fake</code>. </li> </ol> <p>If it's a brand new migration, 2 and 3 won't apply, and it's perfectly fine to rename them. </p>
49,709,252
No PostCSS config found
<p>I am trying to learn reactjs according to a tutorial. Meanwhile the tutorial instructs to use webpack for compiling stylesheets and JS assets. I am stuck in an error where the stylesheets cannot get compiled and throws following error while compiling the file using webpack. It displays following error : </p> <pre><code> ERROR in ./src/stylesheets/hello.css (./node_modules/css-loader!./node_modules/postcss-loader/lib!./src/stylesheets/hello.css) Module build failed: Error: No PostCSS Config found in: E:\developer\start\src\stylesheets at E:\developer\start\node_modules\postcss-load-config\index.js:51:26 at &lt;anonymous&gt; @ ./src/stylesheets/hello.css 2:14-124 @ ./src/lib.js @ ./src/index.js @ multi (webpack)-dev-server/client?http://localhost:4000 ./src/index.js </code></pre> <p>I have done everything according to the tutorial but somehow this error persists and couldn't solve this as I am very new to this. My webpack configuration file webpack.config.js is as follows:</p> <pre><code> module: { rules: [ { test: /\.css$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "postcss-loader" // compiles Sass to CSS }] }, { test: /\.scss$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "postcss-loader" // compiles Sass to CSS }, { loader: "sass-loader" // compiles Sass to CSS }] } ] } }; </code></pre>
49,709,493
5
0
null
2018-04-07 16:03:39.41 UTC
5
2021-07-29 12:05:12.813 UTC
null
null
null
null
5,350,097
null
1
54
webpack|postcss|postcss-loader|webpack.config.js
53,430
<p>Made a new file in the root directory named <code>postcss.config.js</code> and added </p> <p><code>module.exports = {};</code></p> <p>Found this on the following post:</p> <p><a href="https://stackoverflow.com/a/41758053/5350097">https://stackoverflow.com/a/41758053/5350097</a></p>
45,058,893
CSS reveal from corner animation
<p>I am trying to achieve an animation effect as follows:</p> <p>When a banner is shown, the bottom right corner of the next banner should be visible. When you click on this corner, it should hide the current banner and reveal the next one.</p> <p>My current markup is as follows:</p> <pre><code>&lt;div class="banners"&gt; &lt;div class="image active" style="background-color: red;"&gt; &lt;div class="corner"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="image" style="background-color: blue;"&gt; &lt;div class="corner"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS as follows: Notice I used <code>clip-path</code> to create the corner:</p> <pre><code>.banners { width: 800px; height: 600px; } .image { width: 100%; height: 100%; position: absolute; left: 0; top: 0; } .image.active { z-index: 1; clip-path: polygon(100% 0, 100% 65%, 60% 100%, 0 100%, 0 0); } .corner { width: 50%; height: 50%; position: absolute; right: 0; bottom: 0; } </code></pre> <p>JS:</p> <pre><code>$(document).ready(function () { $('.corner').click(function() { $('.image.active').removeClass('active'); $(this).parent().addClass('active'); }); }); </code></pre> <p>Here is a JSFiddle of all the above code: <a href="https://jsfiddle.net/cqqxjjgu/" rel="nofollow noreferrer">https://jsfiddle.net/cqqxjjgu/</a></p> <p>One immediate issue with this is that because I'm using <code>z-index</code> to specify that the current 'active' banner should have precedence, when remove the <code>active</code> class it just displays the next banner immediately, so ideally the <code>z-index</code> should only be changed once the animation has completed.</p> <p>Does anyone have anyt idea how I can achieive this? Ideally I need a cross browser solution (not too fussed about IE &lt; 10).</p>
45,065,095
5
0
null
2017-07-12 13:22:00.07 UTC
10
2017-08-18 10:05:25.867 UTC
2017-08-18 10:05:25.867 UTC
null
372,630
null
372,630
null
1
26
javascript|jquery|css|css-animations
4,798
<p>A simple example accomplishing this effect with no javascript:<br> <a href="https://jsfiddle.net/freer4/j2159b1e/2/" rel="noreferrer">https://jsfiddle.net/freer4/j2159b1e/2/</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-css lang-css prettyprint-override"><code>html, body{ height:100%; width:100%; margin:0; padding:0; } .banners { position:relative; background:#000; width: 100%; height: 100%; overflow:hidden; } .banners input{ display:none; } .slide1{ background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT5T6nwVYWsbzLcLF-JNxnGXFFFwkZMBcCMbaqeTevuldkxHg0N); } .slide2{ background-image:url(http://www.rd.com/wp-content/uploads/sites/2/2016/02/06-train-cat-shake-hands.jpg); } .slide3{ background-image:url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTKr6YlGNsqgJzvgBBkq1648_HsuDizVn_ZXC6iQp9kjXFzLvs1BA); } .image { display:block; height:100%; width:100%; position: absolute; overflow:hidden; z-index:1; text-align:center; background-position:0 0; background-size:cover; transition:z-index 1s step-end; clip-path: polygon(100% 0, 100% 100%, 100% 100%, 0 100%, 0 0); animation-duration: 2s; animation-name: clipout; } input:checked + .image{ z-index:3; transition:z-index 1s step-end; clip-path: polygon(100% 0, 100% 50%, 50% 100%, 0 100%, 0 0); animation-duration: 2.2s; animation-name: clipin; cursor:default; } .image:nth-child(2), input:checked + * + * + .image{ z-index:2; cursor:pointer; } .content{ color:#FFF; display:inline-block; vertical-align:middle; font-family:arial; text-transform:uppercase; font-size:24px; opacity:0; transition:0s opacity 1s; } input:checked + .image .content{ opacity:1; transition:0.8s opacity 0.8s; } .spanner{ vertical-align:middle; width:0; height:100%; display:inline-block; } @keyframes clipout { from { clip-path: polygon(100% 0, 100% 50%, 50% 100%, 0 100%, 0 0); } 50% { clip-path: polygon(100% 0, 100% -100%, -100% 100%, 0 100%, 0 0); } 51% { clip-path: polygon(100% 0, 100% 100%, 100% 100%, 0 100%, 0 0); } to { clip-path: polygon(100% 0, 100% 100%, 100% 100%, 0 100%, 0 0); } } @keyframes clipin{ from { clip-path: polygon(100% 0, 100% 100%, 100% 100%, 0 100%, 0 0); } 50% { clip-path: polygon(100% 0, 100% 100%, 100% 100%, 0 100%, 0 0); } to { clip-path: polygon(100% 0, 100% 50%, 50% 100%, 0 100%, 0 0); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="banners"&gt; &lt;input type="radio" id="slide1" name="slides" checked="checked" /&gt; &lt;label class="image slide1" for="slide1"&gt; &lt;div class="content"&gt; Slide 1 &lt;/div&gt; &lt;div class="spanner"&gt;&lt;/div&gt; &lt;/label&gt; &lt;input type="radio" id="slide2" name="slides" /&gt; &lt;label class="image slide2" for="slide2"&gt; &lt;div class="content"&gt; Slide 2 &lt;/div&gt; &lt;div class="spanner"&gt;&lt;/div&gt; &lt;/label&gt; &lt;input type="radio" id="slide3" name="slides" /&gt; &lt;label class="image slide3" for="slide3"&gt; &lt;div class="content"&gt; Slide 3 &lt;/div&gt; &lt;div class="spanner"&gt;&lt;/div&gt; &lt;/label&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Basically, just use keyframes to animate the clip path. Get fancy with the z-indexes and some sibling selectors. </p>
39,401,504
javascript/react dynamic height textarea (stop at a max)
<p>What I'm trying to achieve is a textarea that starts out as a single line but will grow up to 4 lines and at that point start to scroll if the user continues to type. I have a partial solution kinda working, it grows and then stops when it hits the max, but if you delete text it doesn't shrink like I want it to.</p> <p>This is what I have so far.</p> <pre><code>export class foo extends React.Component { constructor(props) { super(props); this.state = { textareaHeight: 38 }; } handleKeyUp(evt) { // Max: 75px Min: 38px let newHeight = Math.max(Math.min(evt.target.scrollHeight + 2, 75), 38); if (newHeight !== this.state.textareaHeight) { this.setState({ textareaHeight: newHeight }); } } render() { let textareaStyle = { height: this.state.textareaHeight }; return ( &lt;div&gt; &lt;textarea onKeyUp={this.handleKeyUp.bind(this)} style={textareaStyle}/&gt; &lt;/div&gt; ); } } </code></pre> <p>Obviously the problem is <code>scrollHeight</code> doesn't shrink back down when <code>height</code> is set to something larger. Any suggestion for how I might be able to fix this so it will also shrink back down if text is deleted? </p>
39,405,379
9
0
null
2016-09-08 23:14:26.67 UTC
8
2022-03-11 14:31:15.31 UTC
null
null
null
null
1,024,157
null
1
23
javascript|html|css|reactjs
57,025
<p>you can use <a href="https://github.com/jackmoore/autosize" rel="noreferrer">autosize</a> for that </p> <p><a href="https://codesandbox.io/s/l7y53n0k0z" rel="noreferrer">LIVE DEMO</a></p> <pre><code>import React, { Component } from 'react'; import autosize from 'autosize'; class App extends Component { componentDidMount(){ this.textarea.focus(); autosize(this.textarea); } render(){ const style = { maxHeight:'75px', minHeight:'38px', resize:'none', padding:'9px', boxSizing:'border-box', fontSize:'15px'}; return ( &lt;div&gt;Textarea autosize &lt;br/&gt;&lt;br/&gt; &lt;textarea style={style} ref={c=&gt;this.textarea=c} placeholder="type some text" rows={1} defaultValue=""/&gt; &lt;/div&gt; ); } } </code></pre> <p>or if you prefer react modules <a href="https://github.com/andreypopp/react-textarea-autosize" rel="noreferrer">https://github.com/andreypopp/react-textarea-autosize</a></p>
39,168,252
Using ?selectableItemBackground with a white background color
<p>I've always been using <code>android:background="?selectableItemBackground"</code> for a ripple effect when a view (a <code>LinearLayout</code> for example) is clicked. I think I read somewhere that this is backwards compatible to API 14.</p> <p>However, I've found that I need to use this ripple effect but with a white background. Specifically, I have a layout for a list item that will be displayed on the default color background (I'm extending from <code>Theme.AppCompat.Light.NoActionBar</code>), so I want the list item to stand out from this background by coloring the list item plain white (<code>#FFFFFF</code>).</p> <p>Here is the list item layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="?selectableItemBackground" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; ... &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:paddingLeft="@dimen/mdu_keyline_1" android:paddingRight="@dimen/mdu_keyline_1" android:paddingTop="@dimen/mdu_padding_normal" android:paddingBottom="@dimen/mdu_padding_normal"&gt; ... &lt;/LinearLayout&gt; &lt;/FrameLayout&gt; </code></pre> <p>The above produces the ripple effect without the white background.</p> <p>If I try:</p> <pre><code>&lt;FrameLayout ... android:background="@color/white"&gt; </code></pre> <p>This obviously produces a white background but without the ripple effect.</p> <p>I also tried something else - and this produced a result closest to what I am looking for:</p> <pre><code>&lt;FrameLayout ... android:background="@color/white"&gt; ... &lt;LinearLayout ... android:background="?selectableItemBackground"&gt; </code></pre> <p>The above gave me the white background with a ripple effect. <em>However</em>, the ripple always seems to start from the center regardless of which part of the item I click.</p> <p>Here are some screenshots showing the current result (ignore the shadow at the top of the list items - this is the shadow from the <code>AppBarLayout</code> and <code>Toolbar</code> I am using).</p> <p><a href="https://i.stack.imgur.com/sXKfG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sXKfG.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/ASwgw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ASwgw.png" alt="enter image description here"></a></p> <p>How could I achieve the desired effect?</p>
39,168,474
4
0
null
2016-08-26 14:06:32.79 UTC
5
2019-07-01 15:52:56.737 UTC
null
null
null
null
4,230,345
null
1
49
android|android-styles
27,861
<p>You can use the foreground of your FrameLayout : </p> <pre><code>&lt;FrameLayout ... android:background="@android:color/white" android:foreground="?attr/selectableItemBackground"&gt; </code></pre>
22,054,264
partial view was not found or no view engine supports the searched locations
<p>I have following controller code:</p> <pre><code>public MyController:Controller { public ActionResult Index() { return View(); } [ChildActionOnly] public ActionResult MyPartialViewAction() { return PartialView("~/Views/Shared/MyCustomFolder/_MyPartialView",PartialViewModel); } } </code></pre> <p>and my Index view has the following code :</p> <pre><code>@HTML.Action("MyPartialViewAction") </code></pre> <p>When I run the Web app I get HttpException with InnerExceptionMessage as :</p> <blockquote> <p>InnerException {"The partial view '~/Views/Shared/MyCustomFolder/_MyPartialView' was not found or no view engine supports the searched locations. The following locations were searched:\r\n~~/Views/Shared/MyCustomFolder/_MyPartialView"} System.Exception {System.InvalidOperationException}</p> </blockquote> <p>What I have tried till now :</p> <ul> <li><p>Tried moving <code>_MyPartialView</code> from <code>~/Views/Shared/MyCustomFolder</code> to <code>~/Views/Shared/</code> and <code>~/Views/MyControllerFolder</code> but still error exists</p></li> <li><p>Tried changing my Index View code to <code>@HTML.RenderAction()</code> but no luck.</p></li> </ul> <p>Any inputs on where I'm going wrong ?</p> <p>Thanks</p>
22,054,313
6
0
null
2014-02-26 21:57:40.77 UTC
3
2020-02-19 07:14:05.367 UTC
2018-04-12 14:43:22.8 UTC
null
4,429,666
null
2,614,378
null
1
47
asp.net-mvc|asp.net-mvc-3|razor
92,713
<p>You need to add the .cshtml extension to the view name:</p> <pre><code>return PartialView("~/Views/Shared/MyCustomFolder/_MyPartialView.cshtml",PartialViewModel); </code></pre>
41,204,932
Error message "python-pylint 'C0103:Invalid constant name"
<p>I'm confused about the error(s) in this photo:</p> <p><a href="https://i.stack.imgur.com/UVB1s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UVB1s.png" alt="Enter image description here" /></a></p> <p>I don't know how to fix them. My program is a Python-<a href="https://en.wikipedia.org/wiki/Flask_%28web_framework%29" rel="nofollow noreferrer">Flask</a> web frame. When I use Visual Studio Code to debug my program, Pylint shows these errors. I know this problem doesn't matter, but it makes me annoyed. How can I fix it?</p> <pre><code># -*- coding: utf-8 -*- import sys from flask import Flask from flask_bootstrap import Bootstrap from flask_moment import Moment #from flask_wtf import Form #from wtforms import StringField, SubmitField #from wtforms.validators import Required from flask_sqlalchemy import SQLAlchemy reload(sys) sys.setdefaultencoding('utf-8') app = Flask(__name__) app.config['SECRET_KEY'] = 'hard to guess string' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test?' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True bootstrap = Bootstrap(app) moment = Moment(app) db = SQLAlchemy(app) if __name__ == '__main__': db.create_all() app.run() </code></pre>
41,217,309
5
0
null
2016-12-18 02:27:53.93 UTC
7
2021-03-13 09:47:00.857 UTC
2021-01-22 12:13:19.693 UTC
null
63,550
null
7,311,772
null
1
46
python|pylint
53,129
<p>As explained by Kundor, <a href="https://www.python.org/dev/peps/pep-0008/#constants" rel="nofollow noreferrer">PEP 8</a> states that:</p> <blockquote> <p>Constants are usually defined on a module level and written in all capital letters with underscores separating words.</p> </blockquote> <p>The point is that &quot;constants&quot; in Python don't really exist. Pylint, as per PEP 8, expects module level variables to be &quot;constants.&quot;</p> <p>That being said you've several options:</p> <ul> <li><p>you don't want this &quot;constant&quot; thing, then change Pylint's <code>const-rgx</code> regular expression to be the same as e.g. <code>variable-rgx</code>,</p> </li> <li><p>you may deactivate those warnings for this file, or even locally in the file, using <code># pylint: disable=invalid-name</code>,</p> </li> <li><p>avoid module level variables, by wrapping them into a function.</p> </li> </ul> <p>In your case, I would go with the third option, by creating a <code>build_app</code> function or something similar. That would return the application (and maybe the 'db' object as well, but you have several choices there). Then you could add a salt of the second option to get something like:</p> <p><code>app = build_app() # pylint: disable=invalid-name</code></p>
40,200,070
What does axis = 0 do in Numpy's sum function?
<p>I am learning Python, and have encountered <code>numpy.sum</code>. It has an optional parameter <code>axis</code>. This parameter is used to get either column-wise summation or row-wise summation. When <code>axis = 0</code> we imply to sum it over columns only. For example,</p> <pre><code>a = np.array([[1, 2, 3], [4, 5, 6]]) np.sum(a, axis = 0) </code></pre> <p>This snippet of code produces output: <code>array([5, 7, 9])</code>, fine. But if I do:</p> <pre><code>a = np.array([1, 2, 3]) np.sum(a, axis = 0) </code></pre> <p>I get result: <code>6</code>, why is that? Shouldn't I get <code>array([1, 2, 3])</code>?</p>
40,200,131
7
2
null
2016-10-23 06:03:54.783 UTC
15
2022-09-15 09:25:41.477 UTC
2019-04-18 20:35:49.793 UTC
null
3,924,118
null
4,933,403
null
1
40
python|arrays|numpy
81,609
<p>All that is going on is that numpy is summing across the first (0th) and only axis. Consider the following:</p> <pre><code>In [2]: a = np.array([1, 2, 3]) In [3]: a.shape Out[3]: (3,) In [4]: len(a.shape) # number of dimensions Out[4]: 1 In [5]: a1 = a.reshape(3,1) In [6]: a2 = a.reshape(1,3) In [7]: a1 Out[7]: array([[1], [2], [3]]) In [8]: a2 Out[8]: array([[1, 2, 3]]) In [9]: a1.sum(axis=1) Out[9]: array([1, 2, 3]) In [10]: a1.sum(axis=0) Out[10]: array([6]) In [11]: a2.sum(axis=1) Out[11]: array([6]) In [12]: a2.sum(axis=0) Out[12]: array([1, 2, 3]) </code></pre> <p>So, to be more explicit:</p> <pre><code>In [15]: a1.shape Out[15]: (3, 1) </code></pre> <p><code>a1</code> is 2-dimensional, the "long" axis being the first.</p> <pre><code>In [16]: a1[:,0] # give me everything in the first axis, and the first part of the second Out[16]: array([1, 2, 3]) </code></pre> <p>Now, sum along the first axis:</p> <pre><code>In [17]: a1.sum(axis=0) Out[17]: array([6]) </code></pre> <p>Now, consider a less trivial two-dimensional case:</p> <pre><code>In [20]: b = np.array([[1,2,3],[4,5,6]]) In [21]: b Out[21]: array([[1, 2, 3], [4, 5, 6]]) In [22]: b.shape Out[22]: (2, 3) </code></pre> <p>The first axis is the "rows". Sum <em>along</em> the rows:</p> <pre><code>In [23]: b.sum(axis=0) Out[23]: array([5, 7, 9]) </code></pre> <p>The second axis are the "columns". Sum <em>along</em> the columns:</p> <pre><code>In [24]: b.sum(axis=1) Out[24]: array([ 6, 15]) </code></pre>
22,262,344
Error package `com.google.android.gms...` doesn't exist
<p>I am new to Android development. I am learning to use Parse.com backend service and get stuck early on. </p> <p>I am following <a href="https://parse.com/tutorials/anywall-android">tutorial</a> to create application that uses <code>Google Maps Android API v2</code>. What I've done :</p> <ol> <li>download <a href="https://github.com/ParsePlatform/AnyWall/zipball/master">sample project</a> from parse</li> <li>Import <code>AnyWall-android\Anywall</code> folder from downloaded project to Android Studio</li> <li>Rebuild project</li> </ol> <p>Then I get a bunch of errors here :</p> <pre><code>import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap.CancelableCallback; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; </code></pre> <p><code>common</code>, <code>location</code>, and <code>maps</code> highlighted red. The question is how to resolve these errors? </p> <p>I appreciate any kind of help or direction (What should I check? Is it about missing library? If it is, what library should I add and where to get it?)</p>
27,436,350
7
1
null
2014-03-07 22:59:27.087 UTC
6
2022-06-30 11:14:13.253 UTC
null
null
null
null
2,998,271
null
1
33
android|android-studio|parse-platform|google-maps-android-api-2
100,520
<p><a href="https://stackoverflow.com/questions/16636300/cant-find-the-class-com-google-android-gms-location-locationclient-android">Can&#39;t find the class com.google.android.gms.location.LocationClient (android)</a></p> <p>There is some problem with the last GPS lib. You have to use an older version than the latest(6.+). Try with an older version. I didn't see anything inside the doc deprecated or missing about the LocationClient.class... </p> <p>compile 'com.google.android.gms:play-services:5.+'</p>
23,492,043
Change default timeout for mocha
<p>If we have a unit test file my-spec.js and running with mocha: </p> <pre><code>mocha my-spec.js </code></pre> <p>The default timeout will be 2000 ms. It can be overwritten for partial test with a command line parameter: </p> <pre><code>mocha my-spec.js --timeout 5000 </code></pre> <p>Is it possible to change the default timeout globally for all tests? i.e. the default timeout value will be different from 2000 ms when you call:</p> <pre><code>mocha my-spec.js </code></pre>
23,492,442
4
1
null
2014-05-06 10:23:17.667 UTC
21
2022-02-01 07:41:16.03 UTC
2019-06-21 21:40:00.197 UTC
null
51,242
null
291,253
null
1
214
javascript|unit-testing|mocha.js
148,251
<p>By default Mocha will read a file named <code>test/mocha.opts</code> that can contain command line arguments. So you could create such a file that contains:</p> <pre><code>--timeout 5000 </code></pre> <p>Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.</p> <p>Another way which may be better depending on your situation is to set it like this in a top level <code>describe</code> call in your test file:</p> <pre><code>describe("something", function () { this.timeout(5000); // tests... }); </code></pre> <p>This would allow you to set a timeout only on a per-file basis.</p> <p>You could use both methods if you want a global default of 5000 but set something different for some files.</p> <hr> <p>Note that you cannot generally use an arrow function if you are going to call <code>this.timeout</code> (or access any other member of <code>this</code> that Mocha sets for you). For instance, <strong>this will usually not work</strong>:</p> <pre><code>describe("something", () =&gt; { this.timeout(5000); //will not work // tests... }); </code></pre> <p>This is because an arrow function takes <code>this</code> from the scope the function appears in. Mocha will call the function with a good value for <code>this</code> but that value is not passed inside the arrow function. The documentation for Mocha says on <a href="https://mochajs.org/#arrow-functions" rel="noreferrer">this topic</a>:</p> <blockquote> <p>Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context. </p> </blockquote>
23,908,606
How to use hibernate.properties file instead of hibernate.cfg.xml
<p>I am trying to connect to DB in a servlet using Hibernate.I have read that we can use either hibernate.cfg.xml or hibernate.properties file for configuration of session.For me it worked with xml. Now when I am trying to use properties instead of xml its not working. It is saying that <strong>hibernate.cfg.xml</strong> <strong>not found</strong>.But nowhere I mentioned to use xml file and infact I have deleted that xml file.</p> <p>Please Help me. And Please correct me if I am doing anything wrong.</p>
23,908,815
6
1
null
2014-05-28 10:05:15.607 UTC
3
2021-12-30 05:55:19.747 UTC
null
null
null
null
3,663,898
null
1
18
java|xml|database|hibernate|properties
53,296
<p>From what i understood from hibernate the best thing to do is to define the mapping in the <code>hibernate.cfg.xml</code> file and other configurations in the <code>hibernate.properties</code>.</p> <p>An alternative approach to configuration is to specify a full configuration in a file named <code>hibernate.cfg.xml</code>. This file can be used as a replacement for the <code>hibernate.properties</code> file or, if both are present, to override properties.</p> <p>The <code>hibernate.cfg.xml</code> is also more convenient once you have to tune the Hibernate cache. It is your choice to use either hibernate.properties or <code>hibernate.cfg.xml</code>. Both are equivalent.</p> <p>You can read more about this in the following link:</p> <p><a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html" rel="noreferrer">http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html</a></p>
53,342,200
Azure Pipeline Publish: task DotNetCoreCLI with specific folder or project
<p>I'm having a problem (unwanted behavior) when running an Azure Build Pipeline with the following project/folder structure.</p> <p>My repository's root folder has two main folders: </p> <ul> <li>frontend (ASP.Net Core 2.x &amp; Angular 7 project)</li> <li>backend (ASP.Net Core 2.x)</li> </ul> <p>I'm trying to build two separate Azure Pipelines one for the backend and one for the frontend, so I use the <code>projects:</code> parameter to specify the correct path.</p> <p>The <code>build</code> and <code>test</code> commands are running fine and are only restoring/building/testing the <code>backend</code> folder, but the <code>publish</code> command is running for both folders: backend &amp; frontend.</p> <p>This is my yaml file:</p> <pre><code> #build backend project task: DotNetCoreCLI@2 displayName: dotnet build --configuration $(buildConfiguration) name: BuildBackendProject inputs: command: build projects: '**/backend/**/*.csproj' arguments: '--configuration $(buildConfiguration)' ... #run some tests #publish backend project task: DotNetCoreCLI@2 displayName: dotnet publish backend --configuration $(buildConfiguration) name: PublishBackendProject inputs: command: publish projects: '**/backend/**/*.csproj' publishWebProjects: True arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)/backend' zipAfterPublish: True </code></pre> <p>I tried different folder paths but it's always running two publish commands.</p> <p>If I run locally in CMD <code>dotnet publish backend</code> (from repo's root folder) it works fine but apparently that doesn't work with the Azure Pipeline.</p> <p>Any ideas or fixes greatly appreciated.</p>
53,395,041
1
2
null
2018-11-16 16:51:33.55 UTC
5
2018-11-20 14:19:59.657 UTC
null
null
null
null
6,005,707
null
1
29
asp.net-core|azure-devops|azure-pipelines|azure-pipelines-build-task
15,526
<p>The trick is in using the publishWebProjects/projects properties. Those are actually mutually exclusive. If the <code>publishWebProjects</code> is used, the <code>projects</code> property value is skipped.</p> <p>From the <a href="https://github.com/Microsoft/azure-pipelines-tasks/tree/master/Tasks/DotNetCoreCLIV2" rel="noreferrer">documentation</a>:</p> <blockquote> <p>Publish Web Projects*: If true, the task will try to find the web projects in the repository and run the publish command on them. Web projects are identified by presence of either a web.config file or wwwroot folder in the directory.</p> </blockquote> <p>So you could try the following code for publishing:</p> <pre><code>task: DotNetCoreCLI@2 displayName: dotnet publish backend --configuration $(buildConfiguration) name: PublishBackendProject inputs: command: publish projects: '**/backend/**/*.csproj' publishWebProjects: false arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)/backend' zipAfterPublish: true </code></pre>
30,285,551
Why does CalibratedClassifierCV underperform a direct classifer?
<p>I noticed that sklearn's new <code>CalibratedClassifierCV</code> seems to underperform the direct <code>base_estimator</code> when the <code>base_estimator</code> is <code>GradientBoostingClassifer</code>, (I haven't tested other classifiers). Interestingly, if <code>make_classification</code>'s parameters are:</p> <pre><code>n_features = 10 n_informative = 3 n_classes = 2 </code></pre> <p>then the <code>CalibratedClassifierCV</code> seems to be the slight outperformer (log loss evaluation).</p> <p>However, under the following classification data set the <code>CalibratedClassifierCV</code> seems to generally be the underperformer:</p> <pre><code>from sklearn.datasets import make_classification from sklearn import ensemble from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import log_loss from sklearn import cross_validation # Build a classification task using 3 informative features X, y = make_classification(n_samples=1000, n_features=100, n_informative=30, n_redundant=0, n_repeated=0, n_classes=9, random_state=0, shuffle=False) skf = cross_validation.StratifiedShuffleSplit(y, 5) for train, test in skf: X_train, X_test = X[train], X[test] y_train, y_test = y[train], y[test] clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf_cv = CalibratedClassifierCV(clf, cv=3, method='isotonic') clf_cv.fit(X_train, y_train) probas_cv = clf_cv.predict_proba(X_test) cv_score = log_loss(y_test, probas_cv) clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf.fit(X_train, y_train) probas = clf.predict_proba(X_test) clf_score = log_loss(y_test, probas) print 'calibrated score:', cv_score print 'direct clf score:', clf_score print </code></pre> <p>One run yielded:</p> <p><img src="https://i.stack.imgur.com/HarT8.png" alt="enter image description here"></p> <p>Maybe I'm missing something about how <code>CalibratedClassifierCV</code> works, or am not using it correctly, but I was under the impression that if anything, passing a classifier to <code>CalibratedClassifierCV</code> would result in improved performance relative to the <code>base_estimator</code> alone.</p> <p>Can anyone explain this observed underperformance? </p>
32,027,398
3
2
null
2015-05-17 09:48:18.98 UTC
14
2019-11-17 14:19:41.597 UTC
null
null
null
null
3,498,864
null
1
18
python|scikit-learn
9,274
<p>The probability calibration itself requires cross-validation, therefore the <code>CalibratedClassifierCV</code> trains a calibrated classifier per fold (in this case using <code>StratifiedKFold</code>), and takes the mean of the predicted probabilities from each classifier when you call predict_proba(). This could lead to the explanation of the effect. </p> <p>My hypothesis is that if the training set is small with respect to the number of features and classes, the reduced training set for each sub-classifier affects performance and the ensembling does not make up for it (or makes it worse). Also the GradientBoostingClassifier might provide already pretty good probability estimates from the start as its loss function is optimized for probability estimation.</p> <p>If that's correct, ensembling classifiers the same way as the CalibratedClassifierCV but without calibration should be worse than the single classifier. Also, the effect should disappear when using a larger number of folds for calibration. </p> <p>To test that, I extended your script to increase the number of folds and include the ensembled classifier without calibration, and I was able to confirm my predictions. A 10-fold calibrated classifier always performed better than the single classifier and the uncalibrated ensemble was significantly worse. In my run, the 3-fold calibrated classifier also did not really perform worse than the single classifier, so this might be also an unstable effect. These are the detailed results on the same dataset:</p> <p><a href="https://i.stack.imgur.com/esPZ4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/esPZ4.png" alt="Log-loss results from cross-validation"></a></p> <p>This is the code from my experiment:</p> <pre><code>import numpy as np from sklearn.datasets import make_classification from sklearn import ensemble from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import log_loss from sklearn import cross_validation X, y = make_classification(n_samples=1000, n_features=100, n_informative=30, n_redundant=0, n_repeated=0, n_classes=9, random_state=0, shuffle=False) skf = cross_validation.StratifiedShuffleSplit(y, 5) for train, test in skf: X_train, X_test = X[train], X[test] y_train, y_test = y[train], y[test] clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf_cv = CalibratedClassifierCV(clf, cv=3, method='isotonic') clf_cv.fit(X_train, y_train) probas_cv = clf_cv.predict_proba(X_test) cv_score = log_loss(y_test, probas_cv) print 'calibrated score (3-fold):', cv_score clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf_cv = CalibratedClassifierCV(clf, cv=10, method='isotonic') clf_cv.fit(X_train, y_train) probas_cv = clf_cv.predict_proba(X_test) cv_score = log_loss(y_test, probas_cv) print 'calibrated score (10-fold:)', cv_score #Train 3 classifiers and take average probability skf2 = cross_validation.StratifiedKFold(y_test, 3) probas_list = [] for sub_train, sub_test in skf2: X_sub_train, X_sub_test = X_train[sub_train], X_train[sub_test] y_sub_train, y_sub_test = y_train[sub_train], y_train[sub_test] clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf.fit(X_sub_train, y_sub_train) probas_list.append(clf.predict_proba(X_test)) probas = np.mean(probas_list, axis=0) clf_ensemble_score = log_loss(y_test, probas) print 'uncalibrated ensemble clf (3-fold) score:', clf_ensemble_score clf = ensemble.GradientBoostingClassifier(n_estimators=100) clf.fit(X_train, y_train) probas = clf.predict_proba(X_test) score = log_loss(y_test, probas) print 'direct clf score:', score print </code></pre>
29,501,117
Creating a Spark DataFrame from an RDD of lists
<p>I have an rdd (we can call it myrdd) where each record in the rdd is of the form:</p> <pre><code>[('column 1',value), ('column 2',value), ('column 3',value), ... , ('column 100',value)] </code></pre> <p>I would like to convert this into a DataFrame in pyspark - what is the easiest way to do this? </p>
29,547,173
4
1
null
2015-04-07 20:53:48.11 UTC
9
2016-09-09 04:20:50.6 UTC
null
null
null
null
2,636,317
null
1
15
apache-spark|dataframe|pyspark
49,658
<p>How about use the <code>toDF</code> method? You only need add the field names. </p> <pre><code>df = rdd.toDF(['column', 'value']) </code></pre>
46,680,467
What is a-la-carte components? Should i use it?
<p>When starting a new project using vue-cli it asks a few questions to customize the setup. Generally the project name, description, whether to use eslint for linting, karma and mocha for testing etc. This time it asked me </p> <pre><code>? Use a-la-carte components? </code></pre> <p>I searched for it in the vue-cli docs but didn't come across anything. So can anyone tell me what is "a-la-carte components" and if I should use it?</p>
46,682,362
2
1
null
2017-10-11 05:26:40.043 UTC
5
2019-01-31 07:13:12.967 UTC
2018-10-03 15:38:38.34 UTC
null
6,832,284
null
4,323,908
null
1
31
webpack|vuejs2|vuetify.js|vue-cli-3
15,240
<blockquote> <p><a href="https://en.wikipedia.org/wiki/%C3%80_la_carte" rel="noreferrer">À la carte</a> is an English language loan phrase meaning "according to the menu." It refers to "food that can be ordered as separate items, rather than part of a set meal."</p> </blockquote> <p>So if you use a-la-carte components, it means that you only include components that you need (want) to use, instead of getting all of them</p> <p><a href="https://vuetifyjs.com/vuetify/a-la-carte" rel="noreferrer">Vuetify example:</a></p> <blockquote> <p>Vuetify allows you to easily import only what you need, drastically lowering its footprint.</p> </blockquote> <pre><code>import { Vuetify, VApp, VNavigationDrawer, VFooter, VList, VBtn } from 'vuetify' Vue.use(Vuetify, { components: { VApp, VNavigationDrawer, VFooter, VList, VBtn } }) </code></pre> <hr> <p><strong>EDIT 2018/11/14:</strong></p> <p>Since <a href="https://github.com/vuetifyjs/vuetify/releases/tag/v1.3.0" rel="noreferrer">vuetify 1.3.0</a>,<br> <a href="https://github.com/vuetifyjs/vuetify-loader" rel="noreferrer"><code>vuetify-loader</code></a> (included in vuetify cli install)<br> automatically handles your application's a-la-carte needs, which means it will automatically import all Vuetify components as you use them.</p>
32,320,214
ActionController::UrlGenerationError, No route matches
<p>I've read through every similar question I could find and still can't figure out my problem.</p> <pre><code># routes.rb Rails.application.routes.draw do resources :lists, only: [:index, :show, :create, :update, :destroy] do resources :items, except: [:new] end end </code></pre> <hr> <pre><code># items_controller.rb (excerpt) class ItemsController &lt; ApplicationController ... def create @list = List.find(params[:list_id]) ... end ... end </code></pre> <hr> <pre><code># items_controller_spec.rb (excerpt) RSpec.describe ItemsController, type: :controller do ... let!(:list) { List.create(title: "New List title") } let(:valid_item_attributes) { { title: "Some Item Title", complete: false, list_id: list.id } } let!(:item) { list.items.create(valid_item_attributes) } describe "POST #create" do context "with valid params" do it "creates a new item" do expect { post :create, { item: valid_item_attributes, format: :json } }.to change(Item, :count).by(1) end end end ... end </code></pre> <p>And the RSpec error:</p> <pre><code>1) ItemsController POST #create with valid params creates a new item Failure/Error: post :create, { item: valid_item_attributes, format: :json } ActionController::UrlGenerationError: No route matches {:action=&gt;"create", :controller=&gt;"items", :format=&gt;:json, :item=&gt;{:title=&gt;"Some Item Title", :complete=&gt;false, :list_id=&gt;1}} </code></pre> <p>The output from <code>rake routes</code>:</p> <pre><code>list_items GET /lists/:list_id/items(.:format) items#index POST /lists/:list_id/items(.:format) items#create edit_list_item GET /lists/:list_id/items/:id/edit(.:format) items#edit list_item GET /lists/:list_id/items/:id(.:format) items#show PATCH /lists/:list_id/items/:id(.:format) items#update PUT /lists/:list_id/items/:id(.:format) items#update DELETE /lists/:list_id/items/:id(.:format) items#destroy </code></pre> <p>I can successfully create a new item in an existing list via <code>curl</code> which tells me that the route is ok, I must be doing something wrong in my test.</p> <pre><code>curl -i -X POST -H "Content-Type:application/json" -H "X-User-Email:[email protected]" -H "X-Auth-xxx" -d '{ "item": { "title": "new item", "complete": "false"} }' http://localhost:3000/lists/5/items </code></pre> <p>I am really confused. My routes are setup correctly. A <code>ItemsController#create</code> method definitely exists. The rest of the tests in <code>items_controller_spec.rb</code> pass without issue.</p> <p>Am I missing something obvious?</p>
32,333,323
2
2
null
2015-08-31 21:24:18.13 UTC
1
2018-10-17 23:37:53.437 UTC
2017-06-20 15:49:35.923 UTC
null
5,025,116
null
1,419,236
null
1
24
ruby-on-rails|rspec-rails
38,368
<p>Here are the fixes I had to make to my tests (<code>items_controller_spec.rb</code>). I was not passing the correct hash to <code>post create:</code>.</p> <pre><code> describe "POST #create" do context "with valid params" do it "creates a new item" do expect { post :create, { list_id: list.id, item: valid_item_attributes, format: :json } }.to change(Item, :count).by(1) end it "assigns a newly created item as @item" do post :create, { list_id: list.id, item: valid_item_attributes, format: :json } expect(assigns(:item)).to be_a(Item) expect(assigns(:item)).to be_persisted end end # "with valid params" context "with invalid params" do it "assigns a newly created but unsaved item as @item" do post :create, { list_id: list.id, item: invalid_item_attributes, format: :json } expect(assigns(:item)).to be_a_new(Item) end it "returns unprocessable_entity status" do put :create, { list_id: list.id, item: invalid_item_attributes, format: :json } expect(response.status).to eq(422) end end # "with invalid params" end # "POST #create" </code></pre>
25,207,147
dataTable() vs. DataTable() - why is there a difference and how do I make them work together?
<p>The vast majority of the documentation for this plugin indicates that you initialize it with </p> <pre><code>$('#example').dataTable(); </code></pre> <p>However <a href="http://www.datatables.net/examples/api/multi_filter_select.html">http://www.datatables.net/examples/api/multi_filter_select.html</a> initializes using </p> <pre><code>$('#example').DataTable(); </code></pre> <p>The resultant objects differ quite a lot, and the example URL above doesn't work when I initialize with a lower-case 'D', however pretty much everything else <em>requires</em> the lower-case 'D' initialization.</p> <p>Can someone please explain to me why there's a difference, and how to make the two play nice together? Essentially I need the multi-filter-select functionality, but also need to tack on some other calls / plugins, which don't seem to like the upper-case 'D' initialization.</p>
25,216,454
1
3
null
2014-08-08 15:37:49.39 UTC
31
2016-06-01 07:13:37.877 UTC
2016-06-01 07:13:37.877 UTC
null
1,407,478
null
177,943
null
1
63
datatables
28,185
<p>Basically, the two constructurs return different objects. </p> <hr> <h2>dataTable constructor</h2> <pre class="lang-js prettyprint-override"><code>var table = $(&lt;selector&gt;).dataTable() </code></pre> <p><code>dataTable</code> is the oldschool dataTables constructur, which returns a jQuery object. This jQuery object is enriched with a set of API methods in hungarian notation format, such as <code>fnFilter</code>, <code>fnDeleteRow</code> and so on. See a complete list of API methods <a href="http://www.datatables.net/api" rel="noreferrer"><strong>here</strong></a>. Examples :</p> <pre class="lang-js prettyprint-override"><code>table.fnDeleteRow(0); table.fnAddData(['E', 'F']); </code></pre> <p><code>dataTable</code> is supported by all <strong>1.9.x</strong> / <strong>1.10.x</strong> versions. </p> <hr> <h2>DataTable constructor</h2> <pre class="lang-js prettyprint-override"><code>var table = $(&lt;selector&gt;).DataTable() </code></pre> <p>The DataTable constructor was introduced in <strong>1.10.x</strong>, and returns a huge API object with full read/write access to pages, rows, cells and more, see <a href="http://www.datatables.net/reference/api/" rel="noreferrer"><strong>manual</strong></a>. Example equivalences :</p> <pre class="lang-js prettyprint-override"><code>table.row(0).remove(); table.row.add(['E', 'F']).draw(); </code></pre> <hr> <h2>Combining dataTable and DataTable</h2> <p>If you maintain old code, or for some reason need to use the oldschool dataTable constructor, but still needs to use the new API, the jQuery object is extended (from <strong>1.10.0</strong>) with a <code>.api()</code> method that returns the new API. Example equivalences :</p> <pre class="lang-js prettyprint-override"><code>var table = $('#example').dataTable(); table.api().row(0).remove(); table.api().row.add(['E', 'F']).draw(); </code></pre> <p>The old API like <code>table.fnDeleteRow(0)</code> still works. So to your concern :</p> <blockquote> <p>Essentially I need the multi-filter-select functionality, but also need to tack on some other calls / plugins, which don't seem to like the upper-case 'D' initialization.</p> </blockquote> <p>As you see, you can do both! Initialize dataTables the old way, and use <code>.api()</code> when you need access to the new API.</p> <hr> <h2>Why is so many official examples using dataTable()?</h2> <p>Well, you do not <em>need</em> to use the <code>DataTable</code> constructor. If you dont use the new API, there is no reason for using the <code>DataTable</code> constructur. The oldschool <code>dataTable</code> constructor is not deprecated. DataTables is mostly one mans work. It is a huge task to maintain and develop and obviously very time consuming to maintain a huge website with forum, manuals, tons of examples and so on. This is only a guess, but I assume Allan Jardine by now only have changed <code>dataTable</code> to <code>DataTable</code> where it is actually needed, simply bacause he cant do it all in one step.</p>
48,842,397
std::make_shared() change in C++17
<p>In <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared" rel="noreferrer">cppref</a>, the following holds until C++17:</p> <blockquote> <p>code such as <code>f(std::shared_ptr&lt;int&gt;(new int(42)), g())</code> can cause a memory leak if <code>g</code> gets called after <code>new int(42)</code> and throws an exception, while <code>f(std::make_shared&lt;int&gt;(42), g())</code> is safe, since two function calls are never interleaved.</p> </blockquote> <p>I'm wondering which change introduced in C++17 renders this no longer applicable.</p>
48,844,115
2
3
null
2018-02-17 14:33:12.227 UTC
4
2018-02-17 17:54:30.343 UTC
null
null
null
null
1,348,273
null
1
29
c++|language-lawyer|c++17|make-shared|exception-safety
4,275
<p>The evaluation order of function arguments are changed by <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0400r0.html" rel="noreferrer">P0400R0</a>.</p> <p>Before the change, evaluation of function arguments are unsequenced relative to one another. This means evaluation of <code>g()</code> may be inserted into the evaluation of <code>std::shared_ptr&lt;int&gt;(new int(42))</code>, which causes the situation described in your quoted context.</p> <p>After the change, evaluation of function arguments are indeterminately sequenced with no interleaving, which means all side effects of <code>std::shared_ptr&lt;int&gt;(new int(42))</code> take place either before or after those of <code>g()</code>. Now consider the case where <code>g()</code> may throw. </p> <ul> <li><p>If all side effects of <code>std::shared_ptr&lt;int&gt;(new int(42))</code> take place before those of <code>g()</code>, the memory allocated will be deallocated by the destructor of <code>std::shared_ptr&lt;int&gt;</code>.</p></li> <li><p>If all side effects of <code>std::shared_ptr&lt;int&gt;(new int(42))</code> take place after those of <code>g()</code>, there is even no memory allocation.</p></li> </ul> <p>In either case, there is no memory leak again anyway.</p>
39,083,768
AWS Docker deployment
<p>I have a custom docker image uploaded to ECS. I opened up the permissions to try and get through this issue (I will lock it down again once I can get this to work). I am attempting to deploy the docker image to elastic beanstalk. I have a docker enabled elastic beanstalk environment set up. According to the AWS docs, if I am pulling my image from within AWS, I don't need to pass in credentials. So I upload my Dockerrun.aws.json file and attempt to install it. It fails with the error:</p> <blockquote> <p>Command failed on instance. Return code: 1 Output: Failed to authenticate with ECR for registry '434875166128' in 'us-east-1'. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03build.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.</p> </blockquote> <p>The /var/log/eb-activity.log information has nothing useful in it.</p> <p>Here's my Dockerrun.aws.json file:</p> <pre><code>{ "AWSEBDockerrunVersion": "1", "Image": { "Name": "{id000xxxx}.dkr.ecr.us-east-1.amazonaws.com/my-repo:1.0.0", "Update": "true" }, "Ports": [ { "ContainerPort": "4000" } ], "Logging": "/var/log/app-name" } </code></pre> <p>I have also tried adding the authentication with the dockercfg.json file in S3. It didn't work for me either.</p> <blockquote> <p>Note that I am using a business account instead of a personal account, so there may be some unknown variances as well.</p> </blockquote> <p>Thanks!</p> <p>Update: My user has full permissions at the moment too, so there shouldn't be anything permission-wise getting in the way.</p>
40,157,257
3
5
null
2016-08-22 15:48:11.747 UTC
7
2022-08-26 18:27:43.443 UTC
null
null
null
null
2,510,128
null
1
42
amazon-web-services|docker|amazon-elastic-beanstalk|amazon-ecs
7,530
<p>I was having the same problem.</p> <p>Solution: In <code>AWS -&gt; IAM -&gt; Roles - &gt;</code> pick the role your beanstalk is using. </p> <p>In my case it was set to <code>aws-elasticbeanstalk-ec2-role</code></p> <p>Under <strong>Permissions</strong> for the role, attach policy: <code>AmazonEC2ContainerRegistryReadOnly</code></p> <p>In ECR there is no need to give any permissions to this role.</p>
20,002,503
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
<p>I am writing a security system that denies access to unauthorized users.</p> <pre><code>name = input(&quot;Hello. Please enter your name: &quot;) if name == &quot;Kevin&quot; or &quot;Jon&quot; or &quot;Inbar&quot;: print(&quot;Access granted.&quot;) else: print(&quot;Access denied.&quot;) </code></pre> <p>It grants access to authorized users as expected, but it also lets in unauthorized users!</p> <pre class="lang-none prettyprint-override"><code>Hello. Please enter your name: Bob Access granted. </code></pre> <p>Why does this occur? I've plainly stated to only grant access when <code>name</code> equals Kevin, Jon, or Inbar. I have also tried the opposite logic, <code>if &quot;Kevin&quot; or &quot;Jon&quot; or &quot;Inbar&quot; == name</code>, but the result is the same.</p> <hr /> <p><sub>This question is intended as the canonical duplicate target of this very common problem. There is another popular question <a href="https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value">How to test multiple variables for equality against a single value?</a> that has the same fundamental problem, but the comparison targets are reversed. This question should not be closed as a duplicate of that one as this problem is encountered by newcomers to Python who might have difficulties applying the knowledge from the reversed question to their problem.</sub></p>
20,002,504
6
1
null
2013-11-15 13:45:34.753 UTC
49
2022-08-11 05:18:21.39 UTC
2022-08-11 05:18:21.39 UTC
null
523,612
null
953,482
null
1
152
python|boolean|boolean-expression
36,545
<p>In many cases, Python looks and behaves like natural English, but this is one case where that abstraction fails. People can use context clues to determine that &quot;Jon&quot; and &quot;Inbar&quot; are objects joined to the verb &quot;equals&quot;, but the Python interpreter is more literal minded.</p> <pre><code>if name == &quot;Kevin&quot; or &quot;Jon&quot; or &quot;Inbar&quot;: </code></pre> <p>is logically equivalent to:</p> <pre><code>if (name == &quot;Kevin&quot;) or (&quot;Jon&quot;) or (&quot;Inbar&quot;): </code></pre> <p>Which, for user Bob, is equivalent to:</p> <pre><code>if (False) or (&quot;Jon&quot;) or (&quot;Inbar&quot;): </code></pre> <p>The <code>or</code> operator chooses the first argument with a positive <a href="http://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="noreferrer">truth value</a>:</p> <pre><code>if &quot;Jon&quot;: </code></pre> <p>And since &quot;Jon&quot; has a positive truth value, the <code>if</code> block executes. That is what causes &quot;Access granted&quot; to be printed regardless of the name given.</p> <p>All of this reasoning also applies to the expression <code>if &quot;Kevin&quot; or &quot;Jon&quot; or &quot;Inbar&quot; == name</code>. the first value, <code>&quot;Kevin&quot;</code>, is true, so the <code>if</code> block executes.</p> <hr /> <p>There are two common ways to properly construct this conditional.</p> <ol> <li><p>Use multiple <code>==</code> operators to explicitly check against each value:</p> <pre><code>if name == &quot;Kevin&quot; or name == &quot;Jon&quot; or name == &quot;Inbar&quot;: </code></pre> </li> <li><p>Compose a collection of valid values (a set, a list or a tuple for example), and use the <code>in</code> operator to test for membership:</p> <pre><code>if name in {&quot;Kevin&quot;, &quot;Jon&quot;, &quot;Inbar&quot;}: </code></pre> </li> </ol> <p>In general of the two the second should be preferred as it's easier to read and also faster:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('name == &quot;Kevin&quot; or name == &quot;Jon&quot; or name == &quot;Inbar&quot;', setup=&quot;name='Inbar'&quot;) 0.4247764749999945 &gt;&gt;&gt; timeit.timeit('name in {&quot;Kevin&quot;, &quot;Jon&quot;, &quot;Inbar&quot;}', setup=&quot;name='Inbar'&quot;) 0.18493307199999265 </code></pre> <hr /> <p>For those who may want proof that <code>if a == b or c or d or e: ...</code> is indeed parsed like this. The built-in <code>ast</code> module provides an answer:</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; ast.parse(&quot;a == b or c or d or e&quot;, &quot;&lt;string&gt;&quot;, &quot;eval&quot;) &lt;ast.Expression object at 0x7f929c898220&gt; &gt;&gt;&gt; print(ast.dump(_, indent=4)) Expression( body=BoolOp( op=Or(), values=[ Compare( left=Name(id='a', ctx=Load()), ops=[ Eq()], comparators=[ Name(id='b', ctx=Load())]), Name(id='c', ctx=Load()), Name(id='d', ctx=Load()), Name(id='e', ctx=Load())])) </code></pre> <p>As one can see, it's the boolean operator <code>or</code> applied to four sub-expressions: comparison <code>a == b</code>; and simple expressions <code>c</code>, <code>d</code>, and <code>e</code>.</p>
6,719,814
onPageFinished() never called (webview)!
<p>I want to show a toast when the webview is totally loaded. But the toast never show up, i don't know why..here is my code:</p> <pre><code>public class WebViewSignUp extends Activity{ WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webviewsignup); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); ((TextView)findViewById(R.id.home)).setOnClickListener(new OnClickListener(){ public void onClick(View v) { finish(); } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(mWebView, url); Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show(); } }); mWebView.loadUrl("http://pabebbe.com/m/register"); mWebView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show(); } }); } } </code></pre>
6,720,004
2
0
null
2011-07-16 19:48:39.967 UTC
4
2021-04-01 09:55:11.367 UTC
2015-04-25 16:44:42.907 UTC
null
2,535,611
null
420,574
null
1
22
android|load|webview|toast
45,109
<p>The second call to <code>setWebViewClient()</code> is overwriting the first.</p> <p>Create only a single instance of <code>WebViewClient</code> with both overrides in the same class, and call <code>setWebViewClient</code> only once. Then load the Webview:</p> <pre><code>mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(mWebView, url); Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show(); } }); mWebView.loadUrl("http://pabebbe.com/m/register"); </code></pre>
7,527,315
How can I convert datetime to date, truncating the times, leaving me the dates?
<p>I have a field that's in datetime format when date would be better and more consistent with the rest of the database, so I want to convert. The time part is all 00:00:00 anyway.</p> <p>How can I do this in MySQL?</p> <p>Thanks.</p>
7,527,377
3
1
null
2011-09-23 10:04:55.057 UTC
2
2017-10-26 12:12:30.153 UTC
null
null
null
null
290,847
null
1
22
mysql|sql
43,004
<p>If you want this in a <code>SELECT</code>-Statement, just use the <code>DATE</code> Operator:</p> <pre><code>SELECT DATE(`yourfield`) FROM `yourtable`; </code></pre> <p>If you want to change the table structurally, just change the datatype to <code>DATE</code> (of course only do this if this doesn't affect applications depending on this field).</p> <pre><code>ALTER TABLE `yourtable` CHANGE `yourfield` `yourfield` DATE; </code></pre> <p>Both will eliminate the time part.</p>
7,105,230
How to access the files in bin/debug within the project folder in Visual studio 2010?
<p>I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.</p> <pre><code> WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true); MainDocumentPart mainDocPart = wordDoc.MainDocumentPart; XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream()); XslCompiledTransform xslt = new XslCompiledTransform(); string xsltFile = @"\\docx.xsl"; // or @"docx.xsl"; xslt.Load(xsltFile); XmlTextWriter writer = new XmlTextWriter(outputFile, null); xslt.Transform(xpathDoc, null, writer); writer.Close(); wordDoc.Close(); </code></pre> <p>Please Guide me to put correct valid path to access docx.xsl file...</p>
7,105,298
4
3
null
2011-08-18 09:30:15.403 UTC
4
2016-02-10 11:50:01.86 UTC
null
null
null
null
452,680
null
1
24
c#|.net|visual-studio-2010
71,547
<p>You can determine the location of your executable, and assuming the file will be deployed with the application to the relevant directory, then this should help you find the file in debugging and in deployment:</p> <pre><code>string executableLocation = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location); string xslLocation = Path.Combine(executableLocation, "docx.xsl"); </code></pre> <p>You might need the following namespaces imported at the top of your file:</p> <pre><code>using System; using System.IO; using System.Reflection; </code></pre>
1,362,906
How "Real-Time" is Linux 2.6?
<p>I am looking at moving my product from an RTOS to embedded Linux. I don't have many real-time requirements, and the few RT requirements I have are on the order of 10s of milliseconds.</p> <p>Can someone point me to a reference that will tell me how Real-Time the current version of Linux is?</p> <p>Are there any other gotchas from moving to a commercial RTOS to Linux?</p>
1,363,211
4
0
null
2009-09-01 14:51:24.927 UTC
16
2021-10-11 13:23:29.983 UTC
2009-09-01 15:42:31.963 UTC
null
9,516
null
9,516
null
1
29
linux|embedded|real-time
8,386
<p>You can get most of your answers from the Real Time Linux <a href="http://rt.wiki.kernel.org/index.php/Main_Page" rel="noreferrer">wiki</a> and <a href="http://rt.wiki.kernel.org/index.php/Frequently_Asked_Questions" rel="noreferrer">FAQ</a></p> <blockquote> <p><strong>What are real-time capabilities of the stock 2.6 linux kernel?</strong></p> <p>Traditionally, the Linux kernel will only allow one process to preempt another only under certain circumstances:</p> <ul> <li>When the CPU is running user-mode code</li> <li>When kernel code returns from a system call or an interrupt back to user space</li> <li>When kernel code code blocks on a mutex, or explicitly yields control to another process</li> </ul> <p>If kernel code is executing when some event takes place that requires a high priority thread to start executing, the high priority thread can not preempt the running kernel code, until the kernel code explicitly yields control. In the worst case, the latency could potentially be hundreds milliseconds or more.</p> <p>The Linux 2.6 configuration option CONFIG_PREEMPT_VOLUNTARY introduces checks to the most common causes of long latencies, so that the kernel can voluntarily yield control to a higher priority task waiting to execute. This can be helpful, but while it reduces the occurences of long latencies (hundreds of milliseconds to potentially seconds or more), it does not eliminate them. However unlike CONFIG_PREEMPT (discussed below), CONFIG_PREEMPT_VOLUNTARY has a much lower impact on the overall throughput of the system. (As always, there is a classical tradeoff between throughput --- the overall efficiency of the system --- and latency. With the faster CPU's of modern-day systems, it often makes sense to trade off throughput for lower latencies, but server class systems that do not need minimum latency guarantees may very well chose to use either CONFIG_PREEMPT_VOLUNTARY, or to stick with the traditional non-preemptible kernel design.)</p> <p>The 2.6 Linux kernel has an additional configuration option, CONFIG_PREEMPT, which causes all kernel code outside of spinlock-protected regions and interrupt handlers to be eligible for non-voluntary preemption by higher priority kernel threads. With this option, worst case latency drops to (around) single digit milliseconds, although some device drivers can have interrupt handlers that will introduce latency much worse than that. If a real-time Linux application requires latencies smaller than single-digit milliseconds, use of the CONFIG_PREEMPT_RT patch is highly recommended.</p> </blockquote> <p>They also have a list of &quot;Gotcha's&quot; as you called them in the FAQ.</p> <blockquote> <p><strong>What are important things to keep in mind while writing realtime applications?</strong></p> <p>Taking care of the following during the initial startup phase:</p> <ul> <li>Call mlockall() as soon as possible from main().</li> <li>Create all threads at startup time of the application, and touch each page of the entire stack of each thread. Never start threads dynamically during RT show time, this will ruin RT behavior.</li> <li>Never use system calls that are known to generate page faults, such as fopen(). (Opening of files does the mmap() system call, which generates a page-fault).</li> <li>If you use 'compile time global variables' and/or 'compile time global arrays', then use mlockall() to prevent page faults when accessing them.</li> </ul> <p>more information: <a href="http://rt.wiki.kernel.org/index.php/HOWTO:_Build_an_RT-application" rel="noreferrer">HOWTO: Build an RT-application</a></p> </blockquote> <p>They also have a large <a href="http://rt.wiki.kernel.org/index.php/Publications" rel="noreferrer">publications page</a> you might want to checkout.</p>
48,944,875
SourceTree error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
<p>I'm using SourceTree and try to clone from a general github repository, but I got this error:</p> <blockquote> <p>fatal: unable to access '<a href="https://github.com/mfitzp/15-minute-apps.git/" rel="noreferrer">https://github.com/mfitzp/15-minute-apps.git/</a>': error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version Completed with errors, see above.</p> </blockquote> <p>How to solve it?</p>
48,945,089
7
4
null
2018-02-23 09:36:53.833 UTC
5
2018-08-12 15:51:36.577 UTC
2018-02-24 00:12:16.697 UTC
null
4,573,839
null
4,573,839
null
1
73
git|github|atlassian-sourcetree
91,431
<p>Check <code>Tools &gt; Options &gt; Git</code> in SourceTree, if you're using <code>Use Embedded Git</code>, you can see the git version is <code>1.9.5</code> which is old, <a href="https://git-scm.com/downloads" rel="noreferrer"><strong>latest version</strong></a> of git is <code>2.16.2</code>.</p> <p>So click <code>Use System Git</code>, if you install the newer version of git, after <code>Use system Git</code> it'll show newer version, then try to clone again it should work fine.</p> <p>Also see another answer <a href="https://developercommunity.visualstudio.com/content/problem/201457/unable-to-connect-to-github-due-to-tls-12-only-cha.html" rel="noreferrer">HERE</a>.</p> <p><a href="https://i.stack.imgur.com/xAARt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xAARt.png" alt="enter image description here"></a></p>
7,572,872
Changing a macro at runtime in C
<p>I have a macro defined. But I need to change this value at run time depending on a condition. How can I implement this? </p>
7,572,894
5
17
null
2011-09-27 16:56:34.777 UTC
2
2019-02-06 15:09:15.39 UTC
2016-03-21 19:49:03.897 UTC
null
4,370,109
null
405,483
null
1
33
c|c-preprocessor
47,321
<p>Macros are replaced by the preprocessor by their value before your source file even compiles. There is no way you'd be able to change the value of the macro at runtime.</p> <p>If you could explain a little more about the goal you are trying to accomplish undoubtedly there is another way of solving your problem that doesn't include macros.</p>
7,357,123
Get current user's email address in .NET
<p>I would like to know the email address of the user (assuming she's in a typical Windows office network). This is in a C# application. Perhaps something to the effect of</p> <pre><code>CurrentUser.EmailAddress; </code></pre>
7,357,185
5
3
null
2011-09-09 04:21:58.027 UTC
7
2021-02-23 13:14:29.187 UTC
2013-03-18 16:54:20.283 UTC
null
284,795
null
547,296
null
1
43
c#|.net|exchange-server
49,139
<p>If you're behind a Windows domain, you could always grab their email address out of Active Directory.</p> <p>See Javier G. Lozano's example in his tutorial, &quot;<a href="http://lozanotek.com/blog/articles/149.aspx" rel="nofollow noreferrer">Querying Active Directory for User Emails</a>&quot;.</p>
7,393,274
Is it possible to view multiple git branches at the same time for the same project?
<p>I have 2 branches, which are not ready to be merged yet, but have some complementary logic, which I'd like to review (before merging)</p> <p>Can I check out multiple git branches of the same project? Is it possible?</p>
7,393,302
6
2
null
2011-09-12 20:00:18.277 UTC
17
2017-04-04 11:25:58.01 UTC
2011-09-12 20:02:42.703 UTC
null
19,750
null
359,862
null
1
86
git|branch|git-checkout
43,583
<p>You can simply copy the repository to a new location (either by literally copying the directory, or using <a href="https://git-scm.com/docs/git-clone#git-clone---shared" rel="noreferrer"><code>git clone --shared</code></a>) and check out one branch per location.</p> <p>You can also use <a href="https://git-scm.com/docs/git-worktree" rel="noreferrer"><code>git-worktree</code></a> for creating multiple working directories from a single instance of a repository.</p> <p>Otherwise, the primary means for comparing files between branches prior to merging them is <code>git diff</code>.</p>
7,013,735
Turn off caching of static files in Django development server
<p><strong>Is there an easy way to turn off caching of static files in Django's development server?</strong></p> <p>I'm starting the server with the standard command:</p> <pre><code>$ python manage.py runserver </code></pre> <p>I've got <code>settings.py</code> configured to serve up static files from the <code>/static</code> directory of my Django project. I've also got a middleware class that sets the <code>Cache-Control</code> header to <code>must-revalidate, no-cache</code> for development, but that only seems to affect URLs that are not in my <code>/static</code> directory.</p>
7,014,876
10
2
null
2011-08-10 15:47:03.267 UTC
11
2021-03-17 15:28:30.977 UTC
2011-08-10 15:59:29.38 UTC
null
5,377
null
5,377
null
1
40
python|django
25,334
<p>Assuming you're using <code>django.views.static.serve</code>, it doesn't look like it - but writing your own view that just calls <code>django.views.static.serve</code>, adding the Cache-Control header should be rather easy.</p>
7,417,415
How to get second-highest salary employees in a table
<p>It's a question I got this afternoon:</p> <p>There a table contains ID, Name, and Salary of Employees, get names of the second-highest salary employees, in SQL Server</p> <p>Here's my answer, I just wrote it in paper and not sure that it's perfectly valid, but it seems to work: </p> <pre><code>SELECT Name FROM Employees WHERE Salary = ( SELECT DISTINCT TOP (1) Salary FROM Employees WHERE Salary NOT IN (SELECT DISTINCT TOP (1) Salary FROM Employees ORDER BY Salary DESCENDING) ORDER BY Salary DESCENDING) </code></pre> <p>I think it's ugly, but it's the only solution come to my mind.</p> <p>Can you suggest me a better query?</p> <p>Thank you very much.</p>
7,417,462
57
0
null
2011-09-14 13:48:58.323 UTC
16
2021-11-26 11:58:59.15 UTC
2015-07-30 12:17:26.093 UTC
null
79,109
null
79,109
null
1
45
sql|sql-server|tsql|optimization
382,446
<p>To get the names of the employees with the 2nd highest distinct salary amount you can use.</p> <pre><code>;WITH T AS ( SELECT *, DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk FROM Employees ) SELECT Name FROM T WHERE Rnk=2; </code></pre> <p>If Salary is indexed the following may well be more efficient though especially if there are many employees.</p> <pre><code>SELECT Name FROM Employees WHERE Salary = (SELECT MIN(Salary) FROM (SELECT DISTINCT TOP (2) Salary FROM Employees ORDER BY Salary DESC) T); </code></pre> <p>Test Script</p> <pre><code>CREATE TABLE Employees ( Name VARCHAR(50), Salary FLOAT ) INSERT INTO Employees SELECT TOP 1000000 s1.name, abs(checksum(newid())) FROM sysobjects s1, sysobjects s2 CREATE NONCLUSTERED INDEX ix ON Employees(Salary) SELECT Name FROM Employees WHERE Salary = (SELECT MIN(Salary) FROM (SELECT DISTINCT TOP (2) Salary FROM Employees ORDER BY Salary DESC) T); WITH T AS (SELECT *, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Rnk FROM Employees) SELECT Name FROM T WHERE Rnk = 2; SELECT Name FROM Employees WHERE Salary = (SELECT DISTINCT TOP (1) Salary FROM Employees WHERE Salary NOT IN (SELECT DISTINCT TOP (1) Salary FROM Employees ORDER BY Salary DESC) ORDER BY Salary DESC) SELECT Name FROM Employees WHERE Salary = (SELECT TOP 1 Salary FROM (SELECT TOP 2 Salary FROM Employees ORDER BY Salary DESC) sel ORDER BY Salary ASC) </code></pre>
13,869,182
How to get the default gateway from powershell?
<p>If a computer has multiple gateways, how can I determine which is the default gateway using the PowerShell?</p>
13,870,619
5
0
null
2012-12-13 21:57:20.77 UTC
2
2018-04-20 14:42:48.477 UTC
2012-12-15 21:57:06.28 UTC
null
9,967
null
908,687
null
1
8
powershell
49,769
<p>You need to know which of the multiple gateways are used? If so. From what I remember, when multiple gateways are available the gateway with the lowest metric("cost" based on link speed) is used. To get this, run the following command:</p> <pre><code>Get-WmiObject -Class Win32_IP4RouteTable | where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} | Sort-Object metric1 | select nexthop, metric1, interfaceindex </code></pre> <p>if there are multiple default gateways with the same cost, I think it's decided using the binding order of the network adapters. The only way I know to get this is using GUI and registry. To include binding order you could save the output of the script over, get the settingsid from Win32_networkadapterconfiguration (identify using interfaceindex), and read the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Linkage\Bind. This key lists the binding order it seems, and the settingsid you get from win32_networkadapterconfiguration is the GUID they identify the device with. Then sort the gateways with equal metrics using their order in the Bind reg.key and you got your answer.</p> <p>Explained in: <a href="http://social.technet.microsoft.com/Forums/sr-Latn-CS/ITCG/thread/764fee15-9e22-4a46-b284-9f63f774a5e4" rel="nofollow noreferrer">Technet Social - NIC adapter binding</a></p>
14,139,766
Run a particular Python function in C# with IronPython
<p>So far I have a simple class that wraps a python engine (IronPython) for my use. Although code looks big it's really simple so I copy it here to be more clear with my issue.</p> <p>Here's the code:</p> <pre><code>public class PythonInstance { ScriptEngine engine; ScriptScope scope; ScriptSource source; public PythonInstance() { engine = Python.CreateEngine(); scope = engine.CreateScope(); } public void LoadCode(string code) { source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); source.Compile(); } public void SetVariable(string key, dynamic variable) { scope.SetVariable(key, variable); } public void RunCode() { source.Execute(scope); } public void CallFunction(string function) { //?????? no idea what to call here } } </code></pre> <p>So, it works great but it only allows me to execute all python script at once... but what I would like to do is to be able to call particular functions from within a pythos script.</p> <p><strong>So, my question</strong>: How do I call particular function in the loaded script?</p> <p>I was trying to find some information or tutorials but unfortunately couldn't find anything.</p>
14,141,311
2
2
null
2013-01-03 13:21:33.033 UTC
9
2018-12-04 09:42:45.847 UTC
null
null
null
null
786,107
null
1
10
c#|python|dynamic|ironpython
17,984
<p>Thanks to suggestion in comments I was able to figure out how to use it. Here's what I have now:</p> <pre><code>public class PythonInstance { private ScriptEngine engine; private ScriptScope scope; private ScriptSource source; private CompiledCode compiled; private object pythonClass; public PythonInstance(string code, string className = "PyClass") { //creating engine and stuff engine = Python.CreateEngine(); scope = engine.CreateScope(); //loading and compiling code source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); compiled = source.Compile(); //now executing this code (the code should contain a class) compiled.Execute(scope); //now creating an object that could be used to access the stuff inside a python script pythonClass = engine.Operations.Invoke(scope.GetVariable(className)); } public void SetVariable(string variable, dynamic value) { scope.SetVariable(variable, value); } public dynamic GetVariable(string variable) { return scope.GetVariable(variable); } public void CallMethod(string method, params dynamic[] arguments) { engine.Operations.InvokeMember(pythonClass, method, arguments); } public dynamic CallFunction(string method, params dynamic[] arguments) { return engine.Operations.InvokeMember(pythonClass, method, arguments); } } </code></pre> <p>To test it:</p> <pre><code> PythonInstance py = new PythonInstance(@" class PyClass: def __init__(self): pass def somemethod(self): print 'in some method' def isodd(self, n): return 1 == n % 2 "); py.CallMethod("somemethod"); Console.WriteLine(py.CallFunction("isodd", 6)); </code></pre>
13,963,188
Overcoming java.net.MalformedURLException: no protocol Exception
<p>I have a properties file that contains a property specifying the URL of a NOAA web site containing a temperature data set. The property contains a <code>[DATE_REPLACE]</code> token because the URL changes daily when NOAA generates a new forecast.</p> <p>In my properties file, I am specifying:</p> <pre><code>WEATHER_DATA_URL="http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.[DATE_REPLACE]/cy.00.txt" </code></pre> <p>I have declared a method withing a PropertyHelper class (a wrapper for java.util.Properties) to generate the URL String for the current day using <code>WEATHER_DATA_URL</code> as the name, "<em>yyyyMMdd</em>" as the date format, a today's Date.</p> <pre><code>public String getPropertyWithDateReplaceToken(String name, String dateFormat, Date dateToFormat) { String value = this.properties.getProperty(name); if (StringHelper.isNullOrWhitespace(value) || !value.contains("[DATE_REPLACE]")) { throw new UnsupportedOperationException("The property value should specify the [DATE_REPLACE] token"); } StringBuilder sb = new StringBuilder(value); int index = sb.indexOf("[DATE_REPLACE]"); while (index != -1) { String replacement = StringHelper.getTodayAsDateString(dateFormat, dateToFormat); sb.replace(index, index + "[DATE_REPLACE]".length(), replacement); index += replacement.length(); index = sb.indexOf(value, index); } return sb.toString(); } </code></pre> <p>I then call another helper class with the following method to read the text from the web page:</p> <pre><code>public static List&lt;String&gt; readLinesFromWebPage(String urlText) throws Exception { List&lt;String&gt; lines = new ArrayList&lt;String&gt;(); if (StringHelper.isNullOrWhitespace(urlText)) { throw new NullPointerException("URL text cannot be null or empty"); } BufferedReader dataReader = null; try { System.out.println("URL = " + urlText); String trimmedUrlText = urlText.replaceAll("\\s", ""); URL url = new URL(trimmedUrlText); dataReader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while((inputLine = dataReader.readLine()) != null) { lines.add(inputLine); } return lines; } catch(Exception e) { logger.logThrow(Level.SEVERE, e, "Exception (" + e.getMessage() + ") attempting to " + "read data from URL (" + urlText + ")"); throw e; } } </code></pre> <p>As you can see I have tried to trim spaces from the generated URL String in the hopes that that was causing the issue. The URL string is generated properly but I am getting the following exception:</p> <pre><code>java.net.MalformedURLException: no protocol: "http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.20121219/cy.00.txt" </code></pre> <p>If I set the string manually, everything works ... what am I missing?</p>
13,963,266
1
0
null
2012-12-19 23:54:46.143 UTC
null
2012-12-20 00:21:01.81 UTC
2012-12-20 00:21:01.81 UTC
null
1,437,962
null
1,917,267
null
1
10
java|malformedurlexception
48,731
<p>Your property file has double quotes around the value of the URL. Remove these.</p>
14,194,918
code to add markers to map using android google maps v2
<p>I have lat&amp;long values from database.how to display markers based on lat &amp;long values using android google map api v2.In original android google maps,we display markers based on concept itemoverlay. In v2,I dont know how to display markers. </p> <pre><code> dbAdapter.open(); Cursor points = dbAdapter.clustercall(Btmlft_latitude, toprgt_latitude, Btmlft_longitude, toprgt_longitude, gridsize1); int c = points.getCount(); Log.d("count of points", "" + c); if (points != null) { if (points.moveToFirst()) { do { int latitude = (int) (points.getFloat(points .getColumnIndex("LATITUDE")) * 1E6); int longitude = (int) (points.getFloat(points .getColumnIndex("LONGITUDE")) * 1E6); mapView.addMarker(new MarkerOptions().position( new LatLng(latitude, longitude)).icon( BitmapDescriptorFactory.defaultMarker())); } while (points.moveToNext()); } } points.close(); dbAdapter.close(); </code></pre> <p>That is mycode.I am getting <strong>lat&amp;long values from database</strong>,but how to add markers based on lat &amp;long values to map.</p> <p>I read the android google maps api v2.In that have only give <strong>statically added data of markers</strong></p>
14,206,155
3
0
null
2013-01-07 11:24:21.273 UTC
5
2019-04-20 10:20:41.82 UTC
2014-05-05 20:22:40.123 UTC
null
3,235,496
null
1,954,763
null
1
14
android|google-maps-android-api-2
81,367
<p>You have to use the method <code>GoogleMap.addMarker(MarkerOptions);</code> I've explained this in a tutorial on my blog: <a href="http://bon-app-etit.blogspot.be/2012/12/add-informationobject-to-marker-in.html" rel="nofollow noreferrer">http://bon-app-etit.blogspot.be/2012/12/add-informationobject-to-marker-in.html</a></p> <p>On this blog, you'll find some more posts concerning the new Maps API:</p> <ul> <li>Move the map to current or some location</li> <li>Create the custom InfoWindow</li> <li>Associate geodata or objects to a marker</li> </ul>
13,943,062
Extract day of year and Julian day from a string date
<p>I have a string <code>"2012.11.07"</code> in python. I need to convert it to date object and then get an integer value of <em>day of year</em> and also <em>Julian day</em>. Is it possible?</p>
13,943,108
10
1
null
2012-12-18 23:12:36.843 UTC
10
2022-04-08 07:44:07.267 UTC
2018-12-11 23:32:33.947 UTC
null
355,230
null
1,043,898
null
1
30
python|date|datetime|julian-date
83,147
<p>First, you can convert it to a <a href="http://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object like this:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; fmt = '%Y.%m.%d' &gt;&gt;&gt; s = '2012.11.07' &gt;&gt;&gt; dt = datetime.datetime.strptime(s, fmt) &gt;&gt;&gt; dt datetime.datetime(2012, 11, 7, 0, 0) </code></pre> <p>Then you can use the methods on <code>datetime</code> to get what you want… except that <code>datetime</code> doesn't have the function you want directly, so you need to convert to a <a href="http://docs.python.org/2/library/time.html#time.struct_time">time tuple</a></p> <pre><code>&gt;&gt;&gt; tt = dt.timetuple() &gt;&gt;&gt; tt.tm_yday 312 </code></pre> <p>The term "Julian day" has a few different meanings. If you're looking for <code>2012312</code>, you have to do that indirectly, e.g., one of the following.</p> <pre><code>&gt;&gt;&gt; int('%d%03d' % (tt.tm_year, tt.tm_yday)) 2012312 &gt;&gt;&gt; tt.tm_year * 1000 + tt.tm_yday 2012312 </code></pre> <p>If you're looking for a different meaning, you should be able to figure it out from here. For example, if you want the "days since 1 Jan 4713 BC" meaning, and you have a formula that requires Gregorian year and day in year, you've got those two values above to plug in. (If you have a formula that takes Gregorian year, month, and day, you don't even need the <code>timetuple</code> step.) If you can't work out where to go from there, ask for further details.</p> <p>If you don't have a formula—and maybe even if you already do—your best bet is probably to look around PyPI and ActiveState for pre-existing modules. For example, a quick search turned up something called <a href="http://pypi.python.org/pypi/jdcal/1.0"><code>jdcal</code></a>. I'd never seen it before, but a quick <code>pip install jdcal</code> and a brief skim of the readme, and I was able to do this:</p> <pre><code>&gt;&gt;&gt; sum(jdcal.gcal2jd(dt.year, dt.month, dt.day)) 2456238.5 </code></pre> <p>That's the same result that the USN <a href="http://aa.usno.navy.mil/data/docs/JulianDate.php">Julian date converter</a> gave me.</p> <p>If you want integral Julian day, instead of fractional Julian date, you have to decide which direction you want to round—toward 0, toward negative infinity, rounding noon up to the next day, rounding noon toward even days, etc. (Note that Julian date is defined as starting since noon on 1 Jan 4713BC, so half of 7 Nov 2012 is 2456238, the other half is 2456239, and only you know which one of those you want…) For example, to round toward 0:</p> <pre><code>&gt;&gt;&gt; int(sum(jdcal.gcal2jd(dt.year, dt.month, dt.day))) 2456238 </code></pre>
14,356,670
Google Sheets: How to replace text in column header?
<p>I have a query like this <code>=QUERY(B2:C9; "select (C * 100 / B) - 100")</code> in my Google Sheets. What is displayed as a column header is:</p> <p><code>difference(quotient(product(100.0()))100.0())</code>.</p> <p>I want to put a human readable description there instead.</p> <p>How can I achieve this?</p>
14,369,018
4
1
null
2013-01-16 10:51:54.273 UTC
11
2022-09-12 22:42:19.767 UTC
2019-07-04 06:02:56.85 UTC
null
598,520
null
598,520
null
1
57
google-sheets|google-drive-api|google-sheets-query
76,934
<p><code>=QUERY(B2:C9;"select (C*100/B)-100 label (C*100/B)-100 'Value'")</code></p> <p><a href="https://developers.google.com/chart/interactive/docs/querylanguage#Label">https://developers.google.com/chart/interactive/docs/querylanguage#Label</a></p>
14,142,194
Is there a GUI design app for the Tkinter / grid geometry?
<p>Does anyone know of a GUI design app that lets you choose/drag/drop the widgets, and then turn that layout into Python code with the appropriate Tkinter calls &amp; arrangement using the <code>grid</code> geometry manager? So far I've turned up a couple of pretty nice options that I may end up using, but they generate code using either <code>pack</code> or <code>place</code> instead.</p> <p>=========</p> <p><strong>EDIT: Please note this is not to seek a &quot;recommendation&quot; per se, but rather it is a factual inquiry. I was asking whether or not such an app exists.</strong></p> <p>=====</p> <p>Before you say it: Yes, I know Tkinter is easy to learn, and Yes, I've found multiple online sources to help me do so, and I'm already on my way with that. This isn't about avoiding the effort of learning, it's about using the right tool for the job. I found out a long time ago that those drag-and-drop widget environments for coding program logic, are just too klunky and unmanageable when the project gets beyond a certain size -- for bigger stuff, it's just easier to build and maintain the logic when it's in plain text. More recently I've found out that the reverse is true for designing a GUI. Writing text works up to a point, but when you have a main window with 30 or 40 widgets, plus a couple of side windows each with similar complexity, it goes much faster and easier if you can design it graphically rather than typing it all out.</p>
14,142,360
3
5
null
2013-01-03 15:44:18.073 UTC
27
2021-07-07 16:22:32.513 UTC
2021-07-07 16:22:32.513 UTC
null
1,905,392
null
1,905,392
null
1
59
python|grid|tkinter
153,062
<p>You have <strong>VisualTkinter</strong> also known as Visual Python. Development seems not active. You have <a href="http://sourceforge.net/projects/visualtkinter/files/?source=navbar">sourceforge</a> and <a href="http://code.google.com/p/visualtkinter/downloads/list">googlecode</a> sites. Web site <a href="http://visualtkinter.sourceforge.net/download.htm">is here</a>.</p> <p>On the other hand, you have <a href="http://page.sourceforge.net/"><strong>PAGE</strong></a> that seems active and works in python 2.7 and py3k</p> <p>As you indicate on your comment, none of these use the <code>grid</code> geometry. As far as I can say the only GUI builder doing that could probably be <strong>Komodo Pro GUI Builder</strong> which was discontinued and made open source in ca. 2007. The code was located in the <a href="http://sourceforge.net/projects/spectcl/files/?source=navbar">SpecTcl repository</a>.</p> <p>It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC: </p> <p><img src="https://i.stack.imgur.com/Qdbsi.png" alt="enter image description here"></p> <p>By the way, <a href="http://www.bitflipper.ca/rapyd/">Rapyd Tk</a> also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned. </p>
14,274,942
SQL Server CTE and recursion example
<p>I never use CTE with recursion. I was just reading an article on it. This article shows employee info with the help of Sql server CTE and recursion. It is basically showing employees and their manager info. I am not able to understand how this query works. Here is the query:</p> <pre><code>WITH cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel) AS ( SELECT EmployeeID, FirstName, LastName, ManagerID, 1 FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID, r.EmpLevel + 1 FROM Employees e INNER JOIN cteReports r ON e.ManagerID = r.EmpID ) SELECT FirstName + ' ' + LastName AS FullName, EmpLevel, (SELECT FirstName + ' ' + LastName FROM Employees WHERE EmployeeID = cteReports.MgrID) AS Manager FROM cteReports ORDER BY EmpLevel, MgrID </code></pre> <p>Here I am posting about how the output is showing: <img src="https://i.stack.imgur.com/03JpM.jpg" alt="enter image description here"></p> <p>I just need to know how it is showing manager first and then his subordinate in a loop. I guess the first sql statement fires only once and that returns all employee ids.</p> <p>And the second query repeatedly fires, querying the database on which employee exists with the current manager id.</p> <p>Please explain how the sql statement executes in an internal loop and also tell me the sql execution order. Thanks.</p> <h2>MY 2nd phase of question</h2> <pre><code>;WITH Numbers AS ( SELECT n = 1 UNION ALL SELECT n + 1 FROM Numbers WHERE n+1 &lt;= 10 ) SELECT n FROM Numbers </code></pre> <p>Q 1) how is the value of N is getting incremented? if the value is assigned to N every time then N value can be incremented but only the first time N value was initialized.</p> <p>Q 2) CTE and recursion of employee relations:</p> <p>The moment I add two managers and add a few more employees under the second manager is where the problem starts.</p> <p>I want to display the first manager detail and in the next rows only those employee details that relate to the subordinate of that manager.</p> <h2>Suppose</h2> <pre><code>ID Name MgrID Level --- ---- ------ ----- 1 Keith NULL 1 2 Josh 1 2 3 Robin 1 2 4 Raja 2 3 5 Tridip NULL 1 6 Arijit 5 2 7 Amit 5 2 8 Dev 6 3 </code></pre> <p>I want to display the results in such way with CTE expressions. Please tell me what to modify in my sql which I gave here in order to pull manager-employee relations. Thanks.</p> <h2>I want the output to be like this:</h2> <pre><code>ID Name MgrID nLevel Family ----------- ------ ----------- ----------- -------------------- 1 Keith NULL 1 1 3 Robin 1 2 1 2 Josh 1 2 1 4 Raja 2 3 1 5 Tridip NULL 1 2 7 Amit 5 2 2 6 Arijit 5 2 2 8 Dev 6 3 2 </code></pre> <p>Is this possible...?</p>
14,275,097
4
0
null
2013-01-11 09:17:37.907 UTC
76
2019-02-05 16:06:47.943 UTC
2019-02-05 16:06:47.943 UTC
null
133
null
508,127
null
1
121
sql-server|common-table-expression
212,464
<p>I haven't tested your code, just tried to help you understand how it operates in comment;</p> <pre><code>WITH cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel) AS ( --&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;Block 1&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; -- In a rCTE, this block is called an [Anchor] -- The query finds all root nodes as described by WHERE ManagerID IS NULL SELECT EmployeeID, FirstName, LastName, ManagerID, 1 FROM Employees WHERE ManagerID IS NULL --&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;Block 1&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; UNION ALL --&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;Block 2&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; -- This is the recursive expression of the rCTE -- On the first "execution" it will query data in [Employees], -- relative to the [Anchor] above. -- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees] -- as defined by the hierarchy -- Subsequent "executions" of this block will reference R{n-1} SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID, r.EmpLevel + 1 FROM Employees e INNER JOIN cteReports r ON e.ManagerID = r.EmpID --&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;Block 2&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; ) SELECT FirstName + ' ' + LastName AS FullName, EmpLevel, (SELECT FirstName + ' ' + LastName FROM Employees WHERE EmployeeID = cteReports.MgrID) AS Manager FROM cteReports ORDER BY EmpLevel, MgrID </code></pre> <p>The simplest example of a recursive <code>CTE</code> I can think of to illustrate its operation is;</p> <pre><code>;WITH Numbers AS ( SELECT n = 1 UNION ALL SELECT n + 1 FROM Numbers WHERE n+1 &lt;= 10 ) SELECT n FROM Numbers </code></pre> <p><strong>Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize</strong>.</p> <p><code>A1:</code> In this case, <code>N</code> is not a variable. <code>N</code> is an alias. It is the equivalent of <code>SELECT 1 AS N</code>. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a <code>CTE</code> in <code>T-SQL</code>. I've included the analog of a simple <code>CTE</code> in <code>Excel</code> to try and illustrate in a more familiar way what is happening.</p> <pre><code>-- Outside ;WITH CTE (MyColName) AS ( SELECT 1 ) -- Inside ;WITH CTE AS ( SELECT 1 AS MyColName -- Or SELECT MyColName = 1 -- Etc... ) </code></pre> <p><img src="https://i.stack.imgur.com/v8aN0.png" alt="Excel_CTE"></p> <p><strong>Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager</strong></p> <p><code>A2:</code></p> <p>Does this code answer your question?</p> <pre><code>-------------------------------------------- -- Synthesise table with non-recursive CTE -------------------------------------------- ;WITH Employee (ID, Name, MgrID) AS ( SELECT 1, 'Keith', NULL UNION ALL SELECT 2, 'Josh', 1 UNION ALL SELECT 3, 'Robin', 1 UNION ALL SELECT 4, 'Raja', 2 UNION ALL SELECT 5, 'Tridip', NULL UNION ALL SELECT 6, 'Arijit', 5 UNION ALL SELECT 7, 'Amit', 5 UNION ALL SELECT 8, 'Dev', 6 ) -------------------------------------------- -- Recursive CTE - Chained to the above CTE -------------------------------------------- ,Hierarchy AS ( -- Anchor SELECT ID ,Name ,MgrID ,nLevel = 1 ,Family = ROW_NUMBER() OVER (ORDER BY Name) FROM Employee WHERE MgrID IS NULL UNION ALL -- Recursive query SELECT E.ID ,E.Name ,E.MgrID ,H.nLevel+1 ,Family FROM Employee E JOIN Hierarchy H ON E.MgrID = H.ID ) SELECT * FROM Hierarchy ORDER BY Family, nLevel </code></pre> <h2>Another one sql with tree structure</h2> <pre><code>SELECT ID,space(nLevel+ (CASE WHEN nLevel &gt; 1 THEN nLevel ELSE 0 END) )+Name FROM Hierarchy ORDER BY Family, nLevel </code></pre>
9,045,595
Delegates in IOS - Some clarification required
<p>I'm only really beginning IOS development but have a few years dev of ASP.net through C#. To be honest I've never had a real need to understand delegates / events etc. before, I know that I'm using them when programming web.forms but a lot of the functionality is taken care of by the framework, behind the scenes.</p> <p>So now that I'm developing in IOS I'm forced to try to understand how they function (I'm presuming here that the theory of delegates / events is the same across languages, maybe I'm wrong). Anyway, the following line of code in IOS:</p> <pre><code> if ([self.delegate respondsToSelector:@selector(startImporting:)]) { [self.delegate startImporting:self]; } </code></pre> <p>Am I right in thinking that, in pseudo code, it means something along the lines of:</p> <p>If the method/class calling this method has a method in it called 'startImporting' then call the method 'startImporting' within the calling class.</p> <p>Hope that's clear. If that's the case then would it essentially be the same as having a static method in C# that you could call with something like:</p> <pre><code>myImportClass.startImporting(); </code></pre> <p>Presumably not, or that's how it would be done. So, am I missing the whole point of delegates, their benefits etc? I've read what they are over and over and while it makes sense, it never clicks, I never (in web forms anyway) have really seen the benefit of using them.</p> <p>This becomes increasingly important as I'm moving to using lambda expressions in .net and they're closely linked to delegates in C# so while I can just start using them, I'd prefer to know why and what benefit delegates actually are.</p>
9,045,881
3
1
null
2012-01-28 13:27:49.907 UTC
14
2018-06-19 15:45:39.193 UTC
null
null
null
null
989,348
null
1
10
ios|delegates
8,827
<p>The delegation pattern in Cocoa is used to inform (report progress, etc.) or query (ask for credentials, etc.) another object without knowing much about it.</p> <p>Typically, you use a protocol to define what methods you will call on the delegate and the delegate then needs to conform to that protocol. You can also add methods that the delegate doesn't need to implement (optional). When you do so, you'll have to call -respondsToSelector:, because you don't know whether the delegate wants the particular method to be called or not.</p> <p>An example:<br> You have a class that produces something, let's call it <code>Machine</code> and a worker of the class <code>Worker</code>. The machine needs to be adjusted for the task:</p> <pre><code>Machine *machine = [[Machine alloc] init]; [machine prepareWithParameters:myParameters]; </code></pre> <p>Now that we have the machine we want to produce a massive amount of <code>Stuff</code>:</p> <pre><code>[machine produceStuff]; </code></pre> <p>Okay, we're done. But how do we know when an unit of <code>Stuff</code> has been produced? We could have our worker constantly standing beside our machine and wait:</p> <pre><code>while (![machine isFinished]) { if ([machine didProduceStuff]) { Stuff *stuff = [machine producedStuff]; [self doSomethingWithStuff:stuff]; } else { // Get a very large coffee... } } </code></pre> <p>Wouldn't it be great if the machine did inform us automatically, when it's done with producing an unit of <code>Stuff</code>?</p> <pre><code>@protocol MachineDelegate &lt;NSObject&gt; @optional - (void) machine:(Machine *)machine didProduceStuff:(Stuff *)stuff; @end </code></pre> <p>Let's add the <code>worker</code> as a delegate of <code>machine</code>:</p> <pre><code>Worker *worker; Machine *machine = [[Machine alloc] init]; [machine prepareWithParameters:myParameters]; [machine setDelegate:worker]; // worker does conform to &lt;MachineDelegate&gt; [machine produceStuff]; </code></pre> <p>When <code>Machine</code> is done producing something, it will then call:</p> <pre><code>if ([[self delegate] respondsToSelector:@selector(machine:didProduceStuff:)]) [[self delegate] machine:self didProduceStuff:stuff]; </code></pre> <p>The <code>worker</code> will then receive this method and can do something:</p> <pre><code>- (void) machine:(Machine *)machine didProduceStuff:(Stuff *)stuff { [self doSomethingWithStuff:stuff]; if ([machine isFinished]) [self shutDownMachine:machine]; </code></pre> <p>}</p> <p>Isn't that much more efficient and easier for the worker? Now he can do something more productive than standing besides the machine while the machine is still producing. You could now add even more methods to <code>MachineDelegate</code>:</p> <pre><code>@protocol MachineDelegate &lt;NSObject&gt; @required - (void) machineNeedsMaintenance:(Machine *)machine; - (void) machine:(Machine *)machine fatalErrorOccured:(Error *)error; - (BOOL) machine:(Machine *)machine shouldContinueAfterProductionError:(Error *)error; @optional - (void) machineDidEnterEcoMode:(Machine *)machine; - (void) machine:(Machine *)machine didProduceStuff:(Stuff *)stuff; @end </code></pre> <p>Delegates can also be used to change the behavior of an object without subclassing it:</p> <pre><code>@protocol MachineDelegate &lt;NSObject&gt; @required - (Color *) colorForStuffBeingProducedInMachine:(Machine *)machine; - (BOOL) machineShouldGiftWrapStuffWhenDone:(Machine *)machine; @end </code></pre> <p>I hope I could help you understand the benefit of abstracting your code using delegates a little bit.</p>
19,736,008
Twitter Bootstrap: How do I get the selected value of dropdown?
<p>I need to get the value a user selects from a twitter bootstrap dropdown. Once the user selects a value I want the dropdown to display that value. So, the user selects 'pending' then I want to change the selected dropdown value from that and, when the user completes the form, I want to retrieve the selected value. Would someone be able to point me in the right direction?</p> <pre><code>&lt;div class="btn-group"&gt; &lt;i class="dropdown-arrow dropdown-arrow-inverse"&gt;&lt;/i&gt; &lt;button class="btn btn-primary"&gt;status&lt;/button&gt; &lt;button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"&gt; &lt;span class="caret"&gt;&lt;/span&gt; &lt;/button&gt; &lt;ul class="dropdown-menu dropdown-inverse"&gt; &lt;li&gt;&lt;a href="#fakelink"&gt;pending&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#fakelink"&gt;active&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#fakelink"&gt;discontinued&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
19,736,085
4
2
null
2013-11-01 21:54:34.387 UTC
5
2018-08-01 03:53:20.31 UTC
2018-08-01 03:53:20.31 UTC
null
5,640
null
2,525,863
null
1
14
jquery|css|twitter-bootstrap
42,535
<p>Bootstrap provides you with minimum required functionality for your implementation, they aren't dropdowns instead they are mere ul, li's with css applied on it and some events registered in the bootstrap plugin for toggling the button to display them as dropdown. This one you need to do on your own.</p> <p>Set up some identifier to the status button say a className <code>btnStatus</code> and bind a click event to the dropdown links. and do something like this? </p> <pre><code>$('.dropdown-inverse li &gt; a').click(function(e){ $('.btnStatus').text(this.innerHTML); }); </code></pre> <p><strong><a href="http://jsfiddle.net/P9fpd/" rel="noreferrer">Demo</a></strong></p>
19,451,715
Same Navigation Drawer in different Activities
<p>I made a working navigation drawer like it's shown in the tutorial on the <a href="http://developer.android.com" rel="nofollow noreferrer">developer.android.com</a> website. But now, I want to use one Navigation Drawer, i created in the NavigationDrawer.class for multiple Activities in my Application.</p> <p>My question is, if anyone here can make a little Tutorial, which explains, how to use one Navigation drawer for multiple Activities.</p> <p>I read it first at this Answer <a href="https://stackoverflow.com/q/18697966/2876645">Android Navigation Drawer on multiple Activities</a></p> <p>but it didn't work on my Project</p> <pre><code>public class NavigationDrawer extends Activity { public DrawerLayout drawerLayout; public ListView drawerList; private ActionBarDrawerToggle drawerToggle; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) { public void onDrawerClosed(View view) { getActionBar().setTitle(R.string.app_name); } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(R.string.menu); } }; drawerLayout.setDrawerListener(drawerToggle); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); listItems = getResources().getStringArray(R.array.layers_array); drawerList = (ListView) findViewById(R.id.left_drawer); drawerList.setAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.drawer_list_item, android.R.id.text, listItems)); drawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int pos, long arg3) { drawerClickEvent(pos); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } } </code></pre> <p>In this Activity i want to have the Navigation Drawer so I extends 'NavigationDrawer' and in some other Activities i want to User the Same Navigation drawer</p> <pre><code> public class SampleActivity extends NavigationDrawer {...} </code></pre>
19,451,842
13
2
null
2013-10-18 14:07:15.087 UTC
133
2021-11-02 19:28:13.443 UTC
2020-12-06 20:11:52.36 UTC
null
2,876,645
null
2,876,645
null
1
210
android|android-activity|navigation|navigation-drawer|drawer
246,480
<p>If you want a navigation drawer, you should use fragments. I followed this tutorial last week and it works great: </p> <p><a href="http://developer.android.com/training/implementing-navigation/nav-drawer.html" rel="noreferrer">http://developer.android.com/training/implementing-navigation/nav-drawer.html</a></p> <p>You can also download sample code from this tutorial, to see how you can do this.</p> <hr> <p>Without fragments:</p> <p>This is your BaseActivity Code:</p> <pre><code>public class BaseActivity extends Activity { public DrawerLayout drawerLayout; public ListView drawerList; public String[] layers; private ActionBarDrawerToggle drawerToggle; private Map map; protected void onCreate(Bundle savedInstanceState) { // R.id.drawer_layout should be in every activity with exactly the same id. drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) { public void onDrawerClosed(View view) { getActionBar().setTitle(R.string.app_name); } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(R.string.menu); } }; drawerLayout.setDrawerListener(drawerToggle); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); layers = getResources().getStringArray(R.array.layers_array); drawerList = (ListView) findViewById(R.id.left_drawer); View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null); drawerList.addHeaderView(header, null, false); drawerList.setAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.drawer_list_item, android.R.id.text1, layers)); View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate( R.layout.drawer_list_footer, null, false); drawerList.addFooterView(footerView); drawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int pos, long arg3) { map.drawerClickEvent(pos); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } } </code></pre> <p>All the other Activities that needs to have a navigation drawer should extend this Activity instead of Activity itself, example:</p> <pre><code>public class AnyActivity extends BaseActivity { //Because this activity extends BaseActivity it automatically has the navigation drawer //You can just write your normal Activity code and you don't need to add anything for the navigation drawer } </code></pre> <p><b>XML</b></p> <pre><code>&lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;!-- The main content view --&gt; &lt;FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer --&gt; &lt;/FrameLayout&gt; &lt;!-- The navigation drawer --&gt; &lt;ListView android:id="@+id/left_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" android:background="#111"/&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <hr> <p><strong>Edit:</strong></p> <p>I experienced some difficulties myself, so here is a solution if you get NullPointerExceptions. In BaseActivity change the onCreate function to <code>protected void onCreateDrawer()</code>. The rest can stay the same. In the Activities which extend BaseActivity put the code in this order:</p> <pre><code> super.onCreate(savedInstanceState); setContentView(R.layout.activity); super.onCreateDrawer(); </code></pre> <p>This helped me fix my problem, hope it helps!</p> <p>This is how you can create a navigation drawer with multiple activities, if you have any questions feel free to ask.</p> <hr> <p><strong>Edit 2:</strong></p> <p>As said by @GregDan your <strong><code>BaseActivity</code></strong> can also override <code>setContentView()</code> and call onCreateDrawer there:</p> <pre><code>@Override public void setContentView(@LayoutRes int layoutResID) { super.setContentView(layoutResID); onCreateDrawer() ; } </code></pre>
1,275,190
Removing elements from JavaScript arrays
<p>I have the following array setup, i,e:</p> <pre><code>var myArray = new Array(); </code></pre> <p>Using this array, I am creating a breadcrumb menu dynamically as the user adds more menu items. I am also allowing them to removing specific breadcrumb menu items by clicking on the cross alongside eatch breadcrumb menu item.</p> <p>Array may hold the following data:</p> <pre><code>myArray[0] = 'MenuA'; myArray[1] = 'MenuB'; myArray[2] = 'MenuC'; myArray[3] = 'MenuD'; myArray[4] = 'MenuE'; </code></pre> <p>My questions are:</p> <p>a) In JavaScript, how can I remove element [1] from myArray and then recalculate indexes or is this not possible?</p> <p>b) If I don't want menu option MenuB, do I need to splice it to remove it?</p> <p>My problem is, if the user removes menu items as well as create news one at the end, how will the indexes to these elements be spreadout?</p> <p>I just want to be able to remove items but don't know how the array indexes are handled.</p>
1,275,222
5
0
null
2009-08-13 23:17:28.63 UTC
4
2019-08-08 11:34:42.273 UTC
2018-09-03 12:40:36.067 UTC
null
472,495
null
111,479
null
1
4
javascript
39,920
<p>I like <a href="http://ejohn.org/blog/javascript-array-remove/" rel="noreferrer">this implementation</a> of Array.remove, it basically abstracts the use of the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/splice" rel="noreferrer">splice</a> function:</p> <pre><code>// Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from &lt; 0 ? this.length + from : from; return this.push.apply(this, rest); }; </code></pre> <p>Usage:</p> <pre><code>// Remove the second item from the array array.remove(1); // Remove the second-to-last item from the array array.remove(-2); // Remove the second and third items from the array array.remove(1,2); // Remove the last and second-to-last items from the array array.remove(-2,-1); </code></pre>
644,785
Is it possible to get a copyright symbol in C# Console application?
<p>Is it possible to add a copyright symbol or other "special" symbol in any way in a C# console application?</p>
644,793
5
0
null
2009-03-13 22:04:15.817 UTC
2
2017-02-03 10:28:36.4 UTC
null
null
null
P.Bjorklund
70,547
null
1
21
c#|console
42,116
<pre><code>namespace test { class test { public static void Main() { System.Console.WriteLine("©"); } } } </code></pre> <p>works for me flawlessly. Regardless of whether the console window is set to raster fonts or Unicode.</p> <p>If you want to output Unicode, you should set the console output encoding to UTF-8 or Unicode.</p> <pre><code>System.Console.OutputEncoding = System.Text.Encoding.UTF8; </code></pre> <p>or</p> <pre><code>System.Console.OutputEncoding = System.Text.Encoding.Unicode; </code></pre> <p>And if you want to stay clear from source code encoding issues you should specify the character code point directly:</p> <pre><code>System.Console.WriteLine("\u00a9"); </code></pre>
523,540
Difference between JUMP and CALL
<p>How is a JUMP and CALL instruction different? How does it relate to the higher level concepts such as a GOTO or a procedure call? (Am I correct in the comparison?)</p> <p>This is what I think: </p> <p>JUMP or GOTO is a transfer of the control to another location and the control does not automatically return to the point from where it is called. </p> <p>On the other hand, a CALL or procedure/function call returns to the point from where it is called. Due to this difference in their nature, languages typically make use of a stack and a stack frame is pushed to "remember" the location to come back for each procedure called. This behaviour applies to recursive procedures too. In case of tail recursion, there is however no need to "push" a stack frame for <em>each</em> call.</p> <p>Your answers and comments will be much appreciated.</p>
523,550
5
0
null
2009-02-07 09:52:18.913 UTC
13
2019-02-01 18:31:10.49 UTC
2019-02-01 18:31:10.49 UTC
null
7,606,764
user59634
null
null
1
26
functional-programming|recursion|computer-science
37,027
<p>You're mostly right, if you are talking about CALL/JMP in x86 assembly or something similar. The main difference is:</p> <ul> <li>JMP performs a jump to a location, without doing anything else</li> <li>CALL pushes the current instruction pointer on the stack (rather: one after the current instruction), and then JMPs to the location. With a RET you can get back to where you were.</li> </ul> <p>Usually, CALL is just a convenience function implemented using JMP. You could do something like</p> <pre><code> movl $afterJmp, -(%esp) jmp location afterJmp: </code></pre> <p>instead of a CALL.</p>
753,132
How to get the colour of a pixel at X,Y using c#?
<p>How do I get the color of a pixel at X,Y using c#? </p> <p>As for the result, I can convert the results to the color format I need. I am sure there is an API call for this.</p> <p>For any given X,Y on the monitor, I want to get the color of that pixel.</p>
753,157
5
3
null
2009-04-15 18:47:10.16 UTC
10
2019-04-10 09:18:50.54 UTC
2019-01-27 12:04:02.767 UTC
null
1,118,978
null
68,452
null
1
27
c#|api
49,019
<p>To get a pixel color from the <strong>Screen</strong> here's code from <a href="http://www.pinvoke.net/default.aspx/gdi32/GetPixel.html" rel="noreferrer">Pinvoke.net</a>:</p> <pre><code> using System; using System.Drawing; using System.Runtime.InteropServices; sealed class Win32 { [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc); [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos); static public System.Drawing.Color GetPixelColor(int x, int y) { IntPtr hdc = GetDC(IntPtr.Zero); uint pixel = GetPixel(hdc, x, y); ReleaseDC(IntPtr.Zero, hdc); Color color = Color.FromArgb((int)(pixel &amp; 0x000000FF), (int)(pixel &amp; 0x0000FF00) &gt;&gt; 8, (int)(pixel &amp; 0x00FF0000) &gt;&gt; 16); return color; } } </code></pre>
1,030,392
.emacs global-set-key and calling interactive function with argument
<p>In my .emacs i have the following function that transposes a line</p> <pre><code>(defun move-line (n) "Move the current line up or down by N lines." (interactive "p") (let ((col (current-column)) start end) (beginning-of-line) (setq start (point)) (end-of-line) (forward-char) (setq end (point)) (let ((line-text (delete-and-extract-region start end))) (forward-line n) (insert line-text) ;; restore point to original column in moved line (forward-line -1) (forward-char col)))) </code></pre> <p>And I bind a key to it like this</p> <pre><code>(global-set-key (kbd "M-&lt;down&gt;") 'move-line) ;; this is the same as M-x global-set-key &lt;return&gt; </code></pre> <p>However, I want to bind M-up to move-line (-1) But I cant seem to be able to do it correctly:</p> <pre><code>;; M-- M-1 M-x global-set-key &lt;return&gt; </code></pre> <p>How do I define the above using global-set-key to call move-line -1?</p>
1,030,409
5
1
null
2009-06-23 02:33:51.2 UTC
5
2019-04-17 13:23:58.063 UTC
null
null
null
null
123,218
null
1
30
emacs|elisp
12,701
<p>Not minutes after asking the question I figured it out by copy+pasting code. However I have no clue how it works.</p> <pre><code>(global-set-key (kbd "M-&lt;up&gt;") (lambda () (interactive) (move-line -1))) </code></pre>
1,242,190
C++ Memory Efficient Solution for Ax=b Linear Algebra System
<p>I am using Numeric Library Bindings for Boost UBlas to solve a simple linear system. The following works fine, except it is limited to handling matrices A(m x m) for relatively small 'm'.</p> <p>In practice I have a much larger matrix with dimension m= 10^6 (up to 10^7).<br> Is there existing C++ approach for solving Ax=b that uses memory efficiently.</p> <pre><code>#include&lt;boost/numeric/ublas/matrix.hpp&gt; #include&lt;boost/numeric/ublas/io.hpp&gt; #include&lt;boost/numeric/bindings/traits/ublas_matrix.hpp&gt; #include&lt;boost/numeric/bindings/lapack/gesv.hpp&gt; #include &lt;boost/numeric/bindings/traits/ublas_vector2.hpp&gt; // compileable with this command //g++ -I/home/foolb/.boost/include/boost-1_38 -I/home/foolb/.boostnumbind/include/boost-numeric-bindings solve_Axb_byhand.cc -o solve_Axb_byhand -llapack namespace ublas = boost::numeric::ublas; namespace lapack= boost::numeric::bindings::lapack; int main() { ublas::matrix&lt;float,ublas::column_major&gt; A(3,3); ublas::vector&lt;float&gt; b(3); for(unsigned i=0;i &lt; A.size1();i++) for(unsigned j =0;j &lt; A.size2();j++) { std::cout &lt;&lt; "enter element "&lt;&lt;i &lt;&lt; j &lt;&lt; std::endl; std::cin &gt;&gt; A(i,j); } std::cout &lt;&lt; A &lt;&lt; std::endl; b(0) = 21; b(1) = 1; b(2) = 17; lapack::gesv(A,b); std::cout &lt;&lt; b &lt;&lt; std::endl; return 0; } </code></pre>
1,279,744
6
1
null
2009-08-07 00:03:52.12 UTC
15
2013-10-12 10:28:07.527 UTC
2013-10-12 10:28:07.527 UTC
null
2,230,844
null
67,405
null
1
9
c++|boost|linear-algebra|lapack|umfpack
10,506
<p>Short answer: Don't use Boost's <code>LAPACK</code> bindings, these were designed for dense matrices, not sparse matrices, use <code>UMFPACK</code> instead.</p> <p>Long answer: <code>UMFPACK</code> is one of the best libraries for solving Ax=b when A is large and sparse.</p> <ul> <li><a href="http://www.cise.ufl.edu/research/sparse/umfpack/" rel="noreferrer">http://www.cise.ufl.edu/research/sparse/umfpack/</a> </li> <li><a href="http://www.cise.ufl.edu/research/sparse/umfpack/UMFPACK/Doc/QuickStart.pdf" rel="noreferrer">http://www.cise.ufl.edu/research/sparse/umfpack/UMFPACK/Doc/QuickStart.pdf</a></li> </ul> <p>Below is sample code (based on <code>umfpack_simple.c</code>) that generates a simple <code>A</code> and <code>b</code> and solves <code>Ax = b</code>. </p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include "umfpack.h" int *Ap; int *Ai; double *Ax; double *b; double *x; /* Generates a sparse matrix problem: A is n x n tridiagonal matrix A(i,i-1) = -1; A(i,i) = 3; A(i,i+1) = -1; */ void generate_sparse_matrix_problem(int n){ int i; /* row index */ int nz; /* nonzero index */ int nnz = 2 + 3*(n-2) + 2; /* number of nonzeros*/ int *Ti; /* row indices */ int *Tj; /* col indices */ double *Tx; /* values */ /* Allocate memory for triplet form */ Ti = malloc(sizeof(int)*nnz); Tj = malloc(sizeof(int)*nnz); Tx = malloc(sizeof(double)*nnz); /* Allocate memory for compressed sparse column form */ Ap = malloc(sizeof(int)*(n+1)); Ai = malloc(sizeof(int)*nnz); Ax = malloc(sizeof(double)*nnz); /* Allocate memory for rhs and solution vector */ x = malloc(sizeof(double)*n); b = malloc(sizeof(double)*n); /* Construct the matrix A*/ nz = 0; for (i = 0; i &lt; n; i++){ if (i &gt; 0){ Ti[nz] = i; Tj[nz] = i-1; Tx[nz] = -1; nz++; } Ti[nz] = i; Tj[nz] = i; Tx[nz] = 3; nz++; if (i &lt; n-1){ Ti[nz] = i; Tj[nz] = i+1; Tx[nz] = -1; nz++; } b[i] = 0; } b[0] = 21; b[1] = 1; b[2] = 17; /* Convert Triplet to Compressed Sparse Column format */ (void) umfpack_di_triplet_to_col(n,n,nnz,Ti,Tj,Tx,Ap,Ai,Ax,NULL); /* free triplet format */ free(Ti); free(Tj); free(Tx); } int main (void) { double *null = (double *) NULL ; int i, n; void *Symbolic, *Numeric ; n = 500000; generate_sparse_matrix_problem(n); (void) umfpack_di_symbolic (n, n, Ap, Ai, Ax, &amp;Symbolic, null, null); (void) umfpack_di_numeric (Ap, Ai, Ax, Symbolic, &amp;Numeric, null, null); umfpack_di_free_symbolic (&amp;Symbolic); (void) umfpack_di_solve (UMFPACK_A, Ap, Ai, Ax, x, b, Numeric, null, null); umfpack_di_free_numeric (&amp;Numeric); for (i = 0 ; i &lt; 10 ; i++) printf ("x [%d] = %g\n", i, x [i]); free(b); free(x); free(Ax); free(Ai); free(Ap); return (0); } </code></pre> <p>The function <code>generate_sparse_matrix_problem</code> creates the matrix <code>A</code> and the right-hand side <code>b</code>. The matrix is first constructed in triplet form. The vectors Ti, Tj, and Tx fully describe A. Triplet form is easy to create but efficient sparse matrix methods require Compressed Sparse Column format. Conversion is performed with <code>umfpack_di_triplet_to_col</code>. </p> <p>A symbolic factorization is performed with <code>umfpack_di_symbolic</code>. A sparse LU decomposition of <code>A</code> is performed with <code>umfpack_di_numeric</code>. The lower and upper triangular solves are performed with <code>umfpack_di_solve</code>.</p> <p>With <code>n</code> as 500,000, on my machine, the entire program takes about a second to run. Valgrind reports that 369,239,649 bytes (just a little over 352 MB) were allocated. </p> <p>Note this <a href="http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/matrix_sparse.htm" rel="noreferrer">page</a> discusses Boost's support for sparse matrices in Triplet (Coordinate) and Compressed format. If you like, you can write routines to convert these boost objects to the simple arrays <code>UMFPACK</code> requires as input.</p>
198,343
How can I get the size of the Transaction Log in SQL 2005 programmatically?
<p>We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log. </p> <p>Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?</p>
7,085,251
6
0
null
2008-10-13 17:29:15.79 UTC
4
2017-02-16 20:12:47.083 UTC
null
null
null
Greylurk
21,973
null
1
22
sql-server|tsql
79,304
<p>I used your code but, there was an error converting to an int. "Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type int." So wherever there was an "*8" I changed it to *8.0 and the code works perfectly.</p> <pre><code>SELECT (size * 8.0)/1024.0 AS size_in_mb , CASE WHEN max_size = -1 THEN 9999999 -- Unlimited growth, so handle this how you want ELSE (max_size * 8.0)/1024.0 END AS max_size_in_mb FROM YOURDBNAMEHERE.sys.database_files WHERE data_space_id = 0 </code></pre>
1,298,322
Wrong ordering in generated table in jpa
<p>This (should) be a rather simple thing to do, however I am struggling.</p> <p>I want a table to be generated like this:</p> <pre> id organizationNumber name </pre> <p>However, when I look in the database, I see that the ordering is wrong. Does anybody know how I can force hibernate/jpa to generate the table with correct ordering? </p> <pre> desc Organization; +--------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+----------------+ | id | bigint(20) | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | organizationNumber | varchar(255) | NO | UNI | NULL | | +--------------------+--------------+------+-----+---------+----------------+ </pre> <p>This is how my entity bean looks like: </p> <pre><code>@Entity @NamedQuery(name = "allOrganizations", query = "SELECT org FROM Organization org order by name") public class Organization { private Long id; private String organizationNumber; private String name; public Organization() { } public Organization(String name) { this.name = name; } @Id @GeneratedValue public Long getId() { return id; } @SuppressWarnings("unused") private void setId(Long id) { this.id = id; } @NotEmpty @Column(unique=true, nullable=false) public String getOrganizationNumber() { return organizationNumber; } public void setOrganizationNumber(String organizationNumber) { this.organizationNumber = organizationNumber; } @NotEmpty @Column(nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return this.name + " " + this.organizationNumber; } } </code></pre>
1,298,327
6
0
null
2009-08-19 07:34:29.243 UTC
15
2022-06-11 06:24:54.113 UTC
2019-12-12 20:39:01.93 UTC
null
1,281,433
null
37,298
null
1
77
java|hibernate|jpa
43,100
<p>Hibernate generates columns in <strong>alphabetical</strong> order. According to <a href="https://forum.hibernate.org/viewtopic.php?f=6&amp;t=974532" rel="nofollow noreferrer">this post</a> the reason is given as:</p> <blockquote> <p>It is sorted to ensurce deterministic ordering across clusters.</p> <p>We can't rely on the vm to return the methods in the same order every time so we had to do something.</p> </blockquote> <p>Apparently it used to be in the order of occurrence but this changed between 3.2.0 GA and 3.2.1 GA.</p> <p>I also found <a href="https://issues.redhat.com/browse/HIBERNATE-112" rel="nofollow noreferrer">Schema auto generation creates columns in alphabetical order for compound primary keys</a> and this seems to be like your problem. This ticket is about the order changing in primary keys and that negatively impacts index performance.</p> <p>There is no fix for this other than a workaround of naming the columns in such a way that they come out in the correct order (no, I'm not kidding).</p>
52,641,981
Get first Monday in Calendar month
<p>I am trapped in a Calendar/TimeZone/DateComponents/Date hell and my mind is spinning.</p> <p>I am creating a diary app and I want it to work worldwide (with a iso8601 calendar).</p> <p>I am trying to create a calendar view on iOS similar to the macOS calendar so that my user can navigate their diary entries (notice the 7x6 grid for each month):</p> <p><a href="https://i.stack.imgur.com/EQyye.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EQyye.png" alt="/Users/adamwaite/Desktop/Screenshot 2018-10-04 at 08.22.24.png"></a></p> <p>To get the 1st of the month I can do something like the following:</p> <pre><code>func firstOfMonth(month: Int, year: Int) -&gt; Date { let calendar = Calendar(identifier: .iso8601) var firstOfMonthComponents = DateComponents() // firstOfMonthComponents.timeZone = TimeZone(identifier: "UTC") // &lt;- fixes daylight savings time firstOfMonthComponents.calendar = calendar firstOfMonthComponents.year = year firstOfMonthComponents.month = month firstOfMonthComponents.day = 01 return firstOfMonthComponents.date! } (1...12).forEach { print(firstOfMonth(month: $0, year: 2018)) /* Gives: 2018-01-01 00:00:00 +0000 2018-02-01 00:00:00 +0000 2018-03-01 00:00:00 +0000 2018-03-31 23:00:00 +0000 2018-04-30 23:00:00 +0000 2018-05-31 23:00:00 +0000 2018-06-30 23:00:00 +0000 2018-07-31 23:00:00 +0000 2018-08-31 23:00:00 +0000 2018-09-30 23:00:00 +0000 2018-11-01 00:00:00 +0000 2018-12-01 00:00:00 +0000 */ } </code></pre> <p>There's an immediate issue here with daylight savings time. That issue can be "fixed" by uncommenting the commented line and forcing the date to be calculated in UTC. I feel as though by forcing it to UTC the dates become invalid when viewing the calendar view in different time zones.</p> <p>The real question is though: How do I get the first Monday in the week containing the 1st of the month? For example, how do I get Monday 29th February, or Monday 26th April? (see the macOS screenshot). To get the end of the month, do I just add on 42 days from the start? Or is that naive?</p> <p><strong>Edit</strong></p> <p>Thanks to the current answers, but we're still stuck.</p> <p>The following works, until you take daylight savings time into account:</p> <p><a href="https://i.stack.imgur.com/DINaG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DINaG.png" alt="almost"></a></p>
52,654,703
4
7
null
2018-10-04 08:09:19.347 UTC
15
2021-03-19 16:26:37.743 UTC
2018-10-04 12:16:31.207 UTC
null
1,050,447
null
1,050,447
null
1
11
ios|swift|date|calendar|timezone
2,443
<p>OK, this is going to be a long and involved answer (hooray for you!).</p> <p>Overall you're on the right track but there are a couple of subtle errors going on.</p> <h2>Conceptualizing Dates</h2> <p>It's pretty well-established by now (I hope) that <code>Date</code> represents an instant in time. What's not quite as well-established is the inverse. A <code>Date</code> represents an instant, but what represents a calendar value?</p> <p>When you think about it, a "day" or an "hour" (or even a "month") are a <em>range</em>. They're values that represent all possible instants between a start instant and an end instant.</p> <p>For this reason, I find it most helpful to think about <em>ranges</em> when I'm dealing with calendar values. In other words by asking "what is the range for this minute/hour/day/week/month/year?" etc.</p> <p>With this, I think you'll find it's easier to understand what's going on. You understand a <code>Range&lt;Int&gt;</code> already, right? So a <code>Range&lt;Date&gt;</code> is similarly intuitive.</p> <p>Fortunately, there's API on <code>Calendar</code> to get the range. Unfortunately we don't quite get to just use <code>Range&lt;Date&gt;</code> because of holdover API from the Objective-C days. But we get <code>NSDateInterval</code>, which is effectively the same thing.</p> <p>You ask for ranges by asking the <code>Calendar</code> for the range of the hour/day/week/month/year that contains a particular instant, like this:</p> <pre><code>let now = Date() let calendar = Calendar.current let today = calendar.dateInterval(of: .day, for: now) </code></pre> <p>Armed with this, you can get the range of just about anything:</p> <pre><code>let units = [Calendar.Component.second, .minute, .hour, .day, .weekOfMonth, .month, .quarter, .year, .era] for unit in units { let range = calendar.dateInterval(of: unit, for: now) print("Range of \(unit): \(range)") } </code></pre> <p>At the time I'm writing this, it prints:</p> <pre><code>Range of second: Optional(2018-10-04 19:50:10 +0000 to 2018-10-04 19:50:11 +0000) Range of minute: Optional(2018-10-04 19:50:00 +0000 to 2018-10-04 19:51:00 +0000) Range of hour: Optional(2018-10-04 19:00:00 +0000 to 2018-10-04 20:00:00 +0000) Range of day: Optional(2018-10-04 06:00:00 +0000 to 2018-10-05 06:00:00 +0000) Range of weekOfMonth: Optional(2018-09-30 06:00:00 +0000 to 2018-10-07 06:00:00 +0000) Range of month: Optional(2018-10-01 06:00:00 +0000 to 2018-11-01 06:00:00 +0000) Range of quarter: Optional(2018-10-01 06:00:00 +0000 to 2019-01-01 07:00:00 +0000) Range of year: Optional(2018-01-01 07:00:00 +0000 to 2019-01-01 07:00:00 +0000) Range of era: Optional(0001-01-03 00:00:00 +0000 to 139369-07-19 02:25:04 +0000) </code></pre> <p>You can see for the ranges of the respective units getting displayed. There are two things to point out here:</p> <ol> <li><p>This method returns an <em>optional</em> (<code>DateInterval?</code>), because there might be weird situations where it fails. I can't think of any off the top of my head, but calendars are fickle things, so heads up about this.</p></li> <li><p>Asking for an era's range is usually a nonsensical operation, even though eras are vital to properly constructing dates. It's difficult to have much precision with eras outside of certain calendars (primarily the Japanese calendar), so that value saying "The Common Era (CE or AD) started on January 3rd of the year 1" is probably wrong, but we can't really do anything about that. Also, of course, we have no idea when the current era will end, so we just assume it goes on forever.</p></li> </ol> <h2>Printing <code>Date</code> values</h2> <p>This brings me to the next point, about printing dates. I noticed this in your code and I think it might be the source of some of your issues. I applaud your efforts to account for the abomination that is Daylight Saving Time, but I think you're getting caught up on something that isn't actually a bug, but is this:</p> <p><code>Dates</code> <em>always</em> print in UTC.</p> <p>Always always always.</p> <p>This is because they are instants in time, and they are the <em>same instant</em> regardless of whether you're in California or Djibouti or Khatmandu or whatever. A <code>Date</code> value does <em>not</em> have a timezone. It's really just an offset from another known point in time. However, printing <code>560375786.836208</code> as a <code>Date's</code> description doesn't seem that useful to humans, so the creators of the API made it print as a Gregorian date relative to the UTC timezone.</p> <p>If you want to print a date, <em>even for debugging</em>, you're almost definitely going to need a <code>DateFormatter</code>.</p> <h2><code>DateComponents.date</code></h2> <p>This isn't a problem with your code per-say, but is more of a heads up. The <code>.date</code> property on <code>DateComponents</code> does not guarantee to return the first instant that matches the components specified. It does not guarantee to return the last instant that matches the components. All it does is guarantee that, if it can find an answer, it will give you a <code>Date</code> <em>somewhere in the range</em> of the specified units.</p> <p>I don't think you're technically relying on this in your code, but it's a good thing to be aware of, and I've seen this misunderstanding causing bugs in software.</p> <hr> <p>With all of this in mind, let's take a look at what you're wanting to do:</p> <ol> <li>You want to know the range of the year</li> <li>You want to know all of the months in the year</li> <li>You want to know all of the days in a month</li> <li>You want to know the week that contains the first day of the month</li> </ol> <p>So, based on what we've learned about ranges, this should be pretty straight-forward now, and interestingly, we can do it all without needing a single <code>DateComponents</code> value. In the code below, I'll be force-unwrapping values for brevity. In your actual code you'll probably want to have better error handling.</p> <h2>The range of the year</h2> <p>This is easy:</p> <pre><code>let yearRange = calendar.dateInterval(of: .year, for: now)! </code></pre> <h2>The months in the year</h2> <p>This is a little bit more complicated, but not too bad.</p> <pre><code>var monthsOfYear = Array&lt;DateInterval&gt;() var startOfCurrentMonth = yearRange.start repeat { let monthRange = calendar.dateInterval(of: .month, for: startOfCurrentMonth)! monthsOfYear.append(monthRange) startOfCurrentMonth = monthRange.end.addingTimeInterval(1) } while yearRange.contains(startOfCurrentMonth) </code></pre> <p>Basically, we're going to start with the first instant of the year and ask the calendar for the month that contains that instant. Once we've got that, we'll get the final instant of that month and add one second to it to (ostensibly) shift it into the next month. Then we'll get the range of the month that contains that instant, and so on. Repeat until we have a value that is no longer in the year, which means we've aggregated all of the month ranges in the initial year.</p> <p>When I run this on my machine, I get this result:</p> <pre><code>[ 2018-01-01 07:00:00 +0000 to 2018-02-01 07:00:00 +0000, 2018-02-01 07:00:00 +0000 to 2018-03-01 07:00:00 +0000, 2018-03-01 07:00:00 +0000 to 2018-04-01 06:00:00 +0000, 2018-04-01 06:00:00 +0000 to 2018-05-01 06:00:00 +0000, 2018-05-01 06:00:00 +0000 to 2018-06-01 06:00:00 +0000, 2018-06-01 06:00:00 +0000 to 2018-07-01 06:00:00 +0000, 2018-07-01 06:00:00 +0000 to 2018-08-01 06:00:00 +0000, 2018-08-01 06:00:00 +0000 to 2018-09-01 06:00:00 +0000, 2018-09-01 06:00:00 +0000 to 2018-10-01 06:00:00 +0000, 2018-10-01 06:00:00 +0000 to 2018-11-01 06:00:00 +0000, 2018-11-01 06:00:00 +0000 to 2018-12-01 07:00:00 +0000, 2018-12-01 07:00:00 +0000 to 2019-01-01 07:00:00 +0000 ] </code></pre> <p>Again, it's important to point out here that these dates are in UTC, even though I am in the Mountain Timezone. Because of that, the hour shifts between 07:00 and 06:00, because the Mountain Timezone is either 7 or 6 hours behind UTC, depending on whether we've observing DST. So these values are accurate for my calendar's timezone.</p> <h2>The days in a month</h2> <p>This is just like the previous code:</p> <pre><code>var daysInMonth = Array&lt;DateInterval&gt;() var startOfCurrentDay = currentMonth.start repeat { let dayRange = calendar.dateInterval(of: .day, for: startOfCurrentDay)! daysInMonth.append(dayRange) startOfCurrentDay = dayRange.end.addingTimeInterval(1) } while currentMonth.contains(startOfCurrentDay) </code></pre> <p>And when I run this, I get this:</p> <pre><code>[ 2018-10-01 06:00:00 +0000 to 2018-10-02 06:00:00 +0000, 2018-10-02 06:00:00 +0000 to 2018-10-03 06:00:00 +0000, 2018-10-03 06:00:00 +0000 to 2018-10-04 06:00:00 +0000, ... snipped for brevity ... 2018-10-29 06:00:00 +0000 to 2018-10-30 06:00:00 +0000, 2018-10-30 06:00:00 +0000 to 2018-10-31 06:00:00 +0000, 2018-10-31 06:00:00 +0000 to 2018-11-01 06:00:00 +0000 ] </code></pre> <h2>The week containing a month's start</h2> <p>Let's return to that <code>monthsOfYear</code> array we created above. We'll use that to figure out the weeks for each month:</p> <pre><code>for month in monthsOfYear { let weekContainingStart = calendar.dateInterval(of: .weekOfMonth, for: month.start)! print(weekContainingStart) } </code></pre> <p>And for my timezone, this prints:</p> <pre><code>2017-12-31 07:00:00 +0000 to 2018-01-07 07:00:00 +0000 2018-01-28 07:00:00 +0000 to 2018-02-04 07:00:00 +0000 2018-02-25 07:00:00 +0000 to 2018-03-04 07:00:00 +0000 2018-04-01 06:00:00 +0000 to 2018-04-08 06:00:00 +0000 2018-04-29 06:00:00 +0000 to 2018-05-06 06:00:00 +0000 2018-05-27 06:00:00 +0000 to 2018-06-03 06:00:00 +0000 2018-07-01 06:00:00 +0000 to 2018-07-08 06:00:00 +0000 2018-07-29 06:00:00 +0000 to 2018-08-05 06:00:00 +0000 2018-08-26 06:00:00 +0000 to 2018-09-02 06:00:00 +0000 2018-09-30 06:00:00 +0000 to 2018-10-07 06:00:00 +0000 2018-10-28 06:00:00 +0000 to 2018-11-04 06:00:00 +0000 2018-11-25 07:00:00 +0000 to 2018-12-02 07:00:00 +0000 </code></pre> <p>One thing you'll notice here is that the this has <em>Sunday</em> as the first day of the week. In your screenshot, for example, you have the week containing Feburary 1st starting on the 29th.</p> <p>That behavior is governed by the <code>firstWeekday</code> property on <code>Calendar</code>. By default, that value is probably <code>1</code> (depending on your locale), indicating that weeks start on Sunday. If you want your calendar to do computations where a week starts on <em>Monday</em>, then you'll change the value of that property to <code>2</code>:</p> <pre><code>var weeksStartOnMondayCalendar = calendar weeksStartOnMondayCalendar.firstWeekday = 2 for month in monthsOfYear { let weekContainingStart = weeksStartOnMondayCalendar.dateInterval(of: .weekOfMonth, for: month.start)! print(weekContainingStart) } </code></pre> <p>Now when I run that code, I see that the week containing Feburary 1st "starts" on January 29th:</p> <pre><code>2018-01-01 07:00:00 +0000 to 2018-01-08 07:00:00 +0000 2018-01-29 07:00:00 +0000 to 2018-02-05 07:00:00 +0000 2018-02-26 07:00:00 +0000 to 2018-03-05 07:00:00 +0000 2018-03-26 06:00:00 +0000 to 2018-04-02 06:00:00 +0000 2018-04-30 06:00:00 +0000 to 2018-05-07 06:00:00 +0000 2018-05-28 06:00:00 +0000 to 2018-06-04 06:00:00 +0000 2018-06-25 06:00:00 +0000 to 2018-07-02 06:00:00 +0000 2018-07-30 06:00:00 +0000 to 2018-08-06 06:00:00 +0000 2018-08-27 06:00:00 +0000 to 2018-09-03 06:00:00 +0000 2018-10-01 06:00:00 +0000 to 2018-10-08 06:00:00 +0000 2018-10-29 06:00:00 +0000 to 2018-11-05 07:00:00 +0000 2018-11-26 07:00:00 +0000 to 2018-12-03 07:00:00 +0000 </code></pre> <hr> <h2>Final Thoughts</h2> <p>With all of this, you have all the tools you'll need to build the same UI as Calendar.app shows.</p> <p>As an added bonus, all of the code I've posted here works <em>regardless of your calendar, timezone, and locale</em>. It'll work to build UIs for the Japanese calendar, the Coptic calendars, the Hebrew calendar, ISO8601, etc. It'll work in any timezone, and it'll work in any locale.</p> <p>Additionally, having all the <code>DateInterval</code> values like this will likely make implementing your app easier, because doing a "range contains" check is the sort of check you <em>want</em> to be doing when making a calendar app.</p> <p>The only other thing is to make sure you use <code>DateFormatter</code> when <em>rendering</em> these values into a <code>String</code>. Please don't pull out the individual date components.</p> <p>If you have follow-up questions, post them as new questions and <code>@mention</code> me in a comment.</p>
13,486,353
SQL -How to add an auto incremental id in a auto generated temporary table
<p>I have a query like below and it generate a temporary table automatically based on parameter. So, the number of column of this table can be vary. Now , i need to add an auto incremental id column into this table.How i do it?</p> <pre><code>SELECT @SourceFields INTO ##StoreSourceInfo FROM testdb.dbo.@SourceTable </code></pre> <p>Note: 1) Number of source field &amp; name of table pass using the parameter <code>@SourceFields &amp; @SourceTable</code>. 2) So, the number of column can be vary on ##StoreSourceInfo table.</p> <p><strong>Current Result:</strong></p> <p><code>select * from ##StoreSourceInfo</code> shows only the available column.</p> <p><strong>Expected Result:</strong> <code>select * from ##StoreSourceInfo</code> query will show <strong>an additional auto incremental id column</strong> &amp; all rest of the column available in the temp table.</p> <p>Hope you get me. Thanks in advance.</p>
13,486,523
4
2
null
2012-11-21 04:26:27.213 UTC
1
2015-06-12 07:04:14.167 UTC
null
null
null
null
87,238
null
1
5
sql|sql-server
45,610
<p>Use the identity function. See the link for an example. <a href="http://msdn.microsoft.com/en-us/library/ms189838.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms189838.aspx</a></p>
35,475,884
How to hide ToolBar when I scrolling content up?
<p>I am trying to hide my tool bar when I scroll my text and image with content. Here I use scrollView for getting scroll content. When I scroll content up, how to hide the tool bar?</p> <p>Here is my XMl code:</p> <p>content_main.XML:</p> <pre><code>&lt;android.support.v4.widget.NestedScrollView xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; app:layout_behavior=&quot;@string/appbar_scrolling_view_behavior&quot;&gt; &lt;LinearLayout android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;LinearLayout android:paddingTop=&quot;?android:attr/actionBarSize&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:layout_marginLeft=&quot;10dp&quot; android:layout_marginRight=&quot;10dp&quot; android:id=&quot;@+id/textone&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:textSize=&quot;23dp&quot; android:textStyle=&quot;bold&quot; android:text=&quot;hello world jheds sdjhs jds sjbs skjs ksjs kksjs ksj sdd dskd js sk &quot;/&gt; &lt;ImageView android:id=&quot;@+id/imge&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;250dp&quot; android:src=&quot;@drawable/imag_bg&quot;/&gt; &lt;TextView android:id=&quot;@+id/texttwo&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:layout_marginLeft=&quot;10dp&quot; android:layout_marginRight=&quot;10dp&quot; android:text=&quot;Pretty good, the Toolbar is moving along with the list and getting back just as we expect it to. This is thanks to the restrictions that we put on the mToolbarOffset variable. If we would omit checking if it’s bigger than 0 and lower than mToolbarHeight then when we would scroll up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing. up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing up our list, the Toolbar would move along far away off the screen, so to show it back you would have to scroll the list down to 0. Right now it just scrolls up to mToolbarHeight position and not more so it’s “sitting” right above the list all of the time and if we start scrolling down, we can see it immediately showing It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug It works pretty well, but this is not what we want. It feels weird that you can stop it in the middle of the scroll and the Toolbar will stay half visible. Actually this is how it’s done in Google Play Games app which I consider as a bug.&quot;/&gt; &lt;/LinearLayout&gt; &lt;View android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;30dp&quot; /&gt; &lt;LinearLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;Button android:text=&quot;hai&quot; android:layout_width=&quot;160dp&quot; android:layout_height=&quot;match_parent&quot; /&gt; &lt;Button android:text=&quot;hello&quot; android:layout_width=&quot;160dp&quot; android:layout_height=&quot;match_parent&quot; /&gt; &lt;/LinearLayout&gt; </code></pre> <p>&lt;/android.support.v4.widget.NestedScrollView&gt;</p> <p>activity_main.XML</p> <pre><code>&lt;android.support.design.widget.AppBarLayout android:layout_height=&quot;wrap_content&quot; android:layout_width=&quot;match_parent&quot; android:theme=&quot;@style/AppTheme.AppBarOverlay&quot;&gt; &lt;android.support.v7.widget.Toolbar android:id=&quot;@+id/toolbar&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;?attr/actionBarSize&quot; android:background=&quot;?attr/colorPrimary&quot; app:popupTheme=&quot;@style/AppTheme.PopupOverlay&quot; /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;include layout=&quot;@layout/content_main&quot; /&gt; </code></pre> <p><a href="https://i.stack.imgur.com/4CN3S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4CN3S.png" alt="here my image" /></a></p>
35,477,859
5
2
null
2016-02-18 08:03:35.303 UTC
11
2021-12-17 23:47:54.85 UTC
2020-12-19 19:56:21.21 UTC
null
1,783,163
null
5,852,278
null
1
39
android|android-support-library|android-toolbar|android-support-design
69,572
<p>you have to do many changes in your both layout. first use <code>CoordinatorLayout</code> in <code>activity_main.XML</code> like below(change theme as per your requirement).</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;include layout="@layout/content_main" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>in <code>content_main.XML</code> use <code>android.support.v4.widget.NestedScrollView</code> instead of <code>ScrollView</code>. </p> <p>also use <code>app:layout_behavior="@string/appbar_scrolling_view_behavior"</code> inside <code>android.support.v4.widget.NestedScrollView</code> like below.</p> <pre><code>&lt;android.support.v4.widget.NestedScrollView xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" app:layout_behavior="@string/appbar_scrolling_view_behavior"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;TextView android:id="@+id/textone" android:layout_width="match_parent" android:layout_height="match_parent" android:text="hello world jheds sdjhs jds sjbs skjs ksjs kksjs ksj sdd dskd js sk " android:textSize="25dp" android:textStyle="bold" /&gt; /// Add your other code here &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; </code></pre>
21,021,684
ASP.NET MVC data annotations attribute Range set from another property value
<p>Hi I have following in my Asp.net MVc Model</p> <p>TestModel.cs</p> <pre><code>public class TestModel { public double OpeningAmount { get; set; } [Required(ErrorMessage="Required")] [Display(Name = "amount")] [Range(0 , double.MaxValue, ErrorMessage = "The value must be greater than 0")] public string amount { get; set; } } </code></pre> <p>Now from my controller "OpeningAmount " is assign .</p> <p>Finaly when I submit form I want to check that "amount" must be greater than "OpeningAmonut" . so want to set Range dynamically like</p> <pre><code>[Range(minimum = OpeningAmount , double.MaxValue, ErrorMessage = "The value must be greater than 0")] </code></pre> <p>I do not want to use only Jquery or javascript because it will check only client side so possible I can set Range attribute minimum dynamically than it would be great for.</p>
21,021,807
2
5
null
2014-01-09 13:32:12.143 UTC
3
2016-06-13 14:50:57.653 UTC
2014-01-09 15:04:11.12 UTC
null
438,180
null
2,318,354
null
1
9
c#|asp.net-mvc|data-annotations
55,147
<p>There's no built-in attribute which can work with dependence between properties.</p> <p>So if you want to work with attributes, you'll have to write a custom one.</p> <p>Se <a href="http://nickstips.wordpress.com/2011/11/05/asp-net-mvc-lessthan-and-greaterthan-validation-attributes/" rel="nofollow">here</a> for an example of what you need.</p> <p>You can also take a look at <a href="http://dataannotationsextensions.org/" rel="nofollow">dataannotationsextensions.org</a></p> <p>Another solution would be to work with a validation library, like (the very nice) <a href="http://fluentvalidation.codeplex.com/" rel="nofollow">FluentValidation</a> .</p>
33,088,297
Serialize an object directly to a JObject instead of to a string in json.net
<p>How might one serialize an object directly to a <code>JObject</code> instance in JSON.Net? What is typically done is to convert the object directly to a json <em>string</em> like so:</p> <pre><code>string jsonSTRINGResult = JsonConvert.SerializeObject(someObj); </code></pre> <p>One could then <em>deserialize</em> that back to a <code>JObject</code> as follows:</p> <pre><code>JObject jObj = JsonConvert.DeserializeObject&lt;JObject&gt;(jsonSTRINGResult); </code></pre> <p>That seems to work, but it would seem like this way has a double performance hit (serialize and then deserialize). Does <code>SerializeObject</code> internally use a <code>JObject</code> that can be accessed somehow? Or is there some way to just serialize directly to a <code>JObject</code>?</p>
33,088,540
3
5
null
2015-10-12 18:57:01.307 UTC
6
2021-10-18 11:40:39.417 UTC
2015-10-12 19:18:35.707 UTC
null
264,031
null
264,031
null
1
45
c#|json|serialization|json.net
37,765
<p>You can use <code>FromObject</code> static method of <code>JObject</code> </p> <pre><code>JObject jObj = JObject.FromObject(someObj) </code></pre> <p><a href="http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_FromObject.htm" rel="noreferrer">http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_FromObject.htm</a></p>
2,092,005
When to use static string vs. #define
<p>I am a little confused as to when it's best to use:</p> <pre><code>static NSString *AppQuitGracefullyKey = @"AppQuitGracefully"; </code></pre> <p>instead of</p> <pre><code>#define AppQuitGracefullyKey @"AppQuitGracefully" </code></pre> <p>I've seen questions like this for C or C++, and I think what's different here is that this is specifically for Objective C, utilizing an object, and on a device like the iPhone, there may be stack, code space or memory issues that I don't yet grasp.</p> <p>One usage would be:</p> <pre><code>appQuitGracefully = [[NSUserDefaults standardUserDefaults] integerForKey: AppQuitGracefullyKey]; </code></pre> <p>Or it is just a matter of style?</p> <p>Thanks.</p>
2,092,029
6
0
null
2010-01-19 08:12:39.81 UTC
16
2015-07-02 12:38:44.703 UTC
null
null
null
null
86,020
null
1
45
objective-c|cocoa|cocoa-touch|xcode
33,418
<p>If you use a static, the compiler will embed exactly one copy of the string in your binary and just pass pointers to that string around, resulting in more compact binaries. If you use a #define, there will be a separate copy of the string stored in the source on each use. Constant string coalescing will handle many of the dups but you're making the linker work harder for no reason. </p>
1,790,245
In what order does a C# for each loop iterate over a List<T>?
<p>I was wondering about the order that a foreach loop in C# loops through a <code>System.Collections.Generic.List&lt;T&gt;</code> object.</p> <p>I found <a href="https://stackoverflow.com/questions/678162/sort-order-when-using-foreach-on-an-array-list-etc">another question</a> about the same topic, but I do not feel that it answers my question to my satisfaction.</p> <p>Someone states that no order is defined. But as someone else states, the order it traverses an array is fixed (from 0 to Length-1). <a href="http://msdn.microsoft.com/en-us/library/aa664754(VS.71).aspx" rel="noreferrer">8.8.4 The foreach statement</a></p> <p>It was also said that the same holds for any standard classes with an order (e.g. <code>List&lt;T&gt;</code>). I can not find any documentation to back that up. So for all I know it might work like that now, but maybe in the next .NET version it will be different (even though it might be unlikely). </p> <p>I have also looked at the <a href="http://msdn.microsoft.com/en-us/library/x854yt9s.aspx" rel="noreferrer"><code>List(t).Enumerator</code></a> documentation without luck.</p> <p><a href="https://stackoverflow.com/questions/1376934/java-for-each-loop-sort-order">Another related question</a> states that for Java, it is specifically mentioned in the documentation: </p> <blockquote> <p><code>List.iterator()</code>returns an iterator over the elements in this list in proper sequence."</p> </blockquote> <p>I am looking for something like that in the C# documentation.</p> <p>Thanks in advance.</p> <p>Edit: Thank you for all you for all your answers (amazing how fast I got so many replies). What I understand from all the answers is that <code>List&lt;T&gt;</code> does always iterate in the order of its indexing. But I still would like to see a clear peace of documentation stating this, similar to the <a href="http://java.sun.com/javase/6/docs/api/java/util/List.html#iterator()" rel="noreferrer">Java documentation on <code>List</code></a>.</p>
57,523,016
6
0
null
2009-11-24 14:00:18.39 UTC
9
2019-08-16 10:27:54.523 UTC
2019-01-26 03:03:52.01 UTC
null
2,370,483
null
210,336
null
1
100
c#|foreach|operator-precedence
67,097
<p>On <a href="https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,d3661cf752ff3f44" rel="noreferrer">Microsoft Reference Source page</a> for <code>List&lt;T&gt;</code> Enumerator it is explicitly stated that the iteration is done from 0 to Length-1:</p> <pre><code>internal Enumerator(List&lt;T&gt; list) { this.list = list; index = 0; version = list._version; current = default(T); } public bool MoveNext() { List&lt;T&gt; localList = list; if (version == localList._version &amp;&amp; ((uint)index &lt; (uint)localList._size)) { current = localList._items[index]; index++; return true; } return MoveNextRare(); } </code></pre> <p>Hope it's still relevant for somebody</p>
1,756,188
How to Use SHA1 or MD5 in C#?(Which One is Better in Performance and Security for Authentication)
<p>In C# how we can use SHA1 automatically?<br>Is SHA1 better than MD5?(We use hashing for user name and password and need speed for authentication)</p>
1,756,222
7
6
null
2009-11-18 13:58:40.32 UTC
11
2016-08-12 09:59:57.46 UTC
2013-02-23 08:10:30.797 UTC
null
140,934
null
140,934
null
1
25
c#|.net|authentication|md5|sha1
62,687
<p>Not sure what you mean by automatically, but you should really use <code>SHA256</code> and higher. Also <strong>always</strong> <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)" rel="noreferrer">use a Salt</a> (<a href="http://www.dijksterhuis.org/creating-salted-hash-values-in-c/" rel="noreferrer">code</a>) with your hashes. A side note, after time has passed, using hardened hashes is far better than using a plain speed-based hashing function. I.e.: hashing over a few hundred iterations, or using already proven hashing functions such as <code>bcrypt</code> (which is mentioned below I believe). A code sample for using a SHA256 hash function in .NET is as follows:</p> <pre><code>byte[] data = new byte[DATA_SIZE]; byte[] result; using(SHA256 shaM = new SHA256Managed()) { result = shaM.ComputeHash(data); } </code></pre> <p>Will do the trick for you using SHA256 and is found at <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256(VS.71).aspx" rel="noreferrer">MSDN</a>.</p> <hr> <p>Sidenote on the "cracking" of SHA1: <a href="http://www.zdnet.com/blog/ou/putting-the-cracking-of-sha-1-in-perspective/409" rel="noreferrer">Putting the cracking of SHA-1 in perspective</a></p>
1,813,865
Why does C have a distinction between -> and .?
<p>OK, this is of no serious consequence, but it's been bugging me for a while: Is there a reason for the distinction between the <code>-&gt;</code> and <code>.</code> operators?</p> <p>Of course, the current rule is that <code>.</code> acts on a struct, and <code>-&gt;</code> acts on a pointer-to-struct (or union). But here's how it works in practice. Let <code>s</code> be a struct incuding an element <code>x</code>, and let <code>ps</code> be a pointer to a struct of the same form.</p> <p>If you write</p> <pre><code>s-&gt;x </code></pre> <p>the compiler will spit out a warning in the way of</p> <blockquote> <p>You meant s.x. Please retype that and recompile.</p> </blockquote> <p>If you write</p> <pre><code>ps.x </code></pre> <p>the compiler will spit out a warning in the way of</p> <blockquote> <p>You meant ps->x. Please retype that and recompile.</p> </blockquote> <p>Because the compiler knows the type of both <code>s</code> and <code>ps</code> at compile time, it has all the information it needs to interpret what the correct operator would be. I suspect that this isn't like other warnings (like a missing semicolon), in that there is no ambiguity about the correct fix.</p> <p>So here's a hypothetical proposal to the C1x standards committee (that would never be considered, because the ISO is on a conservative streak):</p> <blockquote> <p>Given the expression lhs.rhs, if lhs is a struct or union type, then the expression shall refer to the element of lhs named rhs. If lhs is of type pointer-to-struct or -union, then this shall be interpreted as (*lhs).rhs.</p> </blockquote> <p>This would certainly save us all time, and make it easier for people to learn C [and I've taught enough C to say with authority that learners find the <code>-&gt;</code> thing to be either confusing or annoying.] </p> <p>There's even precedent, where C does a handful of similar things. E.g., for implementation reasons, function declarations are always cast to pointer-to-function, so <code>f(x,y)</code> and <code>(*f)(x,y)</code> will both work regardless of whether <code>f</code> was declared as a function or a pointer to function.</p> <p>So, my question: what's wrong with this proposal? Can you think of examples where there would be fatal ambiguity between <code>ps.x</code> and <code>s.x</code>, or why keeping the mandatory distinction is otherwise useful?</p>
1,813,946
7
5
null
2009-11-28 21:46:02.037 UTC
9
2009-12-02 05:41:08.953 UTC
null
null
null
null
191,196
null
1
55
c|struct
2,064
<p>Well, if you really wanted to introduce that kind of functionality into the specification of C language, then in order to make it "blend" with the rest of the language the logical thing to do would be to extend the concept of "decay to pointer" to struct types. You yourself made an example with a function and a function pointer. The reason it works that way is because function type in C decays to pointer type in all contexts, except for <code>sizeof</code> and unary <code>&amp;</code> operators. (The same thing happens to arrays, BTW.) </p> <p>So, in order to implement something similar to what you suggest, we could introduce the concept of "struct-to-pointer decay", which would work in exactly the same way as all other "decays" in C (namely, array-to-pointer decay and function-to-pointer decay) work: when a struct object of type <code>T</code> is used in an expression, its type immediately decays to type <code>T*</code> - pointer to the beginning of the struct object - except when it's an operand of <code>sizeof</code> or unary <code>&amp;</code>. Once such a decay rule is introduced for structs, you could use <code>-&gt;</code> operator to access struct elements regardless of whether you have a pointer to struct or the struct itself on the left-hand side. Operator <code>.</code> would become completely unnecessary in this case (unless I'm missing something), you'd always use <code>-&gt;</code> and only <code>-&gt;</code>.</p> <p>The above, once again, what this feature would look like, in my opinion, if it was implemented in the spirit of C language. </p> <p>But I'd say (agreeing with what Charles said) that the loss of visual distinction between the code that works with pointers to structs and the code that works with structs themselves is not exactly desirable.</p> <p>P.S. An obvious negative consequence of such a decay rule for structs would be that besides the current army of newbies selflessly believing that "arrays are just constant pointers", we'd have an army of newbies selflessly believing that "struct objects are just constant pointers". And Chris Torek's array FAQ would have to be about 1.5-2x larger to cover structs as well :)</p>
2,282,662
WPF TextBlock font resize to fill available space in a Grid
<p>I have some text that is displayed at run time in a textblock. I want the font size to be the biggest it can be to fill the area that is given. I think I have the textblock setup correctly to "autosize" and I try to increase the font size till the textblock is bigger than than its parent then decrease the font size by 1. The problem is I can't get the control to redraw/recompute its size.</p> <p>Is the a better way to do that? Or is there a way I can make my method work?</p>
2,282,800
7
0
null
2010-02-17 16:57:04.407 UTC
12
2022-07-07 08:56:13.867 UTC
2011-09-24 18:04:45.49 UTC
null
305,637
null
212,449
null
1
62
wpf|fonts|resize|textblock
60,464
<p>Wrap the <code>TextBlock</code> inside a <code>ViewBox</code>:</p> <pre><code> &lt;Grid&gt; &lt;Viewbox&gt; &lt;TextBlock TextWrapping="Wrap" Text="Some Text" /&gt; &lt;/Viewbox&gt; &lt;/Grid&gt; </code></pre>
1,751,263
Hex colors: Numeric representation for "transparent"?
<p>I am building a web CMS in which the user can choose colours for certain site elements. I would like to convert all colour values to hex to avoid any further formatting hassle ("rgb(x,y,z)" or named colours). I have found a good JS library for that.</p> <p>The only thing that I can't get into hex is "transparent". I need this when explicitly declaring an element as transparent, which in my experience can be different from not defining any value at all. </p> <p>Does anybody know whether this can be turned into some numeric form? Will I have to set up all processing instances to accept hex values <em>or</em> "transparent"? I can't think of any other way.</p>
1,751,272
8
1
null
2009-11-17 19:42:45.137 UTC
10
2021-04-09 13:18:04.993 UTC
2010-04-04 18:08:51.98 UTC
null
164,901
null
187,606
null
1
51
css|colors|transparency|rgb
360,696
<p>Transparency is a property outside the color itself, and it's also known as <code>alpha</code> component. You can't code transparency as pure RGB (which stands for red-green-blue channels), but you can use the RGBA notation, in which you define the color + alpha channel together:</p> <pre><code>color: rgba(255, 0, 0, 0.5); /* red at 50% opacity */ </code></pre> <p>If you want &quot;transparent&quot;, just set the last number to 0, regardless of the color. All of the following result in &quot;transparent&quot; even though the color part is set to 100% red, green and blue respectively:</p> <pre><code>color: rgba(255, 0, 0, 0); /* transparent */ color: rgba(0, 255, 0, 0); /* transparent */ color: rgba(0, 0, 255, 0); /* transparent */ </code></pre> <p>There's also the HEXA notation (or RRGGBBAA) now <a href="https://caniuse.com/css-rrggbbaa" rel="noreferrer">supported on all major browsers</a>, which is pretty much the same as RGBA but using hexadecimal notation instead of decimal:</p> <pre><code>color: #FF000080; /* red at 50% opacity */ </code></pre> <p>Additionally, if you just want a transparent <em>background</em>, the simplest way to do it is:</p> <pre><code>background: transparent; </code></pre> <p>You can also play with <code>opacity</code>, although this might be a tad too much and have unwanted side effects in your case:</p> <pre><code>.half { opacity: 0.5; filter: alpha(opacity=50); /* needed to support IE, my sympathies if that's the case */ } </code></pre>
1,668,304
How does Google calculate my location on a desktop?
<p>Right this is confusing me quite a bit, i'm not sure if any of you have noticed or used the "my location" feature on google maps using your desktop (or none GPS/none mobile device). If you have a browser with google gears (easiest to use is Google Chrome) then you will have a blue circle above the zoom function in Google Maps, when clicked (without being logged into my Google Account) using standard Wi Fi to my own personal router and a normal internet connection to my ISP, it somehow manages to pinpoint my exact location with a 100% accuracy (at this moment in time).</p> <p>How does it do it? they breifly mention it <a href="http://google-latlong.blogspot.com/2009/07/blue-circle-comes-to-your-desktop.html" rel="noreferrer">here</a> but it doesn't quite explain it, it says that my browser knows where i am...</p> <p>...i am baffled, how?</p> <p>I am intrigued because I would love to integrate it in the future of my programming projects, just like some background understanding and it doesn't seem too well documented at the moment.</p>
1,668,419
9
3
null
2009-11-03 16:07:23.527 UTC
39
2022-01-27 11:19:46.477 UTC
null
null
null
null
104,934
null
1
112
geolocation|google-gears|google-latitude
134,186
<p>I am currently in Tokyo, and I used to be in Switzerland. Yet, my location until some days ago was not pinpinted exactly, except in the broad Tokyo area. Today I tried, and I appear to be in Switzerland. How?</p> <p>Well the secret is that I am now connected through wireless, and my wireless router has been identified (thanks to association to other wifis around me at that time) in a very accurate area in Switzerland. Now, my wifi moved to Tokyo, but the queried system still thinks the wifi router is in Switzerland, because either it has no information about the additional wifis surrounding me right now, or it cannot sort out the conflicting info (namely, the specific info about my wifi router against my ip geolocation, which pinpoints me in the far east).</p> <p>So, to answer your question, google, or someone for him, did "wardriving" around, mapping the wifi presence. Every time a query is performed to the system (probably in compliance with the <a href="http://dev.w3.org/geo/api/spec-source.html" rel="noreferrer">W3C draft for the geolocation API</a>) your computer sends the wifi identifiers it sees, and the system does two things:</p> <ol> <li>queries its database if geolocation exists for some of the wifis you passed, and returns the "wardrived" position if found, eventually with triangulation if intensities are present. The more wifi networks around, the higher is the accuracy of the positioning.</li> <li>adds additional networks you see that are currently not in the database to their database, so they can be reused later.</li> </ol> <p>As you see, the system builds up by itself. The only thing you need is good seeding. After that, it extends in "50 meters chunks" (the range of a newly found wifi connection).</p> <p>Of course, if you really want the system go banana, you can start exchanging wifi routers around the globe with fellow revolutionaries of the no-global-positioning movement. </p>
1,814,270
gcc/g++ option to place all object files into separate directory
<p>I am wondering why gcc/g++ doesn't have an option to place the generated object files into a specified directory.</p> <p>For example:</p> <pre><code>mkdir builddir mkdir builddir/objdir cd srcdir gcc -c file1.c file2.c file3.c **--outdir=**../builddir/objdir </code></pre> <p>I know that it's possible to achive this with separate -o options given to the compiler, e.g.:</p> <pre><code>gcc -c file1.c -o ../builddir/objdir/file1.o gcc -c file2.c -o ../builddir/objdir/file2.o gcc -c file3.c -o ../builddir/objdir/file3.o </code></pre> <p>... and I know that I can write Makefiles via VPATH and vpath directives to simplify this.</p> <p>But that's a lot of work in a complex build environment.</p> <p>I could also use</p> <pre><code>gcc -c file1.c file2.c file3.c </code></pre> <p>But when I use this approach my srcdir is full of .o garbage afterwards.</p> <p>So I think that an option with the semantics of --outdir would be very useful.</p> <p>What is your opinion?</p> <p><strong>EDIT</strong>: our Makefiles are written in such a way that .o files actually placed into builddir/obj. But I am simply wondering if there might be a better approach.</p> <p><strong>EDIT</strong>: There are several approaches which place the burden to achieve the desired behavior to the build system (aka Make, CMake etc.). But I consider them all as being <em>workarounds</em> for a weakness of gcc (and other compilers too).</p>
1,892,934
10
6
null
2009-11-29 00:37:52.353 UTC
33
2019-08-25 07:47:25.863 UTC
2009-12-16 18:43:51.587 UTC
anon
null
anon
null
null
1
75
gcc|g++
116,031
<p>This is the chopped down makefile for one of my projects, which compiles the sources in 'src' and places the .o files in the directory "obj". The key bit is the the use of the patsubst() function - see the GNU make manual (which is actually a pretty good read) for details:</p> <pre><code>OUT = lib/alib.a CC = g++ ODIR = obj SDIR = src INC = -Iinc _OBJS = a_chsrc.o a_csv.o a_enc.o a_env.o a_except.o \ a_date.o a_range.o a_opsys.o OBJS = $(patsubst %,$(ODIR)/%,$(_OBJS)) $(ODIR)/%.o: $(SDIR)/%.cpp $(CC) -c $(INC) -o $@ $&lt; $(CFLAGS) $(OUT): $(OBJS) ar rvs $(OUT) $^ .PHONY: clean clean: rm -f $(ODIR)/*.o $(OUT) </code></pre>
1,656,591
How to jump back to NERDTree from file in tab?
<p>I usually:</p> <ol> <li>Choose the needed file.</li> <li>Open it in a tab(t character, by default).</li> </ol> <p>But how I can jump back to NERDTree to open one more file in a tab?</p> <p>Temporary solution I use now in my .vimrc file:</p> <pre><code>map &lt;F10&gt; :NERDTree /path/to/root/of/my/project </code></pre> <p>But it's not very useful to start navigation again and again from the root directory.</p>
1,656,604
13
1
null
2009-11-01 07:18:22.71 UTC
93
2022-08-09 10:18:15.42 UTC
2020-01-30 22:27:13.083 UTC
null
74,089
null
74,089
null
1
260
vim|ide|nerdtree
126,989
<p><kbd>Ctrl</kbd>-<kbd>w</kbd><kbd>w</kbd></p> <p>This will move between open windows (so you could hop between the NERDTree window, the file you are editing and the help window, for example... just hold down <kbd>Ctrl</kbd> and press <kbd>w</kbd> twice).</p>
33,720,645
Why is this TensorFlow implementation vastly less successful than Matlab's NN?
<p>As a toy example I'm trying to fit a function <code>f(x) = 1/x</code> from 100 no-noise data points. The matlab default implementation is phenomenally successful with mean square difference ~10^-10, and interpolates perfectly.</p> <p>I implement a neural network with one hidden layer of 10 sigmoid neurons. I'm a beginner at neural networks so be on your guard against dumb code.</p> <pre><code>import tensorflow as tf import numpy as np def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) #Can't make tensorflow consume ordinary lists unless they're parsed to ndarray def toNd(lst): lgt = len(lst) x = np.zeros((1, lgt), dtype='float32') for i in range(0, lgt): x[0,i] = lst[i] return x xBasic = np.linspace(0.2, 0.8, 101) xTrain = toNd(xBasic) yTrain = toNd(map(lambda x: 1/x, xBasic)) x = tf.placeholder("float", [1,None]) hiddenDim = 10 b = bias_variable([hiddenDim,1]) W = weight_variable([hiddenDim, 1]) b2 = bias_variable([1]) W2 = weight_variable([1, hiddenDim]) hidden = tf.nn.sigmoid(tf.matmul(W, x) + b) y = tf.matmul(W2, hidden) + b2 # Minimize the squared errors. loss = tf.reduce_mean(tf.square(y - yTrain)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) # For initializing the variables. init = tf.initialize_all_variables() # Launch the graph sess = tf.Session() sess.run(init) for step in xrange(0, 4001): train.run({x: xTrain}, sess) if step % 500 == 0: print loss.eval({x: xTrain}, sess) </code></pre> <p>Mean square difference ends at ~2*10^-3, so about 7 orders of magnitude worse than matlab. Visualising with</p> <pre><code>xTest = np.linspace(0.2, 0.8, 1001) yTest = y.eval({x:toNd(xTest)}, sess) import matplotlib.pyplot as plt plt.plot(xTest,yTest.transpose().tolist()) plt.plot(xTest,map(lambda x: 1/x, xTest)) plt.show() </code></pre> <p>we can see the fit is systematically imperfect: <a href="https://i.stack.imgur.com/Blxq9.png"><img src="https://i.stack.imgur.com/Blxq9.png" alt="enter image description here"></a> while the matlab one looks perfect to the naked eye with the differences uniformly &lt; 10^-5: <a href="https://i.stack.imgur.com/kC8aJ.jpg"><img src="https://i.stack.imgur.com/kC8aJ.jpg" alt="enter image description here"></a> I have tried to replicate with TensorFlow the diagram of the Matlab network:</p> <p><a href="https://i.stack.imgur.com/ORLXL.png"><img src="https://i.stack.imgur.com/ORLXL.png" alt="enter image description here"></a></p> <p>Incidentally, the diagram seems to imply a tanh rather than sigmoid activation function. I cannot find it anywhere in documentation to be sure. However, when I try to use a tanh neuron in TensorFlow the fitting quickly fails with <code>nan</code> for variables. I do not know why.</p> <p>Matlab uses Levenberg–Marquardt training algorithm. Bayesian regularization is even more successful with mean squares at 10^-12 (we are probably in the area of vapours of float arithmetic).</p> <p>Why is TensorFlow implementation so much worse, and what can I do to make it better?</p>
33,723,404
2
4
null
2015-11-15 14:12:06.85 UTC
15
2016-04-25 17:09:53.563 UTC
null
null
null
null
1,715,157
null
1
32
python|matlab|neural-network|tensorflow
19,063
<p>I tried training for 50000 iterations it got to 0.00012 error. It takes about 180 seconds on Tesla K40.</p> <p><a href="https://i.stack.imgur.com/cH2hN.png"><img src="https://i.stack.imgur.com/cH2hN.png" alt="enter image description here"></a></p> <p>It seems that for this kind of problem, first order gradient descent is not a good fit (pun intended), and you need Levenberg–Marquardt or l-BFGS. I don't think anyone implemented them in TensorFlow yet.</p> <p><strong>Edit</strong> Use <code>tf.train.AdamOptimizer(0.1)</code> for this problem. It gets to <code>3.13729e-05</code> after 4000 iterations. Also, GPU with default strategy also seems like a bad idea for this problem. There are many small operations and the overhead causes GPU version to run 3x slower than CPU on my machine.</p>
17,824,914
Bootstrap: center some navbar items
<p>I would like to have a bootstrap navbar where some nav items are left-justified, some are right justified, and some are centered in the remaining space between them.</p> <pre><code>&lt;div class="navbar"&gt; &lt;div class="navbar-inner"&gt; &lt;ul class="nav"&gt; &lt;li&gt;&lt;a&gt;Left&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav nav-center"&gt; &lt;li&gt;&lt;a&gt;Center 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Center 2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav pull-right"&gt; &lt;li&gt;&lt;a&gt;Right&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This jsfiddle <a href="http://jsfiddle.net/b7whs/" rel="noreferrer">http://jsfiddle.net/b7whs/</a> shows this--I'd like the Center 1 and Center 2 nav items to be together, centered in the navbar. Is this possible?</p> <p>There are a lot suggestions here on SO about how to do this; none of them have worked for me. Is this even possible?</p> <p>In my case, what's on the left and right will always be the same size, so I think it should be feasible.</p>
17,825,103
4
0
null
2013-07-24 03:51:40.04 UTC
4
2018-02-02 16:20:12.657 UTC
null
null
null
null
222,602
null
1
11
css|twitter-bootstrap
45,483
<p>You just needed a couple of styles to get the behaviour that I think you wanted. It looks like you were going the <code>display:inline-block</code> route to center the elements, so I'll just continue along that approach. To your existing styles, add/modify definitions so that these styles are included:</p> <pre><code>.nav.nav-center { margin:0; float:none; } .navbar-inner{ text-align:center; } </code></pre> <p>With that, the two options should move to the exact center of your navigation bar. Here's a <a href="http://jsfiddle.net/b7whs/67/">JSFiddle example</a> to show you what this would look like. I hope this is what you were looking for! If not, let me know and I'll be happy to help further.</p>
6,448,451
Java web application i18n
<p>I've been given the (rather daunting) task of introducing i18n to a J2EE web application using the 2.3 servlet specification. The application is very large and has been in active development for over 8 years.</p> <p>As such, I want to get things right the first time so I can limit the amount of time I need to scrawl through JSPs, JavaScript files, servlets and wherever else, replacing hard-coded strings with values from message bundles.</p> <p>There is no framework being used here. How can I approach supporting i18n. Note that I want to have a single JSP per view that loads text from (a) properties file(s) and not a different JSP for each supported locale.</p> <p>I guess my main question is whether I can set the locale somewhere in the 'backend' (i.e. read locale from user profile on login and store value in session) and then expect that the JSP pages will be able to correctly load the specified string from the correct properties file (i.e. from messages_fr.properties when the locale is to French) as opposed to adding logic to find the correct locale in each JSP.</p> <p>Any ideas how I can approach this?</p>
6,452,824
3
1
null
2011-06-23 01:41:30.533 UTC
9
2011-06-23 10:49:11.053 UTC
2011-06-23 02:46:24.7 UTC
null
54,929
null
394,491
null
1
8
java|jsp|internationalization
7,789
<p>There are a lot of things that need to be taken care of while internationalizing application:</p> <p><strong>Locale detection</strong></p> <p>The very first thing you need to think about is to detect end-user's Locale. Depending on what you want to support it might be easy or a bit complicated.</p> <ol> <li>As you surely know, web browsers tend to send end-user's preferred language via HTTP Accept-Language header. Accessing this information in the Servlet might be as simple as calling <code>request.getLocale()</code>. If you are not planning to support any fancy <a href="https://softwareengineering.stackexchange.com/q/15050/2554">Locale Detection workflow</a>, you might just stick to this method.</li> <li>If you have User Profiles in your application, you might want to add Preferred Language and Preferred Formatting Locale to it. In such case you would need to switch Locale after user logs in.</li> <li>You might want to support URL-based language switching (for example: <a href="http://deutsch.example.com/" rel="nofollow noreferrer">http://deutsch.example.com/</a> or <a href="http://example.com?lang=de" rel="nofollow noreferrer">http://example.com?lang=de</a>). You would need to set valid Locale based on URL information - this could be done in various ways (i.e. URL Filter).</li> <li>You might want to support language switching (selecting it from drop-down menu, or something), however I would not recommend it (unless it is combined with point 3).</li> </ol> <p><strong><em>JSTL</em></strong> approach could be sufficient if you just want to support first method or if you are not planning to add any additional dependencies (like Spring Framework).</p> <p>While we are at <strong><em>Spring Framework</em></strong> it has quite a few nice features that you can use both to detect Locale (like <a href="http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/web/servlet/i18n/CookieLocaleResolver.html" rel="nofollow noreferrer">CookieLocaleResolver</a>, <a href="http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolver.html" rel="nofollow noreferrer">AcceptHeaderLocaleResolver</a>, <a href="http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/web/servlet/i18n/SessionLocaleResolver.html" rel="nofollow noreferrer">SessionLocaleResolver</a> and <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/i18n/LocaleChangeInterceptor.html" rel="nofollow noreferrer">LocaleChangeInterceptor</a>) and externalizing strings and formatting messages (see <a href="http://static.springsource.org/spring/docs/1.2.x/taglib/tag/MessageTag.html" rel="nofollow noreferrer">spring:message tab</a>).<br> Spring Framework would allow you to quite easily implement all the scenarios above and that is why I prefer it.</p> <p><strong>String externalization</strong></p> <p>This is something that should be easy, right? Well, mostly it is - just use appropriate tag. The only problem you might face is when it comes to externalizing client-side (JavaScript) texts. There are several possible approaches, but let me mention these two:</p> <ol> <li>Have each JSP written array of translated strings (with message tag) and simply access that array in client code. This is easier approach but less maintainable - you would need to actually write valid strings from valid pages (the ones that actually reference your client-side scripts). I have done that before and believe me, this is not something you want to do in large application (but it is probably the best solution for small one).</li> <li>Another approach may sound hard in principle but it is actually way easier to handle in the future. The idea is to centralize strings on client side (move them to some common JavaScript file). After that you would need to implement your own Servlet that will return this script upon request - the contents should be translated. You won't be able to use JSTL here, you would need to get strings from Resource Bundles directly.<br> It is much easier to maintain, because you would have one, central point to add translatable strings.</li> </ol> <p><strong>Concatenations</strong></p> <p>I hate to say that, but concatenations are really painful from Localizability perspective. They are very common and most people don't realize it.</p> <p>So what is concatenation then? </p> <p>On the principle, each English sentence need to be translated to target language. The problem is, it happens many times that correctly translated message uses different word order than its English counterpart (so English "Security policy" is translated to Polish "Polityka bezpieczeństwa" - "policy" is "polityka" - the order is different).</p> <p>OK, but how it is related to software?</p> <p>In web application you could concatenate Strings like this:</p> <pre><code>String securityPolicy = "Security " + "policy"; </code></pre> <p>or like this:</p> <pre><code>&lt;p&gt;&lt;span style="font-weight:bold"&gt;Security&lt;/span&gt; policy&lt;/p&gt; </code></pre> <p>Both would be problematic. In the first case you would need to use <code>MessageFormat.format()</code> method and externalize strings as (for example) <code>"Security {0}"</code> and <code>"policy"</code>, in the latter you would externalize the contents of the whole paragraph (p tag), <strong>including</strong> span tag. I know that this is painful for translators but there is really no better way.<br> Sometimes you have to use dynamic content in your paragraph - JSTL fmt:format tag will help you here as well (it works lime MessageFormat on the backend side).</p> <p><strong>Layouts</strong></p> <p>In localized application, it often happens that translated strings are way longer than English ones. The result could look very ugly. Somehow, you would need to fix styles. There are again two approaches:</p> <ol> <li>Fix issues as they happen by adjusting common styles (and pray that it won't break other languages). This is very painful to maintain.</li> <li>Implement CSS Localization Mechanism. The mechanism I am talking about should serve default, language-independent CSS file and per-language overrides. The idea is to have override CSS file for each language, so that you can adjust layouts on-demand (just for one language). In order to do that, default CSS file, as well as JSP pages must not contain <code>!important</code> keyword next to any style definitions. If you really have to use it, move them to language-based en.css - this would allow other languages to modify them.</li> </ol> <p><strong>Culture specific issues</strong></p> <p>Avoid using graphics, colors and sounds that might be specific for western culture. If you really need it, please provide means of Localization. Avoid direction-sensitive graphics (as this would be a problem when you try to localize to say Arabic or Hebrew). Also, do not assume that whole world is using the same numbers (i.e. not true for Arabic).</p> <p><strong>Dates and time zones</strong></p> <p>Handling dates in times in Java is to say the least not easy. If you are not going to support anything else than Gregorian Calendar, you could stick to built-in Date and Calendar classes. You can use JSTL fmt:timeZone, fmt:formatDate and fmt:parseDate to correctly set time zone, format and parse date in JSP.</p> <p>I strongly suggest to use fmt:formatDate like this:</p> <pre><code>&lt;fmt:formatDate value="${someController.somedate}" timeZone="${someController.detectedTimeZone}" dateStyle="default" timeStyle="default" /&gt; </code></pre> <p>It is important to covert date and time to valid (end user's) time zone. Also it is quite important to convert it to easily understandable format - that is why I recommend default formatting style.<br> BTW. Time zone detection is not something easy, as web browsers are not so nice to send anything. Instead, you can either add preferred time zone field to User preferences (if you have one) or get current time zone offset from web browser via client side script (see <a href="http://www.w3schools.com/jsref/jsref_obj_date.asp" rel="nofollow noreferrer">Date object's methods</a>)</p> <p><strong>Numbers and currencies</strong></p> <p>Numbers as well as currencies should be converted to local format. It is done in the similar way to formatting dates (parsing is also done similarly):</p> <pre><code>&lt;fmt:formatNumber value="1.21" type="currency"/&gt; </code></pre> <p><strong>Compound messages</strong></p> <p>You already have been warned not to concatenate strings. Instead you would probably use <code>MessgageFormat</code>. However, I must state that you should minimize use of compound messages. That is just because target grammar rules are quite commonly different, so translators might need not only to re-order the sentence (this would be resolved by using placeholders and <code>MessageFormat.format()</code>), but translate the whole sentence in different way based on what will be substituted. Let me give you some examples:</p> <pre><code>// Multiple plural forms English: 4 viruses found. Polish: Znaleziono 4 wirusy. **OR** Znaleziono 5 wirusów. // Conjugation English: Program encountered incorrect character | Application encountered incorrect character. Polish: Program napotkał nieznaną literę | Aplikacja napotkała nieznaną literę. </code></pre> <p><strong>Character encoding</strong></p> <p>If you are planning to Localize into languages that does not support ISO 8859-1 code page, you would need to support Unicode - the best way is to set page encoding to UTF-8. I have seen people doing it like this:</p> <pre><code>&lt;%@ page contentType="text/html; charset=UTF-8" %&gt; </code></pre> <p>I must warn you: this is <strong><em>not enough</em></strong>. You actually need this declaration:</p> <pre><code>&lt;%@page pageEncoding="UTF-8" %&gt; </code></pre> <p>Also, you would still need to declare encoding in the page header, just to be on the safe side:</p> <pre><code>&lt;META http-equiv="Content-Type" content="text/html;charset=UTF-8"&gt; </code></pre> <p>The list I gave you is not exhaustive but this is good starting point. Good luck :) </p>
6,899,175
Check if a div exists with jquery
<p>Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (listed below)</p> <pre><code>$(document).ready(function() { if ($('#DivID').length){ alert('Found with Length'); } if ($('#DivID').length &gt; 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') != null ) { alert('Found with Not Null'); } }); </code></pre> <p>Which one of the 3 is the correct way to check if the div exists?</p> <p>EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?</p>
6,899,211
3
9
null
2011-08-01 13:34:48.487 UTC
39
2020-02-02 13:36:37.553 UTC
2020-02-02 13:36:37.553 UTC
null
584,192
null
572,771
null
1
331
jquery|html|exists
375,614
<p>The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will <em>never</em> be null or falsy for that matter.</p>
15,990,932
How can I check other users or role permissions in the template? symfony2
<p>I'm building this user manager, where admins can change permission of a group or user. I don't want to use the FOS user bundle, because I want to customize alot.</p> <p>I found out I can give permissions to another user in the controller, but how can I read the permissions of another user/role? And is it possible to read these permissions of another user/role in the template?</p> <p>The Ideal way I would like to do this is: (a page to view users in a group and the permissons)</p> <p>1 Get all objects and users in the controller</p> <p>2 Print the users and objects in the template. Next to the objects, print the permissions this group has: VIEW EDIT DELETE OWNER..</p> <p>And the same for a user(not the current), I want to be able to check the permission of a user(not the current) in the template. On a given object/class..</p> <p>I know how to check if a user has a role/group, but I want to know what permissions the group/user has, like EDIT VIEW DELETE etc. with ACL.</p> <p>How can I achieve this ?</p>
16,518,645
2
0
null
2013-04-13 17:47:59.34 UTC
8
2013-05-13 09:42:21.493 UTC
2013-04-14 14:22:45.46 UTC
null
1,597,435
null
1,597,435
null
1
10
symfony|twig
17,576
<p>I finally found a way to do this, its probably not the most efficient way of doing this but it works and is the only way I know of doing this, as no-one knows how to achieve this till now.</p> <p>First I have a default user for every group, who cannot log in( a dummy user with the default permissions for the group ) - I get the Security ID for the default user:</p> <pre><code>$defaultUser = $this-&gt;getDoctrine() -&gt;getRepository('TdfUserBundle:User') -&gt;findOneByUsername('-default-'.$group-&gt;getCode()); $sid = UserSecurityIdentity::fromAccount($defaultUser); </code></pre> <p>I create an array of permisisons to check for and set some empty arrays, and load the problematic.acl_manager</p> <pre><code>$permissionsToCheck = array('VIEW', 'EDIT', 'CREATE', 'DELETE', 'OPERATOR', 'MASTER', 'OWNER'); $aclManager = $this-&gt;get('problematic.acl_manager'); </code></pre> <p>Then I loop through the objects that I want to check the permission for, and check the permissions I set before in the $permissionsToCheck var. I check the permissions for the default user. The result is put in a array that I send to the template.</p> <pre><code>foreach($forumCategories as $forumCategory) : $permissionArray[] = $this-&gt;checkPermissions($sid, $forumCategory, $permissionsToCheck, ''); endforeach; </code></pre> <p>The checkPermissions function returns an array of the permissions and some stuff I need from the Object given.</p> <pre><code>private function checkPermissions($sid, $object, $permissionsToCheck, $type) { $aclProvider = $this-&gt;get('security.acl.provider'); $oid = ObjectIdentity::fromDomainObject($object); try { $acl = $aclProvider-&gt;createAcl($oid); }catch(\Exception $e) { $acl = $aclProvider-&gt;findAcl($oid); } $aclProvider-&gt;updateAcl($acl); foreach ($permissionsToCheck as $permissionCode): $permissionVar = 'can'.$permissionCode; $builder = new MaskBuilder(); $builder-&gt;add($permissionCode); $mask = $builder-&gt;get(); try { $$permissionVar = $acl-&gt;isGranted(array($mask),array($sid)); } catch(\Exception $e) { $$permissionVar = false; } $tempPermissionsArray[$permissionCode] = $$permissionVar; endforeach; $returnArray = array('id' =&gt; $object-&gt;getId(),'title' =&gt; $object-&gt;getTitle(),'slug' =&gt; $object-&gt;getSlug(),'type' =&gt; $type, 'permissions' =&gt; $tempPermissionsArray); return $returnArray; } </code></pre> <p>After the POST of the form I check what Object has its permissions changed, If so I loop through all users in the group. For each user,revoke permissions,then get all the groups( default user for the group ). check per group(default user) permission, check what permissions to activate and give the user the correct permissions.</p> <p>Here I set all permissions to false and then loop through all roles/groups(default users) and see if the permission should be set.</p> <pre><code> foreach($array['permissions'] as $permissionCode =&gt; $test ): $$permissionCode = false; endforeach; foreach($user-&gt;getRoles() as $role): $role = str_replace('ROLE_', '', $role); $defaultUser = $this-&gt;getDoctrine() -&gt;getRepository('TdfUserBundle:User') -&gt;findOneByUsername('-default-'.$role); $sid = UserSecurityIdentity::fromAccount($defaultUser); // See all permissions foreach($array['permissions'] as $permissionCode =&gt; $test ): $builder = new MaskBuilder(); $builder-&gt;add($permissionCode); $mask = $builder-&gt;get(); try { $isGranted = $acl-&gt;isGranted(array($mask),array($sid)); if($isGranted): $$permissionCode = true; endif; } catch(\Exception $e) { } endforeach; endforeach; </code></pre> <p>After this I know what rights the user should have and then give the account all the rights:</p> <pre><code>$aclManager = $this-&gt;get('problematic.acl_manager'); $aclManager-&gt;revokeAllObjectPermissions($object, $user); $mapping = array( 'VIEW' =&gt; MaskBuilder::MASK_VIEW, 'EDIT' =&gt; MaskBuilder::MASK_EDIT, 'CREATE' =&gt; MaskBuilder::MASK_CREATE, 'UNDELETE' =&gt; MaskBuilder::MASK_UNDELETE, 'DELETE' =&gt; MaskBuilder::MASK_DELETE, 'OPERATOR' =&gt; MaskBuilder::MASK_OPERATOR, 'MASTER' =&gt; MaskBuilder::MASK_MASTER, 'OWNER' =&gt; MaskBuilder::MASK_OWNER, ); foreach($array['permissions'] as $permissionCode =&gt; $test ): if($$permissionCode): $mask = $mapping[$permissionCode]; $aclManager-&gt;addObjectPermission($object, $mask, $user); endif; endforeach; </code></pre>
18,806,210
Generating non-repeating random numbers in JS
<p>I have the following function</p> <pre><code>function randomNum(max, used){ newNum = Math.floor(Math.random() * max + 1); if($.inArray(newNum, used) === -1){ console.log(newNum + " is not in array"); return newNum; }else{ return randomNum(max,used); } } </code></pre> <p>Basically I am creating a random number between 1 - 10 and checking to see if that number has already been created, by adding it to an array and checking the new created number against it. I call it by adding it to a variable..</p> <pre><code>UPDATED: for(var i=0;i &lt; 10;i++){ randNum = randomNum(10, usedNums); usedNums.push(randNum); //do something with ranNum } </code></pre> <p>This works, but in Chrome I get the following error:</p> <pre><code>Uncaught RangeError: Maximum call stack size exceeded </code></pre> <p>Which I guess it's because I am calling the function inside itself too many times. Which means my code is no good.</p> <p>Can someone help me with the logic? what's a best way to make sure my numbers are not repeating?</p>
18,806,417
20
2
null
2013-09-14 20:40:56.89 UTC
18
2022-06-29 00:11:30.857 UTC
2013-09-14 21:39:44.533 UTC
null
1,937,302
user1214678
null
null
1
21
javascript|jquery
121,547
<p>If I understand right then you're just looking for a permutation (i.e. the numbers randomised with no repeats) of the numbers 1-10? Maybe try generating a randomised list of those numbers, once, at the start, and then just working your way through those?</p> <p>This will calculate a random permutation of the numbers in <code>nums</code>:</p> <pre><code>var nums = [1,2,3,4,5,6,7,8,9,10], ranNums = [], i = nums.length, j = 0; while (i--) { j = Math.floor(Math.random() * (i+1)); ranNums.push(nums[j]); nums.splice(j,1); } </code></pre> <p>So, for example, if you were looking for random numbers between 1 - 20 that were also even, then you could use:</p> <pre><code>nums = [2,4,6,8,10,12,14,16,18,20]; </code></pre> <p>Then just read through <code>ranNums</code> in order to recall the random numbers.</p> <p>This runs no risk of it taking increasingly longer to find unused numbers, as you were finding in your approach.</p> <p><strong>EDIT</strong>: After reading <a href="http://bost.ocks.org/mike/shuffle/">this</a> and running a test on <a href="http://jsperf.com/shuffles">jsperf</a>, it seems like a much better way of doing this is a Fisher–Yates Shuffle:</p> <pre><code>function shuffle(array) { var i = array.length, j = 0, temp; while (i--) { j = Math.floor(Math.random() * (i+1)); // swap randomly chosen element with current element temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]); </code></pre> <p>Basically, it's more efficient by avoiding the use of 'expensive' array operations.</p> <p><strong>BONUS EDIT</strong>: Another possibility is using <a href="http://davidwalsh.name/es6-generators">generators</a> (assuming you have <a href="http://kangax.github.io/compat-table/es6/#generators">support</a>):</p> <pre><code>function* shuffle(array) { var i = array.length; while (i--) { yield array.splice(Math.floor(Math.random() * (i+1)), 1)[0]; } } </code></pre> <p>Then to use:</p> <pre><code>var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10]); ranNums.next().value; // first random number from array ranNums.next().value; // second random number from array ranNums.next().value; // etc. </code></pre> <p>where <code>ranNums.next().value</code> will eventually evaluate to <code>undefined</code> once you've run through all the elements in the shuffled array.</p> <p>Overall this won't be as efficient as the Fisher–Yates Shuffle because you're still <code>splice</code>-ing an array. But the difference is that you're now doing that work only when you need it rather than doing it all upfront, so depending upon your use case, this might be better.</p>
19,003,106
MySQL, Error 126: Incorrect key file for table
<p>I read the following question that has relevance, but the replies didn't satify me: <a href="https://stackoverflow.com/q/2011050/570796">MySQL: #126 - Incorrect key file for table</a></p> <hr> <h2>The problem</h2> <p>When running a query I get this error</p> <blockquote> <p>ERROR 126 (HY000): Incorrect key file for table` </p> </blockquote> <h2>The question</h2> <p>When I'm trying to find the problem I cant't find one, so I don't know how to fix it with the repair command. Is there any pointers to how I can find the problem causing this issue in any other way then I already have tried?</p> <hr> <h3>The query</h3> <pre><code>mysql&gt; SELECT -&gt; Process.processId, -&gt; Domain.id AS domainId, -&gt; Domain.host, -&gt; Process.started, -&gt; COUNT(DISTINCT Joppli.id) AS countedObjects, -&gt; COUNT(DISTINCT Page.id) AS countedPages, -&gt; COUNT(DISTINCT Rule.id) AS countedRules -&gt; FROM Domain -&gt; JOIN CustomScrapingRule -&gt; AS Rule -&gt; ON Rule.Domain_id = Domain.id -&gt; LEFT JOIN StructuredData_Joppli -&gt; AS Joppli -&gt; ON Joppli.CustomScrapingRule_id = Rule.id -&gt; LEFT JOIN Domain_Page -&gt; AS Page -&gt; ON Page.Domain_id = Domain.id -&gt; LEFT JOIN Domain_Process -&gt; AS Process -&gt; ON Process.Domain_id = Domain.id -&gt; WHERE Rule.CustomScrapingRule_id IS NULL -&gt; GROUP BY Domain.id -&gt; ORDER BY Domain.host; ERROR 126 (HY000): Incorrect key file for table '/tmp/#sql_2b5_4.MYI'; try to repair it </code></pre> <h3>mysqlcheck</h3> <pre><code>root@scraper:~# mysqlcheck -p scraper Enter password: scraper.CustomScrapingRule OK scraper.Domain OK scraper.Domain_Page OK scraper.Domain_Page_Rank OK scraper.Domain_Process OK scraper.Log OK scraper.StructuredData_Joppli OK scraper.StructuredData_Joppli_Product OK </code></pre> <h3>counted rows</h3> <pre><code>mysql&gt; select count(*) from CustomScrapingRule; +----------+ | count(*) | +----------+ | 26 | +----------+ 1 row in set (0.04 sec) mysql&gt; select count(*) from Domain; +----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.01 sec) mysql&gt; select count(*) from Domain_Page; +----------+ | count(*) | +----------+ | 134288 | +----------+ 1 row in set (0.17 sec) mysql&gt; select count(*) from Domain_Page_Rank; +----------+ | count(*) | +----------+ | 4671111 | +----------+ 1 row in set (11.69 sec) mysql&gt; select count(*) from Domain_Process; +----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.02 sec) mysql&gt; select count(*) from Log; +----------+ | count(*) | +----------+ | 41 | +----------+ 1 row in set (0.00 sec) mysql&gt; select count(*) from StructuredData_Joppli; +----------+ | count(*) | +----------+ | 11433 | +----------+ 1 row in set (0.16 sec) mysql&gt; select count(*) from StructuredData_Joppli_Product; +----------+ | count(*) | +----------+ | 130784 | +----------+ 1 row in set (0.20 sec) </code></pre> <hr> <h2>Update</h2> <hr> <h3>Disk usage</h3> <pre><code>root@scraper:/tmp# df -h Filesystem Size Used Avail Use% Mounted on /dev/xvda1 20G 4.7G 15G 26% / none 4.0K 0 4.0K 0% /sys/fs/cgroup udev 237M 4.0K 237M 1% /dev tmpfs 49M 188K 49M 1% /run none 5.0M 0 5.0M 0% /run/lock none 245M 0 245M 0% /run/shm none 100M 0 100M 0% /run/user </code></pre>
19,296,147
5
3
null
2013-09-25 11:00:27.827 UTC
6
2021-11-10 08:56:51.083 UTC
2017-05-23 11:47:24.667 UTC
null
-1
null
570,796
null
1
29
mysql|sql|mysql-error-126
70,335
<p>It appears that your query is returning a large intermediate result set requiring the creation of a temporary table and that the configured location for mysql temporary disk tables (/tmp) is not large enough for the resulting temporary table.</p> <p>You could try increasing the tmpfs partition size by remounting it:</p> <pre><code>mount -t tmpfs -o remount,size=1G tmpfs /tmp </code></pre> <p>You can make this change permanent by editing /etc/fstab</p> <p>If you are unable to do this you could try changing the location of disk temporary tables by editing the "tmpdir" entry in your my.cnf file (or add it if it is not already there). Remember that the directory you choose should be writable by the mysql user</p> <p>You could also try preventing the creation of an on disk temporary table by increasing the values for the mysql configuration options:</p> <pre><code>tmp_table_size max_heap_table_size </code></pre> <p>to larger values. You will need to increase both of the above parameters</p> <p>Example: </p> <pre><code>set global tmp_table_size = 1G; set global max_heap_table_size = 1G; </code></pre>
40,156,274
Deleting a Row from a UITableView in Swift?
<p>I have a table of names and I am making a swipe and delete function for them which removes them from a names variable which is an array.</p> <p>I selected the functions which most closely resembled the tutorial inside xcode and filled them out, but my app crashes randomly when I click the delete button. Here is my code for the delete button:</p> <pre><code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -&gt; [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .destructive, title: &quot;Delete&quot;) { (rowAction: UITableViewRowAction, indexPath: IndexPath) -&gt; Void in print(&quot;Deleted&quot;) self.catNames.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) self.tableView.reloadData() } } </code></pre> <p>I'm new to coding and learning swift, I am following a tutorial for swift 2 and working with swift 3 so there are a few issues I have when following along, this being one I'm properly stuck on.</p>
40,156,490
9
5
null
2016-10-20 13:45:42.38 UTC
11
2021-10-04 22:51:40.377 UTC
2021-10-04 22:51:40.377 UTC
null
1,265,393
null
4,867,971
null
1
46
swift|uitableview|row
95,886
<p>Works for <strong>Swift 3</strong> and <strong>Swift 4</strong></p> <p>Use the UITableViewDataSource <code>tableView(:commit:forRowAt:)</code> method, see also this answer <a href="https://stackoverflow.com/a/34996901/5327882">here</a>:</p> <pre><code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { print("Deleted") self.catNames.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .automatic) } } </code></pre>
5,324,799
Git - remove commits with empty changeset using filter-branch
<p>How do I remove commits which have no changeset using git filter-branch?</p> <p>I rewrote my git history using:</p> <pre class="lang-bash prettyprint-override"><code>git filter-branch --tree-filter 'rm -r -f my_folder' -f HEAD </code></pre> <p>this worked out well but now I have lots of commits with empty changesets. I would like to remove those commits. Preferably in msysgit.</p> <p>Rebasing is not really an option because I have over 4000 commits and half of them must be removed.</p>
5,326,065
2
2
null
2011-03-16 11:49:52.863 UTC
35
2014-05-25 10:10:14.627 UTC
2014-05-25 10:09:33.323 UTC
user456814
null
null
613,109
null
1
77
git|git-filter-branch
21,562
<p>Just add on the <code>--prune-empty</code> option:</p> <pre class="lang-bash prettyprint-override"><code>git filter-branch --tree-filter 'rm -rf my_folder' --prune-empty -f HEAD </code></pre> <p>(And of course, if you have other refs, you might want to rewrite everything with <code>-- --all</code> instead of just <code>HEAD</code>.)</p> <p>Note that this isn't compatible with <code>--commit-filter</code>; in that case, <a href="https://stackoverflow.com/questions/5324799/git-remove-commits-with-empty-changeset-using-filter-branch/5324916#5324916">Charles Bailey has your answer</a>.</p>
16,394,036
Select column 1 to 10 of ActiveCell row in Excel
<p>this is regarding a macro in an excel. </p> <p>While a combination of keys are pressed (i.e. the macro is triggered), I need to do some format changes to the columns 1 to 10 of the row that has the ActiveCell. </p> <p>At the moment I have am selecting the entire row</p> <pre><code>ActiveCell.EntireRow.Select </code></pre> <p>However, I need to select only the row 1 to 10. I think it ought to be something like </p> <pre><code>ActiveCell.Range(1, 10).Select </code></pre> <p>But that does not work. </p> <p>Just to be clear, I have read about </p> <pre><code>ActiveCell.Offset(5, -4).Select </code></pre> <p>But that is not going to work in my case. The ActiveCell could be any column of the row and hence a hardcoded offset is not going to help. </p> <p>So, the excel gurus there, I am hoping this is a quick stuff, just that somehow I can't find the answer. Please help. </p>
16,394,668
4
0
null
2013-05-06 07:27:03.273 UTC
3
2017-01-16 02:18:06.54 UTC
2015-07-08 04:52:16.327 UTC
null
4,539,709
null
1,298,679
null
1
4
vba|excel
59,546
<p>If it is always columns 1 to 10 (i.e. A to J) then this ought to work:</p> <pre><code>Range("A" &amp; ActiveCell.Row &amp; ":J" &amp; ActiveCell.Row) </code></pre> <p>For example if the activecell is <code>M14</code> then this will select the range <code>A14:J14</code>. You can then format this how you like.</p> <p>Hope this helps</p>
16,291,944
PostgreSQL - SQL state: 42601 syntax error
<p>I would like to know how to use a dynamic query inside a function. I've tried lots of ways, however, when I try to compile my function a message SQL 42601 is displayed.</p> <p>The code that I use:</p> <pre><code>CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text) RETURNS TABLE (name text, rowcount integer) AS $$ BEGIN WITH v_tb_person AS (return query execute sql) select name, count(*) from v_tb_person where nome like '%a%' group by name union select name, count(*) from v_tb_person where gender = 1 group by name; END $$ LANGUAGE plpgsql; </code></pre> <p>Error message I receive:</p> <pre><code>ERROR: syntax error at or near "return" LINE 5: WITH v_tb_person AS (return query execute sql) </code></pre> <p>I tried using:</p> <pre><code>WITH v_tb_person AS (execute sql) WITH v_tb_person AS (query execute) WITH v_tb_person AS (return query execute) </code></pre> <p>What is wrong? How can I solve this problem?</p> <p>Its a question related to <a href="https://stackoverflow.com/questions/16289225/postgresql-equivalent-of-oracle-bulk-collect/16290228?noredirect=1#comment23320001_16290228">PostgreSQL equivalent of Oracle “bulk collect”</a></p>
16,292,676
1
3
null
2013-04-30 04:00:31.773 UTC
4
2022-03-11 18:39:19.91 UTC
2017-05-23 10:34:14.577 UTC
null
-1
null
2,292,091
null
1
11
database|postgresql|plpgsql|bulkinsert|dynamic-sql
188,676
<p>Your function would work like this:</p> <pre><code>CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text) RETURNS TABLE (name text, rowcount integer) AS $$ BEGIN RETURN QUERY EXECUTE ' WITH v_tb_person AS (' || sql || $x$) SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name UNION SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$; END $$ LANGUAGE plpgsql; </code></pre> <p>Call:</p> <pre><code>SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$) </code></pre> <ul> <li><p>You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about <a href="http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" rel="nofollow noreferrer">executing dynamic commands in the manual</a>.</p></li> <li><p>The aggregate function <code>count()</code> returns <code>bigint</code>, but you had <code>rowcount</code> defined as <code>integer</code>, so you need an explicit cast <code>::int</code> to make this work</p></li> <li><p>I use <a href="http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" rel="nofollow noreferrer">dollar quoting</a> to avoid quoting hell.</p></li> </ul> <p><strong>However</strong>, is this supposed to be a <strong>honeypot for <a href="http://bobby-tables.com/" rel="nofollow noreferrer">SQL injection</a></strong> attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.</p> <p>Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to <a href="https://stackoverflow.com/questions/16289225/postgresql-equivalent-of-oracle-bulk-collect/16290228?noredirect=1#comment23320001_16290228">your preceding question</a>. :)</p> <p>The query itself seems rather odd, btw. But that's beside the point here.</p>
260,058
What's the best "file format" for saving complete web pages (images, etc.) in a single archive?
<p>I'm working on a project which stores single images and text files in one place, like a time capsule. Now, most every project can be saved as one file, like DOC, PPT, and ODF. But complete web pages <em>can't</em> -- they're saved as a separate HTML file and data folder. <strong>I want to save a web page in a single archive, and while there are several solutions, there's no &quot;standard&quot;. Which is the best format for HTML archives?</strong></p> <ul> <li><p>Microsoft has <b><a href="http://en.wikipedia.org/wiki/MHTML" rel="nofollow noreferrer">MHTML</a></b> -- basically a file encoded exactly as a MIME HTML email message. It's already based on an existing standard, and MHTML as its own was proposed as <a href="https://www.rfc-editor.org/rfc/rfc2557" rel="nofollow noreferrer">rfc2557</a>. This is a great idea and it's been around forever, except it's been a &quot;proposed standard&quot; since 1999. Plus, implementations other than IE's are just cumbersome. IE and Opera support it; Firefox and Safari with a cumbersome extension.</p> </li> <li><p>Mozilla has <b><a href="https://addons.mozilla.org/en-US/firefox/addon/212" rel="nofollow noreferrer">Mozilla Archive Format</a></b> -- basically a ZIP file with the markup and images, with metadata saved as RDF. It's an awesome idea -- Winamp does this for skins, and ODF and OOXML for their embedded images. I love this, except, 1. Nobody else except Mozilla uses it, 2. The only extension supporting it wasn't updated since Firefox 1.5.</p> </li> <li><p><b><a href="http://en.wikipedia.org/wiki/Data_URI_scheme" rel="nofollow noreferrer">Data URIs</a></b> are becoming more popular. Instead of referencing an external location a la MHTML or MAF, you encode the file straight into the HTML markup as base64. Depending on your view, it's streamlined since the files are <em>right</em> where the markup is. However, support is still somewhat weak. Firefox, Opera, and Safari support it without gaffes; IE, the <em>market leader</em>, only started supporting it at IE8, and even then with limits.</p> </li> <li><p>Then of course, there's <b>&quot;Save complete webpage&quot;</b> where the HTML markup is saved as <code>&quot;savedpage.html&quot;</code> and the files in a separate <code>&quot;savedpage_files&quot;</code> folder. Afaik, everyone does this. It's well supported. But having to handle two separate elements is not simple and streamlined at <em>all</em>. My project needs to have them in a <em>single archive</em>.</p> </li> </ul> <p>Keeping in mind <strong>browser support</strong> and <strong>ease of editing the page</strong>, <strong>what do you think's the best way to save web pages in a single archive?</strong> What would be best as a &quot;standard&quot;? Or should I just buckle down and deal with the HTML file and separate folder? For the sake of my project, I <em>could</em> support that, but <em>I'd best avoid it.</em></p>
260,123
7
3
null
2008-11-03 21:40:35.217 UTC
18
2015-10-21 00:52:40.737 UTC
2021-10-07 05:46:31.917 UTC
Marco
-1
Marco
33,776
null
1
35
html|standards|webpage|archive
23,956
<p>My favourite is the ZIP format. Because:</p> <ul> <li>It is very well sutied for the purpose</li> <li>It is well documented </li> <li>There a a lot of implementations available for creating or reading them</li> <li>A user can easily extract single files, change them and put them back in the archive</li> <li>Almost every major Operating System (Windows, Mac and most linux) have a ZIP program built in</li> </ul> <p>The alternatives all have some flaw:</p> <ul> <li>With MHTMl, you can not easily edit. </li> <li>With data URI's, I don't know how difficult the implementation would be. (With ZIP, even I could do it in PHP, 3 years ago...) </li> <li>The option to store things as seperate files just has far too many things that could go wrong and mess up your archive.</li> </ul>
586,604
How can I make a check box default to being "checked" in Rails 1.2.3?
<p>How can I make a check box default to being "checked" when it is initially displayed? </p> <p>I've not found a "Rails" way to do this (that works) so I did it with JavaScript. Is there a proper way to do this in Rails? I'm using Rails 1.2.3.</p>
586,707
7
0
null
2009-02-25 15:55:01.123 UTC
4
2016-11-04 23:50:05.567 UTC
2010-12-01 04:46:04.677 UTC
null
128,421
daustin777
69,738
null
1
43
ruby-on-rails|ruby
60,591
<p>If you're using <code>check_box</code> in the context of a form, then the check box will show whatever value that field has. </p> <pre><code>@user = Person.find(:first) @user.active = true check_box 'user', 'active' #=&gt; will be checked by default </code></pre> <p>If you're using <code>check_box_tag</code>, the third parameter is the initial state (<a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag" rel="noreferrer" title="doc"><code>check_box_tag</code> doc</a>):</p> <pre><code>check_box_tag "active", 1, true </code></pre>