id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,030,436 | Activation error occured while trying to get instance of type Database, key "" <-- blank | <p>I'm trying out the Enterprise Library 5.0 and was doing some unit-tests on my BL, do I need to have a app.config on the DL or on the Test project?</p>
<p>note: I already have the configuration settings on my web.config on my web project.</p>
<p><strong>how I use the DAAB:</strong></p>
<pre><code>private static Database db = DatabaseFactory.CreateDatabase();
db.ExecuteNonQuery("spInsertSalesman", salesman.Fullname);
</code></pre>
<p><strong>my app.config on DL:</strong></p>
<pre><code><configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<dataConfiguration defaultDatabase="DBTEST" />
<connectionStrings>
<add name="DBTEST" connectionString="Data Source=[dbsource];Initial Catalog=[dbname];User Id=sa;Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
</code></pre> | 4,040,012 | 7 | 3 | null | 2010-10-27 06:13:45.317 UTC | 2 | 2015-02-25 16:42:58.967 UTC | 2010-10-27 11:00:51.22 UTC | null | 437,301 | null | 162,381 | null | 1 | 11 | c#|unit-testing|enterprise-library | 57,813 | <p>i was referencing the wrong .dll copy. it works now.</p> |
3,805,478 | Internal HSQL database complains about privileges | <p>I'm setting up a standalone Java service with an in-process, in-memory HSQL database.</p>
<p><strong>Persistence.xml</strong></p>
<pre><code><persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="manager">
<class>tr.silvercar.data.entities.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:testdb" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.max_fetch_depth" value="3" />
<!-- cache configuration -->
<!--
<property name="hibernate.ejb.classcache.org.hibernate.ejb.test.Item"
value="read-write" />
<property
name="hibernate.ejb.collectioncache.org.hibernate.ejb.test.Item.distributors"
value="read-write, RegionName" />
-->
</properties>
</persistence-unit>
</persistence>
</code></pre>
<p><strong>Code</strong></p>
<pre><code> emf = Persistence.createEntityManagerFactory("manager");
User newUser = new User();
newUser.setName("Testgebruiker");
newUser.setCredits(100);
System.out.println("Inserting user");
EntityManager em = emf.createEntityManager();
em.persist(newUser);
em.close();
System.out.println("Getting user");
em = emf.createEntityManager();
User u = (User) em.createQuery("SELECT u FROM User u").getSingleResult();
em.close();
System.out.println(u);
</code></pre>
<p>It would seem to me that since the database is in memory, and Hibernate should generate tables, that I don't need to do anything else. However, upon calling <code>getSingleResult</code> I get the exception:</p>
<pre><code>org.hsqldb.HsqlException: user lacks privilege or object not found: USER
</code></pre> | 3,808,595 | 8 | 2 | null | 2010-09-27 15:48:52.623 UTC | 3 | 2017-04-06 15:27:45.967 UTC | 2011-09-28 10:56:02.563 UTC | null | 85,821 | null | 85,821 | null | 1 | 13 | java|database|jpa|persistence|hsqldb | 44,840 | <p>You need to use Hibernate 3.5.6 or later, together with HSQLDB version 2.2.x or later. Otherwise, older Hibernte jars work with HSQLDB 1.8.x. The name of the table is not a problem.
I have developed the dialect and run the Hibernate tests for this version, but Pascal knows a lot more about Hibernate usage than I do and has helped a lot of people here.</p> |
3,757,071 | PHP - Debugging Curl | <p>I'd like to see what the post fields in the request are before I send it. (For debugging purposes).</p>
<p>The PHP library (class) I am using is already made (not by me), so I am trying to understand it.</p>
<p>As far as I can tell, it uses <code>curl_setopt()</code> to set different options like headers and such and then it uses <code>curl_exec()</code> to send the request.</p>
<p>Ideas on how to see what post fields are being sent?</p> | 3,760,294 | 8 | 1 | null | 2010-09-21 03:18:53.553 UTC | 69 | 2022-07-04 09:08:02.773 UTC | 2018-12-11 12:34:49.253 UTC | null | 576,746 | null | 299,216 | null | 1 | 250 | php|debugging|curl | 378,525 | <p>You can enable the <code>CURLOPT_VERBOSE</code> option:</p>
<pre><code>curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
</code></pre>
<p>When <code>CURLOPT_VERBOSE</code> is set, output is written to <strong>STDERR</strong> or the file specified using <code>CURLOPT_STDERR</code>. The output is very informative.</p>
<p>You can also use tcpdump or wireshark to watch the network traffic.</p> |
4,030,928 | Extract digits from a string in Java | <p>I have a Java <code>String</code> object. I need to extract only digits from it. I'll give an example:</p>
<p><code>"123-456-789"</code> I want <code>"123456789"</code></p>
<p>Is there a library function that extracts only digits?</p>
<p>Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?</p> | 4,030,936 | 14 | 0 | null | 2010-10-27 07:41:35.977 UTC | 49 | 2020-07-21 11:55:05.393 UTC | 2010-11-01 23:46:43.523 UTC | null | 227,665 | null | 488,469 | null | 1 | 226 | java|string | 340,253 | <p>You can use regex and delete non-digits.</p>
<pre><code>str = str.replaceAll("\\D+","");
</code></pre> |
3,625,759 | Difference between "while" loop and "do while" loop | <p>What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:</p>
<pre><code>do {
printf("Word length... ");
scanf("%d", &wdlen);
} while(wdlen<2);
</code></pre>
<p>This code works perfectly. It prints word length and tascans the input. But when I changed it to</p>
<pre><code>while(wdlen<2){
printf("Word length... ");
scanf("%d", &wdlen);
}
</code></pre>
<p>It gives a blank screen. It do not work. So there is some functional difference between both loops. Can anybody explain it?</p>
<p>Is there any other difference in these two?</p> | 3,625,771 | 16 | 2 | null | 2010-09-02 09:27:01.383 UTC | 13 | 2020-07-19 08:31:10.933 UTC | 2020-07-19 08:31:10.933 UTC | null | 6,296,561 | null | 417,552 | null | 1 | 39 | c|loops | 378,773 | <p>The <strong>do while</strong> loop executes the content of the loop once before checking the condition of the while. </p>
<p>Whereas a <strong>while</strong> loop will check the condition first before executing the content.</p>
<p>In this case you are waiting for user input with scanf(), which will never execute in the <strong>while</strong> loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.</p> |
3,231,804 | In Bash, how to add "Are you sure [Y/n]" to any command or alias? | <p>In this particular case, I'd like to add a confirm in Bash for</p>
<pre>
Are you sure? [Y/n]
</pre>
<p>for Mercurial's <code>hg push ssh://[email protected]//somepath/morepath</code>, which is actually an alias. Is there a standard command that can be added to the alias to achieve it?</p>
<p>The reason is that <code>hg push</code> and <code>hg out</code> can sound similar and sometimes when I want <code>hgoutrepo</code>, I may accidentlly type <code>hgpushrepo</code> (both are aliases).</p>
<p><strong>Update:</strong> if it can be something like a built-in command with another command, such as: <code>confirm && hg push ssh://...</code> that'd be great... just a command that can ask for a <code>yes</code> or <code>no</code> and continue with the rest if <code>yes</code>.</p> | 3,232,082 | 18 | 9 | null | 2010-07-12 19:58:32.85 UTC | 81 | 2021-12-29 12:43:21.387 UTC | 2017-04-07 22:04:49.15 UTC | null | 325,418 | null | 325,418 | null | 1 | 273 | bash|alias|confirmation | 225,450 | <p>These are more compact and versatile forms of <a href="https://stackoverflow.com/questions/3231804/in-bash-how-to-add-are-you-sure-y-n-to-any-command-or-alias/3231821#3231821"><strong>Hamish's</strong> answer</a>. They handle any mixture of upper and lower case letters:</p>
<pre><code>read -r -p "Are you sure? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
do_something
;;
*)
do_something_else
;;
esac
</code></pre>
<p>Or, for Bash >= version 3.2:</p>
<pre><code>read -r -p "Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
do_something
else
do_something_else
fi
</code></pre>
<p>Note: If <code>$response</code> is an empty string, it will give an error. To fix, simply add quotation marks: <code>"$response"</code>. – Always use double quotes in variables containing strings (e.g.: prefer to use <code>"$@"</code> instead <code>$@</code>).</p>
<p>Or, Bash 4.x:</p>
<pre><code>read -r -p "Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ "$response" =~ ^(yes|y)$ ]]
...
</code></pre>
<p><strong>Edit:</strong></p>
<p>In response to your edit, here's how you'd create and use a <code>confirm</code> command based on the first version in my answer (it would work similarly with the other two):</p>
<pre><code>confirm() {
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
</code></pre>
<p>To use this function:</p>
<pre><code>confirm && hg push ssh://..
</code></pre>
<p>or</p>
<pre><code>confirm "Would you really like to do a push?" && hg push ssh://..
</code></pre> |
8,331,135 | How to prevent java.lang.OutOfMemoryError: PermGen space at Scala compilation? | <p>I have noticed a strange behavior of my scala compiler. It occasionally throws an OutOfMemoryError when compiling a class. Here's the error message:</p>
<pre><code>[info] Compiling 1 Scala source to /Users/gruetter/Workspaces/scala/helloscala/target/scala-2.9.0/test-classes...
java.lang.OutOfMemoryError: PermGen space
Error during sbt execution: java.lang.OutOfMemoryError: PermGen space
</code></pre>
<p>It only happens once in a while and the error is usually not thrown on the subsequent compile run. I use Scala 2.9.0 and compile via SBT.</p>
<p>Does anybody have a clue as to what might be the cause for this error? Thanks in advance for your insights.</p> | 8,332,600 | 9 | 1 | null | 2011-11-30 18:41:01.22 UTC | 24 | 2021-03-25 18:29:32.383 UTC | 2017-08-30 11:18:21.113 UTC | null | 4,652,706 | null | 877,324 | null | 1 | 81 | scala|apache-spark|memory-management|sbt|scalatra-sbt | 22,200 | <p>The cause for <code>OutOfMemoryError: PermGen space</code> is that it doesn't have enough <a href="http://mark.koli.ch/2009/01/understanding-javas-perm-gen-maxpermsize-heap-space-etc.html" rel="noreferrer">permanent generation space</a> :) If you are using Oracle JVM, you need to add the <code>-XX:MaxPermSize=256M</code> (or some other amount of space) argument to your <code>sbt</code> script. For other JVMs, look at their documentation.</p> |
8,130,823 | set matplotlib 3d plot aspect ratio | <pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
</code></pre>
<p>Setting the aspect ratio works for 2d plots:</p>
<pre><code>ax = plt.axes()
ax.plot([0,1],[0,10])
ax.set_aspect('equal','box')
</code></pre>
<p>But does not for 3d:</p>
<pre><code>ax = plt.axes(projection='3d')
ax.plot([0,1],[0,1],[0,10])
ax.set_aspect('equal','box')
</code></pre>
<p>Is there a different syntax for the 3d case, or it's not implemented?</p> | 8,141,905 | 11 | 1 | null | 2011-11-15 02:35:27.85 UTC | 16 | 2022-09-19 12:23:45.597 UTC | 2021-10-03 12:46:57.637 UTC | null | 7,758,804 | null | 143,476 | null | 1 | 69 | python|matplotlib | 60,515 | <p>My understanding is basically that this isn't implemented yet (see <a href="https://github.com/matplotlib/matplotlib/issues/17172" rel="nofollow noreferrer">this bug in GitHub</a>). I'm also hoping that it is implemented soon. See <a href="http://comments.gmane.org/gmane.comp.python.matplotlib.general/27415" rel="nofollow noreferrer">This link</a> for a possible solution (I haven't tested it myself).</p> |
4,544,636 | What does [\S\s]* mean in regex in PHP? | <p>What is meant by <code>[\s\S]*</code> in regex in PHP? Does <code>[\s\S]*</code> actually match every string the same as <code>.*</code>?</p> | 4,544,642 | 3 | 0 | null | 2010-12-28 08:17:25.463 UTC | 8 | 2018-11-30 11:25:12.93 UTC | 2018-11-30 11:25:12.93 UTC | null | 266,309 | null | 477,822 | null | 1 | 40 | php|regex | 41,483 | <p>By default <code>.</code> doesn't match new lines - <code>[\s\S]</code> is a hack around that problem.<br>
This is common in JavaScript, but in PHP you can use the <code>/s</code> flag to to make the dot match all characters.</p> |
4,072,365 | Understanding CSS selector priority / specificity | <p>I'd like to understand how CSS selectors work with property collisions. How is one property selected over another one?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
background-color: red;
}
div.my_class {
background-color: black;
}
div#my_id {
background-color: blue;
}
body div {
background-color: green;
}
body>div {
background-color: orange;
}
body>div#my_id {
background-color: pink;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my_id" class="my_class">hello</div></code></pre>
</div>
</div>
</p>
<p>How does selector priority work?</p> | 4,072,434 | 4 | 1 | null | 2010-11-01 19:25:23.837 UTC | 15 | 2019-10-31 02:05:18.697 UTC | 2019-10-31 02:05:18.697 UTC | null | 2,930,477 | null | 185,921 | null | 1 | 42 | html|css|css-selectors | 48,146 | <p>I'll just toss in a link to the CSS 2.1 spec itself, and how browsers are <em>supposed</em> to calculate specificity:</p>
<p><a href="http://www.w3.org/TR/CSS2/cascade.html#specificity" rel="noreferrer">CSS 2.1 Section 6.4.3</a>:</p>
<blockquote>
<p>A selector's specificity is calculated as follows:</p>
<ul>
<li>count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)</li>
<li>count the number of ID attributes in the selector (= b)</li>
<li>count the number of other attributes and pseudo-classes in the selector (= c)</li>
<li>count the number of element names and pseudo-elements in the selector (= d)</li>
<li>The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.</li>
</ul>
<p>Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.</p>
</blockquote>
<p>If the specificities are equal, then <a href="https://www.w3.org/TR/CSS2/cascade.html#cascading-order" rel="noreferrer">CSS 2.1 Section 6.4.1</a> comes into play:</p>
<blockquote>
<ol start="4">
<li>Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.</li>
</ol>
</blockquote>
<p>Note that this is talking about when the style is defined, not when it is used. If classes <code>.a</code> and <code>.b</code> have equal specificity, whichever is defined last <strong>in the stylesheet(s)</strong> wins. <code><p class="a b">...</p></code> and <code><p class="b a">...</p></code> will be styled identically, based on the definition order of <code>.a</code> and <code>.b</code>.</p> |
4,053,917 | Where is the HTML5 Document Type Definition? | <p>The "old" HTML/XHTML standards have a DTD (Document Type Definition) defined for them:</p>
<p>HTML 4.01 <a href="http://www.w3.org/TR/html401/sgml/dtd.html" rel="nofollow noreferrer">http://www.w3.org/TR/html401/sgml/dtd.html</a><br />
XHTML 1.0 <a href="http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict" rel="nofollow noreferrer">http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict</a></p>
<p><strike>This DTDs specify the rules for nesting elements - "which types of elements may appear in which types of elements". I made a diagram for XHTML 1.0 here</strike> (sorry, I no longer have that resource)</p>
<p>I would like to update that diagram with a new version which also includes the new HTML5 elements. However, there doesn't seem to be a HTML5 DTD. It seems that the nesting rules are defined by the various content models that are defined in HTML5.</p>
<p>So there is no DTD, correct?</p>
<p><em><strong>Follow-up question:</strong></em> Is there a reason why there is no DTD in HTML5? The DTD is such a nice method of defining the nesting rules for all the different types of elements. Why wouldn't they include such a thing?</p>
<p><em><strong>Update:</strong></em> I found this: <a href="http://www.w3.org/TR/html5/dom.html#kinds-of-content" rel="nofollow noreferrer">http://www.w3.org/TR/html5/dom.html#kinds-of-content</a> I guess, this is the closest to having a DTD.</p>
<p><em><strong>Update:</strong></em> The Visual Studio Team made a XML Schema for XHTML5. I guess that answers my question: <a href="https://web.archive.org/web/20120730085926/http://blogs.msdn.com/b/webdevtools/archive/2009/11/18/html-5-intellisense-and-validation-schema-for-visual-studio-2008-and-visual-web-developer.aspx" rel="nofollow noreferrer">Link</a></p> | 15,245,834 | 5 | 5 | null | 2010-10-29 16:31:28.64 UTC | 19 | 2021-09-15 05:45:54.373 UTC | 2021-09-15 05:45:54.373 UTC | null | 4,751,173 | null | 425,275 | null | 1 | 73 | html|dtd|sgml | 27,216 | <p>There is no HTML5 DTD. The HTML5 RC explicitly <a href="http://www.w3.org/TR/html5/the-xhtml-syntax.html#writing-xhtml-documents" rel="noreferrer">says this</a> when discussing XHTML serialization, and this clearly applies to HTML serialization as well.</p>
<p>DTDs have been regarded by the designers of HTML5 as too limited in expressive power, and HTML5 validators (basically the HTML5 mode of <a href="http://validator.nu" rel="noreferrer">http://validator.nu</a> and its copy at <a href="http://validator.w3.org/nu/" rel="noreferrer">http://validator.w3.org/nu/</a>) use schemas and ad hoc checks, not DTD-based validation.</p>
<p>Moreover, HTML5 has been designed so that writing a DTD for it is impossible. For example, there is no SGML way to capture the HTML5 rule that any attribute name that starts with “data-” and complies with certain general rules is valid. In SGML, attributes need to be listed individually, so a DTD would need to be infinite.</p>
<p>It is possible to design DTDs that correspond to HTML5 with some omissions and perhaps with some extra rules imposed, but they won’t really be HTML5 DTDs. My <a href="http://www.cs.tut.fi/~jkorpela/html5-dtd.html" rel="noreferrer">experiment</a> with the idea is not very encouraging: too many limitations, too tricky, and the DTD would need to be so permissive that many syntax errors would go uncaught.</p> |
4,605,588 | How to merge some spannable objects? | <p>I divide a spannable object into 3 parts, do different operations, and then I need to merge them.</p>
<pre><code>Spannable str = editText.getText();
Spannable selectionSpannable = new SpannableStringBuilder(str, selectionStart, selectionEnd);
Spannable endOfModifiedSpannable = new SpannableStringBuilder(str, selectionEnd, editText.getText().length());
Spannable beginningOfModifiedSpannable = new SpannableStringBuilder(str, 0, selectionStart);
</code></pre>
<p>How can I do it? I haven't found the required method or constructor to do it.</p> | 4,605,639 | 5 | 0 | null | 2011-01-05 15:10:14.553 UTC | 9 | 2021-01-10 11:44:51.907 UTC | 2019-05-27 14:02:53.91 UTC | null | 1,000,551 | null | 564,122 | null | 1 | 73 | android|spannable|charsequence | 29,336 | <p>You could use this:</p>
<pre><code>TextUtils.concat(span1, span2);
</code></pre>
<p><a href="http://developer.android.com/reference/android/text/TextUtils.html#concat(java.lang.CharSequence...)" rel="noreferrer">http://developer.android.com/reference/android/text/TextUtils.html#concat(java.lang.CharSequence...)</a></p> |
4,740,984 | c# regex matches example | <p>I am trying to get values from the following text. How can this be done with Regex?</p>
<h3>Input</h3>
<blockquote>
<p>Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit. </p>
</blockquote>
<h3>Output</h3>
<pre><code>456
3434
298
893434
</code></pre> | 4,741,010 | 6 | 0 | null | 2011-01-19 21:29:14.663 UTC | 8 | 2021-05-27 20:53:05.21 UTC | 2020-04-17 06:55:19.23 UTC | null | 1,402,846 | null | 543,565 | null | 1 | 79 | c#|regex | 256,797 | <p>So you're trying to grab numeric values that are preceded by the token "%download%#"?</p>
<p>Try this pattern:</p>
<pre><code>(?<=%download%#)\d+
</code></pre>
<p>That should work. I don't think <code>#</code> or <code>%</code> are special characters in .NET Regex, but you'll have to either escape the backslash like <code>\\</code> or use a <a href="http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx" rel="noreferrer">verbatim string</a> for the whole pattern:</p>
<pre><code>var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);
</code></pre>
<p>Tested here: <a href="http://rextester.com/BLYCC16700" rel="noreferrer">http://rextester.com/BLYCC16700</a></p>
<p><strong>NOTE:</strong> The lookbehind assertion <code>(?<=...)</code> is important because you don't want to include <code>%download%#</code> in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">More on lookaround assertions here.</a></p> |
4,758,145 | How to use unscoped on associated relations in Rails3? | <p>I have a default scope on products due to information security constraints.</p>
<pre><code>class Product < ActiveRecord::Base
has_many :photos
default_scope where('visible = 1')
end
</code></pre>
<p>In my associated Photo model, however, I also have to find products that should not be visible.</p>
<pre><code>class Photo < ActiveRecord::Base
belongs_to :product
end
my_photo.product
</code></pre>
<p>In other cases, I can use <a href="http://apidock.com/rails/ActiveRecord/Base/unscoped/class?q=unscoped" rel="noreferrer">unscoped</a> in order to bypass the default_scope, e.g. in <code>Product.unscoped.find_by_title('abc')</code>. However:</p>
<p><strong>How to remove the scope when using associations of a record?</strong></p>
<p><code>my_photo.unscoped.product</code> does not make sense as my_photo does not have a method called <code>unscoped</code>. Neither does <code>my_photo.product.unscoped</code> make sense as <code>my_photo.product</code> may already be nil.</p> | 4,759,121 | 7 | 6 | null | 2011-01-21 11:16:13.697 UTC | 19 | 2016-10-29 17:32:51.553 UTC | 2011-01-21 12:31:49.913 UTC | null | 231,529 | null | 231,529 | null | 1 | 70 | ruby-on-rails|ruby-on-rails-3|scope|arel | 36,760 | <p>Oh. I fooled myself. Thought the following would not work... but it does:</p>
<pre><code>Product.unscoped do
my_photo.product
end
</code></pre>
<p>Notice that you have to call unscoped on the model with the <code>default_scope</code> that should be bypassed.</p>
<p>Also, inheritance has to be respected. If you have <code>class InsuranceProduct < Product</code>and <code>class FinancialProduct < Product</code> and a <code>default_scope</code> in <code>Product</code>, all of the following two combinations will work:</p>
<pre><code>InsuranceProduct.unscoped do
my_record.insurance_products
end
FinancialProduct.unscoped do
my_record.financial_products
end
Product.unscoped do
my_record.products
end
</code></pre>
<p>However, the following <strong>will not work</strong> although the scope is defined in <code>Product</code>:</p>
<pre><code>Product.unscoped do
my_record.financial_products
end
</code></pre>
<p>I guess that's another quirk of STI in Ruby / Rails.</p> |
4,567,688 | Problems with a PHP shell script: "Could not open input file" | <p>Ok, I am <em>trying</em> to create an email logger, that uses a PHP shell script. I have set up CPanel to pipe emails to my script. I am sure this is all configured properly. However I am having problems with the script, well any script for that matter when running it from the shell.</p>
<p>here is an example.</p>
<pre><code>#!/usr/local/bin/php –q
<?php
/* Read the message from STDIN */
$fd = fopen("php://stdin", "r");
$email = ""; // This will be the variable holding the data.
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
/* Saves the data into a file */
$fdw = fopen("mail.txt", "w+");
fwrite($fdw, $email);
fclose($fdw);
/* Script End */
?>
</code></pre>
<p>Real simple, right? Read from STDIN and write to a file...I thought something was wrong, not able to read STDIN for some reason. Hosting provider allows it, allow_url_open and allow_url_include are both on.</p>
<p>When executing the script via SSH I get the following error:
Could not open input file: âq</p>
<p>So once again I thought that was the script telling me, that is could not read from STDIN</p>
<p>So I tried just a simple script.</p>
<pre><code>#!/usr/local/bin/php –q
<?php
echo 'Hello World';
?>
</code></pre>
<p>Same thing:
Could not open input file: âq</p>
<p>So it appears that the PHP program is telling me it is unable to open the script? The script is located in $HOME/mail/forward (CHMOD 755) and the script itself is CHMOD 755, as well the file mail.txt is CHMOD 755
I am really stumped on this.</p> | 4,567,705 | 8 | 1 | null | 2010-12-31 02:29:45.18 UTC | 2 | 2020-12-06 04:51:05.063 UTC | 2010-12-31 02:52:41.84 UTC | null | 23,897 | null | 526,849 | null | 1 | 19 | php|bash|shell | 130,400 | <p>Have you tried:</p>
<pre><code>#!/usr/local/bin/php
</code></pre>
<p>I.e. without the <code>-q</code> part? That's what the error message "Could not open input file: -q" means. The first argument to <code>php</code> if it doesn't look like an option is the name of the PHP file to execute, and <code>-q</code> is CGI only.</p>
<p><strong>EDIT:</strong> A couple of (non-related) tips:</p>
<ol>
<li>You don't need to terminate the last block of PHP with <code>?></code>. In fact, it is often better not to.</li>
<li>When executed on the command line, PHP defines the global constant <code>STDIN</code> to <code>fopen("php://stdin", "r")</code>. You can use that instead of opening <code>"php://stdin"</code> a second time: <code>$fd = STDIN;</code></li>
</ol> |
4,687,208 | Using .htaccess to make all .html pages to run as .php files? | <p>I need to run all of my .html files as .php files and I don't have time to change all of the links before our presentation tomorrow. Is there any way to "hack" this with my Apache server?</p> | 4,687,217 | 18 | 2 | null | 2011-01-14 01:33:55.93 UTC | 16 | 2022-03-24 09:08:31.267 UTC | null | null | null | null | 573,582 | null | 1 | 56 | php|html|apache|.htaccess | 140,960 | <p>Create a .htaccess file at the root of your website and add this line:</p>
<p>[Apache2 @ Ubuntu/Debian: use this directive]</p>
<pre><code>AddType application/x-httpd-php .html .htm
</code></pre>
<p>Or, from comment below:</p>
<pre><code>AddType application/x-httpd-php5 .html .htm
</code></pre>
<p>If your are running PHP as CGI (probably not the case), you should write instead:</p>
<pre><code>AddHandler application/x-httpd-php .html .htm
</code></pre> |
14,750,711 | Catch python 'ImportError' if import from source directory | <p>When one tries to import a module <code>foo</code> while being in the source directory, one gets an rather confusing <code>ImportError</code> message: <code>ImportError: No module named foo</code>.</p>
<p>How can I easily catch this case and return a more informative message, e.g. 'Please do not load module foo from the source directory'?</p>
<p>Having the <code>__init__.py</code>, I would start with:</p>
<pre><code>try:
from _foo import *
except ImportError:
## check whether in the source directory...
</code></pre>
<p>So I would like to distinguish the different causes for an <code>ImportError</code> (e.g. because a module named <code>foo</code> is not installed at all), and detect the case in which the <code>setup.py</code> is located in the current directory. What would be a elegant way of doing this?</p> | 14,750,951 | 1 | 0 | null | 2013-02-07 12:05:43.407 UTC | null | 2013-02-07 13:42:34.423 UTC | 2013-02-07 13:42:34.423 UTC | null | 515,189 | null | 1,116,234 | null | 1 | 34 | python|exception-handling|importerror | 70,380 | <p><code>ImportError: No module named foo</code> actually means the module <code>foo.py</code> or package <code>foo/__init__.py</code> could not be found in any of the directories in the search path (<code>sys.path</code> list).</p>
<p>Since <code>sys.path</code> usually contains <code>.</code> (the current directory), that's probably what you meant by <em>being in the source directory</em>. You are in the top-level directory of package <code>foo</code> (where the <code>__init__.py</code> file is) so obviously you can't find <code>foo/__init__.py</code>.</p>
<p>Finally, you've answered your own question, more or less:</p>
<pre><code>try:
from _foo import *
except ImportError:
raise ImportError('<any message you want here>')
</code></pre>
<p>Alternatively, you could check the contents of <code>sys.path</code>, the current directory and, if known, the expected package directory and produce an even detailed and context-aware message. </p>
<p>Or add <code>..</code> to the <code>PYTHONPATH</code> environment variable (on Unix) to allow you to run from your source directory. Might even work on Windows, but I wouldn't know.</p> |
14,453,864 | Use more than one schema per collection on mongodb | <p>I wanted to use more than one schema per collection in mongodb , how to use it....?<br>
It gives me this error when I try to run it:
<br><br>Error: </p>
<blockquote>
<p>OverwriteModelError: Cannot overwrite <code>allUsers</code> model once compiled.
<br> OverwriteModelError: Cannot overwrite <code>checkInOut</code> model once compiled.</p>
</blockquote>
<p><br>Heres my schema.js</p>
<pre><code> var mongoose = require('mongoose');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var checkInInfoSchema= new Schema({
name:String,
loginSerialId:Number
});
var loginUserSchema = new Schema({
sn : { type: Number, unique:true }
,uname: {type:String, unique:true}
,pass:String
});
var registerUserSchema = new Schema({
sn : { type: Number, unique:true }
, name: String //his/her name
,pass:String,
companyKey:{type:String},
uname:{type:String,unique:true}
});
var checkInOutSchema = new Schema({
uname: String
,companyKey:String
,task:String
,inTime:String
,outTime:String
,date:{type:String}
,serialId:{type:Number,unique:true}
,online:Boolean
});
//Different schema for same collection "allUsers"
var allUser=mongoose.model('allUsers',loginUserSchema);
var registerUser=mongoose.model('allUsers',registerUserSchema);
//Different schema for same collection "checkInOut"
var checkInOut=mongoose.model('checkInOut',checkInOutSchema);
var checkInInfo=mongoose.model('checkInOut',checkInInfoSchema);
module.exports={
allUser:allUser,
registerUser:registerUser,
checkInOut:checkInOut,
checkInInfo:checkInInfo
};
</code></pre> | 14,454,102 | 3 | 0 | null | 2013-01-22 07:50:57.947 UTC | 13 | 2021-09-21 15:13:12.65 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 1,949,475 | null | 1 | 39 | node.js|mongodb|mongoose|schema-design|nosql | 36,868 | <p>In mongoose you can do something like this:</p>
<pre><code>var users = mongoose.model('User', loginUserSchema, 'users');
var registerUser = mongoose.model('Registered', registerUserSchema, 'users');
</code></pre>
<p>This two schemas will save on the 'users' collection.</p>
<p>For more information you can refer to the documentation: <a href="http://mongoosejs.com/docs/api.html#index_Mongoose-model" rel="noreferrer">http://mongoosejs.com/docs/api.html#index_Mongoose-model</a> or you can see the following <a href="https://gist.github.com/1892652" rel="noreferrer">gist</a> it might help.</p> |
14,427,253 | passing several arguments to FUN of lapply (and others *apply) | <p>I have a question regarding passing multiple arguments to a function, when using <code>lapply</code> in <code>R</code>. </p>
<p>When I use lapply with the syntax of <code>lapply(input, myfun);</code> - this is easily understandable, and I can define myfun like that:</p>
<pre><code>myfun <- function(x) {
# doing something here with x
}
lapply(input, myfun);
</code></pre>
<p>and elements of <code>input</code> are passed as <code>x</code> argument to <code>myfun</code>.</p>
<p>But what if I need to pass some more arguments to <code>myfunc</code>? For example, it is defined like that:</p>
<pre><code>myfun <- function(x, arg1) {
# doing something here with x and arg1
}
</code></pre>
<p>How can I use this function with passing both <code>input</code> elements (as <code>x</code> argument) and some other argument?</p> | 14,427,278 | 4 | 1 | null | 2013-01-20 17:38:41.697 UTC | 45 | 2019-11-04 06:07:05.917 UTC | 2019-05-22 12:53:36.333 UTC | null | 10,229,584 | null | 1,707,278 | null | 1 | 135 | r|lapply | 128,846 | <p>If you look up the help page, one of the arguments to <code>lapply</code> is the mysterious <code>...</code>. When we look at the Arguments section of the help page, we find the following line:</p>
<pre><code>...: optional arguments to ‘FUN’.
</code></pre>
<p>So all you have to do is include your other argument in the <code>lapply</code> call as an argument, like so:</p>
<pre><code>lapply(input, myfun, arg1=6)
</code></pre>
<p>and <code>lapply</code>, recognizing that <code>arg1</code> is not an argument it knows what to do with, will automatically pass it on to <code>myfun</code>. All the other <code>apply</code> functions can do the same thing.</p>
<p><em>An addendum:</em> You can use <code>...</code> when you're writing your own functions, too. For example, say you write a function that calls <code>plot</code> at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use <code>...</code> (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to <code>plot</code>.</p> |
2,953,354 | How can I set the current schema for DB2 using Hibernate/JDBC? | <p>I used to use currentSchema=MYSCHEMA; in my JDBC URL connection, but the version of DB2 we're using no longer supports that, showing the error 'The "currentSchema" property is not allowed on the target server'. I've tried using hibernate.default_schema, but it's not automatically adding the schema to my table names. I don't want to set the schema on every @Table annotation since I'll need to change it between test and production. Is there another way to set on the connection or via Hibernate?</p>
<p>Update: it must have been a driver version issue. I upgraded to later drivers and currentSchema worked.</p> | 2,953,703 | 2 | 0 | null | 2010-06-01 21:09:00.317 UTC | 4 | 2020-11-18 17:36:42.837 UTC | 2010-06-02 03:00:31.563 UTC | null | 14,619 | null | 14,619 | null | 1 | 18 | jdbc|schema|db2 | 38,403 | <p>All the properties for the 9.7 (Latest) db are here...</p>
<p><a href="https://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.apdv.java.doc/doc/r0052607.html" rel="noreferrer">https://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.apdv.java.doc/doc/r0052607.html</a></p>
<p>use: </p>
<blockquote>
<p>currentSchema</p>
</blockquote>
<p>Specifies the default schema name that is used to qualify unqualified database objects in dynamically prepared SQL statements. The value of this property sets the value in the CURRENT SCHEMA special register on the database server. The schema name is case-sensitive, and must be specified in uppercase characters.</p> |
2,578,752 | How can I plot NaN values as a special color with imshow in matplotlib? | <p>I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap.</p>
<p>example:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
a = np.arange(25).reshape((5,5)).astype(float)
a[3,:] = np.nan
ax.imshow(a, interpolation='nearest')
f.canvas.draw()
</code></pre>
<p>The resultant image is unexpectedly all blue (the lowest color in the jet colormap). However, if I do the plotting like this:</p>
<pre><code>ax.imshow(a, interpolation='nearest', vmin=0, vmax=24)
</code></pre>
<p>--then I get something better, but the NaN values are drawn the same color as vmin... Is there a graceful way that I can set NaNs to be drawn with a special color (eg: gray or transparent)?</p> | 46,649,061 | 2 | 1 | null | 2010-04-05 14:03:56.713 UTC | 33 | 2017-10-09 14:40:32.587 UTC | 2010-04-05 16:44:50.613 UTC | null | 214,035 | null | 214,035 | null | 1 | 96 | python|matplotlib|nan | 72,974 | <p>With newer versions of Matplotlib, it is not necessary to use a masked array anymore.</p>
<p>For example, let’s generate an array where every 7th value is a NaN:</p>
<pre><code>arr = np.arange(100, dtype=float).reshape(10, 10)
arr[~(arr % 7).astype(bool)] = np.nan
</code></pre>
<p>We can modify the current colormap and plot the array with the following lines:</p>
<pre><code>current_cmap = matplotlib.cm.get_cmap()
current_cmap.set_bad(color='red')
plt.imshow(arr)
</code></pre>
<p><img src="https://i.stack.imgur.com/fAOdf.png" alt="plot result"></p> |
36,869,258 | How to use Graphviz with Anaconda/Spyder? | <p>I am attempting to use Graphviz from Spyder (via an Anaconda install). I am having trouble understanding what is needed to do this and how to go about loading packages, setting variables, etc.</p>
<p>I straight forward approach for a new Python and Graphviz and Spyder user would be great!</p>
<p>Also, apart from just creating and running Graphviz, how can one run Graphviz from python with a pre-generated .gv file?</p> | 36,869,259 | 3 | 0 | null | 2016-04-26 15:23:37.423 UTC | 7 | 2020-10-06 13:49:22.21 UTC | 2017-11-02 00:31:20.137 UTC | null | 5,639,728 | null | 5,639,728 | null | 1 | 9 | python-3.x|anaconda|graphviz|spyder | 38,259 | <p>Here are the steps that worked for me. Much of this information was available but spread out in several different StackOverflow posts and other websites. I hope that this serves as a good one-stop resource.</p>
<ol>
<li><p>Go to the <a href="http://www.graphviz.org/" rel="noreferrer">Graphviz website</a> and download and install to your computer (do NOT need to install for all users).</p></li>
<li><p>Download and install Anaconda3.5 from the <a href="https://www.continuum.io/downloads" rel="noreferrer">Continuum website</a>.</p></li>
<li><p>Add Graphviz to the environment variable "Path":</p>
<ul>
<li>Go to <code>Computer > Properties > Advanced system settings > Environment Variables</code> and then find "Path" in the system variables box. Click on Path and click edit.</li>
<li>Append <code>;C:\Program Files (x86)\Graphviz2.38\bin</code> to the end of the many paths that are already present in Path. Note, the path to Graphviz may be different for you so make sure to put the correct path. The folder "bin" should have many files including the <code>dot.exe</code> application.</li>
<li>To check the install go to the command prompt and enter: <code>dot -V</code> this should return the version of Graphviz installed. For example, <code>dot - graphviz version 2.38.0</code>. If this does not work, enter <code>set</code> and look for the Graphviz path.</li>
</ul></li>
<li><p>Go to the Anaconda command prompt and enter: <code>pip install graphviz</code></p></li>
<li><p>Restart Spyder or launch it if not already open.</p></li>
<li><p>Now within your Python script add <code>import graphviz</code></p></li>
<li><p>Below is an example of how to create a graph and render it using Graphviz from a Graphviz tutorial</p>
<pre><code>import graphviz
dot = graphviz.Digraph(comment='The Round Table')
dot.node('A', 'King Arthur')
dot.node('B', 'Sir Bedevere the Wise')
dot.node('L', 'Sir Lancelot the Brave')
dot.edges(['AB', 'AL'])
dot.edge('B', 'L', constraint='false')
dot.render('FileName', view=True)
</code></pre></li>
<li><p>Below is an example of how to create a graph from a pre-generated .gv file (at least a starting point for exploration)</p>
<pre><code>from graphviz import Source
Source.from_file('file.gv')
</code></pre></li>
</ol>
<p>Usefull Links:</p>
<p><a href="http://matthiaseisen.com/articles/graphviz/" rel="noreferrer">Getting started with Graphviz and Python</a></p>
<p><a href="http://www.graphviz.org/doc/info/attrs.html" rel="noreferrer">Graphviz Attributes</a></p>
<p><a href="http://www.graphviz.org/pdf/dotguide.pdf" rel="noreferrer">Dot Guide</a></p>
<p><a href="https://stackoverflow.com/questions/18438997/why-is-pydot-unable-to-find-graphvizs-executables-in-windows-8">Another StackOverflow Question</a></p>
<p>Versions Used:</p>
<p>Anaconda 3.5 (comes with Spyder)</p>
<p>Graphviz 2.38</p> |
40,445,125 | how can component delete itself in Vue 2.0 | <p>as title, how can I do that</p>
<p>from offical documentation just tell us that $delete can use argument 'object' and 'key'</p>
<p>but I want delete a component by itself like this</p>
<pre><code>this.$delete(this)
</code></pre> | 40,445,367 | 4 | 0 | null | 2016-11-06 01:30:05.123 UTC | 10 | 2022-07-15 20:45:33.873 UTC | null | null | null | null | 6,337,438 | null | 1 | 46 | vue.js|vue-component | 92,198 | <p>No, you will not be able to delete a component directly. The parent component will have to use <code>v-if</code> to remove the child component from the DOM.</p>
<p>Ref: <a href="https://v2.vuejs.org/v2/api/#v-if" rel="nofollow noreferrer">https://v2.vuejs.org/v2/api/#v-if</a></p>
<p>Quoted from docs:</p>
<blockquote>
<p>Conditionally render the element based on the truthy-ness of the expression value. The element and its contained directives / components are destroyed and re-constructed during toggles.</p>
</blockquote>
<p>If the child component is created as part of some data object on parent, you will have to send an event to parent via <code>$emit</code>, modify (or remove) the data and the child component will go away on its own. There was another question on this recently: <a href="https://stackoverflow.com/questions/40181133/delete-a-vue-child-component">Delete a Vue child component</a></p> |
27,888,429 | How can I create a stream from an array? | <p>Currently whenever I need to create stream from an array, I do</p>
<pre><code>String[] array = {"x1", "x2"};
Arrays.asList(array).stream();
</code></pre>
<p>Is there some direct way to create stream from an array?</p> | 27,888,447 | 6 | 0 | null | 2015-01-11 14:57:54.587 UTC | 18 | 2019-10-22 21:53:06.263 UTC | 2015-01-12 14:10:15.687 UTC | null | 1,864,167 | null | 4,360,647 | null | 1 | 140 | java|arrays|java-8|java-stream | 68,144 | <p>You can use Arrays.stream E.g.</p>
<pre><code>Arrays.stream(array);
</code></pre>
<p>You can also use <code>Stream.of</code> as mentioned by @fge , which looks like</p>
<pre><code>public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
</code></pre>
<p>But note <code>Stream.of(intArray)</code> will return <code>Stream<int[]></code> whereas <code>Arrays.stream(intArr)</code> will return <code>IntStream</code> providing you pass an array of type <code>int[]</code>. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.</p>
<pre><code>int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);
IntStream stream2 = Arrays.stream(arr);
</code></pre>
<p>When you pass primitive array to <code>Arrays.stream</code>, the following code is invoked</p>
<pre><code>public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
</code></pre>
<p>and when you pass primitive array to <code>Stream.of</code> the following code is invoked</p>
<pre><code> public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
</code></pre>
<p>Hence you get different results.</p>
<p><strong>Updated</strong>: As mentioned by <a href="https://stackoverflow.com/users/1441122/stuart-marks">Stuart Marks</a> comment
The subrange overload of <code>Arrays.stream</code> is preferable to using <code>Stream.of(array).skip(n).limit(m)</code> because the former results in a SIZED stream whereas the latter does not. The reason is that <code>limit(m)</code> doesn't know whether the size is m or less than m, whereas <code>Arrays.stream</code> does range checks and knows the exact size of the stream
You can read the source code for stream implementation returned by <code>Arrays.stream(array,start,end)</code> <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/stream/ReferencePipeline.java#ReferencePipeline.Head" rel="noreferrer">here</a>, whereas for stream implementation returned by <code>Stream.of(array).skip().limit()</code> is within <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/stream/SliceOps.java#SliceOps.makeRef%28java.util.stream.AbstractPipeline%2Clong%2Clong%29" rel="noreferrer">this method</a>.</p> |
49,930,180 | Flutter, render widget after async call | <p>I would like to render a widget that needs an HTTP call to gather some data.</p>
<p>Got the following code (simplified)</p>
<pre><code>import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'async demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var asyncWidget;
@override
initState() {
super.initState();
loadData().then((result) {
print(result);
setState(() {
asyncWidget = result;
});
});
}
loadData() async {
var widget = new AsyncWidget();
return widget.build();
}
@override
Widget build(BuildContext context) {
if(asyncWidget == null) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Loading..."),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: this.asyncWidget,
),
);
}
}
}
class MyRenderer {
MyRenderer();
Widget render (List data) {
List<Widget> renderedWidgets = new List<Widget>();
data.forEach((element) {
renderedWidgets.add(new ListTile(
title: new Text("one element"),
subtitle: new Text(element.toString()),
));
});
var lv = new ListView(
children: renderedWidgets,
);
return lv;
}
}
class MyCollector {
Future gather() async {
var response = await // do the http request here;
return response.body;
}
}
class AsyncWidget {
MyCollector collector;
MyRenderer renderer;
AsyncWidget() {
this.collector = new MyCollector();
this.renderer = new MyRenderer();
}
Widget build() {
var data = this.collector.gather();
data.then((response) {
var responseObject = JSON.decode(response);
print(response);
return this.renderer.render(responseObject);
});
data.catchError((error) {
return new Text("Oups");
});
}
}
</code></pre>
<p>My code works like this : the widget using async data takes a collector (which make the http call) and a renderer which will render the widgets with the http data.
I create an instance of this widget on the initState() and then I make my async call.</p>
<p>I found some documentation saying that we should use the setState() method to update the widget with the new data but this doesn't work for me.</p>
<p>However when I put some logs, i see the HTTP call is done and the setState() method is called, but the widget does not update.</p> | 49,931,743 | 2 | 1 | null | 2018-04-19 21:01:09.197 UTC | 13 | 2021-03-23 05:59:40.947 UTC | null | null | null | null | 5,578,655 | null | 1 | 73 | async-await|dart|flutter | 84,810 | <p>The best way to do this is to use a <a href="https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html" rel="noreferrer">FutureBuilder</a>.</p>
<p>From the FutureBuilder documentation:</p>
<pre><code>new FutureBuilder<String>(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
</code></pre>
<p>The other thing is that you're building your widget outside of the State.build method and saving the widget itself, which is an anti-pattern. You should be actually building the widgets each time in the build method.</p>
<p>You could get this to work without FutureBuilder, but you should save the result of the http call (processed appropriately) and then use the data within your build function.</p>
<p>See this, but note that using a FutureBuilder is a better way to do this and I'm just providing this for you to learn.</p>
<pre><code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'async demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List data;
@override
initState() {
super.initState();
new Future<String>.delayed(new Duration(seconds: 5), () => '["123", "456", "789"]').then((String value) {
setState(() {
data = json.decode(value);
});
});
}
@override
Widget build(BuildContext context) {
if (data == null) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Loading..."),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new ListView(
children: data
.map((data) => new ListTile(
title: new Text("one element"),
subtitle: new Text(data),
))
.toList(),
),
),
);
}
}
}
</code></pre> |
32,035,251 | Displaying LaTeX in pyQt/pySide QTableWidget | <p>I would like to add mathematical expressions to the table labels (e.g.: 2^3 should be properly formatted)</p>
<p>Here is a simple example of a table:
<a href="http://thomas-cokelaer.info/blog/2012/10/pyqt4-example-of-tablewidget-usage/" rel="noreferrer">http://thomas-cokelaer.info/blog/2012/10/pyqt4-example-of-tablewidget-usage/</a></p>
<p>setHorizontalHeaderLabels accepts string, only.
I wonder if is it possible to implement somehow this matplotlib approach:
<a href="https://stackoverflow.com/questions/2661441/matplotlib-write-tex-on-qt-form?rq=1">matplotlib - write TeX on Qt form</a></p>
<p>are there other options?</p> | 32,085,761 | 1 | 0 | null | 2015-08-16 12:47:50.993 UTC | 9 | 2015-08-19 03:14:23.163 UTC | 2017-05-23 11:54:58.497 UTC | null | -1 | null | 760,418 | null | 1 | 12 | python|qt|pyqt|latex|pyside | 5,964 | <p>I've also been trying for some time to display complex labels in the header of a <em>QTableWidget</em>. I was able to do it by reimplementing the <em>paintSection</em> method of a <em>QHeaderView</em> and painting manually the label with a <em>QTextDocument</em> as described in a <a href="https://forum.qt.io/topic/30598/solved-how-to-display-subscript-text-in-header-of-qtableview/5" rel="noreferrer">thread on Qt Centre</a>.</p>
<p>However, this solution was somewhat limited compared to what could be done with LaTex. I thought this could be a good idea to try the approach you suggested in your OP, i.e. using the capability of matplotlib to render LaTex in PySide.</p>
<h2>1. Convert matplotlib Figure to QPixmap</h2>
<p>First thing that is required in this approach is to be able to convert matplotlib figure in a format that can be easily painted on any <em>QWidget</em>. Below is a function that take a <a href="http://matplotlib.org/users/mathtext.html" rel="noreferrer">mathTex expression</a> as input and convert it through matplotlib to a <em>QPixmap</em>.</p>
<pre><code>import sys
import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PySide import QtGui, QtCore
def mathTex_to_QPixmap(mathTex, fs):
#---- set up a mpl figure instance ----
fig = mpl.figure.Figure()
fig.patch.set_facecolor('none')
fig.set_canvas(FigureCanvasAgg(fig))
renderer = fig.canvas.get_renderer()
#---- plot the mathTex expression ----
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')
ax.patch.set_facecolor('none')
t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs)
#---- fit figure size to text artist ----
fwidth, fheight = fig.get_size_inches()
fig_bbox = fig.get_window_extent(renderer)
text_bbox = t.get_window_extent(renderer)
tight_fwidth = text_bbox.width * fwidth / fig_bbox.width
tight_fheight = text_bbox.height * fheight / fig_bbox.height
fig.set_size_inches(tight_fwidth, tight_fheight)
#---- convert mpl figure to QPixmap ----
buf, size = fig.canvas.print_to_buffer()
qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1],
QtGui.QImage.Format_ARGB32))
qpixmap = QtGui.QPixmap(qimage)
return qpixmap
</code></pre>
<h2>2. Paint the QPixmaps to the header of a QTableWidget</h2>
<p>The next step is to paint the <em>QPixmap</em> in the header of a <em>QTableWidget</em>. As shown below, I've done it by sub-classing <em>QTableWidget</em> and reimplementing the <em>setHorizontalHeaderLabels</em> method, which is used to convert the mathTex expressions for the labels into <em>QPixmap</em> and to pass it as a list to a subclass of <em>QHeaderView</em>. The <em>QPixmap</em> are then painted within a reimplementation of the <em>paintSection</em> method of <em>QHeaderView</em> and the height of the header is set up to fit the height of the mathTex expression in the reimplementation of the <em>sizeHint</em> methods.</p>
<pre><code>class MyQTableWidget(QtGui.QTableWidget):
def __init__(self, parent=None):
super(MyQTableWidget, self).__init__(parent)
self.setHorizontalHeader(MyHorizHeader(self))
def setHorizontalHeaderLabels(self, headerLabels, fontsize):
qpixmaps = []
indx = 0
for labels in headerLabels:
qpixmaps.append(mathTex_to_QPixmap(labels, fontsize))
self.setColumnWidth(indx, qpixmaps[indx].size().width() + 16)
indx += 1
self.horizontalHeader().qpixmaps = qpixmaps
super(MyQTableWidget, self).setHorizontalHeaderLabels(headerLabels)
class MyHorizHeader(QtGui.QHeaderView):
def __init__(self, parent):
super(MyHorizHeader, self).__init__(QtCore.Qt.Horizontal, parent)
self.setClickable(True)
self.setStretchLastSection(True)
self.qpixmaps = []
def paintSection(self, painter, rect, logicalIndex):
if not rect.isValid():
return
#------------------------------ paint section (without the label) ----
opt = QtGui.QStyleOptionHeader()
self.initStyleOption(opt)
opt.rect = rect
opt.section = logicalIndex
opt.text = ""
#---- mouse over highlight ----
mouse_pos = self.mapFromGlobal(QtGui.QCursor.pos())
if rect.contains(mouse_pos):
opt.state |= QtGui.QStyle.State_MouseOver
#---- paint ----
painter.save()
self.style().drawControl(QtGui.QStyle.CE_Header, opt, painter, self)
painter.restore()
#------------------------------------------- paint mathText label ----
qpixmap = self.qpixmaps[logicalIndex]
#---- centering ----
xpix = (rect.width() - qpixmap.size().width()) / 2. + rect.x()
ypix = (rect.height() - qpixmap.size().height()) / 2.
#---- paint ----
rect = QtCore.QRect(xpix, ypix, qpixmap.size().width(),
qpixmap.size().height())
painter.drawPixmap(rect, qpixmap)
def sizeHint(self):
baseSize = QtGui.QHeaderView.sizeHint(self)
baseHeight = baseSize.height()
if len(self.qpixmaps):
for pixmap in self.qpixmaps:
baseHeight = max(pixmap.height() + 8, baseHeight)
baseSize.setHeight(baseHeight)
self.parentWidget().repaint()
return baseSize
</code></pre>
<h2>3. Application</h2>
<p>Below is an example of a simple application of the above.</p>
<pre><code>if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = MyQTableWidget()
w.verticalHeader().hide()
headerLabels = [
'$C_{soil}=(1 - n) C_m + \\theta_w C_w$',
'$k_{soil}=\\frac{\\sum f_j k_j \\theta_j}{\\sum f_j \\theta_j}$',
'$\\lambda_{soil}=k_{soil} / C_{soil}$']
w.setColumnCount(len(headerLabels))
w.setHorizontalHeaderLabels(headerLabels, 25)
w.setRowCount(3)
w.setAlternatingRowColors(True)
k = 1
for j in range(3):
for i in range(3):
w.setItem(i, j, QtGui.QTableWidgetItem('Value %i' % (k)))
k += 1
w.show()
w.resize(700, 200)
sys.exit(app.exec_())
</code></pre>
<p>which results in:</p>
<p><a href="https://i.stack.imgur.com/YiNVQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YiNVQ.png" alt="enter image description here"></a></p>
<p>The solution is not perfect, but it is a good starting point. I'll update it when I will improve it for my own application.</p> |
44,486,532 | react function is not defined no-undef | <p>I get the following error when trying to compile my app - 'getRestaurants' is not defined no-undef</p>
<p>I'm having trouble tracking down why getRestaurants is not defined for zipCodeToCoords</p>
<p>I have an input component that takes a zip code on submit and calls zipCodeToCoords, I then want to call getRestaurants </p>
<p>Here is the main react component</p>
<pre><code>class App extends Component {
constructor(props){
super(props);
this.state = {
restraunts:[],
selectedRestraunt:null
}
}
getRestaurants(lat,lon){
var url = "https://developers.zomato.com/api/v2.1/geocode?lat="+lat+"&lon="+lon;
$.ajax({
url:url,
headers:{
'Accept': 'application/json',
'user_key': 'MY KEY'
}
}).done(function(data){
console.log(data);
});
}
zipCodeToCoords(zip){
var url = "https://www.zipcodeapi.com/rest/MYKEY/info.json/"+ zip +"/degrees";
$.ajax({
url:url,
}).done(function(data){
console.log(data.lat);
getRestaurants(data.lat,data.lng);
});
}
render() {
return (
<div className="App">
<div className="row">
<div className="columns large-9">
<Input onSearchTermSubmit={this.zipCodeToCoords} />
</div>
</div>
<div className="row">
<div className="columns large-9">
<RestrauntInfo />
</div>
<div className="columns large-3">
<RestrauntList />
</div>
</div>
</div>
);
}
}
</code></pre>
<p>Here is the Input component</p>
<pre><code>class Input extends Component{
constructor(props){
super(props);
this.state = {zip:''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
event.preventDefault();
this.props.onSearchTermSubmit(this.state.zip);
}
handleChange(event){
this.setState({zip:event.target.value});
}
render(){
return(<div>
<form onSubmit={this.handleSubmit}>
<div className="input-group">
<span className="input-group-label">Enter Zip Code</span>
<input className="input-group-field" type="number" value={this.state.zip} onChange={this.handleChange} />
<div className="input-group-button">
<input type="submit" className="button" value="Submit" />
</div>
</div>
</form>
</div>);
}
}
</code></pre> | 44,486,594 | 2 | 0 | null | 2017-06-11 17:12:49.093 UTC | 2 | 2017-06-11 17:39:05.28 UTC | null | null | null | null | 2,631,443 | null | 1 | 16 | reactjs | 109,951 | <p>Get restaurants is not some global function, it is a method on your App class so you need to call it as such. The easiest way to resolve this would probably be to:</p>
<ol>
<li>Change your done callback to an arrow function</li>
<li>Call <code>this.getRestaurants</code> in <code>zipCodeToCoords</code></li>
<li>Bind <code>this</code> to <code>getRestaurants</code> and <code>zipCodeToCoords</code> in your constructor i.e. <code>this.getRestaurants = this.getRestaurants.bind(this);</code></li>
</ol>
<p>The callback would become:</p>
<pre><code>done((data) => {
console.log(data.lat);
this.getRestaurants(data.lat,data.lng);
});
</code></pre> |
39,173,982 | What is a NoSuchBeanDefinitionException and how do I fix it? | <p>Please explain the following about <code>NoSuchBeanDefinitionException</code> exception in Spring:</p>
<ul>
<li>What does it mean?</li>
<li>Under what conditions will it be thrown?</li>
<li>How can I prevent it?</li>
</ul>
<hr>
<p><em>This post is designed to be a comprehensive Q&A about occurrences of <code>NoSuchBeanDefinitionException</code> in applications using Spring.</em></p> | 39,173,983 | 1 | 0 | null | 2016-08-26 20:08:22.763 UTC | 39 | 2020-11-03 16:47:06.913 UTC | 2019-04-12 14:18:40.713 UTC | null | 438,154 | null | 438,154 | null | 1 | 69 | java|spring|applicationcontext | 119,305 | <p>The <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/NoSuchBeanDefinitionException.html" rel="noreferrer">javadoc of <code>NoSuchBeanDefinitionException</code></a> explains</p>
<blockquote>
<p>Exception thrown when a <code>BeanFactory</code> is asked for a bean instance for
which it cannot find a definition. This may point to a non-existing
bean, a non-unique bean, or a manually registered singleton instance
without an associated bean definition.</p>
</blockquote>
<p>A <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html" rel="noreferrer"><code>BeanFactory</code></a> is basically the abstraction representing <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html" rel="noreferrer">Spring's Inversion of Control container</a>. It exposes beans internally and externally, to your application. When it cannot find or retrieve these beans, it throws a <code>NoSuchBeanDefinitionException</code>.</p>
<p>Below are simple reasons why a <code>BeanFactory</code> (or related classes) would not be able to find a bean and how you can make sure it does.</p>
<hr />
<h1>The bean doesn't exist, it wasn't registered</h1>
<p>In the example below</p>
<pre><code>@Configuration
public class Example {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Example.class);
ctx.getBean(Foo.class);
}
}
class Foo {}
</code></pre>
<p>we haven't registered a bean definition for the type <code>Foo</code> either through a <code>@Bean</code> method, <code>@Component</code> scanning, an XML definition, or any other way. The <code>BeanFactory</code> managed by the <code>AnnotationConfigApplicationContext</code> therefore has no indication of where to get the bean requested by <code>getBean(Foo.class)</code>. The snippet above throws</p>
<pre class="lang-none prettyprint-override"><code>Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.example.Foo] is defined
</code></pre>
<p>Similarly, the exception could have been thrown while trying to satisfy an <code>@Autowired</code> dependency. For example,</p>
<pre><code>@Configuration
@ComponentScan
public class Example {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Example.class);
}
}
@Component
class Foo { @Autowired Bar bar; }
class Bar { }
</code></pre>
<p>Here, a bean definition is registered for <code>Foo</code> through <code>@ComponentScan</code>. But Spring knows nothing of <code>Bar</code>. It therefore fails to find a corresponding bean while trying to autowire the <code>bar</code> field of the <code>Foo</code> bean instance. It throws (nested inside a <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/UnsatisfiedDependencyException.html" rel="noreferrer"><code>UnsatisfiedDependencyException</code></a>)</p>
<pre class="lang-none prettyprint-override"><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.example.Bar] found for dependency [com.example.Bar]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>
<p>There are multiple ways to register bean definitions.</p>
<ul>
<li><code>@Bean</code> method in a <code>@Configuration</code> class or <code><bean></code> in XML configuration</li>
<li><code>@Component</code> (and its meta-annotations, eg. <code>@Repository</code>) through <code>@ComponentScan</code> or <code><context:component-scan ... /></code> in XML</li>
<li>Manually through <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/support/GenericApplicationContext.html#registerBeanDefinition-java.lang.String-org.springframework.beans.factory.config.BeanDefinition-" rel="noreferrer"><code>GenericApplicationContext#registerBeanDefinition</code></a></li>
<li>Manually through <code>BeanDefinitionRegistryPostProcessor</code></li>
</ul>
<p>...and more.</p>
<p>Make sure the beans you expect are properly registered.</p>
<p><strong>A common error</strong> is to register beans multiple times, ie. mixing the options above for the same type. For example, I might have</p>
<pre><code>@Component
public class Foo {}
</code></pre>
<p>and an XML configuration with</p>
<pre><code><context:component-scan base-packages="com.example" />
<bean name="eg-different-name" class="com.example.Foo />
</code></pre>
<p>Such a configuration would register two beans of type <code>Foo</code>, one with name <code>foo</code> and another with name <code>eg-different-name</code>. Make sure you're not accidentally registering more beans than you wanted. Which leads us to...</p>
<p>If you're using both XML and annotation-based configurations, make sure you import one from the other. XML provides</p>
<pre><code><import resource=""/>
</code></pre>
<p>while Java provides the <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ImportResource.html" rel="noreferrer"><code>@ImportResource</code></a> annotation.</p>
<h1>Expected single matching bean, but found 2 (or more)</h1>
<p>There are times when you need multiple beans for the same type (or interface). For example, your application may use two databases, a MySQL instance and an Oracle one. In such a case, you'd have two <code>DataSource</code> beans to manage connections to each one. For (simplified) example, the following</p>
<pre><code>@Configuration
public class Example {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Example.class);
System.out.println(ctx.getBean(DataSource.class));
}
@Bean(name = "mysql")
public DataSource mysql() { return new MySQL(); }
@Bean(name = "oracle")
public DataSource oracle() { return new Oracle(); }
}
interface DataSource{}
class MySQL implements DataSource {}
class Oracle implements DataSource {}
</code></pre>
<p>throws</p>
<pre class="lang-none prettyprint-override"><code>Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type [com.example.DataSource] is defined:
expected single matching bean but found 2: oracle,mysql
</code></pre>
<p>because both beans registered through <code>@Bean</code> methods satisfied the requirement of <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.Class-" rel="noreferrer"><code>BeanFactory#getBean(Class)</code></a>, ie. they both implement <code>DataSource</code>. In this example, Spring has no mechanism to differentiate or prioritize between the two. But such mechanisms exists.</p>
<p>You could use <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html" rel="noreferrer"><code>@Primary</code></a> (and its equivalent in XML) as described in the <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-primary" rel="noreferrer">documentation</a> and in <a href="https://stackoverflow.com/questions/10534053/autowiring-two-beans-implementing-same-interface-how-to-set-default-bean-to-au">this post</a>. With this change</p>
<pre><code>@Bean(name = "mysql")
@Primary
public DataSource mysql() { return new MySQL(); }
</code></pre>
<p>the previous snippet would not throw the exception and would instead return the <code>mysql</code> bean.</p>
<p>You can also use <code>@Qualifier</code> (and its equivalent in XML) to have more control over the bean selection process, as described in the <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers" rel="noreferrer">documentation</a>. While <code>@Autowired</code> is primarily used to autowire by type, <code>@Qualifier</code> lets you autowire by name. For example,</p>
<pre><code>@Bean(name = "mysql")
@Qualifier(value = "main")
public DataSource mysql() { return new MySQL(); }
</code></pre>
<p>could now be injected as</p>
<pre><code>@Qualifier("main") // or @Qualifier("mysql"), to use the bean name
private DataSource dataSource;
</code></pre>
<p>without issue. <a href="https://docs.oracle.com/javase/7/docs/api/javax/annotation/Resource.html" rel="noreferrer"><code>@Resource</code></a> is also an option.</p>
<h1>Using wrong bean name</h1>
<p>Just as there are multiple ways to register beans, there are also multiple ways to name them.</p>
<p><a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html" rel="noreferrer"><code>@Bean</code></a> has <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html#name--" rel="noreferrer"><code>name</code></a></p>
<blockquote>
<p>The name of this bean, or if plural, aliases for this bean. If left
unspecified the name of the bean is the name of the annotated method.
If specified, the method name is ignored.</p>
</blockquote>
<p><code><bean></code> has the <code>id</code> attribute to represent <em>the unique identifier for a bean</em> and <code>name</code> <em>can be used to create one or more aliases illegal in an (XML) id.</em></p>
<p><a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html" rel="noreferrer"><code>@Component</code></a> and its meta annotations have <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html#value--" rel="noreferrer"><code>value</code></a></p>
<blockquote>
<p>The value may indicate a suggestion for a logical component name, to
be turned into a Spring bean in case of an autodetected component.</p>
</blockquote>
<p>If that's left unspecified, a bean name is automatically generated for the annotated type, typically the lower camel case version of the type name. For example <code>MyClassName</code> becomes <code>myClassName</code> as its bean name. Bean names are case sensitive. Also note that wrong names/capitalization typically occur in beans referred to by string like <code>@DependsOn("my BeanName")</code> or XML config files.</p>
<p><code>@Qualifier</code>, as mentioned earlier, lets you add more aliases to a bean.</p>
<p><strong>Make sure you use the right name when referring to a bean.</strong></p>
<hr />
<h1>More advanced cases</h1>
<h2>Profiles</h2>
<p><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-definition-profiles" rel="noreferrer">Bean definition profiles</a> allow you to register beans conditionally. <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html" rel="noreferrer"><code>@Profile</code></a>, specifically,</p>
<blockquote>
<p>Indicates that a component is eligible for registration when one or
more specified profiles are active.</p>
<p>A profile is a named logical grouping that may be activated
programmatically via
<a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/ConfigurableEnvironment.html#setActiveProfiles-java.lang.String...-" rel="noreferrer"><code>ConfigurableEnvironment.setActiveProfiles(java.lang.String...)</code></a> or
declaratively by setting the <code>spring.profiles.active</code> property as a JVM
system property, as an environment variable, or as a Servlet context
parameter in web.xml for web applications. Profiles may also be
activated declaratively in integration tests via the <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/ActiveProfiles.html" rel="noreferrer"><code>@ActiveProfiles</code></a>
annotation.</p>
</blockquote>
<p>Consider this examples where the <code>spring.profiles.active</code> property is not set.</p>
<pre><code>@Configuration
@ComponentScan
public class Example {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Example.class);
System.out.println(Arrays.toString(ctx.getEnvironment().getActiveProfiles()));
System.out.println(ctx.getBean(Foo.class));
}
}
@Profile(value = "StackOverflow")
@Component
class Foo {
}
</code></pre>
<p>This will show no active profiles and throw a <code>NoSuchBeanDefinitionException</code> for a <code>Foo</code> bean. Since the <code>StackOverflow</code> profile wasn't active, the bean wasn't registered.</p>
<p>Instead, if I initialize the <code>ApplicationContext</code> while registering the appropriate profile</p>
<pre><code>AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("StackOverflow");
ctx.register(Example.class);
ctx.refresh();
</code></pre>
<p>the bean is registered and can be returned/injected.</p>
<h2>AOP Proxies</h2>
<p>Spring uses <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-introduction-proxies" rel="noreferrer">AOP proxies</a> a lot to implement advanced behavior. Some examples include:</p>
<ul>
<li><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html" rel="noreferrer">Transaction management</a> with <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html" rel="noreferrer"><code>@Transactional</code></a></li>
<li><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-annotations" rel="noreferrer">Caching</a> with <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html" rel="noreferrer"><code>@Cacheable</code></a></li>
<li><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support" rel="noreferrer">Scheduling and asynchronous execution</a> with <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Async.html" rel="noreferrer"><code>@Async</code></a> and <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html" rel="noreferrer"><code>@Scheduled</code></a></li>
</ul>
<p>To achieve this, Spring has two options:</p>
<ol>
<li>Use the JDK's <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html" rel="noreferrer">Proxy</a> class to create an instance of a dynamic class at runtime which <strong>only implements your bean's interfaces</strong> and delegates all method invocations to an actual bean instance.</li>
<li>Use <a href="https://github.com/cglib/cglib/wiki" rel="noreferrer">CGLIB</a> proxies to create an instance of a dynamic class at runtime which implements both interfaces and concrete types of your target bean and delegates all method invocations to an actual bean instance.</li>
</ol>
<p>Take this example of JDK proxies (achieved through <code>@EnableAsync</code>'s default <code>proxyTargetClass</code> of <code>false</code>)</p>
<pre><code>@Configuration
@EnableAsync
public class Example {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Example.class);
System.out.println(ctx.getBean(HttpClientImpl.class).getClass());
}
}
interface HttpClient {
void doGetAsync();
}
@Component
class HttpClientImpl implements HttpClient {
@Async
public void doGetAsync() {
System.out.println(Thread.currentThread());
}
}
</code></pre>
<p>Here, Spring attempts to find a bean of type <code>HttpClientImpl</code> which we expect to find because the type is clearly annotated with <code>@Component</code>. However, instead, we get an exception</p>
<pre class="lang-none prettyprint-override"><code>Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.example.HttpClientImpl] is defined
</code></pre>
<p>Spring wrapped the <code>HttpClientImpl</code> bean and exposed it through a <code>Proxy</code> object that only implements <code>HttpClient</code>. So you could retrieve it with</p>
<pre><code>ctx.getBean(HttpClient.class) // returns a dynamic class: com.example.$Proxy33
// or
@Autowired private HttpClient httpClient;
</code></pre>
<p>It's always recommended to <a href="https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface">program to interfaces</a>. When you can't, you can tell Spring to use CGLIB proxies. For example, with <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html" rel="noreferrer"><code>@EnableAsync</code></a>, you can set <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html#proxyTargetClass--" rel="noreferrer"><code>proxyTargetClass</code></a> to <code>true</code>. Similar annotations (<code>EnableTransactionManagement</code>, etc.) have similar attributes. XML will also have equivalent configuration options.</p>
<h2><code>ApplicationContext</code> Hierarchies - Spring MVC</h2>
<p>Spring lets you build <code>ApplicationContext</code> instances with other <code>ApplicationContext</code> instances as parents, using <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ConfigurableApplicationContext.html#setParent-org.springframework.context.ApplicationContext-" rel="noreferrer"><code>ConfigurableApplicationContext#setParent(ApplicationContext)</code></a>. A child context will have access to beans in the parent context, but the opposite is not true. <a href="https://stackoverflow.com/questions/5132604/why-use-spring-applicationcontext-hierarchies">This post</a> goes into detail about when this is useful, particularly in Spring MVC.</p>
<p>In a typical Spring MVC application, you define two contexts: one for the entire application (the root) and one specifically for the <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html" rel="noreferrer"><code>DispatcherServlet</code></a> (routing, handler methods, controllers). You can get more details here:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/3652090/difference-between-applicationcontext-xml-and-spring-servlet-xml-in-spring-frame">Difference between applicationContext.xml and spring-servlet.xml in Spring Framework</a></li>
</ul>
<p>It's also very well explained in the official documentation, <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-servlet" rel="noreferrer">here</a>.</p>
<p><strong>A common error</strong> in Spring MVC configurations is to declare the WebMVC configuration in the root context with <code>@EnableWebMvc</code> annotated <code>@Configuration</code> classes or <code><mvc:annotation-driven /></code> in XML, but the <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/Controller.html" rel="noreferrer"><code>@Controller</code></a> beans in the servlet context. <strong>Since the root context cannot reach into the servlet context to find any beans, no handlers are registered and all requests fail with 404s.</strong> You won't see a <code>NoSuchBeanDefinitionException</code>, but the effect is the same.</p>
<p>Make sure your beans are registered in the appropriate context, ie. where they can be found by the beans registered for WebMVC (<code>HandlerMapping</code>, <code>HandlerAdapter</code>, <code>ViewResolver</code>, <code>ExceptionResolver</code>, etc.). The best solution is to properly isolate beans. The <code>DispatcherServlet</code> is responsible for routing and handling requests so all related beans should go into its context. The <code>ContextLoaderListener</code>, which loads the root context, should initialize any beans the rest of your application needs: services, repositories, etc.</p>
<h1>Arrays, collections, and maps</h1>
<p>Beans of some known types are handled in special ways by Spring. For example, if you tried to inject an array of <code>MovieCatalog</code> into a field</p>
<pre><code>@Autowired
private MovieCatalog[] movieCatalogs;
</code></pre>
<p>Spring will find all beans of type <code>MovieCatalog</code>, wrap them in an array, and inject that array. This is described in the <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation" rel="noreferrer">Spring documentation discussing <code>@Autowired</code></a>. Similar behavior applies to <code>Set</code>, <code>List</code>, and <code>Collection</code> injection targets.</p>
<p>For a <code>Map</code> injection target, Spring will also behave this way if the key type is <code>String</code>. For example, if you have</p>
<pre><code>@Autowired
private Map<String, MovieCatalog> movies;
</code></pre>
<p>Spring will find all beans of type <code>MovieCatalog</code> and add them as values to a <code>Map</code>, where the corresponding key will be their bean name.</p>
<p>As described previously, if no beans of the requested type are available, Spring will throw a <code>NoSuchBeanDefinitionException</code>. Sometimes, however, you just want to declare a bean of these collection types like</p>
<pre><code>@Bean
public List<Foo> fooList() {
return Arrays.asList(new Foo());
}
</code></pre>
<p>and inject them</p>
<pre><code>@Autowired
private List<Foo> foos;
</code></pre>
<p>In this example, Spring would fail with a <code>NoSuchBeanDefinitionException</code> because there are no <code>Foo</code> beans in your context. But you didn't want a <code>Foo</code> bean, you wanted a <code>List<Foo></code> bean. <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers" rel="noreferrer">Before Spring 4.3, you'd have to use <code>@Resource</code></a></p>
<blockquote>
<p>For beans that are themselves defined as a collection/map or array
type, <code>@Resource</code> is a fine solution, referring to the specific
collection or array bean by unique name. That said, <strong>as of 4.3</strong>,
collection/map and array types can be matched through Spring’s
<code>@Autowired</code> type matching algorithm as well, as long as the element
type information is preserved in <code>@Bean</code> return type signatures or
collection inheritance hierarchies. In this case, qualifier values can
be used to select among same-typed collections, as outlined in the
previous paragraph.</p>
</blockquote>
<p>This works for constructor, setter, and field injection.</p>
<pre><code>@Resource
private List<Foo> foos;
// or since 4.3
public Example(@Autowired List<Foo> foos) {}
</code></pre>
<p>However, it will fail for <code>@Bean</code> methods, ie.</p>
<pre><code>@Bean
public Bar other(List<Foo> foos) {
new Bar(foos);
}
</code></pre>
<p>Here, Spring ignores any <code>@Resource</code> or <code>@Autowired</code> annotating the method, because it's a <code>@Bean</code> method, and therefore can't apply the behavior described in the documentation. However, you can use Spring Expression Language (SpEL) to refer to beans by their name. In the example above, you could use</p>
<pre><code>@Bean
public Bar other(@Value("#{fooList}") List<Foo> foos) {
new Bar(foos);
}
</code></pre>
<p>to refer to the bean named <code>fooList</code> and inject that.</p> |
39,346,231 | Resume NSUrlSession on iOS10 | <p>iOS 10 is going to be released soon so it worth to test applications for compatibility with it. During such test we've discovered that our app can't resume background downloads on iOS10. Code that worked well on previous versions does not work on new one, both on an emulator and on a device.</p>
<p>Instead of reducing our code to minimal working test case I've searched internet for NSUrlSession tutorials and tested them. Behaviour is the same: resuming works on previos versions of iOS but breaks on 10th.</p>
<h2>Steps to Reproduce:</h2>
<ol>
<li>Download a project form NSUrlSession tutorial
<a href="https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started" rel="noreferrer">https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started</a></li>
<li>Direct link:
<a href="http://www.raywenderlich.com/wp-content/uploads/2016/01/HalfTunes-Final.zip" rel="noreferrer">http://www.raywenderlich.com/wp-content/uploads/2016/01/HalfTunes-Final.zip</a></li>
<li>Build it and launch under iOS 10. Search something, for example
"swift". Start a download and then hit a "Pause" and then "Resume"</li>
</ol>
<h2>Expected Results:</h2>
<p>Download is resumed. You can check how it works with versions prior to iOS10.</p>
<h2>Actual Results:</h2>
<p>Download fails. In xcode console you can see:</p>
<pre><code>2016-09-02 16:11:24.913 HalfTunes[35205:2279228] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2016-09-02 16:11:24.913 HalfTunes[35205:2279228] *** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
2016-09-02 16:11:24.913 HalfTunes[35205:2279228] Invalid resume data for background download. Background downloads must use http or https and must download to an accessible file.
</code></pre>
<h2>More scenarios:</h2>
<p>If you activate offline mode while a file is beeng downloaded you get</p>
<pre><code>Url session completed with error: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL} {
NSLocalizedDescription = "unsupported URL";
}
</code></pre>
<p>when network is shut down and download never recovers when network is up again. Other use cases with pause, such as reboot, do not work either.</p>
<h2>Additional investigation:</h2>
<p>I've tried to check if returned resumeData is valid using code suggested in</p>
<p><a href="https://stackoverflow.com/questions/21895853/how-can-i-check-that-an-nsdata-blob-is-valid-as-resumedata-for-an-nsurlsessiondo">How can I check that an NSData blob is valid as resumeData for an NSURLSessionDownloadTask?</a></p>
<p>but the target file is in place. Though resumeData format has changed and now file name is stored in NSURLSessionResumeInfoTempFileName and you have to append NSTemporaryDirectory() to it.</p>
<p>Beside that I've filled a bug report to apple, but they haven't replied yet.</p>
<h2>The question (of Life, the Universe, and Everything):</h2>
<p>Is resuming of NSUrlSession broken in all other apps? Can it be fixed on application side?</p> | 39,347,461 | 3 | 0 | null | 2016-09-06 10:04:49.057 UTC | 39 | 2017-03-16 18:41:34.793 UTC | 2017-05-23 12:10:42.083 UTC | null | -1 | null | 6,799,654 | null | 1 | 35 | ios|nsurlsession|ios10|nsurlsessiondownloadtask | 14,100 | <p>This problem arose from currentRequest and originalRequest NSKeyArchived encoded with an unusual root of "NSKeyedArchiveRootObjectKey" instead of NSKeyedArchiveRootObjectKey constant which is "root" literally and some other misbehaves in encoding process of NSURL(Mutable)Request.</p>
<p>I detected that in beta 1 and filed a bug (no. 27144153 in case you want duplicate). Even I sent an email to "Quinn the Eskimo" (eskimo1 at apple dot com) whom is support guy of NSURLSession team, to confirm they received it and he said they got that and are aware of issue.</p>
<p><strong>UPDATE:</strong> I finally figured out how to resolve this issue. Give data to correctResumeData() function and it will return usable resume data</p>
<p><strong>UPDATE 2:</strong> You can use NSURLSession.correctedDownloadTaskWithResumeData() / URLSession.correctedDownloadTask(withResumeData:) function to get a task with a correct originalRequest and currentRequest variables</p>
<p><strong>UPDATE 3:</strong> Quinn says This issue is resolved in iOS 10.2, you can keep using this code to have compatibility with iOS 10.0 and 10.1 and it will work with new version without any issue.</p>
<p>(For Swift 3 code, scroll below, for Objective C see <a href="https://stackoverflow.com/a/40501353/5304286">leavesstar post</a> but I didn't tested it)</p>
<p><strong>Swift 2.3:</strong></p>
<pre><code>func correctRequestData(data: NSData?) -> NSData? {
guard let data = data else {
return nil
}
// return the same data if it's correct
if NSKeyedUnarchiver.unarchiveObjectWithData(data) != nil {
return data
}
guard let archive = (try? NSPropertyListSerialization.propertyListWithData(data, options: [.MutableContainersAndLeaves], format: nil)) as? NSMutableDictionary else {
return nil
}
// Rectify weird __nsurlrequest_proto_props objects to $number pattern
var k = 0
while archive["$objects"]?[1].objectForKey("$\(k)") != nil {
k += 1
}
var i = 0
while archive["$objects"]?[1].objectForKey("__nsurlrequest_proto_prop_obj_\(i)") != nil {
let arr = archive["$objects"] as? NSMutableArray
if let dic = arr?[1] as? NSMutableDictionary, let obj = dic["__nsurlrequest_proto_prop_obj_\(i)"] {
dic.setObject(obj, forKey: "$\(i + k)")
dic.removeObjectForKey("__nsurlrequest_proto_prop_obj_\(i)")
arr?[1] = dic
archive["$objects"] = arr
}
i += 1
}
if archive["$objects"]?[1].objectForKey("__nsurlrequest_proto_props") != nil {
let arr = archive["$objects"] as? NSMutableArray
if let dic = arr?[1] as? NSMutableDictionary, let obj = dic["__nsurlrequest_proto_props"] {
dic.setObject(obj, forKey: "$\(i + k)")
dic.removeObjectForKey("__nsurlrequest_proto_props")
arr?[1] = dic
archive["$objects"] = arr
}
}
// Rectify weird "NSKeyedArchiveRootObjectKey" top key to NSKeyedArchiveRootObjectKey = "root"
if archive["$top"]?.objectForKey("NSKeyedArchiveRootObjectKey") != nil {
archive["$top"]?.setObject(archive["$top"]?["NSKeyedArchiveRootObjectKey"], forKey: NSKeyedArchiveRootObjectKey)
archive["$top"]?.removeObjectForKey("NSKeyedArchiveRootObjectKey")
}
// Reencode archived object
let result = try? NSPropertyListSerialization.dataWithPropertyList(archive, format: NSPropertyListFormat.BinaryFormat_v1_0, options: NSPropertyListWriteOptions())
return result
}
func getResumeDictionary(data: NSData) -> NSMutableDictionary? {
var iresumeDictionary: NSMutableDictionary? = nil
// In beta versions, resumeData is NSKeyedArchive encoded instead of plist
if #available(iOS 10.0, OSX 10.12, *) {
var root : AnyObject? = nil
let keyedUnarchiver = NSKeyedUnarchiver(forReadingWithData: data)
do {
root = try keyedUnarchiver.decodeTopLevelObjectForKey("NSKeyedArchiveRootObjectKey") ?? nil
if root == nil {
root = try keyedUnarchiver.decodeTopLevelObjectForKey(NSKeyedArchiveRootObjectKey)
}
} catch {}
keyedUnarchiver.finishDecoding()
iresumeDictionary = root as? NSMutableDictionary
}
if iresumeDictionary == nil {
do {
iresumeDictionary = try NSPropertyListSerialization.propertyListWithData(data, options: [.MutableContainersAndLeaves], format: nil) as? NSMutableDictionary;
} catch {}
}
return iresumeDictionary
}
func correctResumeData(data: NSData?) -> NSData? {
let kResumeCurrentRequest = "NSURLSessionResumeCurrentRequest"
let kResumeOriginalRequest = "NSURLSessionResumeOriginalRequest"
guard let data = data, let resumeDictionary = getResumeDictionary(data) else {
return nil
}
resumeDictionary[kResumeCurrentRequest] = correctRequestData(resumeDictionary[kResumeCurrentRequest] as? NSData)
resumeDictionary[kResumeOriginalRequest] = correctRequestData(resumeDictionary[kResumeOriginalRequest] as? NSData)
let result = try? NSPropertyListSerialization.dataWithPropertyList(resumeDictionary, format: NSPropertyListFormat.XMLFormat_v1_0, options: NSPropertyListWriteOptions())
return result
}
extension NSURLSession {
func correctedDownloadTaskWithResumeData(resumeData: NSData) -> NSURLSessionDownloadTask {
let kResumeCurrentRequest = "NSURLSessionResumeCurrentRequest"
let kResumeOriginalRequest = "NSURLSessionResumeOriginalRequest"
let cData = correctResumeData(resumeData) ?? resumeData
let task = self.downloadTaskWithResumeData(cData)
// a compensation for inability to set task requests in CFNetwork.
// While you still get -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL error,
// this section will set them to real objects
if let resumeDic = getResumeDictionary(cData) {
if task.originalRequest == nil, let originalReqData = resumeDic[kResumeOriginalRequest] as? NSData, let originalRequest = NSKeyedUnarchiver.unarchiveObjectWithData(originalReqData) as? NSURLRequest {
task.setValue(originalRequest, forKey: "originalRequest")
}
if task.currentRequest == nil, let currentReqData = resumeDic[kResumeCurrentRequest] as? NSData, let currentRequest = NSKeyedUnarchiver.unarchiveObjectWithData(currentReqData) as? NSURLRequest {
task.setValue(currentRequest, forKey: "currentRequest")
}
}
return task
}
}
</code></pre>
<p><strong>Swift 3:</strong></p>
<pre><code>func correct(requestData data: Data?) -> Data? {
guard let data = data else {
return nil
}
if NSKeyedUnarchiver.unarchiveObject(with: data) != nil {
return data
}
guard let archive = (try? PropertyListSerialization.propertyList(from: data, options: [.mutableContainersAndLeaves], format: nil)) as? NSMutableDictionary else {
return nil
}
// Rectify weird __nsurlrequest_proto_props objects to $number pattern
var k = 0
while ((archive["$objects"] as? NSArray)?[1] as? NSDictionary)?.object(forKey: "$\(k)") != nil {
k += 1
}
var i = 0
while ((archive["$objects"] as? NSArray)?[1] as? NSDictionary)?.object(forKey: "__nsurlrequest_proto_prop_obj_\(i)") != nil {
let arr = archive["$objects"] as? NSMutableArray
if let dic = arr?[1] as? NSMutableDictionary, let obj = dic["__nsurlrequest_proto_prop_obj_\(i)"] {
dic.setObject(obj, forKey: "$\(i + k)" as NSString)
dic.removeObject(forKey: "__nsurlrequest_proto_prop_obj_\(i)")
arr?[1] = dic
archive["$objects"] = arr
}
i += 1
}
if ((archive["$objects"] as? NSArray)?[1] as? NSDictionary)?.object(forKey: "__nsurlrequest_proto_props") != nil {
let arr = archive["$objects"] as? NSMutableArray
if let dic = arr?[1] as? NSMutableDictionary, let obj = dic["__nsurlrequest_proto_props"] {
dic.setObject(obj, forKey: "$\(i + k)" as NSString)
dic.removeObject(forKey: "__nsurlrequest_proto_props")
arr?[1] = dic
archive["$objects"] = arr
}
}
/* I think we have no reason to keep this section in effect
for item in (archive["$objects"] as? NSMutableArray) ?? [] {
if let cls = item as? NSMutableDictionary, cls["$classname"] as? NSString == "NSURLRequest" {
cls["$classname"] = NSString(string: "NSMutableURLRequest")
(cls["$classes"] as? NSMutableArray)?.insert(NSString(string: "NSMutableURLRequest"), at: 0)
}
}*/
// Rectify weird "NSKeyedArchiveRootObjectKey" top key to NSKeyedArchiveRootObjectKey = "root"
if let obj = (archive["$top"] as? NSMutableDictionary)?.object(forKey: "NSKeyedArchiveRootObjectKey") as AnyObject? {
(archive["$top"] as? NSMutableDictionary)?.setObject(obj, forKey: NSKeyedArchiveRootObjectKey as NSString)
(archive["$top"] as? NSMutableDictionary)?.removeObject(forKey: "NSKeyedArchiveRootObjectKey")
}
// Reencode archived object
let result = try? PropertyListSerialization.data(fromPropertyList: archive, format: PropertyListSerialization.PropertyListFormat.binary, options: PropertyListSerialization.WriteOptions())
return result
}
func getResumeDictionary(_ data: Data) -> NSMutableDictionary? {
// In beta versions, resumeData is NSKeyedArchive encoded instead of plist
var iresumeDictionary: NSMutableDictionary? = nil
if #available(iOS 10.0, OSX 10.12, *) {
var root : AnyObject? = nil
let keyedUnarchiver = NSKeyedUnarchiver(forReadingWith: data)
do {
root = try keyedUnarchiver.decodeTopLevelObject(forKey: "NSKeyedArchiveRootObjectKey") ?? nil
if root == nil {
root = try keyedUnarchiver.decodeTopLevelObject(forKey: NSKeyedArchiveRootObjectKey)
}
} catch {}
keyedUnarchiver.finishDecoding()
iresumeDictionary = root as? NSMutableDictionary
}
if iresumeDictionary == nil {
do {
iresumeDictionary = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions(), format: nil) as? NSMutableDictionary;
} catch {}
}
return iresumeDictionary
}
func correctResumeData(_ data: Data?) -> Data? {
let kResumeCurrentRequest = "NSURLSessionResumeCurrentRequest"
let kResumeOriginalRequest = "NSURLSessionResumeOriginalRequest"
guard let data = data, let resumeDictionary = getResumeDictionary(data) else {
return nil
}
resumeDictionary[kResumeCurrentRequest] = correct(requestData: resumeDictionary[kResumeCurrentRequest] as? Data)
resumeDictionary[kResumeOriginalRequest] = correct(requestData: resumeDictionary[kResumeOriginalRequest] as? Data)
let result = try? PropertyListSerialization.data(fromPropertyList: resumeDictionary, format: PropertyListSerialization.PropertyListFormat.xml, options: PropertyListSerialization.WriteOptions())
return result
}
extension URLSession {
func correctedDownloadTask(withResumeData resumeData: Data) -> URLSessionDownloadTask {
let kResumeCurrentRequest = "NSURLSessionResumeCurrentRequest"
let kResumeOriginalRequest = "NSURLSessionResumeOriginalRequest"
let cData = correctResumeData(resumeData) ?? resumeData
let task = self.downloadTask(withResumeData: cData)
// a compensation for inability to set task requests in CFNetwork.
// While you still get -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL error,
// this section will set them to real objects
if let resumeDic = getResumeDictionary(cData) {
if task.originalRequest == nil, let originalReqData = resumeDic[kResumeOriginalRequest] as? Data, let originalRequest = NSKeyedUnarchiver.unarchiveObject(with: originalReqData) as? NSURLRequest {
task.setValue(originalRequest, forKey: "originalRequest")
}
if task.currentRequest == nil, let currentReqData = resumeDic[kResumeCurrentRequest] as? Data, let currentRequest = NSKeyedUnarchiver.unarchiveObject(with: currentReqData) as? NSURLRequest {
task.setValue(currentRequest, forKey: "currentRequest")
}
}
return task
}
}
</code></pre> |
34,044,888 | Select multiple nested levels of child tables in Entity Framework Core | <p>I want to get multiple nested levels of child tables in Entity Framework Core using eager loading. I don't think lazy loading is implemented yet.</p>
<p>I found an <a href="https://stackoverflow.com/questions/3356541/entity-framework-linq-query-include-multiple-children-entities">answer</a> for EF6.</p>
<pre><code>var company = context.Companies
.Include(co => co.Employees.Select(emp => emp.Employee_Car))
.Include(co => co.Employees.Select(emp => emp.Employee_Country))
.FirstOrDefault(co => co.companyID == companyID);
</code></pre>
<p>My problem is that <code>Select</code> is not recognized in EF Core</p>
<blockquote>
<p>Error CS1061 'Employees' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'Employees' could be found (are you missing a using directive or an assembly reference?) </p>
</blockquote>
<p>My included namespaces:</p>
<pre><code>using MyProject.Models;
using Microsoft.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
</code></pre>
<p>What is the alternative for <code>Select</code> in EF Core.</p> | 34,046,250 | 2 | 0 | null | 2015-12-02 14:12:26.353 UTC | 4 | 2019-07-24 19:06:25.97 UTC | 2018-02-15 10:45:36.737 UTC | null | 2,349,045 | null | 5,537,070 | null | 1 | 55 | entity-framework-core | 26,893 | <p>You can use the keyword <code>ThenInclude</code> instead</p>
<p>e.g.</p>
<pre><code>var company = context.Companies
.Include(co => co.Employees).ThenInclude(emp => emp.Employee_Car)
.Include(co => co.Employees).ThenInclude(emp => emp.Employee_Country)
.FirstOrDefault(co => co.companyID == companyID);
</code></pre> |
38,576,040 | How to name aggregate columns? | <p>I'm using Spark in Scala and my aggregated columns are anonymous. Is there a convenient way to rename multiple columns from a dataset? I thought about imposing a schema with <code>as</code> but the key column is a struct (due to the <code>groupBy</code> operation), and I can't find out how to define a <code>case class</code> with a <code>StructType</code> in it.</p>
<p>I tried defining a schema as follows:</p>
<pre><code>val returnSchema = StructType(StructField("edge", StructType(StructField("src", IntegerType, true),
StructField("dst", IntegerType), true)),
StructField("count", LongType, true))
edge_count.as[returnSchema]
</code></pre>
<p>but I got a compile error:</p>
<pre><code>Message: <console>:74: error: overloaded method value apply with alternatives:
(fields: Array[org.apache.spark.sql.types.StructField])org.apache.spark.sql.types.StructType <and>
(fields: java.util.List[org.apache.spark.sql.types.StructField])org.apache.spark.sql.types.StructType <and>
(fields: Seq[org.apache.spark.sql.types.StructField])org.apache.spark.sql.types.StructType
cannot be applied to (org.apache.spark.sql.types.StructField, org.apache.spark.sql.types.StructField, Boolean)
val returnSchema = StructType(StructField("edge", StructType(StructField("src", IntegerType, true),
</code></pre> | 38,620,860 | 3 | 2 | null | 2016-07-25 19:35:55.303 UTC | 9 | 2021-10-19 19:44:54.717 UTC | 2016-07-27 18:04:32.687 UTC | null | 832,188 | null | 832,188 | null | 1 | 18 | scala|apache-spark|apache-spark-dataset | 19,429 | <p>I ended up using <code>alias</code>es with the <code>select</code> statement; e.g.,</p>
<pre><code>ds.select($"key.src".as[Short],
$"key.dst".as[Short],
$"sum(count)".alias("count").as[Long])
</code></pre>
<p>First I had to use <code>printSchema</code> to determine the derived column names:</p>
<pre><code>> ds.printSchema
root
|-- key: struct (nullable = false)
| |-- src: short (nullable = false)
| |-- dst: short (nullable = false)
|-- sum(count): long (nullable = true)
</code></pre> |
32,296,272 | Telegram BOT Api: how to send a photo using PHP? | <p>The <a href="https://core.telegram.org/bots/api#sendphoto" rel="noreferrer">sendPhoto</a> command require an argument <code>photo</code> defined as <code>InputFile or String</code>.</p>
<p>The API doc tells: </p>
<pre><code>Photo to send. You can either pass a file_id as String to resend a photo
that is already on the Telegram servers, or upload a new photo using
multipart/form-data.
</code></pre>
<p>And </p>
<pre><code>InputFile
This object represents the contents of a file to be uploaded. Must be
posted using multipart/form-data in the usual way that files are
uploaded via the browser.
</code></pre>
<p>So I tried this method</p>
<pre><code> $bot_url = "https://api.telegram.org/bot<bot_id>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"photo" => "@/path/to/image.png",
));
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/root/dev/fe_new.png"));
$output = curl_exec($ch);
</code></pre>
<p>The curls is executed, but Telegram reply this to me: </p>
<pre><code>Error: Bad Request: Wrong persistent file_id specified: contains wrong
characters or have wrong length
</code></pre>
<p>I also tried replacing <code>@/path...</code> with a <code>file_get_contents</code>, but in this case Telegram give me an empty reply (and <code>curl_error</code> is empty !).</p>
<p><strong>What the way to send a photo to telegram using php + curl ?</strong></p> | 32,296,353 | 7 | 0 | null | 2015-08-30 11:53:46.073 UTC | 12 | 2021-08-16 23:37:13.32 UTC | null | null | null | null | 1,055,279 | null | 1 | 10 | php|curl|telegram|telegram-bot | 59,409 | <p>This is my working solution, but it requires PHP 5.5:</p>
<pre><code>$bot_url = "https://api.telegram.org/bot<bot_id>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id ;
$post_fields = array('chat_id' => $chat_id,
'photo' => new CURLFile(realpath("/path/to/image.png"))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
</code></pre> |
38,028,388 | Cannot read property 'errors' of undefined in angular 2 | <p>I am validating my template using angular2, but meanwhile it shows this error:</p>
<pre><code> Cannot read the property 'errors' of undefined.
</code></pre>
<p>Here is my template:</p>
<pre><code><h3 class = "head">{{title}}</h3>
<form [ngFormModel]="form" #f="ngForm">
<div class="row">
<div class="form-group">
<label class="formHeading">Facebook</label>
<input type="text" id="facebook" class="form-control col-xs-3" ngControl="facebook" #facebook="ngForm" >
</div>
<div *ngIf ="facebook.touched && facebok.errors">
<div class="form-row btn">
<button type="submit" class="btn btn-primary pull-right butspace" [disabled]="!f.valid">Save</button>
</div>
</div>
</form>
</code></pre>
<p>I dont know why it shows this error. Can anyone fix it?</p> | 38,028,446 | 1 | 0 | null | 2016-06-25 12:09:57.583 UTC | 0 | 2018-05-18 17:17:04.3 UTC | 2017-07-07 07:21:05.09 UTC | null | 550,094 | null | 6,459,548 | null | 1 | 10 | html|angular | 40,534 | <p>First of all, you have <code>facebok</code> instead of <code>facebook</code> on the error property.</p>
<p>If that doesn't fix it you're probably using the <code>facebook</code> object before it is assigned, which can happen if it's an <code>@Input()</code> for example.</p>
<p>Use the <code>Elvis operator</code>:</p>
<pre><code>*ngIf ="facebook?.touched && facebook?.errors"
</code></pre> |
35,641,019 | How do you use credentials saved by the browser in auto login script | <p>When I manually open a browser, both firefox and chrome, and proceed to a website where I previously saved my login credentials via the browser, the username and password fields automatically populate as they should. However, when I use the python selenium webdriver to open the browser to a specific page, the fields do not populate. </p>
<p>The point of my script is to open the webpage and use <code>element.submit()</code> to login since the login credentials should already be populated., but the are NOT.
How can i get them to populate in the fields?</p>
<p>For Example:</p>
<pre><code>driver = webdriver.Chrome()
driver.get("https://facebook.com")
element = driver.find_element_by_id("u_0_v")
element.submit()
</code></pre> | 35,641,449 | 4 | 0 | null | 2016-02-26 00:18:05.22 UTC | 9 | 2022-08-03 18:38:59.86 UTC | 2022-08-03 18:38:59.86 UTC | null | 2,308,683 | null | 5,983,391 | null | 1 | 11 | python|selenium|webdriver | 25,675 | <p>This is because selenium doesn't use your default browser instance, it opens a different instance with a temporary (empty) profile. </p>
<p>If you would like it to load a default profile you need to instruct it to do so.</p>
<p>Here's a chrome example:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)
</code></pre>
<p>And here's a firefox example:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile
profile = FirefoxProfile("C:\\Path\\to\\profile")
driver = webdriver.Firefox(profile)
</code></pre>
<p>Here we go, just dug up a link to this in the (unofficial) documentation. <a href="http://selenium-python.readthedocs.org/api.html?highlight=profile#module-selenium.webdriver.firefox.webdriver" rel="noreferrer">Firefox Profile</a> and the Chrome driver info is right underneath it.</p> |
18,668,096 | 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll | <p>I'm writing an application to read the first line of a txt file and write to Excel.</p>
<p>The input line is like this, which has 94 characters in total, the last 8 can be blanks or 0's (the x's are actually blanks): <code>101x071000301x6759601771308202341F094101ACHxxxxxxxxxxxxxxxxxxxxFISxACHxMILWAUKEExxxxxxxx</code></p>
<p>When it prints, it correctly displays the x's as blank. Not sure about the last 8 blanks though.</p>
<p>The Console.WriteLine correctly outputs the string (which has blank spaces between characters), but when I try to extract the characters from the string I get this error:</p>
<blockquote>
<p>'System.ArgumentOutOfRangeException' occurred in mscorlib.dll <br>
Additional information: Index and length must refer to a location within the string.</p>
</blockquote>
<pre><code>while ((input = stream.ReadLine()) != null)
{
//ACH HEADER LINE
if (iCurRecLine == 0 && input.IndexOf(HeaderBeginKeyWord) >= 0)
{
Console.WriteLine(input);
RepDate = input.Substring(23, 6).Trim();
RecordTypeCode = input.Substring(0, 1).Trim();
PriorityCode = input.Substring(1, 2).Trim();
ImmDestination = input.Substring(3, 10).Trim();
ImmOrigin = input.Substring(13, 10).Trim();
FileCreatedDate = input.Substring(23, 6).Trim();
FileCreatedTime = input.Substring(29, 4).Trim();
FileIDModifier = input.Substring(33, 1).Trim();
RecordSize = input.Substring(34, 3).Trim();
BlockingFactor = input.Substring(37, 2).Trim();
FormatCode = input.Substring(39, 1).Trim();
Destination = input.Substring(40, 23).Trim();
Origin = input.Substring(63, 23).Trim();
ReferenceCode = input.Substring(86, 8).Trim();
...
}
}
</code></pre>
<p>Where did I go wrong on this?</p> | 18,668,145 | 1 | 3 | null | 2013-09-06 23:36:21.853 UTC | null | 2022-07-20 14:30:55.807 UTC | 2022-07-20 14:23:36.97 UTC | null | 2,756,409 | null | 1,404,321 | null | 1 | 6 | c#|.net|argumentexception|mscorlib | 38,176 | <p>There seems to be no validation in the file content you're reading.</p>
<p><code>.SubString()</code> throws the <code>ArgumentOutOfRangeException</code> if the <a href="http://msdn.microsoft.com/en-us/library/aka44szs.aspx" rel="nofollow noreferrer">"<code>startIndex</code> plus <code>length</code> indicates a position not within this instance."</a></p>
<p>Therefore:</p>
<pre><code> RepDate = input.Substring(23, 6).Trim();
</code></pre>
<p>Could easily fail and throw this exception if the <code>input</code> only contains 10 characters.</p> |
56,086,420 | How to get React Table Row Data Onclick | <p>Hi I am trying to set up my react app such that when you click on a button in a row item in my react-table the data in that row is passed onto another component. At the moment I am simply trying to console.log the correct data but am unsure of how to pass react-table row data based on click. How can I do this?
Thanks</p>
<p>My Dummy data stored in state along with the button (Show Detailed View) which I want to trigger the data passing onclick:</p>
<pre><code> columns: [
{
Header: "First Name",
accessor: "fname"
},
{
Header: "Last Name",
accessor: "lname"
},
{
Header: "Employee Group",
accessor: "egroup"
},
{
Header: "Date of Birth",
accessor: "dob"
},
{
Header: "",
id: "id",
Cell: ({ row }) => (
<button onClick={e => this.handleShow()}>
Detailed View
</button>
)
},
],
posts: [
{
fname: "gerald",
lname: "nakhle",
egroup: "faisbuk",
dob: "8/10/1995"
}
]
</code></pre>
<p>My Call to render the table:</p>
<pre><code><ReactTable columns={this.state.columns} data={this.state.posts}></ReactTable>
</code></pre>
<p>My onclick handler function but im not sure how I can access the table row data I'm after</p>
<pre><code>handleShow(e) {
console.log(e);
}
</code></pre> | 56,087,117 | 4 | 0 | null | 2019-05-11 01:09:29.467 UTC | 3 | 2021-02-12 13:48:44.06 UTC | 2019-05-11 01:43:14.073 UTC | null | 6,716,062 | null | 6,716,062 | null | 1 | 9 | reactjs|onclick|react-props|react-table | 41,498 | <p>You will need to add an onClick handler for the row</p>
<pre class="lang-js prettyprint-override"><code>const onRowClick = (state, rowInfo, column, instance) => {
return {
onClick: e => {
console.log('A Td Element was clicked!')
console.log('it produced this event:', e)
console.log('It was in this column:', column)
console.log('It was in this row:', rowInfo)
console.log('It was in this table instance:', instance)
}
}
}
<ReactTable columns={this.state.columns} data={this.state.posts} getTrProps={onRowClick}></ReactTable>
</code></pre>
<p>check this post for more info <a href="https://stackoverflow.com/questions/43112105/react-table-component-onclick-event-for-a-column">react-table component onClick event for a column</a></p> |
855,841 | Load balance web application | <p>There are load balanced tomcat web servers. Every request could be served by different tomcat server. </p>
<p>How could we take care of this while writing code for the j2ee (struts) based web application? </p> | 855,864 | 1 | 0 | null | 2009-05-13 02:52:21.887 UTC | 15 | 2012-09-04 09:15:27.933 UTC | null | null | null | null | 32,262 | null | 1 | 17 | java|tomcat|load-balancing | 11,752 | <p>First of all, you'll want to set up your load balancer for session affinity/sticky sessions, so that it continues forwarding all requests to the same Tomcat (as long as it is up) based on JSESSIONID.</p>
<p><a href="http://tomcat.apache.org/tomcat-6.0-doc/cluster-howto.html" rel="noreferrer">The Tomcat clustering doc</a> states two important requirements for your application to successfully have it's sessions replicated:</p>
<ul>
<li>All your session attributes must implement <code>java.io.Serializable</code></li>
<li>Make sure your web.xml has the <code><distributable/></code> element or set at your <code><Context distributable="true" /></code></li>
</ul>
<p>If you start putting Objects into Session which don't implement <code>Serializable</code> (or which have properties/fields that don't implement <code>Serializable</code>), then you're going to have problems.</p>
<p>(Actually these points all apply regardless of which servlet container you are using, I believe.)</p>
<p><strong>Update:</strong> To address some of the questions in the comments about why use sticky sessions when you are balancing the load between multiple servers, I think it's easiest to explain this with an example.</p>
<p>First of all, this only really matters if your application keeps some sort of data in-session, which may not be every single application (although it's probably most). If you don't keep data in-session then you probably won't care about any of this and you can just stop reading here.</p>
<p>Having an environment where you keep data in session but you do <em>not</em> have sticky session would open up a world of headaches. </p>
<p>Let's say <code>first.jsp</code> updates some value in a particular session attribute, and <code>second.jsp</code> happens to read this same session attribute. You can set up Tomcat to replicate session data to all servers in the cluster, but this replication does not occur instantly. What if the initial request for <code>first.jsp</code> is handled by <code>server1</code> and one nanosecond after it completes, the same visitor makes a request to <code>second.jsp</code>, which in your non-sticky environment gets handled by <code>server2</code>. Since replication is not instantaneous, do you have any way of knowing if you are reading the most up-to-date session data? Do you have to add some sort of logic to synchronize your reads across the cluster? This would become giant pain.</p>
<p>Setting up session affinity/sticky sessions removes this headache; by having all requests from the same client server by the same node, you don't have to worry about "is this node up to date by the time it handles the request?" When the node fails, the client can still failover to another node in the cluster, which has a copy of it's session data, but with sticky sessions this becomes the rare case and not the norm.</p>
<p>There is another reason to want sticky sessions: load between the nodes in the cluster. If a request in a session could be handled by any node, then that would imply that you have all-to-all replication set up in the cluster (meaning the session data of node1 is replcated to node2, node3, ..., node N, the session data of node2 is replicated to node1, node3, ... none N, etc). All-to-all session replication can become bandwidth and resource intensive when the cluster gets larger, because each addition to the cluster means yet another node that needs to communicate with every other single node in the cluster. </p>
<p>An alternative to this is have a node's data replicated to only a few "buddies" in the cluster, so that in case the node fails it's data is available elsewhere but without every single node having to have a copy. In this scenario, you would configure the cluster so that node1 has it's data replicated to nodes 2 and 3, node 2 has it's data replicated to nodes 3 and 4, etc., forming a chain. In this scenario, adding additional nodes to the cluster does not cause the amount of communication between nodes to increase rapidly as it does in an all-to-all scheme.</p> |
1,248,129 | List all processes and their current memory & CPU consumption? | <p>How can I get a list of all processes in C# and then for each process current memory and CPU consumption?</p>
<p>Sample code is highly appreciated.</p> | 1,248,141 | 1 | 0 | null | 2009-08-08 06:23:08.63 UTC | 11 | 2016-06-29 11:16:06.703 UTC | 2016-06-29 11:16:06.703 UTC | null | 107,625 | null | 114,916 | null | 1 | 19 | c#|.net|memory-management|cpu-usage|performancecounter | 38,926 | <p>The <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process_members.aspx" rel="noreferrer">Process class</a> has a GetProcesses method that will let you enumerate the running processes and list a bunch of stats like memory usage and CPU time. Look at the documentation under properties for the stats.</p>
<p>Memory usage is a complex matter. There is really no single number, that describe the usage. Please see Russinovich's excellent series on the matter. The first installment is here: <a href="http://blogs.technet.com/markrussinovich/archive/2008/07/21/3092070.aspx" rel="noreferrer">http://blogs.technet.com/markrussinovich/archive/2008/07/21/3092070.aspx</a></p> |
59,115,578 | "httptrace" endpoint of Spring Boot Actuator doesn't exist anymore with Spring Boot 2.2.0 | <p>With Spring Boot 2.2.0 the "httptrace" Actuator endpoint doesn't exist anymore. How can I get this functionality back?</p> | 59,115,579 | 2 | 1 | null | 2019-11-30 11:11:45.437 UTC | 7 | 2022-09-06 09:21:29.65 UTC | 2019-11-30 11:17:07.293 UTC | null | 2,891,595 | null | 2,891,595 | null | 1 | 42 | spring-boot|spring-boot-actuator | 16,428 | <p>The functionality has been <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.2.0-M3-Release-Notes#actuator-http-trace-and-auditing-are-disabled-by-default" rel="nofollow noreferrer">removed</a> by default in Spring Boot 2.2.0.</p>
<p>As a workaround, add this configuration to the Spring environment:</p>
<pre><code>management.endpoints.web.exposure.include: httptrace
</code></pre>
<p>and provide an <code>HttpTraceRepository</code> bean like this:</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
// @Profile("actuator-endpoints")
// if you want: register bean only if profile is set
public class HttpTraceActuatorConfiguration {
@Bean
public HttpTraceRepository httpTraceRepository() {
return new InMemoryHttpTraceRepository();
}
}
</code></pre>
<p>http://localhost:8080/actuator/httptrace works again.</p> |
21,365,928 | Gradle : how to use BuildConfig in an android-library with a flag that gets set in an app | <p>My (gradle 1.10 and gradle plugin 0.8)-based android project consists of a big android-library that is a dependency for 3 different android-apps</p>
<p>In my library, I would love to be able to use a structure like this</p>
<pre class="lang-java prettyprint-override"><code>if (BuildConfig.SOME_FLAG) {
callToBigLibraries()
}
</code></pre>
<p>as proguard would be able to reduce the size of the produced apk, based on the final value of SOME_FLAG</p>
<p>But I can't figure how to do it with gradle as : </p>
<pre><code>* the BuildConfig produced by the library doesn't have the same package name than the app
* I have to import the BuildConfig with the library package in the library
* The apk of an apps includes the BuildConfig with the package of the app but not the one with the package of the library.
</code></pre>
<p>I tried without success to play with BuildTypes and stuff like </p>
<pre class="lang-java prettyprint-override"><code>release {
// packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}
debug {
//packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}
</code></pre>
<p>What is the right way to builds a shared BuildConfig for my library and my apps whose flags will be overridden at build in the apps?</p> | 21,419,752 | 7 | 0 | null | 2014-01-26 16:17:12.743 UTC | 17 | 2020-12-14 13:32:43.633 UTC | 2018-08-19 14:16:33.807 UTC | null | 2,249,915 | null | 3,092,224 | null | 1 | 66 | android-gradle-plugin|buildconfig | 50,044 | <p>You can't do what you want, because <code>BuildConfig.SOME_FLAG</code> isn't going to get propagated properly to your library; build types themselves aren't propagated to libraries -- they're always built as RELEASE. This is bug <a href="https://code.google.com/p/android/issues/detail?id=52962">https://code.google.com/p/android/issues/detail?id=52962</a></p>
<p>To work around it: if you have control over all of the library modules, you could make sure that all the code touched by <code>callToBigLibraries()</code> is in classes and packages that you can cleave off cleanly with ProGuard, then use reflection so that you can access them if they exist and degrade gracefully if they don't. You're essentially doing the same thing, but you're making the check at runtime instead of compile time, and it's a little harder.</p>
<p>Let me know if you're having trouble figuring out how to do this; I could provide a sample if you need it.</p> |
38,554,966 | Controlling column widths with Format-Table | <p>I am trying to get the last reboot time of some PCs from a list. When I use </p>
<pre><code>foreach ($pc in $pclist) {
Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pc |
select csname, lastbootuptime
}
</code></pre>
<p>The output comes as following.</p>
<pre>csname lastbootuptime
------ --------------
CONFA7-L1-1A 7/15/2016 9:55:16 AM
CONFA7-L1-1F 5/31/2016 8:51:46 AM
CONFA7-L1-1G 6/18/2016 11:09:15 AM
CONFA7-L1... 6/26/2016 5:31:31 PM
CONFA7-L3... 7/24/2016 3:48:43 PM</pre>
<p>Which is neat, but if the PC name is long, I am unable to see the full name.
So I pipelined <code>Format-Table</code>:</p>
<pre><code>Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pc |
select csname, lastbootuptime |
Format-Table -HideTableHeaders
</code></pre>
<p>And this is what I get:</p>
<pre>CONFA7-L1-1A 7/15/2016 9:55:16 AM
CONFA7-L1-1E 7/21/2016 12:58:16 PM
CONFA7-L1-1F 5/31/2016 8:51:46 AM</pre>
<p>There are two problems here. </p>
<ol>
<li><p>There is no heading. If I remove <code>-HideTableHeaders</code> there will be heading for every output which is not required.</p></li>
<li><p>There is a lot of white spaces in between.</p></li>
</ol>
<p>Basically I just need to get an output similar to the first one, but without truncating the full names. How can I fix these?</p> | 38,576,389 | 2 | 8 | null | 2016-07-24 17:47:02.977 UTC | 8 | 2021-01-28 03:57:22.46 UTC | 2016-07-25 22:00:17.287 UTC | null | 45,375 | null | 3,881,153 | null | 1 | 25 | powershell|formatting|formattable | 80,947 | <p>To summarize and complement the helpful comments made by <a href="https://stackoverflow.com/users/4003407/petseral">PetSerAl</a> and <a href="https://stackoverflow.com/users/1630171/ansgar-wiechers">Ansgar Wiechers</a>:</p>
<p><strong>tl;dr</strong></p>
<pre><code>Get-CimInstance -ClassName win32_operatingsystem -ComputerName $pclist |
Sort-Object CSName |
Format-Table CSName, LastBootUpTime -AutoSize
</code></pre>
<p><strong><code>-AutoSize</code> is what ensures that the <code>CSName</code> (computer name) column is as wide as it needs to</strong> be to show all values in full (unless these values themselves are too long to fit on a single line, in which case <code>-Wrap</code> must be used - see below).</p>
<p><code>Get-CimInstance</code> takes an <em>array</em> of computer names, so there's no need for a loop; however, since the target computers are queried <em>in parallel</em>, the order of objects returned will typically <em>not</em> match the input order of computer names - this is rectified with the <code>Sort-Object CSName</code> call.</p>
<p>To <strong>control the width of <em>individual columns</em></strong>:</p>
<pre><code># Instead of a simple property name, 'prop1', pass a *hashtable*
# (@{ ... }`) with a 'width' entry to Format-Table
PS> [pscustomobject] @{ prop1='1234567890'; prop2='other' } |
Format-Table -Property @{ e='prop1'; width = 5 }, prop2
prop1 prop2
----- -----
1234… other
</code></pre>
<p><sup>Note: In <em>Windows PowerShell</em>, you'll see just <code>12...</code> as the truncated value, because it uses <em>3 individual <code>.</code> characters</em> to represent the truncation; in PowerShell [Core] 6+ this was improved to using a <em>single</em> character, <code>…</code> (HORIZONTAL ELLIPSIS, <a href="http://www.fileformat.info/info/unicode/char/2026" rel="noreferrer"><code>U+2026</code></a>).</sup></p>
<p>Read on to learn <strong>more about table formatting.</strong></p>
<hr />
<p>At its core, your question is about <strong>how to control the output column width of tabular output</strong>, which applies to <em>any</em> cmdlet's output.</p>
<p><strong>Use the <code>Format-Table</code> cmdlet (directly) for tabular output, <em>not</em> <code>Select-Object</code></strong>: the purpose of <code>Select-Object</code> is to create <em>custom objects</em>, not to format output; if such objects (generally, instances of any type without predefined formatting views) happen to haven <em>4 or fewer properties</em>, they are by default formatted with <code>Format-Table</code> behind the scenes (but you don't get to apply options); otherwise, it is <code>Format-List</code> that is implicitly used. <sup>Thanks, <a href="https://stackoverflow.com/users/4003407/petseral">PetSerAl</a>.</sup></p>
<ul>
<li><p><strong><code>Format-Table</code> invariably limits output lines to the <em>available screen width</em></strong>, which means:</p>
<ul>
<li>Columns may not get printed at all.</li>
<li>Especially the last column that is printed may have its values truncated, with the missing part indicated by <code>...</code> / <code>…</code> - though note that <em>all</em> printed columns <em>can</em> have truncated values, as explained below.</li>
</ul>
</li>
<li><p><strong>If you want to create <em>longer lines</em></strong>, pipe <code>Format-Table</code>'s output to <code>| Out-File -Width <int></code> or <code>| Out-String -Stream -Width <int></code>; note that if you print the latter to the screen, lines will <em>wrap</em> (but the extra line breaks won't be part of the data).</p>
<ul>
<li><p><em>Caveat</em>: On <em>Windows PowerShell</em>, do NOT use <code>-Width ([int]::MaxValue)</code>, because table-formatted data for types with formatting data is unconditionally right-padded with spaces to the full width, which can consume inordinate amounts of memory / space in the output file and you may even run out of memory. In PowerShell <em>Core</em>, this has been fixed as of at least v6.1.</p>
</li>
<li><p>An alternative on <em>Windows</em> (does not work in PowerShell Core on <em>Unix</em>-like platforms) is to use <code>[console]::BufferWidth = <column-count></code> to widen the <em>screen buffer</em> to allow longer lines that don't wrap, but require <em>horizontal scrolling</em>.<br />
Additionally, on Windows it only works in the regular console, not in the ISE.</p>
</li>
</ul>
</li>
<li><p>To <strong>control <em>column widths</em></strong> - which indirectly determines how many columns will fit - use the following parameters:</p>
<ul>
<li><p><strong><code>-AutoSize</code></strong> ... tells <code>Format-Table</code> to <strong>make columns as wide as necessary</strong> to fit all data values, but note that this <strong>can result in fewer (less typically: more) columns getting displayed</strong>.</p>
</li>
<li><p><strong><code>-Wrap</code></strong> ... makes <strong>column values span multiple lines</strong>, if needed, to avoid truncation; again, this can apply to <em>all</em> columns<sup>Thanks, <a href="https://stackoverflow.com/users/7571258/zett42">zett42</a>.</sup>, not just the last one, namely in case an automatically determined or fixed column width (specified via a <code>width</code> entry, as shown next) happens to be exceeded by specific values.</p>
</li>
<li><p>To <strong>specify <em>custom column widths</em></strong>, pass a <strong>hashtable with a <code>width</code> entry</strong> as an argument - a so-called <a href="https://stackoverflow.com/a/39861920/45375">calculated property</a> to <code>Format-Table</code>'s <code>-Property</code> parameter; e.g., the following example limits the 1st output column to 5 characters:</p>
<pre><code> [pscustomobject] @{ prop1='1234567890'; prop2='other' } |
Format-Table -Property @{ e='prop1'; width = 5 }, prop2
</code></pre>
<ul>
<li><p>If truncation occurs, which is applied to the <em>end</em> of values by default, the truncation indicator <code>...</code> / <code>…</code> invariably takes up the <em>last 3</em> characters of the truncated value (in <em>Windows PowerShell</em>) / only the <em>last</em> character (in <em>PowerShell [Core] 6+</em>); in the example above, the <code>prop1</code> value renders as <code>12...</code> / <code>1234…</code> for a total of 5 chars.</p>
</li>
<li><p>To truncate the <em>start</em> of values instead, you must change the column to be <em>right</em>-aligned, with a <code>alignment = 'right'</code> entry (default is <code>'left'</code>, <code>'center'</code> is the 3rd option; both of these truncate the <em>end</em> of values).</p>
</li>
<li><p>If you want to retain <em>left</em> alignment while still truncating at the <em>start</em> of values, you'll have to use a custom expression in a script block (<code>{ ... }</code>) assigned to the <code>e</code> (<code>expression</code>) entry:</p>
<pre><code>[pscustomobject] @{ prop1='1234567890'; prop2='other' } |
Format-Table -Property @{
n='prop1'; e={ $_.prop1 -replace '^.+(.{4})$', '…$1'}; width = 5
}, prop2
</code></pre>
</li>
<li><p>Note: <strong>Specifying at least one custom width means that you must explicitly enumerate <em>all</em> properties to output</strong> in the <code>-Property</code> argument, even the ones that don't need custom widths.<sup>[1]</sup></p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Caveats, as of PowerShell 7.1</strong>:</p>
<ul>
<li><p>A <em>bug</em> prevents custom widths from taking effect unless the <em>first</em> column (also) has one; additionally, it <em>never</em> takes effect in the <em>last</em> column - see <a href="https://github.com/PowerShell/PowerShell/issues/14676" rel="noreferrer">GitHub issue #14676</a>.</p>
</li>
<li><p>As <a href="https://stackoverflow.com/users/7571258/zett42">zett42</a> points out and demonstrates in <a href="https://stackoverflow.com/a/65925861/7571258">this answer</a>, <strong>if the <em>first</em> column is a calculated one that specifies a custom width, the remaining line width is <em>evenly distributed</em> among those remaining columns that do not themselves specify a column width</strong>, irrespective of how wide the values in those columns actually are - <strong>unless you also pass <code>-AutoSize</code></strong>. This unexpected behavior is discussed in <a href="https://github.com/PowerShell/PowerShell/issues/14677" rel="noreferrer">GitHub issue #14677</a>.</p>
</li>
</ul>
</li>
</ul>
<hr />
<p><sup>[1] As <a href="https://stackoverflow.com/users/7571258/zett42">zett42</a> points out, you can technically bypass this requirement <em>if all columns are to have the same custom width</em>, because passing a property-name string to the <code>e</code> (<code>Expression</code>) hashtable entry is interpreted as a <em>wildcard pattern</em>, so that string <code>'*'</code> matches <em>all</em> property names; e.g.:<br />
<code>[pscustomobject] @{ a=1; b=2 } | Format-Table @{ e='*'; width=10 }</code></sup></p> |
7,476,541 | For...in statement Objective-C | <p>I am studying Objective-C and I came across this "for...in" statement. I searched for it but i still don't get how it works. Could someone explain to me in a noob-friendly how this statement works?</p> | 7,476,675 | 1 | 2 | null | 2011-09-19 19:55:26.263 UTC | 8 | 2014-07-02 16:43:19.513 UTC | 2014-07-02 16:43:19.513 UTC | null | 868,270 | null | 868,270 | null | 1 | 33 | objective-c|for-in-loop | 53,774 | <p>See <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html" rel="noreferrer">fast enumeration documentation</a>. </p>
<p>Basically you'd have, usually, an array, and you can obtain each item in the array with a handy loop instead of using NSEnumerator or an integer count variable. It makes your code much cleaner to ask for each NSString in your array rather than to have to assign to a variable using <code>objectAtIndex</code> for each pass of your loop. </p>
<p>Compare:</p>
<pre><code>for (NSString *string in myArray)
{
// do stuff...
}
</code></pre>
<p>To:</p>
<pre><code>for (int i = 0; i < [myArray count]; i++)
{
NSString *string = [myArray objectAtIndex:i];
// Do stuff...
}
</code></pre> |
22,798,826 | In node.js, why is there a util.isArray and an Array.isArray? | <p>I just noticed the API docs for <a href="http://nodejs.org/api/util.html#util_util_isarray_object" rel="noreferrer">Node.js v0.10.26</a> provide for <code>util.isArray</code>,</p>
<blockquote>
<p>util.isArray(object)# Returns true if the given "object" is an Array.</p>
<p>false otherwise.</p>
</blockquote>
<pre><code>var util = require('util');
util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false
</code></pre>
<p>But, how is that different ecmascripts normal, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" rel="noreferrer">Array.isArray</a>?</p>
<pre><code>> Array.isArray([]);
true
> Array.isArray(new Array);
true
> Array.isArray({});
false
</code></pre> | 22,848,148 | 4 | 0 | null | 2014-04-01 23:27:54.467 UTC | 6 | 2017-12-01 06:44:25.627 UTC | 2015-01-26 01:41:55.637 UTC | null | 1,048,572 | null | 124,486 | null | 1 | 38 | javascript|arrays|node.js | 22,498 | <p>To actually answer <em>why</em> <code>util.isArray</code> exists, we need a bit of a history lesson.</p>
<p>When it was <a href="https://github.com/joyent/node/blob/3c7873bd/lib/sys.js#L194-198" rel="noreferrer">first added to node</a>, it did a bit more than call <code>Array.isArray</code>.</p>
<pre><code>function isArray (ar) {
return ar instanceof Array
|| Array.isArray(ar)
|| (ar && ar !== Object.prototype && isArray(ar.__proto__));
}
</code></pre>
<p>This was a local function in utils and actually wasn't <a href="https://github.com/joyent/node/commit/b8f3e18a5d3b9542e452274adb5422dfc0784e15" rel="noreferrer">exported</a> until v0.6.0.</p>
<p>In this form, <code>util.isArray</code> handled a case that <code>Array.isArray</code> doesn't:</p>
<pre><code>> x = [1,2,3]
[ 1, 2, 3 ]
> y = Object.create(x)
[ , , ]
> Array.isArray(y)
false
> Array.isArray(Object.getPrototypeOf(y))
true
</code></pre>
<p><a href="https://groups.google.com/forum/#!topic/nodejs-dev/sIlwFm5GcM8" rel="noreferrer">There's some discussion here</a> about this behavior of <code>util.isArray</code>, and consensus was that this behavior is actually bad because <code>y</code> is not really an <code>Array</code>.</p>
<p>Thus, the prototype-checking functionality was <a href="https://github.com/joyent/node/commit/2dbb470" rel="noreferrer">soon removed and replaced</a> with a check that used both <code>Array.isArray</code> and a check of the argument's <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-8.6.2" rel="noreferrer"><em>[[Class]]</em></a>.</p>
<pre><code>function isArray(ar) {
return Array.isArray(ar) ||
(typeof ar === 'object' && objectToString(ar) === '[object Array]');
}
</code></pre>
<p>However, checking the <em>[[Class]]</em> is actually duplicate effort because <code>Array.isArray</code> <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.3.2" rel="noreferrer">also checks</a> the <em>[[Class]]</em>, so it too was eventually <a href="https://github.com/joyent/node/commit/5fcd6e403" rel="noreferrer">removed</a> – leaving only a call to <code>Array.isArray</code>.</p>
<p>Today, <code>util.isArray</code> is just an <a href="https://github.com/joyent/node/commit/95dbb6b" rel="noreferrer">alias</a> of <code>Array.isArray</code>.</p>
<p>So in other words, the existence of <code>util.isArray</code> is mostly a legacy thing and can be safely ignored.</p> |
39,261,204 | typings vs @types NPM scope | <p>In some cases <code>typings</code> is used for handling TypeScript definitions (e.g. <a href="https://github.com/angular/angular2-seed">angular/angular2-seed</a>).</p>
<p>In other cases scoped NPM <code>@types</code> packages are used with no <code>typings</code> involved (e.g. <a href="https://github.com/AngularClass/angular2-webpack-starter">AngularClass/angular2-webpack-starter</a>).</p>
<p>What are the practical differences between them? Does one of them offer benefits for TypeScript development that the other doesn't?</p> | 39,261,890 | 1 | 0 | null | 2016-09-01 01:01:05.287 UTC | 11 | 2016-09-01 02:41:16.24 UTC | null | null | null | null | 3,731,501 | null | 1 | 42 | typescript|npm|typescript-typings | 17,059 | <p>@types is the new way to install the definitions in typescript 2.0.
It unifies the management of definitions and packages. So that you do not need multiple tools and config files. Only going to need npm and package.json instead of having to have npm, package.json, typings, typings.json. It basically makes installing and managing definitions easier but it is the same as typings. </p>
<p>You can read more about it here: <a href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/">https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/</a></p> |
39,320,393 | JSX or HTML autocompletion in Visual Studio Code | <p>Is there any way to use components or HTML completion in Visual Studio Code? Because typing each letter manually is not good idea when we have classes like Bootstrap etc. For example completion as in Emmet: <code>ul>li*2>a</code></p>
<pre><code>var React = require('react');
var Header = React.createClass({
render: function () {
return (
<nav className="navbar navbar-defaullt">
<div className="container-fluid">
<a href="/" className="navbar-brand">
<img width="50" height="50" src="images/logo.png" alt="logo" />
</a>
<ul className="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/#about">About</a></li>
</ul>
</div>
</nav>
);
}
});
module.exports = Header;
</code></pre> | 41,920,968 | 22 | 1 | null | 2016-09-04 18:52:13.833 UTC | 62 | 2022-09-20 19:47:53.797 UTC | 2016-09-10 11:55:04.777 UTC | null | 2,393,027 | null | 3,203,959 | null | 1 | 121 | reactjs|autocomplete|visual-studio-code|jsx|emmet | 136,533 | <p>Visual studio code detect .jsx extensions and add emmet support by default ( i'm using VS code 1.8.1)</p>
<p>But if you prefer to use .js extention for all your react files - you can associate JavaScript React mode with .js files in bottom right corner of VS Code window.</p>
<p><a href="https://i.stack.imgur.com/D4n8H.gif" rel="noreferrer">How to do this step by step (gif)</a></p>
<p><a href="https://i.stack.imgur.com/D4n8H.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/D4n8H.gif" alt="enter image description here" /></a></p>
<h2>Update 2021</h2>
<p>For those who just want to copy-paste the code:</p>
<pre><code>"emmet.syntaxProfiles": {
"javascript": "jsx"
}
</code></pre>
<p>If the solution above doesn't work, try this:</p>
<pre><code>"emmet.triggerExpansionOnTab": true,
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
</code></pre>
<p>Tested with VS Code v1.56.2.</p> |
3,095,998 | Oracle: copy row while updating one field | <p>Please note: I <em>am</em> asking the question I want answered. I know this question means the database is set up poorly. So I will vote down any answers that suggest changing the way the table is set up.</p>
<p>I need to duplicate a bunch of rows, while changing one value. </p>
<pre><code>name col1 col2
dave a nil
sue b nil
sam c 5
</code></pre>
<p>needs to become:</p>
<pre><code>name col1 col2
dave a nil
dave a a
sue b nil
sue b a
same c 5
</code></pre>
<p>IE for all entries in this table where <code>col2 is null</code>, create a new entry in the table where <code>name</code> and <code>col1</code> are the copied, and <code>col2</code> is <code>a</code>.</p> | 3,096,077 | 3 | 1 | null | 2010-06-22 18:28:48.523 UTC | 4 | 2014-02-06 08:55:38.42 UTC | 2013-03-07 18:37:08.67 UTC | null | 20,146 | null | 168,646 | null | 1 | 15 | sql|oracle|plsql|insert | 40,635 | <p>Use:</p>
<pre><code>INSERT INTO table
(name, col1, col2)
SELECT t.name, t.col1, 'a'
FROM TABLE t
WHERE t.col2 IS NULL
</code></pre>
<p>That's assuming neither the <code>name</code> or <code>col1</code> columns are a primary key or have a unique constraint on either.</p> |
2,585,337 | how to use "tab space" while writing in text file | <pre><code> SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmmSS");
String strCurrDate = formatter.format(new java.util.Date());
String strfileNm = "Cust_Advice_" + strCurrDate + ".txt";
String strFileGenLoc = strFileLocation + "/" + strfileNm;
String strQuery="select name, age, data from basetable";
try {
stmt = conn.createStatement();
System.out.println("Query is -> " + strQuery);
rs = stmt.executeQuery(strQuery);
File f = new File(strFileGenLoc);
OutputStream os = (OutputStream)new FileOutputStream(f);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw);
while (rs.next() ) {
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write(" ");
bw.write(rs.getString(2)==null? "":rs.getString(2));
bw.write(" ");
}
bw.flush();
bw.close();
} catch (Exception e) {
System.out.println(
"Exception occured while getting resultset by the query");
e.printStackTrace();
} finally {
try {
if (conn != null) {
System.out.println("Closing the connection" + conn);
conn.close();
}
} catch (SQLException e) {
System.out.println(
"Exception occured while closing the connection");
e.printStackTrace();
}
}
return objArrayListValue;
}
</code></pre>
<p>i need "one tab space" in between each column(while writing to text file). like</p>
<pre><code> manu 25 data1
manc 35 data3
</code></pre>
<p>in my code i use <code>bw.write(" ")</code> for creating space between each column. how to use "one tab space" in that place instead of giving "space". </p> | 2,585,347 | 3 | 0 | null | 2010-04-06 13:58:19.57 UTC | 1 | 2015-05-13 17:27:59 UTC | 2010-04-06 14:01:05.847 UTC | null | 166,712 | null | 269,246 | null | 1 | 26 | java|tabs|text-formatting | 241,276 | <p>You can use <code>\t</code> to create a tab in a file.</p> |
2,519,436 | Possible to create this redirecting route in Rails? | <p>Is it possible to do a redirect in the routes file of a Rails app?</p>
<p>Specifically, I'd like to forward <code>/j/e</code> to <code>/javascripts/embed.js</code></p>
<p>Right now the only way I can think to do it is to create a <code>j</code> controller with an <code>e</code> method that redirects to that.</p> | 2,519,614 | 3 | 0 | null | 2010-03-25 21:14:03.283 UTC | 17 | 2022-06-28 17:08:04.223 UTC | null | null | null | null | 147,586 | null | 1 | 52 | ruby-on-rails|redirect|routes | 48,186 | <p>Assuming rails version prior to 3.</p>
<p>You can create a new <code>RedirectController</code> or tuck a single function away in an existing controller, to do something like the following:</p>
<pre><code>map.js_embed '/j/e',
:controller => :redirect_controller,
:action => :some_function,
:path => "embed"
</code></pre>
<p>Then your function would do this:</p>
<pre><code>def some_function
if params[:path]
redirect_to "/javascripts/#{params[:path]}.js"
end
end
</code></pre>
<p>or something for that effect.</p> |
2,670,680 | Git basic workflow | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2816369/git-push-error-remote-rejected-master-master-branch-is-currently-checked">git push error '[remote rejected] master -> master (branch is currently checked out)'</a> </p>
</blockquote>
<p>I am new to Git and trying to use it for a local grails project.<br>
The steps I followed:</p>
<ol>
<li>create the grails project </li>
<li>go to the project directory and <code>git init</code> </li>
<li>Add all the files in the project in staging area and commit. </li>
<li><p>The git status at the repo gives the below message </p>
<pre><code>BXX@BXX-PC /c/Work/Grails/projects/yyy/tables (master)
$ git status
# On branch master
nothing to commit (working directory clean)
</code></pre></li>
<li><p>Trying to keep it as the master branch, make the changes by cloning the repo, and later push the changes back. For that</p></li>
<li>In my IDE, checkout the project (IntelliJ).This actually clone the project to another dir. </li>
<li>Make the changes and commit the project </li>
<li><p>Push the local changes to master. </p>
<pre><code>15:41:56.249: git push -v origin master
Pushing to c:/Work/Grails/projects/xxx/tables
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
</code></pre></li>
</ol>
<p>The cloned repo status is </p>
<pre><code>$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
</code></pre>
<p>Please help me with understanding this. Is there a better workflow to follow. I may be able to initialize the repo through Intellij, and try to work on the main branch. Still not sure what is wrong above.</p>
<p>thank you. </p> | 2,670,812 | 4 | 1 | null | 2010-04-19 20:36:21.657 UTC | 17 | 2011-08-03 16:40:13.747 UTC | 2017-05-23 12:26:20.52 UTC | null | -1 | null | 303,477 | null | 1 | 27 | git|push | 22,898 | <p>First of all, you do not need to clone your local repository. You can use branches to divide development in the same repository.</p>
<p>Git is a Distributed VCS, and if you have experience with Subversion or CVS before it, you need to change your mind.</p>
<p>Git is a very agile and you can use different workflows with it. Cloning repositories is more needed for a team work, not for local development (IMHO).</p>
<p>Branches is a good alternative for you.</p>
<p>See. Let's set <strong>master</strong> branch of your repository for a <strong>production-ready</strong> code. Let's create another branch for <strong>development</strong>:</p>
<pre><code>$ git checkout -b development master
</code></pre>
<p>Now you are working on the <strong>development</strong> branch.</p>
<p>You could use different branches for each feature you want to develop. It's very easy and helpful.</p>
<p>Let's imagine you want to implement some new feature, you need to create a new branch:</p>
<pre><code>$ git checkout -b newfeature development
</code></pre>
<p>Now you can work with your code, add files, commit and so on.</p>
<p>Next you need to <strong>merge</strong> your new developed feature to the <strong>development</strong> branch:</p>
<pre><code>$ git add .
$ git commit -m "My last changes for the new feature"
$ git checkout development
$ git merge newfeature
</code></pre>
<p>Now your new code from the <strong>newfeature</strong> branch merged into the <strong>development</strong> branch.</p>
<p>For sometime in the future when you decide that your code in the <strong>development</strong> branch get some milestone, you could merge all the changes from <strong>development</strong> to <strong>master</strong> branch.</p>
<p>It's a very basic workflow, it can be helpful for the many branches.</p>
<p>My advise for you now: read more about git, branching, stashing (very-very-very helpful for quick fixes). And after some time you will get a great effort from using git.</p>
<p>Good luck.</p> |
2,620,377 | Lua - Reflection - Get list of functions/fields on an object? | <p>I'm new to Lua and dealing with Lua as a scripting language in an alpha release of a program. The developer is unresponsive and I need to get a list of functions provided by some C++ objects which are accessible from the Lua code.</p>
<p>Is there any easy way to see what fields and functions these objects expose?</p> | 2,620,398 | 4 | 0 | null | 2010-04-12 07:02:29.807 UTC | 13 | 2017-08-16 21:15:49.08 UTC | null | null | null | null | 314,284 | null | 1 | 35 | c++|reflection|function|object|lua | 47,744 | <p>In Lua, to view the members of a object, you can use:</p>
<pre><code>for key,value in pairs(o) do
print("found member " .. key);
end
</code></pre>
<p>Unfortunately I don't know if this will work for objects imported from C++.</p> |
28,995,827 | Yii2 - How To Add a CSS class to an ActiveForm Field | <p>This is the activeform field. I would like to know how to add a css class to it.</p>
<pre><code><?= $form->field($model, 'url')->label(false); ?>
</code></pre> | 28,997,161 | 2 | 0 | null | 2015-03-11 19:38:23.677 UTC | 3 | 2019-01-11 11:06:53.96 UTC | 2016-10-24 16:33:37.983 UTC | null | 4,305,683 | null | 1,923,625 | null | 1 | 27 | yii2 | 57,772 | <p>You can add it with </p>
<pre><code><?= $form->field($model, 'url')->textInput(['maxlength' => 255, 'class' => 'your class'])->label(false); ?>
</code></pre>
<p>As a rule you can pass html elements when telling activeField what type it should be. The default is textInput so that is why your code works, but if you want to change the input then you have to explicitly tell it the type of input.</p>
<p><a href="http://www.yiiframework.com/doc-2.0/guide-input-forms.html">http://www.yiiframework.com/doc-2.0/guide-input-forms.html</a></p> |
37,687,427 | Change the thickness of an SVG shape | <p>I'm not familiar enough with svg drawing.</p>
<p>I have this arrow in SVG format. How can I increase the thickness of the arrow?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width: 100px; height:100px;">
<svg viewBox="0 0 100 100">
<path d="M 50,0 L 60,10 L 20,50 L 60,90 L 50,100 L 0,50 Z" class="arrow" transform="translate(85,100) rotate(180)"></path>
</svg>
</div></code></pre>
</div>
</div>
</p>
<p>Thanks in advance</p> | 37,687,733 | 3 | 0 | null | 2016-06-07 19:08:16.287 UTC | 10 | 2021-08-05 12:32:20.143 UTC | 2016-06-08 07:14:16.153 UTC | null | 1,292,848 | null | 4,980,017 | null | 1 | 53 | html|svg | 68,062 | <p>You can add a stroke with <code>stroke="black" stroke-width="10"</code> and then adjust your viewBox accordingly.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>OLD:
<div style="width: 100px; height:100px;">
<svg viewBox="0 0 100 100">
<path d="M 50,0 L 60,10 L 20,50 L 60,90 L 50,100 L 0,50 Z" class="arrow" transform="translate(85,100) rotate(180)"></path>
</svg>
</div>
<br>
NEW:
<div style="width: 100px; height:100px;">
<svg viewBox="-10 -10 120 120">
<path d="M 50,0 L 60,10 L 20,50 L 60,90 L 50,100 L 0,50 Z" class="arrow" transform="translate(85,100) rotate(180)" stroke="black" stroke-width="10"></path>
</svg>
</div></code></pre>
</div>
</div>
</p> |
28,821,632 | how to configure eb cli with eb env that is already running | <p>I have taken over a project that has been deployed to elastic beanstalk. I would like to configure my eb cli to deploy to the existing environment without modifying that environment. From my research I get the impression that <code>eb init</code> is the proper command, however when I started going through the interactive session it seemed like it was going to use my entries as the configuration settings (e.g. platform version). I want to make sure that I maintain the settings that are already in use (I was unable to determine what platform version my running environment is using) and I want to make sure that the running ec2 instance will not be replaced or terminated for any reason. Does anyone know the best way to go about doing this? Thanks in advance for any help.</p> | 28,823,517 | 2 | 0 | null | 2015-03-02 23:53:42.827 UTC | 4 | 2017-11-30 07:01:33.447 UTC | null | null | null | null | 1,908,882 | null | 1 | 35 | amazon-web-services|amazon-ec2|amazon-elastic-beanstalk | 19,868 | <p>During <code>eb init</code> make sure select an existing application and environment. As long as you do this it will pull down the settings from the environment.</p>
<p>However, that being said, the settings that <code>eb init</code> creates are default setting used for future environments. It will not overwrite any settings on any running environments. </p>
<p>As far as instances, Elastic Beanstalk can terminate or create instances at anytime based on health and autoscaling. However, if we assume your instances are healthy and no autoscaling events occur, then <code>eb deploy</code> will never cause instances to be replaced.</p>
<p>I am however a little curious as to why you are so worried about your instances being replaced.</p>
<p>As far as determining your current platform, you can get that information from <code>eb status</code>.</p> |
40,357,434 | Pandas df.iterrows() parallelization | <p>I would like to parallelize the following code:</p>
<pre><code>for row in df.iterrows():
idx = row[0]
k = row[1]['Chromosome']
start,end = row[1]['Bin'].split('-')
sequence = sequence_from_coordinates(k,1,start,end) #slow download form http
df.set_value(idx,'GC%',gc_content(sequence,percent=False,verbose=False))
df.set_value(idx,'G4 repeats', sum([len(list(i)) for i in g4_scanner(sequence)]))
df.set_value(idx,'max flexibility',max([item[1] for item in dna_flex(sequence,verbose=False)]))
</code></pre>
<p>I have tried to use <code>multiprocessing.Pool()</code> since each row can be processed independently, but I can't figure out how to share the DataFrame. I am also not sure that this is the best approach to do parallelization with pandas. Any help?</p> | 40,428,356 | 4 | 4 | null | 2016-11-01 09:39:12.36 UTC | 24 | 2021-09-18 15:55:00.533 UTC | 2019-05-11 23:38:10.23 UTC | null | 3,190,076 | null | 3,190,076 | null | 1 | 41 | python|pandas|multiprocessing | 25,917 | <p>As @Khris said in his comment, you should split up your dataframe into a few large chunks and iterate over each chunk in parallel. You could arbitrarily split the dataframe into randomly sized chunks, but it makes more sense to divide the dataframe into equally sized chunks based on the number of processes you plan on using. Luckily someone else has <a href="https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks">already figured out how to do that part</a> for us:</p>
<pre><code># don't forget to import
import pandas as pd
import multiprocessing
# create as many processes as there are CPUs on your machine
num_processes = multiprocessing.cpu_count()
# calculate the chunk size as an integer
chunk_size = int(df.shape[0]/num_processes)
# this solution was reworked from the above link.
# will work even if the length of the dataframe is not evenly divisible by num_processes
chunks = [df.iloc[df.index[i:i + chunk_size]] for i in range(0, df.shape[0], chunk_size)]
</code></pre>
<p>This creates a list that contains our dataframe in chunks. Now we need to pass it into our pool along with a function that will manipulate the data.</p>
<pre><code>def func(d):
# let's create a function that squares every value in the dataframe
return d * d
# create our pool with `num_processes` processes
pool = multiprocessing.Pool(processes=num_processes)
# apply our function to each chunk in the list
result = pool.map(func, chunks)
</code></pre>
<p>At this point, <code>result</code> will be a list holding each chunk after it has been manipulated. In this case, all values have been squared. The issue now is that the original dataframe has not been modified, so we have to replace all of its existing values with the results from our pool.</p>
<pre><code>for i in range(len(result)):
# since result[i] is just a dataframe
# we can reassign the original dataframe based on the index of each chunk
df.iloc[result[i].index] = result[i]
</code></pre>
<p>Now, my function to manipulate my dataframe is vectorized and would likely have been faster if I had simply applied it to the entirety of my dataframe instead of splitting into chunks. However, in your case, your function would iterate over each row of the each chunk and then return the chunk. This allows you to process <code>num_process</code> rows at a time.</p>
<pre><code>def func(d):
for row in d.iterrow():
idx = row[0]
k = row[1]['Chromosome']
start,end = row[1]['Bin'].split('-')
sequence = sequence_from_coordinates(k,1,start,end) #slow download form http
d.set_value(idx,'GC%',gc_content(sequence,percent=False,verbose=False))
d.set_value(idx,'G4 repeats', sum([len(list(i)) for i in g4_scanner(sequence)]))
d.set_value(idx,'max flexibility',max([item[1] for item in dna_flex(sequence,verbose=False)]))
# return the chunk!
return d
</code></pre>
<p>Then you reassign the values in the original dataframe, and you have successfully parallelized this process.</p>
<h2>How Many Processes Should I Use?</h2>
<p>Your optimal performance is going to depend on the answer to this question. While "ALL OF THE PROCESSES!!!!" is one answer, a better answer is much more nuanced. After a certain point, throwing more processes at a problem actually creates more overhead than it's worth. This is known as <a href="https://en.wikipedia.org/wiki/Amdahl%27s_law" rel="noreferrer">Amdahl's Law</a>. Again, we are fortunate that others have already tackled this question for us:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/20039659/python-multiprocessings-pool-process-limit">Python multiprocessing's Pool process limit</a></li>
<li><a href="https://stackoverflow.com/questions/23816546/how-many-processes-should-i-run-in-parallel">How many processes should I run in parallel?</a></li>
</ol>
<p>A good default is to use <code>multiprocessing.cpu_count()</code>, which is the default behavior of <code>multiprocessing.Pool</code>. <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool" rel="noreferrer">According to the documentation</a> "If processes is None then the number returned by cpu_count() is used." That's why I set <code>num_processes</code> at the beginning to <code>multiprocessing.cpu_count()</code>. This way, if you move to a beefier machine, you get the benefits from it without having to change the <code>num_processes</code> variable directly.</p> |
176,720 | Irregular shaped Windows Form (C#) | <p>What is the easiest way to do this? Is it possible with managed code?</p> | 176,734 | 2 | 1 | null | 2008-10-06 23:47:17.633 UTC | 11 | 2019-02-12 00:24:25.683 UTC | 2019-02-12 00:24:25.683 UTC | null | 513,951 | Matias | 4,386 | null | 1 | 19 | c#|.net|winforms | 10,422 | <pre><code>this.BackgroundImage = //Image
this.FormBorderStyle = FormBorderStyle.None;
this.Width = this.BackgroundImage.Width;
this.Height = this.BackgroundImage.Height;
this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color
</code></pre>
<p>This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.</p> |
1,252,270 | How do I view all ignored patterns set with svn:ignore recursively in an SVN repository? | <p>I see it is possible to view a list of properties set on every directory within an SVN repository using proplist and the -R flag (recursive) and -v flag (verbose):</p>
<pre><code>svn proplist -Rv
</code></pre>
<p>This shows me all properties, such as svn:mime-type or svn:executable. I'm looking to filter this to just <code>svn:ignore</code> properties. I'm sure there is some way to pipe the result from this command through a shell command that would only show me the lines I'm interested in, but I can't figure out how to do it. As an example of the type of thing that would be most useful is some type of command like this (but this one doesn't work!).</p>
<pre><code>svn proplist -Rv | grep "^ svn:ignore" | awk "{print \$1}"
</code></pre>
<p>I just don't know enough about shell commands like <a href="http://en.wikipedia.org/wiki/Grep" rel="noreferrer">grep</a> and <a href="http://en.wikipedia.org/wiki/AWK" rel="noreferrer">awk</a> to make this work for me. This just shows "svn:ignore" over and over again, but it doesn't print out the directory path or contents of the <code>svn:ignore</code> property. Here is an example of the output from "svn proplist -Rv" that I'd like to grab, where 'cache' is the path and '*' is the value of the property.</p>
<pre><code>Properties on 'cache':
svn:ignore
*
</code></pre>
<p>How can the above command be made to work and/or is there a better way to view all <code>svn:ignore</code> properties in my repository?</p> | 1,252,303 | 2 | 4 | null | 2009-08-09 20:56:52.67 UTC | 22 | 2017-03-06 09:14:25.953 UTC | 2016-12-11 14:28:05.577 UTC | null | 63,550 | null | 149,503 | null | 1 | 67 | svn|awk|grep | 33,704 | <pre><code>svn pg -R svn:ignore .
</code></pre>
<p>...with <code>pg</code> being a shorthand notation for <code>propget</code>, so this is equal to...</p>
<pre><code>svn propget -R svn:ignore .
</code></pre> |
2,385,609 | Getting selected text with CKEditor Plugin on IE | <p>I have made a plugin for CKEditor, but it relies on the currently selected text.</p>
<p>In FF and Chrome I can use: </p>
<pre><code>var selectedText = editor.getSelection().getNative();
</code></pre>
<p>but this doesn't work in IE and I only get <code>[object Object]</code></p>
<p>Any suggestions?</p> | 2,387,102 | 5 | 1 | null | 2010-03-05 09:19:34.39 UTC | 9 | 2017-10-23 20:19:21.05 UTC | 2017-10-23 20:19:21.05 UTC | null | 241,211 | null | 286,972 | null | 1 | 15 | javascript|internet-explorer|plugins|ckeditor | 19,321 | <p>This is what I use:</p>
<pre><code>var mySelection = editor.getSelection();
if (CKEDITOR.env.ie) {
mySelection.unlock(true);
selectedText = mySelection.getNative().createRange().text;
} else {
selectedText = mySelection.getNative();
}
</code></pre> |
2,412,720 | How to Make a Basic Finite State Machine in Objective-C | <p>I am attempting to build an FSM to control a timer in (iphone sdk) objective c. I felt it was a necessary step, because I was otherwise ending up with nasty spaghetti code containing pages of if-then statements. The complexity, non-readability, and difficulty of adding/changing features lead me to attempt a more formal solution like this. </p>
<p>In the context of the application, the state of the timer determines some complex interactions with NSManagedObjects, Core Data, and so forth. I have left all that functionality out for now, in an attempt to get a clear view of the FSM code. </p>
<p>The trouble is, I cannot find any examples of this sort of code in Obj-C, and I am not so confident about how I have translated it from the C++ example code I was using. (I don't know C++ at all, so there is some guessing involved.) I am basing this version of a state pattern design on this article: <a href="http://www.ai-junkie.com/architecture/state_driven/tut_state1.html" rel="nofollow noreferrer">http://www.ai-junkie.com/architecture/state_driven/tut_state1.html</a>. I'm not making a game, but this article outlines concepts that work for what I'm doing. </p>
<p>In order to create the code (posted below), I had to learn a lot of new concepts, including obj-c protocols, and so forth. Because these are new to me, as is the state design pattern, I'm hoping for some feedback about this implementation. Is this how you work with protocol objects effectively in obj-c? </p>
<p>Here is the protocol:</p>
<pre><code>@class Timer;
@protocol TimerState
-(void) enterTimerState:(Timer*)timer;
-(void) executeTimerState:(Timer*)timer;
-(void) exitTimerState:(Timer*)timer;
@end
</code></pre>
<p>Here is the Timer object (in its most stripped down form) header file:</p>
<pre><code>@interface Timer : NSObject
{
id<TimerState> currentTimerState;
NSTimer *secondTimer;
id <TimerViewDelegate> viewDelegate;
id<TimerState> setupState;
id<TimerState> runState;
id<TimerState> pauseState;
id<TimerState> resumeState;
id<TimerState> finishState;
}
@property (nonatomic, retain) id<TimerState> currentTimerState;
@property (nonatomic, retain) NSTimer *secondTimer;
@property (assign) id <TimerViewDelegate> viewDelegate;
@property (nonatomic, retain) id<TimerState> setupState;
@property (nonatomic, retain) id<TimerState> runState;
@property (nonatomic, retain) id<TimerState> pauseState;
@property (nonatomic, retain) id<TimerState> resumeState;
@property (nonatomic, retain) id<TimerState> finishState;
-(void)stopTimer;
-(void)changeState:(id<TimerState>) timerState;
-(void)executeState:(id<TimerState>) timerState;
-(void) setupTimer:(id<TimerState>) timerState;
</code></pre>
<p>And the Timer Object implementation:</p>
<pre><code>#import "Timer.h"
#import "TimerState.h"
#import "Setup_TS.h"
#import "Run_TS.h"
#import "Pause_TS.h"
#import "Resume_TS.h"
#import "Finish_TS.h"
@implementation Timer
@synthesize currentTimerState;
@synthesize viewDelegate;
@synthesize secondTimer;
@synthesize setupState, runState, pauseState, resumeState, finishState;
-(id)init
{
if (self = [super init])
{
id<TimerState> s = [[Setup_TS alloc] init];
self.setupState = s;
//[s release];
id<TimerState> r = [[Run_TS alloc] init];
self.runState = r;
//[r release];
id<TimerState> p = [[Pause_TS alloc] init];
self.pauseState = p;
//[p release];
id<TimerState> rs = [[Resume_TS alloc] init];
self.resumeState = rs;
//[rs release];
id<TimerState> f = [[Finish_TS alloc] init];
self.finishState = f;
//[f release];
}
return self;
}
-(void)changeState:(id<TimerState>) newState{
if (newState != nil)
{
[self.currentTimerState exitTimerState:self];
self.currentTimerState = newState;
[self.currentTimerState enterTimerState:self];
[self executeState:self.currentTimerState];
}
}
-(void)executeState:(id<TimerState>) timerState
{
[self.currentTimerState executeTimerState:self];
}
-(void) setupTimer:(id<TimerState>) timerState
{
if ([timerState isKindOfClass:[Run_TS class]])
{
secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
}
else if ([timerState isKindOfClass:[Resume_TS class]])
{
secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
}
}
-(void) stopTimer
{
[secondTimer invalidate];
}
-(void)currentTime
{
//This is just to see it working. Not formatted properly or anything.
NSString *text = [NSString stringWithFormat:@"%@", [NSDate date]];
if (self.viewDelegate != NULL && [self.viewDelegate respondsToSelector:@selector(updateLabel:)])
{
[self.viewDelegate updateLabel:text];
}
}
//TODO: releases here
- (void)dealloc
{
[super dealloc];
}
@end
</code></pre>
<p>Don't worry that there are missing things in this class. It doesn't do anything interesting yet. I'm currently just struggling with getting the syntax correct. Currently it compiles (and works) but the isKindOfClass method calls cause compiler warnings (method is not found in protocol). I'm not really sure that I want to use isKindOfClass anyway. I was thinking of giving each <code>id<TimerState></code> object a name string and using that instead. </p>
<p>On another note: all those <code>id<TimerState></code> declarations were originally TimerState * declarations. It seemed to make sense to retain them as properties. Not sure if it makes sense with <code>id<TimerState></code>'s. </p>
<p>Here is an example of one of the state classes: </p>
<pre><code>#import "TimerState.h"
@interface Setup_TS : NSObject <TimerState>{
}
@end
#import "Setup_TS.h"
#import "Timer.h"
@implementation Setup_TS
-(void) enterTimerState:(Timer*)timer{
NSLog(@"SETUP: entering state");
}
-(void) executeTimerState:(Timer*)timer{
NSLog(@"SETUP: executing state");
}
-(void) exitTimerState:(Timer*)timer{
NSLog(@"SETUP: exiting state");
}
@end
</code></pre>
<p>Again, so far it doesn't do anything except announce that what phase (or sub-state) it's in. But that's not the point. </p>
<p>What I'm hoping to learn here is whether this architecture is composed correctly in the obj-c language. One specific problem I'm encountering is the creation of the id objects in the timer's init function. As you can see, I commented out the releases, because they were causing a "release not found in protocol" warning. I wasn't sure how to handle that. </p>
<p>What I don't need is comments about this code being overkill or meaningless formalism, or whatever. It's worth me learning this even it those ideas are true. If it helps, think of it as a theoretical design for an FSM in obj-c. </p>
<p>Thank you in advance for any helpful comments. </p>
<p>(this didn't help too much: <a href="https://stackoverflow.com/questions/1110572/finite-state-machine-in-objective-c">Finite State Machine in Objective-C</a>)</p> | 2,413,173 | 5 | 0 | null | 2010-03-09 21:30:05.567 UTC | 17 | 2013-03-18 23:02:22.9 UTC | 2017-05-23 11:47:12.213 UTC | null | -1 | null | 241,883 | null | 1 | 31 | objective-c|protocols|state-machine | 19,560 | <p>When you use a protocol as a type-modifier, you can provide a comma-separated list of protocols. So all you need to do to get rid of the compiler warning is add NSObject to the protocol list like so:</p>
<pre><code>- (void)setupTimer:(id<TimerState,NSObject>) timerState {
// Create scheduled timers, etc...
}
</code></pre> |
2,361,851 | C# and F# casting - specifically the 'as' keyword | <p>In C# I can do:</p>
<pre><code>var castValue = inputValue as Type1
</code></pre>
<p>In F#, I can do:</p>
<pre><code>let staticValue = inputValue :> Type1
let dynamicValue = inputValue :?> Type1
</code></pre>
<p>But neither of them is the equivalent of the C#'s keyword <code>as</code>.</p>
<p>I guess I need to do a match expression for the equivalent in F#</p>
<pre><code>match inputValue with
| :? Type1 as type1Value -> type1Value
| _ -> null
</code></pre>
<p>Is this correct?</p> | 2,362,114 | 5 | 0 | null | 2010-03-02 08:55:50.377 UTC | 4 | 2020-06-21 15:46:37.257 UTC | 2018-04-18 06:07:05.64 UTC | null | 544,947 | null | 5,932 | null | 1 | 33 | c#|f#|c#-to-f# | 8,158 | <p>As far as I know, F# doesn't have any built-in operator equivalent to C# <code>as</code> so you need to write some more complicated expression. Alternatively to your code using <code>match</code>, you could also use <code>if</code>, because the operator <code>:?</code> can be use in the same way as <code>is</code> in C#:</p>
<pre><code>let res = if (inputValue :? Type1) then inputValue :?> Type1 else null
</code></pre>
<p>You can of course write a function to encapsulate this behavior (by writing a simple generic function that takes an <code>Object</code> and casts it to the specified generic type parameter):</p>
<pre><code>let castAs<'T when 'T : null> (o:obj) =
match o with
| :? 'T as res -> res
| _ -> null
</code></pre>
<p>This implementation returns <code>null</code>, so it requires that the type parameter has <code>null</code> as a proper value (alternatively, you could use <code>Unchecked.defaultof<'T></code>, which is equivalent to <code>default(T)</code> in C#). Now you can write just:</p>
<pre><code>let res = castAs<Type1>(inputValue)
</code></pre> |
2,496,267 | Recording user data for heatmap with JavaScript | <p>I was wondering how sites such as crazyegg.com store user click data during a session. Obviously there is some underlying script which is storing each clicks data, but how is that data then populated into a database? It seems to me the simple solution would be to send data via AJAX but when you consider that it's almost impossible to get a cross browser page unload function setup, I'm wondering if there is perhaps some other more advanced way of getting metric data.</p>
<p>I even saw a site which records each mouse movement and I am guessing they are definitely not sending that data to a database on each mouse move event.</p>
<p>So, in a nutshell, what kind of technology would I need in order to monitor user activity on my site and then store this information in order to create metric data? I am not looking to recreate GA, I'm just very interested to know how this sort of thing is done.</p>
<p>Thanks in advance</p> | 2,496,550 | 5 | 0 | null | 2010-03-22 22:37:21.827 UTC | 16 | 2020-07-09 08:20:34.36 UTC | 2020-01-16 16:37:00.463 UTC | null | 56,621 | null | 170,488 | null | 1 | 39 | javascript|analytics|heatmap|metrics | 13,863 | <p>The fundamental idea used by many tracking systems uses a 1x1px image which is requested with extra GET parameters. The request is added to server log file, then log files are processed to generate some statistics.
So a minimalist click tracking function might look like this:</p>
<pre><code>document.onclick = function(e){
var trackImg = new Image();
trackImg.src = 'http://tracking.server/img.gif?x='+e.clientX+'&y='+e.clientY;
}
</code></pre>
<p>AJAX wouldn't be useful because it is subject to same-origin policy (you won't be able to send requests to your tracking server). And you'd have to add AJAX code to your tracking script.
If you want to send more data (like cursor movements) you'd store the coordinates in a variable and periodically poll for a new image with updated path in the GET parameter.</p>
<p>Now there are many many problems:</p>
<ul>
<li>cross-browser compatibility - to make the above function work in all browsers that matter at the moment you'd probably have to add 20 more lines of code</li>
<li>getting useful data
<ul>
<li>many pages are fixed-width, centered, so raw X and Y coordinates won't let you create visual overlay of clicks n the page</li>
<li>some pages have liquid-width elements, or use a combination of min- and max-height</li>
<li>users may use different font sizes</li>
<li>dynamic elements that appear on the page in response to user's actions</li>
</ul></li>
<li>etc. etc.</li>
</ul>
<p>When you have the tracking script worked out you only need to create a tool that takes raw server logs and turns them into shiny heatmaps :)</p> |
2,452,987 | Hibernate - why use many-to-one to represent a one-to-one? | <p>I've seen people use many-to-one mappings to represent one-to-one relationships. I've also read this in a book by Gavin King and on articles.</p>
<p>For example, if a customer can have exactly one shipping address, and a shipping address can belong to only one customer, the mapping is given as:</p>
<pre><code><class name="Customer" table="CUSTOMERS">
...
<many-to-one name="shippingAddress"
class="Address"
column="SHIPPING_ADDRESS_ID"
cascade="save-update"
unique="true"/>
...
</class>
</code></pre>
<p>The book reasons as (quoting it): </p>
<blockquote>
<p>"You don't care what's on the target side of the association, so you can treat it like a <em>to-one</em> association without the <em>many</em> part."</p>
</blockquote>
<p>My question is, why use <code>many-to-one</code> and not <code>one-to-one</code>? What is it about a <code>one-to-one</code> that makes it a less desirable option to <code>many-to-one</code>?</p>
<p>Thanks.</p> | 2,456,176 | 5 | 0 | null | 2010-03-16 08:42:59.02 UTC | 15 | 2018-06-29 17:05:49.26 UTC | 2012-12-09 12:41:31.747 UTC | null | 143,732 | null | 124,111 | null | 1 | 49 | hibernate|orm | 30,636 | <p>There are several ways to implement a one-to-one association in a database: you can share a primary key but you can also use a foreign key relationship with a unique constraint (one table has a foreign key column that references the primary key of the associated table). </p>
<p>In the later case, the hibernate way to map this is to use a <code>many-to-one</code> association (that allows to specify the foreign key).</p>
<blockquote>
<p>The reason is simple: You don’t care
what’s on the target side of the
association, so you can treat it like
a to-one association without the many
part. <em>All you want is to express “This
entity has a property that is a
reference to an instance of another
entity” and use a foreign key field to
represent that relationship.</em></p>
</blockquote>
<p>In other words, using a <code>many-to-one</code> is the way to map <strong>one-to-one foreign key associations</strong> (which are actually maybe more frequent than <strong>shared primary key one-to-one associations</strong>).</p> |
2,899,201 | 'Microsoft.ACE.OLEDB.12.0' 64x Sql Server and 86x Office? | <p>The error:</p>
<blockquote>
<blockquote>
<p>OLE DB provider 'Microsoft.ACE.OLEDB.12.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode.</p>
</blockquote>
</blockquote>
<p>And the answers I'm seeing is a conflict between 64 bit Sql Server and 32 bit Office. Is there a way to run an openrowset on Excel into Sql Server?</p>
<pre><code>insert into dbo.FiscalCalendar
select * from
openrowset('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;Database=C:\Users\uname\Desktop\fy11.xlsx;',
'Select * from [Sheet1]')
</code></pre> | 2,899,337 | 6 | 0 | null | 2010-05-24 18:17:02.523 UTC | 4 | 2017-08-29 14:17:51.03 UTC | 2015-09-25 18:11:33.473 UTC | null | 103,897 | null | 103,897 | null | 1 | 4 | 64-bit|oledb|32-bit|openrowset | 54,719 | <p>Looks like Microsoft hasn't come up with a solution on this yet.
<a href="https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=125117&wa=wsignin1.0" rel="nofollow noreferrer">check Microsoft feedback form of products</a></p>
<p>They have some workarounds like using SSIS</p> |
3,067,113 | XSLT string replace | <p>I don't really know XSL but I need to fix this code, I have reduced it to make it simpler.<br>
I am getting this error </p>
<blockquote>
<p>Invalid XSLT/XPath function</p>
</blockquote>
<p>on this line</p>
<pre><code><xsl:variable name="text" select="replace($text,'a','b')"/>
</code></pre>
<p>This is the XSL</p>
<pre><code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:inm="http://www.inmagic.com/webpublisher/query" version="1.0">
<xsl:output method="text" encoding="UTF-8" />
<xsl:preserve-space elements="*" />
<xsl:template match="text()" />
<xsl:template match="mos">
<xsl:apply-templates />
<xsl:for-each select="mosObj">
'Notes or subject'
<xsl:call-template
name="rem-html">
<xsl:with-param name="text" select="SBS_ABSTRACT" />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="rem-html">
<xsl:param name="text" />
<xsl:variable name="text" select="replace($text, 'a', 'b')" />
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Can anyone tell me what's wrong with it?</p> | 3,067,130 | 6 | 1 | null | 2010-06-18 03:54:16.907 UTC | 23 | 2022-01-05 13:38:12.507 UTC | 2015-09-24 23:56:54.197 UTC | null | 111,575 | null | 36,036 | null | 1 | 92 | xslt|xpath|replace|xslt-1.0|xpath-1.0 | 356,533 | <p><code>replace</code> isn't available for XSLT 1.0. </p>
<p>Codesling has a <a href="http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx" rel="noreferrer">template for string-replace</a> you can use as a substitute for the function:</p>
<pre><code><xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<!-- Prevent this routine from hanging -->
<xsl:value-of select="$text" />
</xsl:when>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</code></pre>
<p>invoked as:</p>
<pre><code><xsl:variable name="newtext">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$text" />
<xsl:with-param name="replace" select="a" />
<xsl:with-param name="by" select="b" />
</xsl:call-template>
</xsl:variable>
</code></pre>
<p>On the other hand, if you literally only need to replace one character with another, you can call <a href="http://www.zvon.org/xxl/XSLTreference/Output/function_translate.html" rel="noreferrer"><code>translate</code></a> which has a similar signature. Something like this should work fine:</p>
<pre><code><xsl:variable name="newtext" select="translate($text,'a','b')"/>
</code></pre>
<p>Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of <code>$foo = $foo</code> like you had in your original code.</p> |
2,369,081 | How to scroll to top of a div using jQuery? | <p>I have a gridview inside a div.. I want to scroll to top of the div from the bottom of the div using jquery.. Any suggestion..</p>
<pre><code><div id="GridDiv">
// gridview inside..
</div>
</code></pre>
<p>My gridview will have custom pagination generated link buttons in it... I will scroll to top of the div from the bottom of the link button click ...</p>
<pre><code>protected void Nav_OnClick(object sender, CommandEventArgs e)
{
LinkButton lb1 = (LinkButton)sender;
//string s = lb1.ID;
ScriptManager.RegisterClientScriptBlock(lb1, typeof(LinkButton),
"scroll", "javascript:document.getElementById('GridDiv').scrollTop = 0;", true);
</code></pre>
<p>In the place of javascript, I ll call the jquery function... Any suggestion...</p>
<p><strong>EDIT:</strong></p>
<p>Exactly like Stackoverflow questions per user page... When changing page nos it scrolls to top with smooth effect... I want to achieve that...</p> | 2,369,092 | 7 | 1 | null | 2010-03-03 05:59:44.337 UTC | 14 | 2020-04-29 05:51:28.44 UTC | 2018-05-16 10:16:18.99 UTC | null | 7,200,083 | null | 146,857 | null | 1 | 54 | jquery|html|scroll|scrolltop | 129,407 | <p>You could just use:</p>
<pre><code><div id="GridDiv">
// gridview inside...
</div>
<a href="#GridDiv">Scroll to top</a>
</code></pre> |
3,137,097 | Check if a string is a valid Windows directory (folder) path | <p>I am trying to determine whether a string input by a user is valid for representing a path to a folder. By valid, I mean formatted properly.</p>
<p>In my application, the folder represents an installation destination. Provided that the folder path <em>is</em> valid, I want to determine if the folder exists, and create it if it does not.</p>
<p>I am currently using <code>IO.Directory.Exists( String path )</code>. I find that this works fine except when the user does not format the string properly. When that happens, this method will return false which indicates that the folder does not exist. But this is a problem because I won't be able to create the folder afterwards.</p>
<p>From my googling I found a suggestion to use a regular expression to check if the format is proper. I have no experience with regular expressions, and am wondering if that is a viable approach. Here's what I found:</p>
<pre><code>Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" );
return r.IsMatch( path );
</code></pre>
<p>Would a regular expression test in combination with <code>Directory.Exists()</code>, give me a <em>good enough</em> method to check if the path is valid and whether it exists? I know this will vary with the OS and other factors, but the program is targeted for <strong>Windows</strong> users only.</p> | 3,137,165 | 8 | 6 | null | 2010-06-29 00:32:35.66 UTC | 26 | 2020-12-07 13:00:40.627 UTC | 2016-12-08 20:58:10.71 UTC | null | 1,497,596 | null | 139,644 | null | 1 | 93 | c#|windows|validation|filesystems|directory | 153,874 | <p>Call <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx" rel="noreferrer"><code>Path.GetFullPath</code></a>; it will throw exceptions if the path is invalid.</p>
<p>To disallow relative paths (such as <code>Word</code>), call <a href="http://msdn.microsoft.com/en-us/library/system.io.path.ispathrooted" rel="noreferrer"><code>Path.IsPathRooted</code></a>.</p> |
2,531,255 | jQuery Tag Editor? | <p>Is there any open source tag editor for jQuery that works like the tag editor in stack overflow?</p> | 11,968,549 | 9 | 1 | null | 2010-03-27 23:02:17.763 UTC | 15 | 2013-02-15 01:24:32.373 UTC | 2013-01-18 21:57:01.99 UTC | null | 127,880 | null | 140,937 | null | 1 | 34 | javascript|jquery|tags | 13,174 | <p>I have been looking at a bunch of options. None of them seemed to fit exactly what I was looking for. Here are are least some of the things I found. </p>
<ul>
<li><a href="https://github.com/aehlke/tag-it/">Tag-it</a></li>
<li><a href="http://webspirited.com/tagit/docs.html">Tagit</a></li>
<li><a href="http://xoxco.com/projects/code/tagsinput/">Xoxco</a></li>
<li><a href="http://tagedit.webwork-albrecht.de/">Tagedit</a></li>
<li><a href="http://widen.github.com/jQuery-Tagit/">Widen Tagit</a></li>
</ul>
<p>Hope it helps</p>
<pre><code>+--------------------+------+-----+-----+-------+-----+
|Toolkit |Tag-it|Tagit|Xoxco|Tagedit|Widen|
+--------------------+------+-----+-----+-------+-----+
|Setting tags |- |+ |+ |? |+ |
|programmatically | | | | | |
+--------------------+------+-----+-----+-------+-----+
|Getting tags out as |+ |+ |- |? |+ |
|an array | | | | | |
+--------------------+------+-----+-----+-------+-----+
|Editting existing |- |- |- |+ |+ |
|tags | | | | | |
+--------------------+------+-----+-----+-------+-----+
|Tab / cursor |- |- |- |- |- |
|selecting existing | | | | | |
|tags | | | | | |
+--------------------+------+-----+-----+-------+-----+
|Sorting tags |- |+ |- |+ |+ |
+--------------------+------+-----+-----+-------+-----+
|Placeholder text |- |- |+ |- |- |
+--------------------+------+-----+-----+-------+-----+
|Supporting comma |- |+ |- |+ |+ |
|inside tags | | | | | |
+--------------------+------+-----+-----+-------+-----+
</code></pre> |
3,067,479 | Determine via C# whether a string is a valid file path | <p>I would like to know how to determine whether string is valid file path.</p>
<p>The file path may or may <em>not</em> exist.</p> | 3,067,600 | 10 | 3 | null | 2010-06-18 05:53:13.203 UTC | 8 | 2020-07-29 10:09:35.483 UTC | 2016-12-08 19:48:39.777 UTC | null | 1,497,596 | null | 279,911 | null | 1 | 52 | c#|.net|validation|path|filesystems | 97,112 | <p>A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).</p>
<p>Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.</p>
<p>And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.</p>
<p>What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Filename" rel="noreferrer">Wikipedia - Filename</a> for an overview of the rules used by different file systems</li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx" rel="noreferrer" title="Naming Files, Paths, and Namespaces">Naming Files, Paths, and Namespaces</a> for windows specific rules</li>
</ul> |
2,487,931 | LLVM C++ IDE for Windows | <p>Is there some C/C++ IDE for Windows, which is <strong>integrated</strong> with the LLVM compiler (and Clang C/C++ analyzer), just like modern Xcode do.</p>
<p>I have Dev-Cpp (it uses outdated GCC) and <a href="https://en.wikipedia.org/wiki/Code::Blocks" rel="noreferrer">Code::Blocks</a> (with some GCC). But GCC gives me very cryptic error messages. I want to get some more user-friendly error messages from the Clang frontend.</p>
<p>Yes, Clang was not able to be used with complex C++ code, but trunk Clang already can compile LLVM itself. So I wonder if is there any of LLVM IDEs in development or in beta versions.</p>
<p>Yes, I can use Clang as other compiler with GCC-compatible IDEs. But is there any IDE, that are <em>integrated</em> with Clang? Clang have a different output format, so the IDE must parse it. Clang can provide IDE parsing of sources. Clang has an analyze option, which must be supported in an IDE. Take a look, e.g <a href="http://iosdevelopertips.com/xcode/static-code-analysis-clang-and-xcode-3-2.html" rel="noreferrer">http://iosdevelopertips.com/xcode/static-code-analysis-clang-and-xcode-3-2.html</a></p>
<p>And the most wanted feature of Clang - is smart auto-completion, so the IDE can suggest only syntaxilly-correct variants, e.g. list only fields of this struct, class.</p>
<p><strong>Results:</strong> (merged from answers):</p>
<ul>
<li>Eclipse with CDT>=8 and with <a href="https://code.google.com/archive/p/llvm4eclipsecdt/" rel="noreferrer">https://code.google.com/archive/p/llvm4eclipsecdt/</a> plugin, from Petri Tuononen (no smart auto-completion)</li>
<li>Vim with vimrc from the LLVM project (smart completion only?) <a href="https://llvm.org/viewvc/llvm-project/llvm/trunk/utils/vim/" rel="noreferrer">https://llvm.org/viewvc/llvm-project/llvm/trunk/utils/vim/</a></li>
<li>Emacs with (smart completion only?) <a href="https://llvm.org/svn/llvm-project/cfe/trunk/utils/clang-completion-mode.el" rel="noreferrer">https://llvm.org/svn/llvm-project/cfe/trunk/utils/clang-completion-mode.el</a></li>
<li>Qt Creator: <a href="https://blog.qt.io/blog/2011/10/19/qt-creator-and-clang/" rel="noreferrer">https://blog.qt.io/blog/2011/10/19/qt-creator-and-clang/</a></li>
<li>CodeLite: <a href="http://www.codelite.org/LiteEditor/ClangIntegration35" rel="noreferrer">http://www.codelite.org/LiteEditor/ClangIntegration35</a></li>
</ul> | 5,979,028 | 13 | 2 | null | 2010-03-21 17:12:53.877 UTC | 42 | 2019-11-27 13:25:03.62 UTC | 2017-07-01 03:52:06.827 UTC | null | 1,033,581 | null | 196,561 | null | 1 | 94 | c++|windows|ide|llvm|clang | 61,593 | <p>LLVM is supported in <strong>Eclipse CDT</strong> via plug-in (<strong>llvm4eclipsecdt</strong>). It is the <strong>only Windows supported IDE supporting LLVM</strong> as far as I know. I am the main author of the plug-in so you can ask any questions related to it.</p>
<p>The plug-in offers the basic functionality for Clang and llvm-gcc compilation and support Linux and Windows (w/ Cygwin & MiNGW). LLVM tools such as assembler, archiver, linker, and static compiler (llc) are configured and can be customized via UI. The plug-in offers all the benefits that IDE can offer such as easy configuration and building with one action. </p>
<p>The only drawback is that it is not ready yet as it lacks of some of the advanced features that LLVM can offer such as Clang analyze and smart auto-completion. The plug-in is also not tested well and may not work perfectly therefore I hope I can get user feedback via mailing list found from Google code development site (listed below). I wish I had time to develop it further. I only develop it in my spare time, which is very limited. I welcome any developers to participate and contribute to the project.</p>
<p>Development site:<br />
<del><a href="http://code.google.com/p/llvm4eclipsecdt/" rel="noreferrer">http://code.google.com/p/llvm4eclipsecdt/</a></del><br />
<a href="https://github.com/TuononenP/llvm4eclipsecdt" rel="noreferrer">https://github.com/TuononenP/llvm4eclipsecdt</a></p>
<p>Eclipse marketplace (100% free & open-source):<br />
<del><a href="http://marketplace.eclipse.org/content/llvm-toolchain-eclipse-cdt" rel="noreferrer">http://marketplace.eclipse.org/content/llvm-toolchain-eclipse-cdt</a></del></p>
<p><b>UPDATE: The plugin is deprecated. Instead install "C/C++ LLVM-Family Compiler Build Support" under Programming Languages using the official Eclipse update site e.g. <a href="http://download.eclipse.org/releases/mars" rel="noreferrer">http://download.eclipse.org/releases/mars</a></b></p> |
2,364,147 | How to get just one file from another branch? | <p>I have a <code>master</code> branch with a file called <code>app.js</code>. I made changes to this file on an <code>experiment</code> branch.</p>
<p>I want to apply only the changes made to <code>app.js</code> from <code>experiment</code> onto the <code>master</code> branch.</p> | 2,364,223 | 14 | 2 | null | 2010-03-02 15:15:18.127 UTC | 424 | 2022-07-25 05:17:03.773 UTC | 2022-07-25 05:17:03.773 UTC | null | 365,102 | null | 253,470 | null | 1 | 1,824 | git|git-branch|git-checkout | 1,082,528 | <pre><code>git checkout master # first get back to master
git checkout experiment -- app.js # then copy the version of app.js
# from branch "experiment"
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/692246/git-how-to-undo-changes-of-one-file">git how to undo changes of one file?</a></p>
<hr />
<h3>Update August 2019, Git 2.23</h3>
<p>With the new <a href="https://stackoverflow.com/a/57066202/6309"><code>git switch</code></a> and <a href="https://stackoverflow.com/a/57066072/6309"><code>git restore</code></a> commands, that would be:</p>
<pre><code>git switch master
git restore --source experiment -- app.js
</code></pre>
<p>By default, only the working tree is restored.<br />
If you want to update the index as well (meaning restore the file content, <em>and</em> add it to the index in one command):</p>
<pre><code>git restore --source experiment --staged --worktree -- app.js
# shorter:
git restore -s experiment -SW -- app.js
</code></pre>
<hr />
<p>As <a href="https://stackoverflow.com/users/46058/jakub-narebski">Jakub Narębski</a> mentions in the comments:</p>
<pre><code>git show experiment:path/to/app.js > path/to/app.js
</code></pre>
<p>works too, except that, as detailed in the SO question "<a href="https://stackoverflow.com/questions/610208/how-to-retrieve-a-single-file-from-specific-revision-in-git/610315#610315">How to retrieve a single file from specific revision in Git?</a>", you need to use the full path from the root directory of the repo.<br />
Hence the path/to/app.js used by Jakub in his example.</p>
<p>As <a href="https://stackoverflow.com/users/7476/frosty">Frosty</a> mentions in the comment:</p>
<blockquote>
<p>you will only get the most recent state of app.js</p>
</blockquote>
<p>But, for <code>git checkout</code> or <code>git show</code>, you can actually reference any revision you want, as illustrated in the SO question "<a href="https://stackoverflow.com/questions/1507300/git-checkout-revision-of-a-file-in-git-gui/1507678#1507678">git checkout revision of a file in git gui</a>":</p>
<pre><code>$ git show $REVISION:$FILENAME
$ git checkout $REVISION -- $FILENAME
</code></pre>
<p>would be the same is $FILENAME is a <strong>full path</strong> of a versioned file.</p>
<p><code>$REVISION</code> can be as shown in <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html" rel="noreferrer"><code>git rev-parse</code></a>:</p>
<pre><code>experiment@{yesterday}:app.js # app.js as it was yesterday
experiment^:app.js # app.js on the first commit parent
experiment@{2}:app.js # app.js two commits ago
</code></pre>
<p>and so on.</p>
<p><a href="https://stackoverflow.com/users/430418/schmijos">schmijos</a> adds <a href="https://stackoverflow.com/questions/2364147/how-to-get-just-one-file-from-another-branch/2364223#comment93480592_2364223">in the comments</a>:</p>
<blockquote>
<p>you also can do this from a stash:</p>
<pre><code>git checkout stash -- app.js
</code></pre>
<p>This is very useful if you're working on two branches and don't want to commit.</p>
</blockquote> |
3,115,191 | Scalable, Delayed PHP Processing | <p>I'm working on an online PHP application that has a need for delayed PHP event. Basically I need to be able to execute arbitrary PHP code x many seconds (but it could be days) after the initial hit to a URL. I need fairly precise execution of these PHP event, also I want it to be fairly scalable. I'm trying to avoid the need to schedule a cron job to run every second. I was looking into <a href="http://gearman.org/" rel="noreferrer">Gearman</a>, but it doesn't seem to provide any ability to schedule events and as I understand, PHP isn't really meant to run as a daemon.</p>
<p><strike>It would be ideal if I could tell some external process to poll a "event checker" url on PHP server at the exact time that the next event should be run. This poll time will need to be able to decreased or increased at will since event can be removed and added to the queue and. Any ideas on an elegant way to accomplish this?</strike> There is simply to much overhead in calling PHP externally (having to parse HTTP request or calling via CLI) to make this idea feasible for my needs.</p>
<p><strike>My current plan is write a PHP daemon that will run the event and interface with it from the PHP server with gearman. The PHP daemon would be build around <a href="http://www.php.net/manual/en/class.splminheap.php" rel="noreferrer">SplMinHeap</a> so hopefully the performance wouldn't be to bad. This idea leaves a bad taste in my mouth and I was wondering if anyone had a better idea?</strike> Ideas changed slightly. Read Edit 2.</p>
<p>EDIT:</p>
<p>I'm creating an online game that evolves players taking turns with variable time limit. I'm using XMPP and BOSH to allow me to push messages to and from my clients, but I've got that part all done and working. Now I'm trying to add an arbitrary event that triggers after play from the client to let the client (and other ppl in the game) that he took to long. I can't use timed trigger on the client side because that would be exploitable (since the client can play by themselves). Hope that helps.</p>
<p>EDIT 2:</p>
<p>Thank you all for your feedback. While I think most of your ideas would work well on small scale, I have a feeling they wouldn't scale very well (external event manager) or lack the exactness this project requires (CRON). Also, in both of those cases they are external pieces which could fail and add complexity to an already complex system.</p>
<p>I personally feel that the only <em>clean</em> solution that meets the requirements for this project is to write a PHP daemon that handles the delayed events. I've begun writing what I think is the <em>first</em> PHP runloop. It handles watching the sockets and executing delayed PHP events. Hopefully when I'm closer to being done with this project I can post up the source, if any of you are interested in it. So far in testing it has shown to be promising solution (no problems with memory leaking or instability).</p>
<p>EDIT 3:
Here is a link to the PHP event loop library called <a href="http://github.com/Wordi/LooPHP" rel="noreferrer">LooPHP</a> for those who are interested.</p>
<p><strong>TL;DR Requirements</strong></p>
<ul>
<li>Call (preferably natively) PHP at a delayed time (ranging from seconds to days)</li>
<li>Handle creation/updating/deletion of events arbitrarily (I'm expecting a high amount of canceled call).</li>
<li>Handle high load of events scheduled (100-1000 a second per server)</li>
<li>Calls should be within one second of it's scheduled time</li>
<li>At this point i'm not open to rewriting the code base into another language (maybe some day I will)</li>
</ul> | 3,115,483 | 15 | 11 | null | 2010-06-25 02:32:57.833 UTC | 13 | 2016-04-17 20:17:13.823 UTC | 2010-07-16 19:54:32.2 UTC | null | 188,044 | null | 188,044 | null | 1 | 21 | php|events|asynchronous|daemon | 6,842 | <p>I think a PHP only solution will be hard(almost impossible) to implement. I came up with two solutions to your problem.</p>
<h2>PHP/Redis solution</h2>
<p>Question asked by Kendall:</p>
<ul>
<li>How stable is redis:</li>
</ul>
<p>Redis is very stable. The developer really writes some clean C code. You should check it out on github ;). Also a lot of big sites are using redis. For example github.They had a really interesting blog <a href="http://github.com/blog/530-how-we-made-github-fast" rel="nofollow noreferrer">post</a> how they made github fast :). Also superfeedr uses <a href="http://superfeedr.posterous.com/redissuperfeedr" rel="nofollow noreferrer">redis</a>. There are a lot more big companies which are using redis ;). I would advise you to google for it ;).</p>
<ul>
<li>How PHP-friendly is redis:</li>
</ul>
<p>PHP is very PHP friendly. A lot of users are writing PHP libraries for redis. The protocol is really simple. You can debug it with telnet ;). Looking quickly predis for example has the blocking pop implemented.</p>
<ul>
<li>how would i remove events:</li>
</ul>
<p>I think you should use something like <a href="http://code.google.com/p/redis/wiki/ZremCommand" rel="nofollow noreferrer">ZRemCommand</a>.</p>
<blockquote>
<p>Redis is an advanced key-value store.
It is similar to memcached but the
dataset is not volatile, and values
can be strings, exactly like in
memcached, but also lists, sets, and
ordered sets. All this data types can
be manipulated with atomic operations
to push/pop elements, add/remove
elements, perform server side union,
intersection, difference between sets,
and so forth. Redis supports different
kind of sorting abilities.</p>
</blockquote>
<p>What I came up with(Pseudo-code....):</p>
<p>processor.php:</p>
<pre><code><?php
######----processer.php
######You should do something like nohup php processor.php enough times for processors to run event.
#$key: should be unique, but should also be used by wakeup.php
while(true) {
$event = blpop($key); #One of the available blocking threads will wakeup and process event
process($event); #You should write process. This could take some time so this process could not be available
zrem($key1, $event); #Remove event after processing it. Added this later!!!!!!
}
</code></pre>
<p>client.php:</p>
<pre><code>######----client.php
######The user/browser I guess should generate these events.
#$key1: should be unique.
#$millis: when event should run
#$event: just the event to work on.
if ("add event") {
zadd($key1, $millis, $event);
} else if ("delete event") {
zremove($key1, $event)
}
#Get event which has to be scheduled first
$first = zrange($key1, 0, 0);
if ($oldfirst <> $first) { #got different first event => notify wakeup.php.
lpush($key2, $first);
}
$oldfirst = $first;
</code></pre>
<p>wakeup.php:</p>
<pre><code>####wakeup.php
#### 1 time do something like nohup php wakeup.php
#http://code.google.com/p/redis/wiki/IntroductionToRedisDataTypes => read sorted set part.
while(true) {
$first = zrange($key1, 0, 0);
$event = blpop($key2, $timeoutTillFirstEvent);
if ($event == nill) {
#Blockingqueue has timedout which means event should be run by 1 of blocking threads.
blpop($key2, $first);
}
}
</code></pre>
<p>Something along the lines of this you could also write a pretty efficient scheduler using PHP(Okay redis is C so kickass fast :)) only and it would be pretty efficient as well :). I would also like to code this solution so stayed tuned ;). I think I could write a usable prototype in a day....</p>
<h2>My java solution</h2>
<p>This morning I think I created a <a href="http://github.com/alfredwesterveld/java-schedule-broadcaster" rel="nofollow noreferrer">java program</a> which you can use for your problem. </p>
<ol>
<li><p><strong>download</strong>:</p>
<p>Visit <a href="http://github.com/alfredwesterveld/java-schedule-broadcaster/downloads" rel="nofollow noreferrer">github's download page</a> to download the jar file(with all dependencies included).</p></li>
<li><p><strong>install</strong>: </p>
<p>java -jar schedule-broadcaster-1.0-SNAPSHOT-jar-with-dependencies-1277709762.jar</p></li>
<li><p><strong><a href="http://gist.github.com/455553" rel="nofollow noreferrer">Run simple PHP snippets</a></strong></p>
<ol>
<li>First <code>php -f scheduler.php</code></li>
<li>Next <code>php -f receiver.php</code></li>
</ol></li>
<li><p><strong><a href="http://github.com/alfredwesterveld/java-schedule-broadcaster/issues" rel="nofollow noreferrer">Questions</a></strong></p>
<p>I created these little snippets so that hopefully you will understand how to use my program. There is also a little bit documentation in the <a href="http://wiki.github.com/alfredwesterveld/java-schedule-broadcaster/" rel="nofollow noreferrer">WIKI</a>.</p></li>
</ol>
<h2>App Engine's TaskQueue</h2>
<p>A quick solution would be to Use Google's app engine task queue which has a reasonable free quota. After that you have to pay for what you use.</p>
<blockquote>
<p>Using this model, App Engine's Task
Queue API allows you to specify tasks
as HTTP Requests (both the contents of
the request as its data, and the
target URL of the request as its code
reference). Programmatically referring
to a bundled HTTP request in this
fashion is sometimes called a "web
hook."</p>
<p>Importantly, the offline nature of the
Task Queue API allows you to specify
web hooks ahead of time, without
waiting for their actual execution.
Thus, an application might create many
web hooks at once and then hand them
off to App Engine; the system will
then process them asynchronously in
the background (by 'invoking' the HTTP
request). This web hook model enables
efficient parallel processing - App
Engine may invoke multiple tasks, or
web hooks, simultaneously.</p>
<p>To summarize, the Task Queue API
allows a developer to execute work in
the background, asynchronously, by
chunking that work into offline web
hooks. The system will invoke those
web hooks on the application's behalf,
scheduling for optimal performance by
possibly executing multiple webhooks
in parallel. This model of granular
units of work, based on the HTTP
standard, allows App Engine to
efficiently perform background
processing in a way that works with
any programming language or web
application framework.</p>
</blockquote> |
2,701,192 | What characters can be used for up/down triangle (arrow without stem) for display in HTML? | <p>I'm looking for a <strong>HTML</strong> or <strong>ASCII</strong> character which is a triangle pointing up or down so that I can use it as a toggle switch.</p>
<p>I found ↑ (<code>&uarr;</code>), and ↓ (<code>&darr;</code>) - but those have a narrow stem. I'm looking just for the HTML arrow "head".</p> | 2,701,226 | 20 | 12 | null | 2010-04-23 18:51:54.08 UTC | 480 | 2022-04-11 22:03:25.93 UTC | 2022-04-11 22:03:25.93 UTC | null | 1,946,501 | null | 323,920 | null | 1 | 1,355 | html|css|unicode|icons|symbols | 1,375,629 | <p>Unicode arrows heads:</p>
<ul>
<li>▲ - U+25B2 BLACK UP-POINTING TRIANGLE</li>
<li>▼ - U+25BC BLACK DOWN-POINTING TRIANGLE</li>
<li>▴ - U+25B4 SMALL BLACK UP-POINTING TRIANGLE</li>
<li>▾ - U+25BE SMALL BLACK DOWN-POINTING TRIANGLE</li>
</ul>
<p>For ▲ and ▼ use <code>&#x25B2;</code> and <code>&#x25BC;</code> respectively if you cannot include Unicode characters directly (use UTF-8!).</p>
<p>Note that the font support for the smaller versions is not as good. Better to use the large versions in smaller font.</p>
<p>More Unicode arrows are at:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode" rel="noreferrer">http://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode</a></li>
<li><a href="http://en.wikipedia.org/wiki/Geometric_Shapes" rel="noreferrer">http://en.wikipedia.org/wiki/Geometric_Shapes</a></li>
</ul>
<p>Lastly, these arrows are not ASCII, including ↑ and ↓: they are Unicode.</p> |
39,969,202 | Convert UPPERCASE string to sentence case in Python | <p>How does one convert an uppercase string to proper sentence-case? Example string:</p>
<pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
</code></pre>
<p>Using <code>titlecase(str)</code> gives me:</p>
<pre><code>"Operator Fail to Properly Remove Solid Waste"
</code></pre>
<p>What I need is:</p>
<pre><code>"Operator fail to properly remove solid waste"
</code></pre>
<p>Is there an easy way to do this?</p> | 39,969,258 | 3 | 0 | null | 2016-10-11 01:33:30.533 UTC | 3 | 2022-04-07 01:50:21.827 UTC | null | null | null | null | 1,860,317 | null | 1 | 53 | python | 41,602 | <p>Let's use an even more appropriate function for this: <a href="https://docs.python.org/2/library/string.html#string.capitalize" rel="noreferrer"><code>string.capitalize</code></a></p>
<pre><code>>>> s="OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
>>> s.capitalize()
'Operator fail to properly remove solid waste'
</code></pre> |
10,458,465 | How to set height of element to match height of another element? | <p>I currently have two columns, with another column in-between them. What I want is to have the left and right columns extend in height as the centre column has more content added to it.</p>
<p>Something to note is that I cannot set an exact height for the parent div and then have the left and right columns set to "height: 100%". This is because there could be only a small amount of content in the centre column, or a lot.</p> | 10,458,536 | 2 | 0 | null | 2012-05-05 03:02:51.553 UTC | 3 | 2020-05-26 14:27:57.943 UTC | 2017-02-01 17:36:01.653 UTC | null | 5,798,798 | null | 1,374,827 | null | 1 | 20 | css|html|height | 80,205 | <p>It looks like you're going to have to implement a Javascript approach. The way I would go about it would be to grab the height of <code>.legs</code> then apply it to <code>.flight_no</code> and <code>.price</code>.</p>
<p>The only other option I can think of would be to "fake it" by giving <code>.flight</code> a background image that would include however your left and right columns are stylistically different, then <code>repeat-y</code> in your CSS. If you do that, the sidebars wouldn't actually have to span the same height.</p>
<p>Something like this, using jQuery, will dynamically set your sidebars to the height of the middle column.</p>
<pre><code>$(document).ready(function() {
$(".flight_no, .price").css("height", $(".legs").height());
});
</code></pre>
<hr>
<p>Edit:</p>
<p>Times have changed -- jQuery is not the juggernaut it once was, and we welcomed Flexbox to the world. See this SO page for column-based solutions:</p>
<p><a href="https://stackoverflow.com/questions/2114757/css-equal-height-columns">CSS - Equal Height Columns?</a></p> |
6,139,425 | Can you hint an array's items type? | <p>This question is linked to <a href="https://stackoverflow.com/questions/308027/can-you-hint-return-types-in-php-5-2-5">this one</a> :</p>
<p>Is it possible to hint the type of the items inside a returned array ?</p>
<p>e.g. :</p>
<pre><code>/**
* MyFunction does a lot of things
*
* @param TClass1 $var1
* @param TClass2 $var2
* @return array[TClass3] //<- I'm trying to express this
*/
function MyFunction( $var1, $var2 ){
...
</code></pre>
<p>I am using NetBeans as an IDE, which takes (like many other PHP IDEs) advantage of the doc blocs above functions to determine the type of returned values.</p>
<p>If I could explain what type is expected inside an array, I could hope for the IDE to be able to offer correct completion for the following case :</p>
<pre><code> $myTab = MyFunction( $foo, $bar );
foreach( $myTab as $itm ){
$itm->myFi| //offer the completion for a TClass3 object
}
</code></pre> | 6,153,912 | 2 | 2 | null | 2011-05-26 13:39:53.303 UTC | 4 | 2014-11-03 17:42:57.967 UTC | 2017-05-23 12:13:57.547 UTC | null | -1 | null | 86,072 | null | 1 | 34 | php|netbeans|return-value|phpdoc|type-hinting | 6,928 | <p>Use</p>
<pre><code>@return TClass3[]
</code></pre>
<p>or</p>
<pre><code>@return TClass3[]|TClass3
</code></pre> |
18,261,214 | Load external js file in another js file | <p>I have this file include in my html and I want to call it from another javascript.
Please suggest me how should I do it?</p>
<pre><code><script type="text/javascript" src="js.js">/*
old:123
new: 456*/
</script>
</code></pre>
<p>I want to include it in my js file, not in the html.</p> | 18,261,253 | 1 | 5 | null | 2013-08-15 20:28:19.433 UTC | 8 | 2019-04-09 19:57:40.153 UTC | 2013-08-15 22:07:09.447 UTC | null | 2,539,720 | null | 1,520,210 | null | 1 | 27 | javascript|jquery | 71,299 | <p>If you want to include a JS file in a JS you can use <a href="https://api.jquery.com/jQuery.getScript/" rel="noreferrer">jQuery.getScript()</a> for that</p>
<pre><code>$.getScript('another_file.js', function() {
//script is loaded and executed put your dependent JS here
});
</code></pre>
<p>And if you cannot use jQuery</p>
<pre><code>var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
</code></pre>
<p><a href="https://stackoverflow.com/a/4634669/1893629">Source</a></p>
<p>For more information about the current CSP3 spec from W3 look <a href="https://www.w3.org/TR/CSP3/#csp-header" rel="noreferrer">here</a>.</p> |
33,415,992 | Ansible: How to iterate over a role with an array? | <p>Is it possible to call a role multiple times in a loop like this:</p>
<pre><code>vars:
my_array:
- foo
- bar
- baz
roles:
- role: foobar
with_items: my_array
</code></pre>
<p>How can we do this?</p> | 40,852,606 | 5 | 0 | null | 2015-10-29 13:45:53.097 UTC | 8 | 2021-10-18 09:08:54.42 UTC | 2017-12-20 13:51:15.01 UTC | null | 1,245,190 | null | 828,473 | null | 1 | 39 | ansible | 48,599 | <p>Now supported as of <a href="https://github.com/ansible/ansible/issues/17966" rel="noreferrer">Ansible 2.3.0</a>:</p>
<pre><code>- name: myrole
with_items:
- "aone"
- "atwo"
include_role:
name: myrole
vars:
thing: "{{ item }}"
</code></pre> |
32,566,416 | Change format of md-datepicker in Angular Material with momentjs | <p>Angular material introduced a new date picker component found <a href="https://material.angularjs.org/HEAD/#/demo/material.components.datepicker">here</a>.</p>
<p>I want the date returned by this component to be in the format <em>yyy-mm-dd</em> but I am not sure how is this done. By searching I found that <code>$mdDateLocaleProvider</code> can be used, but I could not find an example of using it.</p>
<p>Can someone show me a working example of formatting the date returned by <code>md-datepicker</code>?</p> | 32,566,653 | 13 | 0 | null | 2015-09-14 13:44:17.607 UTC | 10 | 2019-03-22 11:03:27.527 UTC | 2019-02-07 22:52:57.49 UTC | null | 5,490,782 | null | 4,045,121 | null | 1 | 59 | javascript|angularjs|localization|angular-material|momentjs | 94,678 | <p>There is a documentation for <a href="https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider" rel="noreferrer"><code>$mdDateLocaleProvider</code></a> in the Angular Material docs.</p>
<pre><code>angular.module('app').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
});
</code></pre>
<p>If you don't use moment.js, substitute the code inside <code>formatDate</code> for whatever you wish to use to format the date.</p>
<p><a href="http://codepen.io/anon/pen/vNLyGJ" rel="noreferrer">Here</a> is a CodePen example based on the samples from Angular Material docs.</p> |
47,344,183 | How to align <td rowspan ="value"> value to center vertically? | <p>I need to align <code>td</code> cell value to center, both horizontally and vertically. <code><td></code> has a <code>rowspan</code> attribute.</p>
<p>The output right now is like:</p>
<pre><code>A | B | C | D
1 | 2 | 3 | 4
1 | 2 | 3 |
1 | 2 | 3 |
</code></pre>
<p>Desired:</p>
<pre><code>A | B | C | D
1 | 2 | 3 |
1 | 2 | 3 | 4
1 | 2 | 3 |
1 | 2 | 3 |
</code></pre> | 47,344,360 | 10 | 1 | null | 2017-11-17 05:59:09.387 UTC | 1 | 2020-04-16 15:15:12.47 UTC | 2019-11-20 23:16:41.233 UTC | null | 3,345,644 | null | 6,751,456 | null | 1 | 20 | html|css | 44,063 | <p>Try :</p>
<pre><code><td style="vertical-align : middle;text-align:center;">
</code></pre> |
21,322,182 | How to store ECDSA private key in Go | <p>I am using the <code>ecdsa.GenerateKey</code> method to generate a private/public key pair in Go. I would like to store the private key in a file on the users computer, and load it whenever the program starts. There is a method <code>elliptic.Marshal</code> that marshals the public key, but nothing for the private key. Should I simply roll my own, or is there a recommended way to store the private key?</p> | 41,315,404 | 3 | 1 | null | 2014-01-24 00:28:51.957 UTC | 12 | 2018-12-04 22:36:10.27 UTC | null | null | null | null | 58,109 | null | 1 | 24 | go|ecdsa | 15,439 | <p>Here is a code sample that demonstrates encoding and decoding of keys in Go. It helps to know that you need to connect couple of steps. Crypto algorithm is the fist step, in this case ECDSA key. Then you need standard encoding, x509 is most commontly used standard. Finally you need a file format, PEM is again commonly used one. This is currently most commonly used combination, but feel free to substitute any other algoriths or encoding.</p>
<pre><code>func encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string) {
x509Encoded, _ := x509.MarshalECPrivateKey(privateKey)
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey)
pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})
return string(pemEncoded), string(pemEncodedPub)
}
func decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
block, _ := pem.Decode([]byte(pemEncoded))
x509Encoded := block.Bytes
privateKey, _ := x509.ParseECPrivateKey(x509Encoded)
blockPub, _ := pem.Decode([]byte(pemEncodedPub))
x509EncodedPub := blockPub.Bytes
genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub)
publicKey := genericPublicKey.(*ecdsa.PublicKey)
return privateKey, publicKey
}
func test() {
privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
publicKey := &privateKey.PublicKey
encPriv, encPub := encode(privateKey, publicKey)
fmt.Println(encPriv)
fmt.Println(encPub)
priv2, pub2 := decode(encPriv, encPub)
if !reflect.DeepEqual(privateKey, priv2) {
fmt.Println("Private keys do not match.")
}
if !reflect.DeepEqual(publicKey, pub2) {
fmt.Println("Public keys do not match.")
}
}
</code></pre> |
35,401,041 | Concatenation of 2 1D `numpy` Arrays Along 2nd Axis | <p>Executing</p>
<pre><code>import numpy as np
t1 = np.arange(1,10)
t2 = np.arange(11,20)
t3 = np.concatenate((t1,t2),axis=1)
</code></pre>
<p>results in a </p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-264-85078aa26398>", line 1, in <module>
t3 = np.concatenate((t1,t2),axis=1)
IndexError: axis 1 out of bounds [0, 1)
</code></pre>
<p>why does it report that axis 1 is out of bounds?</p> | 35,401,356 | 5 | 0 | null | 2016-02-15 03:26:46.83 UTC | 4 | 2019-06-17 20:03:52.417 UTC | 2019-06-17 20:03:52.417 UTC | null | 195,787 | null | 4,139,744 | null | 1 | 22 | arrays|numpy|concatenation|numpy-ndarray|index-error | 62,893 | <p>Your title explains it - a 1d array does not have a 2nd axis!</p>
<p>But having said that, on my system as on <code>@Oliver W.</code>s, it does not produce an error</p>
<pre><code>In [655]: np.concatenate((t1,t2),axis=1)
Out[655]:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18,
19])
</code></pre>
<p>This is the result I would have expected from <code>axis=0</code>:</p>
<pre><code>In [656]: np.concatenate((t1,t2),axis=0)
Out[656]:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18,
19])
</code></pre>
<p>It looks like <code>concatenate</code> ignores the <code>axis</code> parameter when the arrays are 1d. I don't know if this is something new in my 1.9 version, or something old.</p>
<p>For more control consider using the <code>vstack</code> and <code>hstack</code> wrappers that expand array dimensions if needed:</p>
<pre><code>In [657]: np.hstack((t1,t2))
Out[657]:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18,
19])
In [658]: np.vstack((t1,t2))
Out[658]:
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9],
[11, 12, 13, 14, 15, 16, 17, 18, 19]])
</code></pre> |
35,641,994 | Accessing local filesystem in AWS lambda | <p>Is it possible to access local filesystem in a AWS lambda function? If so, is there any downside to doing so?</p> | 35,642,189 | 2 | 0 | null | 2016-02-26 01:55:02.113 UTC | 1 | 2019-05-20 17:28:39.733 UTC | null | null | null | null | 5,982,369 | null | 1 | 42 | aws-lambda | 36,863 | <p>It is possible. I have python function that does something like</p>
<pre><code> localFilename = '/tmp/{}'.format(os.path.basename(key))
s3.download_file(Bucket=bucket, Key=key, Filename=localFilename)
inFile = open(localFilename, "r")
</code></pre>
<p>Be sure you are using it for temporary storage and not to maintain any state.
Depends on what you are trying to do.</p> |
29,958,143 | What are en0, en1, p2p, and so on, that are displayed after executing ifconfig? | <p>When I type <code>ifconfig</code> on my Mac terminal, several information is printed. But I can't understand what they are. Can anyone briefly tell me what they are? What are <code>lo0</code>, <code>gif0</code>, <code>en0</code>, and so on?</p>
<p>Here is the results of my terminal.</p>
<pre><code> Last login: Wed Apr 29 21:22:21 on ttys000
gim-yeongdeog-ui-MacBook-Air:~ KimYoungDirk$ ifconfig
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 64:76:ba:ae:a3:02
inet6 fe80::6676:baff:feae:a302%en0 prefixlen 64 scopeid 0x4
inet 172.30.7.47 netmask 0xffff0000 broadcast 172.30.255.255
nd6 options=1<PERFORMNUD>
media: autoselect
status: active
en1: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 32:00:1b:3e:80:00
media: autoselect <full-duplex>
status: inactive
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 06:76:ba:ae:a3:02
media: autoselect
status: inactive
awdl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1452
ether 0e:f1:59:ca:a5:30
inet6 fe80::cf1:59ff:feca:a530%awdl0 prefixlen 64 scopeid 0x7
nd6 options=1<PERFORMNUD>
media: autoselect
status: active
bridge0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether 66:76:ba:ea:38:00
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en1 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 5 priority 0 path cost 0
nd6 options=1<PERFORMNUD>
media: <unknown type>
status: inactive
gim-yeongdeog-ui-MacBook-Air:~ KimYoungDirk$
</code></pre> | 55,232,331 | 3 | 1 | null | 2015-04-30 02:46:18.283 UTC | 12 | 2021-11-22 07:44:52.203 UTC | 2018-12-02 11:35:59.813 UTC | null | 3,924,118 | null | 4,836,234 | null | 1 | 43 | macos|terminal|ifconfig | 45,285 | <p>In arbitrary order of my familarity / widespread relevance:</p>
<p><code>lo0</code> is loopback.</p>
<p><code>en0</code> at one point "ethernet", now is WiFi (and I have no idea what extra <code>en1</code> or <code>en2</code> are used for).</p>
<p><code>fw0</code> is the FireWire network interface.</p>
<p><code>stf0</code> is an <a href="https://www.freebsd.org/cgi/man.cgi?gif(4)" rel="noreferrer">IPv6 to IPv4 tunnel interface</a> to support <a href="http://en.wikipedia.org/wiki/6to4" rel="noreferrer">the transition</a> from IPv4 to the IPv6 standard.</p>
<p><code>gif0</code> is a more <a href="https://www.freebsd.org/cgi/man.cgi?gif(4)" rel="noreferrer">generic tunneling interface</a> [46]-to-[46]. </p>
<p><code>awdl0</code> is <a href="https://stackoverflow.com/questions/19587701/what-is-awdl-apple-wireless-direct-link-and-how-does-it-work">Apple Wireless Direct Link</a></p>
<p><code>p2p0</code> is related to AWDL features. Either as an old version, or virtual interface with different semantics than <code>awdl</code>. </p>
<hr>
<p>Note also, </p>
<ul>
<li>the "Network" panel in System Preferences to see what network devices "exist" or "can exist" with current configuration. </li>
<li>many VPNs will add additional devices, often "utun#" or "utap#" following <a href="https://en.wikipedia.org/wiki/TUN/TAP" rel="noreferrer">TUN/TAP (L3/L2)</a> virtual networking devices. </li>
<li>use <code>netstat -nr</code> to see how traffic is currently routed via network devices according to destination.</li>
<li>interface naming conventions started in BSD were retained in OS X / macOS, and now there also additions.</li>
</ul>
<p>Also answered in part on Apple SE <a href="https://apple.stackexchange.com/a/212202/15936">here</a> and <a href="https://apple.stackexchange.com/a/47481/15936">there</a>.</p> |
8,915,630 | iOS - UIImageView - how to handle UIImage image orientation | <p>Is it possible to setup <code>UIImageView</code> to handle image orientation? When I set the <code>UIImageView</code> to image with orientation <em>RIGHT</em> (it is photo from camera roll), the image is rotated to right, but I want to show it in proper orientation, as it was taken.</p>
<p>I know I can rotate image data but it is possible to do it more elegant?</p> | 8,915,809 | 14 | 0 | null | 2012-01-18 18:49:38.827 UTC | 39 | 2022-01-22 23:46:30.217 UTC | 2019-11-20 13:05:49.3 UTC | null | 10,607,772 | null | 329,242 | null | 1 | 85 | ios|uiimageview|uiimage|orientation | 114,264 | <p>If I understand, what you want to do is disregard the orientation of the UIImage? If so then you could do this:</p>
<pre><code>UIImage *originalImage = [... whatever ...];
UIImage *imageToDisplay =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:[originalImage scale]
orientation: UIImageOrientationUp];
</code></pre>
<p>So you're creating a new UIImage with the same pixel data as the original (referenced via its CGImage property) but you're specifying an orientation that doesn't rotate the data.</p> |
48,048,299 | Angular 5 Scroll to top on every Route click | <p>I am using Angular 5. I have a dashboard where I have few sections with small content and few sections with so large content that I am facing a problem when changing router while going to top. Every time I need to scroll to go to top.</p>
<p>How can I solve this issue so that when I change the router, my view always stay at the top?</p> | 48,048,822 | 22 | 1 | null | 2018-01-01 08:46:48.033 UTC | 41 | 2022-09-23 17:43:27.767 UTC | 2022-01-04 12:59:14.173 UTC | null | 8,839,059 | null | 5,330,809 | null | 1 | 169 | javascript|angular|typescript|scrolltop|angular-router | 238,661 | <p>There are some solutions, make sure to check them all :)</p>
<hr>
<p><strong>Option1:</strong></p>
<p>The router outlet will emit the <code>activate</code> event any time a new component is being instantiated, so we could use <code>(activate)</code> to scroll (for example) to the top:</p>
<p><strong>app.component.html</strong></p>
<pre><code><router-outlet (activate)="onActivate($event)"></router-outlet>
</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code>onActivate(event) {
// window.scroll(0,0);
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}
</code></pre>
<p>As the smooth scroll is not implemented well in Safari, use, for exemple, <a href="https://stackoverflow.com/a/26158508/5468463">this solution</a> for a smooth scroll:</p>
<pre><code>onActivate(event) {
let scrollToTop = window.setInterval(() => {
let pos = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
</code></pre>
<hr>
<p>If you wish to be selective, say not every component should trigger the scrolling, you can check it in an <code>if</code> statement like this:</p>
<pre><code>onActivate(e) {
if (e.constructor.name)==="login"{ // for example
window.scroll(0,0);
}
}
</code></pre>
<hr>
<p><strong>Option2:</strong></p>
<p>Since Angular6.1, we can also use <code>{ scrollPositionRestoration: 'enabled' }</code> on eagerly loaded modules and it will be applied to all routes:</p>
<pre><code>RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
</code></pre>
<p>It will also do the smooth scrolling, already. However this has the inconvenient for doing it on every routing.</p>
<hr>
<p><strong>Option3:</strong></p>
<p>An other solution is to do the top scrolling on router animation. Add this in every transition where you want to scroll to the top:</p>
<pre><code>query(':enter, :leave', style({ position: 'fixed' }), { optional: true })
</code></pre> |
26,966,652 | Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model | <p>I have very basic problem. In L4 thes below methods worked out of the box, so now I am lost. Please help. A few days ago I started a Laravel 5.0 project. I have now fresh, clean installation.</p>
<p>Problem 1: When I try to get anything from database</p>
<pre><code>$headquote = DB::table('quotation_texts')->find(176);
</code></pre>
<p>I get this:</p>
<pre><code>Class 'App\Http\Controllers\DB' not found
</code></pre>
<p>Problem 2: Before I cloned the User.php Model, changed Class name to "Quotation". Below is the content of file Quotations.php put in App root folder:</p>
<pre><code><?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Quotation extends Model {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'quotation_texts';
}
</code></pre>
<p>Any attempt to use the model </p>
<pre><code>$headquote = Quotation::find(176);
</code></pre>
<p>ends up with this:</p>
<pre><code>Class 'App\Http\Controllers\Quotation' not found
</code></pre>
<p>Any ideas how I could resolve the issue? </p> | 26,967,460 | 7 | 1 | null | 2014-11-17 06:15:51.353 UTC | 11 | 2020-04-21 22:01:01.36 UTC | 2014-11-17 07:19:31.663 UTC | null | 3,593,996 | null | 4,209,866 | null | 1 | 57 | php|laravel|namespaces|models|laravel-5 | 182,222 | <p>The problem here are PHP namespaces. You need to learn how to use them. As your controller are in <code>App\Http\Controllers</code> namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add <code>use</code> statement at the beginning of file (before class definition). </p>
<p>So in your case you could use:</p>
<pre><code>$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);
</code></pre>
<p>or add in your controller class <code>use</code> statement so the beginning of your controller class could look like this:</p>
<pre><code><?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
</code></pre>
<p>For more information about namespaces you could look at <a href="https://stackoverflow.com/questions/24607045/how-to-use-objects-from-other-namespaces-and-how-to-import-namespaces-in-php/24607087">How to use objects from other namespaces and how to import namespaces in PHP</a> or <a href="http://php.net/manual/en/language.namespaces.rationale.php" rel="noreferrer">namespaces in PHP manual</a></p> |
1,120,228 | How to dynamically call a class' method in .NET? | <p>How to pass a class and a method name as <em>strings</em> and invoke that class' method?</p>
<p>Like</p>
<pre><code>void caller(string myclass, string mymethod){
// call myclass.mymethod();
}
</code></pre>
<p>Thanks</p> | 1,120,238 | 3 | 0 | null | 2009-07-13 15:38:19.18 UTC | 10 | 2009-07-13 16:23:20.523 UTC | 2009-07-13 15:43:35.127 UTC | null | 82 | null | 42,636 | null | 1 | 14 | c#|reflection | 23,060 | <p>You will want to use <a href="http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx" rel="noreferrer">reflection</a>.</p>
<p>Here is a simple example:</p>
<pre><code>using System;
using System.Reflection;
class Program
{
static void Main()
{
caller("Foo", "Bar");
}
static void caller(String myclass, String mymethod)
{
// Get a type from the string
Type type = Type.GetType(myclass);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);
}
}
class Foo
{
public void Bar()
{
Console.WriteLine("Bar");
}
}
</code></pre>
<p>Now this is a <em>very</em> simple example, devoid of error checking and also ignores bigger problems like what to do if the type lives in another assembly but I think this should set you on the right track.</p> |
1,274,405 | How to create new folder? | <p>I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.</p>
<p>Suppose I have given folder path like <code>"C:\Program Files\alex"</code> and <code>alex</code> folder doesn't exist then program should create <code>alex</code> folder and should put output information in the <code>alex</code> folder.</p> | 1,274,465 | 3 | 1 | null | 2009-08-13 20:33:50.52 UTC | 67 | 2017-09-26 02:20:00.187 UTC | 2013-07-02 08:42:14.097 UTC | null | 807,090 | alex | null | null | 1 | 271 | python|mkdir | 568,902 | <p>You can create a folder with <a href="http://docs.python.org/3/library/os.html?highlight=os.makedirs#os.makedirs" rel="noreferrer">os.makedirs()</a><br>
and use <a href="http://docs.python.org/3/library/os.path.html?highlight=os.path.exists#os.path.exists" rel="noreferrer">os.path.exists()</a> to see if it already exists:</p>
<pre><code>newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
</code></pre>
<p>If you're trying to make an installer: <a href="http://www.advancedinstaller.com/" rel="noreferrer">Windows Installer</a> does a lot of work for you.</p> |
617,706 | Passing an "in" list via stored procedure | <p>How can I construct a stored procedure that will allow me to pass (for example) an <code>@IDList</code> so that I can write:</p>
<pre><code>Select * from Foo Where ID in @IDList
</code></pre>
<p>Is this doable?</p> | 617,736 | 3 | 1 | null | 2009-03-06 04:51:39.007 UTC | 1 | 2016-01-26 14:54:40.56 UTC | 2016-01-26 14:54:40.56 UTC | Mitch Wheat | 419,956 | peiklk | 72,852 | null | 1 | 18 | sql-server|tsql|stored-procedures | 69,661 | <p>see this answer...</p>
<p><a href="https://stackoverflow.com/questions/43249/t-sql-stored-procedure-that-accepts-multiple-id-values/43767#43767">T-SQL stored procedure that accepts multiple Id values</a></p> |
6,798,699 | Monad instance for binary tree | <p>I built binary tree with:</p>
<pre><code>data Tree a = Empty
| Node a (Tree a) (Tree a)
deriving (Eq, Ord, Read, Show)
</code></pre>
<p>How can i make Monad type class instance for this tree? And can i make it on not?</p>
<p>i try:</p>
<pre><code>instance Monad Tree where
return x = Node x Empty Empty
Empty >>= f = Empty
(Node x Empty Empty) >>= f = f x
</code></pre>
<p>But i can't make (>>=) for Node x left right. </p>
<p>Thank you. </p> | 6,799,885 | 1 | 2 | null | 2011-07-23 06:26:34.087 UTC | 11 | 2012-08-24 06:44:01.303 UTC | null | null | null | null | 274,299 | null | 1 | 28 | haskell|tree|monads | 6,884 | <p>There is no (good) monad for the type you just described, exactly. It would require rebalancing the tree and merging together the intermediate trees that are generated by the bind, and you can't rebalance based on any information in 'a' because you know nothing about it.</p>
<p>However, there is a similar tree structure</p>
<pre><code>data Tree a = Tip a | Bin (Tree a) (Tree a)
</code></pre>
<p>which admits a monad</p>
<pre><code>instance Monad Tree where
return = Tip
Tip a >>= f = f a
Bin l r >>= f = Bin (l >>= f) (r >>= f)
</code></pre>
<p>I talked about this and other tree structures <a href="http://comonad.com/reader/2010/finger-trees/">a year or two back at Boston Haskell</a> as a lead-in to talking about finger trees. The slides there may be helpful in exploring the difference between leafy and traditional binary trees.</p>
<p>The reason I said there is no good monad, is that any such monad would have to put the tree into a canonical form for a given number of entries to pass the monad laws or quotient out some balance concerns by not exposing the constructors to the end user, but doing the former would require much more stringent reordering than you get for instance from an AVL or weighted tree. </p> |
35,070,217 | What technology does Google Drive use to get real-time updates? | <p>What technology does Google Drive use to do real-time?</p>
<p>When I type in a Google Drive document that is being accessed by multiple users, the Chrome Developer Tools Network tab shows that there are no WebSockets.</p>
<p>I see that the two most frequent types of AJAX call have either "bind?" or "save?" in the URL. "save?" POST requests are made every time I type, which makes sense- normal AJAX for sending updates to the server.</p>
<p>When another user types, the most recent "bind?" GET call stays open, and the amount of data transferred over that connection increases. Periodically, "bind?"s are closed and new ones open up, and the logic seems to be some function of duration and data size. </p>
<p>This isn't long-polling, since when the server sends updates it doesn't complete the response.</p>
<p>This doesn't seem to be server-sent events, since the content-type is "text/plain" instead of "text/stream".</p>
<p>Is there a name for what Google is doing? If so, how can I try implementing this?</p>
<p><a href="https://i.stack.imgur.com/AqkMu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AqkMu.png" alt="Chrome Dev Tools - editing a Google Drive document"></a></p> | 37,514,952 | 2 | 1 | null | 2016-01-28 19:23:35.247 UTC | 30 | 2022-01-06 09:42:01.887 UTC | null | null | null | null | 2,482,570 | null | 1 | 61 | websocket|real-time|long-polling|server-sent-events | 12,211 | <h2>Is there a name for Google's solution for real-time updates in Drive (such as "long polling" or "sockets")?</h2>
<p>It didn't have a name until now. I'll call it "no-polling," to contrast with polling and long-polling.</p>
<p>With polling, the client periodically sends queries for new data.</p>
<p>With long-polling, the client queries for data, and the server holds onto the request, ending the response with the updates when there are updates.</p>
<p>No-polling (what Google Drive does) takes advantage of how the browser can read data from the body of a request before the request is complete. So as collaborators do more typing and edits, the server appends more data to the current request. If certain limits are met (length of the content or duration of the request), the request completes, and the client initiates a new request with the server.</p>
<h2>How can I try implementing this?</h2>
<p>For the client to send updates to the server: this can be done with normal POSTs.</p>
<p>For the client to subscribe to updates from the server:</p>
<ul>
<li><p>The client sends a GET for an update stream, then starts reading the body of the response before the response is complete.</p>
<blockquote>
<p>XHR objects can emit <a href="https://developer.mozilla.org/en-US/docs/Web/Events/progress" rel="noreferrer"><code>progress</code></a> events before the request is complete. The (partial) response is accessible using <code>xhr.responseText</code>. ~~There's no simple way to watch for progress with <code>fetch</code> <a href="https://github.com/whatwg/fetch/issues/21" rel="noreferrer">yet</a> (as of May 2016).~~ When using <code>fetch</code> one can watch for progress by <a href="https://fetch.spec.whatwg.org/#concept-body" rel="noreferrer">consuming the res.body ReadableStream</a>.</p>
</blockquote></li>
<li><p>The client should initiate a new request when the current request ends.</p></li>
</ul>
<p>The server has to:</p>
<ul>
<li>Keep track of which clients are subscribed to which update streams.</li>
<li>When a request comes in for a particular update stream, write data to the response, but don't complete the response until the amount of data gets large or a timeout is met.</li>
</ul>
<p>No-polling seems superior to long-polling, in my opinion, though I haven't played with it much. Long-polling forces a trade-off between latency and message size (given a constant rate of updates), a trade-off no-polling doesn't have to make. Another disadvantage of long-polling is that it can lead to many HTTP requests, paying the overhead of HTTP each time.</p>
<p>No-polling's big advantage over WebSockets is that no-polling is supported by every browser, though WebSocket support is pretty good — <a href="http://caniuse.com/#search=websocket" rel="noreferrer">IE10+</a>.</p> |
28,604,363 | JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null') | <p>We have the following string which is a valid JSON written to a file on HDFS. </p>
<pre><code>{
"id":"tag:search.twitter.com,2005:564407444843950080",
"objectType":"activity",
"actor":{
"objectType":"person",
"id":"id:twitter.com:2302910022",
"link":"http%3A%2F%2Fwww.twitter.com%2Fme7me4610012",
"displayName":"",
"postedTime":"2014-01-21T11:06:06.000Z",
"image":"https%3A%2F%2Fpbs.twimg.com%2Fprofile_images%2F563125491159162881%2FfypkHK3M_normal.jpeg",
"summary":"ضًـأّيِّعٌهّ أّروٌأّحًنِأّ تٌـشُـتٌـهّـيِّ مًنِ يِّفُـهّـمًهّـأّ فُـقُط حسابي بالإنستقرام lloooo_20",
"links":[
{
"href":null,
"rel":"me"
}
],
"friendsCount":10503,
"followersCount":10325,
"listedCount":12,
"statusesCount":84957,
"twitterTimeZone":null,
"verified":false,
"utcOffset":null,
"preferredUsername":"me7me4610012",
"languages":[
"ar"
],
"favoritesCount":17
},
"verb":"share",
"postedTime":"2015-02-08T12:56:35.000Z",
"generator":{
"displayName":"Twitter for Android",
"link":"http%3A%2F%2Ftwitter.com%2Fdownload%2Fandroid"
},
"provider":{
"objectType":"service",
"displayName":"Twitter",
"link":"http%3A%2F%2Fwww.twitter.com"
},
"link":"http%3A%2F%2Ftwitter.com%2Fme7me4610012%2Fstatuses%2F564407444843950080",
"body":"RT @sckud1: فيديو: إمام يرفض بغضب الصلاة على أحد قتلى حزب الله في سوريا بسبب إطلاق النار: ماعاد http%3A%2F%2Ft.co%2FC55SaQKmUV http%3A%2F%2Ft.co%2Ft5TjIln…",
"object":{
"id":"tag:search.twitter.com,2005:564407126526013440",
"objectType":"activity",
"actor":{
"objectType":"person",
"id":"id:twitter.com:462268717",
"link":"http%3A%2F%2Fwww.twitter.com/sckud1",
"displayName":"صفق الهوى",
"postedTime":"2012-01-12T19:24:17.000Z",
"image":"https%3A%2F%2Fpbs.twimg.com%2Fprofile_images%2F508424482885615616%2FmPBGZBPx_normal.jpeg",
"summary":"اعلانك في سوق الخليج يحقق لك الوصول الى اكثر من مليون متابع خليجي http%3A%2F%2Fmarketgulf.com",
"links":[
{
"href":"http%3A%2F%2Fmarketgulf.com",
"rel":"me"
}
],
"friendsCount":435237,
"followersCount":464951,
"listedCount":708,
"statusesCount":1071685,
"twitterTimeZone":"Riyadh",
"verified":false,
"utcOffset":"10800",
"preferredUsername":"sckud1",
"languages":[
"ar"
],
"location":{
"objectType":"place",
"displayName":"Made in K S A"
},
"favoritesCount":77
},
"verb":"post",
"postedTime":"2015-02-08T12:55:19.000Z",
"generator":{
"displayName":"Tweet Old Post",
"link":"http%3A%2F%2Fwww.ajaymatharu.com%2F"
},
"provider":{
"objectType":"service",
"displayName":"Twitter",
"link":"http%3A%2F%2Fwww.twitter.com"
},
"link":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatuses%2F564407126526013440",
"body":"فيديو: إمام يرفض بغضب الصلاة على أحد قتلى حزب الله في سوريا بسبب إطلاق النار: ماعاد http%3A%2F%2Ft.co%2FC55SaQKmUV http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"object":{
"objectType":"note",
"id":"object:search.twitter.com,2005:564407126526013440",
"summary":"فيديو: إمام يرفض بغضب الصلاة على أحد قتلى حزب الله في سوريا بسبب إطلاق النار: ماعاد http%3A%2F%2Ft.co%2FC55SaQKmUV http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"link":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatuses%2F564407126526013440",
"postedTime":"2015-02-08T12:55:19.000Z"
},
"favoritesCount":0,
"twitter_entities":{
"hashtags":[
],
"trends":[
],
"urls":[
{
"url":"http%3A%2F%2Ft.co%2FC55SaQKmUV",
"expanded_url":"http%3A%2F%2Fwww.hasterya.com%2Farchives%2F34688utm_source%3DReviveOldPost%26utm_medium%3Dsocial%26utm_campaign%3DReviveOldPost",
"display_url":"hasterya.com/archives/34688…",
"indices":[
85,
107
]
}
],
"user_mentions":[
],
"symbols":[
],
"media":[
{
"id":564407126341468160,
"id_str":"564407126341468160",
"indices":[
108,
130
],
"media_url":"http%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"media_url_https":"https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"url":"http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"display_url":"pic.twitter.com/t5TjIlnZgN",
"expanded_url":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatus%2F564407126526013440%2Fphoto%2F1",
"type":"photo",
"sizes":{
"large":{
"w":320,
"h":180,
"resize":"fit"
},
"thumb":{
"w":150,
"h":150,
"resize":"crop"
},
"small":{
"w":320,
"h":180,
"resize":"fit"
},
"medium":{
"w":320,
"h":180,
"resize":"fit"
}
}
}
]
},
"twitter_extended_entities":{
"media":[
{
"id":564407126341468160,
"id_str":"564407126341468160",
"indices":[
108,
130
],
"media_url":"http%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"media_url_https":"https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"url":"http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"display_url":"pic.twitter.com/t5TjIlnZgN",
"expanded_url":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatus%2F564407126526013440%2Fphoto%2F1",
"type":"photo",
"sizes":{
"large":{
"w":320,
"h":180,
"resize":"fit"
},
"thumb":{
"w":150,
"h":150,
"resize":"crop"
},
"small":{
"w":320,
"h":180,
"resize":"fit"
},
"medium":{
"w":320,
"h":180,
"resize":"fit"
}
}
}
]
},
"twitter_filter_level":"low",
"twitter_lang":"ar"
},
"favoritesCount":0,
"twitter_entities":{
"hashtags":[
],
"trends":[
],
"urls":[
{
"url":"http%3A%2F%2Ft.co%2FC55SaQKmUV",
"expanded_url":"http%3A%2F%2Fwww.hasterya.com%2Farchives%2F34688utm_source%3DReviveOldPost%26utm_medium%3Dsocial%26utm_campaign%3DReviveOldPost",
"display_url":"hasterya.com/archives/34688…",
"indices":[
97,
119
]
}
],
"user_mentions":[
{
"screen_name":"sckud1",
"name":"صفق الهوى",
"id":462268717,
"id_str":"462268717",
"indices":[
3,
10
]
}
],
"symbols":[
],
"media":[
{
"id":564407126341468160,
"id_str":"564407126341468160",
"indices":[
139,
140
],
"media_url":"http%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"media_url_https":"https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"url":"http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"display_url":"pic.twitter.com/t5TjIlnZgN",
"expanded_url":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatus%2F564407126526013440%2Fphoto%2F1",
"type":"photo",
"sizes":{
"large":{
"w":320,
"h":180,
"resize":"fit"
},
"thumb":{
"w":150,
"h":150,
"resize":"crop"
},
"small":{
"w":320,
"h":180,
"resize":"fit"
},
"medium":{
"w":320,
"h":180,
"resize":"fit"
}
},
"source_status_id":564407126526013440,
"source_status_id_str":"564407126526013440"
}
]
},
"twitter_extended_entities":{
"media":[
{
"id":564407126341468160,
"id_str":"564407126341468160",
"indices":[
139,
140
],
"media_url":"http%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"media_url_https":"https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FB9UtSoJIQAA07-r.jpg",
"url":"http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"display_url":"pic.twitter.com/t5TjIlnZgN",
"expanded_url":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatus%2F564407126526013440%2Fphoto%2F1",
"type":"photo",
"sizes":{
"large":{
"w":320,
"h":180,
"resize":"fit"
},
"thumb":{
"w":150,
"h":150,
"resize":"crop"
},
"small":{
"w":320,
"h":180,
"resize":"fit"
},
"medium":{
"w":320,
"h":180,
"resize":"fit"
}
},
"source_status_id":564407126526013440,
"source_status_id_str":"564407126526013440"
}
]
},
"twitter_filter_level":"low",
"twitter_lang":"ar",
"retweetCount":1,
"gnip":{
"matching_rules":[
{
"tag":"ISIS66"
}
],
"urls":[
{
"url":"http%3A%2F%2Ft.co%2Ft5TjIlnZgN",
"expanded_url":"http%3A%2F%2Ftwitter.com%2Fsckud1%2Fstatus%2F564407126526013440%2Fphoto%2F1",
"expanded_status":200
},
{
"url":"http%3A%2F%2Ft.co%2FC55SaQKmUV",
"expanded_url":"http%3A%2F%2Fwww.hasterya.com%2Farchives%2F34688utm_source%3DReviveOldPost%26utm_medium%3Dsocial%26utm_campaign%3DReviveOldPost",
"expanded_status":200
}
],
"klout_score":50,
"language":{
"value":"ar"
}
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>We configure a flume agent that reads the data from that file and pass it to Solr sink but unfortunately this exception in the title is throw.</p>
<p>and here is the stack trace </p>
<pre><code>org.kitesdk.morphline.api.MorphlineRuntimeException: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@20d7aa52; line: 1, column: 9]
at org.kitesdk.morphline.stdio.AbstractParser.doProcess(AbstractParser.java:98)
at org.kitesdk.morphline.base.AbstractCommand.process(AbstractCommand.java:156)
at org.kitesdk.morphline.stdlib.TryRulesBuilder$TryRules.doProcess(TryRulesBuilder.java:120)
at org.kitesdk.morphline.base.AbstractCommand.process(AbstractCommand.java:156)
at org.kitesdk.morphline.base.AbstractCommand.doProcess(AbstractCommand.java:181)
at org.kitesdk.morphline.base.AbstractCommand.process(AbstractCommand.java:156)
at org.apache.flume.sink.solr.morphline.MorphlineHandlerImpl.process(MorphlineHandlerImpl.java:128)
at org.apache.flume.sink.solr.morphline.MorphlineSink.process(MorphlineSink.java:141)
at org.apache.flume.sink.DefaultSinkProcessor.process(DefaultSinkProcessor.java:68)
at org.apache.flume.SinkRunner$PollingRunner.run(SinkRunner.java:147)
at java.lang.Thread.run(Thread.java:744)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@20d7aa52; line: 1, column: 9]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3095)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2340)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:818)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:698)
at com.fasterxml.jackson.databind.MappingIterator.hasNextValue(MappingIterator.java:159)
at org.kitesdk.morphline.json.ReadJsonBuilder$ReadJson.doProcess(ReadJsonBuilder.java:109)
at org.kitesdk.morphline.stdio.AbstractParser.doProcess(AbstractParser.java:96)
... 10 more
</code></pre> | 28,604,705 | 6 | 1 | null | 2015-02-19 10:48:10.887 UTC | 2 | 2022-03-05 12:22:30.827 UTC | 2017-04-24 20:44:49.103 UTC | null | 2,275,818 | null | 299,758 | null | 1 | 19 | java|jackson|cloudera | 164,121 | <blockquote>
<p>We have the following string which is a valid JSON ...</p>
</blockquote>
<p>Clearly the JSON parser disagrees!</p>
<p>However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.</p>
<p>You need to find what JSON is <em>actually</em> being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for <code>JsonParseException</code> ... then find out what is in the <code>ByteArrayInputStream</code> that it is attempting to parse.</p> |
42,942,781 | Python - AttributeError: 'numpy.ndarray' object has no attribute 'append' | <p>This is related to my question, <a href="https://stackoverflow.com/questions/42941668/valueerror-could-not-broadcast-input-array-from-shape-22500-3-into-shape-1">here</a>.</p>
<p>I now have the updated code as follows:</p>
<pre><code>import numpy as np
import _pickle as cPickle
from PIL import Image
import sys,os
pixels = []
labels = []
traindata = []
i = 0
directory = 'C:\\Users\\abc\\Desktop\\Testing\\images'
for root, dirs, files in os.walk(directory):
for file in files:
floc = file
im = Image.open(str(directory) + '\\' + floc)
pix = np.array(im.getdata())
pixels.append(pix)
labels.append(1)
pixels = np.array(pixels)
labels = np.array(labels)
traindata.append(pixels)
traindata.append(labels)
traindata = np.array([traindata[i][i],traindata[1]], dtype=object)
i = i + 1
# do the same for validation and test data
# put all data and labels into 'data' array
cPickle.dump(traindata,open('data.pickle','wb'))
FILE = open("data.pickle", 'rb')
content = cPickle.load(FILE)
print (content)
</code></pre>
<p>When having only one image, the code runs fine. But, when I add another image or more, I get the following:</p>
<pre><code>Traceback (most recent call last):
File "pickle_data.py", line 17, in <module>
pixels.append((pix))
AttributeError: 'numpy.ndarray' object has no attribute 'append'
</code></pre>
<p>How can I solve this issue?</p>
<p>Thanks.</p> | 42,943,379 | 4 | 1 | null | 2017-03-22 04:31:36.193 UTC | 6 | 2019-04-03 08:46:07.023 UTC | 2019-04-03 08:46:07.023 UTC | null | 707,111 | null | 588,855 | null | 1 | 15 | python|numpy|pickle | 295,889 | <pre><code>for root, dirs, files in os.walk(directory):
for file in files:
floc = file
im = Image.open(str(directory) + '\\' + floc)
pix = np.array(im.getdata())
pixels.append(pix)
labels.append(1) # append(i)???
</code></pre>
<p>So far ok. But you want to leave <code>pixels</code> as a list until you are done with the iteration.</p>
<pre><code>pixels = np.array(pixels)
labels = np.array(labels)
</code></pre>
<p>You had this indention right in your other question. What happened? <a href="https://stackoverflow.com/questions/42941668/valueerror-could-not-broadcast-input-array-from-shape-22500-3-into-shape-1">previous</a></p>
<p>Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:</p>
<pre><code>alist = []
for ..
alist.append(...)
arr = np.array(alist)
</code></pre>
<p>If names indicate something about the nature of the object I'm less likely to get errors like yours.</p>
<p>I don't understand what you are trying to do with <code>traindata</code>. I doubt if you need to build it during the loop. <code>pixels</code> and <code>labels</code> have the basic information.</p>
<p>That</p>
<pre><code>traindata = np.array([traindata[i][i],traindata[1]], dtype=object)
</code></pre>
<p>comes from the previous question. I'm not sure you understand that answer.</p>
<pre><code>traindata = []
traindata.append(pixels)
traindata.append(labels)
</code></pre>
<p>if done outside the loop is just</p>
<pre><code>traindata = [pixels, labels]
</code></pre>
<p><code>labels</code> is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). <code>pixels</code> is a higher dimension array. What is its shape?</p>
<p>Stop right there. There's no point in turning that list into an array. You can save the list with <code>pickle</code>.</p>
<p>You are copying code from an earlier question, and getting the formatting wrong. <a href="https://stackoverflow.com/questions/29781976/cpickle-very-large-amount-of-data">cPickle very large amount of data</a></p> |
42,952,191 | Is it possible to mock a function imported from a package in golang? | <p>I have the following method to test, which uses a function imported from a package.</p>
<pre><code>import x.y.z
func abc() {
...
v := z.SomeFunc()
...
}
</code></pre>
<p>Is it possible to mock <code>SomeFunc()</code> in golang?</p> | 42,952,311 | 5 | 2 | null | 2017-03-22 12:52:20.453 UTC | 18 | 2022-04-28 04:26:53.6 UTC | 2017-03-22 13:04:13.443 UTC | null | 1,705,598 | null | 1,087,152 | null | 1 | 42 | unit-testing|testing|go|mocking | 31,130 | <p>Yes, with a simple refactoring. Create a <code>zSomeFunc</code> variable of function type, initialized with <code>z.SomeFunc</code>, and have your package call that instead of <code>z.SomeFunc()</code>:</p>
<pre><code>var zSomeFunc = z.SomeFunc
func abc() {
// ...
v := zSomeFunc()
// ...
}
</code></pre>
<p>In tests you may assign another function to <code>zSomeFunc</code>, one that is defined in tests, and does whatever the test wants it to.</p>
<p>For example:</p>
<pre><code>func TestAbc(t *testing.T) {
// Save current function and restore at the end:
old := zSomeFunc
defer func() { zSomeFunc = old }()
zSomeFunc = func() int {
// This will be called, do whatever you want to,
// return whatever you want to
return 1
}
// Call the tested function
abc()
// Check expected behavior
}
</code></pre>
<p>See related / possible duplicate:
<a href="https://stackoverflow.com/questions/40615641/testing-os-exit-scenarios-in-go-with-coverage-information-coveralls-io-goverall/40801733#40801733">Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)</a></p> |
69,889,519 | VS 2022 - Convert to file-scoped namespace in all files | <p>I'm converting my project to .NET 6 and I want to use filescoped namespaces everywhere. But the conversion tool exists only in the editor.</p>
<p><a href="https://i.stack.imgur.com/yY5zi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yY5zi.png" alt="file-scoped namespace conversion" /></a></p>
<p>Has anyone found out if there's a way to run this editor function across all files in solution at once? (Looks like Rider has that function)</p> | 69,889,803 | 4 | 0 | null | 2021-11-08 20:22:45.597 UTC | 7 | 2022-07-11 01:45:40.363 UTC | 2021-11-09 17:09:40.91 UTC | null | 2,501,279 | null | 823,680 | null | 1 | 61 | c#|visual-studio-2022|c#-10.0 | 9,376 | <p>Adding a rule to use file scoped namespaces in <code>.editorconfig</code> worked for me:</p>
<ul>
<li>create an <code>.editorconfig</code> file in the solution directory</li>
<li>add following line/content below (<a href="https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#namespace-options" rel="noreferrer">docs</a>, <a href="https://github.com/dotnet/roslyn/blob/6884d36627795f1e00303bf4a068dd7998667bd9/src/Analyzers/Core/Analyzers/IDEDiagnosticIds.cs#L164" rel="noreferrer">code - IDE0161</a>)</li>
</ul>
<p>Example <code>.editorconfig</code> file content:</p>
<pre><code>[*.cs]
csharp_style_namespace_declarations = file_scoped:warning
</code></pre>
<p>After that the preview changes dialog had an option to apply the fix to the whole project/solution:</p>
<p><a href="https://i.stack.imgur.com/ROKvV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ROKvV.png" alt="enter image description here" /></a></p> |
6,061,722 | How do I set the security.policy file for a specific application from within NetBeans? | <p>I am having a bit of trouble -- a lot actually -- trying to figure out how get NetBeans to read my policy file for a particular application. Please take a look at the below code:</p>
<pre><code> public static void main(final String[] args)
{
System.setSecurityManager(new SecurityManager());
System.setProperty("java.security.policy","file:/C:/Users/kBPersonal/Documents/NetBeansProjects/JAASTest/JAASTest.policy");
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JAASFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
</code></pre>
<p>No matter what I do I keep getting the following error which lets me know that NetBeans is not reading my security.policy file (I even added it's location to the main security.policy file in the <code>C:\Program Files (x86)\Java\jre6\lib\security\java.security</code>). Incidentally, line 20 is where I try to set the <code>System.setProperty("java.security.policy, ...)</code></p>
<pre><code> Exception in thread "main" java.security.AccessControlException: access denied (java.util.PropertyPermission java.security.policy write)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.System.setProperty(System.java:725)
at JAASTest.main(JAASTest.java:20)
</code></pre>
<p>Any and all help is greatly appreciated!</p> | 6,061,897 | 4 | 0 | null | 2011-05-19 16:22:35.15 UTC | 4 | 2016-05-04 05:59:53.247 UTC | 2013-10-13 19:59:35.05 UTC | null | 1,576,461 | null | 520,312 | null | 1 | 10 | java|netbeans|security-policy | 50,677 | <p>The easiest way to set a specific security policy is via a runtime argument. For example, this is what we do here for the same problem:</p>
<ol>
<li>Open "Project Properties -> Run"</li>
<li>Select your runtime configuration </li>
<li>Edit the "VM Options" for the runtime configuration </li>
<li><p>Add the following: </p>
<p><code>-Djava.security.manager -Djava.security.policy=src/dir1/dir2/important.policy</code></p></li>
</ol>
<p>where you <code>src/dir1/dir2/important.policy</code> would be changed in your example to point at your file <code>JAASTest.policy</code>.</p> |
6,086,981 | What is the difference between OpenNI and OpenKinect? | <p>I am considering using Kinect in one my projects, but I am totally lost between all the libraries. Don't know what is what exactly. Most importantly I am reading stuff about OpenNI and OpenKinect. But don't know their relation/differences. PS. I am using Ubuntu or Mac.</p> | 6,112,661 | 4 | 0 | null | 2011-05-22 09:06:05.887 UTC | 11 | 2014-07-12 06:01:57.553 UTC | 2012-05-25 11:51:19.98 UTC | null | 488,657 | null | 313,245 | null | 1 | 26 | kinect | 20,478 | <p><a href="http://openkinect.org/wiki/Main_Page" rel="noreferrer">OpenKinect</a> is a community of people, not a library. The OpenKinect community releases the <a href="https://github.com/OpenKinect/libfreenect" rel="noreferrer">libfreenect</a> Kinect driver. libfreenect and OpenNI+SensorKinect are two competing, opensource libraries/drivers. libfreenect (Apache 2.0 or GPLv2) derives from the initial, reverse-engineered/hacked Kinect driver whereas OpenNI+SensorKinect is derived from open sourced (LGPL) PrimeSense code.</p>
<p>Both projects work on Windows, Linux (Ubuntu), and Mac OS X. Both projects allow you to access color and depth images from the camera. The projects are not compatible and they can not be used simultaneously.</p>
<p>Differences between the libraries are motor control (libfreenect has it, OpenNI+SensorKinect doesn't), and integration with the NITE middleware for higher-level NUI support (OpenNI+SensorKinect only). These differences tend to drive projects towards one of the libraries.</p> |
34,512,880 | How to debug/reset Android 6.0 permissions? | <p>While migrating one of my apps to use the Android 6.0 permissions system, I found it very hard to debug permissions using the emulator.</p>
<p><strong>Findings:</strong></p>
<ul>
<li>Disabling a permission in the app info screen doesn't re-show the grant permission dialog when using the <code>requestPermissions()</code> method.</li>
<li>Reinstalling the app seems to be the only way to make the app show the grant permission dialog again.</li>
</ul>
<p>What is the proper method to debug permission using the Android emulator?</p> | 34,512,887 | 1 | 1 | null | 2015-12-29 14:15:27.263 UTC | 8 | 2017-10-03 20:27:31.05 UTC | 2017-10-03 20:27:31.05 UTC | null | 1,052,697 | null | 1,052,697 | null | 1 | 27 | android|android-permissions|android-6.0-marshmallow|android-debug|runtime-permissions | 14,249 | <p>It’s actually very easy to debug Android 6.0 permissions. You can reset the permissions to the "install state" for <strike>the current foreground app</strike> <strong>all apps</strong> using the following ADB shell command:</p>
<pre><code>adb shell pm reset-permissions
</code></pre>
<p><strong><em>Note:</strong> Currently you can't reset the runtime permissions for a specific package, the package manger (pm) tool help section states:</em></p>
<blockquote>
<p>revert all runtime permissions to their default state.</p>
</blockquote>
<p>You can easily execute the <code>reset-permissions</code> command using the terminal interface in Android Studio. Note that ADB commands only works if the ADB directory is added to the PATH system environment variable (see: <a href="https://stackoverflow.com/questions/8744758/adb-is-not-recognized-as-internal-or-external-command-on-windows">add ADB to path variable</a>).</p>
<p>You can also reset/revoke a specific permissions using:</p>
<pre><code>adb shell pm revoke com.your.package android.permission.WRITE_EXTERNAL_STORAGE
</code></pre>
<p>A downside of this command is that it will restart your app, but this doesn't reset the runtime permissions for all apps. To grant a permission replace <code>revoke</code> with <code>grant</code>.</p> |
1,812,311 | Displaying fixed and editable items in a Source List | <h2>Background</h2>
<p>I am creating a Source List for my application and I want it structured in a way similar to that of iTunes, with two types of items:</p>
<ul>
<li>"Fixed" items – these do not change and can't be moved around – at the top</li>
<li>Editable items underneath, which <em>can</em> be changed by the user – moved around, renamed etc (in the iTunes example, like Playlists and Smart Playlists)</li>
</ul>
<p>In my iTunes analogy:</p>
<p><a href="https://i.stack.imgur.com/CmhD2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CmhD2.jpg" alt="iTunes Source List"></a><br>
<sub>(source: <a href="http://perspx.com/wp-content/uploads/2010/02/itunessourcelist.jpg" rel="nofollow noreferrer">perspx.com</a>)</sub> </p>
<p>The way I've structured my data so far is as follows:</p>
<ul>
<li>The items which I want to be editable are "group" items, in the form of <code>Group</code> Core Data entities.</li>
<li>Each item in the Source List is represented as a <code>SourceListItem</code> regular Objective-C object so that I can associate each item with a title, icon, child items etc</li>
<li>The fixed items are currently represented by <code>SourceListItem</code> instances, stored in an array in my controller object.</li>
</ul>
<h2>The Question</h2>
<p>I am unsure of how to amalgamate these two types of item into the Source List, so that the fixed items are at the top and always there and do not change, and the editable items are at the bottom and can be moved around and edited.</p>
<p>These are the ideas I've come up with so far:</p>
<ul>
<li><p><strong>Add the fixed items to the Core Data model.</strong> This means that I can create an entity to represent Source List items and have my fixed and editable items placed in instances of these. Then these can be bound to the Outline View table column with an Array/Tree Controller. However, this means that I'd have to create a new entity to represent the Source List items, and then sync the <code>Group</code>s with this. I'd also have to have some way of creating all the fixed items only once, and if something happened to any of the persistent store files then the fixed items would not be displayed.</p></li>
<li><p><strong>Merge the fixed items with the group items.</strong> Whilst both are stored in separate arrays, this could be done in the controller for my window when the Outline View requests the data (if adopting the <code>NSOutlineViewDataSource</code> protocol, not bindings). However this means that I'd have to create new <code>SourceListItem</code>s for each group in the array controller (to associate each with icons and other attributes), store these and then watch the group array controller for changes to remove, add or modify the <code>SourceListItem</code> instances when changes are made to the groups.</p></li>
</ul>
<p>Does anyone have any better ideas on how I can implement this?</p>
<p>I would like my application to be compatible with OS X v10.5 so I'd prefer any solutions that <strong>didn't</strong> depend on having Snow Leopard installed.</p> | 1,812,924 | 2 | 0 | null | 2009-11-28 11:31:11.477 UTC | 14 | 2019-05-13 04:05:36.527 UTC | 2019-05-13 04:05:36.527 UTC | null | 4,751,173 | null | 75,245 | null | 1 | 14 | objective-c|cocoa|core-data | 1,830 | <p>I'm working on an app that has this exact same behavior, and here's how I'm doing it:</p>
<p>I have 5 main entities in my Core Data Model:</p>
<ol>
<li><code>AbstractItem</code> - an abstract Entity that has the attributes common to all items, like <code>name</code>, <code>weight</code>, and <code>editable</code>. Also has two relationships: <code>parent</code> (to-one relationship to <code>AbstractItem</code>) and <code>children</code> (to-many relationship to <code>AbstractItem</code>, and the inverse of <code>parent</code>).</li>
<li><code>Group</code> - concrete child Entity of <code>AbstractItem</code>.</li>
<li><code>Folder</code> - concrete child Entity of <code>AbstractItem</code>. Adds a many-to-many relationship to the basic <code>Item</code> entity.</li>
<li><code>SmartFolder</code> - concrete child Entity of <code>Folder</code>. Adds a binary attribute <code>predicateData</code>. Overrides <code>Folder</code>'s "items" relationship accessor to return the results of executing a fetch request with the predicate defined by the <code>predicateData</code> attribute.</li>
<li><code>DefaultFolder</code> - concrete child Entity of <code>SmartFolder</code>. Adds a string attribute <code>identifier</code>.</li>
</ol>
<p>For the "Library" section items, I insert <code>DefaultFolder</code> objects and give them a unique identifier so I can retrieve them easily and differentiate between them. I also give them an <code>NSPredicate</code> that corresponds to what <code>Items</code> they're supposed to show. For example, the "Music" <code>DefaultFolder</code> would have a predicate to retrieve all Music items, the "Podcasts" <code>DefaultFolder</code> would have a predicate to retrieve all Podcast items, etc.</p>
<p>The root-level items ("Library", "Shared", "Store", "Genius", etc) are all <code>Group</code> items with a <code>nil</code> parent. The groups and Folders that cannot be edited have their <code>editable</code> attribute set to <code>NO</code>.</p>
<p>As for actually getting this stuff in your outlineView, you'll have to implement the <code>NSOutlineViewDataSource</code> and <code>NSOutlineViewDelegate</code> protocols yourself. There's just too much behavioral complexity here to pump it out through an <code>NSTreeController</code>. However, in my app, I got all of the behavior in (even drag-and-drop) in under 200 lines of code (so it's not <em>that</em> bad).</p> |
59,545,620 | flutter: Too many positional arguments: 0 expected, but 1 found | <p>I've been following <a href="https://resocoder.com/2019/04/06/flutter-nosql-database-sembast-tutorial-w-bloc/" rel="nofollow noreferrer">this NoSQL tutorial</a> which uses BLoC. But when I paste in the code from 'fruit_event.dart' into Visual Studio Code, it gives me an error.</p>
<p>fruit_event.dart:</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import 'package:sembast_prep/data/fruit.dart';
@immutable
abstract class FruitEvent extends Equatable {
FruitEvent([List props = const []]) : super(props); // error here!
}
class LoadFruits extends FruitEvent {}
class AddRandomFruit extends FruitEvent {}
class UpdateWithRandomFruit extends FruitEvent {
final Fruit updatedFruit;
UpdateWithRandomFruit(this.updatedFruit) : super([updatedFruit]);
}
class DeleteFruit extends FruitEvent {
final Fruit fruit;
DeleteFruit(this.fruit) : super([fruit]);
}
</code></pre>
<p>I get this error (Visual Studio Code):</p>
<pre><code>[List<dynamic> props = const []]
Too many positional arguments: 0 expected, but 1 found.
Try removing the extra positional arguments.dart(extra_positional_arguments)
</code></pre> | 59,545,944 | 1 | 0 | null | 2019-12-31 14:56:30.893 UTC | 2 | 2022-03-29 03:14:45.537 UTC | null | null | null | null | 11,979,688 | null | 1 | 2 | flutter|nosql|bloc | 40,189 | <p>Source code of Equatable class: <a href="https://github.com/felangel/equatable/blob/master/lib/src/equatable.dart" rel="noreferrer">https://github.com/felangel/equatable/blob/master/lib/src/equatable.dart</a></p>
<p>It has only one constructor and the constructor accepts no argument/parameter. So you are not allowed to call <code>super(props)</code> from your constructor.</p>
<p>But, in your code you are passing one argument i.e <code>props</code> to the constructor of super class i.e Equatable in your case.</p>
<p>Replace this:</p>
<pre><code>FruitEvent([List props = const []]) : super(props);
</code></pre>
<p>With this: </p>
<pre><code>FruitEvent([List props = const []]);
</code></pre>
<p>And it won't give you any error.</p>
<p>You may want to refer this question to understand usage of super constructor in dart: <a href="https://stackoverflow.com/questions/13272035/how-do-i-call-a-super-constructor-in-dart">How do I call a super constructor in Dart?</a></p>
<p><strong><em>Edited:</em></strong></p>
<ol>
<li>You should use Equitable class to override your hashcode and
toString.</li>
<li>so for the fields which you want to include in your hashcode and
toString you need to have following override:</li>
</ol>
<hr>
<pre><code>/// The [List] of `props` (properties) which will be used to determine whether
/// two [Equatables] are equal.
@override
List<Object> get props => [parameter1, parameter2, parameter3.....];
</code></pre>
<hr>
<ol start="3">
<li>But as you don't have any fields in your class it doesn't makes much
sense to use Equitable.</li>
</ol>
<p><em>Read this comment from the source code:</em></p>
<pre><code>/// A class that helps implement equality
/// without needing to explicitly override == and [hashCode].
/// Equatables override their own `==` operator and [hashCode] based on their `props`.
const Equatable();
</code></pre>
<p>You can refer: <a href="https://pub.dev/packages/equatable#-example-tab-" rel="noreferrer">https://pub.dev/packages/equatable#-example-tab-</a> to learn about using Equitable class.</p>
<p>I hope this helps, in case of any doubt please comment. <em>If this answer helps you then please accept and up-vote it.</em></p> |
29,192,927 | A graph DB vs a Prolog (or miniKanren) | <p>Recently I have been looking into graph databases like Neo4j and into logic programming in Prolog and miniKanren. From what I have learned so far, both allow specifying facts and relations between them, and also querying the resulting system for some selections. So, actually I cannot see much difference between them in that they both can be used to build a graph and query it, but using different syntax. However, they are presented as totally different kinds of software.</p>
<p>Except the technicality that databases maybe propose a more space-time effective storage technology, and except that tiny logic cores like miniKanren are simpler and embeddable, what is the actual difference between graph databases and logic programming languages, if they are both just a graph database + query API?</p> | 29,195,084 | 3 | 2 | null | 2015-03-22 09:44:39.403 UTC | 10 | 2019-11-12 17:46:22.663 UTC | 2015-03-22 09:57:27.06 UTC | null | 980,550 | null | 821,443 | null | 1 | 30 | neo4j|prolog|graph-databases|minikanren | 4,114 | <p>No, logic programming as embodied by those things and neo4j are quite different.</p>
<p>On one level, you're right that they conceptually both amount to graph storage and graph query. But for logic programming, it's only conceptually graph query, there's no guarantee that it's actually stored that way (where with neo4j, it is).</p>
<p>Second, with logic programming you're usually trying to establish <a href="http://en.wikipedia.org/wiki/Horn_clause">horn clauses</a> that allow you to reason through lots of data. You can think of a horn clause as a simple rule, like "If a person is male, and is the direct ancestor of a biological child, that implies that person is a father". In cypher with neo4j, you would describe a graph pattern you wish to match, that results in data, e.g.:</p>
<pre><code> MATCH (p:Person)-[:father*]->(maleAncestor:Person)
RETURN maleAncestor
</code></pre>
<p>This tells to traverse the graph by <code>father</code> relationships, and return male ancestors. In a logic programming language, you wouldn't do it this way. You might specify that <code>a</code> being a father of <code>b</code> means that <code>a</code> is male, and <code>a</code> is an ancestor of <code>b</code>. This would implicitly and transitively state that for all valid a/b pairings. Then you'd ask a question, "who are the male ancestors"? The programming environment would then answer that by exploiting your rules. That would have the effect of building a traversal through the data that's very similar to the cypher I specified above, but the way you go about understanding your data and building that traversal is totally different.</p>
<p>Logic programming languages usually work via <a href="http://en.wikipedia.org/wiki/Resolution_(logic)">predicate resolution</a>. A graph query language like cypher works by a combination of pattern matching, and explicit path designation. They're very different.</p> |
Subsets and Splits