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
29,167,428
same-origin policy and CORS - what's the point?
<p>I have some trouble understanding the same-origin policy and the different ways to "workaround" it.<br><br> It is clear that the same-origin policy exists as a security measure, so one script that comes from a server/domain has no access to data coming from another server/domain.<br><br> It is also clear that sometimes, it is useful to be able to break this rule, so for example a mashup application accesses information from different servers in order to build up the results wanted. And one of the ways to do this is CORS.<br><br> 1) If I'm not wrong, CORS allows <strong>the target server</strong> to say to the browser "<em>it is ok for you to take data/code from myself</em>" by adding some headers in the response. But, if this is correct, this means that a malicious server could just add this header and the browser would allow the retrieval of any data or code, potentially harmful, coming from that server.<br><br> 2) On the other side, we have JSONP, allowing us to retrieve arbitrary code or data from a server without CORS enabled, thus avoiding the main goal of the SOP. So again, a malicious server able to manage JSONP is able to inject data or code even with the SOP hardwired in the browser.<br><br> So my questions are:<br><br> Is the second argumentation correct? Is it the decision of the server whether the browser must accept the contents? Is the second argumentation correct? It is, again, not in the browser's decision whether to accept or not data?<br><br> Does not JSONP render the SOP useless?<br><br> Thanks for enlightening me!!<br></p>
29,167,709
1
1
null
2015-03-20 13:17:43.79 UTC
8
2022-08-24 15:53:36.49 UTC
null
null
null
null
2,455,285
null
1
54
cors|same-origin-policy
8,384
<p>The important thing to note here is that if the user is signed in to a site <code>http://example.com/</code> and the request <code>http://example.com/delete?id=1</code> deletes a post by the user, then the following code will delete the user's post:</p> <pre><code>&lt;script src=&quot;http://example.com/delete?id=1&quot; /&gt; </code></pre> <p>This is called a CSRF/XSRF attack (cross-site request forgery). This is why most server-side web applications demand a transaction ticket: instead of <code>http://example.com/delete?id=1</code> you have to do <code>http://example.com/delete?id=1&amp;txid=SomethingTheUserCannotGuess</code></p> <p>Now the following attack won't work:</p> <pre><code>&lt;script src=&quot;http://example.com/delete?id=1&quot; /&gt; </code></pre> <p>...because it doesn't contain the txid parameter. Now, let's consider what happens if the site could be accessed using XmlHttpRequest. The script running on the user's browser could behind the user's back retrieve and parse <code>http://example.com/pageThatContainsDeleteLink</code>, extract the txid and then request <code>http://example.com/delete?id=1&amp;txid=SomethingTheUserCannotGuess</code></p> <p>Now, if XmlHttpRequest cannot access sites having a different origin, the only way to try to retrieve the txid would be to try to do something like:</p> <pre><code>&lt;script src=&quot;http://example.com/pageThatContainsDeleteLink&quot; /&gt; </code></pre> <p>...but it doesn't help as the result is a HTML page, not a piece of JavaScript code. So, there's a reason why you can include <code>&lt;script&gt;</code>s from other sites but not access other sites via XmlHttpRequest.</p> <p>You may be interested in reading this: <a href="http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/" rel="nofollow noreferrer">http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/</a></p> <p>This attack worked against Gmail back in the day and allowed you to fetch the user's mails from JavaScript code running on another site. This all shows that the security model of WWW is very subtle and not well thought of. It has evolved instead of being well-designed.</p> <p>As for your question: you seem to think that the server <code>http://example.com/</code> is the malicious one. That's not the case. Using the notations of my answer, <code>http://example.com/</code> is the server that is the target of the attack, and <code>http://attacker.com/</code> is the site of the attacker. If <code>http://example.com/</code> opens up the possibility to send requests using JSONP or CORS, it is true that it may become vulnerable to the CSRF/XSRF attack I just described. But it does not mean that other sites would become vulnerable to the attack. Similarly, if <code>http://attacker.com/</code> opens up the possibility to send requests using JSONP or CORS, the attacker's site just became vulnerable to a CSRF/XSRF attack. Thus, a misinformed server administrator may open up a hole in his own site but it doesn't affect the security of other sites.</p> <p><b>Edit:</b> a valid comment was made. It explained that the following code:</p> <pre><code>&lt;script src=&quot;http://example.com/delete?id=1&quot; /&gt; </code></pre> <p>...sends a GET request, and that <code>example.com</code> should accept only POST or DELETE requests if the request changes state such as deletes something important.</p> <p>This is true, a well-designed site shouldn't change state based on any GET request. However, this sends a POST request:</p> <pre><code>&lt;p&gt;You just won $100! Click below to redeem your prize:&lt;/p&gt; &lt;form action=&quot;http://example.com/delete&quot; method=&quot;post&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;id&quot; value=&quot;1&quot; /&gt; &lt;input type=&quot;submit&quot; value=&quot;Redeem prize&quot; /&gt; &lt;/form&gt; </code></pre> <p>In this case, the code claiming the user won $100 can be embedded into the attacker's site and it sends a POST request not to the attacker's site but rather the victim's site.</p>
29,327,222
Mongodb find created results by date today
<p>I have this query to get results on month. But I wanted to get the results of today.</p> <pre><code>var start = new Date(2010, 11, 1); var end = new Date(2010, 11, 30); db.posts.find({created_on: {$gte: start, $lt: end}}); </code></pre> <p>What is the best way to do this?</p>
29,327,353
2
1
null
2015-03-29 08:45:50.49 UTC
15
2022-06-03 18:54:24.46 UTC
2018-10-30 16:13:58.263 UTC
null
122,005
null
2,671,261
null
1
29
node.js|mongodb|date|meanjs
48,863
<p>Your start date object should hold the current date time hours at <code>00:00:00.000</code> (milliseconds precision) and set the hours for today's date to <code>23:59:59.999</code>:</p> <pre><code>var start = new Date(); start.setHours(0,0,0,0); var end = new Date(); end.setHours(23,59,59,999); </code></pre> <p>Then pass the modified date objects as usual in your MongoDB query operator:</p> <pre><code>db.posts.find({created_on: {$gte: start, $lt: end}}); </code></pre> <p>If you are using the <a href="https://day.js.org/" rel="nofollow noreferrer">dayjs date utility</a> library, this can be done by using the <a href="https://day.js.org/docs/en/manipulate/start-of#docsNav" rel="nofollow noreferrer"><code>startOf()</code></a> and <a href="https://day.js.org/docs/en/manipulate/end-of" rel="nofollow noreferrer"><code>endOf()</code></a> methods on dayjs current date object, passing the string <code>'day'</code> as argument:</p> <pre><code>const start = dayjs().startOf('day'); // set to 12:00 am today const end = dayjs().endOf('day'); // set to 23:59 pm today </code></pre> <hr /> <p>You can also use <a href="https://www.mongodb.com/docs/manual/reference/operator/query/expr/" rel="nofollow noreferrer"><code>$expr</code></a> as follows:</p> <pre><code>db.posts.find({ $expr: { $eq: [ { $dateToString: { format: '%Y-%m-%d', date: '$$NOW' } }, { $dateToString: { format: '%Y-%m-%d', date: '$created_on' } }, ], }, }) </code></pre>
6,161,567
Express-js wildcard routing to cover everything under and including a path
<p>I'm trying to have one route cover everything under <code>/foo</code> including <code>/foo</code> itself. I've tried using <code>/foo*</code> which work for everything <em>except</em> it doesn't match <code>/foo</code>. Observe:</p> <pre><code>var express = require("express"), app = express.createServer(); app.get("/foo*", function(req, res, next){ res.write("Foo*\n"); next(); }); app.get("/foo", function(req, res){ res.end("Foo\n"); }); app.get("/foo/bar", function(req, res){ res.end("Foo Bar\n"); }); app.listen(3000); </code></pre> <p>Outputs: </p> <pre><code>$ curl localhost:3000/foo Foo $ curl localhost:3000/foo/bar Foo* Foo Bar </code></pre> <p>What are my options? The best I've come up with is to route <code>/fo*</code> which of course isn't very optimal as it would match way too much.</p>
6,161,675
5
3
null
2011-05-28 12:13:24.083 UTC
15
2020-08-28 20:09:28.99 UTC
2018-05-16 17:47:04.43 UTC
null
1,028,230
null
29,347
null
1
118
node.js|express
136,866
<p>I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.</p> <p><a href="https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js" rel="noreferrer">https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js</a></p> <p>If you have 2 routes that perform the same action you can do the following to keep it <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a>.</p> <pre><code>var express = require("express"), app = express.createServer(); function fooRoute(req, res, next) { res.end("Foo Route\n"); } app.get("/foo*", fooRoute); app.get("/foo", fooRoute); app.listen(3000); </code></pre>
5,942,327
jQuery Validation not working in IE7 + IE8
<p>I'm trying to use the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="noreferrer">jQuery Validation</a> plugin on a form on my website. The form works in FF, Chrome, Opera and Safari. It has yet to work in IE7 or IE8.</p> <p>Below is a simplified version of my code that seems to work in every browser but IE.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Form&lt;/title&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ var validator = $("form").validate ({ rules: { first_name: "required" }, messages: { first_name: "Enter your firstname" } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post"&gt; &lt;label for="first_name" class="hide"&gt;First Name&lt;/label&gt; &lt;input type="text" name="first_name" value="" id="first_name" class="required" /&gt; &lt;button type="submit" id="submit" name="submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Edit:</strong> We now know that using jquery latest, I was using jQuery v1.6, was the issue. I changed back to v1.5.2 and changed</p> <pre><code>var validator = $("form").validate ({ </code></pre> <p>to:</p> <pre><code>$("form").validate ({ </code></pre> <p>Everything is working in IE, now. Thanks.</p>
5,942,500
6
2
null
2011-05-09 20:48:48.063 UTC
11
2014-06-06 21:31:43.64 UTC
2011-10-10 21:43:06.953 UTC
null
669,611
null
669,611
null
1
37
jquery|internet-explorer|internet-explorer-8|internet-explorer-7|jquery-validate
62,515
<p>I think you either need to move back to an earlier version of jquery (1.5.2) or use the newer version of the <a href="http://nuget.org/List/Packages/jQuery.Validation" rel="noreferrer">validation plugin 1.8.0.1.</a></p>
6,261,504
Android Test Driven Development
<p>I have considerable experience in making Android applications. For my new project, we have decided to do Test Driven Development (TDD). I have been getting my hands wet on Robotium for User Scenario Testing, and it works fine and looks easy too. </p> <p>For unit testing, I tried to mock Context using (MockContext Android Class) but I am unable to do so. I went through this blog <a href="http://sites.google.com/site/androiddevtesting/" rel="noreferrer">http://sites.google.com/site/androiddevtesting/</a> and through this <a href="http://sdudzin.blogspot.com/2011/01/easy-unit-testing-for-android.html" rel="noreferrer">http://sdudzin.blogspot.com/2011/01/easy-unit-testing-for-android.html</a> , which suggests that mocking in Android apps is still very limited and hard, and have suggested to use PowerMock, jMockit, JeasyTest, or Roboelectric (in combination with Mockito and Maven) and even RoboGuice. </p> <p>I would like to get any suggestions from you guys on which unit testing framework in your opinion is the best for testing Android applications. (particularly testing Android classes, possibly giving mock Contexts and other mocking features so that I can make my test cases as independent as possible). Any suggestions or pointers would be helpful . Thanks </p>
6,324,209
6
2
null
2011-06-07 06:44:58.373 UTC
27
2017-04-05 06:20:15.36 UTC
null
null
null
null
435,597
null
1
44
android|unit-testing|frameworks|tdd|mocking
18,371
<p>For off-device testing, look at <a href="http://pivotal.github.com/robolectric/" rel="noreferrer">Robolectric</a></p> <p>For on-device testing, look at <a href="http://www.paulbutcher.com/2011/03/mock-objects-on-android-with-borachio-part-1/" rel="noreferrer">Borachio</a></p> <p>Bottom line: it's still very, very difficult to do well. Things are improving (the situation is dramatically better today than it was 6 months ago) but Android is comfortably the most test-hostile environment I've ever written programs for.</p>
5,851,966
Moving a git repo to a second computer?
<p>I have a project with a simple local git repo, and I want to <em>move</em> this project (folders etc.) to another computer and work from there from now on. I don't want to have anything left on the old machine (except of course my other git projects). I want it to be as if I have been working from the new machine all along.</p> <p>Can I simply move all the files over to that computer, or will there be a problem with keys? Should I have the same key across two machines? If simply moving all the folders can't be done, what should I do? I want to avoid the hassle of setting up and learning to use a server, since this seems complicated and I don't want to alter my workflow.</p>
5,852,283
6
0
null
2011-05-01 22:45:16.61 UTC
13
2022-08-07 17:07:14.007 UTC
2011-05-02 00:34:23.75 UTC
null
154,066
null
154,066
null
1
81
git
51,611
<p>For your case, the best way to do it is to copy over the folder (copy, scp, cp, robocopy - whichever) to the new computer and delete the old folder.</p> <p>I completely disagree with @Pablo Santa Cruz that cloning is the paradigm for what you are doing. No it is not. You are moving a repo to a new computer.</p> <p>Why I don't like clone for this purpose:</p> <ul> <li><strong>It creates remote-tracking branches for each branch in the cloned repository</strong>. You are moving, and the old repo is defunct.</li> <li><strong>Any remote branches and other refs are completely ignored.</strong></li> <li><strong>You don't get your hooks if you had any and you might forget that you had them!</strong></li> <li><strong>You cannot get "lost" commits etc using git reflog or other means.</strong> Might not be a huge issue, especially if the repo acted as a server but something to be aware of.</li> </ul> <p>If you search for ways to backup a git repo, git clone wouldn't be in the top answers. So it shouldn't be used for moving a repo! I also feel that just a <code>git clone</code> cannot be a proper answer because <code>git clone</code> has the <code>--mirror</code> option, which <em>preserves</em> the repo, meaning that a <code>git clone</code> repo is different from <code>git clone --mirror</code> repo (apart from being bare, the differences are mostly those I mentioned above). I would do a copy because I <em>know</em> what I get with the copied repo - the <em>same</em> repo!</p> <p>When to consider git clone:</p> <ol> <li>It is faster as git does some optimization while cloning</li> <li>You might have different git version on the new machine and a copy might make the repo unusable in the other version (not very common nowadays). But actually this can be another pro for copying, since this would inform you that that the new computer has a different git version.</li> </ol>
5,632,031
How to stop default link click behavior with jQuery
<p>I have a link on a web page. When a user clicks it, a widget on the page should update. However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires. </p> <p>This is what the link looks like:</p> <pre><code>&lt;a href="store/cart/" class="update-cart"&gt;Update Cart&lt;/a&gt; </code></pre> <p>This is what the jQuery looks like:</p> <pre><code>$('.update-cart').click(function(e) { e.stopPropagation(); updateCartWidget(); }); </code></pre> <p>What is the problem?</p>
5,632,052
6
1
null
2011-04-12 07:52:15.237 UTC
11
2021-02-25 15:02:29.887 UTC
2020-02-18 15:28:17.84 UTC
null
10,691,622
null
344,211
null
1
94
javascript|jquery|events|click|jquery-events
152,124
<pre><code>e.preventDefault(); </code></pre> <p>from <a href="https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault</a></p> <blockquote> <p>Cancels the event if it is cancelable, without stopping further propagation of the event.</p> </blockquote>
5,953,239
How do I change file extension with javascript
<p>Does anyone know an easy way to change a file extension in Javascript?</p> <p>For example, I have a variable with "first.docx" but I need to change it to "first.html".</p>
5,953,384
7
0
null
2011-05-10 16:27:28.663 UTC
3
2022-09-13 20:29:29.207 UTC
2015-08-18 13:10:28.097 UTC
null
240,338
null
747,203
null
1
50
javascript|programming-languages|methods
51,382
<p>This will change the <em>string containing</em> the file name;</p> <pre><code>let file = &quot;first.docx&quot;; file = file.substr(0, file.lastIndexOf(&quot;.&quot;)) + &quot;.htm&quot;; </code></pre> <p>For situations where there may not be an extension:</p> <pre><code>let pos = file.lastIndexOf(&quot;.&quot;); file = file.substr(0, pos &lt; 0 ? file.length : pos) + &quot;.htm&quot;; </code></pre>
5,772,769
How to copy a file from one directory to another using PHP?
<p>Say I've got a file <code>test.php</code> in <code>foo</code> directory as well as <code>bar</code>. How can I replace <code>bar/test.php</code> with <code>foo/test.php</code> using <code>PHP</code>? I'm on Windows XP, a cross platform solution would be great but windows preferred.</p>
5,772,780
10
0
null
2011-04-24 19:41:21.75 UTC
16
2022-05-23 14:39:45.143 UTC
2014-03-31 05:54:14.23 UTC
null
1,862,107
null
49,153
null
1
175
php|file|file-io|copy|filesystems
336,672
<p>You could use the <a href="http://fr2.php.net/copy" rel="noreferrer"><strong><code>copy()</code></strong></a> function :</p> <pre><code>// Will copy foo/test.php to bar/test.php // overwritting it if necessary copy('foo/test.php', 'bar/test.php'); </code></pre> <p><br> Quoting a couple of relevant sentences from its manual page :</p> <blockquote> <p>Makes a copy of the file source to dest. <br> <br><strong>If the destination file already exists, it will be overwritten.</strong></p> </blockquote>
5,935,892
if...else within JSP or JSTL
<p>I want to output some HTML code based on some condition in a JSP file.</p> <pre class="lang-none prettyprint-override"><code>if (condition 1) { Some HTML code specific for condition 1 } else if (condition 2) { Some HTML code specific for condition 2 } </code></pre> <p>How can I do that? Should I use JSTL?</p>
5,935,934
13
2
null
2011-05-09 10:57:04.65 UTC
71
2022-07-27 18:56:02.697 UTC
2019-07-13 13:47:40.41 UTC
null
157,882
null
485,743
null
1
312
jsp|if-statement|jstl
949,708
<blockquote> <p>Should I use JSTL ? </p> </blockquote> <p>Yes.</p> <p>You can use <code>&lt;c:if&gt;</code> and <code>&lt;c:choose&gt;</code> tags to make conditional rendering in jsp using JSTL.</p> <p>To simulate <strong>if</strong> , you can use:</p> <pre class="lang-xml prettyprint-override"><code>&lt;c:if test="condition"&gt;&lt;/c:if&gt; </code></pre> <p>To simulate <strong>if...else</strong>, you can use:</p> <pre class="lang-xml prettyprint-override"><code>&lt;c:choose&gt; &lt;c:when test="${param.enter=='1'}"&gt; pizza. &lt;br /&gt; &lt;/c:when&gt; &lt;c:otherwise&gt; pizzas. &lt;br /&gt; &lt;/c:otherwise&gt; &lt;/c:choose&gt; </code></pre>
46,501,047
What does "Required filename-based automodules detected." warning mean?
<p>In my multi-module project, I created <code>module-info.java</code> only for few modules. And during compilation with <code>maven-compiler-plugin:3.7.0</code> I'm getting next warning:</p> <blockquote> <p>[WARNING] * Required filename-based automodules detected. Please don't publish this project to a public artifact repository! *</p> </blockquote> <p>What does it mean? Is that because I have only a few modules with <code>module-info.java</code> and not the whole project?</p>
46,504,438
3
1
null
2017-09-30 08:34:16.793 UTC
10
2021-04-05 08:34:14.123 UTC
2021-04-05 08:32:33.413 UTC
null
1,746,118
null
7,110,799
null
1
34
java|maven|java-9|java-platform-module-system|maven-compiler-plugin
12,137
<h2>Automatic module recap</h2> <p>An explicit module (i.e. one with a <code>module-info.java</code>) can only access code of modules that it requires (ignoring <a href="https://blog.codefx.org/java/implied-readability/" rel="noreferrer">implied readability</a> for a moment). That's great if all dependencies are modularized, but what if they are not? How to refer to a JAR that isn't modular?</p> <p><a href="http://openjdk.java.net/projects/jigsaw/spec/sotms/#automatic-modules" rel="noreferrer">Automatic modules</a> are the answer: Any JAR that ends up on the module path gets turned into a module. If a JAR contains no module declaration, the module system creates an automatic module with the following properties:</p> <ul> <li>inferred name (this is the important bit here)</li> <li>reads all other modules</li> <li>exports all packages</li> </ul> <p>Maven relies on that mechanism and once you create a <code>module-info.jar</code> it places all dependencies on the module path.</p> <h2>Automatic names</h2> <p>There are two ways to infer an automatic module's name:</p> <ul> <li>entry in the manifest</li> <li>guess from the JAR file name</li> </ul> <p>In the first case, the name was deliberately picked by the maintainer, so it can be assumed to be stable (for example it doesn't change when the project gets modularized). The second one is obviously unstable across the ecosystem - not all project setups lead to the exact same file names of their dependencies.</p> <blockquote> <p>What does it mean?</p> </blockquote> <p>The reason for the warnings is that some of your dependencies are automatic modules <em>and</em> do not define their future module name in the manifest. Instead, their name is derived from the file name, which makes them unstable.</p> <h2>Stable names</h2> <p>So why are unstable names such a problem? Assume your library gets published with <code>requires guava</code> and my framework gets published with <code>requires com.google.guava</code>. Now somebody uses your library with my framework and suddenly they need the modules <em>guava</em> and <em>com.google.guava</em> on their module path. There is no painless solution to that problem, so it needs to be prevented!</p> <p>How? For example by discouraging developers from publishing artifacts that depend on filename-based automatic modules. </p>
5,597,139
Build Android with Superuser
<p>Does anyone know how to include super-user privileges when building android from source (AOSP)?</p>
12,624,051
1
2
null
2011-04-08 15:16:12.11 UTC
10
2016-05-16 00:28:31.783 UTC
2016-05-16 00:28:31.783 UTC
null
808,044
null
568,508
null
1
14
android|root|android-source
17,877
<p>To get a root(ed) shell, edit <code>system/core/rootdir</code> or the init.rc associated to your device (e.g. <code>device/ti/panda/init.rc</code> for pandaboard) in android sources, and change those lines:</p> <pre><code>service console /system/bin/sh class core console disabled user shell group log </code></pre> <p>into:</p> <pre><code>service console /system/bin/sh class core console disabled user root group root </code></pre> <p>To embed Superuser.apk in AOSP, you have to fetch and build:</p> <ol> <li><a href="https://github.com/ChainsDD/su-binary">su-binary</a> (e.g. in <code>external/</code>) and stub/remove <code>system/extras/su</code> package.</li> <li><a href="https://github.com/ChainsDD/Superuser">Superuser</a> (e.g. in <code>packages/app/</code>)</li> </ol> <p>You may also have to set the sticky bit of <code>/system/xbin/su</code> in su-binary/Android.mk. For instance, I used following makefile:</p> <pre><code>LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := su LOCAL_SRC_FILES := su.c db.c activity.cpp SU_SHARED_LIBRARIES := liblog libsqlite ifeq ($(PLATFORM_SDK_VERSION),4) LOCAL_CFLAGS += -DSU_LEGACY_BUILD SU_SHARED_LIBRARIES += libandroid_runtime else SU_SHARED_LIBRARIES += libcutils libbinder libutils LOCAL_MODULE_TAGS := eng endif LOCAL_C_INCLUDES += external/sqlite/dist LOCAL_SHARED_LIBRARIES := $(SU_SHARED_LIBRARIES) LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES) SU_INSTALL_DIR := $(TARGET_OUT)/xbin SU_BINARY := $(SU_INSTALL_DIR)/su # taken from busybox-android $(SU_BINARY)-post: su @echo "Setting SUID/GUID to su-binary..." chmod ug+s $(TARGET_OUT_OPTIONAL_EXECUTABLES)/su SU_CMD := su SYMLINKS := $(addprefix $(TARGET_OUT_EXECUTABLES)/,$(SU_CMD)) $(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(SU_BINARY)-post $(LOCAL_PATH)/Android.mk @echo "Symlink: $@ -&gt; /system/xbin/$(SU_CMD)" @mkdir -p $(dir $@) @rm -rf $@ @ln -sf /system/xbin/$(SU_CMD) $@ ALL_DEFAULT_INSTALLED_MODULES += $(SU_BINARY)-post $(SYMLINKS) include $(BUILD_EXECUTABLE) </code></pre>
44,640,911
AttributeError: module 'cv2.cv2' has no attribute 'cv'
<p>I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here:</p> <p><img src="https://i.stack.imgur.com/ucMND.png" alt="recognizer module"></p> <p>and i am facing following error.</p> <blockquote> <p>C:\Users\MAN\AppData\Local\Programs\Python\Python36\python.exe C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py Traceback (most recent call last): File "C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py", line 11, in font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) AttributeError: module 'cv2.cv2' has no attribute 'cv'</p> <p>Process finished with exit code 1</p> </blockquote> <p>Is this the Windows issue or it shows only error in Python 3.6 version? for you kind information I am using Python 3.6 in Windows platform.</p>
44,641,013
2
2
null
2017-06-19 22:28:21.843 UTC
1
2021-05-23 15:11:00.63 UTC
2019-04-16 16:43:47.32 UTC
null
147,618
null
8,181,047
null
1
14
python|opencv
57,289
<p>in Opencv3 the <code>cv</code> module is deprecated. So, in line 11 you can initialize the font like following:</p> <pre><code>font = cv2.FONT_HERSHEY_SIMPLEX </code></pre>
42,245,636
How to do an Horizontal ListView, or FlatList in react-native
<p>I'm searching a way to make an horizontal ListView or FlatList In React-native.</p> <p>like the image below:</p> <p><a href="https://i.stack.imgur.com/D4RA5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/D4RA5.jpg" alt="enter image description here" /></a></p> <p>I tried to managed it with Flex but it's make me stranges results, and always with a vertical ListView</p> <p>If you got any idea, let me know.</p> <p>Regards,</p>
42,247,704
2
2
null
2017-02-15 09:39:39.643 UTC
1
2022-02-24 08:16:57.22 UTC
2021-01-19 17:17:01.83 UTC
null
12,368,797
null
5,457,220
null
1
30
horizontal-scrolling|react-native|react-native-listview|react-native-ios
44,238
<p>The answer is to add the horizontal property set to <code>true</code>.</p> <p>Yeah now it's described in the doc: <a href="https://reactnative.dev/docs/flatlist#horizontal" rel="nofollow noreferrer">https://reactnative.dev/docs/flatlist#horizontal</a></p> <p>So obviously a FlatList is a Child of a ScrollView so he got the Horizontal Bool.</p> <pre><code> &lt;FlatList horizontal={true} data={DATA} renderItem={renderItem} keyExtractor={(item) =&gt; item.id} extraData={selectedId} /&gt; </code></pre> <p>Ciao</p>
9,301,507
Bootstrap CSS Active Navigation
<p>On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the background colors and everything, however, I changed my CSS to be similar but when I scroll down or click on the menu item the active class does not switch. Not sure what I'm doing wrong.</p> <p>HTML:</p> <pre><code>&lt;ul class=&quot;menu&quot;&gt; &lt;li&gt;&lt;a href=&quot;#&quot; aria-current=&quot;page&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#about&quot;&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre><code>.menu { list-style:none; } .menu &gt; li { float: left; } .menu &gt; li &gt; a { color: #555; float: none; padding: 10px 16px 11px; display: block; } .menu &gt; li &gt; a:hover { color: #F95700; } .menu a[aria-current=&quot;page&quot;], .menu a[aria-current=&quot;page&quot;]:hover { color:#F95700; } </code></pre> <p>I checked the files; jQuery, bootstrap.js and bootstrap.css are all linked properly. Do I have to add some additional jQuery in or am I missing some CSS to get the active to switch like the subnav menu on their site?</p>
9,301,647
13
0
null
2012-02-15 21:14:59.753 UTC
26
2021-03-26 17:24:05.983 UTC
2021-03-26 17:24:05.983 UTC
null
2,215,004
null
1,029,779
null
1
45
jquery|html|css|twitter-bootstrap
142,838
<p>In order to switch the class, you need to perform some JavaScript.</p> <p>In jQuery:</p> <pre><code>$('.menu li a').click(function(e) { var $this = $(this); if (!$this.hasClass('active')) { $this.addClass('active'); } e.preventDefault(); }); </code></pre> <p>In JavaScript:</p> <pre><code>var menu = document.querySelector('.menu'); var anchors = menu.getElementsByTagName('a'); for (var i = 0; i &lt; anchors.length; i += 1) { anchors[i].addEventListener('click', function() { clickHandler(anchors[i]) }, false); } function clickHandler(anchor) { var hasClass = anchor.getAttribute('class'); if (hasClass !== 'active') { anchor.setAttribute('class', 'active'); } } </code></pre> <p>I hope this helps.</p>
10,422,949
CSS Background Opacity
<p>I am using something similar to the following code: </p> <pre><code>&lt;div style="opacity:0.4; background-image:url(...);"&gt; &lt;div style="opacity:1.0;"&gt; Text &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I expected this to make the background have an opacity of 0.4 and the text to have 100% opacity. Instead they both have an opacity of 0.4. </p>
10,422,974
8
1
null
2012-05-02 23:05:00.163 UTC
102
2021-08-27 06:17:44.387 UTC
2019-03-23 00:24:09.867 UTC
null
63,550
null
1,227,172
null
1
829
html|css|opacity
2,599,800
<p>Children inherit opacity. It'd be weird and inconvenient if they didn't.</p> <p>You can use a translucent PNG file for your background image, or use an RGBa (a for alpha) color for your background color.</p> <p>Example, 50% faded black background:</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-html lang-html prettyprint-override"><code>&lt;div style="background-color:rgba(0, 0, 0, 0.5);"&gt; &lt;div&gt; Text added. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
22,578,799
Javascript get element by value
<p>I want to get HTML element by it's value using Javascript. I thought that there is function like <code>getElementByValue()</code> but there isn't. How I can do it?</p>
22,579,011
1
1
null
2014-03-22 14:23:39.05 UTC
null
2014-03-22 14:40:40.183 UTC
null
null
null
null
2,759,262
null
1
3
javascript|html
38,075
<p>I don't know what exactly you want to achieve, but following are the ways you can use to get value of an element.</p> <ol> <li><p>Select element using id and then get value of it. This works cross browser.</p> <p>var my_id = document.getElementById("my_id"); var my_value = my_id.value;</p></li> <li><p>Select element using class name (this works on all modern browser but not on ie8 and below)</p> <p>var my_class = document.getElementsByClassName("my_class"); var count = my_class.length; for(var i = 0; i &lt; count; i++){ my_class[i].value; }</p></li> </ol> <p>3.Select element using tag name</p> <pre><code>var my_tag = document.getElementsByTagName("my_tag"); var count = my_tag.length; for(var i = 0; i &lt; count; i++){ my_tag[i].value; } </code></pre>
7,150,849
How can I get a console readout at runtime in an application?
<p>For debugging purposes, I'd like to access console printouts at runtime in a way similar to the Console app current on the App Store (that can be found <a href="http://itunes.apple.com/us/app/console/id317676250?mt=8" rel="noreferrer">here</a>).</p> <p>I did some searching of the docs and I can't find anything that's provided by Apple, but I feel like I'm missing something important. Any insight?</p> <p>Thanks.</p>
7,151,773
2
0
null
2011-08-22 16:58:14.427 UTC
10
2016-02-24 17:47:27.123 UTC
2012-11-07 21:11:03.587 UTC
null
418,715
null
280,825
null
1
12
objective-c|ios|console
9,913
<p>You can do so using <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/asl.3.html" rel="nofollow"><code>&lt;asl.h&gt;</code></a>. Here is an example that I threw together to create an array of console messages.</p> <pre><code>-(NSArray*)console { NSMutableArray *consoleLog = [NSMutableArray array]; aslclient client = asl_open(NULL, NULL, ASL_OPT_STDERR); aslmsg query = asl_new(ASL_TYPE_QUERY); asl_set_query(query, ASL_KEY_MSG, NULL, ASL_QUERY_OP_NOT_EQUAL); aslresponse response = asl_search(client, query); asl_free(query); aslmsg message; while((message = asl_next(response)) != NULL) { const char *msg = asl_get(message, ASL_KEY_MSG); [consoleLog addObject:[NSString stringWithCString:msg encoding:NSUTF8StringEncoding]]; } if (message != NULL) { asl_free(message); } asl_free(response); asl_close(client); return consoleLog; } </code></pre>
37,691,727
How to use MongoDBs aggregate `$lookup` as `findOne()`
<p>So as you all know, <code>find()</code> returns an array of results, with <code>findOne()</code> returning just a simply object.</p> <p>With Angular, this makes a huge difference. Instead of going <code>{{myresult[0].name}}</code>, I can simply just write <code>{{myresult.name}}</code>.</p> <p>I have found that the <code>$lookup</code> method in the aggregate pipeline returns an array of results instead of just a single object.</p> <p>For example, I have two colletions:</p> <p><strong><code>users</code> collection:</strong></p> <pre><code>[{ "firstName": "John", "lastName": "Smith", "country": 123 }, { "firstName": "Luke", "lastName": "Jones", "country": 321 }] </code></pre> <p><strong><code>countries</code> collection:</strong></p> <pre><code>[{ "name": "Australia", "code": "AU", "_id": 123 }, { "name": "New Zealand", "code": "NZ", "_id": 321 }] </code></pre> <p><strong>My aggregate <code>$lookup</code>:</strong></p> <pre><code>db.users.aggregate([{ $project: { "fullName": { $concat: ["$firstName", " ", "$lastName"] }, "country": "$country" } }, { $lookup: { from: "countries", localField: "country", foreignField: "_id", as: "country" } }]) </code></pre> <p><strong>The results from the query:</strong></p> <pre><code>[{ "fullName": "John Smith", "country": [{ "name": "Australia", "code": "AU", "_id": 123 }] }, { "fullName": "Luke Jones", "country": [{ "name": "New Zealand", "code": "NZ", "_id": 321 }] }] </code></pre> <p>As you can see by the above results, each <code>country</code> is an array instead of a single object like <code>"country": {....}</code>.</p> <p>How can I have my <code>$lookup</code> return a single object instead of an array since it will only ever match a single document?</p>
37,699,997
5
1
null
2016-06-08 01:02:03.757 UTC
15
2022-08-24 12:52:27.62 UTC
2017-12-15 01:55:29.253 UTC
null
1,303,897
null
1,799,136
null
1
78
mongodb|mongodb-query|aggregation-framework
49,649
<p>You're almost there, you need to add another <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/project/" rel="noreferrer"><code>$project</code></a> stage to your pipeline and use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/" rel="noreferrer"><code>$arrayElemAt</code></a> to return the single element in the array.</p> <pre><code>db.users.aggregate( [ { "$project": { "fullName": { "$concat": [ "$firstName", " ", "$lastName"] }, "country": "$country" }}, { "$lookup": { "from": "countries", "localField": "country", "foreignField": "_id", "as": "countryInfo" }}, { "$project": { "fullName": 1, "country": 1, "countryInfo": { "$arrayElemAt": [ "$countryInfo", 0 ] } }} ] ) </code></pre>
18,039,723
C++ trying to get function address from a std::function
<p>i'm trying to find the address of a function from a std::function.</p> <p>The first solution was:</p> <pre><code>size_t getAddress(std::function&lt;void (void)&gt; function) { typedef void (fnType)(void); fnType ** fnPointer = function.target&lt;fnType *&gt;(); return (size_t) *fnPointer; } </code></pre> <p>But that only works for function with (void ()) signature, since i need for function that signature are (void (Type &amp;)), i tried to do</p> <pre><code>template&lt;typename T&gt; size_t getAddress(std::function&lt;void (T &amp;)&gt; function) { typedef void (fnType)(T &amp;); fnType ** fnPointer = function.target&lt;fnType *&gt;(); return (size_t) *fnPointer; } </code></pre> <p>And i get "Error - expected '(' for function-style cast or type construction"</p> <p>Update: Is any way to capture member class address? for class members i'm using:</p> <pre><code>template&lt;typename Clazz, typename Return, typename ...Arguments&gt; size_t getMemberAddress(std::function&lt;Return (Clazz::*)(Arguments...)&gt; &amp; executor) { typedef Return (Clazz::*fnType)(Arguments...); fnType ** fnPointer = executor.template target&lt;fnType *&gt;(); if (fnPointer != nullptr) { return (size_t) * fnPointer; } return 0; } </code></pre> <p>Update: To capture lambda i'm using</p> <pre><code>template &lt;typename Function&gt; struct function_traits : public function_traits&lt;decltype(&amp;Function::operator())&gt; { }; template &lt;typename ClassType, typename ReturnType, typename... Args&gt; struct function_traits&lt;ReturnType(ClassType::*)(Args...) const&gt; { typedef ReturnType (*pointer)(Args...); typedef std::function&lt;ReturnType(Args...)&gt; function; }; template &lt;typename Function&gt; typename function_traits&lt;Function&gt;::function to_function (Function &amp; lambda) { return static_cast&lt;typename function_traits&lt;Function&gt;::function&gt;(lambda); } template &lt;typename Lambda&gt; size_t getAddress(Lambda lambda) { auto function = new decltype(to_function(lambda))(to_function(lambda)); void * func = static_cast&lt;void *&gt;(function); return (size_t)func; } std::cout &lt;&lt; getAddress([] { std::cout &lt;&lt; "Hello" &lt;&lt; std::endl;}) &lt;&lt; std::endl; </code></pre>
18,039,824
2
2
null
2013-08-04 04:31:36.32 UTC
8
2017-12-18 13:05:32.103 UTC
2013-08-04 05:58:27.45 UTC
null
2,200,038
null
2,200,038
null
1
16
c++|function|pointers|std
16,445
<p>You need to use the <code>template</code> keyword when you call target:</p> <pre><code>#include &lt;functional&gt; #include &lt;iostream&gt; template&lt;typename T&gt; size_t getAddress(std::function&lt;void (T &amp;)&gt; f) { typedef void (fnType)(T &amp;); fnType ** fnPointer = f.template target&lt;fnType*&gt;(); return (size_t) *fnPointer; } void foo(int&amp; a) { a = 0; } int main() { std::function&lt;void(int&amp;)&gt; f = &amp;foo; std::cout &lt;&lt; (size_t)&amp;foo &lt;&lt; std::endl &lt;&lt; getAddress(f) &lt;&lt; std::endl; return 0; } </code></pre> <p>Hint: When you have problems with C++ syntax, I suggest you use <code>clang++</code> to compile your code. If you play around with how your write the code it will <em>usually</em> point you in the write direction to fix the error (when it can figure out what you are doing).</p> <p>I also suggest that you use variadic templates to make your function a bit more general:</p> <pre><code>template&lt;typename T, typename... U&gt; size_t getAddress(std::function&lt;T(U...)&gt; f) { typedef T(fnType)(U...); fnType ** fnPointer = f.template target&lt;fnType*&gt;(); return (size_t) *fnPointer; } </code></pre>
18,041,876
How to define an OnClick event handler for a button from within Qt Creator?
<p>In visual studio, when designing a windows form, I can easily add an OnClick event handler for a button by double clicking on it. Is it possible to do the same in QtCreator? How should I handle the Click event of a button? Is manually writing the required code from scratch the only option?</p>
18,041,962
2
1
null
2013-08-04 10:17:50.597 UTC
6
2020-10-20 10:48:57.11 UTC
null
null
null
null
69,537
null
1
30
qt|button|event-handling|onclick|qt-creator
64,357
<p>In the designer,</p> <ol> <li>add Push Button to the form</li> <li>right click the Push Button</li> <li>select "Go to slot..."</li> <li>select "clicked()" signal</li> <li>done</li> </ol> <p>The terms are different from .NET, so in this case we are talking about signals and slots, and the signal emitted when QPushButton is clicked is called <code>clicked()</code> instead of <code>OnClick</code>.</p> <p>Reading the <a href="http://qt-project.org/doc/qt-5.1/qtcore/signalsandslots.html">Qt's documentation about signals and slots</a> is recommended.</p>
18,685,674
How add key to dictionary without value?
<p>in normally we should add <code>key</code> and <code>value</code> together in <code>dictionary type</code>. like:</p> <pre><code>myDict.Add(key1, value1); myDict.Add(key2, value2); </code></pre> <p>I want to know, Is there any way to add <code>key</code> first, then insert its <code>value</code>? (not both of them at the same time)</p>
18,685,849
1
0
null
2013-09-08 15:58:26.01 UTC
null
2021-07-04 16:41:55.133 UTC
null
null
null
null
1,348,721
null
1
26
c#|dictionary|key|add
70,876
<p>If the <code>value</code> type of the dictionary is nullable, you could add a null value:</p> <pre><code>myDict.Add(key1, null); </code></pre> <p>If the <code>value</code> is non nullable, you can use a default value, either <code>default</code> or some out of range value, depending on your expected meaningful values.</p> <pre><code>myDict.Add(key1, default(int)); myDict.Add(key1, Int32.MinValue); </code></pre> <h2>But</h2> <p>as mentioned in the comments, there is no discernible merit in doing this. You can add values at any time, there is no need to pre-initialize a dictionary with keys.</p>
1,532,534
Converting human-friendly date to milliseconds
<p>How to convert human-friendly date to milliseconds since the unix epoch?</p>
1,532,543
3
3
null
2009-10-07 15:55:51.173 UTC
3
2020-08-11 12:14:14.18 UTC
2017-01-02 18:04:11.593 UTC
null
1,033,581
null
89,946
null
1
32
php|datetime
55,171
<pre><code>strtotime($human_readable_date) * 1000 </code></pre>
1,571,265
Why is the Java date API (java.util.Date, .Calendar) such a mess?
<p>As most people are painfully aware of by now, the Java API for handling calendar dates (specifically the classes <code>java.util.Date</code> and <code>java.util.Calendar</code>) are a terrible mess.</p> <p>Off the top of my head:</p> <ul> <li>Date is mutable</li> <li>Date represents a timestamp, not a date</li> <li>no easy way to convert between date components (day, month, year...) and Date</li> <li>Calendar is clunky to use, and tries to combine different calendar systems into one class</li> </ul> <p><a href="http://www.jroller.com/cpurdy/entry/the_seven_habits_of_highly" rel="noreferrer">This post</a> sums it up quite well, and <a href="http://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR-310</a> also expains these problems.</p> <p>Now my question is: </p> <p>How did these classes make it into the Java SDK? Most of these problems seem fairly obvious (especially Date being mutable) and should have been easy to avoid. So how did it happen? Time pressure? Or are the problems obvious in retrospect only?</p> <p>I realize this is not strictly a programming question, but I'd find it interesting to understand how API design could go so wrong. After all, mistakes are always a good learning opportunity (and I'm curious).</p>
1,571,329
3
7
null
2009-10-15 09:34:06.06 UTC
15
2015-08-31 09:31:46.91 UTC
2009-10-15 09:44:55.847 UTC
null
26,457
null
43,681
null
1
66
java|date|api-design
14,026
<p>Someone put it better than I could ever say it:</p> <blockquote> <ul> <li>Class <code>Date</code> represents a specific instant in time, with millisecond precision. The design of this class is a very bad joke - a sobering example of how even good programmers screw up. Most of the methods in Date are now deprecated, replaced by methods in the classes below.</li> <li><p>Class <code>Calendar</code> is an abstract class for converting between a <code>Date</code> object and a set of integer fields such as year, month, day, and hour.</p></li> <li><p>Class <code>GregorianCalendar</code> is the only subclass of <code>Calendar</code> in the JDK. It does the Date-to-fields conversions for the calendar system in common use. Sun licensed this overengineered junk from Taligent - a sobering example of how average programmers screw up.</p></li> </ul> </blockquote> <p>from <em>Java Programmers FAQ</em>, version from 07.X.1998, by Peter van der Linden - this part was removed from later versions though.</p> <p>As for mutability, a lot of the early JDK classes suffer from it (<code>Point</code>, <code>Rectangle</code>, <code>Dimension</code>, ...). Misdirected optimizations, I've heard some say.</p> <p>The idea is that you want to be able to reuse objects (<code>o.getPosition().x += 5</code>) rather than creating copies (<code>o.setPosition(o.getPosition().add(5, 0))</code>) as you have to do with immutables. This may even have been a good idea with the early VMs, while it's most likely isn't with modern VMs.</p>
8,409,026
Search a String array in Delphi
<p>Is there a function in the Delphi standard library to search string arrays for a particular value?</p> <p>e.g.</p> <pre><code>someArray:=TArray&lt;string&gt;.Create('One','Two','Three'); if ArrayContains(someArray, 'Two') then ShowMessage('It contains Two'); </code></pre>
8,409,972
3
1
null
2011-12-07 00:45:38.487 UTC
2
2016-02-17 18:02:02.473 UTC
2012-08-24 04:34:05.573 UTC
null
348,610
null
348,610
null
1
13
delphi
44,197
<p>There is absolutely no need to reinvent the wheel. <a href="http://docwiki.embarcadero.com/VCL/en/StrUtils.MatchText" rel="noreferrer">StrUtils.MatchStr</a> does the job.</p> <pre><code>procedure TForm1.FormCreate(Sender: TObject); var someArray: TArray&lt;string&gt;; begin someArray:=TArray&lt;string&gt;.Create('One','Two','Three'); if MatchStr('Two', someArray) then ShowMessage('It contains Two'); end; </code></pre> <p>Note the parameter order convention.</p> <p>Another note: <code>MatchStr</code> is a canonicalized name assigned to this function somewhen in between Delphi 7 and Delphi 2007. Historical name is <code>AnsiMatchStr</code> (convention is the same as in the rest of RTL: Str/Text suffix for case-sensitivity, Ansi prefix for MBCS/Locale)</p>
8,726,268
how to get session variables using session id
<p>I have the session id of my application. now i want to get all the session variables by using this session id. </p> <p>I used <code>&lt;?php echo session_id()?&gt;</code> to get the session id but how to get all the session object values by using this session id?</p>
8,726,536
4
1
null
2012-01-04 11:41:40.88 UTC
4
2021-07-23 11:38:19.017 UTC
2013-04-10 05:38:20.477 UTC
null
739,331
null
1,029,506
null
1
25
php|session
88,255
<p>According to <a href="http://www.php.net/manual/en/session.security.php" rel="noreferrer">php.net</a>: <em>There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.</em></p> <p>This begs the question, how do you have the session ID but unable to access the script? </p> <p>Regardless, you would need to set the session ID and then start it...then access the data.</p> <pre><code>session_id($whatever_id_you_have); session_start(); echo $_SESSION['somekey']; </code></pre>
8,366,957
How to center an iframe horizontally?
<p>Consider the following example: (<a href="http://jsfiddle.net/wYNSu/" rel="noreferrer">live demo</a>)</p> <p>HTML:</p> <pre><code>&lt;div&gt;div&lt;/div&gt; &lt;iframe&gt;&lt;/iframe&gt; </code></pre> <p>CSS:</p> <pre><code>div, iframe { width: 100px; height: 50px; margin: 0 auto; background-color: #777; } </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/d82gb.png" alt="enter image description here"></p> <p>Why the <code>iframe</code> is not centrally aligned like the <code>div</code>? How could I centrally align it?</p>
8,366,972
13
1
null
2011-12-03 10:11:59.573 UTC
40
2022-02-07 10:50:10.26 UTC
null
null
null
null
247,243
null
1
294
html|css|iframe|alignment|center-align
604,112
<p>Add <code>display:block;</code> to your iframe css.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div, iframe { width: 100px; height: 50px; margin: 0 auto; background-color: #777; } iframe { display: block; border-style:none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt;div&lt;/div&gt; &lt;iframe src="data:,iframe"&gt;&lt;/iframe&gt;</code></pre> </div> </div> </p>
8,987,679
How to retrieve the current version of a MySQL database management system (DBMS)?
<p>What command returns the current version of a MySQL database?</p>
55,045,330
23
1
null
2012-01-24 13:33:14.553 UTC
71
2022-07-28 00:10:03.383 UTC
2020-01-23 23:53:16.487 UTC
null
2,005,680
null
1,045,704
null
1
566
mysql
676,983
<p>Many answers suggest to use <code>mysql --version</code>. But the <code>mysql</code> programm is the client. The server is <code>mysqld</code>. So the command should be</p> <pre><code>mysqld --version </code></pre> <p>or </p> <pre><code>mysqld --help </code></pre> <p>That works for me on Debian and Windows.</p> <p>When connected to a MySQL server with a client you can use</p> <pre><code>select version() </code></pre> <p>or</p> <pre><code>select @@version </code></pre>
19,487,322
What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface?
<p>Looking at ASP.NET Identity (new membership implementation in ASP.NET), I came across this interface when implementing my own <code>UserStore</code>:</p> <pre><code>//Microsoft.AspNet.Identity.Core.dll namespace Microsoft.AspNet.Identity { public interface IUserSecurityStampStore&lt;TUser&gt; : { // Methods Task&lt;string&gt; GetSecurityStampAsync(TUser user); Task SetSecurityStampAsync(TUser user, string stamp); } } </code></pre> <p><code>IUserSecurityStampStore</code> is implemented by the default <code>EntityFramework.UserStore&lt;TUser&gt;</code> which essentially get and set the <code>TUser.SecurityStamp</code> property.</p> <p>After some more digging, it appears that a <code>SecurityStamp</code> is a <code>Guid</code> that is newly generated at key points in the <code>UserManager</code> (for example, changing passwords).</p> <p>I can't really decipher much beyond this since I'm examining this code in <strong>Reflector</strong>. Almost all the symbol and async information has been optimized out.</p> <p>Also, Google hasn't been much help.</p> <h1>Questions are:</h1> <ul> <li>What is a <code>SecurityStamp</code> in ASP.NET Identity and what is it used for?</li> <li>Does the <code>SecurityStamp</code> play any role when authentication cookies are created?</li> <li>Are there any security ramifications or precautions that need to be taken with this? For example, don't send this value downstream to clients?</li> </ul> <hr> <h2>Update (9/16/2014)</h2> <p>Source code available here:</p> <ul> <li><a href="https://github.com/aspnet/Identity/">https://github.com/aspnet/Identity/</a></li> <li><a href="https://github.com/aspnet/Security/">https://github.com/aspnet/Security/</a></li> </ul>
19,505,060
3
1
null
2013-10-21 06:09:05.787 UTC
72
2017-12-22 20:11:18.49 UTC
2014-09-17 05:13:32.73 UTC
null
9,275
null
9,275
null
1
207
asp.net|asp.net-mvc|asp.net-mvc-5|asp.net-identity
72,142
<p>This is meant to represent the current snapshot of your user's credentials. So if nothing changes, the stamp will stay the same. But if the user's password is changed, or a login is removed (unlink your google/fb account), the stamp will change. This is needed for things like automatically signing users/rejecting old cookies when this occurs, which is a feature that's coming in 2.0.</p> <p>Identity is not open source yet, its currently in the pipeline still.</p> <p><strong>Edit: Updated for 2.0.0.</strong> So the primary purpose of the <code>SecurityStamp</code> is to enable sign out everywhere. The basic idea is that whenever something security related is changed on the user, like a password, it is a good idea to automatically invalidate any existing sign in cookies, so if your password/account was previously compromised, the attacker no longer has access.</p> <p>In 2.0.0 we added the following configuration to hook the <code>OnValidateIdentity</code> method in the <code>CookieMiddleware</code> to look at the <code>SecurityStamp</code> and reject cookies when it has changed. It also automatically refreshes the user's claims from the database every <code>refreshInterval</code> if the stamp is unchanged (which takes care of things like changing roles etc)</p> <pre><code>app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;ApplicationUserManager, ApplicationUser&gt;( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) =&gt; user.GenerateUserIdentityAsync(manager)) } }); </code></pre> <p>If your app wants to trigger this behavior explicitly, it can call:</p> <pre><code>UserManager.UpdateSecurityStampAsync(userId); </code></pre>
1,158,424
How to use c# code inside <% ... %> tags on asp.net page?
<p>I'm writing an asp.net user control. It has a property, FurtherReadingPage, and two controls bound to it: ObjectDataSource and a Repeater. Inside the Repeater I would like to display a hyperlink with an href property set to something like <code>FurtherReadingPage + "?id=" + Eval("Id")</code>. I don't know how to do it inside the page's markup. I can use <code>&lt;% Eval("Id") %&gt;</code> or <code>&lt;% Response.Write(FurtherReadingPage + "?id=") %&gt;</code> alone but I don't know how to mix them.</p>
1,158,459
4
0
null
2009-07-21 10:40:58.49 UTC
4
2015-02-25 17:58:12.44 UTC
2015-02-25 17:58:12.44 UTC
null
56,793
null
40,872
null
1
11
c#|asp.net
52,100
<p>You can do it like this -</p> <pre><code>&lt;asp:Hyperlink runat="Server" ID="hlLink" NavigateUrl='&lt;%# FurtherReadingPage + "?Id=" + DataBinder.Eval(Container.DataItem, "Id") %&gt;' /&gt; </code></pre>
411,254
What are the differences between PHP and Java?
<p>What are the main differences between PHP and Java that someone proficient in PHP but learning Java should know about?</p> <p><strong>Edit:</strong> I mean differences in the syntax of the languages, i.e their data types, how they handle arrays &amp; reference variables, and so forth :)</p>
411,650
4
1
null
2009-01-04 16:48:19.423 UTC
18
2019-02-03 14:31:07.217 UTC
2012-07-21 08:00:26.15 UTC
Java
812,149
Java
49,153
null
1
23
java|php
37,618
<p>Not an exhaustive list, and I'm PHP developer who did a tour of Java a while back so Caveat Emptor.</p> <p>Every variable in Java needs to be prepended with a data type. This includes primitive types such as boolean, int, double and char, as well as Object data-types, such as ArrayList, String, and your own objects</p> <pre><code>int foo = 36; char bar = 'b'; double baz = 3.14; String speech = "We hold these truths ..."; MyWidget widget = new MyWidget(foo,bar,baz,speech); </code></pre> <hr> <p>Every variable can only hold a value of its type. Using the above declarations, the following is not valid</p> <pre><code>foo = baz </code></pre> <hr> <p>Equality on objects (not on primitive types) checks for object identity. So the following un-intuitively prints false. Strings have an equality method to handle this.</p> <pre><code>//see comments for more information on what happens //if you use this syntax to declare your strings //String v1 = "foo"; //String v2 = "foo"; String v1 = new String("foo"); String v2 = new String("foo"); if(v1 == v2){ println("True"); } else{ println("False"); } </code></pre> <hr> <p>Arrays are your classic C arrays. Can only hold variables of one particular type, need to be created with a fixed length</p> <hr> <p>To get around this, there's a series of collection Objects, one of which is named ArrayList that will act more like PHP arrays (although the holds one type business is still true). You don't get the array like syntax, all manipulation is done through methods </p> <pre><code>//creates an array list of strings ArrayList&lt;String&gt; myArr = new ArrayList&lt;String&gt;(); myArr.add("My First Item"); </code></pre> <p>ArrayLists still have numeric keys. There's another collection called HashMap that will give you a dictionary (or associative array, if you went to school in the 90s) like object.</p> <hr> <p>ArrayLists and other collections are implemented with something called generics (the &lt;String&gt;). I am not a Java programmer, so all I understand about Generics is they describe the type of thing an Object will operate on. There is much more going on there.</p> <hr> <p>Java has no pointers. However, all Objects are actually references, similar to PHP 5, dissimilar to PHP 4. I don't <strong>think</strong> Java has the (depreciated) PHP &amp;reference &amp;syntax. </p> <hr> <p>All method parameters are passed by value in Java. However, since all Objects are actually references, you're passing the value of the reference when you pass an object. This means if you manipulate an object passed into a method, the manipulations will stick. However, if you try something like this, you won't get the result you expect</p> <pre><code>public void swapThatWontWork(String v1, String v2) { String temp = var1; var1 = var2; var2 = temp; } </code></pre> <hr> <p>It's as good a time as any to mention that methods need to have their return type specified, and bad things will happen if an method returns something it's not supposed to. The following method returns an int</p> <pre><code>public int fooBarBax(int v1){ } </code></pre> <hr> <p>If a method is going to throw an exception, you have to declare it as such, or the compiler won't have anything to do with it.</p> <pre><code>public int fooBarBax(int v1) throws SomeException,AnotherException{ ... } </code></pre> <p>This can get tricky if you're using objects you haven't written in your method that might throw an exception.</p> <hr> <p>You main code entry point in Java will be a method to a class, as opposed to PHPs main global entry point </p> <hr> <p>Variable names in Java do not start with a sigil ($), although I think they can if you want them to</p> <hr> <p>Class names in Java are case sensitive.</p> <hr> <p>Strings are not mutable in Java, so concatenation can be an expensive operation. </p> <hr> <p>The Java Class library provides a mechanism to implement threads. PHP has no such mechanism.</p> <hr> <p>PHP methods (and functions) allow you have optional parameters. In java, you need to define a separate method for each possible list of parameters</p> <pre><code>public function inPHP($var1, $var2='foo'){} public void function inJava($var1){ $var2 = "foo"; inJava($var1,$var2); } public void function inJava($var1,$var2){ } </code></pre> <hr> <p>PHP requires an explicit $this be used when an object calls its own methods methods. Java (as seen in the above example) does not. </p> <hr> <p>Java programs tend to be built from a "program runs, stays running, processes requests" kind of way, where as PHP applications are built from a "run, handle the request, stop running" kind of way.</p>
1,188,073
How to convert vdproj file to WiX format?
<p>I need to convert a vdproj file to WiX format so that I can get it building using msbuild. One solution was to call the devenv executable from msbuild and build the vdproj file from there but that's just nasty. I thought that I would try manually converting the file to WiX format but looking at its contents scared me quite a bit. Are there any tools or elegant solutions that could possibly help with this conversion?</p>
1,188,124
4
5
null
2009-07-27 13:08:12.033 UTC
9
2016-02-19 16:26:45.547 UTC
null
null
null
null
66,098
null
1
30
msbuild|wix|vdproj
19,164
<p>You can try work with <a href="http://wixtoolset.org/documentation/manual/v3/overview/alltools.html" rel="nofollow noreferrer">Dark</a> which converts any MSI into Wix. You will need to remove a lot of "<em>junk</em>" especially in the UI areas but it will give you a decent start. </p>
1,096,772
Is it safe to use isKindOfClass: against an NSString instance to determine type?
<p>From the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isKindOfClass:" rel="noreferrer">isKindOfClass: method documentation in NSObject:</a></p> <p><strong>Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected.</strong></p> <p>The documentation then proceeds to give an example of why you should never ask something like the following of an NSArray instance:</p> <pre><code>// DO NOT DO THIS! if ([myArray isKindOfClass:[NSMutableArray class]]) { // Modify the object } </code></pre> <p>Now to give an example of a different use, let's say I have an instance of NSObject where I would like to determine if I have an NSString or NSArray. </p> <p>Both of these types are class clusters - but it seems from the documentation above that the danger lies in the answer to isKindOfClass: being too affirmative (answering YES sometimes when you really do not have a mutable array) whereas asking a question about simple membership in a cluster would still be valid. </p> <p>An example:</p> <pre><code>NSObject *originalValue; // originalValue gets set to some instance if ( [originalValue isKindOfClass:[NSString class]] ) // Do something with string </code></pre> <p>Is this assumption correct? Is it really safe to use isKindOfClass: against class cluster instances to determine membership? I'm specifically interested in the answer for the omnipresent NSString, NSArray and NSDictionary but I'd be interested to know if it's generalizable.</p>
1,096,984
4
3
null
2009-07-08 08:19:55.573 UTC
9
2014-04-22 02:20:59.623 UTC
2011-08-21 20:12:07.893 UTC
null
8,047
null
6,330
null
1
36
objective-c
69,021
<p>The warning in the documentation uses the <code>NSMutableArray</code> example. Suppose some developer uses <code>NSMutableArray</code> as base class for his own implementation of a new kind of array <code>CoolFunctioningArray</code>. This <code>CoolFunctioningArray</code> by design is not mutable. However, <code>isKindOfClass</code> will return <code>YES</code> to <code>isKindOfClass:[NSMutableArray class]</code>, which is true, but by design is not.</p> <p><code>isKindOfClass:</code> will return <code>YES</code> if the receiver somewhere inherits from the class passed as argument. <code>isMemberOfClass:</code> will return <code>YES</code> only if the receiver is an instance of the class passed as argument only, i.e. not including subclasses.</p> <p>Generally <code>isKindOfClass:</code> is not safe to use to test for membership. If an instance returns <code>YES</code> for <code>isKindOfClass:[NSString class]</code>, you know only that it will respond to all methods defined in the <code>NSString</code> class, but you will not know for sure what the implementation of those methods might do. Someone might have subclassed <code>NSString</code> to raise an exception for the length method.</p> <p>I think you could use <code>isKindOfClass:</code> for this kind of testing, especially if you're working with your own code which you (as a good Samaritan) designed in such a way it will respond in a way we all expect it to (e.g. the length method of an <code>NSString</code> subclass to return the length of the string it represents instead of raising an exception). If you're using a lot of external libraries of weird developers (such as the developer of the <code>CoolFunctioningArray</code>, which should be shot) you should use the <code>isKindOfClass</code> method with caution, and preferably use the <code>isMemberOfClass:</code> method (possibly multiple times to test membership of a group of classes).</p>
656,537
Is there a better way to determine elapsed time in Perl?
<pre><code>my $start_time = [Time::HiRes::gettimeofday()]; my $diff = Time::HiRes::tv_interval($start_time); print "\n\n$diff\n"; </code></pre>
656,550
4
0
null
2009-03-18 00:24:43.483 UTC
10
2020-03-14 08:04:57.433 UTC
2009-03-18 19:44:24.273 UTC
brian d foy
2,766,176
zzztimbo
16,838
null
1
49
perl|time
61,077
<p>Possibly. Depends on what you mean by "better".</p> <p>If you are asking for a "better" solution <strong>in terms of functionality</strong>, then this is pretty much it.</p> <p>If you are asking for a "better" <strong>in the sense of "less awkward" notation</strong>, then know that, in scalar context, <code>Time::HiRes::gettimeofday()</code> will return floating seconds since epoch (with the fractional part representing microseconds), just like <a href="http://perldoc.perl.org/Time/HiRes.html" rel="noreferrer"><code>Time::HiRes::time()</code></a> (which is a good drop-in replacement for the standard <code>time()</code> function.)</p> <pre><code>my $start_time = Time::HiRes::gettimeofday(); ... my $stop_time = Time::HiRes::gettimeofday(); printf("%.2f\n", $stop_time - $start_time); </code></pre> <p>or:</p> <pre><code>use Time::HiRes qw( time ); my $begin_time = time(); ... my $end_time = time(); printf("%.2f\n", $end_time - $begin_time); </code></pre>
896,530
Use MaxBackupIndex in DailyRollingFileAppender -log4j
<p>Can someone please tell me how to use MaxBackupIndex in DailyRollingFileAppender.I know that the RollingFileAppender supports a maxBackupIndex property, but is there any workarounds for using MaxBackupIndex in DailyRollingFileAppender?</p>
896,646
1
0
null
2009-05-22 05:56:37.82 UTC
10
2022-07-20 13:42:43.41 UTC
2022-07-20 13:42:43.41 UTC
null
2,308,683
Apps
null
null
1
27
java|log4j
76,896
<p>This feature is not available in current stable version (1.2) of Log4j.</p> <p>Anyway you can explore the following: <a href="http://wiki.apache.org/logging-log4j/DailyRollingFileAppender" rel="noreferrer">http://wiki.apache.org/logging-log4j/DailyRollingFileAppender</a></p>
876,143
Eclipse/MySQL integration plugins?
<p>What plugins should I install in Eclipse to integrate MySQL into Eclipse so that I can, for example, create and modify tables inside Eclipse?</p>
876,269
1
1
null
2009-05-18 03:30:16.61 UTC
9
2012-06-15 12:33:04.21 UTC
2009-12-11 15:19:15.713 UTC
null
5,355
null
104,450
null
1
33
mysql|eclipse|plugins
71,083
<p>You can use any plugin which allows editing database through JDBC. You will need the MySql JDBC driver (<a href="http://www.mysql.com/products/connector/" rel="noreferrer">get it here</a>). </p> <p>There is the Eclipse own <a href="http://www.eclipse.org/datatools/" rel="noreferrer">Data Tools Project</a> (you can get it as part of the <a href="http://www.eclipse.org/downloads/packages/eclipse-ide-java-and-report-developers/ganymedesr2" rel="noreferrer">BIRT package</a>). </p> <p>Two popular plugins are <a href="http://www.ne.jp/asahi/zigen/home/plugin/dbviewer/about_en.html" rel="noreferrer">DBViewer</a> and <a href="http://eclipsesql.sourceforge.net/" rel="noreferrer">Eclipse SQL Explorer</a>, but there are a lot of other options. Most of <a href="http://www.eclipseplugincentral.com/Web_Links-index-req-viewcatlink-cid-3.html" rel="noreferrer">these</a> will work.</p> <p>Personally, I admit, I prefer working with a native tool, I just don't like browsing the tables inside my IDE (I use <a href="http://www.sequelpro.com/" rel="noreferrer">Sequel Pro</a>, which is Mac only).</p>
55,787,035
Is there an API to detect which theme the OS is using - dark or light (or other)?
<h2>Background</h2> <p>On recent Android versions, ever since Android 8.1, the OS got more and more support for themes. More specifically dark theme.</p> <h2>The problem</h2> <p>Even though there is a lot of talk about dark mode in the point-of-view for users, there is almost nothing that's written for developers.</p> <h2>What I've found</h2> <p>Starting from Android 8.1, Google provided some sort of dark theme . If the user chooses to have a dark wallpaper, some UI components of the OS would turn black (article <a href="https://www.theandroidsoul.com/dark-theme-android-8-1-oreo/" rel="noreferrer"><strong>here</strong></a>). </p> <p>In addition, if you developed a live wallpaper app, you could tell the OS which colors it has (3 types of colors), which affected the OS colors too (at least on Vanilla based ROMs and on Google devices). That's why I even made an app that lets you have any wallpaper while still be able to choose the colors (<a href="https://play.google.com/store/apps/details?id=com.lb.lwp_plus" rel="noreferrer"><strong>here</strong></a>). This is done by calling <a href="https://developer.android.com/reference/android/service/wallpaper/WallpaperService.Engine.html#notifyColorsChanged()" rel="noreferrer"><strong>notifyColorsChanged</strong></a> and then provide them using <a href="https://developer.android.com/reference/android/service/wallpaper/WallpaperService.Engine.html#onComputeColors()" rel="noreferrer"><strong>onComputeColors</strong></a></p> <p>Starting from Android 9.0, it is now possible to choose which theme to have: light, dark or automatic (based on wallpaper) :</p> <p><a href="https://i.stack.imgur.com/CKZdV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CKZdV.png" alt="enter image description here"></a></p> <p>And now on the near Android Q , it seems it went further, yet it's still unclear to what extent. Somehow a launcher called "Smart Launcher" has ridden on it, offering to use the theme right on itself (article <a href="https://www.androidcentral.com/smart-launcher-5-adds-android-q-dark-theme-support" rel="noreferrer"><strong>here</strong></a>). So, if you enable dark mode (manually, as written <a href="https://www.xda-developers.com/android-q-toggle-dark-theme/" rel="noreferrer"><strong>here</strong></a>) , you get the app's settings screen as such:</p> <p><a href="https://i.stack.imgur.com/W43vo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W43vo.png" alt="enter image description here"></a></p> <p>The only thing I've found so far is the above articles, and that I'm following this kind of topic.</p> <p>I also know how to request the OS to change color using the live wallpaper, but this seems to be changing on Android Q, at least according to what I've seen when trying it (I think it's more based on time-of-day, but not sure).</p> <h2>The questions</h2> <ol> <li><p>Is there an API to get which colors the OS is set to use ? </p></li> <li><p>Is there any kind of API to get the theme of the OS ? From which version?</p></li> <li><p>Is the new API somehow related to night mode too? How do those work together?</p></li> <li><p>Is there a nice API for apps to handle the chosen theme? Meaning that if the OS is in certain theme, so will the current app?</p></li> </ol>
56,515,949
6
0
null
2019-04-21 21:44:11.913 UTC
5
2022-02-22 07:03:00.49 UTC
null
null
null
null
878,126
null
1
43
android|themes|android-9.0-pie|android-8.1-oreo|android-10.0
27,072
<p>OK so I got to know how this usually works, on both newest version of Android (Q) and before.</p> <p>It seems that when the OS creates the WallpaperColors , it also generates color-hints. In the function <code>WallpaperColors.fromBitmap</code> , there is a call to <code>int hints = calculateDarkHints(bitmap);</code> , and this is the code of <code>calculateDarkHints</code> :</p> <pre><code>/** * Checks if image is bright and clean enough to support light text. * * @param source What to read. * @return Whether image supports dark text or not. */ private static int calculateDarkHints(Bitmap source) { if (source == null) { return 0; } int[] pixels = new int[source.getWidth() * source.getHeight()]; double totalLuminance = 0; final int maxDarkPixels = (int) (pixels.length * MAX_DARK_AREA); int darkPixels = 0; source.getPixels(pixels, 0 /* offset */, source.getWidth(), 0 /* x */, 0 /* y */, source.getWidth(), source.getHeight()); // This bitmap was already resized to fit the maximum allowed area. // Let's just loop through the pixels, no sweat! float[] tmpHsl = new float[3]; for (int i = 0; i &lt; pixels.length; i++) { ColorUtils.colorToHSL(pixels[i], tmpHsl); final float luminance = tmpHsl[2]; final int alpha = Color.alpha(pixels[i]); // Make sure we don't have a dark pixel mass that will // make text illegible. if (luminance &lt; DARK_PIXEL_LUMINANCE &amp;&amp; alpha != 0) { darkPixels++; } totalLuminance += luminance; } int hints = 0; double meanLuminance = totalLuminance / pixels.length; if (meanLuminance &gt; BRIGHT_IMAGE_MEAN_LUMINANCE &amp;&amp; darkPixels &lt; maxDarkPixels) { hints |= HINT_SUPPORTS_DARK_TEXT; } if (meanLuminance &lt; DARK_THEME_MEAN_LUMINANCE) { hints |= HINT_SUPPORTS_DARK_THEME; } return hints; } </code></pre> <p>Then searching for <code>getColorHints</code> that the <code>WallpaperColors.java</code> has, I've found <code>updateTheme</code> function in <code>StatusBar.java</code> :</p> <pre><code> WallpaperColors systemColors = mColorExtractor .getWallpaperColors(WallpaperManager.FLAG_SYSTEM); final boolean useDarkTheme = systemColors != null &amp;&amp; (systemColors.getColorHints() &amp; WallpaperColors.HINT_SUPPORTS_DARK_THEME) != 0; </code></pre> <p>This would work only on Android 8.1 , because then the theme was based on the colors of the wallpaper alone. On Android 9.0 , the user can set it without any connection to the wallpaper.</p> <p>Here's what I've made, according to what I've seen on Android :</p> <pre><code>enum class DarkThemeCheckResult { DEFAULT_BEFORE_THEMES, LIGHT, DARK, PROBABLY_DARK, PROBABLY_LIGHT, USER_CHOSEN } @JvmStatic fun getIsOsDarkTheme(context: Context): DarkThemeCheckResult { when { Build.VERSION.SDK_INT &lt;= Build.VERSION_CODES.O -&gt; return DarkThemeCheckResult.DEFAULT_BEFORE_THEMES Build.VERSION.SDK_INT &lt;= Build.VERSION_CODES.P -&gt; { val wallpaperManager = WallpaperManager.getInstance(context) val wallpaperColors = wallpaperManager.getWallpaperColors(WallpaperManager.FLAG_SYSTEM) ?: return DarkThemeCheckResult.UNKNOWN val primaryColor = wallpaperColors.primaryColor.toArgb() val secondaryColor = wallpaperColors.secondaryColor?.toArgb() ?: primaryColor val tertiaryColor = wallpaperColors.tertiaryColor?.toArgb() ?: secondaryColor val bitmap = generateBitmapFromColors(primaryColor, secondaryColor, tertiaryColor) val darkHints = calculateDarkHints(bitmap) //taken from StatusBar.java , in updateTheme : val HINT_SUPPORTS_DARK_THEME = 1 shl 1 val useDarkTheme = darkHints and HINT_SUPPORTS_DARK_THEME != 0 if (Build.VERSION.SDK_INT == VERSION_CODES.O_MR1) return if (useDarkTheme) DarkThemeCheckResult.UNKNOWN_MAYBE_DARK else DarkThemeCheckResult.UNKNOWN_MAYBE_LIGHT return if (useDarkTheme) DarkThemeCheckResult.MOST_PROBABLY_DARK else DarkThemeCheckResult.MOST_PROBABLY_LIGHT } else -&gt; { return when (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { Configuration.UI_MODE_NIGHT_YES -&gt; DarkThemeCheckResult.DARK Configuration.UI_MODE_NIGHT_NO -&gt; DarkThemeCheckResult.LIGHT else -&gt; DarkThemeCheckResult.MOST_PROBABLY_LIGHT } } } } fun generateBitmapFromColors(@ColorInt primaryColor: Int, @ColorInt secondaryColor: Int, @ColorInt tertiaryColor: Int): Bitmap { val colors = intArrayOf(primaryColor, secondaryColor, tertiaryColor) val imageSize = 6 val bitmap = Bitmap.createBitmap(imageSize, 1, Bitmap.Config.ARGB_8888) for (i in 0 until imageSize / 2) bitmap.setPixel(i, 0, colors[0]) for (i in imageSize / 2 until imageSize / 2 + imageSize / 3) bitmap.setPixel(i, 0, colors[1]) for (i in imageSize / 2 + imageSize / 3 until imageSize) bitmap.setPixel(i, 0, colors[2]) return bitmap } </code></pre> <p>I've set the various possible values, because in most of those cases nothing is guaranteed. </p>
2,982,935
Java Applet in JAR File
<p>I have created a java applet (.class file) and made a .jar with it and digitally signed the .jar file. Now I need to run the .jar as an applet in firefox. What do I put in the html code to run the .jar file as an applet? I tried and it doesn't work, it tries to get a .class file, how do I load and run my applet as a .jar file using the applet tag in Internet Explorer and Firefox? I searched on the internet and could not find an answer.</p>
2,982,942
2
1
null
2010-06-06 02:53:21.79 UTC
null
2016-05-19 23:00:16.24 UTC
null
null
null
null
359,500
null
1
8
java|jar|applet
45,105
<p><a href="http://java.sun.com/docs/books/tutorial/deployment/jar/run.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/deployment/jar/run.html</a></p> <p>should work</p> <pre><code>&lt;applet code=TicTacToe.class archive="TicTacToe.jar" width=120 height=120&gt; &lt;/applet&gt; </code></pre> <p>(The class has your main() I assume, the jar is the entire thing)</p>
48,877,182
Kubernetes rolling deployments and database migrations
<p>When processing a rolling update with database migrations, how does kubernetes handle this? </p> <p>For an instance - I have an app that gets updated from app-v1 to app-v2, which includes a migration step to alter an existing table. So this would mean it requires me to run something like <code>db:migrate</code> for a rails app once deployed.</p> <p>When a rolling deployment takes place on 3 replica set. It will deploy from one pod to another. Potentially allowing PODs that don't have the new version of the app to break. </p> <p>Although this scenario is not something that happens very often. It's quite possible that it would. I would like to learn about the best/recommended approaches for this scenario.</p>
48,880,687
3
0
null
2018-02-20 02:56:38.59 UTC
12
2021-05-22 22:09:03.98 UTC
2021-05-22 22:09:03.98 UTC
null
213,269
null
540,771
null
1
42
kubernetes|database-migration
12,537
<p>One way to prevent an old version from breaking is to split a migration into multiple steps. </p> <p>E.g. you want to rename a column in the database. Renaming the column directly would break old versions of the app. This can be split into multiple steps:</p> <ul> <li>Add a db migration that inserts the new column</li> <li>Change the app so that all writes go to the old and new column</li> <li>Run a task that copies all values from the old to the new column</li> <li>Change the app that it reads from the new column</li> <li>Add a migration that remove the old column</li> </ul> <p>This is unfortunately quite a hassle, but prevents having a downtime with a maintenance page up.</p>
42,395,225
SpringApplicationConfiguration not found: Erroneous spring-boot-starter-test content?
<p>Getting a compilation error in Maven:</p> <pre><code>[INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] /C:/prototypes/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[6,37] package org.springframework.boot.test does not exist [ERROR] /C:/TITAN/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[10,2] cannot find symbol symbol: class SpringApplicationConfiguration [INFO] 2 errors [INFO] ------------------------------------------------------------- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ </code></pre> <p>Maven repo seems to have the jar present: </p> <p><a href="https://i.stack.imgur.com/YndGu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YndGu.png" alt="enter image description here"></a></p> <p>howerever that jar doesn't have any compiled classes inside it. only META-INF dir:</p> <p><a href="https://i.stack.imgur.com/aXh5v.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aXh5v.png" alt="enter image description here"></a></p> <p>Is that by design? Where do I get the jar containing <strong>SpringApplicationConfiguration</strong> class to make Maven happy? </p> <p>Here's the relevant parts of my pom.xml:</p> <pre><code>&lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.5.1.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.webjars.bower&lt;/groupId&gt; &lt;artifactId&gt;jquery&lt;/artifactId&gt; &lt;version&gt;2.1.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.webjars&lt;/groupId&gt; &lt;artifactId&gt;bootstrap&lt;/artifactId&gt; &lt;version&gt;3.3.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.projectlombok&lt;/groupId&gt; &lt;artifactId&gt;lombok&lt;/artifactId&gt; &lt;version&gt;1.16.4&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre>
42,397,047
3
0
null
2017-02-22 15:09:23.977 UTC
11
2017-12-04 07:55:26.393 UTC
2017-02-22 15:16:10.4 UTC
null
283,837
null
283,837
null
1
31
maven|testing|spring-boot|spring-boot-test
41,247
<p><code>spring-boot-starter-test</code>, like all the other Spring Boot starters, is really just a pom that pulls in a number of other dependencies transitively. It only has a jar to keep some build systems that don't like pom-only dependencies happy.</p> <p>It looks like you have upgraded an application from Spring Boot 1.4 to Spring Boot 1.5. Spring Boot 1.5 removes a number of classes that were deprecated in 1.4, including <code>org.springframework.boot.test.SpringApplicationConfiguration</code>.</p> <p>I would recommend dropping back to Spring Boot 1.4.4.RELEASE and fixing all of the deprecation warnings. You should then be able to upgrade to Spring Boot 1.5.1.RELEASE without difficulty.</p>
20,048,352
How to adjust the size of matplotlib legend box
<p>I have a graph whose left upper corner is quite blank. So I decide to put my legend box there. </p> <p>However, I find the <strong>items in legend</strong> are very small and the <strong>legend box itself</strong> is also <strong>quite small</strong>.</p> <p>By "small", I mean something like this</p> <p><img src="https://i.stack.imgur.com/ylMMM.png" alt="enter image description here"></p> <p><strong>How can I make the items (<em>not texts!</em>) in the legend box bigger?</strong></p> <p><strong>How can i make the box itself bigger?</strong></p>
20,049,202
2
0
null
2013-11-18 12:55:57.997 UTC
33
2022-06-06 18:46:38.92 UTC
2022-06-06 18:46:38.92 UTC
null
7,758,804
null
2,106,753
null
1
34
python|matplotlib|legend
76,048
<p>To control the padding inside the legend (effectively making the legend box bigger) use the <code>borderpad</code> kwarg.</p> <p>For example, here's the default:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/flY3I.png" alt="enter image description here"></p> <hr> <p>If we change inside padding with <code>borderpad=2</code>, we'll make the overall legend box larger (the units are multiples of the font size, similar to <code>em</code>):</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left', borderpad=2) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/UzOLJ.png" alt="enter image description here"></p> <hr> <p>Alternately, you might want to change the spacing between the items. Use <code>labelspacing</code> to control this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left', labelspacing=2) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/4FA7d.png" alt="enter image description here"></p> <hr> <p>In most cases, however, it makes the most sense to adjust both <code>labelspacing</code> and <code>borderpad</code> at the same time:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left', borderpad=1.5, labelspacing=1.5) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/U87D1.png" alt="enter image description here"></p> <hr> <p>On the other hand, if you have very large markers, you may want to make the length of the line shown in the legend larger. For example, the default might look something like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 5) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, marker='o', markersize=20, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/oSeuE.png" alt="enter image description here"></p> <p>If we change <code>handlelength</code>, we'll get longer lines in the legend, which looks a bit more realistic. (I'm also tweaking <code>borderpad</code> and <code>labelspacing</code> here to give more room.)</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 5) fig, ax = plt.subplots() for i in range(1, 6): ax.plot(x, i*x + x, marker='o', markersize=20, label='$y={i}x + {i}$'.format(i=i)) ax.legend(loc='upper left', handlelength=5, borderpad=1.2, labelspacing=1.2) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/5AsXV.png" alt="enter image description here"></p> <hr> <p>From the docs, here are some of the other options you might want to explore:</p> <pre><code>Padding and spacing between various elements use following keywords parameters. These values are measure in font-size units. E.g., a fontsize of 10 points and a handlelength=5 implies a handlelength of 50 points. Values from rcParams will be used if None. ===================================================================== Keyword | Description ===================================================================== borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns </code></pre>
20,204,284
Is it possible to create multiple PendingIntents with the same requestCode and different extras?
<p>I'm using <code>AlarmManager</code> to schedule anywhere between 1 and 35 alarms (depending on user input). When the user requests to schedule new alarms, I need to cancel the current alarms, so I create all of my alarms with the same requestCode, defined in a <code>final</code> variable.</p> <pre><code>// clear remaining alarms Intent intentstop = new Intent(this, NDService.class); PendingIntent senderstop = PendingIntent.getService(this, NODIR_REQUESTCODE, intentstop, 0); am.cancel(senderstop); // loop through days if (sched_slider.getBooleanValue()) for (int day = 1; day &lt; 8; day++) { if (day == 1 &amp;&amp; sun.isChecked()) scheduleDay(day); if (day == 2 &amp;&amp; mon.isChecked()) scheduleDay(day); if (day == 3 &amp;&amp; tue.isChecked()) scheduleDay(day); if (day == 4 &amp;&amp; wed.isChecked()) scheduleDay(day); if (day == 5 &amp;&amp; thu.isChecked()) scheduleDay(day); if (day == 6 &amp;&amp; fri.isChecked()) scheduleDay(day); if (day == 7 &amp;&amp; sat.isChecked()) scheduleDay(day); } ... public void scheduleDay(int dayofweek) { Intent toolintent = new Intent(this, NDService.class); toolintent.putExtra("TOOL", "this value changes occasionally"); PendingIntent pi = PendingIntent.getService(this, NODIR_REQUESTCODE, toolintent, 0); calendar.set(Calendar.DAY_OF_WEEK, dayofweek); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); am.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pi); } </code></pre> <p>Here, if the user has <code>sun</code> (which is a CheckBox) checked, it will schedule an alarm to run every Sunday at <code>hour</code> and <code>minute</code>. You can see that every alarm created this way has the same requestCode, but the <code>TOOL</code> extra changes sometimes for each alarm.</p> <p>However, in my testing, when the alarm goes off and my Service runs, the extras from the Intent are now <code>null</code>. <a href="https://stackoverflow.com/questions/2882459/getextra-from-intent-launched-from-a-pendingintent">This question</a> suggests that using <code>PendingIntent.FLAG_CANCEL_CURRENT</code> will solve this, but wouldn't that cancel the other PendingIntents?</p> <h2>In short:</h2> <p>Can someone explain how PendingIntents work, in reference to creating multiple ones with the same requestCode and different extras? What flags (if any) should I be using?</p>
20,205,696
2
0
null
2013-11-25 22:00:59.203 UTC
12
2016-07-28 06:28:42.81 UTC
2017-05-23 12:18:12.49 UTC
null
-1
null
408,178
null
1
23
android|alarmmanager|android-pendingintent
7,494
<p>Actually, you don't "create" <code>PendingIntent</code>s. You request them from the Android framework. When you request a <code>PendingIntent</code> from the Android framework, it checks to see if there is already a <code>PendingIntent</code> that matches the criteria you pass as arguments. If so, it does not create a new <code>PendingIntent</code>, it just gives you back a "token" that points to the existing <code>PendingIntent</code>. If it doesn't find a matching <code>PendingIntent</code>, it will create one and then give you back a "token" that points to the one it just created. There are some flags that you can set to modify this behaviour, but not that much. The most important thing to understand here is the way the Android framework does the matching.</p> <p>To do this it checks if the following parameters match (comparing the existing <code>PendingIntent</code> with the parameters you have passed):</p> <ul> <li>Request codes must be the same. Otherwise they do not match.</li> <li>The "action" in the <code>Intent</code> must be the same (or both null). Otherwise they do not match.</li> <li>The "data" in the <code>Intent</code> must be the same (or both null). Otherwise they do not match.</li> <li>The "type" (of the data) in the <code>Intent</code> must be the same (or both null). Otherwise they do not match.</li> <li>The "package" and/or "component" in the <code>Intent</code> must be the same (or both null). Otherwise they do not match. "package" and "component" fields are set for "explicit" <code>Intent</code>s.</li> <li>The list of "categories" in the <code>Intent</code> must be the same. Otherwise they do not match.</li> </ul> <p>You should notice that "extras" <strong>is not in the list above</strong>. That means that if you request a <code>PendingIntent</code> the "extras" are not taken into consideration when the Android framework tries to find a matching <code>PendingIntent</code>. This is a common mistake that developers make.</p> <p>We can now address the additional flags that you can add to modify the behaviour of a <code>PendingIntent</code> request:</p> <p><code>FLAG_CANCEL_CURRENT</code> - When you specify this flag, if a matching <code>PendingIntent</code> is found, that <code>PendingIntent</code> is cancelled (removed, deleted, invalidated) and a new one is created. This means that any applications that are holding a "token" pointing to the old <code>PendingIntent</code> will not be able to use it, because it is no longer valid.</p> <p><code>FLAG_NO_CREATE</code> - When you specify this flag, if a matching <code>PendingIntent</code> is found, a "token" pointing to the existing <code>PendingIntent</code> is returned (this is the usual behaviour). However, if no matching <code>PendingIntent</code> is found, a new one <strong>is not created</strong> and the call just returns <code>null</code>. This can be used to determine if there is an active <code>PendingIntent</code> for a specific set of parameters.</p> <p><code>FLAG_ONE_SHOT</code> - When you specify this flag, the <code>PendingIntent</code> that is created can only be used once. That means that if you give the "token" for this <code>PendingIntent</code> to multiple applications, after the first use of the <code>PendingIntent</code> it will be canceled (removed, deleted, invalidated) so that any future attempt to use it will fail.</p> <p><code>FLAG_UPDATE_CURRENT</code> - When you specify this flag, if a matching <code>PendingIntent</code> is found, the "extras" in that <code>PendingIntent</code> will be replaced by the "extras" in the <code>Intent</code> that you pass as a parameter to the <code>getxxx()</code> method. If no matching <code>PendingIntent</code> is found, a new one is created (this is the normal behaviour). This can be used to change the "extras" on an existing <code>PendingIntent</code> where you have already given the "token" to other applications and don't want to invalidate the existing <code>PendingIntent</code>.</p> <p>Let me try to address your specific problem:</p> <p>You cannot have more than one active <code>PendingIntent</code> in the system if the request code, action, data, type and package/component parameters are the same. So your requirement to be able to have up to 35 active <code>PendingIntent</code>s all with the same request code, action, data, type and package/component parameters, but with different "extras", is not possible.</p> <p>I would suggest that you either use 35 different request codes, or create 35 different unique "action" parameters for your <code>Intent</code>.</p>
34,894,372
Spark SQL case insensitive filter for column conditions
<p>How to use Spark SQL filter as a case insensitive filter.</p> <p>For example:</p> <pre class="lang-scala prettyprint-override"><code>dataFrame.filter(dataFrame.col("vendor").equalTo("fortinet")); </code></pre> <p>just return rows that <code>'vendor'</code> column is equal to <code>'fortinet'</code> but i want rows that <code>'vendor'</code> column equal to <code>'fortinet'</code> or <code>'Fortinet'</code> or <code>'foRtinet'</code> or ...</p>
34,894,591
3
0
null
2016-01-20 07:52:09.693 UTC
2
2022-03-10 20:08:44.783 UTC
2019-01-14 00:35:11.73 UTC
null
1,560,062
null
1,528,519
null
1
20
apache-spark|apache-spark-sql
38,377
<p>You can either use case-insensitive regex:</p> <pre class="lang-scala prettyprint-override"><code>val df = sc.parallelize(Seq( (1L, "Fortinet"), (2L, "foRtinet"), (3L, "foo") )).toDF("k", "v") df.where($"v".rlike("(?i)^fortinet$")).show // +---+--------+ // | k| v| // +---+--------+ // | 1|Fortinet| // | 2|foRtinet| // +---+--------+ </code></pre> <p>or simple equality with <code>lower</code> / <code>upper</code>:</p> <pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions.{lower, upper} df.where(lower($"v") === "fortinet") // +---+--------+ // | k| v| // +---+--------+ // | 1|Fortinet| // | 2|foRtinet| // +---+--------+ df.where(upper($"v") === "FORTINET") // +---+--------+ // | k| v| // +---+--------+ // | 1|Fortinet| // | 2|foRtinet| // +---+--------+ </code></pre> <p>For simple filters I would prefer <code>rlike</code> although performance should be similar, for <code>join</code> conditions equality is a much better choice. See <a href="https://stackoverflow.com/q/33168970/1560062">How can we JOIN two Spark SQL dataframes using a SQL-esque &quot;LIKE&quot; criterion?</a> for details.</p>
36,988,622
What does Rust's unary || (parallel pipe) mean?
<p>In <a href="http://smallcultfollowing.com/babysteps/blog/2016/04/27/non-lexical-lifetimes-introduction/" rel="noreferrer">Non-Lexical Lifetimes: Introduction</a>, Niko includes the following snippet:</p> <pre><code>fn get_default3&lt;'m,K,V:Default&gt;(map: &amp;'m mut HashMap&lt;K,V&gt;, key: K) -&gt; &amp;'m mut V { map.entry(key) .or_insert_with(|| V::default()) } </code></pre> <p>What does the <code>|| V::default()</code> mean here?</p>
36,988,692
2
0
null
2016-05-02 17:56:27.86 UTC
5
2017-07-08 14:59:34.057 UTC
2017-07-08 14:59:34.057 UTC
null
155,423
null
1,739,271
null
1
30
rust
5,231
<p>It is a closure with zero arguments. This is a simplified example to show the basic syntax and usage (<a href="https://play.rust-lang.org/?gist=11e98bb5c3bc581816469f8fbc9b215c&amp;version=stable&amp;backtrace=0" rel="noreferrer">play</a>):</p> <pre><code>fn main() { let c = || println!("c called"); c(); c(); } </code></pre> <p>This prints:</p> <pre><code>c called c called </code></pre> <p>Another <a href="https://doc.rust-lang.org/book/closures.html" rel="noreferrer">example from the documentation</a>:</p> <pre><code>let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); </code></pre>
30,356,069
Extract News article content from stored .html pages
<p>I am reading text from html files and doing some analysis. These .html files are news articles. </p> <p><strong>Code:</strong></p> <pre><code> html = open(filepath,'r').read() raw = nltk.clean_html(html) raw.unidecode(item.decode('utf8')) </code></pre> <p>Now I just want the article content and not the rest of the text like advertisements, headings etc. How can I do so relatively accurately in python?</p> <p>I know some tools like Jsoup(a java api) and <a href="https://code.google.com/p/boilerpipe/downloads/list" rel="noreferrer">bolier</a> but I want to do so in python. I could find some techniques using <a href="https://stackoverflow.com/questions/25752027/get-the-contentsfull-of-text-from-the-paragraph-beautiful-soup">bs4</a> but there limited to one type of page. And I have news pages from numerous sources. Also, there is dearth of any sample code example present.</p> <p>I am looking for something exactly like this <a href="http://www.psl.cs.columbia.edu/wp-content/uploads/2011/03/3463-WWWJ.pdf" rel="noreferrer">http://www.psl.cs.columbia.edu/wp-content/uploads/2011/03/3463-WWWJ.pdf</a> in python.</p> <p><strong>EDIT:</strong> To better understand, please write a sample code to extract the content of the following link <a href="http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&amp;ref=general" rel="noreferrer">http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&amp;ref=general</a> </p>
30,357,133
6
0
null
2015-05-20 17:03:42.253 UTC
12
2022-04-26 15:31:26.123 UTC
2017-07-15 18:22:18.987 UTC
null
7,878,081
null
3,646,408
null
1
15
python|urllib2|beautifulsoup
18,952
<p>There are libraries for this in Python too :) </p> <p>Since you mentioned Java, there's a Python wrapper for boilerpipe that allows you to directly use it inside a python script: <a href="https://github.com/misja/python-boilerpipe" rel="noreferrer">https://github.com/misja/python-boilerpipe</a></p> <p>If you want to use purely python libraries, there are 2 options:</p> <p><a href="https://github.com/buriy/python-readability" rel="noreferrer">https://github.com/buriy/python-readability</a></p> <p>and</p> <p><a href="https://github.com/grangier/python-goose" rel="noreferrer">https://github.com/grangier/python-goose</a></p> <p>Of the two, I prefer Goose, however be aware that the recent versions of it sometimes fail to extract text for some reason (my recommendation is to use version 1.0.22 for now)</p> <p>EDIT: here's a sample code using Goose:</p> <pre><code>from goose import Goose from requests import get response = get('http://www.nytimes.com/2015/05/19/health/study-finds-dense-breast-tissue-isnt-always-a-high-cancer-risk.html?src=me&amp;ref=general') extractor = Goose() article = extractor.extract(raw_html=response.content) text = article.cleaned_text </code></pre>
59,188,483
Error: Invalid login: 535-5.7.8 Username and Password not accepted
<p>The code below is perfect to send emails using node.js code/program. However, still getting error mentioned in the title.</p> <pre><code>var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '[email protected]', pass: '**********' } }); var mailOptions = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', text: 'That was easy!' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); </code></pre>
59,194,512
8
0
null
2019-12-05 04:55:24.383 UTC
12
2022-08-04 13:54:57.51 UTC
2020-01-27 08:22:10.3 UTC
null
10,048,779
null
10,048,779
null
1
44
javascript|node.js|gmail|smtp-auth
67,522
<p>Yes, code is perfect. However, you need to allow less secure apps from your google account to send emails. Through this link. <a href="https://myaccount.google.com/lesssecureapps" rel="noreferrer">Allow less secure apps From your Google Account</a></p>
22,407,612
Installing SSL with only a .pem file
<p>Is it possible to install SSL certificate in Centos (6.5) and apache with just a .pem file? I have been told by the client that they do not have a .crt file or a .key file. It is a wildcard certificate that I need to install in one of the subdomain.</p>
22,407,867
1
0
null
2014-03-14 14:20:14.307 UTC
3
2016-10-17 08:36:36.063 UTC
null
null
null
null
1,293,053
null
1
10
apache|ssl|centos|pem
43,017
<p>Extensions do not matter. Usually .crt is used for a certificate in PEM format and .key for the matching key. Both are base64 encoded data with a PEM header like "---- BEGIN CERTIFICATE ---" or "----- BEGIN RSA PRIVATE KEY -----". But you can put both certificate and key together in a single PEM file and use this inside the certificate and key parameters. But, of course, you have to make sure that your *.pem files really contains both certificate and key.</p>
22,371,826
How do I set a cookie to expire after 1 minute or 30 seconds in Jquery?
<p>How do i set my cookie to expire after 30 sec or 1 m ? this is my code : </p> <pre><code>$.cookie('username', username, { expires: 14 }); // expires after 14 days </code></pre>
22,371,898
4
0
null
2014-03-13 07:26:07.173 UTC
2
2019-01-10 09:11:04.88 UTC
2014-03-13 09:30:16.75 UTC
null
2,224,265
null
3,084,005
null
1
19
jquery|cookies|jquery-cookie
61,976
<p>For 1 minute, you can use:</p> <pre><code>var date = new Date(); date.setTime(date.getTime() + (60 * 1000)); $.cookie('username', username, { expires: date }); // expires after 1 minute </code></pre> <p>For 30 seconds, you can use:</p> <pre><code>var date = new Date(); date.setTime(date.getTime() + (30 * 1000)); $.cookie('username', username, { expires: date }); // expires after 30 second </code></pre>
28,233,406
Invalidating/Disabling Entity Framework cache
<p>I see there are plenties of question on EF cache, but I have found no solution yet to my problem.</p> <h2>The straight question is</h2> <p>How do I completely disable Entity Framework 6 cache? Or, can I programmatically tell EF to forget about the cache because something happened to data?</p> <h3>Background</h3> <p>First, I have <strong>inherited</strong> an application made of a strange mixture of EF (model-first to define entities) and plain old SQL (to manipulate data). What I did was to refactor the application in order to:</p> <ul> <li>Make simple queries (like <code>GetAll()</code> for an entity) use EF6 LINQ</li> <li>Leave complex data manipulation in SQL, using <code>DbContext.Database.Connection</code> when needed</li> <li>Add <code>Spring.Web</code> support to enable DI and transactions (not yet)</li> </ul> <p>At the current point, I have reorganized the code so that the main function of the application (running complex SQL queries on huge datasets) works as it did before, but then lookup domain entity manipulation is done smarter using <em>as most</em> Entity Framework as possible</p> <h3>As most....</h3> <p>One of the pages I inherited is a multi-checkbox page I'm going to show you for best understanding. I won't discuss the previous implementor's choice, because it's cheaper to fix my current problem and later refactor code than blocking development for a broken feature.</p> <p>This is how the page looks like</p> <p><img src="https://i.stack.imgur.com/1Fbxh.jpg" alt="enter image description here"></p> <p>Basically the <code>Controller</code> method is the following</p> <pre><code> [HttpPost] public ActionResult Index(string[] codice, string[] flagpf, string[] flagpg, string[] flagammbce, string[] flagammdiv, string[] flagammest, string[] flagintab, string[] flagfinanz, string[] flagita, string[] flagest, string pNew){ Sottogruppo2015Manager.ActivateFlagFor("pf", flagpf); Sottogruppo2015Manager.ActivateFlagFor("pg", flagpg); Sottogruppo2015Manager.ActivateFlagFor("ammbce", flagammbce); Sottogruppo2015Manager.ActivateFlagFor("ammdiv", flagammdiv); Sottogruppo2015Manager.ActivateFlagFor("ammest", flagammest); Sottogruppo2015Manager.ActivateFlagFor("intab", flagintab); Sottogruppo2015Manager.ActivateFlagFor("finanz", flagfinanz); Sottogruppo2015Manager.ActivateFlagFor("ita", flagita); Sottogruppo2015Manager.ActivateFlagFor("est", flagest); return RedirectToAction("Index", new { pNew }); } </code></pre> <p>Each <code>string[]</code> parameter is a column in the table. The <code>ActivateFlagFor</code> method runs two queries in sequence</p> <pre><code>UPDATE table SET --param1-- = 0; UPDATE table SET --param1-- = 1 where id in (--param2--) </code></pre> <h3>When the cache kicks in</h3> <p>The following is the behaviour:</p> <ul> <li>I first load the page issuing a LINQ select: checks match the ones and zeroes in columns</li> <li>I change one or more checks and submit</li> <li>The controller issues the queries to update checks in the DB</li> <li>Before <strong>redirecting</strong> (!means new request!) to reload the page, I check the DB and the changes are applied</li> <li>The page reloads issuing the same LINQ select above: <strong>old checks are displayed</strong></li> </ul> <p>I am sure that this is a caching problem, because reloading the application fixes the problem. Since the main feature of the application is totally SQL based, changes to lookup tables are reflected into main operation and that's the correct behaviour.</p> <p>I understand that EF caching is a great feature for performance, but in my case I just don't want it, at least until I migrate the whole application to LINQ DML (probably impossible).</p> <h3>How I use the <code>DbContext</code></h3> <p>Of course some of you may ask "how do you use your DbContext?" "do you dispose of it correctly?".</p> <ul> <li>I haven't yet integrated Spring transactions in my Manager classes</li> <li>Each object that performs <em>actions</em> on the database is a <code>I&lt;Entity&gt;Manager</code> extending <code>BaseManager</code></li> <li><code>DbContext</code> is a request-scoped Spring object. I already <a href="https://stackoverflow.com/questions/28232703/disposable-request-scoped-object">asked about disposing request-scoped objects</a> but I currently implemented a workaround that, while bad, <strong>correctly disposes of</strong> the DbContext at the end of the request.</li> </ul> <h3>Example code</h3> <pre><code>public class ExampleManagerImpl : BaseManager, IExampleManager { public void ActivateFlagFor(string aFlag, string[] aList) { string sql = "UPDATE table SET flag" + aFlag + " = 0"; RunStatementV1(sql); if (aList != null &amp;&amp; aList.Any()) { sql = "UPDATE table SET flag" + aFlag + " = 1 WHERE id in (" + aList.ToCsvApex() + ")"; RunStatementV1(sql); } } public IList&lt;Models.Example&gt; GetAll() { return DataContext.example.ToList(); //I don't dispose of the DataContext willingly } } </code></pre> <p>and</p> <pre><code>public abstract class BaseManager { public DbContext DataContext { get; set; } //Autowired protected void RunStatementV1(string aSqlStatement) { IDbConnection connection = DataContext.Database.Connection; if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken) connection.Open(); //Needed because sometimes I found the connection closed, even if I don't dispose of it using (IDbCommand command = connection.CreateCommand()) { command.CommandText = aSqlStatement; command.ExecuteNonQuery(); } } } </code></pre> <h3>What I tried</h3> <ul> <li><a href="https://stackoverflow.com/questions/4346494/how-to-stop-entity-framework-caching">How to stop entity framework caching</a> : disabling lazy loading didn't work</li> <li><a href="https://stackoverflow.com/a/22818783/471213">https://stackoverflow.com/a/22818783/471213</a>: <code>Detach</code> seems to solve the problem but I'd need to apply it to dozen of entities, in order to revert someday in the future</li> </ul>
35,545,313
2
0
null
2015-01-30 10:03:52.027 UTC
5
2017-01-08 14:30:09.04 UTC
2017-05-23 12:34:17.993 UTC
null
-1
null
471,213
null
1
25
c#|linq|entity-framework|caching
40,086
<p>If you want to completely ignore EF6's cache for data retrieval, then add <code>AsNoTracking()</code> to the end of your query (before calling <code>ToList()</code> or doing anything else that would execute the query.</p> <p><a href="https://msdn.microsoft.com/en-us/library/dn237200%28v=vs.113%29.aspx" rel="noreferrer">MSDN on <code>AsNoTracking()</code></a></p> <p>Please note that doing so will neither check the cache for existing data, nor will it add the results of the database call to the cache. Additionally, Entity Framework will not automatically detect changes to entities that you retrieve from the database. If you do want to change any entities and save them back to the database, you'll need to attach the changed entities before calling <code>SaveChanges()</code>.</p> <p>Your method is currently:</p> <pre><code>public IList&lt;Models.Example&gt; GetAll() { return DataContext.example.ToList(); } </code></pre> <p>It would change to:</p> <pre><code>public IList&lt;Models.Example&gt; GetAll() { return DataContext.example.AsNoTracking().ToList(); } </code></pre> <p>If you are interested in other options for dealing with EF's cache, I've written a <a href="http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/" rel="noreferrer">blog post about EF6 Cache Busting</a>.</p>
25,569,180
ffmpeg convert without loss quality
<p>I need convert all videos to my video player (in website) when file type is other than flv/mp4/webm.</p> <p>When I use: <code>ffmpeg -i filename.mkv -sameq -ar 22050 filename.mp4</code> :</p> <blockquote> <p>[h264 @ 0x645ee0] error while decoding MB 22 1, bytestream (8786)</p> </blockquote> <p>My point is, what I should do, when I need convert file type: .mkv and other(not supported by jwplayer) to flv/mp4 without quality loss.</p>
48,110,363
5
2
null
2014-08-29 13:21:46.5 UTC
5
2022-07-06 10:15:17.89 UTC
null
null
null
null
3,458,952
null
1
22
ffmpeg|loss
76,372
<p>Instead of -sameq (removed by FFMpeg), use <code>-qscale 0</code> : the file size will increase but it will preserve the quality.</p>
30,280,370
How does Content Security Policy (CSP) work?
<p>I'm getting a bunch of errors in the developer console:</p> <blockquote> <p>Refused to evaluate a string</p> <p>Refused to execute inline script because it violates the following Content Security Policy directive</p> <p>Refused to load the script</p> <p>Refused to load the stylesheet</p> </blockquote> <p>What's this all about? How does Content Security Policy (CSP) work? How do I use the <code>Content-Security-Policy</code> HTTP header?</p> <p>Specifically, how to...</p> <ol> <li>...allow multiple sources?</li> <li>...use different directives?</li> <li>...use multiple directives?</li> <li>...handle ports?</li> <li>...handle different protocols?</li> <li>...allow <code>file://</code> protocol?</li> <li>...use inline styles, scripts, and tags <code>&lt;style&gt;</code> and <code>&lt;script&gt;</code>?</li> <li>...allow <code>eval()</code>?</li> </ol> <p>And finally:</p> <ol start="9"> <li>What exactly does <code>'self'</code> mean?</li> </ol>
30,280,371
2
1
null
2015-05-16 20:22:47.777 UTC
203
2022-08-24 18:25:14.407 UTC
2020-07-20 19:39:08.153 UTC
null
63,550
null
1,697,755
null
1
331
javascript|html|security|http-headers|content-security-policy
309,582
<p>The <code>Content-Security-Policy</code> meta-tag allows you to reduce the risk of <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS</a> attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.</p> <p>I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining <strong>some</strong> points of CSP briefly, mostly concentrating on the things I found hard to solve.</p> <p>For brevity I won’t write the full tag in each sample. Instead I'll only show the <code>content</code> property, so a sample that says <code>content=&quot;default-src 'self'&quot;</code> means this:</p> <pre><code>&lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src 'self'&quot;&gt; </code></pre> <p><strong>1. How can I allow multiple sources?</strong></p> <p>You can simply list your sources after a directive as a space-separated list:</p> <pre><code>content=&quot;default-src 'self' https://example.com/js/&quot; </code></pre> <p>Note that there are no quotes around parameters other than the <em>special</em> ones, like <code>'self'</code>. Also, there's no colon (<code>:</code>) after the directive. Just the directive, then a space-separated list of parameters.</p> <p>Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:</p> <pre><code>https://example.com/js/file.js https://example.com/js/subdir/anotherfile.js </code></pre> <p>These, however, would not be valid:</p> <pre><code>http://example.com/js/file.js ^^^^ wrong protocol https://example.com/file.js ^^ above the specified path </code></pre> <p><strong>2. How can I use different directives? What do they each do?</strong></p> <p>The most common directives are:</p> <ul> <li><code>default-src</code> the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc</li> <li><code>script-src</code> defines valid sources for javascript files</li> <li><code>style-src</code> defines valid sources for css files</li> <li><code>img-src</code> defines valid sources for images</li> <li><code>connect-src</code> defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a <code>400</code> error</li> </ul> <p>There are others, but these are the ones you're most likely to need.</p> <p><strong>3. How can I use multiple directives?</strong></p> <p>You define all your directives inside one meta-tag by terminating them with a semicolon (<code>;</code>):</p> <pre><code>content=&quot;default-src 'self' https://example.com/js/; style-src 'self'&quot; </code></pre> <p><strong>4. How can I handle ports?</strong></p> <p>Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:</p> <pre><code>content=&quot;default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/&quot; </code></pre> <p>The above would result in:</p> <pre><code>https://ajax.googleapis.com:123 ^^^^ Not ok, wrong port https://ajax.googleapis.com - OK http://example.com/free/stuff/file.js ^^ Not ok, only the port 123 is allowed http://example.com:123/free/stuff/file.js - OK </code></pre> <p>As I mentioned, you can also use an asterisk to explicitly allow all ports:</p> <pre><code>content=&quot;default-src example.com:*&quot; </code></pre> <p><strong>5. How can I handle different protocols?</strong></p> <p>By default, only standard protocols are allowed. For example to allow WebSockets <code>ws://</code> you will have to allow it explicitly:</p> <pre><code>content=&quot;default-src 'self'; connect-src ws:; style-src 'self'&quot; ^^^ web Sockets are now allowed on all domains and ports. </code></pre> <p><strong>6. How can I allow the file protocol <code>file://</code>?</strong></p> <p>If you'll try to define it as such it won’t work. Instead, you'll allow it with the <code>filesystem</code> parameter:</p> <pre><code>content=&quot;default-src filesystem&quot; </code></pre> <p><strong>7. How can I use inline scripts and style definitions?</strong></p> <p>Unless explicitly allowed, you can't use inline style definitions, code inside <code>&lt;script&gt;</code> tags or in tag properties like <code>onclick</code>. You allow them like so:</p> <pre><code>content=&quot;script-src 'unsafe-inline'; style-src 'unsafe-inline'&quot; </code></pre> <p>You'll also have to explicitly allow inline, base64 encoded images:</p> <pre><code>content=&quot;img-src data:&quot; </code></pre> <p><strong>8. How can I allow <code>eval()</code>?</strong></p> <p>I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:</p> <pre><code>content=&quot;script-src 'unsafe-eval'&quot; </code></pre> <p><strong>9. What exactly does <code>'self'</code> mean?</strong></p> <p>You might take <code>'self'</code> to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.</p> <p>I've used <code>'self'</code> in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.</p> <p><strong>But hang on a minute!</strong> Can't I just use <code>content=&quot;default-src *&quot;</code> and be done with it?</p> <p>No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though <a href="http://content-security-policy.com/" rel="noreferrer">some docs</a> claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:</p> <pre><code>content=&quot;default-src * 'unsafe-inline' 'unsafe-eval'&quot; </code></pre> <p>... but I trust you won’t.</p> <p><strong>Further reading:</strong></p> <p><a href="http://content-security-policy.com" rel="noreferrer">http://content-security-policy.com</a></p> <p><a href="http://en.wikipedia.org/wiki/Content_Security_Policy" rel="noreferrer">http://en.wikipedia.org/wiki/Content_Security_Policy</a></p>
36,524,238
Include HTML files in R Markdown file?
<h1>Quick Summary</h1> <p>How do I place HTML files <strong><em>in place</em></strong> within an R Markdown file?</p> <h1>Details</h1> <p>I have created some nice animated choropleth maps via <a href="https://cran.r-project.org/web/packages/choroplethr/vignettes/g-animated-choropleths.html" rel="noreferrer">choroplethr</a>.</p> <p>As the link demonstrates, the animated choropleths function via creating a set of PNG images, which are then rolled into an HTML file that cycles through the images, to show the animation. Works great, looks great.</p> <p>But now I want to embed / incorporate these pages within the .Rmd file, so that I have a holistic report including these animated choropleths, along with other work.</p> <p>It seems to me there should be an easy way to do an equivalent to</p> <p>Links:</p> <pre><code>[please click here](http://this.is.where.you.will.go.html) </code></pre> <p>or</p> <p>Images:</p> <pre><code>![cute cat image](http://because.that.is.what.we.need...another.cat.image.html) </code></pre> <p>The images path is precisely what I want: a reference that is "blown up" to put the information in place, instead of just as a link. How can I do this with a full HTML file instead of just an image? Is there any way?</p> <h1>Explanation via Example</h1> <p>Let's say my choropleth HTML file lives in my local path at <code>'./animations/demographics.html'</code>, and I have an R Markdown file like:</p> <pre><code>--- title: 'Looking at the demographics issue' author: "Mike" date: "April 9th, 2016" output: html_document: number_sections: no toc: yes toc_depth: 2 fontsize: 12pt --- # Introduction Here is some interesting stuff that I want to talk about. But first, let's review those earlier demographic maps we'd seen. !![demographics map]('./animations/demographics.html') </code></pre> <p>where I have assumed / pretended that <code>!!</code> is the antecedent that will do precisely what I want: allow me to embed that HTML file in-line with the rest of the report.</p> <h1>Updates</h1> <p>Two updates. Most recently, I still could not get things to work, so I pushed it all up to a <a href="https://github.com/lazarillo/persuasive_analytical_report/tree/master" rel="noreferrer">GitHub repository</a>, in case anyone is willing to help me sort out the problem. Further details can be found at that repo's Readme file.</p> <p>It seems that being able to embed HTML into an R Markdown file would be incredibly useful, so I keep trying to sort it out.</p> <hr> <p>(Older comments)</p> <p>As per some of the helpful suggestions, I tried and failed the following in the R Markdown file:</p> <p>Shiny method:</p> <pre><code>```{r showChoro1} shiny::includeHTML("./animations/demographics.html") ``` </code></pre> <p>(I also added <code>runtime:Shiny</code> up in the YAML portion.)</p> <p><code>htmltools</code> method:</p> <pre><code>```{r showChoro1} htmltools::includeHTML("./animations/demographics.html") ``` </code></pre> <p>(In this case, I made no changes to the YAML.)</p> <p>In the former case (<code>Shiny</code>), it did not work at all. In fact, including the HTML seemed to muck up the functionality of the document altogether, such that the runtime seemed perpetually not-fully-functional. (In short, while it appeared to load everything, the "loading" spindel never went away.)</p> <p>In the latter case, nothing else got messed up, but it was a broken image. Strangely, there was a "choropleth player" ribbon at the top of the document which would work, it's just that none of the images would pop up.</p> <hr> <p>For my own sanity, I also provided simple links, which worked fine.</p> <pre><code>[This link](./animations/demographics.html) worked without a problem, except that it is not embedded, as I would prefer. </code></pre> <p>So it is clearly a challenge with the embedding.</p>
36,525,111
3
4
null
2016-04-10 00:07:11.887 UTC
6
2022-05-17 17:33:33.063 UTC
2016-04-11 00:55:07.463 UTC
null
534,238
null
534,238
null
1
37
html|r|markdown|r-markdown
40,245
<p>Here is a hack (probably inelegant)...idea is to directly insert HTML programmatically in Rmd and then render Rmd.</p> <p>temp.Rmd file:</p> <pre><code>--- title: "Introduction" author: "chinsoon12" date: "April 10, 2016" output: html_document --- &lt;&lt;insertHTML:[test.html] etc, etc, etc ```{r, echo=FALSE} htmltools::includeHTML("test.html") ``` etc, etc, etc </code></pre> <p>test.html file:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;This is an R HTML document. When you click the &lt;b&gt;Knit HTML&lt;/b&gt; button a web page will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:&lt;/p&gt; &lt;p&gt;test test&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>verbose code to replace Rmd code with HTML code and then render (can probably be shortened by a lot)</p> <pre><code>library(stringi) subHtmlRender &lt;- function(mdfile, htmlfile) { #replace &lt;&lt;insertHTML:htmlfile with actual html code #but without beginning white space lines &lt;- readLines(mdfile) toSubcode &lt;- paste0("&lt;&lt;insertHTML:[",htmlfile,"]") location &lt;- which(stri_detect_fixed(lines, toSubcode) ) htmllines &lt;- stri_trim(readLines(htmlfile)) #render html doc newRmdfile &lt;- tempfile("temp", getwd(), ".Rmd") newlines &lt;- c(lines[1:(location-1)], htmllines, lines[min(location+1, length(lines)):length(lines)]) #be careful when insertHTML being last line in .Rmd file write(newlines, newRmdfile) rmarkdown::render(newRmdfile, "html_document") shell(gsub(".Rmd",".html",basename(newRmdfile),fixed=T)) } #end subHtmlRender subHtmlRender("temp.Rmd", "test.html") </code></pre> <hr> <p>EDIT: htmltools::includeHTML also works with the sample files that I provided. Is it because your particular html does not like UTF8-encoding?</p> <hr> <p>EDIT: taking @MikeWilliamson comments into feedback</p> <p>I tried the following </p> <ol> <li>copied and pasted <a href="https://github.com/lazarillo/persuasive_analytical_report/blob/master/SPM/animated_choropleth.html" rel="noreferrer">animated_choropleth.html</a> into a blank .Rmd</li> <li>remove references to cloudfare.com as I had access issues while rendering (see below)</li> <li>knit HTML</li> <li>put back those cloudfare weblinks </li> <li>put the graphs in the same folder as the rendered html</li> <li>open the HTML</li> </ol> <p>I appear to get back the html but am not sure if the result is what you expect</p> <p>Are you also facing the same issue in pt 2? You might want to post the error message and ask for fixes :). This was my error message</p> <pre><code>pandoc.exe: Failed to retrieve http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/css/bootstrap.min.css FailedConnectionException2 "cdnjs.cloudflare.com" 80 False getAddrInfo: does not exist (error 11001) Error: pandoc document conversion failed with error 61 </code></pre>
39,094,349
How to make svg animation with Animated in react-native
<p>ReactNative:</p> <pre><code>&lt;ScrollView style={styles.container}&gt; &lt;Svg height="100" width="100"&gt; &lt;Circle cx="50" cy="50" r="50" stroke="blue" strokeWidth="2.5" fill="green"/&gt; &lt;/Svg&gt; &lt;/ScrollView&gt; </code></pre> <p>I want to make Circle scale with Animated.Value. I have tried this :</p> <pre><code> let AnimatedScrollView = Animated.createAnimatedComponent(ScrollView); let AnimatedCircle = Animated.createAnimatedComponent(Circle); &lt;ScrollView style={styles.container}&gt; &lt;Svg height="100" width="100"&gt; &lt;AnimatedCircle cx="50" cy="50" r={this.state.animator} stroke="blue" strokeWidth="2.5" fill="green"/&gt; &lt;/Svg&gt; &lt;/ScrollView&gt; </code></pre> <p>Then flash back with no error.</p> <p>How can I do?</p> <hr> <p><strong>update 2016.8.24</strong></p> <p>I found a new way instead of requestAnimationFrame :</p> <p>constructor: </p> <pre><code>this.state = { animator: new Animated.Value(0), radius: 1, }; this.state.animator.addListener((p) =&gt; { this.setState({ radius: p.value, }); }); </code></pre> <p>render: </p> <pre><code>&lt;Circle cx="50" cy="50" r={this.state.radius} stroke="blue" strokeWidth="2.5" fill="green"/&gt; </code></pre> <p>But here <a href="http://facebook.github.io/react-native/docs/animated.html" rel="noreferrer">the guides</a> gives advice using it sparingly since it might have performance implications in the future.</p> <p>so what's the best way ?</p>
39,480,283
3
5
null
2016-08-23 06:58:59.877 UTC
9
2017-12-20 11:16:10.18 UTC
2016-08-24 04:23:12.21 UTC
null
6,592,713
null
6,592,713
null
1
15
svg|react-native
28,458
<p>No better answers, and I implemented by adding listener to <code>Animated.Value</code> variable, you can get more info from my question description.</p>
7,482,666
Get AOP proxy from the object itself
<p>Is possible to get the proxy of a given object in Spring? I need to call a function of a subclass. But, obviously, when I do a direct call, the aspects aren't applied. Here's an example:</p> <pre><code>public class Parent { public doSomething() { Parent proxyOfMe = Spring.getProxyOfMe(this); // (please) Method method = this.class.getMethod("sayHello"); method.invoke(proxyOfMe); } } public class Child extends Parent { @Secured("president") public void sayHello() { System.out.println("Hello Mr. President"); } } </code></pre> <p>I've found a way of achieving this. It works, but I think is not very elegant:</p> <pre><code>public class Parent implements BeanNameAware { @Autowired private ApplicationContext applicationContext; private String beanName; // Getter public doSomething() { Parent proxyOfMe = applicationContext.getBean(beanName, Parent.class); Method method = this.class.getMethod("sayHello"); method.invoke(proxyOfMe); } } </code></pre>
7,482,767
3
1
null
2011-09-20 09:04:35.673 UTC
18
2014-06-26 21:42:57.073 UTC
null
null
null
null
167,365
null
1
30
spring|aop|spring-aop
23,537
<p>This hack is extremely awkward, please consider refactoring your code or using AspectJ weaving. You may feel warned, here is the solution</p> <pre><code>AopContext.currentProxy() </code></pre> <p><a href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/aop/framework/AopContext.html#currentProxy()" rel="noreferrer">JavaDoc</a>. I blogged about it <a href="http://nurkiewicz.blogspot.com/2009/09/spring-aop-riddle-demystified.html" rel="noreferrer">here</a> and <a href="http://nurkiewicz.blogspot.com/2009/08/spring-aop-riddle.html" rel="noreferrer">here</a>.</p>
7,654,822
Remove refs/original/heads/master from git repo after filter-branch --tree-filter?
<p>I had the same question as asked here: <a href="https://stackoverflow.com/questions/7193507/new-git-repository-in-root-directory-to-subsume-an-exist-repository-in-a-sub-dire">New git repository in root directory to subsume an exist repository in a sub-directory</a></p> <p>I followed this answer here: <a href="https://stackoverflow.com/questions/7193507/new-git-repository-in-root-directory-to-subsume-an-exist-repository-in-a-sub-dire/7194124#7194124">New git repository in root directory to subsume an exist repository in a sub-directory</a></p> <p>Now, <code>gitk --all</code> shows two histories: one culminating in the current <code>master</code>, and one named <code>original/refs/heads/master</code>.</p> <p>I don't know what this second history is, or how to remove it from the repo. I don't need two histories in my repository.</p> <p>How do I get rid of it?</p> <p>To reproduce yourself:</p> <pre><code>mkdir -p project-root/path/to/module cd project-root/path/to/module mkdir dir1 dir2 dir3 for dir in * ; do touch $dir/source-file-$dir.py ; done git init git add . git commit -m 'Initial commit' </code></pre> <p>Now we have the original poster's problem. Let's move the root of the git repo to project-root using the answer linked above:</p> <pre><code>git filter-branch --tree-filter 'mkdir -p path/to/module ; git mv dir1 dir2 dir3 path/to/module' HEAD rm -rf path cd ../../../ # Now PWD is project-root mv path/to/module/.git . git reset --hard </code></pre> <p>Now, see my current problem:</p> <pre><code>gitk --all &amp; git show-ref </code></pre> <p>How do I get rid of <code>refs/original/heads/master</code> and all associated history?</p>
7,654,880
3
1
null
2011-10-04 22:38:56.47 UTC
70
2018-09-19 08:38:31.657 UTC
2017-05-23 12:34:47.823 UTC
null
-1
null
979,412
null
1
196
git|git-rewrite-history|git-plumbing
47,629
<p><code>refs/original/*</code> is there as a backup, in case you mess up your filter-branch. Believe me, it's a <em>really</em> good idea.</p> <p>Once you've inspected the results, and you're very confident that you have what you want, you can remove the backed up ref:</p> <pre><code>git update-ref -d refs/original/refs/heads/master </code></pre> <p>or if you did this to many refs, and you want to wipe it all out:</p> <pre><code>git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d </code></pre> <p>(That's taken directly from the filter-branch manpage.)</p> <p>This doesn't apply to you, but to others who may find this: If you do a filter-branch which <em>removes</em> content taking up significant disk space, you might also want to run <code>git reflog expire --expire=now --all</code> and <code>git gc --prune=now</code> to expire your reflogs and delete the now-unused objects. (Warning: completely, totally irreversible. Be very sure before you do it.)</p>
7,280,867
What is the difference between writing to a file and a mapped memory?
<p>I have the following questions related to handling files and mapping them (<code>mmap</code>):</p> <ol> <li>We know that if we create a file, and write to that file, then either ways we are writing to the memory. Then why map that file to memory using <code>mmap</code> and then write?</li> <li>If it is because of protection that we are achieving using <code>mmap</code> - <code>PROT_NONE</code>, <code>PROT_READ</code>, <code>PROT_WRITE</code>, then the same level of protection can also be achieved using files. <code>O_RDONLY</code>, <code>O_RDWR</code> etc. Then why <code>mmap</code>?</li> <li>Is there any special advantage we get on mapping files to memory, and then using it? Rather than just creating a file and writing to it?</li> <li>Finally, suppose we <code>mmap</code> a file to memory, if we write to that memory location returned by mmap, does it also simultaneously write to that file as well?</li> </ol> <h2>Edit: sharing files between threads</h2> <p>As far as I know, if we share a file between two threads (not process) then it is advisable to <code>mmap</code> it into memory and then use it, rather than directly using the file.</p> <p>But we know that using a file means, it is surely in main memory, then why again the threads needs to be mmaped?</p>
7,280,929
4
0
null
2011-09-02 08:21:20.037 UTC
11
2019-10-22 21:31:10.24 UTC
2019-10-22 21:31:10.24 UTC
null
472,495
null
575,281
null
1
19
c|linux|file|mmap
12,066
<p>A memory mapped file is actually partially or wholly mapped in memory (RAM), whereas a file you write to would be written to memory and then flushed to disk. A memory mapped file is taken from disk and placed into memory explicitly for reading and/or writing. It stays there until you unmap it. </p> <p>Access to disk is slower, so when you've written to a file, it will be flushed to disk and no longer reside in RAM, which means, that next time you need the file, you might be going to get it from disk (slow), whereas in memory mapped files, you know the file is in RAM and you can have faster access to it then when it's on disk.</p> <p>Also, mememory mapped files are often used as an IPC mechanism, so two or more processes can easily share the same file and read/write to it. (using necessary sycnh mechanisms)</p> <p>When you need to read a file often, and this file is quite large, it can be advantageous to map it into memory so that you have faster access to it then having to go open it and get it from disk each time. </p> <p><strong>EDIT:</strong></p> <p>That <strong>depends</strong> on your needs, when you have a file that will need to be accessed very frequently by different threads, then I'm not sure that memory mapping the file will necessarily be a good idea, from the view that, you'll need to synch access to this mmap'ed file if you wish it write to it, in the same places from different threads. If that happens very often, it could be a spot for resource contention.</p> <p>Just reading from the file, then this might be a good solution, cause you don't really need to synch access, if you're <strong>only</strong> reading from it from multiple threads. The moment you start writing, you <strong>do have to</strong> use synch mechanisms.</p> <p>I suggest, that you have each thread do it's own file access in a thread local way, if you have to write to the file, just like you do with any other file. In this way it reduces the need for thread synchronization and the likelyhood of bugs hard to find and debug.</p>
7,709,320
jQuery UI Datepicker enable only specific days in array
<p>I am trying to disable all dates in a datepicker and only enable dates which are in an array. This is the code I have so far <a href="http://jsfiddle.net/peter/yXMKC/" rel="noreferrer">http://jsfiddle.net/peter/yXMKC/</a> the problem is only May 14th shows up as enabled. The others are all disabled. Any ideas? </p> <pre><code>var availableDates = ["9-5-2011","14-5-2011","15-5-2011"]; function available(date) { dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear(); if ($.inArray(dmy, availableDates) == 1) { return [true, "","Available"]; } else { return [false,"","unAvailable"]; } } $('#date').datepicker({ beforeShowDay: available }); </code></pre>
7,709,464
1
1
null
2011-10-10 06:45:02.84 UTC
10
2011-10-10 07:02:12.26 UTC
null
null
null
null
804,087
null
1
29
jquery|jquery-ui|datepicker
56,590
<p>$.inArray(dmy, availableDates) returns the index of the element, so when you compare with 1 only 14-5-2011 will match. Check for not equal to -1. Should work.</p> <p>Fiddle - <a href="http://jsfiddle.net/yXMKC/4/" rel="noreferrer">http://jsfiddle.net/yXMKC/4/</a></p> <pre><code>var availableDates = ["9-5-2011","14-5-2011","15-5-2011"]; function available(date) { dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear(); console.log(dmy+' : '+($.inArray(dmy, availableDates))); if ($.inArray(dmy, availableDates) != -1) { return [true, "","Available"]; } else { return [false,"","unAvailable"]; } } </code></pre>
1,783,312
Using Parameters in DATEADD function of a Query
<p>I am trying to us the <a href="http://technet.microsoft.com/en-us/library/ms186819.aspx" rel="noreferrer">DateAdd</a> function of SQL in my Query. The problem is when I use a parameter to set the second arguement, the <em>number</em> argument I get an error which will say something like this:</p> <blockquote> <p>Failed to convert parameter value from a Decimal to a DateTime</p> </blockquote> <p>While if I enter it parameterless, i.e hardcode an Int, it works fine.</p> <p>This works:</p> <pre><code>SELECT FieldOne, DateField FROM Table WHERE (DateField&gt; DATEADD(day, -10, GETDATE())) </code></pre> <p>while this does not:</p> <pre><code>SELECT FieldOne, DateField FROM Table WHERE (DateField&gt; DATEADD(day, @days, GETDATE())) </code></pre> <p>Where @days = -10</p> <p>Any ideas into what I am doing wrong? Incidentally I am setting this variable in SQL Server Manager, as I am trying to work out a bug in my DataAccess code. Not sure if that makes a difference. </p> <p>Thanks</p>
1,783,361
4
2
null
2009-11-23 14:07:50.35 UTC
1
2019-04-26 13:18:39.167 UTC
null
null
null
null
35,454
null
1
5
sql-server|parameters|dateadd
39,080
<p>It sounds like you're passing the decimal as the 3rd instead of the 2nd parameter to <code>DATEADD()</code>, like:</p> <pre><code>DATEADD(day, GETDATE(), @days) </code></pre> <p>Although the snippet in the question looks fine.</p> <p>(For extra clarity, the snippet above is an error. This is the code that would generate the error from the question.)</p>
1,786,509
How do I fix the 'Out of range value adjusted for column' error?
<p>I went into phpMyAdmin and changed the value for an integer(15)field to a 10-digit number, so everything should work fine. I entered the value '4085628851' and I am receiving the following error:</p> <blockquote> <p>Warning: #1264 Out of range value adjusted for column 'phone' at row 1</p> </blockquote> <p>It then changes the value to '2147483647'.</p> <p>After some googling, I found this article that explains how to fix the problem. <a href="http://webomania.wordpress.com/2006/10/01/out-of-range-value-adjusted-for-column-error/" rel="noreferrer">http://webomania.wordpress.com/2006/10/01/out-of-range-value-adjusted-for-column-error/</a>, but I don't know how to login to the Mysql shell. </p> <p>How do I login to the Mysql shell? How do I fix this error?</p>
1,786,540
4
1
null
2009-11-23 22:29:01.667 UTC
null
2019-05-02 23:21:12.523 UTC
null
null
null
null
83,916
null
1
17
mysql|range
80,857
<p>The value you were trying to set is too large for a signed <code>INT</code> field. The display width <code>(15)</code> does not affect the range of values that can be stored, only how the value is displayed.</p> <p>Ref: <a href="http://dev.mysql.com/doc/refman/5.1/en/numeric-types.html" rel="nofollow noreferrer">MySQL Docs on numerics</a></p> <p>On phone numbers - see <a href="https://stackoverflow.com/questions/1547920/is-it-better-to-store-telephone-numbers-in-some-canonical-format-or-as-entered">Is it better to store telephone numbers in some canonical format or &quot;as entered&quot;?</a></p>
1,552,058
How to implement precompiled headers into your project
<p>I understand the purpose and reasoning behind precompiled headers. However, what are the rules when implementing them? From my understanding, it goes something like this:</p> <ol> <li>Set your project up to use precompiled headers with the YU directive.</li> <li>Create your stdafx.h file and set that to be your precompiled header.</li> <li>Include this as the top include statement in each of your .h files.</li> </ol> <p>It this correct? Should you exclude the including it in the files that are included within your precompiled header? Currently, I get the following compilation error when following my intuition with this:</p> <blockquote> <p>error C2857: '#include' statement specified with the /Ycstdafx.h command-line option was not found in the source file</p> </blockquote> <p>The command-line options are as such:</p> <blockquote> <p>/Od /I "../External/PlatformSDK/Include" /I ".." /I "../External/atlmfc/Include" /D "_DEBUG" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /MDd /Yc"stdafx.h" /Fp"....\Output\LudoCore\Debug\LudoCore.pch" /Fo"....\Output\LudoCore\Debug\" /Fd"....\Output\LudoCore\Debug\vc80.pdb" /W4 /WX /nologo /c /ZI /TP /wd4201 /errorReport:prompt</p> </blockquote>
1,552,104
4
0
null
2009-10-11 23:15:07.737 UTC
18
2015-11-17 16:13:34.663 UTC
2009-10-12 02:03:38.147 UTC
null
104,060
null
104,060
null
1
24
c++|visual-c++|visual-studio-2005|include|precompiled-headers
43,016
<p>You stdafx.cpp should include stdafx.h and be built using <code>/Yc"stdafx.h"</code>.</p> <p>Your other *.cpp should be include stdafx.h and be built using <code>/Yu"stdafx.h"</code>.</p> <p>Note the double-quote characters used in the compiler options!</p> <p>Here's a screenshot of the Visual Studio settings for stdafx.cpp to create a precompiled header:</p> <p><img src="https://i.stack.imgur.com/pGa0W.gif" alt="create precompiled header"></p> <p>Here are the corresponding command-line options (which are read-only but reflect the settings specified on other pages; note that the IDE inserts double-quote characters around the filename, in the compiler option):</p> <p><img src="https://i.stack.imgur.com/dGtSM.gif" alt="options"></p> <p>This is what's in my stdafx.cpp file:</p> <pre><code>// stdafx.cpp : source file that includes just the standard includes // CallWinsock.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file </code></pre>
1,912,481
WPF TreeView HierarchicalDataTemplate - binding to object with multiple child collections
<p>I am trying to get a <code>TreeView</code> to bind my collection so that all groups show nested groups and each group will show entry.</p> <p>How can I use the <code>HierarchicalDataTemplate</code> so that the <code>TreeView</code> will process both SubGroups and Entries collection?</p> <p>Groups show subgroups and entries:</p> <pre><code>Example: Group1 --Entry --Entry Group2 --Group4 ----Group1 ------Entry ------Entry ----Entry ----Entry --Entry --Entry Group3 --Entry --Entry </code></pre> <p><br></p> <h2>Objects:</h2> <hr /> <pre><code>namespace TaskManager.Domain { public class Entry { public int Key { get; set; } public string Name { get; set; } } } namespace TaskManager.Domain { public class Group { public int Key { get; set; } public string Name { get; set; } public IList&lt;Group&gt; SubGroups { get; set; } public IList&lt;Entry&gt; Entries { get; set; } } } </code></pre> <h2>Test data:</h2> <hr /> <pre><code>namespace DrillDownView { public class TestData { public IList&lt;Group&gt; Groups = new List&lt;Group&gt;(); public void Load() { Group grp1 = new Group() { Key = 1, Name = "Group 1", SubGroups = new List&lt;Group&gt;(), Entries = new List&lt;Entry&gt;() }; Group grp2 = new Group() { Key = 2, Name = "Group 2", SubGroups = new List&lt;Group&gt;(), Entries = new List&lt;Entry&gt;() }; Group grp3 = new Group() { Key = 3, Name = "Group 3", SubGroups = new List&lt;Group&gt;(), Entries = new List&lt;Entry&gt;() }; Group grp4 = new Group() { Key = 4, Name = "Group 4", SubGroups = new List&lt;Group&gt;(), Entries = new List&lt;Entry&gt;() }; //grp1 grp1.Entries.Add(new Entry() { Key=1, Name="Entry number 1" }); grp1.Entries.Add(new Entry() { Key=2, Name="Entry number 2" }); grp1.Entries.Add(new Entry() { Key=3,Name="Entry number 3" }); //grp2 grp2.Entries.Add(new Entry(){ Key=4, Name = "Entry number 4"}); grp2.Entries.Add(new Entry(){ Key=5, Name = "Entry number 5"}); grp2.Entries.Add(new Entry(){ Key=6, Name = "Entry number 6"}); //grp3 grp3.Entries.Add(new Entry(){ Key=7, Name = "Entry number 7"}); grp3.Entries.Add(new Entry(){ Key=8, Name = "Entry number 8"}); grp3.Entries.Add(new Entry(){ Key=9, Name = "Entry number 9"}); //grp4 grp4.Entries.Add(new Entry(){ Key=10, Name = "Entry number 10"}); grp4.Entries.Add(new Entry(){ Key=11, Name = "Entry number 11"}); grp4.Entries.Add(new Entry(){ Key=12, Name = "Entry number 12"}); grp4.SubGroups.Add(grp1); grp2.SubGroups.Add(grp4); Groups.Add(grp1); Groups.Add(grp2); Groups.Add(grp3); } } } </code></pre> <h2>XAML:</h2> <hr /> <pre><code>&lt;Window x:Class="DrillDownView.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TaskManager.Domain;assembly=TaskManager.Domain" Title="Window2" Height="300" Width="300"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;TreeView Name="GroupView" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}"&gt; &lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Group}" ItemsSource="{Binding SubGroups}"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Entry}" ItemsSource="{Binding Entries}"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/TreeView.Resources&gt; &lt;/TreeView&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <h2>XAML.CS:</h2> <hr /> <pre><code>public partial class Window2 : Window { public Window2() { InitializeComponent(); LoadView(); } private void LoadView() { TestData data = new TestData(); data.Load(); GroupView.ItemsSource = data.Groups; } } </code></pre>
1,912,682
4
4
null
2009-12-16 05:21:19.883 UTC
27
2020-09-10 15:32:50.117 UTC
2017-09-27 10:49:04.373 UTC
null
4,558,029
null
12,242
null
1
65
c#|wpf|xaml|treeview|hierarchicaldatatemplate
97,528
<p>A <code>HierarchicalDataTemplate</code> is a way of saying 'this is how you render this type of object and here is a property that can be probed to find the child nodes under this object'</p> <p>Therefore you need a single property that returns the 'children' of this node. e.g. (If you can't make both Group and Entry derive from a common Node type)</p> <pre><code>public class Group{ .... public IList&lt;object&gt; Items { get { IList&lt;object&gt; childNodes = new List&lt;object&gt;(); foreach (var group in this.SubGroups) childNodes.Add(group); foreach (var entry in this.Entries) childNodes.Add(entry); return childNodes; } } </code></pre> <p>Next you don't need a <code>HierarchicalDataTemplate</code> for entry since an entry doesn't have children. So the XAML needs to be changed to use the new Items property and a <code>DataTemplate</code> for Entry:</p> <pre><code>&lt;TreeView Name="GroupView" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}"&gt; &lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Group}" ItemsSource="{Binding Items}"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;DataTemplate DataType="{x:Type local:Entry}" &gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;/DataTemplate&gt; &lt;/TreeView.Resources&gt; &lt;/TreeView&gt; </code></pre> <p>And here's what that looks like. <img src="https://lh4.ggpht.com/_nxgDpneh8yk/Syh6K2zgFxI/AAAAAAAAAzQ/QIRgTsKqhlk/s288/HierarchicalDataTemplate_longDay.jpg" alt="Screenshot of Output"></p>
1,634,216
What is 'PermSize' in Java?
<p>I was going through the document in <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf" rel="noreferrer">Java Memory Management</a> and in that I came across PermSize which I couldn't understand. The document says that it stores, "JVM stores its metadata", but I couldn't exactly get what is meant by metadata. I was googling and somewhere I read it stores a value object (user defined object).</p> <p>What kind of objects are stored there? An example with an explanation would be great.</p>
1,634,424
4
3
null
2009-10-27 23:12:10.3 UTC
16
2018-08-22 20:18:33.903 UTC
2012-09-27 22:20:57.337 UTC
null
132,565
null
135,334
null
1
69
java|memory
165,935
<p>A quick definition of the "permanent generation":</p> <blockquote> <p>"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." <a href="http://java.sun.com/docs/hotspot/gc1.4.2/faq.html" rel="noreferrer">[ref]</a></p> </blockquote> <p>In other words, this is where class definitions go (and this explains why you may get the message <code>OutOfMemoryError: PermGen space</code> if an application loads a large number of classes and/or on redeployment).</p> <p>Note that <strong><code>PermSize</code></strong> is additional to the <strong><code>-Xmx</code></strong> value set by the user on the JVM options. But <strong><code>MaxPermSize</code></strong> allows for the JVM to be able to grow the <strong><code>PermSize</code></strong> to the amount specified. Initially when the VM is loaded, the <strong><code>MaxPermSize</code></strong> will still be the default value (32mb for <code>-client</code> and 64mb for <code>-server</code>) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH <strong><code>PermSize</code></strong> and <strong><code>MaxPermSize</code></strong> to 256mb, you would notice that the overall heap has increased by 256mb additional to the <strong><code>-Xmx</code></strong> setting.</p>
71,713,405
Cannot find module 'react-dom/client' from 'node_modules/@testing-library/react/dist/pure.js'
<p>hope someone could help me here.</p> <p>while running npm test got following mistake</p> <pre><code>Cannot find module 'react-dom/client' from 'node_modules/@testing-library/react/dist/pure.js' Required stack: node_modules/@testing-library/react/dist/pure.js node_modules/@testing-library/react/dist/index.js </code></pre> <p>all neccesserry packages seem to be installed. I was trying to reinstall react-dom and didnot help. Below providing imports used in my test file:</p> <pre><code>import React from &quot;react&quot;; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import '@testing-library/jest-dom'; </code></pre> <p>was trying to solve this for few days... thank you in advance for any help</p> <p>P.S.Additionally providing my package.json</p> <pre><code>{ &quot;name&quot;: &quot;fe&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@fontsource/roboto&quot;: &quot;^4.5.3&quot;, &quot;@material-ui/core&quot;: &quot;^4.12.3&quot;, &quot;@material-ui/icons&quot;: &quot;^4.11.2&quot;, &quot;@mui/icons-material&quot;: &quot;^5.5.0&quot;, &quot;@mui/material&quot;: &quot;5.5.3&quot;, &quot;@mui/styles&quot;: &quot;^5.5.1&quot;, &quot;@reduxjs/toolkit&quot;: &quot;^1.8.0&quot;, &quot;@testing-library/jest-dom&quot;: &quot;5.16.3&quot;, &quot;@testing-library/react&quot;: &quot;13.0.0&quot;, &quot;@testing-library/user-event&quot;: &quot;14.0.4&quot;, &quot;axios&quot;: &quot;^0.26.1&quot;, &quot;react&quot;: &quot;^17.0.2&quot;, &quot;react-dom&quot;: &quot;^17.0.2&quot;, &quot;react-hook-form&quot;: &quot;^7.28.1&quot;, &quot;react-redux&quot;: &quot;^7.2.6&quot;, &quot;react-router-dom&quot;: &quot;^6.2.2&quot;, &quot;react-scripts&quot;: &quot;5.0.0&quot;, &quot;redux&quot;: &quot;^4.1.2&quot;, &quot;styled-components&quot;: &quot;^5.3.5&quot;, &quot;web-vitals&quot;: &quot;^2.1.4&quot;, &quot;yup&quot;: &quot;^0.32.11&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;devDependencies&quot;: { &quot;@types/jest&quot;: &quot;^27.4.0&quot;, &quot;@types/node&quot;: &quot;^16.11.25&quot;, &quot;@types/react&quot;: &quot;^17.0.39&quot;, &quot;@types/react-dom&quot;: &quot;^17.0.11&quot;, &quot;@types/styled-components&quot;: &quot;^5.1.24&quot;, &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^5.12.0&quot;, &quot;@typescript-eslint/parser&quot;: &quot;^5.12.0&quot;, &quot;eslint&quot;: &quot;^8.9.0&quot;, &quot;eslint-config-airbnb&quot;: &quot;^19.0.4&quot;, &quot;eslint-config-prettier&quot;: &quot;^8.4.0&quot;, &quot;eslint-import-resolver-typescript&quot;: &quot;^2.5.0&quot;, &quot;eslint-plugin-import&quot;: &quot;^2.25.4&quot;, &quot;eslint-plugin-jsx-a11y&quot;: &quot;^6.5.1&quot;, &quot;eslint-plugin-prettier&quot;: &quot;^4.0.0&quot;, &quot;eslint-plugin-react&quot;: &quot;^7.28.0&quot;, &quot;eslint-plugin-react-hooks&quot;: &quot;^4.3.0&quot;, &quot;prettier&quot;: &quot;2.5.1&quot;, &quot;typescript&quot;: &quot;^4.5.5&quot; } } </code></pre>
71,716,438
5
3
null
2022-04-01 22:42:33.917 UTC
3
2022-07-29 08:23:04.963 UTC
2022-05-01 07:52:30.337 UTC
null
17,173,516
null
17,173,516
null
1
66
reactjs|typescript|unit-testing
39,926
<p>I think it's because your @testing-library/react using the newer version, just test with version of 12.1.2</p>
7,205,964
How to build task 'assets:precompile'
<p>I'm getting that error on my production server, and can't figure out why. It happens when running this command:</p> <pre><code>bundle exec rake assets:precompile RAILS_ENV=production </code></pre> <p>I'm using Rails 3.1.0.rc6</p>
7,262,159
5
7
null
2011-08-26 14:12:27.76 UTC
8
2018-07-24 13:39:12.527 UTC
2017-04-11 16:03:49.557 UTC
null
1,033,581
null
202,875
null
1
32
ruby-on-rails|ruby-on-rails-3|ruby-on-rails-3.1|production|asset-pipeline
19,957
<p>This is most likely due your <code>config/application.rb</code> not requiring <code>rails/all</code> (the default), but some custom requires.</p> <p>To resolve this, add the following to <code>config/application.rb</code>:</p> <pre><code>require 'sprockets/railtie' </code></pre>
7,197,790
Cannot convert string to GUID in C#.NET
<p>Why would the cast (to a System.Guid type) statement be invalid (second line in try block)?</p> <p>For example, suppose I have a string with a value of "5DD52908-34FF-44F8-99B9-0038AFEFDB81". I'd like to convert that to a GUID. Is that not possible?</p> <pre><code> Guid ownerIdGuid = Guid.Empty; try { string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString(); ownerIdGuid = (Guid)ownerId; } catch { // Implement catch } </code></pre>
7,197,808
6
14
null
2011-08-25 22:04:47.58 UTC
5
2017-11-04 22:39:05.807 UTC
2017-08-10 00:36:20.24 UTC
null
63,550
null
640,205
null
1
41
c#|string|.net-3.5|casting|guid
108,850
<p>Try this:</p> <pre><code>Guid ownerIdGuid = Guid.Empty; try { string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString(); ownerIdGuid = new Guid(ownerId); } catch { // implement catch } </code></pre>
7,613,335
How to Set Base URL in Yii Framework
<p>When I do</p> <pre><code>print_r(Yii::app()-&gt;request-&gt;baseUrl) </code></pre> <p>I get an empty string. A post on the Yii forum says <a href="http://www.yiiframework.com/forum/index.php?/topic/23890-yiiapp-request-baseurl-doesnt-work/page__view__findpost__p__116111">this is blank by default</a>. How can I change its default value so that I can use absolute URLs?</p>
7,618,679
7
5
null
2011-09-30 16:27:31.787 UTC
3
2018-03-30 04:09:41.47 UTC
2013-10-10 21:03:36.697 UTC
null
727,208
null
553,994
null
1
9
php|yii|yii-routing
76,281
<p>As the post in that forum says, it might be different for different platforms, or if the web app isnt located in the default folder.<br/> All these things work for me: <br/></p> <pre><code>echo Yii::app()-&gt;request-&gt;baseUrl."&lt;br/&gt;" ; print_r(Yii::app()-&gt;request-&gt;baseUrl); echo "&lt;br/&gt;"; var_dump(Yii::app()-&gt;getBaseUrl(true)); echo "&lt;br/&gt;"; echo Yii::app()-&gt;request-&gt;getBaseUrl(true); </code></pre> <p>I used yiic to create the web app, with default settings using the following command in a terminal, <code>yiic webapp /path/to/webapp</code><br/> So that generates the necessary directory structure for the web app, and also the default skeleton files. Try it and then see how it works. I'm new to yii myself.</p> <p><strong>Edit:</strong></p> <p>This solution might have worked for the op, but the correct way baseUrl can be set is shown by <a href="https://stackoverflow.com/a/11211440/720508" title="https://stackoverflow.com/a/11211440/720508">ecco's answer to this question</a>.</p>
7,671,282
Android linear layout align center and right
<p>This is what I have:</p> <p><img src="https://i.stack.imgur.com/FH6X9.png" alt="enter image description here"></p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#FFFFFF"&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:background="#E30000" android:layout_gravity="center_horizontal|center_vertical" android:gravity="center_horizontal|center_vertical"&gt; &lt;TextView android:id="@+id/TextView00" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="20px" android:textStyle="bold" android:text="Something" android:gravity="right|center_vertical" /&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:gravity="right|center_vertical" android:layout_gravity="center_vertical" android:background="#E30000"&gt; &lt;Button android:id="@+id/btnCalls" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/icon" android:gravity="right|center_vertical" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>And I want this:</p> <p><img src="https://i.stack.imgur.com/bEeEK.png" alt="enter image description here"></p> <p>So horizontal center align the text and vertical center align the button.</p> <p>What am I missing? I haven't tried RelativeLayout and I would prefer LinearLayout to work this out.</p>
7,671,379
9
0
null
2011-10-06 07:22:38.04 UTC
4
2018-01-10 12:14:23.51 UTC
2017-06-02 02:58:29.603 UTC
null
210,916
null
571,648
null
1
13
android|layout|android-linearlayout|center
51,346
<p>try this one </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#FFFFFF"&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:background="#E30000" android:layout_gravity="center_horizontal|center_vertical" android:gravity="center_vertical"&gt; &lt;TextView android:id="@+id/TextView00" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="20px" android:textStyle="bold" android:text="Something" android:layout_weight="1" android:gravity="center"/&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:gravity="right|center_vertical" android:layout_gravity="center_vertical" android:background="#E30000" android:layout_width="wrap_content"&gt; &lt;Button android:id="@+id/btnCalls" android:layout_width="wrap_content" android:drawableLeft="@drawable/icon" android:gravity="right|center_vertical" android:layout_height="wrap_content" android:layout_margin="5dip"/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
7,312,468
JavaScript: Round to a number of decimal places, but strip extra zeros
<p>Here's the scenario: I'm getting <code>.9999999999999999</code> when I should be getting <code>1.0</code>.<br> I can afford to lose a decimal place of precision, so I'm using <code>.toFixed(15)</code>, which kind of works.</p> <p>The rounding works, but the problem is that I'm given <code>1.000000000000000</code>.<br> <strong>Is there a way to round to a number of decimal places, but strip extra whitespace?</strong></p> <p>Note: <code>.toPrecision</code> isn't what I want; I only want to specify how many numbers after the decimal point.<br> Note 2: I can't just use <code>.toPrecision(1)</code> because I need to keep the high precision for numbers that actually have data after the decimal point. Ideally, there would be exactly as many decimal places as necessary (up to 15).</p>
7,312,534
10
2
null
2011-09-05 20:26:08.253 UTC
19
2022-06-14 10:27:31.117 UTC
2011-09-05 20:33:17.913 UTC
null
515,160
null
515,160
null
1
101
javascript|math|floating-point|rounding
107,740
<pre><code>&gt;&gt;&gt; parseFloat(0.9999999.toFixed(4)); 1 &gt;&gt;&gt; parseFloat(0.0009999999.toFixed(4)); 0.001 &gt;&gt;&gt; parseFloat(0.0000009999999.toFixed(4)); 0 </code></pre>
14,013,261
How to loop through a SortedList, getting both the key and the value
<p>The following code loops through a list and gets the values, but how would I write a similar statement that gets both the keys and the values </p> <pre><code>foreach (string value in list.Values) { Console.WriteLine(value); } </code></pre> <p>e.g something like this</p> <pre><code> foreach (string value in list.Values) { Console.WriteLine(value); Console.WriteLine(list.key); } </code></pre> <p>code for the list is:</p> <pre><code>SortedList&lt;string, string&gt; list = new SortedList&lt;string, string&gt;(); </code></pre>
14,013,268
4
0
null
2012-12-23 17:54:48.683 UTC
4
2016-01-13 19:42:22.397 UTC
2012-12-23 17:56:40.393 UTC
null
14,357
null
1,240,649
null
1
22
c#|sortedlist
42,151
<pre><code>foreach (KeyValuePair&lt;string, string&gt; kvp in list) { Console.WriteLine(kvp.Value); Console.WriteLine(kvp.Key); } </code></pre> <p>From <a href="http://msdn.microsoft.com/en-us/library/ms132335.aspx" rel="noreferrer">msdn</a>:</p> <p>GetEnumerator returns an enumerator of type <code>KeyValuePair&lt;TKey, TValue&gt;</code> that iterates through the <code>SortedList&lt;TKey, TValue&gt;</code>.</p> <p>As Jon stated, you can use <code>var</code> keyword instead of writing type name of iteration variable (type will be inferred from usage):</p> <pre><code>foreach (var kvp in list) { Console.WriteLine(kvp.Value); Console.WriteLine(kvp.Key); } </code></pre>
9,490,322
MVC 3 Razor. Partial View validation is not working
<p>I'm having the problem that I cannot get client-side validation to fire from within my partial view, that loads into a div after a user clicks a button. In this example I've stopped the div from "toggling" to see if the validation fires, but to no avail, nothing happens.</p> <p>Luckily, the model doesn't accept any invalid input, but it also doesn't warn the user of the actual mistake. Any help would be appreciated.</p> <p><strong>Here is my Model:</strong></p> <pre><code>public class Help { [HiddenInput(DisplayValue=true)] public int HelpID { get; set; } [Required(ErrorMessage = "Please enter a proper URL")] public string URL { get; set; } [Required(ErrorMessage = "Please enter a content description:")] [DataType(DataType.MultilineText)] public string HelpContent { get; set; } /*? 2 properites are nullable*/ public DateTime? createDateTime { get; set; } public DateTime? modifiedDateTime { get; set; } } </code></pre> <p><strong>Here is my Controller:</strong></p> <pre><code>namespace HelpBtn.WebUI.Controllers { /*Create the admin controller*/ public class AdminController : Controller { //declare interface object private IHelpRepository repository; /*Pass a db interface to controller*/ public AdminController(IHelpRepository repo) { repository = repo; } /*default admin screen. displays help table obs*/ public ViewResult Index() { return View(); } /*Returns add view form*/ public ViewResult AddForm() { return View(); } /*Returns edit view form, searches for object to edit with id if no id provided, 0 by default*/ public ViewResult EditForm(int helpID = 0) { Help help = repository.Help.FirstOrDefault(q =&gt; q.HelpID == helpID); return View(help); } /*Will handle the post for the edit screen after user has submitted edit information*/ [HttpPost] [ValidateInput(false)] //this allows admin to place html in field. may cause validation problems public ActionResult EditForm(Help help) { if (ModelState.IsValid) //if all fields are validated { //set the edit date help.modifiedDateTime = DateTime.Now; repository.SaveHelp(help); return RedirectToAction("Index"); } else //there is something wrong. send back to view { return View(help); } } /*Delete action method, searches with id*/ [AcceptVerbs(HttpVerbs.Post)] [GridAction] public ActionResult Delete(int helpId) { Help helpDel = repository.Help.FirstOrDefault(p =&gt; p.HelpID == helpId); if (helpDel != null) //if the object is found, delete { repository.DeleteHelp(helpDel); } //in all cases return to index return RedirectToAction("Index"); } /*Used by the telerik table to rebind grid*/ [GridAction] public ActionResult AjaxBinding() { return View(new GridModel(repository.Help)); } }//end admin class }//end namespace </code></pre> <p><strong>Here is my Main View:</strong></p> <pre><code>&lt;div id="addContent" style="display: none"&gt;&lt;/div&gt; //Select Function. saves selected row function onRowSelect(e) { HelpID = e.row.cells[0].innerHTML; } //end onRowSelect //Refresh grid function function refreshGrid() { $("#Grid").data('tGrid').rebind(); } //end refresh grid //Variables. '$' b4 name for intellisense var HelpID; var $editContent = $("#editContent"); var $addContent = $("#addContent"); //end variables //Add Form call. loads partial view to div:content $("#Add").click(function () { $editContent.hide(); $editContent.html(""); $.ajax({ type: "Get", url: "/Admin/AddForm", datatype: "html", success: function (data) { $addContent.html(data); $addContent.toggle(); } //end success }); //end ajax }); //end add //Edit Form call. loads partial view to div:content $("#Edit").click(function () { $addContent.hide(); $addContent.html(""); $.ajax({ type: "Get", url: "/Admin/EditForm", dataType: "html", data: { HelpID: HelpID }, success: function (data) { $editContent.html(data); $editContent.toggle(); } //end sucess }); //end ajax }); //end edit //Delete call. deletes selected row in table $("#Delete").live('click', function () { $.post("/Admin/Delete", { HelpID: HelpID }, function () { $addContent.html(""); $editContent.html(""); refreshGrid(); }); //end function }); //end delete //post add form data back to server $("#btnAdd").live('click', function (e) { e.preventDefault(); $.post($('#Addx').attr('action'), $('#Addx').serialize(), function (data) { refreshGrid(); $addContent.html(""); }); //end post e.preventDefault(); }); // end .live //post edit form data back to server $("#btnEdit").live('click', function (e) { $.post($('#Editx').attr('action'), $('#Editx').serialize(), function (data) { refreshGrid(); $editContent.html(""); }); e.preventDefault(); }); //end post edit </code></pre> <p><strong>And here is my partial view, that loads into the main page's div:</strong></p> <pre><code>@model HelpBtn.Domain.Entities.Help @*THIS POSTS BACK TO EDIT/ADMIN. needs to be asynchronous*@ @using (Html.BeginForm("EditForm", "Admin", FormMethod.Post, new { id = "Addx" })) { &lt;fieldset&gt; &lt;legend&gt;Add Entry&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.URL) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.URL) @Html.ValidationMessageFor(model =&gt; model.URL) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.HelpContent, "Help Content") &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.HelpContent) &lt;p&gt; @Html.ValidationMessageFor(model =&gt; model.HelpContent, "Enter a value") &lt;/p&gt; &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.createDateTime, "Created Date") &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.createDateTime) @Html.ValidationMessageFor(model =&gt; model.createDateTime) &lt;/div&gt; &lt;p&gt; &lt;input id="btnAdd" type="submit" value="Create" /&gt; &lt;/p&gt; &lt;/fieldset&gt; } </code></pre>
9,490,670
1
1
null
2012-02-28 21:52:55.07 UTC
12
2016-06-29 09:29:27.563 UTC
2014-02-24 16:54:03.103 UTC
null
1,404,206
null
1,238,864
null
1
11
asp.net-mvc|asp.net-mvc-3|razor
18,147
<p>Everytime you perform an AJAX call and substitute some part of your DOM with partial HTML contents returned by the controller action you need to reparse the client side unobtrusive validation rules. So in your AJAX success callbacks when after you call the <code>.html()</code> method to refresh the DOM you need to parse:</p> <pre><code>$('form').removeData('validator'); $('form').removeData('unobtrusiveValidation'); $.validator.unobtrusive.parse('form'); </code></pre>
9,195,304
How to Use Content-disposition for force a file to download to the hard drive?
<p>I want to force the browser to download a <code>pdf</code> file.</p> <p>I am using the following code :</p> <pre><code>&lt;a href="../doc/quot.pdf" target=_blank&gt;Click here to Download quotation&lt;/a&gt; </code></pre> <p>It makes the browser open the pdf in a new window, but I want it to download to the hard drive when a user clicks it.</p> <p>I found that <code>Content-disposition</code> is used for this, but how do I use it in my case?</p>
9,195,376
2
1
null
2012-02-08 14:33:06.01 UTC
13
2020-12-02 07:59:14.387 UTC
2013-12-05 17:09:35.11 UTC
null
993,915
null
1,118,830
null
1
90
html|download|httpresponse|content-disposition
164,437
<p>On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:</p> <pre><code>Content-Disposition: attachment; filename=quot.pdf; </code></pre> <p>See <a href="http://en.wikipedia.org/wiki/MIME#Content-Disposition">content-disposition</a> on the wikipedia MIME page.</p>
58,780,817
Using optional chaining operator for object property access
<p>TypeScript 3.7 now supports the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining" rel="noreferrer">optional chaining operator</a>. Hence, you can write code such as:</p> <pre><code>const value = a?.b?.c; </code></pre> <p>I.e., you can use this operator to access properties of an object, where the object itself may be <code>null</code> or <code>undefined</code>. Now what I would like to do is basically the same, but the property names are dynamic:</p> <pre><code>const value = a?[b]?.c; </code></pre> <p>However, there I get a syntax error:</p> <blockquote> <p>error TS1005: ':' expected.</p> </blockquote> <p>What am I doing wrong here? Is this even possible?</p> <p>The <a href="https://github.com/tc39/proposal-optional-chaining#syntax" rel="noreferrer">proposal</a> seems to imply that this is not possible (but maybe I get the syntax examples wrong).</p>
58,780,897
2
3
null
2019-11-09 15:42:14.36 UTC
15
2022-03-24 12:19:46.373 UTC
2022-03-24 12:19:46.373 UTC
null
3,001,761
null
1,333,873
null
1
110
javascript|typescript|optional-chaining
19,060
<p>When accessing a property using bracket notation and optional chaining, you need to use a dot in addition to the brackets:</p> <pre><code>const value = a?.[b]?.c; </code></pre> <p>This is the syntax that was adopted by the <a href="https://github.com/tc39/proposal-optional-chaining" rel="noreferrer">TC39 proposal</a>, because otherwise it's hard for the parser to figure out if this <code>?</code> is part of a ternary expression or part of optional chaining.</p> <p>The way I think about it: the symbol for optional chaining isn't <code>?</code>, it's <code>?.</code>. If you're doing optional chaining, you'll always be using both characters.</p>
58,754,860
CMD opens Windows Store when I type 'python'
<p>Today when I tried to run simple code on Sublime Text 3, the following message appeared:</p> <blockquote> <p>Python was not found but can be installed from the Microsoft Store: <a href="https://go.microsoft.com/fwlink?linkID=2082640" rel="noreferrer">https://go.microsoft.com/fwlink?linkID=2082640</a></p> </blockquote> <p>And when I type Python in CMD, it opens the Windows Store for me to download Python 3.7. This problem started today for no good reason. I didn't change or download anything about Python and already tried reinstalling Python, and the Path environment variable is correct.</p>
58,773,979
11
6
null
2019-11-07 18:22:06.373 UTC
36
2022-06-17 23:42:13.273 UTC
2022-06-17 22:55:42.357 UTC
null
63,550
null
10,267,497
null
1
250
python|windows-10|sublimetext3
204,223
<p>Use the Windows search bar to find &quot;Manage app execution aliases&quot;. There should be two aliases for Python. Unselect them, and this will allow the usual Python aliases &quot;python&quot; and &quot;python3&quot;. See the image below.</p> <p><a href="https://i.stack.imgur.com/eDPFY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eDPFY.png" alt="Enter image description here" /></a></p> <p>I think we have this problem when installing Python because in a new Windows installation the aliases are in the ON position as in image below. When turned on, Windows puts an empty or fake file named <em>python.exe</em> and <em>python3.exe</em> in the directory named %USERPROFILE%\AppData\Local\Microsoft\WindowsApps. This is the alias.</p> <p><a href="https://i.stack.imgur.com/UCwkU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UCwkU.png" alt="Enter image description here" /></a></p> <p>Then Microsoft put that directory at the top of the list in the &quot;Path&quot; environment variables.</p> <p><a href="https://i.stack.imgur.com/iTeHL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iTeHL.png" alt="Enter image description here" /></a></p> <p>When you enter &quot;python&quot; in cmd, it searches the directories listed in your &quot;Path&quot; environment variables page from top to bottom. So if you installed Python after a new Windows 10 install then get redirected to the Windows Store, it's because there are two python.exe's: The alias in the App Execution Alias page, and the real one wherever you installed Python. But cmd finds the App execution, alias python.exe, first because that directory is at the top of the Path.</p> <p>I think the easiest solution is to just check the <em>python.exe</em> and <em>python3.exe</em> to OFF as I suggested before, which deletes the fake EXE file files. Based on <a href="https://devblogs.microsoft.com/python/python-in-the-windows-10-may-2019-update/" rel="noreferrer">this Microsoft Devblog</a>, they stated they created this system partially for new Python users, specifically kids learning Python in school that had trouble installing it.</p> <p>Creating this alias was to help kids just starting Python to install it and focus on learning to code. I think Windows probably deletes those aliases if you install Python from the Windows App Store. We are noticing that they do not get deleted if you manually install from another source.</p> <p>(Also, the empty/fake python.exe is not really empty. It says 0 KB in the screenshot, but entering &quot;start ms-windows-store:&quot; in cmd opens the Windows App Store, so it probably just has a line with that and a way to direct it to the Python page.)</p> <p>Finally, as Chipjust suggested, you can create a new alias for Python using something like DOSKEY as explained in this article for example: <em><a href="https://winaero.com/how-to-set-aliases-for-the-command-prompt-in-windows/" rel="noreferrer">How to set aliases for the command prompt in Windows</a></em></p>
46,152,850
webkit box orient styling disappears from styling
<p>In my Angular app (I'm on version 4.3.1) I'm adding a CSS ellipsis after multiple lines.<br> For this, I use the following css code in Sass.</p> <pre><code>.ellipsis { -webkit-box-orient: vertical; display: block; display: -webkit-box; -webkit-line-clamp: 2; overflow: hidden; text-overflow: ellipsis; } </code></pre> <p>For some reason, the box-orient line simply gets removed from the styling by the transpile, causing the ellipsis to not work. This seems to happen in Angular and Ionic apps.</p>
46,152,851
5
4
null
2017-09-11 09:55:48.153 UTC
7
2020-12-03 08:45:09.95 UTC
null
null
null
null
1,645,981
null
1
39
css|angular|ionic-framework|sass|ellipsis
16,123
<p>Wrapping <code>-webkit-box-orient</code> in the following autoprefixer code seems to solve the issue.</p> <pre><code>.ellipsis { display: block; display: -webkit-box; -webkit-line-clamp: 2; overflow: hidden; text-overflow: ellipsis; -webkit-box-orient: vertical; /* autoprefixer: off */ } </code></pre>
19,681,226
Built in access logs in node.js (express framework)
<p>I was wondering if <strong>node.js</strong> (or <strong>express</strong> framework) has any kind of built in access logging like grails has for example?</p> <p>I have grails application that runs on tomcat and it automatically generates <code>/apache-tomcat-7.0.42/logs/localhost_access_log.2013.10.30.txt</code> file in which are logs about request response like this one: </p> <pre><code>[30/Oct/2013:00:00:01 +0000] [my-ip-address] [http-bio-8080-exec-18] "GET /my-service/check HTTP/1.0" [200] [took: 1 milis] </code></pre> <p>This logs are written automatically by system and I don't have to worry about that.</p> <p>So what about <strong>node.js</strong>?</p> <p>Thanks for any help!</p> <p>Ivan</p>
19,681,432
4
2
null
2013-10-30 11:40:41.19 UTC
null
2015-05-14 01:07:49.173 UTC
null
null
null
null
1,441,771
null
1
19
node.js|logging|express|access-log
39,132
<p><strong>edit</strong> As of express <code>4.0.0</code> this solution is apparently no longer enough. Check out the answer from whirlwin for an updated solution.</p> <p>You can use <code>app.use(express.logger());</code></p> <p>Documented here: <a href="http://www.senchalabs.org/connect/logger.html" rel="noreferrer">http://www.senchalabs.org/connect/logger.html</a></p>
694,669
What is the Scheme function to find an element in a list?
<p>I have a list of elements '(a b c) and I want to find if (true or false) x is in it, where x can be 'a or 'd, for instance. Is there a built in function for this?</p>
694,790
5
1
null
2009-03-29 14:07:54.233 UTC
2
2020-06-25 16:21:47.523 UTC
2009-05-15 10:57:54.223 UTC
null
6,068
Kai
75,458
null
1
8
lisp|scheme
43,618
<p>If you need to compare using one of the build in equivalence operators, you can use <a href="http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_idx_428" rel="noreferrer"><code>memq</code>, <code>memv</code>, or <code>member</code></a>, depending on whether you want to look for equality using <a href="http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.1" rel="noreferrer"><code>eq?</code>, <code>eqv?</code>, or <code>equal?</code></a>, respectively.</p> <pre><code>&gt; (memq 'a '(a b c)) '(a b c) &gt; (memq 'b '(a b c)) '(b c) &gt; (memq 'x '(a b c)) #f </code></pre> <p>As you can see, these functions return the sublist starting at the first matching element if they find an element. This is because if you are searching a list that may contain booleans, you need to be able to distinguish the case of finding a <code>#f</code> from the case of not finding the element you are looking for. A list is a true value (the only false value in Scheme is <code>#f</code>) so you can use the result of <code>memq</code>, <code>memv</code>, or <code>member</code> in any context expecting a boolean, such as an <code>if</code>, <code>cond</code>, <code>and</code>, or <code>or</code> expression.</p> <pre><code>&gt; (if (memq 'a '(a b c)) "It's there! :)" "It's not... :(") "It's there! :)" </code></pre> <p>What is the difference between the three different functions? It's based on which equivalence function they use for comparison. <code>eq?</code> (and thus <code>memq</code>) tests if two objects are the same underlying object; it is basically equivalent to a pointer comparison (or direct value comparison in the case of integers). Thus, two strings or lists that look the same may not be <code>eq?</code>, because they are stored in different locations in memory. <code>equal?</code> (and thus <code>member?</code>) performs a deep comparison on lists and strings, and so basically any two items that print the same will be <code>equal?</code>. <code>eqv?</code> is like <code>eq?</code> for almost anything but numbers; for numbers, two numbers that are numerically equivalent will always be <code>eqv?</code>, but they may not be <code>eq?</code> (this is because of bignums and rational numbers, which may be stored in ways such that they won't be <code>eq?</code>)</p> <pre><code>&gt; (eq? 'a 'a) #t &gt; (eq? 'a 'b) #f &gt; (eq? (list 'a 'b 'c) (list 'a 'b 'c)) #f &gt; (equal? (list 'a 'b 'c) (list 'a 'b 'c)) #t &gt; (eqv? (+ 1/2 1/3) (+ 1/2 1/3)) #t </code></pre> <p>(Note that some behavior of the functions is undefined by the specification, and thus may differ from implementation to implementation; I have included examples that should work in any R<sup>5</sup>RS compatible Scheme that implements exact rational numbers)</p> <p>If you need to search for an item in a list using an equivalence predicate different than one of the built in ones, then you may want <a href="http://srfi.schemers.org/srfi-1/srfi-1.html#find" rel="noreferrer"><code>find</code></a> or <a href="http://srfi.schemers.org/srfi-1/srfi-1.html#find-tail" rel="noreferrer"><code>find-tail</code></a> from SRFI-1:</p> <pre><code>&gt; (find-tail? (lambda (x) (&gt; x 3)) '(1 2 3 4 5 6)) '(4 5 6) </code></pre>
171,332
Accessing internal members via System.Reflection?
<p>I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is:</p> <pre><code>FieldInfo[] _fields = typeof(ButtonedForm.TitleButton).GetFields( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); Console.WriteLine("{0} fields:", _fields.Length); foreach (FieldInfo fi in _fields) { Console.WriteLine(fi.Name); } </code></pre> <p>This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?</p>
171,337
5
0
null
2008-10-05 01:41:23.317 UTC
9
2022-08-06 14:03:15.03 UTC
null
null
null
monoxide
15,537
null
1
24
c#|.net|reflection|internal
17,201
<p>It would be more appropriate to use the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow noreferrer"><code>InternalsVisibleTo</code></a> attribute to grant access to the internal members of the assembly to your unit test assembly.</p> <p>Here is a link with some helpful additional info and a walk through:</p> <ul> <li><a href="https://jason.whitehorn.us/blog/2007/11/08/the-wonders-of-internalsvisibleto/" rel="nofollow noreferrer">The Wonders Of InternalsVisibleTo</a></li> </ul> <p>To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from <a href="http://msdn.microsoft.com/en-us/library/ms173183.aspx" rel="nofollow noreferrer">MSDN</a>:</p> <blockquote> <p>The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isassembly.aspx" rel="nofollow noreferrer">IsAssembly</a> property. To identify a protected internal method, use the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isfamilyorassembly.aspx" rel="nofollow noreferrer">IsFamilyOrAssembly</a>.</p> </blockquote>
682,039
How do i convert HH:MM:SS into just seconds using C#.net?
<p>Is there a tidy way of doing this rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?</p>
682,057
5
0
null
2009-03-25 15:10:37.08 UTC
2
2020-10-30 11:09:39.63 UTC
2009-03-25 15:16:43.103 UTC
Adam Lassek
1,249
SocialAddict
73,228
null
1
32
c#|.net|datetime
64,199
<p>It looks like a timespan. So simple parse the text and get the seconds.</p> <pre><code>string time = "00:01:05"; double seconds = TimeSpan.Parse(time).TotalSeconds; </code></pre>
662,164
WPF Context menu doesn't bind to right databound item
<p>I have a problem when binding a command in a context menu on a usercontrol that is on a tab page. The first time I use the menu (right-click on the tab) it works great, but if I switch tab the command will use the databound instance that was used the first time.</p> <p>If I put a button that is bound to the command in the usercontrol it works as expected...</p> <p>Can someone please tell me what I'm doing wrong??</p> <p>This is a test project that exposes the problem:</p> <p>App.xaml.cs:</p> <pre><code>public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); CompanyViewModel model = new CompanyViewModel(); Window1 window = new Window1(); window.DataContext = model; window.Show(); } } </code></pre> <p>Window1.xaml:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vw="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;DataTemplate x:Key="HeaderTemplate"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="{x:Type vw:PersonViewModel}"&gt; &lt;vw:UserControl1/&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;TabControl ItemsSource="{Binding Path=Persons}" ItemTemplate="{StaticResource HeaderTemplate}" IsSynchronizedWithCurrentItem="True" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>UserControl1.xaml:</p> <pre><code>&lt;UserControl x:Class="WpfApplication1.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinWidth="200"&gt; &lt;UserControl.ContextMenu&gt; &lt;ContextMenu &gt; &lt;MenuItem Header="Change" Command="{Binding Path=ChangeCommand}"/&gt; &lt;/ContextMenu&gt; &lt;/UserControl.ContextMenu&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="100" /&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0"&gt;The name:&lt;/Label&gt; &lt;TextBox Grid.Column="1" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>CompanyViewModel.cs:</p> <pre><code>public class CompanyViewModel { public ObservableCollection&lt;PersonViewModel&gt; Persons { get; set; } public CompanyViewModel() { Persons = new ObservableCollection&lt;PersonViewModel&gt;(); Persons.Add(new PersonViewModel(new Person { Name = "Kalle" })); Persons.Add(new PersonViewModel(new Person { Name = "Nisse" })); Persons.Add(new PersonViewModel(new Person { Name = "Jocke" })); } } </code></pre> <p>PersonViewModel.cs:</p> <pre><code>public class PersonViewModel : INotifyPropertyChanged { Person _person; TestCommand _testCommand; public PersonViewModel(Person person) { _person = person; _testCommand = new TestCommand(this); } public ICommand ChangeCommand { get { return _testCommand; } } public string Name { get { return _person.Name; } set { if (value == _person.Name) return; _person.Name = value; OnPropertyChanged("Name"); } } void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>TestCommand.cs:</p> <pre><code>public class TestCommand : ICommand { PersonViewModel _person; public event EventHandler CanExecuteChanged; public TestCommand(PersonViewModel person) { _person = person; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { _person.Name = "Changed by command"; } } </code></pre> <p>Person.cs:</p> <pre><code>public class Person { public string Name { get; set; } } </code></pre>
662,246
6
0
null
2009-03-19 13:20:59.32 UTC
9
2017-11-14 09:41:45.42 UTC
null
null
null
user80011
null
null
1
17
wpf|data-binding|mvvm|contextmenu
22,060
<p>The key thing to remember here is <strong>context menus are not part of the visual tree.</strong></p> <p>Therefore they don't inherit the same source as the control they belong to for binding. The way to deal with this is to bind to the placement target of the ContextMenu itself.</p> <pre><code>&lt;MenuItem Header="Change" Command="{Binding Path=PlacementTarget.ChangeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" /&gt; </code></pre>
525,197
Where is the default log location for SharePoint/MOSS?
<p>I found the answer after digging and thought I'd store it here. C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS</p>
527,353
6
1
2009-02-23 07:19:44.7 UTC
2009-02-08 05:25:17.36 UTC
3
2018-04-13 11:03:47.06 UTC
2012-06-30 05:17:23.347 UTC
null
918,414
PangoMancakes
63,606
null
1
24
sharepoint|moss
133,648
<p>SharePoint uses a lot of different logging mechanisms. Most importantly you can configure the location of the logs through Central Admin. To give you an understanding of the logs involved, here is a quote from <a href="http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/" rel="noreferrer">http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/</a></p> <blockquote> <p>All file based logs can be read by text editors and can be parsed by using popular log parsing tools (Log Parser 2.2 from Microsoft or Funnel Web). It will also be a good idea to read the IIS Logs which are generally saved at (System Drive):\WINDOWS\system32\LogFiles</p> <p>a) Diagnostics Logs</p> <p>· Event Throttling Logs – These end up going to the Windows Event Log and can be viewed in the Event Viewer. They show Errors and Warnings.</p> <p>· Trace Logs – These show detailed line by line tracing infomration emitted during a web request or service execution. They end up being stored at a known location on the front-end server. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\LOGS\ </p> <p>b) Audit Logs - They end up in the associated Content Database tables and can be viewed at Site Collection Level as well as Site Level using the web browser. WSS 3.0 and MOSS 2007 use different pages to show Audit Log Reports.</p> <p>c) Usage Logs – They get stored locally on the front-end servers and get processed both locally and at farm level via SSP (this is based on the setup as I understand the results from the local processing are merged by SSP) and can be viewed at both the Site Level and Site Collection Level. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Logs</p> <p>d) Search\Query Logs – These are saved in the associated SSP database but can be viewed at SSP level via the Web Browser and in MOSS at Site Collection Level by going to the settings page.</p> <p>e) Information Management Logs – Stored in the associated Content Database and can be can be viewed at the Site Collection Level.</p> <p>f) Content and Structure Logs – This option is only available after one enables the publication feature. This store is saved in the Content Database associated with the Site Collection and can be viewed at Site Collection level by going to the settings page.</p> </blockquote>
13,506,257
Fastest method to check if an array is empty
<p>I want to know the fastest way to check if an array is empty in VB.NET. The array is already initialized so I can't use any of the checks that look at that. This is the current code below:</p> <pre><code>If Not (cubes(threadnumber)(i).objects.GetLength(0) = 0) Then cubes(threadnumber)(i).objects = New Double() {} ReDim cubes(threadnumber)(i).objects(-1) End If </code></pre> <p>I've done some testing and I know that using <code>.GetUpperBound</code> is a little faster, but I'm not sure if this will work because I think <code>.GetUpperBound</code> returns a 0 if the array length is 1.</p> <p>Any/all methods to speed this up (even fractionally) will be tremendously helpful. This program takes ages to compleate and the first line of the above code is a big portion of the time, it's called 136 million times.</p> <p>Also if anyone knows how to speed up For...Next loops that'd be great too!</p>
13,522,514
4
3
null
2012-11-22 05:12:43.357 UTC
3
2020-12-11 14:44:39.527 UTC
2020-12-11 14:44:39.527 UTC
null
1,115,360
null
1,601,928
null
1
5
arrays|vb.net|performance|optimization
43,880
<p>After some intensive testing and analyzing I've found what appears to be the quickest method (so far at least). Making this small change has sped up my program 500-600%.</p> <p>When there is an item added to the object arrays I also add the index of the second dimension of the cubes to a list IF the index of the second dimension is not already in the list. Any other suggest would be welcome though.</p>
17,850,967
Run a curl command using CRON jobs
<p>I want to run this statement:</p> <pre><code>curl 'http://localhost:8983/solr/dataimport?command=full-import' </code></pre> <p>every 10 minutes using CRON jobs.</p> <p>How do I achieve this?</p>
17,852,939
3
0
null
2013-07-25 06:50:45.707 UTC
4
2017-09-15 08:26:46.123 UTC
2017-09-15 08:26:46.123 UTC
null
562,769
null
2,492,264
null
1
14
curl|cron|scheduled-tasks
73,159
<p>Something like:</p> <pre><code>crontab &lt;&lt;'EOF' SHELL=/bin/bash #min hr md mo wkday command */10 * * * * curl 'http://localhost:8983/solr/dataimport?command=full-import' EOF </code></pre> <p>Use <code>crontab -l</code> to get a look at it afterwards. <em>BUT</em>, add an option to that <code>curl</code> command to put the output somewhere specific, since it might be run somewhere to which you don't have write access. Also, if <code>curl</code> is anywhere unusual, you may need to specify its full path, like <code>/usr/bin/curl</code>, or set the <code>crontab</code> PATH variable.</p> <p>The quotes around <code>EOF</code> prevent substitution in the contents of the HEREIS document (everything between the <code>&lt;&lt;EOF</code> and <code>EOF). HEREIS documents are a shell feature, not part of</code>crontab`.</p> <p>See <code>man 5 crontab</code> for a detailed breakdown of what goes in crontab files.</p> <p>I usually keep a <code>~/.crontab</code> file to edit with a special first line, and the execute bit set:</p> <pre><code>#!/usr/bin/env crontab SHELL+/bin/sh [... etc.] </code></pre> <p>This lets me edit my <code>~/.crontab</code> and then just run it with:</p> <pre><code>$ vi ~/.crontab $ ~/.crontab </code></pre> <p>(I also usually have extensions on them to indicate which host they're for, like ~/.crontab.bigbox)</p>
2,319,838
Open a program with python minimized or hidden
<p>What I'm trying to do is to write a script which would open an application only in process list. Meaning it would be "hidden". I don't even know if its possible in python.</p> <p>If its not possible, I would settle for even a function that would allow for a program to be opened with python in a minimized state maybe something like this:</p> <pre><code>import subprocess def startProgram(): subprocess.Hide(subprocess.Popen('C:\test.exe')) # I know this is wrong but you get the idea... startProgram() </code></pre> <p>Someone suggested to use win32com.client but the thing is that the program that i want to launch doesn't have a COM server registered under the name.</p> <p>Any ideas? </p>
2,323,367
5
0
null
2010-02-23 16:27:26.173 UTC
9
2022-07-17 13:02:33.897 UTC
2010-02-23 16:34:09.623 UTC
null
192,839
null
273,206
null
1
9
python|windows
27,783
<p>You should use win32api and hide your window e.g. using <a href="http://msdn.microsoft.com/en-us/library/ms633497%28VS.85%29.aspx" rel="noreferrer">win32gui.EnumWindows</a> you can enumerate all top windows and hide your window</p> <p>Here is a small example, you may do something like this:</p> <pre><code>import subprocess import win32gui import time proc = subprocess.Popen(["notepad.exe"]) # lets wait a bit to app to start time.sleep(3) def enumWindowFunc(hwnd, windowList): """ win32gui.EnumWindows() callback """ text = win32gui.GetWindowText(hwnd) className = win32gui.GetClassName(hwnd) #print hwnd, text, className if text.find("Notepad") &gt;= 0: windowList.append((hwnd, text, className)) myWindows = [] # enumerate thru all top windows and get windows which are ours win32gui.EnumWindows(enumWindowFunc, myWindows) # now hide my windows, we can actually check process info from GetWindowThreadProcessId # http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx for hwnd, text, className in myWindows: win32gui.ShowWindow(hwnd, False) # as our notepad is now hidden # you will have to kill notepad in taskmanager to get past next line proc.wait() print "finished." </code></pre>
2,025,712
Extract sql query from LINQ expressions
<p><strong>Is it possible to extract sql statements from LINQ queries ?</strong></p> <p>Say, I have this LINQ expression.</p> <pre><code> string[] names = new string[] { &quot;Jon Skeet&quot;, &quot;Marc Gravell&quot;, &quot;tvanfosson&quot;, &quot;cletus&quot;, &quot;Greg Hewgill&quot;, &quot;JaredPar&quot; }; var results = from name in names where name.StartsWith(&quot;J&quot;) select name; </code></pre> <p><a href="http://ruchitsurati.net/files/linq-debugging.png" rel="nofollow noreferrer">alt text http://ruchitsurati.net/files/linq-debugging.png</a></p> <p>After this statement 'results' is only holding the LINQ expression and not the results due to deferred execution of LINQ queries.</p> <blockquote> <p><strong>Can I extract or produce the LINQ query out of 'results' and prepare a valid SQL statement from the query stored in 'LINQ'?</strong></p> </blockquote> <h2>EDIT</h2> <p>Here's My objective:</p> <p>We have written our own ORM. We have to write queries every-time we need to do db operations. Now we need to get rid of it at DAL. We wish to write LINQ expression in code which will produce SQL statements against my ORM and we will execute this SQL on the database.</p> <p><strong>Will I haev to write my custom Linq Providers to do what I need ?</strong></p>
2,025,732
5
2
null
2010-01-08 05:25:30.31 UTC
5
2019-02-22 19:39:22.62 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
89,556
null
1
16
c#|linq|linq-to-sql
43,093
<p>Edit: Wait, you're talking about LINQ to Objects? No, that is impossible<sup>1</sup>. There is no way to convert the expression tree for a LINQ to Object query to an expression tree that represents querying some database.</p> <p>Edit: Don't write you're own ORM. There are proven solutions to this problem. You're wasting value by trying to solve this problem again. If you're going to use your own ORM, to translate an expression to a SQL statement, yes you will have to write your own provider. Here's a <a href="http://msdn.microsoft.com/en-us/library/bb546158.aspx" rel="noreferrer">walkthrough</a> on MSDN doing that.</p> <p>But seriously, do not write your own ORM. Five years ago before NHibernate and LINQ to SQL came along and matured, fine. But not now. No way.</p> <p>The rest of this answer assumed that you were asking about LINQ to SQL.</p> <p>There are two ways that I know of.</p> <p>First:</p> <p>Set the <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx" rel="noreferrer"><code>DataContext.Log</code></a> property to <code>Console.Out</code> (or another <code>System.IO.TextWriter</code> of your choice):</p> <pre><code>var db = new MyDataContext(); db.Log = Console.Out; </code></pre> <p>This will print the SQL statements to the console as they are executed. For more on this feature see <a href="http://msdn.microsoft.com/en-us/library/bb386961.aspx" rel="noreferrer">MSDN</a>. Elsewhere there are <a href="http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11" rel="noreferrer">examples</a> of <code>TextWriter</code>s that let you send the output to the debugger output window.</p> <p>Second:</p> <p>Use the <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">LINQ to SQL Debug Visualizer</a> from Scott Guthrie. This allows you to see the SQL statements through the debugger in Visual Studio. This option has the advantage that you can see the SQL statement without executing the query. You can even execute the query and see the results in the visualizer.</p> <p><sup>1</sup>: Perhaps not impossible, but certainly very hard.</p>
1,442,189
Heartbeat Protocols/Algorithms or best practices
<p>Recently I've added some load-balancing capabilities to a piece of software that I wrote. It is a networked application that does some data crunching based on input coming from a SQL database. Since the crunching can be pretty intensive I've added the capability to have multiple instances of this application running on different servers to split the load but as it is now the load balancing is a manual act. A user must specify which instances take which portion of the input domain.</p> <p>I would like to take that to the next level and program the instances to automatically negotiate the diving up of the input data and to recognize if one of them "disappears" (has crashed or has been powered down) so that the remaining instances can take on the failed instance's workload.</p> <p>In order to implement this I'm considering using a simple heartbeat protocol between the instances to determine who's online and who isn't and while this is not terribly complicated I'd like to know if there are any established heartbeat network protocols (based on UDP, TCP or both).</p> <p>Obviously this happens a lot in the networking world with clustering, fail-over and high-availability technologies so I guess in the end I'd like to know if maybe there are any established protocols or algorithms that I should be aware of or implement.</p> <p><strong>EDIT</strong></p> <p>It seems, based on the answers, that either there are no well established heart-beat protocols or that nobody knows about them (which would imply that they aren't so well established after all) in which case I'm just going to roll my own.</p> <p>While none of the answers offered what I was looking for specifically I'm going to vote for <a href="https://stackoverflow.com/questions/1442189/heartbeat-protocols-algorithms-or-best-practices/1442901#1442901">Matt Davis's answer</a> since it was the closest and he pointed out a good idea to use multicast.</p> <p>Thank you all for your time~</p>
1,442,901
5
2
null
2009-09-18 01:27:15.81 UTC
13
2009-12-23 14:57:22.663 UTC
2017-05-23 11:54:43.49 UTC
null
-1
null
63,074
null
1
21
sockets|network-programming|network-protocols|distributed-computing
17,447
<p><a href="http://en.wikipedia.org/wiki/Distributed_Interactive_Simulation" rel="noreferrer">Distribued Interactive Simulation</a> (DIS), which is defined under <a href="http://standards.ieee.org/" rel="noreferrer">IEEE</a> Standard 1278, uses a default heartbeat of 5 seconds via UDP broadcast. A DIS heartbeat is essentially an Entity State PDU, which fully defines the state, including the position, of the given entity. Due to its application within the simulation community, DIS also uses a concept referred to as dead-reckoning to provide higher frequency heartbeats when the actual position, for example, is outside a given threshold of its predicted position.</p> <p>In your case, a DIS Entity State PDU would be overkill. I only mention it to make note of the fact that heartbeats can vary in frequency depending on the circumstances. I don't know that you'd need something like this for the application you described, but you never know.</p> <p>For heartbeats, use UDP, not TCP. A heartbeat is, by nature, a connectionless contrivance, so it goes that UDP (connectionless) is more relevant here than TCP (connection-oriented).</p> <p>The thing to keep in mind about UDP broadcasts is that a broadcast message is confined to the <a href="http://en.wikipedia.org/wiki/Broadcast_domain" rel="noreferrer">broadcast domain</a>. In short, if you have computers that are separated by a layer 3 device, e.g., a router, then broadcasts are not going to work because the router will not transmit broadcast messages from one broadcast domain to another. In this case, I would recommend using multicast since it will span the broadcast domains, providing the time-to-live (TTL) value is set high enough. It's also a more automated approach than directed unicast, which would require the sender to know the IP address of the receiver in order to send the message.</p>
2,124,468
Possible to calculate MD5 (or other) hash with buffered reads?
<p>I need to calculate checksums of quite large files (gigabytes). This can be accomplished using the following method:</p> <pre><code> private byte[] calcHash(string file) { System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.MD5.Create(); FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] hash = ha.ComputeHash(fs); fs.Close(); return hash; } </code></pre> <p>However, the files are normally written just beforehand in a buffered manner (say writing 32mb's at a time). I am so convinced that I saw an override of a hash function that allowed me to calculate a MD5 (or other) hash at the same time as writing, ie: calculating the hash of one buffer, then feeding that resulting hash into the next iteration.</p> <p>Something like this: (pseudocode-ish)</p> <pre><code>byte [] hash = new byte [] { 0,0,0,0,0,0,0,0 }; while(!eof) { buffer = readFromSourceFile(); writefile(buffer); hash = calchash(buffer, hash); } </code></pre> <p>hash is now sililar to what would be accomplished by running the calcHash function on the entire file.</p> <p>Now, I can't find any overrides like that in the.Net 3.5 Framework, am I dreaming ? Has it never existed, or am I just lousy at searching ? The reason for doing both writing and checksum calculation at once is because it makes sense due to the large files. </p>
2,124,500
5
0
null
2010-01-23 19:51:47.83 UTC
16
2017-08-08 16:08:35.02 UTC
null
null
null
null
37,119
null
1
35
c#|.net-3.5|hash|md5|buffer
18,479
<p>You use the <code>TransformBlock</code> and <code>TransformFinalBlock</code> methods to process the data in chunks.</p> <pre><code>// Init MD5 md5 = MD5.Create(); int offset = 0; // For each block: offset += md5.TransformBlock(block, 0, block.Length, block, 0); // For last block: md5.TransformFinalBlock(block, 0, block.Length); // Get the has code byte[] hash = md5.Hash; </code></pre> <p>Note: It works (at least with the MD5 provider) to send all blocks to <code>TransformBlock</code> and then send an empty block to <code>TransformFinalBlock</code> to finalise the process.</p>
2,201,335
Dynamically create PHP object based on string
<p>I would like to create an object in PHP based on a type defined by a string in a MySQL database. The database table has columns and sample data of:</p> <pre class="lang-none prettyprint-override"><code> id | type | propertyVal ----+------+------------- 1 | foo | lorum 2 | bar | ipsum </code></pre> <p>...with PHP data types</p> <pre><code>class ParentClass {...} class Foo extends ParentClass {private $id, $propertyVal; ...} class Bar extends ParentClass {private $id, $propertyVal; ...} //...(more classes)... </code></pre> <p>Using only one query, I would like to SELECT a row by id and create an object of the type define the table's type column with other columns in the SELECTed row being assigned to the newly created object.</p> <p>I was thinking that using: </p> <ol> <li><code>mysql_fetch_object()</code></li> <li>Reading the type attribute</li> <li>Creating an object with type defined by type attribute</li> </ol> <p>But know of no way to dynamically create a type based on a string. How does one do this? </p>
2,201,370
5
0
null
2010-02-04 16:32:44.21 UTC
16
2018-09-10 12:40:47.813 UTC
2012-03-29 12:43:03.87 UTC
null
229,044
null
25,985
null
1
49
php|mysql|oop|casting
66,808
<blockquote> <p>But know of no way to dynamically create a type based on a string. How does one do this? </p> </blockquote> <p>You can do it quite easily and naturally:</p> <pre><code>$type = 'myclass'; $instance = new $type; </code></pre> <p>If your query is returning an associative array, you can assign properties using similar syntax:</p> <pre><code>// build object $type = $row['type']; $instance = new $type; // remove 'type' so we don't set $instance-&gt;type = 'foo' or 'bar' unset($row['type']); // assign properties foreach ($row as $property =&gt; $value) { $instance-&gt;$property = $value; } </code></pre>
1,785,083
how do web crawlers handle javascript
<p>Today a lot of content on Internet is generated using JavaScript (specifically by background AJAX calls). I was wondering how web crawlers like Google handle them. Are they aware of JavaScript? Do they have a built-in JavaScript engine? Or do they simple ignore all JavaScript generated content in the page (I guess quite unlikely). Do people use specific techniques for getting their content indexed which would otherwise be available through background AJAX requests to a normal Internet user? </p>
1,785,101
6
1
null
2009-11-23 18:35:04.053 UTC
11
2015-09-14 14:30:22.523 UTC
null
null
null
null
208,890
null
1
22
javascript|web-crawler
10,546
<p>JavaScript is handled by both Bing and Google crawlers. Yahoo uses the Bing crawler data, so it should be handled as well. I didn't look into other search engines, so if you care about them, you should look them up.</p> <p><a href="http://blogs.bing.com/webmaster/2013/03/21/search-engine-optimization-best-practices-for-ajax-urls/" rel="noreferrer">Bing published guidance in March 2014</a> as to how to create JavaScript-based websites that work with their crawler (mostly related to <code>pushState</code>) that are good practices in general:</p> <ul> <li>Avoid creating broken links with <code>pushState</code></li> <li>Avoid creating two different links that link to the same content with <code>pushState</code></li> <li>Avoid <a href="https://en.wikipedia.org/wiki/Cloaking" rel="noreferrer">cloaking</a>. (<a href="http://blogs.bing.com/webmaster/2007/12/04/bing-and-cloaking-detection/" rel="noreferrer">Here's an article Bing published about their cloaking detection in 2007</a>)</li> <li>Support browsers (and crawlers) that can't handle <code>pushState</code>.</li> </ul> <p><a href="http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html" rel="noreferrer">Google later published guidance in May 2014</a> as to how to create JavaScript-based websites that work with their crawler, and their recommendations are also recommended:</p> <ul> <li>Don't block the JavaScript (and CSS) in the robots.txt file.</li> <li>Make sure you can handle the load of the crawlers.</li> <li>It's a good idea to support browsers and crawlers that can't handle (or users and organizations that won't allow) JavaScript</li> <li>Tricky JavaScript that relies on arcane or specific features of the language might not work with the crawlers.</li> <li>If your JavaScript removes content from the page, it might not get indexed. around.</li> </ul>
1,410,951
How does Java's System.exit() work with try/catch/finally blocks?
<p>I'm aware of headaches that involve returning in try/catch/finally blocks - cases where the return in the finally is always the return for the method, even if a return in a try or catch block should be the one executed.</p> <p>However, does the same apply to System.exit()? For example, if I have a try block:</p> <pre><code>try { //Code System.exit(0) } catch (Exception ex) { //Log the exception } finally { System.exit(1) } </code></pre> <p>If there are no exceptions, which System.exit() will be called? If the exit was a return statement, then the line System.exit(1) would always (?) be called. However, I'm not sure if exit behaves differently than return.</p> <p>The code is in an extreme case that is very difficult, if not impossible, to reproduce, so I can't write a unit test. I'm going to try to run an experiment later today, if I get a few free minutes, but I'm curious anyway, and perhaps someone on SO knows the answer and can provide it before or in case I can't run an experiment.</p>
1,410,961
6
3
null
2009-09-11 13:43:14.203 UTC
20
2016-09-19 17:53:43.58 UTC
null
null
null
null
572
null
1
88
java|try-catch-finally|system.exit
110,366
<p>No. <code>System.exit(0)</code> doesn't return, and the finally block is not executed.</p> <p><code>System.exit(int)</code> can throw a <code>SecurityException</code>. If that happens, the finally block <em>will</em> be executed. And since the same principal is calling the same method from the same code base, another <code>SecurityException</code> is likely to be thrown from the second call.</p> <hr> <p>Here's an example of the second case:</p> <pre><code>import java.security.Permission; public class Main { public static void main(String... argv) throws Exception { System.setSecurityManager(new SecurityManager() { @Override public void checkPermission(Permission perm) { /* Allow everything else. */ } @Override public void checkExit(int status) { /* Don't allow exit with any status code. */ throw new SecurityException(); } }); System.err.println("I'm dying!"); try { System.exit(0); } finally { System.err.println("I'm not dead yet!"); System.exit(1); } } } </code></pre>
1,626,368
Difference between CLR 2.0 and CLR 4.0
<p>I have read countless blogs, posts and StackOverflow questions about the new features of C# 4.0. Even new WPF 4.0 features have started to come out in the open. What I could not find and will like to know:</p> <ol> <li>What are the major changes to CLR 4.0 from a C#/WPF developer perspective?</li> <li>What are the major changes to CLR 4.0 as a whole?</li> </ol> <p>I think, internally, most changes are for the new dynamic languages and parallel programming. But are there any other major improvements? Because language improvements are just that, language improvements. You just need the new compiler and those features can be used with a lower version of .Net, apart from version 1.0/1.1 (at least most of them can be used).</p> <p>And if the above features are the only ones, only for these features the version is changed to 4.0, which I think is 4.0 because of being based on .Net 4.0 version (i.e. after 1.0/1.1, 2.0 &amp; 3.0/3.5). Is the version increment justified?</p> <p><strong>Edited:</strong></p> <p>As Pavel Minaev pointed out in the comments, even those two features are CLR independent. There were speed and other improvements in 3.0 and 3.5 also. So why the version increment?</p>
1,626,441
7
1
null
2009-10-26 18:07:01.983 UTC
11
2011-03-04 20:49:57.22 UTC
2009-10-26 18:21:53.387 UTC
null
162,176
null
162,176
null
1
22
clr|.net-4.0|c#-4.0
18,141
<p>One new CLR thing that I know about is a form of structural typing for interfaces, structs and delegates for the sake of <a href="http://luke.breuer.com/time/item/Advances_in_the_NET_Type_System/492.aspx" rel="noreferrer">NoPIA support</a> - basically, it lets runtime treat distinct types with equivalent definitions as if they were the same - so if two assemblies <code>A</code> and <code>B</code> each have a COM-imported interface <code>IFoo</code> declared in them, with the same IID and same members, runtime will treat them as equivalent types; so if there's an instance some class <code>Foo</code> implementing <code>[A]IFoo</code>, you can cast it to <code>[B]IFoo</code>, and the cast will work.</p> <p>One other thing is the ability to host several CLR versions side-by-side in a single process. You cannot host 1.x and 2.0 in one process, for example, but you can host 2.0 and 4.0. The main benefit for this is the ability to load plugins written for either CLR version concurrently.</p> <p>One minor bit is that a few more exceptions have become uncatchable like <code>StackOverflowException</code> was in 2.0 - you cannot catch <code>AccessViolationException</code> anymore, for example.</p> <p>Also, <a href="http://mschnlnine.vo.llnwd.net/d1/pdc08/PPTX/PC49.pptx" rel="noreferrer">here</a> is a PowerPoint presentation on CLR 4.0 from PDC 2008. It might be a bit dated now, but most stuff that's mentioned there seems to be in the betas.</p>
1,346,132
How do I extract data from a DataTable?
<p>I have a <code>DataTable</code> that is filled in from an SQL query to a local database, but I don't know how to extract data from it. Main method (in test program):</p> <pre class="lang-cs prettyprint-override"><code>static void Main(string[] args) { const string connectionString = "server=localhost\\SQLExpress;database=master;integrated Security=SSPI;"; DataTable table = new DataTable("allPrograms"); using (var conn = new SqlConnection(connectionString)) { Console.WriteLine("connection created successfuly"); string command = "SELECT * FROM Programs"; using (var cmd = new SqlCommand(command, conn)) { Console.WriteLine("command created successfuly"); SqlDataAdapter adapt = new SqlDataAdapter(cmd); conn.Open(); Console.WriteLine("connection opened successfuly"); adapt.Fill(table); conn.Close(); Console.WriteLine("connection closed successfuly"); } } Console.Read(); } </code></pre> <p>The command I used to create the tables in my database:</p> <pre class="lang-sql prettyprint-override"><code>create table programs ( progid int primary key identity(1,1), name nvarchar(255), description nvarchar(500), iconFile nvarchar(255), installScript nvarchar(255) ) </code></pre> <p>How can I extract data from the <code>DataTable</code> into a form meaningful to use?</p>
1,346,142
7
0
null
2009-08-28 10:19:39.06 UTC
29
2020-09-10 03:14:59.81 UTC
2017-02-23 10:58:09.153 UTC
null
6,357,360
null
117,069
null
1
90
c#|sql|ado.net
426,229
<p>The DataTable has a collection <code>.Rows</code> of DataRow elements.</p> <p>Each DataRow corresponds to one row in your database, and contains a collection of columns.</p> <p>In order to access a single value, do something like this:</p> <pre><code> foreach(DataRow row in YourDataTable.Rows) { string name = row[&quot;name&quot;].ToString(); string description = row[&quot;description&quot;].ToString(); string icoFileName = row[&quot;iconFile&quot;].ToString(); string installScript = row[&quot;installScript&quot;].ToString(); } </code></pre>
1,860,645
Create request with POST, which response codes 200 or 201 and content
<p>Suppose I write a REST service whose intent is to add a new data item to a system.</p> <p>I plan to POST to </p> <pre><code>http://myhost/serviceX/someResources </code></pre> <p>Suppose that works, what response code should I use? And what content might I return.</p> <p>I'm looking at the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noreferrer">definitions</a> of HTTP response codes and see these possibilities:</p> <p>200: Return <em>an entity describing or containing the result of the action;</em></p> <p>201: which means CREATED. Meaning *The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. *</p> <p>The latter sounds more in line with the Http spec, but I'm not at all clear what </p> <blockquote> <p>The response SHOULD include an entity containing a list of resource characteristics and location(s)</p> </blockquote> <p>means.</p> <p>Recommendations? Interpretations?</p>
36,373,586
7
0
null
2009-12-07 15:20:06.29 UTC
55
2021-03-19 18:29:37.45 UTC
2015-01-20 19:54:22.75 UTC
null
4,178,262
null
82,511
null
1
177
rest|content-type|http-status-codes
221,499
<p>The idea is that the response body gives you a page that links you to the thing:</p> <blockquote> <p><strong>201 Created</strong></p> <p>The <code>201</code> (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a <code>Location</code> header field in the response or, if no <code>Location</code> field is received, by the effective request URI.</p> </blockquote> <p>This means that you would include a <strong><code>Location</code></strong> in the response <em>header</em> that gives the URL of where you can find the newly created <em>thing</em>:</p> <pre><code>HTTP/1.1 201 Created Date: Sat, 02 Apr 2016 12:22:40 GMT Location: http://stackoverflow.com/a/36373586/12597 </code></pre> <h2>Response body</h2> <p>They then go on to mention what you should include in the response <em>body</em>:</p> <blockquote> <p>The <code>201</code> response payload typically describes and links to the resource(s) created.</p> </blockquote> <p>For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:</p> <pre><code>HTTP/1.1 201 Created Date: Sat, 02 Apr 2016 12:22:40 GMT Location: http://stackoverflow.com/a/36373586/12597 Content-Type: text/html Your answer has been saved! Click &lt;A href=&quot;/a/36373586/12597&quot;&gt;here&lt;/A&gt; to view it. </code></pre> <p>If the page will only be used by a robot, the it makes sense to have the response be computer readable:</p> <pre><code>HTTP/1.1 201 Created Date: Sat, 02 Apr 2016 12:22:40 GMT Location: http://stackoverflow.com/a/36373586/12597 Content-Type: application/xml &lt;createdResources&gt; &lt;questionID&gt;1860645&lt;/questionID&gt; &lt;answerID&gt;36373586&lt;/answerID&gt; &lt;primary&gt;/a/36373586/12597&lt;/primary&gt; &lt;additional&gt; &lt;resource&gt;http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586&lt;/resource&gt; &lt;resource&gt;http://stackoverflow.com/a/1962757/12597&lt;/resource&gt; &lt;/additional&gt; &lt;/createdResource&gt; </code></pre> <p>Or, if you prefer:</p> <pre><code>HTTP/1.1 201 Created Date: Sat, 02 Apr 2016 12:22:40 GMT Location: http://stackoverflow.com/a/36373586/12597 Content-Type: application/json { &quot;questionID&quot;: 1860645, &quot;answerID&quot;: 36373586, &quot;primary&quot;: &quot;/a/36373586/12597&quot;, &quot;additional&quot;: [ &quot;http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586&quot;, &quot;http://stackoverflow.com/a/36373586/12597&quot; ] } </code></pre> <p>The response is entirely up to you; it's arbitrarily what you'd like.</p> <h2>Cache friendly</h2> <p>Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or <strong><code>ETag</code></strong> which I can store with the content I just uploaded:</p> <blockquote> <p>See <a href="https://www.rfc-editor.org/rfc/rfc7231#section-7.2" rel="noreferrer">Section 7.2</a> for a discussion of the meaning and purpose of validator header fields, such as <code>ETag</code> and <code>Last-Modified</code>, in a <code>201</code> response.</p> </blockquote> <pre><code>HTTP/1.1 201 Created Date: Sat, 02 Apr 2016 12:22:40 GMT Location: http://stackoverflow.com/a/23704283/12597 Content-Type: text/html ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4 Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT Your answer has been saved! Click &lt;A href=&quot;/a/36373586/12597&quot;&gt;here&lt;/A&gt; to view it. </code></pre> <p>And <strong><code>ETag</code></strong> s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The <strong><code>ETag</code></strong> is usually a hash (e.g. SHA2-256). But it can be a database <code>rowversion</code>, or an incrementing revision number. Anything that will <em>change</em> when the <em>thing</em> changes.</p>
1,754,318
How do I deploy two ClickOnce versions simultaneously?
<p>I would like the ability to have a test ClickOnce server for my applications where users can run both the production version and the test version in parallel. Is this possible?</p> <p>I first tried using the following in <code>AssemblyInfo.cs</code> and also changing the name in the ClickOnce deployment though all this achieved was overwriting the users' production version with the test version. Likewise, it did the same when they went back to the production server.</p> <pre><code>#if DEBUG [assembly: AssemblyTitle("Product Name - Test")] #else [assembly: AssemblyTitle("Product Name")] #endif </code></pre> <p>I thought I should also clarify that the two deployment locations are different from one another and on different servers.</p> <p><strong>UPDATE</strong></p> <p>I've also tried setting the GUID for the manifest depending on the debug mode, but again it does not work (dummy GUID's used below).</p> <pre><code>#if DEBUG [assembly: Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")] #else [assembly: Guid("BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB")] #endif </code></pre> <p>How are the two distinguished? It seems that the installer sees them as two separate programs as I get a confirmation of installation for each. Though, when I install the second one, "Add/Remove Programs" only sees the latter, though the former is still on disk, as when I go to reinstall it later, it just simply runs, but then the add/remove programs switches back to the former name.</p>
1,754,418
9
3
null
2009-11-18 07:59:55.723 UTC
14
2022-03-09 07:53:10.46 UTC
2014-12-09 22:46:03.8 UTC
null
63,550
null
140,037
null
1
38
c#|.net|deployment|clickonce
20,164
<p>It might sound kind of lame, but the easiest way to do this is to have two EXE projects in your solution. The <code>Main</code> method of each of these will just call the <code>Main</code> method in your original EXE project (which you'll have just switched over to being a DLL file).</p> <p>This means that each EXE project can have its own ClickOnce publishing settings, as well as its own <code>app.config</code> file. This means you have different connection strings for the production and the test version.</p> <p>Your other option (the one that might seem to make the most sense) is to use <a href="http://msdn.microsoft.com/en-us/library/xhctdw55(VS.80).aspx" rel="noreferrer">MageUI.exe</a> to manually build the ClickOnce files, which would let you choose a different configuration file and publish location each time you ran the tool. There's also a command line version (Mage.exe) so you could in theory automate this.</p> <p>However, we found that the solution with two "runner" projects was far far simpler. I'd recommend you try that first.</p>
1,361,892
How to decompress Gzip string in ruby?
<p>Zlib::GzipReader can take "an IO, or IO-like, object." as it's input, as stated in docs. </p> <pre><code>Zlib::GzipReader.open('hoge.gz') {|gz| print gz.read } File.open('hoge.gz') do |f| gz = Zlib::GzipReader.new(f) print gz.read gz.close end </code></pre> <p>How should I ungzip a string?</p>
1,366,187
9
0
null
2009-09-01 11:18:22.437 UTC
11
2019-01-22 08:11:56.257 UTC
2019-01-22 08:11:56.257 UTC
null
123,927
null
123,927
null
1
53
ruby|gzip|zlib
43,638
<p>The above method didn't work for me.<br> I kept getting <code>incorrect header check (Zlib::DataError)</code> error. Apparently it assumes you have a header by default, which may not always be the case.</p> <p>The work around that I implemented was:</p> <pre><code>require 'zlib' require 'stringio' gz = Zlib::GzipReader.new(StringIO.new(resp.body.to_s)) uncompressed_string = gz.read </code></pre>
1,874,049
Explanation of the UML arrows
<p>I have recently been studying UML and drawing simple diagrams with ordinary plain arrows between classes, but I know it's not enough. There are plenty of other arrows: generalization, realisation and etc. which have meaning to the diagram reader. </p> <p>Is there a nice resource which could explain each arrow (ordinary, plain, dotted, diamond-filled, diamond)? </p> <p>It would be the best if it will have some code examples for them.</p>
2,293,763
9
2
null
2009-12-09 13:53:24.947 UTC
271
2021-03-23 16:04:23.497 UTC
2015-12-02 14:51:35.773 UTC
null
147,953
null
147,953
null
1
314
oop|uml
394,606
<p>Here's some explanations from the Visual Studio 2015 docs:</p> <p><strong>UML Class Diagrams: Reference</strong>: <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/uml-class-diagrams-reference" rel="noreferrer">https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/uml-class-diagrams-reference</a></p> <p><img src="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/media/uml-classovreading.png" alt="UML class diagram" /></p> <blockquote> <p><strong>5</strong>: <strong>Association</strong>: A relationship between the members of two classifiers.</p> <p><strong>5a</strong>: <strong>Aggregation</strong>: An association representing a shared ownership relationship. The <strong>Aggregation</strong> property of the owner role is set to <strong>Shared</strong>.</p> <p><strong>5b</strong>: <strong>Composition</strong>: An association representing a whole-part relationship. The <strong>Aggregation</strong> property of the owner role is set to <strong>Composite</strong>.</p> <p><strong>9</strong>: <strong>Generalization</strong>: The specific classifier inherits part of its definition from the general classifier. The general classifier is at the arrow end of the connector. Attributes, associations, and operations are inherited by the specific classifier. Use the <strong>Inheritance</strong> tool to create a generalization between two classifiers.</p> </blockquote> <p><img src="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/media/uml-classovpackage.png" alt="Package diagram" /></p> <blockquote> <p><strong>13</strong>: <strong>Import</strong>: A relationship between packages, indicating that one package includes all the definitions of another.</p> <p><strong>14</strong>: <strong>Dependency</strong>: The definition or implementation of the dependent classifier might change if the classifier at the arrowhead end is changed.</p> </blockquote> <p><img src="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/media/uml-classovrealize.png" alt="Realization relationship" /></p> <blockquote> <p><strong>15</strong>: <strong>Realization</strong>: The class implements the operations and attributes defined by the interface. Use the <strong>Inheritance</strong> tool to create a realization between a class and an interface.</p> <p><strong>16</strong>: <strong>Realization</strong>: An alternative presentation of the same relationship. The label on the lollipop symbol identifies the interface.</p> </blockquote> <p><strong>UML Class Diagrams: Guidelines</strong>: <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/modeling/uml-class-diagrams-guidelines" rel="noreferrer">http://msdn.microsoft.com/library/dd409416%28VS.140%29.aspx</a></p> <blockquote> <p><strong>Properties of an Association</strong></p> <p><strong>Aggregation</strong>: This appears as a diamond shape at one end of the connector. You can use it to indicate that instances at the aggregating role own or contain instances of the other.</p> <p><strong>Is Navigable</strong>: If true for only one role, an arrow appears in the navigable direction. You can use this to indicate navigability of links and database relations in the software.</p> </blockquote> <br/> <blockquote> <p><strong>Generalization</strong>: Generalization means that the specializing or derived type inherits attributes, operations, and associations of the general or base type. The general type appears at the arrowhead end of the relationship.</p> <p><strong>Realization</strong>: Realization means that a class implements the attributes and operations specified by the interface. The interface is at the arrow end of the connector.</p> </blockquote> <p>Let me know if you have more questions.</p>
1,999,181
Is there a standard "never returns" attribute for C# functions?
<p>I have one method that looks like this:</p> <pre><code>void throwException(string msg) { throw new MyException(msg); } </code></pre> <p>Now if I write</p> <pre><code>int foo(int x, y) { if (y == 0) throwException("Doh!"); else return x/y; } </code></pre> <p>the compiler will complain about foo that "not all paths return a value".</p> <p>Is there an attribute I can add to throwException to avoid that ? Something like:</p> <pre><code>[NeverReturns] void throwException(string msg) { throw new MyException(msg); } </code></pre> <p>I'm afraid custom attributes won't do, because for my purpose I'd need the cooperation of the compiler.</p>
1,999,201
10
6
null
2010-01-04 12:13:57.647 UTC
2
2022-03-23 06:01:24.577 UTC
null
null
null
null
192,472
null
1
39
c#|exception|attributes|return-type
5,313
<p>No. I suggest you change the signature of your first function to return the exception rather than throw it, and leave the throw statement in your second function. That'll keep the compiler happy, and smells less bad as well.</p> <p><strong>Edit</strong>: there is now a <code>DoesNotReturn</code> attribute that provides an alternative.</p>
2,118,656
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
<p>Sometimes, when using <code>&lt;h:commandLink&gt;</code>, <code>&lt;h:commandButton&gt;</code> or <code>&lt;f:ajax&gt;</code>, the <code>action</code>, <code>actionListener</code> or <code>listener</code> method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted <code>UIInput</code> values.</p> <p>What are the possible causes and solutions for this?</p>
2,120,183
12
0
null
2010-01-22 16:18:46.67 UTC
328
2020-10-16 20:35:50.87 UTC
2017-09-14 08:59:22.543 UTC
null
4,478,047
null
171,950
null
1
363
jsf|jsf-2|action|commandbutton|commandlink
223,972
<h2>Introduction</h2> <p>Whenever an <code>UICommand</code> component (<code>&lt;h:commandXxx&gt;</code>, <code>&lt;p:commandXxx&gt;</code>, etc) fails to invoke the associated action method, or an <code>UIInput</code> component (<code>&lt;h:inputXxx&gt;</code>, <code>&lt;p:inputXxxx&gt;</code>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per <a href="https://stackoverflow.com/questions/27526753/exception-handling-in-jsf-ajax-requests">Exception handling in JSF ajax requests</a>, nor when you set below context parameter in <code>web.xml</code>,</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;javax.faces.PROJECT_STAGE&lt;/param-name&gt; &lt;param-value&gt;Development&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the <em>Console</em> tab), then work through below list of possible causes.</p> <h2>Possible causes</h2> <ol> <li><p><code>UICommand</code> and <code>UIInput</code> components must be placed inside an <code>UIForm</code> component, e.g. <code>&lt;h:form&gt;</code> (and thus not plain HTML <code>&lt;form&gt;</code>), otherwise nothing can be sent to the server. <code>UICommand</code> components must also not have <code>type=&quot;button&quot;</code> attribute, otherwise it will be a dead button which is only useful for JavaScript <code>onclick</code>. See also <a href="https://stackoverflow.com/questions/3681123/how-to-get-hinputtext-values-from-gui-xhtml-into-java-class-jsf-bean">How to send form input values and invoke a method in JSF bean</a> and <a href="https://stackoverflow.com/questions/12958208/hcommandbutton-does-not-initiate-a-postback">&lt;h:commandButton&gt; does not initiate a postback</a>.</p> </li> <li><p>You cannot nest multiple <code>UIForm</code> components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use <code>UIForm</code> components in parallel, but they won't process each other during submit. You should also watch out with &quot;God Form&quot; antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also <a href="https://stackoverflow.com/questions/7371903/using-multiple-hform-in-a-jsf-page">How to use &lt;h:form&gt; in JSF page? Single form? Multiple forms? Nested forms?</a>.</p> </li> <li><p>No <code>UIInput</code> value validation/conversion error should have occurred. You can use <code>&lt;h:messages&gt;</code> to show any messages which are not shown by any input-specific <code>&lt;h:message&gt;</code> components. Don't forget to include the <code>id</code> of <code>&lt;h:messages&gt;</code> in the <code>&lt;f:ajax render&gt;</code>, if any, so that it will be updated as well on ajax requests. See also <a href="https://stackoverflow.com/questions/16175178/hmessages-does-not-display-messages-when-pcommandbutton-is-pressed">h:messages does not display messages when p:commandButton is pressed</a>.</p> </li> <li><p>If <code>UICommand</code> or <code>UIInput</code> components are placed inside an iterating component like <code>&lt;h:dataTable&gt;</code>, <code>&lt;ui:repeat&gt;</code>, etc, then you need to ensure that exactly the same <code>value</code> of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in <code>@PostConstruct</code> of the bean (and thus not in a getter method!) should fix it. See also <a href="https://stackoverflow.com/questions/5765853/when-should-i-load-the-collection-from-database-for-hdatatable">How and when should I load the model from database for h:dataTable</a>.</p> </li> <li><p>If <code>UICommand</code> or <code>UIInput</code> components are included by a dynamic source such as <code>&lt;ui:include src=&quot;#{bean.include}&quot;&gt;</code>, then you need to ensure that exactly the same <code>#{bean.include}</code> value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in <code>@PostConstruct</code> of the bean (and thus not in a getter method!) should fix it. See also <a href="https://stackoverflow.com/questions/7108668/how-to-ajax-refresh-dynamic-include-content-by-navigation-menu-jsf-spa">How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)</a>.</p> </li> <li><p>The <code>rendered</code> attribute of the component and all of its parents and the <code>test</code> attribute of any parent <code>&lt;c:if&gt;</code>/<code>&lt;c:when&gt;</code> should not evaluate to <code>false</code> during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a <code>@ViewScoped</code> bean or making sure that you're properly preinitializing the condition in <code>@PostConstruct</code> of a <code>@RequestScoped</code> bean should fix it. The same applies to the <code>disabled</code> and <code>readonly</code> attributes of the component, which should not evaluate to <code>true</code> during apply request values phase. See also <a href="https://stackoverflow.com/questions/13326404/jsf-commandbutton-action-not-invoked">JSF CommandButton action not invoked</a>, <a href="https://stackoverflow.com/questions/18782503/form-submit-in-conditionally-rendered-component-is-not-processed">Form submit in conditionally rendered component is not processed</a>, <a href="https://stackoverflow.com/questions/23742141/hcommandbutton-is-not-working-once-i-wrap-it-in-a-hpanelgroup-rendered">h:commandButton is not working once I wrap it in a &lt;h:panelGroup rendered&gt;</a> and <a href="https://stackoverflow.com/questions/32390081/force-jsf-to-process-validate-and-update-readonly-disabled-input-components-any">Force JSF to process, validate and update readonly/disabled input components anyway</a></p> </li> <li><p>The <code>onclick</code> attribute of the <code>UICommand</code> component and the <code>onsubmit</code> attribute of the <code>UIForm</code> component should not return <code>false</code> or cause a JavaScript error. There should in case of <code>&lt;h:commandLink&gt;</code> or <code>&lt;f:ajax&gt;</code> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also <a href="https://stackoverflow.com/questions/16166039/adding-jquery-to-primefaces-results-in-uncaught-typeerror-over-all-place">Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors</a>.</p> </li> <li><p>If you're using Ajax via JSF 2.x <code>&lt;f:ajax&gt;</code> or e.g. PrimeFaces <code>&lt;p:commandXxx&gt;</code>, make sure that you have a <code>&lt;h:head&gt;</code> in the master template instead of the <code>&lt;head&gt;</code>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like &quot;mojarra is not defined&quot; or &quot;PrimeFaces is not defined&quot; in browser's JS console. See also <a href="https://stackoverflow.com/questions/9933777/hcommandlink-actionlistener-is-not-invoked-when-used-with-fajax-and-uirepeat">h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat</a>.</p> </li> <li><p>If you're using Ajax, and the submitted values end up being <code>null</code>, then make sure that the <code>UIInput</code> and <code>UICommand</code> components of interest are covered by the <code>&lt;f:ajax execute&gt;</code> or e.g. <code>&lt;p:commandXxx process&gt;</code>, otherwise they won't be executed/processed. See also <a href="https://stackoverflow.com/questions/17960929/submitted-form-values-not-updated-in-model-when-adding-fajax-to-hcommandbut">Submitted form values not updated in model when adding &lt;f:ajax&gt; to &lt;h:commandButton&gt;</a> and <a href="https://stackoverflow.com/questions/25339056/understanding-process-and-update-attributes-of-primefaces">Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes</a>.</p> </li> <li><p>If the submitted values still end up being <code>null</code>, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to <code>@Dependent</code> which effectively recreates the bean on every single evaluation of the EL expression. See also <a href="https://stackoverflow.com/questions/9470440/sessionscoped-bean-looses-scope-and-gets-recreated-all-the-time-fields-become">@SessionScoped bean looses scope and gets recreated all the time, fields become null</a> and <a href="https://stackoverflow.com/questions/19322364/what-is-the-default-managed-bean-scope-in-a-jsf-2-application">What is the default Managed Bean Scope in a JSF 2 application?</a></p> </li> <li><p>If a parent of the <code>&lt;h:form&gt;</code> with the <code>UICommand</code> button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as <a href="https://github.com/javaee/javaserverfaces-spec/issues/790" rel="noreferrer">JSF spec issue 790</a> and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <code>&lt;h:form&gt;</code> in the <code>render</code> of the <code>&lt;f:ajax&gt;</code>. See also <a href="https://stackoverflow.com/questions/11408130/hcommandbutton-hcommandlink-does-not-work-on-first-click-works-only-on-second">h:commandButton/h:commandLink does not work on first click, works only on second click</a>.</p> </li> <li><p>If the <code>&lt;h:form&gt;</code> has <code>enctype=&quot;multipart/form-data&quot;</code> set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the <code>FacesServlet</code> will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <code>&lt;t:inputFileUpload&gt;</code>, check <a href="https://stackoverflow.com/questions/5418292/jsf-2-0-file-upload/5424229#5424229">this answer</a> and for PrimeFaces <code>&lt;p:fileUpload&gt;</code>, check <a href="https://stackoverflow.com/questions/8875818/how-to-use-primefaces-pfileupload-listener-method-is-never-invoked/8880083#8880083">this answer</a>. Or, if you're actually not uploading a file at all, then remove the attribute altogether.</p> </li> <li><p>Make sure that the <code>ActionEvent</code> argument of <code>actionListener</code> is an <code>javax.faces.event.ActionEvent</code> and thus not <code>java.awt.event.ActionEvent</code>, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use <code>actionListener=&quot;#{bean.method}&quot;</code>. If you don't want an argument in your method, use <code>actionListener=&quot;#{bean.method()}&quot;</code>. Or perhaps you actually want to use <code>action</code> instead of <code>actionListener</code>. See also <a href="https://stackoverflow.com/questions/3909267/differences-between-action-and-actionlistener">Differences between action and actionListener</a>.</p> </li> <li><p>Make sure that no <code>PhaseListener</code> or any <code>EventListener</code> in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling <code>FacesContext#renderResponse()</code> or <code>FacesContext#responseComplete()</code>.</p> </li> <li><p>Make sure that no <code>Filter</code> or <code>Servlet</code> in the same request-response chain has blocked the request fo the <code>FacesServlet</code> somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also <a href="https://stackoverflow.com/questions/30133329/spring-security-4-and-primefaces-5-ajax-request-handling">Spring Security 4 and PrimeFaces 5 AJAX request handling</a>.</p> </li> <li><p>If you are using a PrimeFaces <code>&lt;p:dialog&gt;</code> or a <code>&lt;p:overlayPanel&gt;</code>, then make sure that they have their own <code>&lt;h:form&gt;</code>. Because, these components are by default by JavaScript relocated to end of HTML <code>&lt;body&gt;</code>. So, if they were originally sitting inside a <code>&lt;form&gt;</code>, then they would now not anymore sit in a <code>&lt;form&gt;</code>. See also <a href="https://stackoverflow.com/questions/18958729/pcommandbutton-action-doesnt-work-inside-pdialog">p:commandbutton action doesn&#39;t work inside p:dialog</a></p> </li> <li><p>Bug in the framework. For example, RichFaces has a &quot;<a href="https://issues.jboss.org/browse/RF-12594" rel="noreferrer">conversion error</a>&quot; when using a <code>rich:calendar</code> UI element with a <code>defaultLabel</code> attribute (or, in some cases, a <code>rich:placeholder</code> sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.</p> </li> </ol> <h2>Debugging hints</h2> <p>In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the <em>Console</em> tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <code>&lt;f:ajax&gt;</code> enabled button while not having <code>&lt;h:head&gt;</code> declared (as described in point 7 above).</p> <p><a href="https://i.stack.imgur.com/2qsLp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2qsLp.png" alt="js console" /></a></p> <p>Click the <em>Network</em> tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <code>&lt;h:inputText&gt;</code> and a single <code>&lt;h:commandButton&gt;</code> with <code>&lt;f:ajax execute=&quot;@form&quot; render=&quot;@form&quot;&gt;</code>.</p> <p><a href="https://i.stack.imgur.com/mg5Al.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mg5Al.png" alt="network monitor" /></a></p> <p><em>(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)</em></p> <p>In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of <code>UICommand</code> component, that would be <a href="http://grepcode.com/file/repo1.maven.org/maven2/javax.faces/javax.faces-api/2.2/javax/faces/component/UICommand.java#UICommand.queueEvent%28javax.faces.event.FacesEvent%29" rel="noreferrer"><code>UICommand#queueEvent()</code></a> and in case of <code>UIInput</code> component, that would be <a href="http://grepcode.com/file/repo1.maven.org/maven2/javax.faces/javax.faces-api/2.2/javax/faces/component/UIInput.java#UIInput.validate%28javax.faces.context.FacesContext%29" rel="noreferrer"><code>UIInput#validate()</code></a>. Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.</p> <p><a href="https://i.stack.imgur.com/mnn5R.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mnn5R.png" alt="debug server" /></a></p>
1,420,029
How to break out of a loop from inside a switch?
<p>I'm writing some code that looks like this:</p> <pre><code>while(true) { switch(msg-&gt;state) { case MSGTYPE: // ... break; // ... more stuff ... case DONE: break; // **HERE, I want to break out of the loop itself** } } </code></pre> <p>Is there any direct way to do that?</p> <p>I know I can use a flag, and break from the loop by putting a conditional break just after the switch. I just want to know if C++ has some construct for this already.</p>
1,420,100
20
13
null
2009-09-14 06:51:09.273 UTC
39
2021-11-14 12:46:14.737 UTC
2012-01-30 21:45:54.933 UTC
null
229,044
null
2,119,053
null
1
143
c++|loops|syntax|switch-statement|break
147,689
<h2>Premise</h2> <p>The following code should be considered bad form, regardless of language or desired functionality:</p> <pre><code>while( true ) { } </code></pre> <h2>Supporting Arguments</h2> <p>The <code>while( true )</code> loop is poor form because it:</p> <ul> <li><em>Breaks the implied contract of a while loop.</em> <ul> <li>The while loop declaration should explicitly state the <em>only</em> exit condition.</li> </ul></li> <li><em>Implies that it loops forever.</em> <ul> <li>Code within the loop must be read to understand the terminating clause.</li> <li>Loops that repeat forever prevent the user from terminating the program from within the program.</li> </ul></li> <li><em>Is inefficient.</em> <ul> <li>There are multiple loop termination conditions, including checking for "true".</li> </ul></li> <li><em>Is prone to bugs.</em> <ul> <li>Cannot easily determine where to put code that will always execute for each iteration.</li> </ul></li> <li><em>Leads to unnecessarily complex code.</em></li> <li><em>Automatic source code analysis.</em> <ul> <li>To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.</li> </ul></li> <li><em>Infinite loops.</em> <ul> <li>If everyone always uses <code>while(true)</code> for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)</li> </ul></li> </ul> <h2>Alternative to "Go To"</h2> <p>The following code is better form:</p> <pre><code>while( isValidState() ) { execute(); } bool isValidState() { return msg-&gt;state != DONE; } </code></pre> <h2>Advantages</h2> <p>No flag. No <code>goto</code>. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:</p> <ol> <li>Isolates the knowledge of the loop's workload from the loop itself.</li> <li>Allows someone maintaining the code to easily extend the functionality.</li> <li>Allows multiple terminating conditions to be assigned in one place.</li> <li>Separates the terminating clause from the code to execute.</li> <li>Is safer for Nuclear Power plants. ;-)</li> </ol> <p>The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:</p> <h3>Option #1</h3> <p>Readily insert the pause:</p> <pre><code>while( isValidState() ) { execute(); sleep(); } </code></pre> <h3>Option #2</h3> <p>Override execute:</p> <pre><code>void execute() { super-&gt;execute(); sleep(); } </code></pre> <p>This code is simpler (thus easier to read) than a loop with an embedded <code>switch</code>. The <code>isValidState</code> method should only determine if the loop should continue. The workhorse of the method should be abstracted into the <code>execute</code> method, which allows subclasses to override the default behaviour (a difficult task using an embedded <code>switch</code> and <code>goto</code>).</p> <h2>Python Example</h2> <p>Contrast the following answer (to a Python question) that was posted on StackOverflow:</p> <ol> <li>Loop forever.</li> <li>Ask the user to input their choice.</li> <li>If the user's input is 'restart', continue looping forever.</li> <li>Otherwise, stop looping forever.</li> <li>End.</li> </ol> Code <pre><code>while True: choice = raw_input('What do you want? ') if choice == 'restart': continue else: break print 'Break!' </code></pre> <p>Versus:</p> <ol> <li>Initialize the user's choice.</li> <li>Loop while the user's choice is the word 'restart'.</li> <li>Ask the user to input their choice.</li> <li>End.</li> </ol> Code <pre><code>choice = 'restart'; while choice == 'restart': choice = raw_input('What do you want? ') print 'Break!' </code></pre> <p>Here, <code>while True</code> results in misleading and overly complex code.</p>
8,635,456
How to open an app in terminal and passing the current working directory?
<p>I often want to open the entire directory I'm working in by using the <code>mate</code> command, but how do I pass in the working directory itself?</p> <p>For example, if I'm working in a rails app and I want to open the app folder into the TextMate tree, I would do <code>mate app</code>, but how could I pass in the working directory itself (i.e. open the entire rails app in the tree)?</p>
8,636,065
7
2
null
2011-12-26 11:50:29.307 UTC
null
2015-02-06 21:11:35.347 UTC
2015-02-06 21:11:35.347 UTC
null
55,075
null
840,973
null
1
16
bash|shell|directory|terminal|textmate
54,360
<p><code>mate .</code> will open the currently directory. I use the <code>.</code> directory a lot, for example open finder for the current directory <code>open .</code>.</p>
18,117,376
warning: return makes pointer from integer without a cast but returns integer as desired
<p>I'm trying to find out the proper way to return an integer from a void * function call within C.</p> <p>ie .. </p> <pre><code>#include &lt;stdio.h&gt; void *myfunction() { int x = 5; return x; } int main() { printf("%d\n", myfunction()); return 0; } </code></pre> <p>But I keep getting: </p> <blockquote> <p>warning: return makes pointer from integer without a cast</p> </blockquote> <p>Is there a cast I need to do to make this work? It seems to return x without problem, the real myfunction returns pointers to structs and character strings as well which all work as expected.</p>
18,117,947
4
3
null
2013-08-08 03:25:00.617 UTC
1
2016-01-05 15:32:48.037 UTC
2013-08-08 06:48:14.643 UTC
null
694,576
null
2,662,982
null
1
10
c|function|casting|integer|void
63,157
<p>It's not obvious what you're trying to accomplish here, but I'll assume you're trying to do some pointer arithmetic with x, and would like x to be an integer for this arithmetic but a void pointer on return. Without getting into why this does or doesn't make sense, you can eliminate the warning by explicitly casting x to a void pointer.</p> <pre><code>void *myfunction() { int x = 5; return (void *)x; } </code></pre> <p>This will most likely raise another warning, depending on how your system implements pointers. You may need to use a long instead of an int.</p> <pre><code>void *myfunction() { long x = 5; return (void *)x; } </code></pre>