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
32,778,671
Java Remainder of Integer Divison?
<p>I was searching around about this topic but I still don't get it, if someone can elaborate I would be very thankful.</p> <p>My task is to divide two variables as integer division with remainder.. The problem is, that I have no clue what a remainder is, for now I did something like that, this is what I found by searching through the internet:</p> <pre><code>int a; int b; int remainder = Math.Pow(a,2) % b; System.out.println("a^2 / b = " + Math.Pow(a,2) / b); System.out.println("remainder = " + remainder); </code></pre> <p>if I for example set (a = 43) and (b = 67)</p> <p>Then I will get this reslut:</p> <pre><code>a^2 / b = 27 remainder = 40 </code></pre> <p>Now since I have no idea what the remainder is (this is just a suggestion form the internet) I have no idea if this is the correct answer..?</p> <p>Thanks for any help,</p> <p>Kind Regards</p>
32,778,852
6
3
null
2015-09-25 09:09:47.513 UTC
2
2021-03-30 12:04:17.577 UTC
null
null
null
null
5,109,161
null
1
18
java|math|divide
80,105
<p>If you are looking for the mathematical modulo operation you could use</p> <pre><code>int x = -22; int y = 24; System.out.println(Math.floorMod(x, y)); </code></pre> <p>If you are not interested in the mathematical modulo (just the remainder) then you could use</p> <pre><code>int x = -22; int y = 24; System.out.println(x%y); </code></pre>
19,712,395
module import: NameError: name is not defined
<p>How do I define the function in the importer so that it is visible inside imported? I tried this</p> <p><code>importer.py</code> is</p> <pre><code>def build(): print "building" build() import imported </code></pre> <p>Whereby, <code>imported.py</code> is simply</p> <pre><code>build() </code></pre> <p>Yet, this fails</p> <pre><code>building Traceback (most recent call last): File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\importer.py", line 6, in &lt;module&gt; import imported File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\imported.py", line 1, in &lt;module&gt; build() NameError: name 'build' is not defined </code></pre> <p><strong>Update</strong> After I have got the response to make the circular import, so that import and imported depend on each other, I feel that I need to make clear that this is not always good. My purpose is to specify some common strategy in the imported module. It will use some user-defined functions, e.g. <code>build</code>. User defines the necessary function(s) and calls the strategy. The point is that the shared strategy must not depend on specific user definitions. I believe that in place of <code>import</code>, I need something like <code>evaluate(imported.py)</code>, which I believe is a basic function in any script language, including Python. irc://freenode/python insists that I must use <code>import</code> but I do not understand how.</p>
19,713,635
3
2
null
2013-10-31 16:55:18.147 UTC
1
2013-10-31 19:06:06.937 UTC
2013-10-31 19:06:06.937 UTC
null
1,083,704
null
1,083,704
null
1
2
python|python-import
56,909
<p>I know that this is a blasphemy but the thing that allows to import a module without tying the imported with importer is easily available in Python as a script language. You can always evaluate a file with <a href="https://stackoverflow.com/a/1027739/1083704">execfile</a></p>
24,836,044
Case insensitive string search in golang
<p>How do I search through a file for a word in a <em>case insensitive</em> manner? </p> <p><strong>For example</strong> </p> <p>If I'm searching for <code>UpdaTe</code> in the file, if the file contains update, the search should pick it and count it as a match.</p>
26,623,607
4
3
null
2014-07-19 02:00:57.933 UTC
10
2017-03-27 01:28:44.753 UTC
2015-05-12 16:51:15.66 UTC
null
1,047,788
null
3,841,581
null
1
36
string|go|case-insensitive|string-search
54,004
<p><code>strings.EqualFold()</code> can check if two strings are equal, while ignoring case. It even works with Unicode. See <a href="http://golang.org/pkg/strings/#EqualFold" rel="noreferrer">http://golang.org/pkg/strings/#EqualFold</a> for more info.</p> <p><a href="http://play.golang.org/p/KDdIi8c3Ar" rel="noreferrer">http://play.golang.org/p/KDdIi8c3Ar</a></p> <pre><code>package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.EqualFold("HELLO", "hello")) fmt.Println(strings.EqualFold("ÑOÑO", "ñoño")) } </code></pre> <p>Both return true.</p>
185,780
Modifying NSDate to represent 1 month from today
<p>I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date:</p> <pre><code>[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))] </code></pre> <p>I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.</p>
186,104
5
1
null
2008-10-09 03:00:30.207 UTC
11
2012-07-17 06:23:24.193 UTC
2008-11-10 02:52:46.503 UTC
Ned Batchelder
14,343
bmalicoat
13,069
null
1
16
objective-c|cocoa|nsdate
22,375
<p>(Almost the same as <a href="https://stackoverflow.com/questions/181459/is-there-a-better-way-to-find-midnight-tomorrow/181495#181495">this question</a>.)</p> <p>From the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html" rel="nofollow noreferrer">Dates and Times Programming Topics for Cocoa</a>.</p> </blockquote> <p>Following that advice:</p> <pre><code>NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; components.month = 1; NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0]; [components release]; NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth]; NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today]; nextMonthComponents.day = todayDayComponents.day; NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents]; [gregorian release]; </code></pre> <p>There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.</p>
1,035,183
How can I create a Word document using Python?
<p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/" rel="noreferrer">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p> <p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p> <p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
1,035,392
5
0
null
2009-06-23 20:59:08.54 UTC
22
2019-04-09 09:10:51.567 UTC
2011-11-09 17:25:38.27 UTC
null
249,690
null
10,040
null
1
48
python|xml|xslt|ms-word
92,269
<p>A couple ways you can create Word documents using Python:</p> <ul> <li>Use COM automation to create a document using the MS Word object model (using <code>pywin32</code>). <a href="http://python.net/crew/pirx/spam7/" rel="noreferrer">http://python.net/crew/pirx/spam7/</a></li> <li>Automate OpenOffice using Python: <a href="http://wiki.services.openoffice.org/wiki/Python" rel="noreferrer">http://wiki.services.openoffice.org/wiki/Python</a></li> <li>If rtf format is OK, use the PyRTF library: <a href="http://pyrtf.sourceforge.net/" rel="noreferrer">http://pyrtf.sourceforge.net/</a></li> </ul> <p>EDIT:</p> <p>Since COM is out of the question, I suggest the following (inspired by @kcrumley's answer):</p> <p>Using the UNO library to automate Open Office from python, open the HTML file in OOWriter, then save as .doc.</p> <p>EDIT2:</p> <p>There is now a pure Python <a href="https://python-docx.readthedocs.org/en/latest/" rel="noreferrer">python-docx project</a> that looks nice (I have not used it).</p>
626,058
File used by another process
<p>Many a times we get an error, while trying to write file on Windows platform, </p> <p>"The process cannot access the file 'XXX' because it is being used by another process." </p> <p>How to check in C#, before writing to file that its not being used by another process?</p>
626,070
6
0
null
2009-03-09 12:42:26.713 UTC
3
2012-07-27 13:52:40.33 UTC
2010-07-26 17:48:02.11 UTC
null
71,249
nils_gate
71,249
null
1
22
c#|file-io
55,957
<p>You can't, basically - you have to attempt to open the file for writing, and if you get an exception you can't write to it :(</p> <p>Even if you could do a separate check first, the result would be out of date before you could start writing - you could still end up with the exception later.</p> <p>It would be nice if the framework provided a <code>TryOpen</code> method, admittedly...</p>
13,652,783
JBoss AS7 - Failed to process phase POST_MODULE of deployment
<p>Always when I deploy my project (jsf) I get the following error on my JBoss AS7. On JBoss 6 everything worked fine. What can be reasons for that error message? Do you have any idea how I can solve that?</p> <p><strong>JBoss AS7-Console</strong></p> <pre><code>21:25:17,026 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) JBAS015876: Starting deployment of "myproject.war" 21:25:17,662 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-5) MSC00001: Failed to start service jboss.deployment.unit."seminarpla ner.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."myproject.war".POST_MODULE: Failed to proce ss phase POST_MODULE of deployment "myproject.war" at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final .jar:7.1.1.Final] at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2 .GA] at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_31] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_31] at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31] Caused by: java.lang.RuntimeException: Error getting reflective information for class at.uhs.myproject.util.HibernateTransactionFilter w ith ClassLoader ModuleClassLoader for Module "deployment.myproject.war:main" from Service Module Loader at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:70) [jboss-as-serve r-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotationInformation(MethodAnnotationAggregator.java:58) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.handleAnnotations(InterceptorAnnotationProcessor.java:85) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.processComponentConfig(InterceptorAnnotationProcessor.java:70) at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.deploy(InterceptorAnnotationProcessor.java:55) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final .jar:7.1.1.Final] ... 5 more Caused by: java.lang.NoClassDefFoundError: org/hibernate/Session at java.lang.Class.getDeclaredFields0(Native Method) [rt.jar:1.6.0_31] at java.lang.Class.privateGetDeclaredFields(Class.java:2291) [rt.jar:1.6.0_31] at java.lang.Class.getDeclaredFields(Class.java:1743) [rt.jar:1.6.0_31] at org.jboss.as.server.deployment.reflect.ClassReflectionIndex.&lt;init&gt;(ClassReflectionIndex.java:57) [jboss-as-server-7.1.1.Final.jar :7.1.1.Final] at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:66) [jboss-as-serve r-7.1.1.Final.jar:7.1.1.Final] ... 10 more Caused by: java.lang.ClassNotFoundException: org.hibernate.Session from [Module "deployment.myproject.war:main" from Service Module Load er] at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) [jboss-modules.jar:1.1.1.GA] at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.1.1.GA] at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.1.1.GA] at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) [jboss-modules.jar:1.1.1.GA] at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.1.1.GA] at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.1.1.GA] ... 15 more 21:25:17,708 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "myproject.war" was rolled bac k with failure message {"JBAS014671: Failed services" =&gt; {"jboss.deployment.unit.\"myproject.war\".POST_MODULE" =&gt; "org.jboss.msc.servic e.StartException in service jboss.deployment.unit.\"myproject.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"sem inarplaner.war\""}} 21:25:17,756 INFO [org.jboss.as.server.deployment] (MSC service thread 1-3) JBAS015877: Stopped deployment myproject.war in 48ms 21:25:17,758 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report JBAS014777: Services which failed to start: service jboss.deployment.unit."myproject.war".POST_MODULE: org.jboss.msc.service.Star tException in service jboss.deployment.unit."myproject.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "seminarplane r.war" 21:25:17,764 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" =&gt; {"Operation step-2" =&gt; {"JBAS014671: Failed services" =&gt; {"jboss.deployment.unit.\"myproject.war\". POST_MODULE" =&gt; "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"myproject.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"myproject.war\""}}}} </code></pre>
13,683,971
1
4
null
2012-11-30 20:35:57.95 UTC
1
2015-08-04 07:32:57.053 UTC
2012-12-03 13:12:18.457 UTC
null
1,586,660
null
1,586,660
null
1
4
jsf-2|jboss|jboss7.x|jboss5.x
70,209
<p>Finally I've the answer to my question. I had to edit the <code>jboss/standalone/configuration/standalone.xml</code> file and add the following content (add a datasource):</p> <pre><code> &lt;subsystem xmlns="urn:jboss:domain:datasources:1.0"&gt; &lt;datasources&gt; &lt;datasource jndi-name="java:jboss/datasources/myDatasource" pool-name="myDatasource" enabled="true" use-java-context="true"&gt; &lt;connection-url&gt;jdbc:postgresql://localhost/mydatabase&lt;/connection-url&gt; &lt;driver&gt;org.postgresql&lt;/driver&gt; &lt;pool&gt; &lt;min-pool-size&gt;2&lt;/min-pool-size&gt; &lt;max-pool-size&gt;50&lt;/max-pool-size&gt; &lt;prefill&gt;false&lt;/prefill&gt; &lt;use-strict-min&gt;false&lt;/use-strict-min&gt; &lt;flush-strategy&gt;FailingConnectionOnly&lt;/flush-strategy&gt; &lt;/pool&gt; &lt;security&gt; &lt;user-name&gt;myUser&lt;/user-name&gt; &lt;/security&gt; &lt;validation&gt; &lt;check-valid-connection-sql&gt;SELECT 1&lt;/check-valid-connection-sql&gt; &lt;validate-on-match&gt;false&lt;/validate-on-match&gt; &lt;background-validation&gt;false&lt;/background-validation&gt; &lt;/validation&gt; &lt;/datasource&gt; &lt;drivers&gt; &lt;driver name="org.postgresql" module="org.postgresql"&gt; &lt;xa-datasource-class&gt;org.postgresql.xa.PGXADataSource&lt;/xa-datasource-class&gt; &lt;/driver&gt; &lt;/drivers&gt; &lt;/datasources&gt; &lt;/subsystem&gt; </code></pre>
48,942,639
'react-scripts' is not recognized as an internal or external command, operable program or batch file
<p>I am learning to react. The version I installed is 16. I installed prop-types via npm after I got an error that 'react-scripts' is not recognized as an internal or external command, operable program or batch file.&quot;</p> <p><a href="https://i.stack.imgur.com/9TsdZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9TsdZ.png" alt="enter image description here" /></a></p>
49,584,932
19
9
null
2018-02-23 06:51:46.563 UTC
5
2021-11-08 18:57:37.26 UTC
2021-05-23 14:08:54.007 UTC
null
12,311,697
null
8,189,936
null
1
44
reactjs|node-modules|package.json|react-scripts
108,868
<p>It is an error about <strong>react-scripts</strong> file missing in your <strong>node modules</strong> directory at the time of installation.</p> <p>Now, you can add manually this via the command:</p> <blockquote> <p><strong>npm install react-scripts</strong></p> </blockquote>
37,662,955
Laravel migration default value
<p>I didn't understand what is the effect of the <code>default</code> option in the migrations.</p> <p>I can see that the column in the database is defined with default value, but the models are ignore it completely. Say I have a <code>Book</code> model that reflect the <code>books</code> table in the database. I have migration to create the books table: </p> <pre><code>Schema::create('books', function (Blueprint $table) { $table-&gt;increments('id'); -&gt;string('author'); -&gt;string('title'); -&gt;decimal('price', 4, 1)-&gt;default(100); -&gt;timestamps(); }); </code></pre> <p>When I create a new instance of <code>Book</code> model I see:</p> <pre><code>$book = new Book(); var_dump($book-&gt;price); //Always 0... </code></pre> <p>The default value is ignored and the attribute is not sets correctly. Ok, I can get it, because it is a new object and it shouldn't get the default values from the DB. <strong>But</strong> if I tries to save model like:</p> <pre><code>$book = new Book(); $book-&gt;author = 'Test' $book-&gt;title = 'Test' $book-&gt;save(); </code></pre> <p>It is saves <strong>0</strong> in the field <code>price</code> in the database! </p> <p>So what is the point of the <code>default</code> option in the migrations? </p> <p>By the way... It wasn't be better if the model see inside the migration (if exists) what are the fields types and behavior instead to define it manually in the model and the migration? And moreover, even to create a validator automatically for the model. I think that it was possible with small change of the migration structure, so why it is not like that?</p>
37,663,054
5
3
null
2016-06-06 16:55:32.923 UTC
7
2021-06-21 16:56:26.703 UTC
2019-12-24 11:52:51.767 UTC
null
1,725,836
null
1,725,836
null
1
75
laravel|laravel-5
216,926
<p>Put the default value in single quote and it will work as intended. An example of migration: </p> <pre><code>$table-&gt;increments('id'); $table-&gt;string('name'); $table-&gt;string('url'); $table-&gt;string('country'); $table-&gt;tinyInteger('status')-&gt;default('1'); $table-&gt;timestamps(); </code></pre> <p><strong>EDIT :</strong> in your case ->default('100.0');</p>
37,635,328
What is the meaning of viewer field in GraphQL?
<p>What is the purpose of root query field <code>viewer</code> in GraphQL?</p> <p>Based on <a href="https://medium.com/the-graphqlhub/graphql-and-authentication-b73aed34bbeb#.cpmrcqcyt">this article</a>, <code>viewer</code> could be used to accept a token parameter so we can see who is currently logged in.</p> <p>How should I implement it?</p>
37,636,116
2
3
null
2016-06-04 21:46:50.073 UTC
14
2021-10-12 12:37:38.283 UTC
2017-08-11 00:12:27.167 UTC
null
710,693
null
2,628,278
null
1
29
graphql|relayjs
10,935
<h2>Purpose of <code>viewer</code> root query field</h2> <p><code>viewer</code> is not something GraphQL or Relay-specific. Most web applications serve some purposes of its users or viewers. The top level entity to model the various data served to the user can be named as <code>viewer</code>. You can also name it <code>user</code>. For example, the <a href="https://github.com/facebook/relay/blob/5729cc69266d6c18cd8baecd103fdcbda092887d/examples/todo/data/schema.js#L126" rel="noreferrer">Relay todo example</a> has a <code>viewer</code> root query field:</p> <pre><code>viewer: { type: GraphQLUser, resolve: () =&gt; getViewer(), }, </code></pre> <p>We may also do without <code>viewer</code>. For instance, <a href="https://github.com/facebook/relay/blob/5729cc69266d6c18cd8baecd103fdcbda092887d/examples/star-wars/data/schema.js#L230-L244" rel="noreferrer">Relay starwars example</a> does not have any <code>viewer</code> root query field.</p> <p>In short, having this <code>viewer</code> as a root query field of the GraphQL schema enables us to provide data based on the current user.</p> <h2>Implementation: How to use authentication token together with viewer</h2> <p>My answer follows what is already described in your mentioned article. The steps are:</p> <ol> <li><p>On the server-side, create a mutation to obtain an authentication token. Let's name it <code>LoginMutation</code>. Input to this mutation are the user credentials and the output is an authentication token.</p></li> <li><p>On the client-side, if you use <a href="https://github.com/facebook/relay" rel="noreferrer">relay framework</a>, implement a client-side mutation. After the mutation is successful, store the authentication token.</p></li> <li><p>On the client-side Relay code, add <code>authToken</code> parameter for your <code>viewer</code> queries. The value of <code>authToken</code> is the authentication token received after successful login mutation.</p></li> </ol> <h2>An alternative</h2> <p>As already mentioned in the article, an alternative way of authenticating user is to do it outside of GraphQL. You may want to see two excellent answers <a href="https://stackoverflow.com/a/35004335/2821632">this</a> and <a href="https://stackoverflow.com/a/37356630/2821632">this</a> for details.</p> <p>Jonas Helfer wrote a two-part article on this, which you'll find very useful: <a href="https://medium.com/apollo-stack/a-guide-to-authentication-in-graphql-e002a4039d1#.ha9zd7yod" rel="noreferrer">Part 1</a>, <a href="https://medium.com/apollo-stack/auth-in-graphql-part-2-c6441bcc4302#.288hyxkc7" rel="noreferrer">Part 2</a></p>
35,542,176
Typescript: Property 'src' does not exist on type 'HTMLElement'
<p>I get a error from Typescript and I am not sure how to correct it. The code works fine when "compiled" but I can't correct the error. I have extracted the parts that involve the error from my code. I guess I have to predifine the src but not sure how.</p> <p>Error msg in Editor and on Gulp compile: </p> <p><strong><em>"Property 'src' does not exist on type 'HTMLElement'.at line 53 col 17"</em></strong></p> <pre><code>... element:HTMLElement; /* Defining element */ ''' this.element = document.createElement('img'); /*creating a img*/ ''' </code></pre> <p>This is the method I run to render the element, position, top and left all works with out giving a error. </p> <pre><code>display() { this.element.src = this.file; /*This is the line that gives the error*/ this.element.style.position = "absolute"; this.element.style.top = this.pointX.toString() + "px"; this.element.style.left = this.pointY.toString() + "px"; document.body.appendChild(this.element); }; </code></pre>
35,542,249
8
3
null
2016-02-21 21:17:21.443 UTC
4
2021-08-20 11:53:44.677 UTC
null
null
null
null
1,318,321
null
1
35
javascript|typescript
54,385
<p>Because <code>src</code> is not a property of the <code>HTMLElement</code> type, but of <code>HTMLImageElement</code>.</p> <p>If you are certain you'll get an img element, you might want to declare your variable with the correct subtype:</p> <pre><code>element: HTMLImageElement; /* Defining element */ // ... this.element = document.createElement('img'); /*creating a img*/ </code></pre> <p>Also, you might want to have a look at what <code>document.createElement</code> returns. It's the very same type if you specify <code>"img"</code> as its argument.</p>
68,240,884
Error object inside catch is of type unknown
<p>I have the following code:</p> <pre class="lang-js prettyprint-override"><code>try { phpDoc(vscode.window.activeTextEditor); } catch (err) { console.error(err); vscode.window.showErrorMessage(err.message); } </code></pre> <p>however <code>err.message</code> gets the error <code>Object is of type 'unknown'.ts(2571)</code> on <code>err.</code>, but I cannot type the object in <code>catch (err: Error)</code>.</p> <p>What should I do?</p>
68,257,472
5
2
null
2021-07-04 00:37:22.227 UTC
9
2022-09-06 23:03:03.877 UTC
2022-07-07 03:27:51.673 UTC
null
4,975,772
null
5,728,714
null
1
66
typescript|try-catch
36,102
<p>As a supplementary answer to <a href="https://stackoverflow.com/users/9515207/certainperformance">CertainPerformance</a>'s <a href="https://stackoverflow.com/a/68240891/11407695">one</a>:</p> <p>Up until TypeScript 4.0, the <code>catch</code> clause bindings were set to <code>any</code> thus allowing easy access to the <code>message</code> property. This is unsafe because it is not <em>guaranteed</em> that what's thrown will be inheriting from the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" rel="noreferrer"><code>Error</code></a> prototype - it just <em>happens</em> that we don't throw anything but errors as best practice:</p> <pre class="lang-js prettyprint-override"><code>(() =&gt; { try { const myErr = { code: 42, reason: &quot;the answer&quot; }; throw myErr; //don't do that in real life } catch(err) { console.log(err.message); //undefined } })(); </code></pre> <p>TypeScript 4.0 <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#unknown-on-catch-clause-bindings" rel="noreferrer">introduced</a> an option for a safer <code>catch</code> clause by allowing you to annotate the parameter as <code>unknown</code>, forcing you to either do an explicit type assertion or, even better, to type guard (which makes the clause both compile-time and runtime-safe).</p> <p>However, to avoid breaking most of the codebases out there, you had to explicitly opt-in for the new behavior:</p> <pre class="lang-js prettyprint-override"><code>(() =&gt; { try { throw new Error(&quot;ouch!&quot;); } catch(err: unknown) { console.log(err.message); //Object is of type 'unknown' } })(); </code></pre> <p>TypeScript 4.4 introduced a new compiler option called <a href="https://www.typescriptlang.org/tsconfig#useUnknownInCatchVariables" rel="noreferrer"><code>useUnknownInCatchVariables</code></a> that makes this behavior mandatory. It is <code>false</code> by default, but if you have the <code>strict</code> option turned on (as you should), it is turned on which is most likely the reason why you got the error in the first place.</p>
23,260,390
Node.js tail-call optimization: possible or not?
<p>I like JavaScript so far, and decided to use Node.js as my engine partly because of <a href="https://stackoverflow.com/questions/3660577/are-any-javascript-engines-tail-call-optimized">this</a>, which claims that Node.js offers TCO. However, when I try to run this (obviously tail-calling) code with Node.js, it causes a stack overflow:</p> <pre><code>function foo(x) { if (x == 1) { return 1; } else { return foo(x-1); } } foo(100000); </code></pre> <p>Now, I did some digging, and I found <a href="http://dailyjs.com/2013/10/17/yield/" rel="noreferrer">this</a>. Here, it seems to say I should write it like this:</p> <pre><code>function* foo(x) { if (x == 1) { return 1; } else { yield foo(x-1); } } foo(100000); </code></pre> <p>However, this gives me syntax errors. I've tried various permutations of it, but in all cases, Node.js seems unhappy with <em>something</em>. </p> <p>Essentially, I'd like to know the following:</p> <ol> <li>Does or doesn't Node.js do TCO?</li> <li>How does this magical <code>yield</code> thing work in Node.js?</li> </ol>
30,369,729
4
3
null
2014-04-24 05:17:49.84 UTC
14
2017-11-09 18:02:34.843 UTC
2017-05-23 12:26:36.55 UTC
null
-1
null
2,629,787
null
1
35
javascript|node.js|tail-call-optimization
15,532
<p>There are two fairly-distinct questions here:</p> <ul> <li>Does or doesn't Node.js do TCO?</li> <li>How does this magical yield thing work in Node.js?</li> </ul> <blockquote> <p><strong>Does or doesn't Node.js do TCO?</strong></p> </blockquote> <p><strong>TL;DR</strong>: <strong>Not anymore, as of Node 8.x</strong>. It did for a while, behind one flag or another, but as of this writing (November 2017) it doesn't anymore because the underlying V8 JavaScript engine it uses doesn't support TCO anymore. See <a href="https://stackoverflow.com/a/42788286/157247">this answer</a> for more on that.</p> <p>Details:</p> <p>Tail-call optimization (TCO) is a required <a href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tail-position-calls" rel="noreferrer">part of the ES2015 ("ES6") specification</a>. So supporting it isn't, directly, a NodeJS thing, it's something the V8 JavaScript engine that NodeJS uses needs to support.</p> <p>As of Node 8.x, V8 doesn't support TCO, not even behind a flag. It may do (again) at some point in the future; see <a href="https://stackoverflow.com/a/42788286/157247">this answer</a> for more on that.</p> <p>Node 7.10 down to 6.5.0 at least (my notes say 6.2, but <a href="http://node.green" rel="noreferrer">node.green</a> disagrees) supported TCO behind a flag (<code>--harmony</code> in 6.6.0 and up, <code>--harmony_tailcalls</code> earlier) in strict mode only.</p> <p>If you want to check your installation, here are the tests <a href="http://node.green" rel="noreferrer">node.green</a> uses (be sure to use the flag if you're using a relevant version):</p> <pre><code>function direct() { "use strict"; return (function f(n){ if (n &lt;= 0) { return "foo"; } return f(n - 1); }(1e6)) === "foo"; } function mutual() { "use strict"; function f(n){ if (n &lt;= 0) { return "foo"; } return g(n - 1); } function g(n){ if (n &lt;= 0) { return "bar"; } return f(n - 1); } return f(1e6) === "foo" &amp;&amp; f(1e6+1) === "bar"; } console.log(direct()); console.log(mutual()); </code></pre> <pre> $ # Only certain versions of Node, notably not 8.x or (currently) 9.x; see above $ node --harmony tco.js true true </pre> <blockquote> <p><strong>How does this magical <code>yield</code> thing work in Node.js?</strong></p> </blockquote> <p>This is another ES2015 thing ("generator functions"), so again it's something that V8 has to implement. It's completely implemented in the version of V8 in Node 6.6.0 (and has been for several versions) and isn't behind any flags.</p> <p>Generator functions (ones written with <code>function*</code> and using <code>yield</code>) work by being able to stop and return an iterator that captures their state and can be used to continue their state on a subsequent occasion. Alex Rauschmeyer has an in-depth article on them <a href="http://www.2ality.com/2015/03/es6-generators.html" rel="noreferrer">here</a>.</p> <p>Here's an example of using the iterator returned by the generator function explicitly, but you usually won't do that and we'll see why in a moment:</p> <pre><code>"use strict"; function* counter(from, to) { let n = from; do { yield n; } while (++n &lt; to); } let it = counter(0, 5); for (let state = it.next(); !state.done; state = it.next()) { console.log(state.value); } </code></pre> <p>That has this output:</p> <pre> 0 1 2 3 4 </pre> <p>Here's how that works:</p> <ul> <li>When we call <code>counter</code> (<code>let it = counter(0, 5);</code>), the initial internal state of the call to <code>counter</code> is initialized and we immediately get back an iterator; none of the actual code in <code>counter</code> runs (yet).</li> <li>Calling <code>it.next()</code> runs the code in <code>counter</code> up through the first <code>yield</code> statement. At that point, <code>counter</code> pauses and stores its internal state. <code>it.next()</code> returns a state object with a <code>done</code> flag and a <code>value</code>. If the <code>done</code> flag is <code>false</code>, the <code>value</code> is the value yielded by the <code>yield</code> statement.</li> <li>Each call to <code>it.next()</code> advances the state inside <code>counter</code> to the next <code>yield</code>.</li> <li>When a call to <code>it.next()</code> makes <code>counter</code> finish and return, the state object we get back has <code>done</code> set to <code>true</code> and <code>value</code> set to the return value of <code>counter</code>.</li> </ul> <p>Having variables for the iterator and the state object and making calls to <code>it.next()</code> and accessing the <code>done</code> and <code>value</code> properties is all boilerplate that (usually) gets in the way of what we're trying to do, so ES2015 provides the new <code>for-of</code> statement that tucks it all away for us and just gives us each value. Here's that same code above written with <code>for-of</code>:</p> <pre><code>"use strict"; function* counter(from, to) { let n = from; do { yield n; } while (++n &lt; to); } for (let v of counter(0, 5)) { console.log(v); } </code></pre> <p><code>v</code> corresponds to <code>state.value</code> in our previous example, with <code>for-of</code> doing all the <code>it.next()</code> calls and <code>done</code> checks for us.</p>
2,164,258
Is it not possible to define multiple constructors in Python?
<blockquote> <p><strong>Possible Duplicate:</strong> <br/> <a href="https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python">What is a clean, pythonic way to have multiple constructors in Python?</a></p> </blockquote> <p>Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it?</p> <p>For example, let's say you wanted to define a class <code>City</code>.</p> <p>I'd like to be able to say <code>someCity = City()</code> or <code>someCity = City(&quot;Berlin&quot;)</code>, where the first just gives a default name value, and the second defines it.</p>
2,164,279
5
3
null
2010-01-29 18:38:13.077 UTC
48
2022-05-24 13:46:49.643 UTC
2021-01-28 21:27:09.103 UTC
null
63,550
null
104,060
null
1
288
python|constructor
318,155
<p>Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.</p> <pre><code>def __init__(self, city="Berlin"): self.city = city </code></pre>
2,287,144
Copy contents of one textbox to another
<p>Suppose an entry is made in a textbox. Is it possible to retain the same entered text in a second text box? If so, how is this done?</p> <pre><code>&lt;html&gt; &lt;label&gt;First&lt;/label&gt; &lt;input type="text" name="n1" id="n1"&gt; &lt;label&gt;Second&lt;/label&gt; &lt;input type="text" name="n1" id="n1"/&gt; &lt;/html&gt; </code></pre>
2,287,199
7
0
null
2010-02-18 08:19:20.583 UTC
8
2019-03-07 07:39:18.723 UTC
2019-03-07 07:39:18.723 UTC
null
9,331,166
null
221,149
null
1
14
javascript|html
92,062
<pre><code>&lt;script&gt; function sync() { var n1 = document.getElementById('n1'); var n2 = document.getElementById('n2'); n2.value = n1.value; } &lt;/script&gt; &lt;input type="text" name="n1" id="n1" onkeyup="sync()"&gt; &lt;input type="text" name="n2" id="n2"/&gt; </code></pre>
1,425,147
Finding a specific character in a string in Matlab
<p>Suppose I have a string <code>'[email protected]'</code>. I want to store the string before and after "@" into 2 separate strings. What would be the easiest method of finding the "@" character or other characters in the string?</p>
1,425,203
7
0
null
2009-09-15 04:42:13.987 UTC
3
2016-10-30 10:24:09.697 UTC
2013-04-30 13:11:57.91 UTC
null
1,714,410
null
98,299
null
1
19
string|matlab
53,550
<p>I used strtok and strrep from Matlab instead.</p>
2,122,385
Dynamic terminal printing with python
<p>Certain applications like hellanzb have a way of printing to the terminal with the appearance of dynamically refreshing data, kind of like top().</p> <p>Whats the best method in python for doing this? I have read up on logging and curses, but don't know what to use. I am creating a reimplementation of top. If you have any other suggestions I am open to them as well. </p>
2,122,972
7
2
2010-01-23 06:33:29.813 UTC
2010-01-23 06:33:29.813 UTC
35
2021-07-09 13:20:43.503 UTC
null
null
null
null
106,534
null
1
57
python|terminal
91,668
<p>The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use <code>'\r'</code> (carriage return) and <code>sys.stdout</code>:</p> <pre><code>import sys import time for i in range(10): sys.stdout.write("\r{0}&gt;".format("="*i)) sys.stdout.flush() time.sleep(0.5) </code></pre> <p>If you need a proper console UI that support moving the pointer etc., use the <a href="http://docs.python.org/library/curses.html" rel="noreferrer"><code>curses</code></a> module from the standard library:</p> <pre><code>import time import curses def pbar(window): for i in range(10): window.addstr(10, 10, "[" + ("=" * i) + "&gt;" + (" " * (10 - i )) + "]") window.refresh() time.sleep(0.5) curses.wrapper(pbar) </code></pre> <p>It's highly advisable to use the <a href="http://docs.python.org/library/curses.html#curses.wrapper.wrapper" rel="noreferrer"><code>curses.wrapper</code></a> function to call your main function, it will take care of cleaning up the terminal in case of an error, so it won't be in an unusable state afterwards.</p> <p>If you create a more complex UI, you can create multiple windows for different parts of the screen, text input boxes and mouse support.</p>
1,507,082
Python: Is it bad form to raise exceptions within __init__?
<p>Is it considered bad form to raise exceptions within <code>__init__</code>? If so, then what is the accepted method of throwing an error when certain class variables are initialized as <code>None</code> or of an incorrect type?</p>
1,507,127
7
0
null
2009-10-01 23:47:38.957 UTC
21
2021-09-11 17:05:52.28 UTC
2018-06-25 15:58:26.003 UTC
null
410,624
user178884
null
null
1
158
python|exception
68,250
<p>Raising exceptions within <code>__init__()</code> is absolutely fine. There's no other good way to indicate an error condition within an initializer, and there are many hundreds of examples in the standard library where initializing an object can raise an exception.</p> <p>The error class to raise, of course, is up to you. <code>ValueError</code> is best if the initializer was passed an invalid parameter.</p>
1,798,368
Using regex to extract username from email address
<p>My string of text looks like this:</p> <pre><code>[email protected] (John Doe) </code></pre> <p>I need to get just the part before the @ and nothing else. The text is coming from a simple XML object if that matters any.</p> <p>The code I have looks like this:</p> <pre><code>$authorpre = $key-&gt;{"author"}; $re1 = '((?:[a-z][a-z]+))'; if ($c = preg_match_all ("/".$re1."/is", $authorpre, $matches)) { $author = $matches[1][0]; } </code></pre> <p>Sometimes the username might have numbers or an underscore before the @ symbol, which is where the regex stops it seems.</p>
1,798,387
12
4
null
2009-11-25 16:58:37.997 UTC
6
2020-06-27 18:59:35.99 UTC
2017-08-06 12:05:13.3 UTC
null
63,550
null
115,949
null
1
30
php|regex|preg-match
60,764
<p>The regular expression that will match and capture any character until it reaches the <code>@</code> character:</p> <pre><code>([^@]+) </code></pre> <p>That seems like what you need. It'll handle all kinds of freaky variations on e-mail addresses.</p> <hr /> <p>I'm not sure why <a href="https://stackoverflow.com/users/189179/ben-james">Ben James</a> deleted his answer, since I feel it's better than mine. I'm going to post it here (unless he undeletes his answer):</p> <blockquote> <p>Why use regex instead of string functions?</p> <pre><code>$parts = explode(&quot;@&quot;, &quot;[email protected]&quot;); $username = $parts[0]; </code></pre> </blockquote> <p>You don't need regular expressions in this situation at all. I think using <code>explode</code> is a much better option, personally.</p> <hr /> <p>As <a href="https://stackoverflow.com/users/73070/johannes-rossel">Johannes Rössel</a> points out in the comments, e-mail address parsing is rather complicated. If you want to be 100% sure that you will be able to handle any technically-valid e-mail address, you're going to have to write a routine that will handle quoting properly, because both solutions listed in my answer will choke on addresses like <code>&quot;a@b&quot;@example.com</code>. There may be a library that handles this kind of parsing for you, but I am unaware of it.</p>
33,547,233
How to convert Emoji from Unicode in PHP?
<p>I use this <a href="http://apps.timwhitlock.info/emoji/tables/unicode" rel="noreferrer">table of Emoji</a> and try this code:</p> <pre><code>&lt;?php print json_decode('"\u2600"'); // This convert to ☀ (black sun with rays) ?&gt; </code></pre> <p>If I try to convert this <a href="http://apps.timwhitlock.info/unicode/inspect/hex/1F600" rel="noreferrer">\u1F600</a> (grinning face) through <code>json_decode</code>, I see this symbol — <code>ὠ0</code>.</p> <p>Whats wrong? How to get right Emoji?</p>
33,548,423
3
3
null
2015-11-05 14:32:52.37 UTC
4
2022-09-24 18:47:03.173 UTC
null
null
null
null
5,334,651
null
1
27
php|unicode|emoji
49,124
<p><strong>PHP 5</strong></p> <p>JSON's <code>\u</code> can only handle one UTF-16 code unit at a time, so you need to write the surrogate pair instead. For <a href="http://www.fileformat.info/info/unicode/char/1F600/index.htm"><code>U+1F600</code></a> this is <code>\uD83D\uDE00</code>, which works:</p> <pre><code>echo json_decode('"\uD83D\uDE00"'); </code></pre> <p><strong>PHP 7</strong></p> <p>You now no longer need to use <code>json_decode</code> and can just use the <code>\u</code> and the unicode literal:</p> <pre><code>echo "\u{1F30F}"; </code></pre>
8,415,003
Direct descendants only with jQuery's find()
<p>Is it possible to select only direct descendants of an element using jQuery's <code>find()</code> or <code>children()</code> functions?</p> <p>I have several <code>ul</code> elements, each with other <code>ul</code> elements inside them, and some root <code>li</code> elements too. I store a specific parent <code>ul</code> in a variable (as a jQuery object) and then look for any of the root <code>li</code> elements within using: <code>my_root_ul.find('li');</code>. </p> <p>However, this method also finds any <code>li</code> that belongs to the <code>ul</code> inside the <code>ul</code>, if that makes sense.</p> <p>My question is, how can I select only direct descendants of type <code>li</code> within the <code>my_root_ul</code> object using <code>find()</code>. Ordinarily, we could use something like <code>$('ul &gt; li')</code> to return only direct <code>li</code> elements, but it must be possible to filter down the returned elements?</p> <p>Here is an example to demonstrate what I mean:</p> <pre><code>&lt;ul&gt; &lt;li&gt;I want this &lt;ul&gt; &lt;li&gt;I don't want this&lt;/li&gt; &lt;li&gt;I don't want this&lt;/li&gt; &lt;li&gt;I don't want this&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;I want this&lt;/li&gt; &lt;li&gt;I want this&lt;/li&gt; &lt;/ul&gt; </code></pre>
8,415,027
1
2
null
2011-12-07 12:03:32.667 UTC
3
2019-07-11 13:30:17.54 UTC
2011-12-07 12:14:28.277 UTC
null
41,655
null
367,401
null
1
41
javascript|jquery|dom
16,381
<p>Like this:</p> <pre><code>my_root_ul.find('&gt; li'); </code></pre> <p><code>.children()</code> also selects only the immediate children, so you can use that also:</p> <pre><code>my_root_ul.children('li'); </code></pre>
17,746,481
Cannot use X as Y because the name is already in use, even though it's not
<p>I'm using PHP 5.4, and have a PSR-0 class structure similar to the following.</p> <p><strong>A\Library\Session.php</strong>:</p> <pre class="lang-php prettyprint-override"><code>namespace A\Library; class Session { ... } </code></pre> <p><strong>My\Application\Session.php</strong>:</p> <pre class="lang-php prettyprint-override"><code>namespace My\Application; class Session { ... } </code></pre> <p><strong>My\Application\Facebook.php</strong>:</p> <pre class="lang-php prettyprint-override"><code>namespace My\Application; use A\Library\Session; class Facebook { ... } </code></pre> <p>When I try to run the application, I get the following error:</p> <blockquote> <p>Cannot use A\Library\Session as Session because the name is already in use in My\Application\Facebook.php</p> </blockquote> <p>Even though it's not, at least not in this file. The Facebook.php file declares only the <code>Facebook</code> class, and imports exactly one <code>Session</code> class, the <code>A\Library</code> one.</p> <p>The only problem I can see is that another <code>Session</code> class exists in the same namespace as the <code>Facebook</code> class, but as it was never imported in the Facebook.php file, I thought it did not matter at all.</p> <p>Am I wrong (in that case please point to the relevant documentation), or is this a bug?</p>
23,879,699
4
2
null
2013-07-19 12:49:31.76 UTC
2
2019-12-01 10:53:55.093 UTC
null
null
null
null
759,866
null
1
46
php
53,300
<p>There is a bug confirmed in PHP that may affect the behavior you see. It is supposed to fatal error, but with opcache enabled, it may still execute flawlessly.</p> <p><a href="https://bugs.php.net/bug.php?id=66773">https://bugs.php.net/bug.php?id=66773</a></p> <p>If it still concerns you, please vote for the bug.</p>
18,119,387
Iterating over a mongodb cursor serially (waiting for callbacks before moving to next document)
<p>Using mongoskin, I can do a query like this, which will return a cursor:</p> <pre><code>myCollection.find({}, function(err, resultCursor) { resultCursor.each(function(err, result) { } } </code></pre> <p>However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called back (similar to the eachSeries structure in the async.js module). E.g:</p> <pre><code>myCollection.find({}, function(err, resultCursor) { resultCursor.each(function(err, result) { externalAsyncFunction(result, function(err) { //externalAsyncFunction completed - now want to move to next doc }); } } </code></pre> <p>How could I do this?</p> <p>Thanks</p> <p><strong>UPDATE:</strong></p> <p>I don't wan't to use <code>toArray()</code> as this is a large batch operation, and the results might not fit in memory in one go.</p>
18,119,789
9
4
null
2013-08-08 06:36:13.677 UTC
24
2019-09-08 20:55:56.093 UTC
2014-03-20 15:19:13.827 UTC
null
324,381
null
324,381
null
1
71
node.js|mongodb|mongoskin|async.js
46,238
<p>If you don't want to load all of the results into memory using toArray, you can iterate using the cursor with something like the following.</p> <pre><code>myCollection.find({}, function(err, resultCursor) { function processItem(err, item) { if(item === null) { return; // All done! } externalAsyncFunction(item, function(err) { resultCursor.nextObject(processItem); }); } resultCursor.nextObject(processItem); } </code></pre>
17,946,960
With HTML5 url input validation assume url starts with http://
<p>HTML5 provides for automatic URL validation :-</p> <pre><code>&lt;form&gt; &lt;input type="url" name="someUrl"&gt; &lt;/form&gt; </code></pre> <p>This will fail validation for URL's that don't have a protocol prefix - e.g. <code>stackoverflow.com</code> will fail while <code>http://stackoverflow.com</code> will pass.</p> <p>How can I automatically add http:// to a url if there isn't already a protocol?</p> <p>I could add a onblur event handler but is there a better way like some before validation event?</p>
28,282,844
9
5
null
2013-07-30 12:23:57.827 UTC
5
2021-05-12 08:43:16.06 UTC
null
null
null
null
20,198
null
1
32
html
27,880
<p>The code for this should not interrupt the user's action, but should instead wait until the user leaves the form field to check the input text for "http". So use "onblur" instead of "onkeyup".</p> <p>Then, just see if the string contains "http" using indexOf. If not, it will return -1, which is falsey.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function checkURL (abc) { var string = abc.value; if (!~string.indexOf("http")) { string = "http://" + string; } abc.value = string; return abc }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;input type="url" name="someUrl" onblur="checkURL(this)" /&gt; &lt;input type="text"/&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/pvu77sst/" rel="noreferrer">Fiddle</a></p>
41,946,007
Efficient (and well explained) implementation of a Quadtree for 2D collision detection
<p>I've been working on adding a Quadtree to a program that I'm writing, and I can't help but notice that there are few well explained/performing tutorials for the implementation that I'm looking for.</p> <p>Specifically, a list of the methods and pseudocode for how to implement them (or just a description of their processes) that are commonly used in a Quadtree (retrieve, insert, remove, etc.) is what I'm looking for, along with maybe some tips to improve performance. This is for collision detection, so it'd be best to be explained with 2d rectangles in mind, as they are the objects that will be stored.</p>
48,330,314
7
4
null
2017-01-30 21:50:31.127 UTC
106
2020-11-04 18:44:10.627 UTC
null
null
null
null
7,213,753
null
1
93
data-structures|collision|rectangles|quadtree
66,885
<ol> <li>Efficient Quadtrees</li> </ol> <hr /> <p>All right, I'll take a shot at this. First a teaser to show the results of what I'll propose involving 20,000 agents (just something I whipped up real quick for this specific question):</p> <p><a href="https://i.stack.imgur.com/6cQeQ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/6cQeQ.gif" alt="enter image description here" /></a></p> <p>The GIF has extremely reduced frame rate and significantly lower res to fit the 2 MB maximum for this site. Here's a video if you want to see the thing at close to full speed: <a href="https://streamable.com/3pgmn" rel="noreferrer">https://streamable.com/3pgmn</a>.</p> <p>And a GIF with 100k though I had to fiddle with it so much and had to turn off the quadtree lines (didn't seem to want to compress as much with them on) as well as change the way the agents looked to get it to fit in 2 megabytes (I wish making a GIF was as easy as coding a quadtree):</p> <p><a href="https://i.stack.imgur.com/3qBeV.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/3qBeV.gif" alt="enter image description here" /></a></p> <p>The simulation with 20k agents takes ~3 megabytes of RAM. I can also easily handle 100k smaller agents without sacrificing frame rates, though it leads to a bit of a mess on the screen to the point where you can barely see what's going on as in the GIF above. This is all running in just one thread on my i7 and I'm spending almost half the time according to VTune just drawing this stuff on the screen (just using some basic scalar instructions to plot things one pixel at a time in CPU).</p> <p><a href="https://streamable.com/9mqd4" rel="noreferrer">And here's a video with 100,000 agents</a> though it's hard to see what's going on. It's kind of a big video and I couldn't find any decent way to compress it without the whole video turning into a mush (might need to download or cache it first to see it stream at reasonable FPS). With 100k agents the simulation takes around 4.5 megabytes of RAM and the memory use is very stable after running the simulation for about 5 seconds (stops going up or down since it ceases to heap allocate). <a href="https://streamable.com/v0ifs" rel="noreferrer">Same thing in slow motion</a>.</p> <p><strong>Efficient Quadtree for Collision Detection</strong></p> <p>All right, so actually quadtrees are not my favorite data structure for this purpose. I tend to prefer a grid hierarchy, like a coarse grid for the world, a finer grid for a region, and an even finer grid for a sub-region (3 fixed levels of dense grids, and no trees involved), with row-based optimizations so that a row that has no entities in it will be deallocated and turned into a null pointer, and likewise completely empty regions or sub-regions turned into nulls. While this simple implementation of the quadtree running in one thread can handle 100k agents on my i7 at 60+ FPS, I've implemented grids that can handle a couple million agents bouncing off each other every frame on older hardware (an i3). Also I always liked how grids made it very easy to predict how much memory they'll require, since they don't subdivide cells. But I'll try to cover how to implement a reasonably efficient quadtree.</p> <p>Note that I won't go into the full theory of the data structure. I'm assuming that you already know that and are interested in improving performance. I'm also just going into my personal way of tackling this problem which seems to outperform most of the solutions I find online for my cases, but there are many decent ways and these solutions are tailor-fitted to my use cases (very large inputs with everything moving every frame for visual FX in films and television). Other people probably optimize for different use cases. When it comes to spatial indexing structures in particular, I really think the efficiency of the solution tells you more about the implementer than the data structure. Also the same strategies I'll propose to speeding things up also apply in 3 dimensions with octrees.</p> <p><strong>Node Representation</strong></p> <p>So first of all, let's cover the node representation:</p> <pre class="lang-cpp prettyprint-override"><code>// Represents a node in the quadtree. struct QuadNode { // Points to the first child if this node is a branch or the first // element if this node is a leaf. int32_t first_child; // Stores the number of elements in the leaf or -1 if it this node is // not a leaf. int32_t count; }; </code></pre> <p>It's a total of 8 bytes, and this is very important as it's a key part of the speed. I actually use a smaller one (6 bytes per node) but I'll leave that as an exercise to the reader.</p> <p>You can probably do without the <code>count</code>. I include that for pathological cases to avoid linearly traversing the elements and counting them each time a leaf node might split. In most common cases a node shouldn't store that many elements. However, I work in visual FX and the pathological cases aren't necessarily rare. You can encounter artists creating content with a boatload of coincident points, massive polygons that span the entire scene, etc, so I end up storing a <code>count</code>.</p> <p><strong>Where are the AABBs?</strong></p> <p>So one of the first things people might be wondering is where the bounding boxes (rectangles) are for the nodes. I don't store them. I compute them on the fly. I'm kinda surprised most people don't do that in the code I've seen. For me, they're only stored with the tree structure (basically just one AABB for the root).</p> <p>That might seem like it'd be more expensive to be computing these on the fly, but reducing the memory use of a node can proportionally reduce cache misses when you traverse the tree, and those cache miss reductions tend to be more significant than having to do a couple of bitshifts and some additions/subtractions during traversal. Traversal looks like this:</p> <pre class="lang-cpp prettyprint-override"><code>static QuadNodeList find_leaves(const Quadtree&amp; tree, const QuadNodeData&amp; root, const int rect[4]) { QuadNodeList leaves, to_process; to_process.push_back(root); while (to_process.size() &gt; 0) { const QuadNodeData nd = to_process.pop_back(); // If this node is a leaf, insert it to the list. if (tree.nodes[nd.index].count != -1) leaves.push_back(nd); else { // Otherwise push the children that intersect the rectangle. const int mx = nd.crect[0], my = nd.crect[1]; const int hx = nd.crect[2] &gt;&gt; 1, hy = nd.crect[3] &gt;&gt; 1; const int fc = tree.nodes[nd.index].first_child; const int l = mx-hx, t = my-hx, r = mx+hx, b = my+hy; if (rect[1] &lt;= my) { if (rect[0] &lt;= mx) to_process.push_back(child_data(l,t, hx, hy, fc+0, nd.depth+1)); if (rect[2] &gt; mx) to_process.push_back(child_data(r,t, hx, hy, fc+1, nd.depth+1)); } if (rect[3] &gt; my) { if (rect[0] &lt;= mx) to_process.push_back(child_data(l,b, hx, hy, fc+2, nd.depth+1)); if (rect[2] &gt; mx) to_process.push_back(child_data(r,b, hx, hy, fc+3, nd.depth+1)); } } } return leaves; } </code></pre> <p>Omitting the AABBs is one of the most unusual things I do (I keep looking for other people doing it just to find a peer and fail), but I've measured the before and after and it did reduce times considerably, at least on very large inputs, to compact the quadtree node substantially and just compute AABBs on the fly during traversal. Space and time aren't always diametrically opposed. Sometimes reducing space also means reducing time given how much performance is dominated by the memory hierarchy these days. I've even sped up some real world operations applied on massive inputs by compressing the data to quarter the memory use and decompressing on the fly.</p> <p>I don't know why many people choose to cache the AABBs: whether it's programming convenience or if it's genuinely faster in their cases. Yet for data structures which split evenly down the center like regular quadtrees and octrees, I'd suggest measuring the impact of omitting the AABBs and computing them on the fly. You might be quite surprised. Of course it makes sense to store AABBs for structures that don't split evenly like Kd-trees and BVHs as well as loose quadtrees.</p> <p><strong>Floating-Point</strong></p> <p>I don't use floating-point for spatial indexes and maybe that's why I see improved performance just computing AABBs on the fly with right shifts for division by 2 and so forth. That said, at least SPFP seems really fast nowadays. I don't know since I haven't measured the difference. I just use integers by preference even though I'm generally working with floating-point inputs (mesh vertices, particles, etc). I just end up converting them to integer coordinates for the purpose of partitioning and performing spatial queries. I'm not sure if there's any major speed benefit of doing this anymore. It's just a habit and preference since I find it easier to reason about integers without having to think about denormalized FP and all that.</p> <p><strong>Centered AABBs</strong></p> <p>While I only store a bounding box for the root, it helps to use a representation that stores a center and half size for nodes while using a left/top/right/bottom representation for queries to minimize the amount of arithmetic involved.</p> <p><strong>Contiguous Children</strong></p> <p>This is likewise key, and if we refer back to the node rep:</p> <pre class="lang-cpp prettyprint-override"><code>struct QuadNode { int32_t first_child; ... }; </code></pre> <p>We don't need to store an array of children because all 4 children are <em>contiguous</em>:</p> <pre><code>first_child+0 = index to 1st child (TL) first_child+1 = index to 2nd child (TR) first_child+2 = index to 3nd child (BL) first_child+3 = index to 4th child (BR) </code></pre> <p>This not only significantly reduces cache misses on traversal but also allows us to significantly shrink our nodes which further reduces cache misses, storing only one 32-bit index (4 bytes) instead of an array of 4 (16 bytes).</p> <p>This does mean that if you need to transfer elements to just a couple of quadrants of a parent when it splits, it must still allocate all 4 child leaves to store elements in just two quadrants while having two empty leaves as children. However, the trade-off is more than worth it performance-wise at least in my use cases, and remember that a node only takes 8 bytes given how much we've compacted it.</p> <p>When deallocating children, we deallocate all four at a time. I do this in constant-time using an indexed free list, like so:</p> <p><a href="https://i.stack.imgur.com/1oetf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1oetf.png" alt="enter image description here" /></a></p> <p>Except we're pooling out memory chunks containing 4 contiguous elements instead of one at a time. This makes it so we usually don't need to involve any heap allocations or deallocations during the simulation. A group of 4 nodes gets marked as freed indivisibly only to then be reclaimed indivisibly in a subsequent split of another leaf node.</p> <p><strong>Deferred Cleanup</strong></p> <p>I don't update the quadtree's structure right away upon removing elements. When I remove an element, I just descend down the tree to the child node(s) it occupies and then remove the element, but I don't bother to do anything more just yet even if the leaves become empty.</p> <p>Instead I do a deferred cleanup like this:</p> <pre class="lang-cpp prettyprint-override"><code>void Quadtree::cleanup() { // Only process the root if it's not a leaf. SmallList&lt;int&gt; to_process; if (nodes[0].count == -1) to_process.push_back(0); while (to_process.size() &gt; 0) { const int node_index = to_process.pop_back(); QuadNode&amp; node = nodes[node_index]; // Loop through the children. int num_empty_leaves = 0; for (int j=0; j &lt; 4; ++j) { const int child_index = node.first_child + j; const QuadNode&amp; child = nodes[child_index]; // Increment empty leaf count if the child is an empty // leaf. Otherwise if the child is a branch, add it to // the stack to be processed in the next iteration. if (child.count == 0) ++num_empty_leaves; else if (child.count == -1) to_process.push_back(child_index); } // If all the children were empty leaves, remove them and // make this node the new empty leaf. if (num_empty_leaves == 4) { // Push all 4 children to the free list. nodes[node.first_child].first_child = free_node; free_node = node.first_child; // Make this node the new empty leaf. node.first_child = -1; node.count = 0; } } } </code></pre> <p>This is called at the end of every single frame after moving all the agents. The reason I do this kind of deferred removal of empty leaf nodes in multiple iterations and not all at once in the process of removing a single element is that element <code>A</code> might move to node <code>N2</code>, making <code>N1</code> empty. However, element <code>B</code> might, in the same frame, move to <code>N1</code>, making it occupied again.</p> <p>With the deferred cleanup, we can handle such cases without unnecessarily removing children only to add them right back when another element moves into that quadrant.</p> <p>Moving elements in my case is a straightforward: 1) remove element, 2) move it, 3) reinsert it to the quadtree. After we move all the elements and at the end of a frame (not time step, there could be multiple time steps per frame), the <code>cleanup</code> function above is called to remove the children from a parent which has 4 empty leaves as children, which effectively turns that parent into the new empty leaf which might then be cleaned up in the next frame with a subsequent <code>cleanup</code> call (or not if things get inserted to it or if the empty leaf's siblings are non-empty).</p> <p>Let's look at the deferred cleanup visually:</p> <p><a href="https://i.stack.imgur.com/FnfxP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FnfxP.png" alt="enter image description here" /></a></p> <p>Starting with this, let's say we remove some elements from the tree leaving us with 4 empty leaves:</p> <p><a href="https://i.stack.imgur.com/7vh2y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7vh2y.png" alt="enter image description here" /></a></p> <p>At this point, if we call <code>cleanup</code>, it will remove 4 leaves if it finds 4 empty child leaves and turn the parent into an empty leaf, like so:</p> <p><a href="https://i.stack.imgur.com/Cqliu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cqliu.png" alt="enter image description here" /></a></p> <p>Let's say we remove some more elements:</p> <p><a href="https://i.stack.imgur.com/iuG5k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iuG5k.png" alt="enter image description here" /></a></p> <p>... and then call <code>cleanup</code> again:</p> <p><a href="https://i.stack.imgur.com/TVwGG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TVwGG.png" alt="enter image description here" /></a></p> <p>If we call it yet again, we end up with this:</p> <p><a href="https://i.stack.imgur.com/8IB74.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8IB74.png" alt="enter image description here" /></a></p> <p>... at which point the root itself turns into an empty leaf. However, the cleanup method never removes the root (it only removes children). Again the main point of doing it deferred this way and in multiple steps is to reduce the amount of potential redundant work that could occur per time step (which can be a lot) if we did this all immediately every single time an element is removed from the tree. It also helps to distribute that works across frames to avoid stutters.</p> <p>TBH, I originally applied this &quot;deferred cleanup&quot; technique in a DOS game I wrote in C out of sheer laziness! I didn't want to bother with descending down the tree, removing elements, and then removing nodes in a bottom-up fashion back then because I originally wrote the tree to favor top-down traversal (not top-down and back up again) and really thought this lazy solution was a productivity compromise (sacrificing optimal performance to get implemented faster). However, many years later, I actually got around to implementing quadtree removal in ways that immediately started removing nodes and, to my surprise, I actually significantly made it slower with more unpredictable and stuttery frame rates. The deferred cleanup, in spite of originally being inspired by my programmer laziness, was actually (and accidentally) a very effective optimization for dynamic scenes.</p> <p><strong>Singly-Linked Index Lists for Elements</strong></p> <p>For elements, I use this representation:</p> <pre class="lang-cpp prettyprint-override"><code>// Represents an element in the quadtree. struct QuadElt { // Stores the ID for the element (can be used to // refer to external data). int id; // Stores the rectangle for the element. int x1, y1, x2, y2; }; // Represents an element node in the quadtree. struct QuadEltNode { // Points to the next element in the leaf node. A value of -1 // indicates the end of the list. int next; // Stores the element index. int element; }; </code></pre> <p>I use an &quot;element node&quot; which is separate from &quot;element&quot;. An element is only inserted once to the quadtree no matter how many cells it occupies. However, for each cell it occupies, an &quot;element node&quot; is inserted which indexes that element.</p> <p>The element node is a singly-linked index list node into an array, and also using the free list method above. This incurs some more cache misses over storing all the elements contiguously for a leaf. However, given that this quadtree is for very dynamic data which is moving and colliding every single time step, it generally takes more processing time than it saves to seek out a perfectly contiguous representation for the leaf elements (you would effectively have to implement a variable-sized memory allocator which is really fast, and that's far from an easy thing to do). So I use the singly-linked index list which allows a free list constant-time approach to allocation/deallocation. When you use that representation, you can transfer elements from split parents to new leaves by just changing a few integers.</p> <p><strong><code>SmallList&lt;T&gt;</code></strong></p> <p>Oh, I should mention this. Naturally it helps if you don't heap allocate just to store a temporary stack of nodes for non-recursive traversal. <code>SmallList&lt;T&gt;</code> is similar to <code>vector&lt;T&gt;</code> except it won't involve a heap allocation until you insert more than 128 elements to it. It's similar to SBO string optimizations in the C++ standard lib. It's something I implemented and have been using for ages and it does help a lot to make sure you use the stack whenever possible.</p> <p><strong>Tree Representation</strong></p> <p>Here's the representation of the quadtree itself:</p> <pre class="lang-cpp prettyprint-override"><code>struct Quadtree { // Stores all the elements in the quadtree. FreeList&lt;QuadElt&gt; elts; // Stores all the element nodes in the quadtree. FreeList&lt;QuadEltNode&gt; elt_nodes; // Stores all the nodes in the quadtree. The first node in this // sequence is always the root. std::vector&lt;QuadNode&gt; nodes; // Stores the quadtree extents. QuadCRect root_rect; // Stores the first free node in the quadtree to be reclaimed as 4 // contiguous nodes at once. A value of -1 indicates that the free // list is empty, at which point we simply insert 4 nodes to the // back of the nodes array. int free_node; // Stores the maximum depth allowed for the quadtree. int max_depth; }; </code></pre> <p>As pointed out above, we store a single rectangle for the root (<code>root_rect</code>). All sub-rects are computed on the fly. All nodes are stored in contiguously in an array (<code>std::vector&lt;QuadNode&gt;</code>) along with the elements and element nodes (in <code>FreeList&lt;T&gt;</code>).</p> <p><strong><code>FreeList&lt;T&gt;</code></strong></p> <p>I use a <code>FreeList</code> data structure which is basically an array (and random-access sequence) that lets you remove elements from anywhere in constant-time (leaving holes behind which get reclaimed upon subsequent insertions in constant-time). Here's a simplified version which doesn't bother with handling non-trivial data types (doesn't use placement new or manual destruction calls):</p> <pre class="lang-cpp prettyprint-override"><code>/// Provides an indexed free list with constant-time removals from anywhere /// in the list without invalidating indices. T must be trivially constructible /// and destructible. template &lt;class T&gt; class FreeList { public: /// Creates a new free list. FreeList(); /// Inserts an element to the free list and returns an index to it. int insert(const T&amp; element); // Removes the nth element from the free list. void erase(int n); // Removes all elements from the free list. void clear(); // Returns the range of valid indices. int range() const; // Returns the nth element. T&amp; operator[](int n); // Returns the nth element. const T&amp; operator[](int n) const; private: union FreeElement { T element; int next; }; std::vector&lt;FreeElement&gt; data; int first_free; }; template &lt;class T&gt; FreeList&lt;T&gt;::FreeList(): first_free(-1) { } template &lt;class T&gt; int FreeList&lt;T&gt;::insert(const T&amp; element) { if (first_free != -1) { const int index = first_free; first_free = data[first_free].next; data[index].element = element; return index; } else { FreeElement fe; fe.element = element; data.push_back(fe); return static_cast&lt;int&gt;(data.size() - 1); } } template &lt;class T&gt; void FreeList&lt;T&gt;::erase(int n) { data[n].next = first_free; first_free = n; } template &lt;class T&gt; void FreeList&lt;T&gt;::clear() { data.clear(); first_free = -1; } template &lt;class T&gt; int FreeList&lt;T&gt;::range() const { return static_cast&lt;int&gt;(data.size()); } template &lt;class T&gt; T&amp; FreeList&lt;T&gt;::operator[](int n) { return data[n].element; } template &lt;class T&gt; const T&amp; FreeList&lt;T&gt;::operator[](int n) const { return data[n].element; } </code></pre> <p>I have one which does work with non-trivial types and provides iterators and so forth but is much more involved. These days I tend to work more with trivially constructible/destructible C-style structs anyway (only using non-trivial user-defined types for high-level stuff).</p> <p><strong>Maximum Tree Depth</strong></p> <p>I prevent the tree from subdividing too much by specifying a max depth allowed. For the quick simulation I whipped up, I used 8. For me this is crucial since again, in VFX I encounter pathological cases a lot including content created by artists with lots of coincident or overlapping elements which, without a maximum tree depth limit, could want it to subdivide indefinitely.</p> <p>There is a bit of fine-tuning if you want optimal performance with respect to max depth allowed and how many elements you allow to be stored in a leaf before it splits into 4 children. I tend to find the optimal results are gained with something around 8 elements max per node before it splits, and a max depth set so that the smallest cell size is a little over the size of your average agent (otherwise more single agents could be inserted into multiple leaves).</p> <p><strong>Collision and Queries</strong></p> <p>There are a couple of ways to do the collision detection and queries. I often see people do it like this:</p> <pre><code>for each element in scene: use quad tree to check for collision against other elements </code></pre> <p>This is very straightforward but the problem with this approach is that the first element in the scene might be in a totally different location in the world from the second. As a result, the paths we take down the quadtree could be totally sporadic. We might traverse one path to a leaf and then want to go down that same path again for the first element as, say, the 50,000th element. By this time the nodes involved in that path may have already been evicted from the CPU cache. So I recommend doing it this way:</p> <pre><code>traversed = {} gather quadtree leaves for each leaf in leaves: { for each element in leaf: { if not traversed[element]: { use quad tree to check for collision against other elements traversed[element] = true } } } </code></pre> <p>While that's quite a bit more code and requires we keep a <code>traversed</code> bitset or parallel array of some sort to avoid processing elements twice (since they may be inserted in more than one leaf), it helps make sure that we descend the same paths down the quadtree throughout the loop. That helps keep things much more cache-friendly. Also if after attempting to move the element in the time step, it's still encompassed entirely in that leaf node, we don't even need to work our way back up again from the root (we can just check that one leaf only).</p> <p><strong>Common Inefficiencies: Things to Avoid</strong></p> <p>While there are many ways to skin the cat and achieve an efficient solution, there is a common way to achieve a <em>very inefficient</em> solution. And I've encountered my share of <em>very inefficient</em> quadtrees, kd trees, and octrees in my career working in VFX. We're talking over a gigabyte of memory use just to partition a mesh with 100k triangles while taking 30 secs to build, when a decent implementation should be able to do the same hundreds of times a second and just take a few megs. There are many people whipping these up to solve problems who are theoretical wizards but didn't pay much attention to memory efficiency.</p> <p>So the absolute most common no-no I see is to store one or more full-blown containers with each tree node. By full-blown container, I mean something that owns and allocates and frees its own memory, like this:</p> <pre class="lang-cpp prettyprint-override"><code>struct Node { ... // Stores the elements in the node. List&lt;Element&gt; elements; }; </code></pre> <p>And <code>List&lt;Element&gt;</code> might be a list in Python, an <code>ArrayList</code> in Java or C#, <code>std::vector</code> in C++, etc: some data structure that manages its own memory/resources.</p> <p>The problem here is that while such containers are very efficiently implemented for storing a large number of elements, <em>all</em> of them in all languages are extremely inefficient if you instantiate a boatload of them only to store a few elements in each one. One of the reasons is that the container metadata tends to be quite explosive in memory usage at such a granular level of a single tree node. A container might need to store a size, capacity, a pointer/reference to data it allocates, etc, and all for a generalized purpose so it might use 64-bit integers for size and capacity. As a result the metadata just for an empty container might be 24 bytes which is already 3 times larger than the entirety of the node representation I proposed, and that's just for an empty container designed to store elements in leaves.</p> <p>Furthermore each container often wants to either heap/GC-allocate on insertion or require even more preallocated memory in advance (at which point it might take 64 bytes just for the container itself). So that either becomes slow because of all the allocations (note that GC allocations are really fast initially in some implementations like JVM, but that's only for the initial burst Eden cycle) or because we're incurring a boatload of cache misses because the nodes are so huge that barely any fit into the lower levels of the CPU cache on traversal, or both.</p> <p>Yet this is a very natural inclination and makes intuitive sense since we talk about these structures theoretically using language like, <em>&quot;Elements are stored in the leaves&quot;</em> which suggests storing a container of elements in leaf nodes. Unfortunately it has an explosive cost in terms of memory use and processing. So avoid this if the desire is to create something reasonably efficient. Make the <code>Node</code> share and point to (refer to) or index memory allocated and stored for the entire tree, not for every single individual node. In actuality the elements shouldn't be stored in the leaves.</p> <blockquote> <p>Elements should be stored in the <em>tree</em> and leaf nodes should <em>index</em> or <em>point to</em> those elements.</p> </blockquote> <p><strong>Conclusion</strong></p> <p>Phew, so those are the main things I do to achieve what is hopefully considered a decent-performing solution. I hope that helps. Note that I am aiming this at a somewhat advanced level for people who have already implemented quadtrees at least once or twice. If you have any questions, feel free to shoot.</p> <p>Since this question is a bit broad, I might come and edit it and keep tweaking and expanding it over time if it doesn't get closed (I love these types of questions since they give us an excuse to write about our experiences working in the field, but the site doesn't always like them). I'm also hoping some experts might jump in with alternative solutions I can learn from and perhaps use to improve mine further.</p> <p>Again quadtrees aren't actually my favorite data structure for extremely dynamic collision scenarios like this. So I probably have a thing or two to learn from people who do favor quadtrees for this purpose and have been tweaking and tuning them for years. Mostly I use quadtrees for static data that doesn't move around every frame, and for those I use a very different representation from the one proposed above.</p>
23,830,413
Broker architectural pattern in plain english
<p>Could someone explain the <a href="http://en.wikipedia.org/wiki/Broker_Pattern" rel="noreferrer">Broker pattern</a> to me in plain english? Possibly in terms of Java or a real life analogy.</p>
23,830,667
1
3
null
2014-05-23 13:23:09.347 UTC
7
2014-05-23 13:43:55.223 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
992,426
null
1
32
java|design-patterns|broker
13,236
<p>Try to imagine that 10 people have messages they need to deliver. Another 10 people are expecting messages from the previous group. In an open environment, each person in the first group would have to deliver their message to the recipient manually, so each person has to visit at least one member of the second group. This is inefficient and chaotic.</p> <p>In broker, there is a control class (in this case the postman) who receives all the messages from group one. The broker then organizes the messages based off destination and does any operations needed, before visiting each recipient once to deliver all messages for them. This is far more efficient. </p> <p>In software design, this lets remote and heterogeneous classes communicate with each other easily. The control class has an interface which all incoming messages can interact with so a sorts of messages can be sent and interpreted correctly. Keep in mind this is not very scalable, so it loses effectiveness for larger systems.</p> <p>Hope this helped!</p>
18,377,554
C# There is an error in XML document (2, 2)
<p>I'm trying to deserialize the following XML :</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;XGResponse&gt;&lt;Failure code="400"&gt; Message id &amp;apos;1&amp;apos; was already submitted. &lt;/Failure&gt;&lt;/XGResponse&gt; </code></pre> <p>through this call :</p> <pre><code>[...] var x = SerializationHelper.Deserialize&lt;XMLGateResponse.XGResponse&gt;(nResp); [...] public static T Deserialize&lt;T&gt;(string xml) { using (var str = new StringReader(xml)) { var xmlSerializer = new XmlSerializer(typeof(T)); return (T)xmlSerializer.Deserialize(str); } } </code></pre> <p>to get an instance of the corresponding class :</p> <pre><code>//------------------------------------------------------------------------------ // &lt;auto-generated&gt; // This code was generated by a tool. // Runtime Version:4.0.30319.18052 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // &lt;/auto-generated&gt; //------------------------------------------------------------------------------ using System.Xml.Serialization; // // This source code was auto-generated by xsd, Version=4.0.30319.1. // namespace XMLGateResponse { /// &lt;remarks/&gt; [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)] public partial class XGResponse { private object[] itemsField; /// &lt;remarks/&gt; [System.Xml.Serialization.XmlElementAttribute("Failure", typeof(Failure))] [System.Xml.Serialization.XmlElementAttribute("Success", typeof(Success))] public object[] Items { get { return this.itemsField; } set { this.itemsField = value; } } } /// &lt;remarks/&gt; [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)] public partial class Failure { private string codeField; private string titleField; private string valueField; /// &lt;remarks/&gt; [System.Xml.Serialization.XmlAttributeAttribute(DataType = "NMTOKEN")] public string code { get { return this.codeField; } set { this.codeField = value; } } /// &lt;remarks/&gt; [System.Xml.Serialization.XmlAttributeAttribute()] public string title { get { return this.titleField; } set { this.titleField = value; } } /// &lt;remarks/&gt; [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return this.valueField; } set { this.valueField = value; } } } /// &lt;remarks/&gt; [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/XMLGateResponse")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLGateResponse", IsNullable = false)] public partial class Success { private string titleField; /// &lt;remarks/&gt; [System.Xml.Serialization.XmlAttributeAttribute()] public string title { get { return this.titleField; } set { this.titleField = value; } } } } </code></pre> <p>But it raise the error <code>There is an error in XML document (2, 2)</code>. <br/>I've looked for a solution to this for about an hour now, but it didn't help much.</p> <p>I even tried a slight change which should not do anything :</p> <pre><code>public static T Deserialize&lt;T&gt;(string xml) { [...] var xmlSerializer = new XmlSerializer(typeof(T), new XmlRootAttribute(typeof(T).Name)); [...] } </code></pre> <p>Yet, this does prevent the error to happen. But since it only achieve to return me a XMLGateResponse.XGResponse instance fully empty (every elements/attributes are null), it's not really an improvement.</p> <p>I know this kind of question <code>There is an error in XML document (2, 2)</code> has been discussed a lot already, but I really didn't find a solution that worked for me.</p>
18,377,750
2
4
null
2013-08-22 10:12:01.953 UTC
1
2018-01-08 09:58:43.613 UTC
null
null
null
null
876,706
null
1
11
c#|xml-deserialization
69,704
<p>XGResponse is decorated with an <code>XmlRootAttribute</code> that specifies a default namspace name but your document does not.</p> <p>Either remove this namespace declaration or add <code>xmlns="http://tempuri.org/XMLGateResponse"</code> to the root element of you xml</p>
16,015,088
How to set aggregation with grouping in ng-grid
<p>I want to see totals (or generally any aggregation function) for each group in a grid.</p> <p>This was requested and closed as done in issue: <a href="https://github.com/angular-ui/ng-grid/issues/95" rel="nofollow">https://github.com/angular-ui/ng-grid/issues/95</a> (but unfortunately without any example).</p> <p>I am able to redefine default template <a href="https://github.com/angular-ui/ng-grid/blob/master/src/templates/aggregateTemplate.html" rel="nofollow">https://github.com/angular-ui/ng-grid/blob/master/src/templates/aggregateTemplate.html</a> by <code>aggregateTemplate</code> config option. But I don't know how to extend it properly.</p> <p>This template is evaluating in ng-grid scope and I don't know how to trigger my custom aggregation function. I want to create similar function as '''totalChildren''' (from <a href="https://github.com/angular-ui/ng-grid/blob/master/src/classes/aggregate.js" rel="nofollow">https://github.com/angular-ui/ng-grid/blob/master/src/classes/aggregate.js</a> )</p> <p>Any ideas?</p>
16,019,015
1
0
null
2013-04-15 12:24:50.95 UTC
12
2013-09-12 18:20:08.383 UTC
2013-09-12 18:20:08.383 UTC
null
1,632,669
null
1,045,752
null
1
7
angularjs|angular-ui|ng-grid
16,077
<p>I found the answer: <a href="https://github.com/angular-ui/ng-grid/issues/290">https://github.com/angular-ui/ng-grid/issues/290</a></p> <p>For a completenes here is an example of my aggredate function:</p> <pre><code>function WorkLoadCtrl($scope, Issue, $routeParams, HttpCache) { $scope.issues = Issue.jql_search({jql: $routeParams.jql}); $scope.aggFC = function (row) { var res = 0; var calculateChildren = function(cur) { var res = 0; var remaining; angular.forEach(cur.children, function(a) { remaining = a.getProperty('fields.timetracking.remainingEstimateSeconds'); if (remaining) { res += remaining; } }); return res; }; var calculateAggChildren = function(cur) { var res = 0; res += calculateChildren(cur); angular.forEach(cur.aggChildren, function(a) { res += calculateAggChildren(a); }); return res; }; return (calculateAggChildren(row) / 3600).toFixed(2); } $scope.mySelections = []; $scope.gridOptions = { data: 'issues.issues', columnDefs: [ {field:'key', displayName:'key'}, {field:'fields.assignee.name', displayName:'Assignee'}, {field:'fields.status.name', displayName:'Status'}, {field:'fields.summary', displayName:'Summary'}, {field:'fields.timetracking.remainingEstimate', displayName:'Remaining'}, ], showFooter: true, showGroupPanel: true, enablePinning: true, enableColumnResize: true, enableColumnReordering: true, showColumnMenu: true, showFilter: true, //jqueryUIDraggable: true, bug: when used grouping stop work, but column reordering start to work:( selectedItems: $scope.mySelections, multiSelect: false, aggregateTemplate: '&lt;div ng-click="row.toggleExpand()" ng-style="rowStyle(row)" class="ngAggregate"&gt; &lt;span class="ngAggregateText"&gt;{{row.label CUSTOM_FILTERS}} (count: {{row.totalChildren()}} {{AggItemsLabel}} Remaining: {{aggFC(row)}})&lt;/span&gt; &lt;div class="{{row.aggClass()}}"&gt;&lt;/div&gt; &lt;/div&gt;' }; } </code></pre>
18,844,199
How to fetch a remote file (e.g. from Github) in a Puppet file resource?
<pre><code>file { 'leiningen': path =&gt; '/home/vagrant/bin/lein', ensure =&gt; 'file', mode =&gt; 'a+x', source =&gt; 'https://raw.github.com/technomancy/leiningen/stable/bin/lein', } </code></pre> <p>was my idea, but Puppet doesn’t know <code>http://</code>. Is there something about <code>puppet://</code> I have missed?</p> <p>Or if not, is there a way to declaratively fetch the file first and then use it as a local source?</p>
18,846,683
5
2
null
2013-09-17 07:50:42.627 UTC
8
2018-04-25 16:18:01.33 UTC
null
null
null
null
1,382,925
null
1
33
http|puppet
40,281
<p>Before Puppet 4.4, as per <a href="https://docs.puppet.com/puppet/4.3/type.html#file-attribute-source" rel="noreferrer">http://docs.puppetlabs.com/references/latest/type.html#file</a>, the file source only accepts <strong>puppet://</strong> or <strong>file://</strong> URIs.</p> <p>As of Puppet 4.4+, <a href="https://docs.puppet.com/puppet/4.4/type.html#file-attribute-source" rel="noreferrer">your original code would be possible</a>.</p> <p>If you're using an older version, one way to achieve what you want to do without pulling down the entire Git repository would be to use the <strong>exec</strong> resource to fetch the file.</p> <pre><code>exec{'retrieve_leiningen': command =&gt; "/usr/bin/wget -q https://raw.github.com/technomancy/leiningen/stable/bin/lein -O /home/vagrant/bin/lein", creates =&gt; "/home/vagrant/bin/lein", } file{'/home/vagrant/bin/lein': mode =&gt; 0755, require =&gt; Exec["retrieve_leiningen"], } </code></pre> <p>Although the use of <strong>exec</strong> is somewhat frowned upon, it can be used effectively to create your own types. For example, you could take the snippet above and create your own resource type.</p> <pre><code>define remote_file($remote_location=undef, $mode='0644'){ exec{"retrieve_${title}": command =&gt; "/usr/bin/wget -q ${remote_location} -O ${title}", creates =&gt; $title, } file{$title: mode =&gt; $mode, require =&gt; Exec["retrieve_${title}"], } } remote_file{'/home/vagrant/bin/lein': remote_location =&gt; 'https://raw.github.com/technomancy/leiningen/stable/bin/lein', mode =&gt; '0755', } </code></pre>
35,253,914
My angular 2 app takes a long time to load for first time users, I need help to speed it up
<p>Below I have pasted in my app.ts file.</p> <p>I'm using angular2, with firebase and typescript.</p> <p>Is the reason its slow because I have a lot of routes and I'm injecting a lot of files?</p> <p>Also, my app works fine its just for first time users visiting the homepage I have this issue for.</p> <p>I'm not sure if the bootstrap can be improved at the bottom or if I'm doing anything wrong.</p> <p><strong>This is my app.ts file:</strong></p> <pre><code>import {Component, bind, provide, Injectable} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser' import {NgIf} from 'angular2/common'; import {Router, Location, ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF, CanActivate, OnActivate, ComponentInstruction} from 'angular2/router'; import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http'; import {ANGULAR2_GOOGLE_MAPS_PROVIDERS} from 'angular2-google-maps/core'; import {enableProdMode} from 'angular2/core'; enableProdMode(); import {LoggedInRouterOutlet} from './interceptor'; import {AuthService} from './services/authService/authService'; import {SocialService} from './services/socialService/socialService'; import {UserService} from './services/userService/userService'; import {OrganisationService} from './services/organisationService/organisationService'; import {NotificationService} from './services/notificationService/notificationService'; import {EmailService} from './services/emailService/emailService'; import {UserProfile} from './models/profile/profile'; import {Organisation} from './models/organisation/organisation'; import {HeaderNavigation} from './components/header/header'; import {HeaderNavigationLoggedIn} from './components/header/headerNavigationLoggedIn'; import {HeaderNavigationLoggedInCompany} from './components/header/headerNavigationLoggedInCompany'; import {Footer} from './components/footer/footer'; import {SideMenuCompany} from './components/header/sideMenuCompany'; import {SideMenuUser} from './components/header/sideMenuUser'; import {Splash} from './components/splash/splash'; import {CreateJob} from './components/createJob/createJob'; import {SearchJobs} from './components/searchJobs/searchJobs'; import {Login} from './components/login/login'; import {Applications} from './components/applications/applications'; import {Register} from './components/register/register'; import {ForgotPassword} from './components/forgotpassword/forgotpassword'; import {ChangePassword} from './components/changepassword/changepassword'; import {ChangeEmail} from './components/changeemail/changeemail'; import {SocialRegister} from './components/socialregister/socialregister'; import {Admin} from './components/admin/admin'; import {Contact} from './components/contact/contact'; import {SearchUsers} from './components/searchusers/searchusers'; import {Jobs} from './components/job/jobs'; import {CompanyProfile} from './components/company/company'; import {Home} from './components/home/home'; import {Dashboard} from './components/dashboard/dashboard'; import {Profile} from './components/profile/profile'; import {UserApplications} from './components/userApplications/userApplications'; @Component({ selector: 'app', providers: [UserService, UserProfile, OrganisationService, Organisation], template: ` &lt;Splash *ngIf="isLoggedIn"&gt;&lt;/Splash&gt; &lt;HeaderNavigation *ngIf="!isLoggedIn"&gt;&lt;/HeaderNavigation&gt; &lt;HeaderNavigationLoggedIn *ngIf="isLoggedIn &amp;&amp; isUserLogin"&gt;&lt;/HeaderNavigationLoggedIn&gt; &lt;HeaderNavigationLoggedInCompany *ngIf="isLoggedIn &amp;&amp; isCompanyLogin"&gt;&lt;/HeaderNavigationLoggedInCompany&gt; &lt;SideMenuCompany *ngIf="isLoggedIn &amp;&amp; isCompanyLogin"&gt;&lt;/SideMenuCompany&gt; &lt;SideMenuUser *ngIf="isLoggedIn &amp;&amp; isUserLogin"&gt;&lt;/SideMenuUser&gt; &lt;div class="content"&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt; `, directives: [RouterOutlet, RouterLink, Splash, HeaderNavigation, HeaderNavigationLoggedIn, NgIf, HeaderNavigationLoggedInCompany, SideMenuCompany, SideMenuUser, Footer, LoggedInRouterOutlet] }) @RouteConfig([ { path: '/', component: Home, as: 'Home', data:{title: 'Welcome Home'}}, { path: '/home', component: Home, as: 'Home', useAsDefault: true}, { path: '/login', component: Login, as: 'Login' }, { path: '/register/:id', component: Register, as: 'Register' }, { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' }, { path: '/dashboard', component: Dashboard, as: 'Dashboard' }, { path: '/search', component: SearchJobs, as: 'Search' }, { path: '/profile', component: Profile, as: 'Profile' }, { path: '/settings', component: CompanyProfile, as: 'Settings' }, { path: '/jobs', component: Jobs, as: 'Jobs' }, { path: '/password', component: ChangePassword, as: 'Password' }, { path: '/email', component: ChangeEmail, as: 'Email' }, { path: '/applications', component: Applications, as: 'Applications' }, { path: '/socialRegister/:id', component: SocialRegister, as: 'SocialRegister' }, { path: '/socialRegister', component: SocialRegister, as: 'SocialRegister' }, { path: '/applys', component: UserApplications, as: 'Applys' }, { path: '/contact', component: Contact, as: 'Contact' }, { path: '/searchTeachers', component: SearchUsers, as: 'SearchUsers' }, { path: '/createJob', component: CreateJob, as: 'CreateJob' }, { path: '/adminmarkchris2016', component: Admin, as: 'AdminMarkChris2016' }, { path:'/**', redirectTo: ['Home']} ]) @Injectable() export class AppComponent { router: Router; location: Location; authService: AuthService; userService: UserService isLoggedIn: boolean = false; isCompanyLogin: boolean = false; isUserLogin: boolean = false; userProfile: UserProfile; constructor(_router: Router, _location: Location, _authService: AuthService, _userService: UserService, _userProfile: UserProfile){ this.router = _router; this.location = _location; this.authService = _authService; this.userService = _userService; this.userProfile = _userProfile; this.isUserLoggedIn(this.location.path()); //On refresh this.router.subscribe((currentRoute) =&gt; { this.isUserLoggedIn(currentRoute); }) } isUserLoggedIn(currentRoute): void{ this.authService.checkIfLoggedIn().then((response) =&gt; { this.isLoggedIn = response if(this.isLoggedIn){ this.isUserOrganisationOrTeacher(); } if(currentRoute.substring(0, 14) == "socialRegister" || currentRoute == "socialRegister" || currentRoute == "home" || currentRoute == "contact" || currentRoute == "" || currentRoute == "forgotpassword" || currentRoute == "login" || currentRoute.substring(0, 8) == "register"){ this.isCompanyLogin = false; this.isUserLogin = false; this.isLoggedIn = false; } }); } isUserOrganisationOrTeacher(): void{ this.userService.checkIfProfileExists().then((response) =&gt; { this.isCompanyLogin = false; this.isUserLogin = false; if(response){ this.isUserLogin = true; this.isCompanyLogin = false; }else{ this.isCompanyLogin = true; this.isUserLogin = false; } }); } } bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), HTTP_PROVIDERS, AuthService, SocialService, UserService, EmailService, OrganisationService, NotificationService, ANGULAR2_GOOGLE_MAPS_PROVIDERS]); </code></pre>
35,254,018
6
11
null
2016-02-07 13:13:16.927 UTC
23
2020-02-17 09:45:50.297 UTC
2016-02-08 05:01:44.813 UTC
null
1,905,476
null
1,590,389
null
1
43
typescript|angular
70,018
<p>To have something ready for production (and speed it up), you need to package it.</p> <p>I mean transpiling all files into JavaScript ones and concat them the same way Angular2 does for example. This way you will have several modules contained into a single JS file. This way you will reduce the number of HTTP calls to load your application code into the browser.</p> <p>As a matter of fact, for the following configuration of SystemJS, you will have one call per module (it's suitable for development but not really efficient in production):</p> <pre class="lang-html prettyprint-override"><code> &lt;script&gt; System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } } }); System.import('app/boot') .then(null, console.error.bind(console)); &lt;/script&gt; </code></pre> <p>This answer could give hints about how module resolution works:</p> <ul> <li><a href="https://stackoverflow.com/questions/35253719/how-does-angular2-resolve-imports/35253891#35253891">How does Angular2 resolve imports?</a></li> </ul> <p>You can do this packaging using Gulp and its plugins:</p> <ul> <li><a href="https://www.npmjs.com/package/gulp-tsc" rel="nofollow noreferrer">https://www.npmjs.com/package/gulp-tsc</a></li> <li><a href="https://github.com/contra/gulp-concat" rel="nofollow noreferrer">https://github.com/contra/gulp-concat</a></li> </ul> <p>See the following answers:</p> <ul> <li><a href="https://stackoverflow.com/questions/24591854/using-gulp-to-concatenate-and-uglify-files">Using Gulp to Concatenate and Uglify files</a></li> <li><a href="https://github.com/JavascriptMick/angular2-gulp-typescript/blob/master/gulpfile.js" rel="nofollow noreferrer">https://github.com/JavascriptMick/angular2-gulp-typescript/blob/master/gulpfile.js</a></li> </ul>
5,281,007
Bookmarklets Which Creates An Overlay On Page
<p>I've been looking for a way to show a simple red div on the top-right corner of a page using a bookmarklet, but can't seem to find any tutorial on it on the web. Can anybody give me a quick rundown on how I can create such a bookmarklet?</p>
5,281,040
2
0
null
2011-03-12 06:30:51.53 UTC
12
2011-03-13 13:24:03.59 UTC
null
null
null
null
576,589
null
1
4
javascript|jquery|html|bookmarklet
3,912
<p>To create a bookmarklet in general or just how to display the box using javascript?</p> <h1>Adding your stuff to the body in the top-right corner</h1> <p>Let's start with the latter part - you tagged jquery, so lets go with that (might be a bit heavy for a bookmarklet, though):</p> <pre><code>// create the element: var $e = $('&lt;div id=&quot;yourelement&quot;&gt;&lt;/div&gt;'); // append it to the body: $('body').append($e); // style it: $e.css({ position: 'absolute', top: '10px', right: '10px', width: '200px', height: '90px', backgroundColor: 'red' }); </code></pre> <p>that's all you need for that...</p> <h1>Easiest way to create your bookmarklet and include jquery</h1> <p>What we need to do:</p> <ol> <li>Save the code from above into a javascript file hosted on your server.</li> <li>create a piece of javascript code that adds jquery and your newly hosted javascript file to the current page's body</li> <li>place that javascript code inside an <code>&lt;a&gt;</code> tag.</li> </ol> <p>This is the code to do that:</p> <pre><code>javascript:var i,s,ss=['http://yourdomain.com/path-to-your-script','http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js'];for(i=0;i!=ss.length;i++){s=document.createElement('script');s.src=ss[i];document.body.appendChild(s);}void(0); </code></pre> <p>It's just looping through an array and attaching <code>&lt;script&gt;</code> tags to its body with the path to both javascript files as <code>src</code>.</p> <p>As for creating the bookmarklet itself, you just place all the code inside <code>&lt;a&gt;</code> tag, sort of like this (watch out for double-quotes):</p> <pre><code>&lt;a href=&quot;javascript:javascript:var i,s,ss=['http://yourdomain.com/path-to-your-script','http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js'];for(i=0;i!=ss.length;i++){s=document.createElement('script');s.src=ss[i];document.body.appendChild(s);}void(0);&quot;&gt;Drag me to your toolbar&lt;/a&gt; </code></pre> <p>And that's it.</p> <p>Note that the bookmarklet actually overrides the jquery version used on the site, if there is one .. could break some sites...</p> <p>More information about creating bookmarklets:</p> <p><a href="http://betterexplained.com/articles/how-to-make-a-bookmarklet-for-your-web-application/" rel="noreferrer">http://betterexplained.com/articles/how-to-make-a-bookmarklet-for-your-web-application/</a></p>
5,515,257
Android: Understanding Intent-Filters
<p>I would like to create an Intent-Filter, so that certain links will trigger the start of my application (see this stackoverflow-thread for example: <a href="https://stackoverflow.com/questions/2430045/how-to-register-some-url-namespace-myapp-app-start-for-accessing-your-progra/2430468#2430468">How to register some URL namespace (myapp://app.start/) for accessing your program by calling a URL in browser in Android OS?</a> )</p> <p>While trying, I figured out, that I dont quite understand how Intents and Intent-Filters (defined in the Manifest.xml) actually work. What is the difference between the following:</p> <pre><code>&lt;action android:name="android.intent.action.VIEW" /&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; </code></pre> <p>or the following:</p> <pre><code>&lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.MAIN" /&gt; </code></pre> <p>And what is actually the difference between category and action Intent-Filters. I read this page <a href="http://developer.android.com/reference/android/content/Intent.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/content/Intent.html</a> but I still missing a basic understanding.</p>
5,516,068
2
0
null
2011-04-01 15:09:28.653 UTC
18
2016-08-22 14:02:51.553 UTC
2017-05-23 12:00:17.993 UTC
null
-1
null
351,723
null
1
33
android|android-intent|intentfilter
18,464
<p>Instead of looking at it from your app's point of view, flip it around and look at it from the Intent side.</p> <p>When an Intent is created, the creator has no idea what apps are on the system to handle that Intent. But the creator does know what it wants to do (e.g., an app might want to let the user pick out a contact from somewhere on the device), and needs to reach out to other apps on the system to ask for what's desired.</p> <p>To do this, Intents have several pieces of information attached to them. Among them are actions and categories.</p> <p>The actions define in a general way the action the Intent wants to do, like VIEW a contact, PICK an image from the Gallery, etc.</p> <p>The category is an additional piece of information that gives the Intent another way to differentiate itself. For example, when a link in the browser is clicked, the Intent that is created has the BROWSABLE category attached to it.</p> <p>So, when the OS resolves the Intent, it will look for registered Activities or BroadcastReceivers that have an intent filter that includes <strong>all</strong> of pieces of information. If the Intent specifies the PICK action, Activities that do not have an intent-filter with the PICK action will be discarded from the list of candidates to handle the Intent.</p> <p>In this way, the combined set of action, categories, type, and (possibly) scheme associated with an Intent serve to pinpoint the set of Activities that can handle the Intent. When you set up your intent-filter in your manifest, you are telling the OS which class of Intents you can handle.</p>
5,262,881
Mocking objects without no-argument constructor in C# / .NET
<p>Is it possible to create a mock from a class that doesn't provide a no-argument constructor and don't pass any arguments to the constructor? Maybe with creating IL dynamically?</p> <p>The background is that I don't want to define interfaces only for testing. The workaround would be to provide a no-argument constructor for testing.</p>
5,263,019
2
4
null
2011-03-10 16:43:45.683 UTC
null
2011-03-10 18:44:23.237 UTC
null
null
null
null
238,134
null
1
43
c#|.net|reflection|constructor|mocking
26,528
<p>Sure thing. In this example i'll use Moq, a really awesome mocking library.</p> <p>Example:</p> <pre><code>public class MyObject { public MyObject(object A, object B, object C) { // Assign your dependencies to whatever } } Mock&lt;MyObject&gt; mockObject = new Mock&lt;MyObject&gt;(); Mock&lt;MyObject&gt; mockObject = new Mock&lt;MyObject&gt;(null, null, null); // Pass Nulls to specific constructor arguments, or 0 if int, etc </code></pre> <p>In many cases though, I assign Mock objects as the arguments so I can test the dependencies:</p> <pre><code>Mock&lt;Something&gt; x = new Mock&lt;Something&gt;(); MyObject mockObject = new MyObject(x.Object); x.Setup(d =&gt; d.DoSomething()).Returns(new SomethingElse()); etc </code></pre>
963,971
How to conditionally style a row in a rich:dataTable
<p>How can I change the style of a particular row based on a condition? I can use JSF EL in rich:column style class attribute, but I have to write for each column. I want to change the entire row.</p> <p>Thanks</p>
967,401
7
0
null
2009-06-08 09:00:30.077 UTC
4
2014-01-15 12:02:01.977 UTC
null
null
null
null
4,206
null
1
21
jsf|seam|richfaces
50,301
<p>I do as you've already mentioned and put the style on the column.</p> <p>However you could always try wrapping all of your columns in a <code>&lt;rich:columnGroup&gt;</code> which is supposed to output a <code>&lt;tr&gt;</code> and place your conditional style on that.</p> <p><strong>EDIT:</strong> (in response to comment): if the header facets in your columns are being broken then you can separate them into a column group as well. Should work - you may not even need the column group in the header??</p> <p>Eg.</p> <pre><code>&lt;rich:dataTable&gt; &lt;f:facet name="header"&gt; &lt;rich:columnGroup&gt; &lt;rich:column&gt;Header 1&lt;/rich:column&gt; &lt;rich:column&gt;Header 1&lt;/rich:column&gt; &lt;/rich:columnGroup&gt; &lt;/f:facet&gt; &lt;rich:columnGroup&gt; &lt;rich:column&gt;Data&lt;/rich:column&gt; &lt;rich:column&gt;Data&lt;/rich:column&gt; &lt;/rich:columnGroup&gt; &lt;/rich:dataTable&gt; </code></pre>
106,800
Unit Testing Guidelines
<p>Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):</p> <ul> <li>Should tests be in the same project as application logic?</li> <li>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</li> <li>How should I name my test classes, methods, and projects (if they go in different projects)</li> <li>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</li> <li>Should unit and integration tests be separated?</li> <li>Is there a <strong>good</strong> reason not to have 100% test coverage?</li> </ul> <p>What am I not asking about that I should be?</p> <p>An online resource would be best.</p>
106,813
7
0
null
2008-09-20 02:19:11.75 UTC
10
2012-04-20 18:11:39.017 UTC
2009-03-17 06:56:17.053 UTC
Ian Suttle
19,421
Ian Suttle
19,421
null
1
23
unit-testing|tdd
4,871
<p>I would recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0321146530" rel="noreferrer" rel="nofollow noreferrer">Kent Beck's</a> book on TDD.</p> <p>Also, you need to go to <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Martin Fowler's</a> site. He has a lot of good information about testing as well.</p> <p>We are pretty big on TDD so I will answer the questions in that light.</p> <blockquote> <p>Should tests be in the same project as application logic?</p> </blockquote> <p>Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests</p> <blockquote> <p>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</p> </blockquote> <p>Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution.</p> <blockquote> <p>How should I name my test classes, methods, and projects (if they go in different projects)</p> </blockquote> <p>I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so:</p> <pre><code>public class UserBehavior </code></pre> <p>Methods should be named to describe the behavior that you expect.</p> <pre><code>public void ShouldBeAbleToSetUserFirstName() </code></pre> <p>Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization.</p> <blockquote> <p>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</p> </blockquote> <p>Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change.</p> <blockquote> <p>Should unit and integration tests be separated?</p> </blockquote> <p>Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well.</p> <blockquote> <p>Is there a good reason not to have 100% test coverage?</p> </blockquote> <p>I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point.</p> <p>In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.</p>
624,821
Vim split line command
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/237383/how-do-i-insert-a-linebreak-where-the-cursor-is-without-entering-into-insert-mod">How do I insert a linebreak where the cursor is without entering into insert mode in Vim?</a> </p> </blockquote> <p>In vim, <kbd>J</kbd> joins the next line to the current line. Is there a similar one-key (or relatively short) command to split a line at a given cursor position? I know it be done with a simple macro, but it seems like if the <kbd>J</kbd>-command exists there should be a similar function. I've tried searching for it, but can't seem to find an answer.</p>
624,835
7
2
null
2009-03-09 02:32:55.01 UTC
20
2014-05-31 09:53:58.027 UTC
2017-05-23 12:10:26.633 UTC
Paul Tomblin
-1
dburke
72,656
null
1
93
vim
63,560
<p>I don't think that there is a single key command for this. The best you can do with stock vim is probably <kbd>i</kbd> <kbd>Enter</kbd> <kbd>Esc</kbd>.</p>
343,811
Is there a jQuery Click method?
<p>I'm trying to click on a link using jquery. There only appears to be a click event that replicates "onclick" (i.e user input). Is it possible to use jquery to actually click a link?</p>
344,186
8
1
null
2008-12-05 13:21:59.057 UTC
8
2011-07-27 12:43:55.44 UTC
null
null
null
Jeff Banks
43,626
null
1
25
jquery
52,193
<p>From your answer: </p> <pre><code>$("a[0]") </code></pre> <p>is not a valid selector. to get the first a on the page use: </p> <pre><code>$("a:first") </code></pre> <p>or </p> <pre><code>$("a").eq(0). </code></pre> <p>So for the selector in your answer:</p> <pre><code>$("table[1]/tr[1]/td[1]/a").trigger('click'); </code></pre> <p>write </p> <pre><code>$("table").eq(1).children("tr").eq(1).children('td').eq(1).children('a').click(); </code></pre> <p>Note how this will click all the links in the second table cell of the second table row in the second table on your page.<br> If you use this method to redirect the page to the href of the a the following method is slightly nicer:</p> <pre><code>document.location = $("table").eq(1).children("tr").eq(1).children('td').eq(1).children('a').attr('href'); </code></pre> <p>Note how this will set the document location to the href of the first a found in the second table cell of the second table row found in the second table on the page.<br> If you want to match the first elements use eq(0) instead of eq(1). </p> <p><B>EDIT</B><br> If you really want to do this 1337-haxxor</p> <pre><code>$("table:eq(1) &gt; tr:eq(1) &gt; td:eq(1) &gt; a").click(); </code></pre> <p>however I think the other method is more readible.</p> <p><b>EDIT</b></p> <p>Okay, from you next answer/question thingie<br> How about not actually clicking on the link but just setting the document.location string to it:</p> <pre><code>document.location = $("table").eq(0).children("tr").eq(0).children('td').eq(0).children('a').eq(0).attr('href'); </code></pre>
949,352
Is there something like instanceOf(Class<?> c) in Java?
<p>I want to check if an object <code>o</code> is an instance of the class <code>C</code> or of a subclass of <code>C</code>.</p> <p>For instance, if <code>p</code> is of class <code>Point</code> I want <code>x.instanceOf(Point.class)</code> to be <code>true</code> and also <code>x.instanceOf(Object.class)</code> to be <code>true</code>.</p> <p>I want it to work also for boxed primitive types. For instance, if <code>x</code> is an <code>Integer</code> then <code>x.instanceOf(Integer.class)</code> should be <code>true</code>.</p> <p>Is there such a thing? If not, how can I implement such a method?</p>
949,392
8
1
null
2009-06-04 08:53:55.823 UTC
10
2021-10-02 08:23:05.393 UTC
2016-07-05 01:20:57.347 UTC
null
1,850,609
null
110,028
null
1
97
java|reflection|instanceof
96,885
<p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)" rel="noreferrer">Class.isInstance</a> does what you want.</p> <pre><code>if (Point.class.isInstance(someObj)){ ... } </code></pre> <p>Of course, you shouldn't use it if you could use <code>instanceof</code> instead, but for reflection scenarios it often comes in handy.</p>
312,702
is it safe to keep database connections open for long time
<p>I have a .net client application which is connected to a remote database. Is it safe to keep a single connection open for the lifetime of the client (hours)?</p> <p>Does the answer hold if I have multiple (10 or 100) clients running?</p>
312,719
9
0
null
2008-11-23 16:46:49.397 UTC
18
2020-10-08 12:39:03.527 UTC
2020-10-08 12:39:03.527 UTC
null
11,737,639
DanJ
4,697
null
1
42
.net|database|database-connection
28,954
<p>Absolutely it is safe to do this. This is how client-server applications work. If you are using a three-tier application, the application server will keep a pool of connections open anyway.</p> <p>Scalability is an issue, or at least used to be in the days that machines had less memory than modern kit. With a two-tier (client-server) application, each client opened a connection and held it open. This had several effects:</p> <ul> <li><p>Memory was used per-connection, so large numbers of (relatively) idle connections would use up machine memory. However, a modern 64-bit server can have tens or hundreds of GB of memory, so it could support a very large number of such connections.</p></li> <li><p>If a transaction was left uncommitted on the client machine, the locks would be held open for as long as the transaction was open. This led to a class of problems when someone could start a transaction, go off to lunch and forget they had left something open. This would lock any records referenced by the transaction for hours at a time.</p></li> <li><p>Transactions could, however easily cover multiple acceses to the database, which is harder to do with a conneciton pool.</p></li> </ul> <p>A pooled architecture, which is common on 3-tier architectures has a finite number of connections between the application server and the database. Queries simply use the next available connection and updates are committed immediately. This uses less resources as you only have a finite number of connections open, and (in conjunction with an <a href="https://stackoverflow.com/questions/129329/optimistic-vs-pessimistic-locking#129397">optimistic concurrency</a> strategy) will eliminate a large of potential application concurrency issues.</p> <p>In order to use <a href="http://en.wikipedia.org/wiki/Long-running_transaction" rel="noreferrer">long transactions</a> (i.e. transactions that cover more than one call to the database) one has to de-couple the transaction from the connection. This is the basic architecture of a TP monitor and there are some standard protocols such as <a href="http://www.opengroup.org/publications/catalog/c193.htm" rel="noreferrer">XA</a> or <a href="http://msdn.microsoft.com/en-us/library/cc229116%28PROT.10%29.aspx" rel="noreferrer">OLE Transactions</a> to support this. If this type of externally managed transaction is unavailable the application has to construct a <a href="http://en.wikipedia.org/wiki/Compensating_transaction" rel="noreferrer">compensating transaction</a> that undoes the changes made by the application's transaction. This type of architecture is often used by <a href="http://en.wikipedia.org/wiki/Workflow_application" rel="noreferrer">workflow management systems.</a></p>
950,414
MySQL: Compare differences between two tables
<p>Same as <a href="https://stackoverflow.com/questions/688537/">oracle diff: how to compare two tables?</a> except in mysql.</p> <blockquote> <p>Suppose I have two tables, t1 and t2 which are identical in layout but which may contain different data.</p> <p>What's the best way to diff these two tables?</p> </blockquote> <p>To be more precise, I'm trying to figure out a simple SQL query that tells me if data from one row in t1 is different from the data from the corresponding row in t2</p> <p>It appears I cannot use the intersect nor minus. When I try</p> <pre><code>SELECT * FROM robot intersect SELECT * FROM tbd_robot </code></pre> <p>I get an error code:</p> <blockquote> <p>[Error Code: 1064, SQL State: 42000] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM tbd_robot' at line 1</p> </blockquote> <p>Am I doing something syntactically wrong? If not, is there another query I can use?</p> <p>Edit: Also, I'm querying through a free version DbVisualizer. Not sure if that might be a factor.</p>
950,505
9
1
null
2009-06-04 12:58:46.237 UTC
51
2022-07-23 21:12:04.67 UTC
2021-06-15 10:24:02.13 UTC
null
6,340,496
null
6,833
null
1
73
sql|mysql
142,165
<p><code>INTERSECT</code> needs to be emulated in <code>MySQL</code>:</p> <pre><code>SELECT 'robot' AS `set`, r.* FROM robot r WHERE ROW(r.col1, r.col2, …) NOT IN ( SELECT col1, col2, ... FROM tbd_robot ) UNION ALL SELECT 'tbd_robot' AS `set`, t.* FROM tbd_robot t WHERE ROW(t.col1, t.col2, …) NOT IN ( SELECT col1, col2, ... FROM robot ) </code></pre>
1,164,213
How to stop event bubbling on checkbox click
<p>I have a checkbox that I want to perform some Ajax action on the click event, however the checkbox is also inside a container with it's own click behaviour that I don't want to run when the checkbox is clicked. This sample illustrates what I want to do:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('#container').addClass('hidden'); $('#header').click(function() { if ($('#container').hasClass('hidden')) { $('#container').removeClass('hidden'); } else { $('#container').addClass('hidden'); } }); $('#header input[type=checkbox]').click(function(event) { // Do something }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container.hidden #body { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="container"&gt; &lt;div id="header"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;input type="checkbox" name="test" /&gt; &lt;/div&gt; &lt;div id="body"&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>However, I can't figure out how to stop the event bubbling without causing the default click behaviour (checkbox becoming checked/unchecked) to not run.</p> <p>Both of the following stop the event bubbling but also don't change the checkbox state:</p> <pre><code>event.preventDefault(); return false; </code></pre>
1,164,254
9
1
null
2009-07-22 09:55:38.793 UTC
40
2020-10-27 10:37:40.367 UTC
2020-08-04 11:30:10.473 UTC
null
2,117,156
null
270
null
1
202
javascript|jquery|checkbox|events
197,274
<p>replace </p> <pre><code>event.preventDefault(); return false; </code></pre> <p>with</p> <pre><code>event.stopPropagation(); </code></pre> <p><strong><em>event.stopPropagation()</em></strong> </p> <blockquote> <p>Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.</p> </blockquote> <p><strong><em>event.preventDefault()</em></strong> </p> <blockquote> <p>Prevents the browser from executing the default action. Use the method isDefaultPrevented to know whether this method was ever called (on that event object).</p> </blockquote>
545,937
What technology to use in creating DSL for rules engine?
<p>What technology would you recommend to create a DSL for a <a href="http://abdullin.com/journal/2008/11/23/net-application-block-for-validation-and-business-rules.html" rel="noreferrer">Business Rules and Validation Application Block for .NET</a>? And why?</p> <p>The architecture of the framework is established and proof-tested by a production. I just want to create a .NET processor to transform human-readable rules to a compiled Rule implementations. </p> <p>The options that I'm aware of are:</p> <ul> <li>Use compiler pipeline of <a href="http://boo.codehaus.org/" rel="noreferrer">.NET Boo</a> </li> <li>Use the parser builders that come with F# - <a href="http://stepheneasey.wordpress.com/2009/02/11/fslex-and-fsyacc-tutorial-parsing-sql/" rel="noreferrer">FsLex and FsYacc</a></li> </ul> <p>Unfortunately none of these approaches provides anything to build more-or-less friendly IDE for editing DSL, given the DSL syntax (which would evolve).</p> <p>Any ideas or hints?</p>
555,056
11
0
null
2009-02-13 13:34:36.517 UTC
12
2021-10-20 14:12:48.79 UTC
2009-02-16 14:06:57.65 UTC
Rinat Abdullin
47,366
Rinat Abdullin
47,366
null
1
7
.net|f#|dsl|rules|boo
6,701
<p>Microsoft's next generation application development platform, codenamed <a href="https://www.microsoft.com/en-us/microsoft-365/blog/2014/03/11/introducing-codename-oslo-and-the-office-graph/" rel="nofollow noreferrer">Oslo (now Delve)</a></p> <blockquote> <p>Makes it easier for people to write things down in ways that make sense for the problem domain they are working in</p> </blockquote> <p>Oslo seems to consist of a visual design tool named &quot;Quadrant&quot;, a modelling language named &quot;M&quot;, and the &quot;Oslo&quot; repository (a SQL Server database) storing the rules.</p> <p>So if I read things correctly, you could define a modelling language in M, use Quadrant to define and edit your validation rules using your own modelling language, and write an application that makes use of the Oslo repository, generating your Business Rules and Validation Application Block for .NET.</p>
667,802
What is the algorithm to convert an Excel Column Letter into its Number?
<p>I need an algorithm to convert an Excel Column letter to its proper number.</p> <p>The language this will be written in is C#, but any would do or even pseudo code. </p> <p>Please note I am going to put this in C# and I don't want to use the office dll.</p> <p>For 'A' the expected result will be 1</p> <p>For 'AH' = 34</p> <p>For 'XFD' = 16384</p>
667,902
11
1
null
2009-03-20 20:14:42.163 UTC
20
2022-04-27 09:30:52.61 UTC
2009-03-20 21:17:04.667 UTC
Ian Nelson
2,084
Longhorn213
2,469
null
1
72
c#|excel|math
46,182
<pre><code>public static int ExcelColumnNameToNumber(string columnName) { if (string.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName"); columnName = columnName.ToUpperInvariant(); int sum = 0; for (int i = 0; i &lt; columnName.Length; i++) { sum *= 26; sum += (columnName[i] - 'A' + 1); } return sum; } </code></pre>
1,012,378
Eclipse "Server Locations" section disabled and need to change to use Tomcat installation
<p>I have set up a dynamic web project in Eclipse with a Tomcat 5.5 installation.</p> <p>I want to be to set the server to us the Tomcat installation instead of the workspace metadata location, but when Eclipse displays the "Overview" screen for the server the "Server Locations" section is disabled and therefore I am unable to change it.</p> <p>The overview screen is displayed when you have the servers view open and you then double click on the server.</p> <p>Is it possible to enable this part of the "Overview" screen or hack a config file to point at the Tomcat installation?</p>
1,012,459
11
0
null
2009-06-18 12:30:04.227 UTC
42
2016-07-22 05:27:00.157 UTC
2013-08-28 14:30:12.81 UTC
null
814,702
null
15,352
null
1
116
eclipse|tomcat|eclipse-wtp|tomcat5.5|eclipse-3.4
157,998
<p>Ok, sorry for my previous answer, I had never seen that Overview screen before.</p> <p>Here is how I did it: <ol><li>Right click on my tomcat server in "Servers" view, select "Properties…"</li> <li>In the "General" panel, click on the "Switch Location" button</li> <li>The "Location: [workspace metadata]" bit should have been replaced by something else.</li> <li>Open (or close and reopen) the Overview screen for the server.</li></ol></p>
397,556
How to bind RadioButtons to an enum?
<p>I've got an enum like this:</p> <pre><code>public enum MyLovelyEnum { FirstSelection, TheOtherSelection, YetAnotherOne }; </code></pre> <p>I got a property in my DataContext:</p> <pre><code>public MyLovelyEnum VeryLovelyEnum { get; set; } </code></pre> <p>And I got three RadioButtons in my WPF client.</p> <pre><code>&lt;RadioButton Margin="3"&gt;First Selection&lt;/RadioButton&gt; &lt;RadioButton Margin="3"&gt;The Other Selection&lt;/RadioButton&gt; &lt;RadioButton Margin="3"&gt;Yet Another one&lt;/RadioButton&gt; </code></pre> <p>Now how do I bind the RadioButtons to the property for a proper two-way binding?</p>
406,798
11
1
null
2008-12-29 11:35:00.847 UTC
155
2021-09-18 01:34:26.357 UTC
2019-10-21 14:37:40.413 UTC
null
1,506,454
Sam
7,021
null
1
457
wpf|data-binding|enums|radio-button
158,197
<p>You could use a more generic converter</p> <pre><code>public class EnumBooleanConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string parameterString = parameter as string; if (parameterString == null) return DependencyProperty.UnsetValue; if (Enum.IsDefined(value.GetType(), value) == false) return DependencyProperty.UnsetValue; object parameterValue = Enum.Parse(value.GetType(), parameterString); return parameterValue.Equals(value); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string parameterString = parameter as string; if (parameterString == null) return DependencyProperty.UnsetValue; return Enum.Parse(targetType, parameterString); } #endregion } </code></pre> <p>And in the XAML-Part you use:</p> <pre><code>&lt;Grid&gt; &lt;Grid.Resources&gt; &lt;l:EnumBooleanConverter x:Key="enumBooleanConverter" /&gt; &lt;/Grid.Resources&gt; &lt;StackPanel &gt; &lt;RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}"&gt;first selection&lt;/RadioButton&gt; &lt;RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}"&gt;the other selection&lt;/RadioButton&gt; &lt;RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}"&gt;yet another one&lt;/RadioButton&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; </code></pre>
246,038
Unit testing void methods?
<p>What is the best way to unit test a method that doesn't return anything? Specifically in c#.</p> <p>What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.</p>
246,060
11
0
null
2008-10-29 07:28:12.883 UTC
65
2021-04-15 18:46:10.77 UTC
2020-08-17 09:00:20.647 UTC
jdiaz
13,370,965
jdiaz
831
null
1
216
c#|unit-testing|void
182,800
<p>If a method doesn't return anything, it's either one of the following</p> <ul> <li><strong>imperative</strong> - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)</li> <li><strong>informational</strong> - just notifying someone that something happened (without expecting action or response) respectively. </li> </ul> <p>Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.</p> <pre><code>void DeductFromBalance( dAmount ) </code></pre> <p>can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount</p> <p>Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.</p> <pre><code>void OnAccountDebit( dAmount ) // emails account holder with info </code></pre> <p>can be tested by verifying if the email is being sent</p> <p><em>Post more details about your actual method and people will be able to answer better.</em><br> <strong>Update</strong>: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested. </p> <pre><code>string[] ExamineLogFileForX( string sFileName ); void InsertStringsIntoDatabase( string[] ); </code></pre> <p>String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check <a href="https://stackoverflow.com/questions/31837/best-books-about-tdd">this thread</a> for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.<br> In the code it would be used like </p> <pre><code>InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) ); </code></pre>
278,081
Resolving a Git conflict with binary files
<p>I've been using Git on Windows (msysgit) to track changes for some design work I've been doing.</p> <p>Today I've been working on a different PC (with remote repo <code>brian</code>) and I'm now trying to merge the edits done today back into my regular local version on my laptop.</p> <p>On my laptop, I've used <code>git pull brian master</code> to pull the changes into my local version. Everything was fine apart from the main InDesign document - this shows as a conflict.</p> <p>The version on the PC (<code>brian</code>) is the latest one that I want to keep but I don't know what commands tells the repo to use this one. </p> <p>I tried directly copying the file across onto my laptop but this seems to break the whole merge process.</p> <p>Can anyone point me in the right direction?</p>
2,163,926
12
0
null
2008-11-10 15:03:44.827 UTC
170
2022-09-18 19:23:17.503 UTC
2013-05-30 12:53:50.767 UTC
user456814
null
Kevin Wilson
33,721
null
1
552
git|merge-conflict-resolution
229,273
<p><code>git checkout</code> accepts an <code>--ours</code> or <code>--theirs</code> option for cases like this. So if you have a merge conflict, and you know you just want the file from the branch you are merging in, you can do:</p> <pre><code>$ git checkout --theirs -- path/to/conflicted-file.txt </code></pre> <p>to use that version of the file. Likewise, if you know you want your version (not the one being merged in) you can use</p> <pre><code>$ git checkout --ours -- path/to/conflicted-file.txt </code></pre>
923,235
Why does it say "Project with that name already opened in the solution"?
<p>I recently migrated a VSS database to TFS 2008. Using Source Control Explorer, I got the latest version of a solution with 12 projects. </p> <p>When I opened the solution in VS 2005, two of the projects were not found. I am not sure why these two projects were not found, but thought it easiest to just delete and re-add them to the solution. </p> <p>When I do this, VS gives me a "A project with that name is already open in the solution." The project doesn't appear in solution explorer, and is not listed in the .sln file. </p> <p>Any ideas?</p>
1,196,928
13
0
null
2009-05-28 21:12:36.523 UTC
6
2022-09-14 18:52:39.71 UTC
2014-02-23 21:33:16.587 UTC
null
148,998
null
60,757
null
1
36
visual-studio|tfs
35,689
<p>I had the same message... Seems like it comes from (.csproj) project file. Under first propertygroup there is a section named </p> <pre><code>&lt;ProjectTypeGuids&gt;...&lt;/ProjectTypeGuids&gt; </code></pre> <p>which generally tells Visual Studio to handle that project in some specific way. Some Guids can be found <a href="http://www.mztools.com/Articles/2008/MZ2008017.aspx" rel="noreferrer">here</a>.</p> <p>First make a backup copy of that file. Then removing that section can help you open the project as usual project. As it seems that the Visual Studio thinks that the project is not the type that is specified in the ProjectTypeGuids.</p>
199,624
scp transfer via java
<p>What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libraries. None of these solutions seem to have an easy answer.</p>
199,705
15
1
null
2008-10-14 00:50:49.953 UTC
22
2022-04-06 10:02:30.853 UTC
2022-04-06 10:02:30.853 UTC
null
5,446,749
Lloyd Meinholz
4,229
null
1
85
java|scp|bouncycastle|jsse|jsch
111,153
<p>I ended up using <a href="http://www.jcraft.com/jsch/" rel="noreferrer">Jsch</a>- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).</p>
1,205,135
How to encrypt String in Java
<p>What I need is to encrypt string which will show up in 2D barcode(PDF-417) so when someone get an idea to scan it will get nothing readable. </p> <p>Other requirements: </p> <ul> <li>should not be complicated</li> <li>it should not consist of RSA, PKI infrastructure, key pairs, etc.</li> </ul> <p>It must be simple enough to get rid of the people snooping around, and easy to decrypt for other companies interested in getting that data. They call us, we tell them the standard or give them some simple key which can then be used for decryption. </p> <p>Probably those companies could use different technologies so it would be good to stick to some standard which is not tied to some special platform or technology. </p> <p>What do you suggest? Is there some Java class doing <code>encrypt()</code> &amp; <code>decrypt()</code> without much complication in achieving high security standards? </p>
43,779,197
16
2
null
2009-07-30 08:13:10.147 UTC
114
2022-03-14 03:34:12.24 UTC
2019-04-10 11:25:43.787 UTC
null
5,091,346
null
88,448
null
1
180
java|encryption
480,411
<blockquote> <p>This is the first page that shows up via Google and the security vulnerabilities in all the implementations make me cringe so I'm posting this to add information regarding encryption for others as it has been <strong>7 Years</strong> from the original post. I hold a <strong>Masters Degree</strong> in Computer Engineering and spent a lot of time studying and learning Cryptography so I'm throwing my two cents to make the internet a safer place.</p> <p>Also, do note that a lot of implementation might be secure for a given situation, but why use those and potentially accidentally make a mistake? Use the strongest tools you have available unless you have a specific reason not to. Overall I highly advise using a library and staying away from the nitty gritty details if you can.</p> <p><strong>UPDATE 4/5/18:</strong> I rewrote some parts to make them simpler to understand and changed the recommended library from <a href="http://www.jasypt.org/" rel="noreferrer">Jasypt</a> to <a href="https://github.com/google/tink/" rel="noreferrer">Google's new library Tink</a>, I would recommend completely removing <a href="http://www.jasypt.org/" rel="noreferrer">Jasypt</a> from an existing setup.</p> </blockquote> <p><strong>Foreword</strong></p> <p>I will outline the basics of secure symmetric cryptography below and point out common mistakes I see online when people implement crypto on their own with the standard Java library. If you want to just skip all the details run over to <a href="https://github.com/google/tink/" rel="noreferrer">Google's new library Tink</a> import that into your project and use AES-GCM mode for all your encryptions and you shall be secure.</p> <p>Now if you want to learn the nitty gritty details on how to encrypt in java read on :)</p> <p><strong>Block Ciphers</strong></p> <p>First thing first you need to pick a symmetric key Block Cipher. A Block Cipher is a computer function/program used to create Pseudo-Randomness. Pseudo-Randomness is fake randomness that no computer other than a Quantum Computer would be able to tell the difference between it and real randomness. The Block Cipher is like the building block to cryptography, and when used with different modes or schemes we can create encryptions.</p> <p>Now regarding Block Cipher Algorithms available today, Make sure to <strong>NEVER</strong>, I repeat <strong>NEVER</strong> use <a href="http://en.wikipedia.org/wiki/Data_Encryption_Standard" rel="noreferrer">DES</a>, I would even say NEVER use <a href="http://en.wikipedia.org/wiki/3DES" rel="noreferrer">3DES</a>. The only Block Cipher that even Snowden's NSA release was able to verify being truly as close to Pseudo-Random as possible is <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="noreferrer">AES 256</a>. There also exists AES 128; the difference is AES 256 works in 256-bit blocks, while AES 128 works in 128 blocks. All in all, AES 128 is considered secure although some weaknesses have been discovered, but 256 is as solid as it gets.</p> <p>Fun fact <a href="http://en.wikipedia.org/wiki/Data_Encryption_Standard" rel="noreferrer">DES</a> was broken by the NSA back when it was initially founded and actually kept a secret for a few years. Although some people still claim <a href="http://en.wikipedia.org/wiki/3DES" rel="noreferrer">3DES</a> is secure, there are quite a few research papers that have found and analyzed weaknesses in <a href="http://en.wikipedia.org/wiki/3DES" rel="noreferrer">3DES</a>.</p> <p><strong>Encryption Modes</strong></p> <p>Encryption is created when you take a block cipher and use a specific scheme so that the randomness is combined with a key to creating something that is reversible as long as you know the key. This is referred to as an Encryption Mode.</p> <p>Here is an example of an encryption mode and the simplest mode known as ECB just so you can visually understand what is happening:</p> <p><a href="https://i.stack.imgur.com/DOlZl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DOlZl.png" alt="ECB Mode" /></a></p> <p>The encryption modes you will see most commonly online are the following:</p> <p><em>ECB CTR, CBC, GCM</em></p> <p>There exist other modes outside of the ones listed and researchers are always working toward new modes to improve existing problems.</p> <p>Now let's move on to implementations and what is secure. <strong>NEVER</strong> use ECB this is bad at hiding repeating data as shown by the famous <a href="https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation" rel="noreferrer">Linux penguin</a>.<a href="https://i.stack.imgur.com/X67ZV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X67ZV.jpg" alt="Linux Penguin Example" /></a></p> <p>When implementing in Java, note that if you use the following code, ECB mode is set by default:</p> <pre><code>Cipher cipher = Cipher.getInstance(&quot;AES&quot;); </code></pre> <p><strong>... DANGER THIS IS A VULNERABILITY!</strong> and unfortunately, this is seen all over StackOverflow and online in tutorials and examples.</p> <p><strong>Nonces and IVs</strong></p> <p>In response to the issue found with ECB mode nounces also known as IVs were created. The idea is that we generate a new random variable and attach it to every encryption so that when you encrypt two messages that are the same they come out different. The beauty behind this is that an IV or nonce is public knowledge. That means an attacker can have access to this but as long as they don't have your key, they cant do anything with that knowledge.</p> <p>Common issues I will see is that people will set the IV as a static value as in the same fixed value in their code. and here is the pitfall to IVs the moment you repeat one you actually compromise the entire security of your encryption.</p> <p><strong>Generating A Random IV</strong></p> <pre><code>SecureRandom randomSecureRandom = new SecureRandom(); byte[] iv = new byte[cipher.getBlockSize()]; randomSecureRandom.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); </code></pre> <p><strong>Note:</strong> SHA1 is broken but I couldn't find how to implement SHA256 into this use case properly, so if anyone wants to take a crack at this and update it would be awesome! Also SHA1 attacks still are unconventional as it can take a few years on a huge cluster to crack. <a href="https://shattered.io/" rel="noreferrer">Check out details here.</a></p> <p><strong>CTR Implementation</strong></p> <p>No padding is required for CTR mode.</p> <pre><code> Cipher cipher = Cipher.getInstance(&quot;AES/CTR/NoPadding&quot;); </code></pre> <p><strong>CBC Implementation</strong></p> <p>If you choose to implement CBC Mode do so with PKCS7Padding as follows:</p> <pre><code> Cipher cipher = Cipher.getInstance(&quot;AES/CBC/PKCS7Padding&quot;); </code></pre> <p><strong>CBC and CTR Vulnerability and Why You Should Use GCM</strong></p> <p>Although some other modes such as CBC and CTR are secure they run into the issue where an attacker can flip the encrypted data, changing its value when decrypted. So let's say you encrypt an imaginary bank message &quot;Sell 100&quot;, your encrypted message looks like this &quot;eu23ng&quot; the attacker changes one bit to &quot;eu53ng&quot; and all of a sudden when decrypted your message, it reads as &quot;Sell 900&quot;.</p> <p>To avoid this the majority of the internet uses GCM, and every time you see HTTPS they are probably using GCM. GCM signs the encrypted message with a hash and checks to verify that the message has not been changed using this signature.</p> <p>I would avoid implementing GCM because of its complexity. You are better off using <a href="https://github.com/google/tink/" rel="noreferrer">Googles new library Tink</a> because here again if you accidentally repeat an IV you are compromising the key in the case with GCM, which is the ultimate security flaw. New researchers are working towards IV repeat resistant encryption modes where even if you repeat the IV the key is not in danger but this has yet to come mainstream.</p> <p>Now if you do want to implement GCM, here is a <a href="https://gist.github.com/praseodym/f2499b3e14d872fe5b4a" rel="noreferrer">link to a nice GCM implementation</a>. However, I can not ensure the security or if its properly implemented but it gets the basis down. Also note with GCM there is no padding.</p> <pre><code>Cipher cipher = Cipher.getInstance(&quot;AES/GCM/NoPadding&quot;); </code></pre> <p><strong>Keys vs Passwords</strong></p> <p>Another very important note, is that when it comes to cryptography a Key and a Password are not the same things. A Key in cryptography needs to have a certain amount of entropy and randomness to be considered secure. This is why you need to make sure to use the proper cryptographic libraries to generate the key for you.</p> <p>So you really have two implementations you can do here, the first is to use the code found on <a href="https://stackoverflow.com/questions/18228579/how-to-create-a-secure-random-aes-key-in-java">this StackOverflow thread for Random Key Generation</a>. This solution uses a secure random number generator to create a key from scratch that you can the use.</p> <p>The other less secure option is to use, user input such as a password. The issue as we discussed is that the password doesn't have enough entropy, so we would have to use <a href="https://en.wikipedia.org/wiki/PBKDF2" rel="noreferrer">PBKDF2</a>, an algorithm that takes the password and strengthens it. Here is a <a href="https://stackoverflow.com/a/27928435/2607972">StackOverflow implementation I liked</a>. However Google Tink library has all this built in and you should take advantage of it.</p> <p><strong>Android Developers</strong></p> <p>One important point to point out here is know that your android code is reverse engineerable and most cases most java code is too. That means if you store the password in plain text in your code. A hacker can easily retrieve it. Usually, for these type of encryption, you want to use Asymmetric Cryptography and so on. This is outside the scope of this post so I will avoid diving into it.</p> <p>An <a href="https://cs.ucsb.edu/%7Echris/research/doc/ccs13_cryptolint.pdf" rel="noreferrer">interesting reading from 2013</a>: Points out that 88% of Crypto implementations in Android were done improperly.</p> <p><strong>Final Thoughts</strong></p> <p>Once again I would suggest avoid implementing the java library for crypto directly and use <a href="https://github.com/google/tink/" rel="noreferrer">Google Tink</a>, it will save you the headache as they have really done a good job of implementing all the algorithms properly. And even then make sure you check up on issues brought up on the Tink github, vulnerabilities popup here and there.</p> <p>If you have any questions or feedback feel free to comment! Security is always changing and you need to do your best to keep up with it :)</p>
641,148
Application_Start not firing?
<p>I have an ASP.NET MVC (beta) application that I'm working on, and am having trouble figuring out if I'm doing something wrong, or if my <code>Application_Start</code> method in Global.asax.cs is in fact not firing when I try to debug the application.</p> <p>I put a breakpoint on a line in my <code>Application_Start</code> method, and am expecting that when I attempt to debug the application that the breakpoint should get hit... but it never does. Not after I reset IIS, not after I reboot, not ever. Am I missing something? Why is this method never getting called?</p>
641,274
29
2
null
2009-03-13 01:22:06.71 UTC
18
2020-02-26 14:30:30.393 UTC
2015-09-24 21:34:10.983 UTC
null
2,642,204
ryexley
18,831
null
1
149
c#|asp.net-mvc
107,982
<p>If this is in IIS, the app can get started before the debugger has attached. If so, I am not sure if you can thread sleep long enough to get attached. </p> <p>In Visual Studio, you can attach the debugger to a process. You do this by clicking Debug >> Attach to process. Attach to the browser and then hit your application. To be safe, then restart IIS and hit the site. I am not 100% convinced this will solve the problem, but it will do much better than firing off a thread sleep in App_Start.</p> <p>Another option is temporarily host in the built in web server until you finish debugging application start.</p>
6,898,259
When is it required to escape characters in XML?
<p>When should we replace <code>&lt; &gt; &amp; " '</code> in XML to characters like <code>&amp;lt</code> etc.</p> <p>My understanding is that it's just to make sure that if the content part of XML has <code>&gt; &lt;</code> the parser will not treat is start or end of a tag.</p> <p>Also, if I have a XML like:</p> <pre><code>&lt;hello&gt;mor&gt;ning&lt;hello&gt; </code></pre> <p>should this be replaced to either:</p> <ul> <li><code>&amp;lthello&amp;gtmor&amp;gtning&amp;lthello&amp;gt</code></li> <li><code>&amp;lthello&amp;gtmor&gt;ning&amp;lthello&amp;gt</code></li> <li><code>&lt;hello&gt;mor&amp;gtning&lt;hello&gt;</code></li> </ul> <p>I don't understand why replacing is needed. When exactly is it required and what exactly (tags or text) should be replaced?</p>
6,898,340
5
0
null
2011-08-01 12:15:12.85 UTC
3
2017-11-15 17:13:59.83 UTC
2016-09-19 14:50:17.677 UTC
null
457,268
null
642,583
null
1
14
xml|soap|escaping
50,352
<p><code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>, <code>"</code> and <code>'</code> all have special meanings in XML (such as "start of entity" or "attribute value delimiter").</p> <p>In order to have those characters appear as data (instead of for their special meaning) they can be represented by entities (<code>&amp;lt;</code> for <code>&lt;</code> and so on).</p> <p>Sometimes those special meanings are context sensitive (e.g. " doesn't mean "attribute delimiter" outside of a tag) and there are places where they can appear raw as data. Rather then worry about those exceptions, it is simplest to just always represent them as entities if you want to avoid their special meaning. Then the only gotcha is explicit CDATA sections where the special meaning doesn't hold (and <code>&amp;</code> won't start an entity).</p> <blockquote> <p>should this be replaced to either</p> </blockquote> <p>It shouldn't be represented as any of those. Entities must be terminated with a semi-colon.</p> <p>How you should represent it depends on which bit of your example of data and which is markup. You haven't said, for example, if <code>&lt;hello&gt;</code> is supposed to be data or the start tag for a hello element.</p>
6,672,525
Multiprocessing Queue in Python
<p>I'm trying to use a queue with the multiprocessing library in Python. After executing the code below (the print statements work), but the processes do not quit after I call join on the Queue and there are still alive. How can I terminate the remaining processes? </p> <p>Thanks!</p> <pre><code>def MultiprocessTest(self): print "Starting multiprocess." print "Number of CPUs",multiprocessing.cpu_count() num_procs = 4 def do_work(message): print "work",message ,"completed" def worker(): while True: item = q.get() do_work(item) q.task_done() q = multiprocessing.JoinableQueue() for i in range(num_procs): p = multiprocessing.Process(target=worker) p.daemon = True p.start() source = ['hi','there','how','are','you','doing'] for item in source: q.put(item) print "q close" q.join() #q.close() print "Finished everything...." print "num active children:",multiprocessing.active_children() </code></pre>
6,672,593
5
0
null
2011-07-12 23:42:01.38 UTC
15
2015-08-14 08:00:18.26 UTC
2011-07-12 23:49:00.05 UTC
null
90,308
null
839,635
null
1
16
python|multiprocessing
34,992
<p>try this:</p> <pre><code>import multiprocessing num_procs = 4 def do_work(message): print "work",message ,"completed" def worker(): for item in iter( q.get, None ): do_work(item) q.task_done() q.task_done() q = multiprocessing.JoinableQueue() procs = [] for i in range(num_procs): procs.append( multiprocessing.Process(target=worker) ) procs[-1].daemon = True procs[-1].start() source = ['hi','there','how','are','you','doing'] for item in source: q.put(item) q.join() for p in procs: q.put( None ) q.join() for p in procs: p.join() print "Finished everything...." print "num active children:", multiprocessing.active_children() </code></pre>
6,505,389
Recommend a development environment for HTML5/Javascript?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/788978/ide-for-javascript-development">IDE for JavaScript development</a> </p> </blockquote> <p>I want to teach myself HTML5 and Javascript (or if not Javascript, whatever the preferred technology is for manipulating HTML 5 and the DOM these days). Can anyone recommend a good development environment for this (on a Windows 7 PC)? I can make a start with notepad and Google chrome, but I was kind-of hoping a developer friendly IDE exists for this kind of thing.</p> <p>Also, as a follow up question, is Javascript THE way to manipulated the DOM, or is there some other technology out there I don't know about that's superior and supported across the board?</p> <p>Thanks.</p> <p>Edit: Ok, I would like to expand the scenario somewhat, because I didn't really put the question into context. I'm interested in designing and writing GUI components with HTML5/Canvass. I already do this for a living with native development and wanted to extend my skills onto the web, so I've still got that base covered from a skills point of view. So my goal here is to provide some "drag and drop" (not an appropriate metaphor for web development I'm sure) components that others can use. I'm assuing HTML5/Javascript is the way to go, but I'm used to a good debugger, so was kind-of hoping to have that ability too. I'm not sure if browsers support this in any reasonable sense - but an embedded browser in a specialised IDE might. </p>
6,505,537
5
4
null
2011-06-28 11:00:44.19 UTC
4
2013-05-15 13:52:29.397 UTC
2017-05-23 12:30:12.627 UTC
null
-1
null
416,274
null
1
21
javascript|html|ide
62,586
<p>It's a tricky question to answer as it's very much down to personal preference.</p> <p>It sounds as though you are starting out, so to guess a couple of requirements I'm guessing you'll probably want it to be free (or cheap), easy to use, easy to install?</p> <p>If so I'd reccomend checking out either <a href="http://www.microsoft.com/web/webmatrix/" rel="nofollow">Mirosoft WebMatrix</a> or <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-web-developer-express" rel="nofollow">Visual Studio Web Developer Express</a>.</p> <p>Both are free, WebMatrix is geard towards early learning. So I'd suggest starting with WebMatrix.</p> <p>Visual Studio Web Developer Express is more complex, but I'd recommend using this if you're planning to become a professional web developer as it's very similar to Visual Studio Professional.</p> <p>Web Developer Express has intellisense (auto complete) for html and javascript and since sp1 (I think automatically installed) also includes support for HTML5. I believe WebMatrix does as well, but probably not as sophisticated intellisense.</p> <p>I'd especially recommend these tools if you are later planing to learn ASP.net.</p> <p>Both can be very easily installed using the web platform installer via this site: <a href="http://www.microsoft.com/web/platform/tools.aspx" rel="nofollow">http://www.microsoft.com/web/platform/tools.aspx</a></p> <hr> <p>EDIT: My mistake, I thought Robinson was a beginer to development (I was very wrong!) :-) Instead just getting back into the web side of things.</p> <p>If you're looking for a full blown IDE; debugger / web server / intellisense / live(ish) preview of changes etc etc and perhaps in the future thinking of ASP.net: I'd reccomend Visual Studio Web Developer Express.</p>
6,960,434
Timing Delays in VBA
<p>I would like a 1 second delay in my code. Below is the code I am trying to make this delay. I think it polls the date and time off the operating system and waits until the times match. I am having an issue with the delay. I think it does not poll the time when it matches the wait time and it just sits there and freezes up. It only freezes up about 5% of the time I run the code. I was wondering about Application.Wait and if there is a way to check if the polled time is greater than the wait time.</p> <pre><code> newHour = Hour(Now()) newMinute = Minute(Now()) newSecond = Second(Now()) + 1 waitTime = TimeSerial(newHour, newMinute, newSecond) Application.Wait waitTime </code></pre>
6,960,716
13
1
null
2011-08-05 17:43:07.07 UTC
5
2021-08-05 20:18:52.847 UTC
2018-04-02 18:27:26.467 UTC
null
8,112,776
null
787,789
null
1
18
vba|timer|wait|pause|timedelay
226,035
<p>I use this little function for VBA. </p> <pre><code>Public Function Pause(NumberOfSeconds As Variant) On Error GoTo Error_GoTo Dim PauseTime As Variant Dim Start As Variant Dim Elapsed As Variant PauseTime = NumberOfSeconds Start = Timer Elapsed = 0 Do While Timer &lt; Start + PauseTime Elapsed = Elapsed + 1 If Timer = 0 Then ' Crossing midnight PauseTime = PauseTime - Elapsed Start = 0 Elapsed = 0 End If DoEvents Loop Exit_GoTo: On Error GoTo 0 Exit Function Error_GoTo: Debug.Print Err.Number, Err.Description, Erl GoTo Exit_GoTo End Function </code></pre>
42,135,503
Why not concatenate C source files before compilation?
<p>I come from a scripting background and the preprocessor in C has always seemed ugly to me. None the less I have embraced it as I learn to write small C programs. I am only really using the preprocessor for including the standard libraries and header files I have written for my own functions.</p> <p>My question is why don't C programmers just skip all the includes and simply concatenate their C source files and then compile it? If you put all of your includes in one place you would only have to define what you need once, rather than in all your source files.</p> <p>Here's an example of what I'm describing. Here I have three files:</p> <pre><code>// includes.c #include &lt;stdio.h&gt; </code></pre> <pre><code>// main.c int main() { foo(); printf("world\n"); return 0; } </code></pre> <pre><code>// foo.c void foo() { printf("Hello "); } </code></pre> <p>By doing something like <code>cat *.c &gt; to_compile.c &amp;&amp; gcc -o myprogram to_compile.c</code> in my Makefile I can reduce the amount of code I write.</p> <p>This means that I don't have to write a header file for each function I create (because they're already in the main source file) and it also means I don't have to include the standard libraries in each file I create. This seems like a great idea to me!</p> <p>However I realise that C is a very mature programming language and I'm imagining that someone else a lot smarter than me has already had this idea and decided not to use it. Why not?</p>
42,135,581
10
15
null
2017-02-09 11:28:35.263 UTC
14
2017-02-15 17:10:55.577 UTC
2017-02-15 17:10:55.577 UTC
null
541,136
user3420382
null
null
1
75
c|compilation|c-preprocessor
9,681
<p>Some software are built that way.</p> <p>A typical example is <a href="http://sqlite.org/" rel="noreferrer">SQLite</a>. It is sometimes compiled as an <a href="http://sqlite.org/amalgamation.html" rel="noreferrer">amalgamation</a> (done at build time from many source files).</p> <p>But that approach has pros and cons.</p> <p>Obviously, the compile time will increase by quite a lot. So it is practical only if you compile that stuff rarely.</p> <p>Perhaps, the compiler might optimize a bit more. But with link time optimizations (e.g. if using a <em>recent</em> GCC, compile and link with <code>gcc -flto -O2</code>) you can get the same effect (of course, at the expense of increased build time).</p> <blockquote> <p>I don't have to write a header file for each function</p> </blockquote> <p>That is a wrong approach (of having one header file per function). For a single-person project (of less than a hundred thousand lines of code, a.k.a. KLOC = kilo line of <a href="https://en.wikipedia.org/wiki/Source_lines_of_code" rel="noreferrer">code</a>), it is quite reasonable -at least for small projects- to have a <em>single</em> common header file (which you could <a href="https://stackoverflow.com/a/40619764/841108">pre-compile</a> if using <a href="http://gcc.gnu.org/" rel="noreferrer">GCC</a>), which will contain declarations of all public functions and types, and perhaps <em>definitions</em> of <code>static inline</code> functions (those small enough and called frequently enough to profit from <a href="http://sqlite.org/" rel="noreferrer">inlining</a>). For example, the <a href="http://members.tip.net.au/%7Edbell/programs/sash-3.8.tar.gz" rel="noreferrer"><code>sash</code> shell</a> is organized that way (and so is the <a href="http://savannah.nongnu.org/projects/lout" rel="noreferrer"><code>lout</code> formatter</a>, with 52&nbsp;KLOC).</p> <p>You might also have a few header files, and perhaps have some single "grouping" header which <code>#include</code>-s all of them (and which you could pre-compile). See for example <a href="http://www.digip.org/jansson/" rel="noreferrer">jansson</a> (which actually has a single <em>public</em> header file) and <a href="http://gtk.org/" rel="noreferrer">GTK</a> (which has <em>lots</em> of internal headers, but most applications using it <a href="https://developer.gnome.org/gtk3/stable/ch01s04.html" rel="noreferrer">have</a> just one <code>#include &lt;gtk/gtk.h&gt;</code> which in turn include all the internal headers). On the opposite side, <a href="https://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> has a big lot of header files, and it documents which ones should be included and in which order.</p> <p>Some people prefer to have a lot of header files (and some even favor putting a single function declaration in its own header). I don't (for personal projects, or small projects on which only two or three persons would commit code), but <strong>it is a matter of <em>taste</em></strong>. BTW, when a project grows a lot, it happens quite often that the set of header files (and of translation units) changes significantly. Look also into <a href="https://redis.io/" rel="noreferrer">REDIS</a> (it has 139 <code>.h</code> header files and 214 <code>.c</code> files i.e. translation units totalizing 126&nbsp;KLOC).</p> <p>Having one or several <a href="https://en.wikipedia.org/wiki/Translation_unit_(programming)" rel="noreferrer">translation units</a> is also a matter of taste (and of convenience and habits and conventions). My preference is to have source files (that is translation units) which are not too small, typically several thousand lines each, and often have (for a small project of less than 60&nbsp;KLOC) a common single header file. Don't forget to use some <a href="https://en.wikipedia.org/wiki/Build_automation" rel="noreferrer">build automation</a> tool like <a href="https://www.gnu.org/software/make/" rel="noreferrer">GNU make</a> (often with a <a href="https://www.gnu.org/software/make/manual/html_node/Parallel.html" rel="noreferrer">parallel</a> build through <code>make -j</code>; then you'll have <em>several</em> compilation processes running concurrently). The advantage of having such a source file organization is that compilation is reasonably quick. BTW, in some cases a <a href="https://en.wikipedia.org/wiki/Metaprogramming" rel="noreferrer">metaprogramming</a> approach is worthwhile: some of your (internal header, or translation units) C "source" files could be <em>generated</em> by something else (e.g. some script in <a href="https://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a>, some specialized C program like <a href="https://www.gnu.org/software/bison/" rel="noreferrer">bison</a> or your own thing).</p> <p>Remember that C was designed in the 1970s, for computers much smaller and slower than your favorite laptop today (typically, memory was at that time a megabyte at most, or even a few hundred kilobytes, and the computer was at least a thousand times slower than your mobile phone today).</p> <p>I strongly suggest to <strong>study the source code and build some <em>existing</em> <a href="https://en.wikipedia.org/wiki/Free_software" rel="noreferrer">free software</a> projects</strong> (e.g. those on <a href="http://github.com/" rel="noreferrer">GitHub</a> or <a href="http://sourceforge.net/" rel="noreferrer">SourceForge</a> or your favorite Linux distribution). You'll learn that they are different approaches. Remember that <strong>in C <em>conventions</em> and <em>habits</em> matter a lot in practice</strong>, so <strong>there are <em>different</em> ways to organize your project in <code>.c</code> and <code>.h</code> files</strong>. Read about the <a href="https://gcc.gnu.org/onlinedocs/cpp/" rel="noreferrer">C preprocessor</a>.</p> <blockquote> <p>It also means I don't have to include the standard libraries in each file I create</p> </blockquote> <p>You include header files, not libraries (but you should <a href="https://en.wikipedia.org/wiki/Linker_%28computing%29" rel="noreferrer"><em>link</em></a> libraries). But you could include them in each <code>.c</code> files (and many projects are doing that), or you could include them in one single header and pre-compile that header, or you could have a dozen of headers and include them after system headers in each compilation unit. <strong>YMMV.</strong> Notice that preprocessing time is quick on today's computers (at least, when you ask the compiler to optimize, since optimizations takes more time than parsing &amp; preprocessing).</p> <p>Notice that what goes into some <code>#include</code>-d file is <em>conventional</em> (and is not defined by the C specification). Some programs have some of their code in some such file (which should then not be called a "header", just some "included file"; and which then should not have a <code>.h</code> suffix, but something else like <code>.inc</code>). Look for example into <a href="https://en.wikipedia.org/wiki/X_PixMap" rel="noreferrer">XPM</a> files. At the other extreme, you might in principle not have any of your own header files (you still need header files from the implementation, like <code>&lt;stdio.h&gt;</code> or <code>&lt;dlfcn.h&gt;</code> from your POSIX system) and copy and paste duplicated code in your <code>.c</code> files -e.g. have the line <code>int foo(void);</code> in every <code>.c</code> file, but that is very bad practice and is frowned upon. However, some programs are <em>generating</em> C files sharing some common content.</p> <p>BTW, C or C++14 do not have modules (like OCaml has). In other words, in C a module is mostly a <em>convention</em>.</p> <p><sup>(notice that having many thousands of <em>very small</em> <code>.h</code> and <code>.c</code> files of only a few dozen lines each may slow down your build time dramatically; having hundreds of files of a few hundred lines each is more reasonable, in term of build time.)</sup></p> <p>If you begin to work on a single-person project in C, I would suggest to first have one header file (and pre-compile it) and several <code>.c</code> translation units. In practice, you'll change <code>.c</code> files much more often than <code>.h</code> ones. Once you have more than 10 KLOC you might refactor that into several header files. Such a refactoring is tricky to design, but easy to do (just a lot of copy&amp;pasting chunk of codes). Other people would have different suggestions and hints (and that is ok!). But don't forget to enable all warnings and debug information when compiling (so compile with <code>gcc -Wall -g</code>, perhaps setting <code>CFLAGS= -Wall -g</code> in your <code>Makefile</code>). Use the <code>gdb</code> debugger (and <a href="http://valgrind.org/" rel="noreferrer">valgrind</a>...). Ask for optimizations (<code>-O2</code>) when you benchmark an already-debugged program. Also use a version control system like <a href="http://git-scm.com/" rel="noreferrer">Git</a>.</p> <p>On the contrary, if you are designing a larger project on which <em>several persons</em> would work, it could be better to have several files -even several header files- (intuitively, each file has a single person mainly responsible for it, with others making minor contributions to that file).</p> <p>In a comment, you add:</p> <blockquote> <p>I'm talking about writing my code in lots of different files but using a Makefile to concatenate them</p> </blockquote> <p>I don't see why that would be useful (except in very weird cases). It is much better (and very usual and common practice) to compile each translation unit (e.g. each <code>.c</code> file) into its <a href="https://en.wikipedia.org/wiki/Object_file" rel="noreferrer">object file</a> (a <code>.o</code> <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format" rel="noreferrer">ELF</a> file on Linux) and <a href="https://en.wikipedia.org/wiki/Linker_%28computing%29" rel="noreferrer">link</a> them later. This is easy with <code>make</code> (in practice, when you'll change only one <code>.c</code> file e.g. to fix a bug, only that file gets compiled and the incremental build is really quick), and you can ask it to compile object files in <a href="https://www.gnu.org/software/make/manual/html_node/Parallel.html" rel="noreferrer">parallel</a> using <code>make -j</code> (and then your build goes really fast on your multi-core processor).</p>
45,470,802
How to pass along CSRF token in an AJAX post request for a form?
<p>I'm using Scala Play! 2.6 Framework, but that may not be the issue. I'm using their Javascript routing - and it seems to work ok, but it's having issues. I have a form, which when rendered produces this, with a CSRF token:</p> <pre><code>&lt;form method="post" id="myForm" action="someURL"&gt; &lt;input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden"&gt; &lt;input type="text" id="sometext"&gt; &lt;button type="submit"&gt; Submit! &lt;/button&gt; &lt;/form&gt; </code></pre> <p>And here's roughly, my AJAX:</p> <pre><code>$(document).on('submit', '#myForm', function (event) { event.preventDefault(); var data = { textvalue: $('#sometext').val() } var route = jsRoutes.controllers.DashboardController.postNewProject() $.ajax({ url: route.url, type: route.type, data : JSON.stringify(data), contentType : 'application/json', success: function (data) { ... }, error: function (data) { ... } }) }); </code></pre> <p>But when I post this, I am getting an UNAUTHORIZED response back from my Server, and my console in IntelliJ is telling me the CSRF check is failing. How would I pass along the CSRF token in the request?</p>
45,490,899
7
5
null
2017-08-02 20:53:05.383 UTC
15
2021-01-22 06:50:54.52 UTC
2017-08-03 17:24:52.303 UTC
null
7,082,628
null
7,082,628
null
1
18
jquery|ajax|scala|playframework|csrf
71,582
<p>Ok, after fighting this for a few hours and trying to decrypt Play's frequently-lacking-context-Documentation on the <a href="https://www.playframework.com/documentation/2.6.x/ScalaCsrf" rel="noreferrer">subject</a>, I've got it. </p> <p>So, from their docs:</p> <blockquote> <p>To allow simple protection for non browser requests, Play only checks requests with cookies in the header. If you are making requests with AJAX, you can place the CSRF token in the HTML page, and then add it to the request using the <code>Csrf-Token</code> header.</p> </blockquote> <p>And then there's no code or example. Thanks Play. Very descriptive. Anyway, here's how:</p> <p>in your <code>view.html.formTemplate</code> you might write in IntelliJ:</p> <pre><code>@() &lt;form method="post" id="myForm" action="someURL"&gt; @helper.CSRF.formField &lt;!-- This auto-generates a token for you --&gt; &lt;input type="text" id="sometext"&gt; &lt;button type="submit"&gt; Submit! &lt;/button&gt; &lt;/form&gt; </code></pre> <p>And this will render like this when delivered to the client:</p> <pre><code>&lt;form method="post" id="myForm" action="someURL"&gt; &lt;input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden"&gt; &lt;input type="text" id="sometext"&gt; &lt;button type="submit"&gt; Submit! &lt;/button&gt; &lt;/form&gt; </code></pre> <p>Ok, almost there, now we have to create our AJAX call. I have all of mine in a separate main.js file, but you could also put this in your <code>view.html.formTemplate</code> if you want.</p> <pre><code>$(document).on('submit', '#myForm', function (event) { event.preventDefault(); var data = { myTextToPass: $('#sometext').val() } // LOOK AT ME! BETWEEN HERE AND var token = $('input[name="csrfToken"]').attr('value') $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Csrf-Token', token); } }); // HERE var route = jsRoutes.controllers.DashboardController.postNewProject() $.ajax({ url: route.url, type: route.type, data : JSON.stringify(data), contentType : 'application/json', success: function (data) { ... }, error: function (data) { ... } }) }); </code></pre> <p>With this line: <code>var token = $('input[name="csrfToken"]').attr('value')</code> You are plucking out the CSRF token auto generated in your form field and grabbing its value in a var to be used in your Javascript. </p> <p>The other important chunk from all that AJAX is here:</p> <pre><code>$.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Csrf-Token', token); } }); </code></pre> <p>Using the <code>$.ajaxSetup</code>, you can set what's in the header. This is what you have to infer from their documentation:</p> <blockquote> <p>add it to the request using the Csrf-Token header.</p> </blockquote> <p>Good luck! Let me know if this is clear. </p> <hr> <p><strong>Note</strong>: when using <a href="https://github.com/krakenjs/lusca" rel="noreferrer">lusca</a>, use <code>X-CSRF-Token</code> instead of <code>Csrf-Token</code>.</p>
15,954,710
Insert Dictionary into MongoDB with c# driver
<p>I am in a situation where I can't predict which fields my MongoDB document is going to have. So I can no longer create an object with an <code>_id</code> field of type <code>BsonID</code>. I find it very convenient to create a Dictionary (HashTable) and add my DateTime and String objects inside, as many times as I need it. </p> <p>I then try to insert the resulting Dictionary object into MongoDb, but default serialization fails.</p> <p>Here's my object of Type HashTable (like a Dictionary, but with varied types inside):</p> <pre><code>{ "_id":"", "metadata1":"asaad", "metadata2":[], "metadata3":ISODate("somedatehere")} </code></pre> <p>And the error from the driver I get is:</p> <blockquote> <p>Serializer DictionarySerializer expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions</p> </blockquote> <p>I googled it, but couldn't find anything useful. What am I doing wrong?</p>
16,450,242
1
0
null
2013-04-11 17:03:46.737 UTC
9
2016-08-03 08:45:57.133 UTC
2016-08-03 08:45:57.133 UTC
null
4,519,059
null
1,426,861
null
1
15
c#|mongodb|serialization|dictionary|insert
17,135
<p>The driver needs to be able to find the _id field. You could create a C# class that has just two properties: Id and Values.</p> <pre><code>public class HashTableDocument { public ObjectId Id { get; set; } [BsonExtraElements] public Dictionary&lt;string, object&gt; Values { get; set; } } </code></pre> <p>Note that we have to use Dictionary&lt;string, object&gt; instead of Hashtable.</p> <p>You could then use code like the following to insert a document:</p> <pre><code>var document = new HashTableDocument { Id = ObjectId.GenerateNewId(), Values = new Dictionary&lt;string, object&gt; { { "metadata1", "asaad" }, { "metadata2", new object[0] }, { "metadata3", DateTime.UtcNow } } }; collection.Insert(document); </code></pre> <p>We can use the MongoDB shell to confirm that the inserted document has the desired form:</p> <pre><code>&gt; db.test.find().pretty() { "_id" : ObjectId("518abdd4e447ad1f78f74fb1"), "metadata1" : "asaad", "metadata2" : [ ], "metadata3" : ISODate("2013-05-08T21:04:20.895Z") } &gt; </code></pre>
15,566,405
Run Executable from makefile
<p>Hey I just have a quick question about makefile's. Is there some way to auto run the executable generated from a makefile?</p> <p>Like if I just type "make" it will compile and build and automatically execute so I can skip the extra step of ./myExecutable</p> <p>I have down in my notes:</p> <pre><code>run: prog1 ./prog1 </code></pre> <p>But it doesn't seem to work.</p> <p>Thanks</p>
15,566,477
1
2
null
2013-03-22 09:05:43.893 UTC
2
2013-03-22 09:09:12.93 UTC
null
null
null
null
2,044,609
null
1
18
linux|command-line|makefile|executable
49,072
<p>If you run make without specifying any targets, it would execute the first target it finds within the Makefile. By convention <code>all</code> is the name of such a target.</p> <p>If you make <code>run</code> a pre-requisite for <code>all</code> and mark both <code>all</code> and <code>run</code> as PHONY targets, you should be good to go.</p> <pre><code>all: run run: prog1 ./prog1 .PHONY: all run </code></pre> <p>BTW, I presume you already have some rules for building <code>prog1</code> in your Makefile, and hence have not included it in the above shown Makefile.</p> <p>An alternative would be to just invoke make explicitly with the <code>run</code> target, i.e. execute the following command:</p> <pre><code>make run </code></pre>
15,956,307
TFS API: GetLocalWorkspaceInfo always returns null
<p>On one of my machines, I get a return value of null from any <code>GetLocalWorkspaceInfo</code> call. I have isolated to problem to where it even fails for this simple program:</p> <pre><code>namespace WorkstationTest { using Microsoft.TeamFoundation.VersionControl.Client; class Program { static void Main() { string workspaceLocalPath = @"C:\Dev"; var info = Workstation.Current .GetLocalWorkspaceInfo(workspaceLocalPath); // info is always null here } } } </code></pre> <p>What I have already checked:</p> <ul> <li><p>The exact same code works on my other machine the way it should.</p></li> <li><p>I have verified that I have a workspace at <code>C:\Dev</code></p> <p><img src="https://i.stack.imgur.com/UeFTd.png" alt="Workspace Screenshot"></p></li> <li><p>I have created a new workspace and in a different directory and changed the <code>workspaceLocalPath</code> variable in the code to match.</p></li> <li><p>I have consulted <a href="http://msdn.microsoft.com/en-us/library/bb139693.aspx" rel="noreferrer">the documentation</a> which states that the return value will be null <code>if the path is not in a workspace</code>. From the above image, the path should be in a workspace.</p></li> </ul> <p>Yet, everything seems to suggest this should work. Is there anything I could be missing?</p>
43,348,710
8
4
null
2013-04-11 18:37:24.09 UTC
10
2021-01-28 17:15:31.07 UTC
2015-03-03 17:42:16.947 UTC
null
937,623
null
937,623
null
1
31
c#|tfs-sdk
10,831
<p>After migrating from TFS2013 to TFS2017 in the company I work for I had the same problem with Workstation.Current.GetLocalWorkspaceInfo.</p> <p>What worked for me is a call to <a href="https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.workstation.ensureupdateworkspaceinfocache(v=vs.120).aspx" rel="noreferrer"><code>Workstation.EnsureUpdateWorkspaceInfoCache</code></a>:</p> <pre><code>TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("&lt;your-tfs-uri-here&gt;")); VersionControlServer tfServer = tpc.GetService&lt;VersionControlServer&gt;(); Workstation.Current.EnsureUpdateWorkspaceInfoCache(tfServer, tfServer.AuthorizedUser); </code></pre> <p>I added the above code lines to the constructor of my TFS proxy class that uses GetLocalWorkspaceInfo.</p>
15,899,798
subprocess.Popen in different console
<p>I hope this is not a duplicate.</p> <p>I'm trying to use <code>subprocess.Popen()</code> to open a script in a separate console. I've tried setting the <code>shell=True</code> parameter but that didn't do the trick.</p> <p>I use a 32 bit Python 2.7 on a 64 bit Windows 7.</p>
15,899,818
3
8
null
2013-04-09 10:43:10.67 UTC
9
2020-05-31 14:53:12.807 UTC
null
null
null
null
1,664,657
null
1
37
python|python-2.7|subprocess|popen
70,000
<pre><code>from subprocess import * c = 'dir' #Windows handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True) print handle.stdout.read() handle.flush() </code></pre> <p>If you don't use <code>shell=True</code> you'll have to supply <code>Popen()</code> with a list instead of a command string, example:</p> <pre><code>c = ['ls', '-l'] #Linux </code></pre> <p>and then open it without shell.</p> <pre><code>handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE) print handle.stdout.read() handle.flush() </code></pre> <p>This is the most manual and flexible way you can call a subprocess from Python. If you just want the output, go for:</p> <pre><code>from subproccess import check_output print check_output('dir') </code></pre> <hr> <h1>To open a new console GUI window and execute X:</h1> <pre><code>import os os.system("start cmd /K dir") #/K remains the window, /C executes and dies (popup) </code></pre>
15,613,978
difference of freeglut vs glew?
<p>I've recently started learning OpenGL (> 3.3) &amp; I've noticed a lot of examples &amp; tutorials use both freeglut &amp; glew, but don't really explain the difference at all. The best description I've found, after googling &amp; reading ad nauseum, has been this <a href="http://www.opengl.org/wiki/Related_toolkits_and_APIs#Context.2FWindow_Toolkits">OpenGL Related toolkits and APIs</a> but found it lacking. I've even read the tag info on SO. <br></p> <p>As someone really new to OpenGL I'm still trying to get a grasp of the different concepts. I've gotten to the stage of creating a basic program that uses glew, create context (on windows, VS2010), &amp; draw really basic shapes, all without the need for explicitly including freeglut. So I don't understand why I would need it.</p> <p>So my question then is, what's the <strong>difference</strong> between: <br> -freeglut <br> -glew <br> -(&amp; glfw) <br> What can one do <strong>that the other can't</strong>?</p>
15,618,501
2
1
null
2013-03-25 11:38:17.843 UTC
21
2015-02-17 08:36:01.693 UTC
2013-03-25 13:16:41.443 UTC
null
44,729
null
1,132,062
null
1
51
opengl|glew|freeglut|glfw
38,445
<p>The OpenGL Extension Wrangler (<strong>GLEW</strong>) is used to access the modern OpenGL API functions(version 3.2 up to latest version).If we use an ancient version of OpenGL then we can access the OpenGL functions simply including as <code>#include &lt;GL/gl.h&gt;</code>.But in modern OpenGL, the API functions are determined at run time, not compile time. GLEW will handle the run time loading of the OpenGL API.About GLEW see <a href="https://stackoverflow.com/tags/glew/info">here</a></p> <p><strong>GLFW</strong> or <strong>freeglut</strong> will allow us to create a window, and receive mouse and keyboard input in a cross-platform way. OpenGL does not handle window creation or input, so we have to use these library for handling window, keyboard, mouse, joysticks, input and other purpose.</p> <p><strong>GLFW</strong> and <strong>freeglut</strong> are alternative for us according to our need we can choose any one but <strong>GLEW</strong> is different from them which is used for run time loading of the OpenGL API. </p>
15,804,101
Dart lambda/shortland function confusion
<p>I'm still pretty new to Dart and the syntax of => (fat arrow) still confuses me (I come from C# background).</p> <p>So in C# fat arrow ( => ) says: <em>goes to</em> so for example:</p> <pre class="lang-csharp prettyprint-override"><code>Action&lt;string&gt; action1 = (str) =&gt; { System.Diagnostic.Debug.WriteLine("Parameter received: " + str.ToString()); } action1("Some parameter"); </code></pre> <p>means: whatever send as parameter to <code>action1</code> (if it could be casted to <code>string</code>) <em>goes to</em> inner scope (in our case it just printed in <code>Debug.WriteLine()</code></p> <p>but in Dart it's something different.... (?)</p> <p>for example in <code>Future.then</code></p> <pre class="lang-dart prettyprint-override"><code>ClassWithFutures myClass = new ClassWithFutures(); myClass.loadedFuture.then( (str) =&gt; { print("Class was loaded with info: $str"), onError: (exp) =&gt; { print("Error occurred in class loading. Error is: $exp"); } ); </code></pre> <p>Dart editor warn me that the first and second <code>print</code> is: <code>Expected string literal for map entry key</code>. I think in C# way that <code>str</code> it just name for parameter that will be filled by internal callback that <code>Future.then</code> uses to call <code>onValue</code> or <code>onError</code></p> <p>What I'm doing wrong ?</p>
15,804,343
3
1
null
2013-04-04 06:35:18.723 UTC
5
2019-07-15 13:37:07.137 UTC
2019-07-15 13:37:07.137 UTC
null
71,444
null
1,144,952
null
1
64
dart
45,643
<p>You need to choose either block syntax or single expression syntax, but not both.</p> <p>You can't combine => with {}</p> <p>Your two options are as follows using your example:</p> <pre class="lang-dart prettyprint-override"><code>ClassWithFutures myClass = new ClassWithFutures(); myClass.loadedFuture.then( (str) =&gt; print("Class was loaded with info: $str"), onErrro: (exp) =&gt; print("Error occurred in class loading. Error is: $exp") ); </code></pre> <p>or</p> <pre class="lang-dart prettyprint-override"><code>ClassWithFutures myClass = new ClassWithFutures(); myClass.loadedFuture.then( (str) { print("Class was loaded with info: $str"); }, onErrro: (exp) { print("Error occurred in class loading. Error is: $exp"); } ); </code></pre> <p>In both cases, it is just a way to express an anonymous function.</p> <p>Normally if you want to just run a single expression, you use the => syntax for cleaner and more to the point code. Example:</p> <pre class="lang-dart prettyprint-override"><code>someFunction.then( (String str) =&gt; print(str) ); </code></pre> <p>or you can use a block syntax with curly braces to do more work, or a single expression. </p> <pre class="lang-dart prettyprint-override"><code>someFunction.then( (String str) { str = str + "Hello World"; print(str); }); </code></pre> <p>but you can't combine them since then you are making 2 function creation syntaxes and it breaks.</p> <p>Hope this helps.</p>
32,800,341
Invalid conversion from throwing function of type (_,_,_) throws -> Void to non-throwing function type (NSData?, NSURLResponse?, NSError?) -> Void
<p>I have written this code: </p> <pre><code>func getjson() { let urlPath = "https://api.whitehouse.gov/v1/petitions.json?limit=100" let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -&gt; Void in print("Task completed") if(error != nil) { print(error!.localizedDescription) } let err: NSError? if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { if(err != nil) { print("JSON Error \(err!.localizedDescription)") } if let results: NSArray = jsonResult["results"] as? NSArray { dispatch_async(dispatch_get_main_queue(), { self.tableData = results self.Indextableview.reloadData() }) } } }) task.resume() } </code></pre> <p>And after update to XCode 7 it gives me this error: Invalid conversion from throwing function of type (_, _, _) throws -> Void to non-throwing function type (NSData?, NSURLResponse?, NSError?) -> Void. It is in line, where is let task.</p> <p>Thanks</p>
32,800,848
4
5
null
2015-09-26 18:08:01.573 UTC
9
2021-12-14 13:21:18.29 UTC
2021-12-14 13:21:18.29 UTC
null
5,175,709
null
4,760,366
null
1
60
ios|swift|try-catch|urlsession|json-serialization
79,803
<p>You need to implement Do Try Catch error handling as follow:</p> <pre><code>import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true extension URL { func asyncDownload(completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -&gt; ()) { URLSession.shared .dataTask(with: self, completionHandler: completion) .resume() } } </code></pre> <hr> <pre><code>let jsonURL = URL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=100")! let start = Date() jsonURL.asyncDownload { data, response, error in print("Download ended:", Date().description(with: .current)) print("Elapsed Time:", Date().timeIntervalSince(start), terminator: " seconds\n") print("Data size:", data?.count ?? "nil", terminator: " bytes\n\n") guard let data = data else { print("URLSession dataTask error:", error ?? "nil") return } do { let jsonObject = try JSONSerialization.jsonObject(with: data) if let dictionary = jsonObject as? [String: Any], let results = dictionary["results"] as? [[String: Any]] { DispatchQueue.main.async { results.forEach { print($0["body"] ?? "", terminator: "\n\n") } // self.tableData = results // self.Indextableview.reloadData() } } } catch { print("JSONSerialization error:", error) } } print("\nDownload started:", start.description(with: .current)) </code></pre>
35,877,994
Font Awesome is loading very slow
<p>I have been doing some troubleshooting on my site, because the page load seemed very slow. I have icons on every page, multiple times as the site serves as a blog, and each blog post has share icons. By removing font awesome I noticed an extreme speed boost. Now I am unsure what to do because I need the icons. Any suggestions? </p> <p>Update: I tried using my server and I also used CDN but I get the same results. </p>
35,880,730
2
12
null
2016-03-08 21:05:35.09 UTC
8
2018-07-10 02:04:04.29 UTC
2016-03-08 21:15:54.767 UTC
null
2,567,660
null
2,567,660
null
1
21
css
45,472
<p>Load this into your head: </p> <pre><code>&lt;script type="text/javascript"&gt; (function() { var css = document.createElement('link'); css.href = 'https://use.fontawesome.com/releases/v5.1.0/css/all.css'; css.rel = 'stylesheet'; css.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(css); })(); &lt;/script&gt; </code></pre> <p>What does this do exactly? Well it loads font awesome via javascript which is placed at the head of the page. Basically we are rendering font awesome before rendering the page which means it should load quicker.</p>
50,274,554
How to efficiently check if a list of consecutive numbers is missing any elements
<p>I have this array</p> <pre><code>var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; </code></pre> <p>I was trying to find an algorithm that will tell me which <code>s</code>s are missing. As you can see, the list consists of consecutive <code>s</code>s (<code>s1</code>, <code>s2</code>, etc.).</p> <p>At first I went with this solution:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; for (var i=1;i&lt;arr.length;i++){ var thisI = parseInt(arr[i].toLowerCase().split("s")[1]); var prevI = parseInt(arr[i-1].toLowerCase().split("s")[1]); if (thisI != prevI+1) console.log(`Seems like ${prevI+1} is missing. thisI is ${thisI} and prevI is ${prevI}`) }</code></pre> </div> </div> </p> <p>But this method fails for more than one consecutive numbers missing (<code>s15</code>, <code>s16</code>). So I added a <code>while</code> loop which works.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; for (var i=1;i&lt;arr.length;i++){ var thisI = parseInt(arr[i].toLowerCase().split("s")[1]); var prevI = parseInt(arr[i-1].toLowerCase().split("s")[1]); if (thisI != prevI+1) { while(thisI-1 !== prevI++){ console.log(`Seems like ${prevI} is missing. thisI is ${thisI} and prevI is ${prevI}`) } } }</code></pre> </div> </div> </p> <p>However, I feel like I'm overly complicating things. I thought of creating an ideal array:</p> <pre><code>var idealArray = []; for (var i =0; i&lt;200;i++) { idealArray.push(i) } </code></pre> <p>And then, while checking, tamper with my array (<code>arr</code>) so that the loop checks two arrays of the same length. I.e., use this solution:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var idealArray = []; for (var i =0; i&lt;200;i++) { idealArray.push(i) } var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; for (let i = 0; i&lt;idealArray.length;i++){ if (parseInt(arr[i].toLowerCase().split("s")[1]) != idealArray[i]) { console.log(`Seems like ${idealArray[i]}is missing`); arr.splice(i,0,"dummyel") } }</code></pre> </div> </div> </p> <p>But, once again, I have the feeling that creating this second array is not very efficient either (thinking of a big list, I'd waste unnecessary space).</p> <p>So... how do I efficiently perform this task in JavaScript? (Efficiently meaning as close to O(1) as possible both for time complexity and for space complexity.)</p>
50,277,123
12
5
null
2018-05-10 13:53:01.61 UTC
4
2018-07-06 21:26:24.53 UTC
2018-05-11 13:44:52.313 UTC
null
87,015
null
3,233,388
null
1
29
javascript|arrays|algorithm
4,808
<p>Since you know you are expecting a sequential array, I don't know why it needs to be more complicated than a loop through numbers <code>arr[0]</code> through <code>arr[end]</code> while keeping a counter to know where you are in the array. This will run at O(n), but I don't think you can improve on that — you need to look at every element at least once in the worst case.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; let first = parseInt(arr[0].substring(1)) let last = parseInt(arr[arr.length-1].substring(1)) let count = 0 for (let i = first; i&lt; last; i++) { if (parseInt(arr[count].substring(1)) == i) {count++; continue} else console.log(`seem to be missing ${'s'+i.toString().padStart(2,'0')} between: ${arr[count-1]} and ${arr[count]}` ) }</code></pre> </div> </div> </p> <hr> <p><strong>EDIT:</strong></p> <p>After thinking a bit about the comments below, I made a recursive approach that splits the array and checks each half. Mostly as an experiment, not as a practical solution. This does in fact run with fewer than <code>n</code> iterations in most cases, but I couldn't find a case where it was actually faster Also, I just pushed indexes showing where the gaps are to make the structure easier to see and test. <s>And as you'll see, because it's recursive the results aren't in order.</s></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["s00","s01","s02","s03","s04","s05","s07","s08","s09","s10","s11","s12","s13","s14","s17","s19","s20","s21","s22","s24","s25","s26","s27","s28","s30","s32","s33","s34","s36","s38","s39","s41","s43","s44","s45","s46","s47","s48","s49","s50","s51","s52","s53","s54","s55","s56","s58","s60","s61","s62","s63","s64","s65","s67","s69","s70"]; let missingGaps = [] function missing(arr, low, high) { if (high &lt;= low) return let l = parseInt(arr[low].substring(1)) let h = parseInt(arr[high].substring(1)) if (h - l == high - low) return if (high - low === 1) { missingGaps.push([low, high]) return } else { let mid = ((high - low) &gt;&gt; 1) + low missing(arr, low, mid) // need to check case where split might contain gap let m = parseInt(arr[mid].substring(1)) let m1 = parseInt(arr[mid + 1].substring(1)) if (m1 - m !== 1) missingGaps.push([mid, mid + 1]) missing(arr, mid + 1, high) } } missing(arr, 0, arr.length-1) missingGaps.forEach(g =&gt; console.log(`missing between indices ${arr[g[0]]} and ${arr[g[1]]}`))</code></pre> </div> </div> </p> <p>Maybe another answer or comment will have an improvement that makes it a bit faster.</p>
10,299,034
How to pass kwargs from save to post_save signal
<p>I'm wiring up a custom post_save signal and noticed that I can't seem to find an easy way to pass a set of kwargs.</p> <p>During the save itself (inside a custom form)</p> <pre><code>def save(self, commit=True): user = super(CustomFormThing, self).save(commit=False) #set some other attrs on user here ... if commit: user.save() return user </code></pre> <p>Then inside my custom post_save hook I have the following (but never get any kwargs)</p> <pre><code>@receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): some_id = kwargs.get('some', None) other_id = kwargs.get('other', None) if created: #do something with the kwargs above... </code></pre> <p>How might I pass kwargs from the save to the post_save event?</p>
10,299,274
3
4
null
2012-04-24 13:36:45.793 UTC
12
2020-07-21 06:18:23.097 UTC
null
null
null
null
2,701
null
1
31
python|django
12,202
<p>Built-in signals are sent by Django, so you can't control their kwargs.</p> <p>You can:</p> <ol> <li>Define and send your own signals.</li> <li><p>Store additional info in model instance. Like this</p> <pre><code>def save(self, commit=True): user = super(CustomFormThing, self).save(commit=False) #set some other attrs on user here ... user._some = 'some' user._other = 'other' if commit: user.save() return user @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): some_id = getattr(instance, '_some', None) other_id = getattr(instance, '_other', None) if created: #do something with the kwargs above... </code></pre></li> </ol>
10,592,753
How to define setter/getter on prototype
<p><strong>EDIT Oct 2016</strong>: Please note this question was asked in 2012. Every month or so someone adds a new answer or comment that refutes an answer, but doesn't really make sense to do so as the question is probably out of date (remember, it was for <strong>Gnome Javascript</strong> to write gnome-shell extensions, not browser stuff, which is quite specific).</p> <p>Following <a href="https://stackoverflow.com/questions/10580158/making-subclass-with-prototype-and-proto">my previous question</a> on how to do subclassing in Javascript, I'm making a subclass of a superclass like so:</p> <pre><code>function inherits(Child,Parent) { var Tmp = function {}; Tmp.prototype = Parent.prototype; Child.prototype = new Tmp(); Child.prototype.constructor = Child; } /* Define subclass */ function Subclass() { Superclass.apply(this,arguments); /* other initialisation */ } /* Set up inheritance */ inherits(Subclass,Superclass); /* Add other methods */ Subclass.prototype.method1 = function ... // and so on. </code></pre> <p>My question is, <strong>how do I define a setter/getter on the prototype with this syntax?</strong></p> <p>I used to do:</p> <pre><code>Subclass.prototype = { __proto__: Superclass.prototype, /* other methods here ... */ get myProperty() { // code. } } </code></pre> <p>But obviously the following won't work:</p> <pre><code>Subclass.prototype.get myProperty() { /* code */ } </code></pre> <p>I'm using GJS (GNOME Javascript), and the engine is meant to be the more-or-less same as the Mozilla Spidermonkey one. My code is not intended for a browser so as long as it's supported by GJS (I guess that means Spidermonkey?), I don't mind if it's not cross-compatible.</p>
10,592,815
6
5
null
2012-05-15 00:29:14.867 UTC
30
2021-08-13 16:40:58.397 UTC
2021-08-13 16:40:58.397 UTC
null
10,052,111
null
913,184
null
1
90
javascript|getter|gjs
65,545
<p>Using an object literal declaration (simplest way):</p> <pre><code>var o = { a: 7, get b() { return this.a + 1; }, set c(x) { this.a = x / 2 } }; </code></pre> <p>Using <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty" rel="noreferrer"><code>Object.defineProperty</code></a> (on modern browsers that support ES5):</p> <pre><code>Object.defineProperty(o, "myProperty", { get: function myProperty() { // code } }); </code></pre> <p>Or using <code>__defineGetter__</code> and <code>__defineSetter__</code> (<strong>DEPRECATED</strong>):</p> <pre><code>var d = Date.prototype; d.__defineGetter__("year", function() { return this.getFullYear(); }); d.__defineSetter__("year", function(y) { this.setFullYear(y); }); </code></pre>
10,502,298
How to set a MySQL row to READ-ONLY?
<p>I have a row in a table that I do not want to be changed (ever).</p> <p>Is it possible to set a MySQL row to READ-ONLY so that it cannot be updated in any way? If so, how?</p> <p>If not, is it possible to set a permanent value in one of the columns of that row so that it cannot be changed? If so, how?</p> <p>Thanks.</p>
10,502,350
1
6
null
2012-05-08 16:09:17.283 UTC
13
2016-03-10 09:02:13.653 UTC
null
null
null
null
869,849
null
1
36
mysql|sql|database
19,160
<p>This is likely to be business logic, which probably doesn't belong in your data storage layer. However, it can nonetheless be accomplished using <a href="https://dev.mysql.com/doc/en/trigger-syntax.html" rel="noreferrer">triggers</a>.</p> <p>You can create a <code>BEFORE UPDATE</code> trigger that raises an error if a "locked" record is about to be updated; since an error occurs <em>before</em> the operation is undertaken, MySQL ceases to proceed with it. If you also want to prevent the record from being deleted, you'd need to create a similar trigger <code>BEFORE DELETE</code>.</p> <p>To determine whether a record is "locked", you could create a boolean <code>locked</code> column:</p> <pre><code>ALTER TABLE my_table ADD COLUMN locked BOOLEAN NOT NULL DEFAULT FALSE; DELIMITER ;; CREATE TRIGGER foo_upd BEFORE UPDATE ON my_table FOR EACH ROW IF OLD.locked THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot update locked record'; END IF;; CREATE TRIGGER foo_del BEFORE DELETE ON my_table FOR EACH ROW IF OLD.locked THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete locked record'; END IF;; DELIMITER ; UPDATE my_table SET locked = TRUE WHERE ...; </code></pre> <p>Note that <a href="http://dev.mysql.com/doc/en/signal.html" rel="noreferrer"><code>SIGNAL</code></a> was introduced in MySQL 5.5. In earlier versions, you must perform some erroneous action that causes MySQL to raise an error: I often call an non-existent procedure, e.g. with <code>CALL raise_error;</code></p> <hr> <blockquote> <p>I cannot create an additional column on this table, but the row has a unique id in one of the columns, so how would I do this for that scenario?</p> </blockquote> <p>Again, if you <em>absolutely must</em> place this logic in the storage layer—and cannot identify the locked records through any means other than the PK—you <em>could</em> hard-code the test into your trigger; for example, to "lock" the record with <code>id_column = 1234</code>:</p> <pre><code>DELIMITER ;; CREATE TRIGGER foo_upd BEFORE UPDATE ON my_table FOR EACH ROW IF OLD.id_column &lt;=&gt; 1234 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot update locked record'; END IF;; CREATE TRIGGER foo_del BEFORE DELETE ON my_table FOR EACH ROW IF OLD.id_column &lt;=&gt; 1234 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete locked record'; END IF;; DELIMITER ; </code></pre> <p>But this is <em>absolutely horrible</em> and I would do <em>almost anything</em> to avoid it whenever possible.</p>
24,960,902
Elasticsearch list indices sorted by name
<p>How can the following query's results be sorted by index name?</p> <pre><code>curl "localhost:9200/_aliases?pretty" </code></pre>
28,032,127
6
5
null
2014-07-25 17:05:08.177 UTC
5
2020-07-14 01:23:05.457 UTC
null
null
null
null
404,696
null
1
36
sorting|elasticsearch|aliases
38,924
<p>I think that the best way to do this would be via the console. Something like this:</p> <p><code>$ curl --silent 'http://path.to.cluster:9200/_cat/indices' | cut -d ' ' -f2 | sort </code></p>
32,018,741
How to get the result value of Alamofire.request().responseJSON in swift 2?
<p>I have a question about the new version of Alamofire for Swift 2</p> <pre><code>Alamofire.request(.POST, urlString, parameters: parameters as? [String : AnyObject]) .responseJSON { (request, response, result) -&gt; Void in let dico = result as? NSDictionary for (index, value) in dico! { print("index : \(index) value : \(value)") } } </code></pre> <p>In this section I would like to cast the result in to a NSDictionary. But When I compile and put a breakpoint, the debugger says that dico is nil. If I use debugDescription to print result, it is not nil and contains what I expected How can I cast the Result variable?</p>
33,423,387
3
4
null
2015-08-14 21:13:54.68 UTC
8
2020-10-13 13:47:32.27 UTC
2015-12-10 16:08:22.637 UTC
null
1,373,105
null
5,228,805
null
1
32
ios|json|swift|swift2|alamofire
51,665
<p>The accepted answer works great but with the introduction of Alamofire 3.0.0 there are some breaking changes that affects this implementation.<br> The <a href="https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md">migration guide</a> has further explanations but i will highlight the ones related to the actual solution.</p> <ul> <li><p><a href="https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md#response">Response</a><br> <em>All response serializers (with the exception of response) return a generic Response struct.</em></p></li> <li><p><a href="https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md#result-type">Response type</a><br> <em>The Result type has been redesigned to be a double generic type that does not store the NSData? in the <code>.Failure</code> case.</em></p></li> </ul> <p>Also take in count that Alamofire treats any completed request to be successful, regardless of the content of the response. So you need to chain a <code>.validate()</code> before <code>.responseJSON()</code> to hit the <code>.Failure</code> case. Read more about it <a href="https://github.com/Alamofire/Alamofire#validation">here</a>.</p> <p>Updated code:</p> <pre class="lang-swift prettyprint-override"><code>let url = "http://api.myawesomeapp.com" Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success(let data): let json = JSON(data) let name = json["name"].stringValue print(name) case .Failure(let error): print("Request failed with error: \(error)") } } </code></pre> <p>For reference:</p> <ul> <li>Xcode 7.3 (Swift 2.2)</li> <li>Alamofire 3.3.1</li> <li>SwiftyJSON 2.3.3</li> </ul>
33,359,157
Instead of using prefixes I want to ask site visitors to upgrade their browser
<p>I'm re-building a site using CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes" rel="nofollow noreferrer">flexbox</a>.</p> <p>In checking <a href="http://caniuse.com/#search=flexbox" rel="nofollow noreferrer">browser compatibility</a>, I see that flexbox is supported by all modern browsers, except that Safari 8 and IE 10 require vendor prefixes.</p> <p>In checking Google Analytics, I see that 96% of site visitors in the last 6 months use browsers that fully support flexbox. The remaining 4% use browsers that require prefixes or provide no support.</p> <p>Since we're talking about 4% of users, and the number will keep getting smaller, (and I like to keep my code as clean and simple as possible), I'm considering not using prefixes, and instead asking users to upgrade their browsers.</p> <blockquote> <p><em>How can I target older browsers in order to display a message to users asking them to update their browser?</em></p> </blockquote> <p>Here's what I have so far:</p> <pre><code>&lt;!--[if IE]&gt; &lt;div class="browserupgrade"&gt; &lt;p&gt;You are using an outdated browser. Please &lt;a href="http://browsehappy.com/"&gt; upgrade your browser&lt;/a&gt; to improve your experience.&lt;/p&gt; &lt;/div&gt; &lt;![endif]--&gt; </code></pre> <p>This IE conditional comment covers me for IE versions 6, 7, 8 and 9.</p> <p>These visitors will get an alert with a link to download a current browser. However, <a href="https://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx" rel="nofollow noreferrer">Microsoft discontinued support for conditional comments starting with IE10</a>.</p> <p>Now I need something similar for:</p> <ul> <li>IE 10</li> <li>Safari 7-8</li> <li>Opera Mini &lt; 8</li> <li>UC Browser for Android</li> <li>Android Browser &lt; 4.4</li> </ul> <p>Is there a simple JS/jQuery script to handle this job? Or another lightweight method?</p> <hr> <h2>Solution</h2> <p>Thanks for all the answers. Clearly there are many ways to tackle this problem (Modernizr, PHP, jQuery functions, plain Javascript, CSS, browser-update.org, etc.) Many of these methods will do the job completely and effectively. </p> <p>I went with the simplest one: CSS (credit <a href="https://stackoverflow.com/a/34812442/3597276">@LGSon</a>).</p> <p>This CSS covers essentially all targeted browsers, except for IE &lt;= 7.</p> <pre><code>.browserupgrade { display: block; } _:-ms-fullscreen, :root .browserupgrade { display: none; } :-o-prefocus, .browserupgrade { display: none; } @supports (display: flex) { .browserupgrade { display: none; }} </code></pre> <p>See the answer for details.</p> <p>And for those relatively few visitors using IE &lt;= 7, a conditional comment in the HTML:</p> <pre><code>&lt;!--[if lte IE 7]&gt; &lt;div style=" ... inline styles here ..."&gt; browser upgrade message here &lt;/div&gt; &lt;![endif]--&gt; </code></pre>
34,812,442
15
14
null
2015-10-27 02:49:02.413 UTC
15
2018-02-21 19:01:12.89 UTC
2018-02-21 19:01:12.89 UTC
null
2,827,823
null
3,597,276
null
1
40
javascript|jquery|css|flexbox
4,174
<p>Revised answer after question edit</p> <p>Here is a CSS only way to achieve that.</p> <p>As the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@supports" rel="noreferrer">CSS <code>@supports</code></a> won't work on your targeted (unwanted) browsers: Safari 7-8, IE &lt;= 10, Android Browser &lt; 4.4, UC Browser for Android and Opera Mini &lt; 8, your "browserupgrade" message will be visible on those using this rule.</p> <pre><code>@supports (display: flex) { .browserupgrade { display: none; }} </code></pre> <p>There is a few browsers that still does support the non-prefixed <code>flex</code> but doesn't support <code>@supports</code>, IE 11<sup>(1)</sup> and Opera Mini 8, but luckily we can address them with a couple of CSS specific rules.</p> <pre><code>/* IE 11 */ _:-ms-fullscreen, :root .browserupgrade { display: none; } /* Opera Mini 8 */ :-o-prefocus, .browserupgrade { display: none; } </code></pre> <hr> <p>Here is the complete code to show an upgrade message for your targeted browsers.</p> <p>CSS</p> <pre><code>.browserupgrade { display: block; } /* IE 11 */ _:-ms-fullscreen, :root .browserupgrade { display: none; } /* Opera Mini 8 */ :-o-prefocus, .browserupgrade { display: none; } /* all modern browsers */ @supports (display: flex) { .browserupgrade { display: none; }} </code></pre> <p>HTML </p> <pre><code>&lt;div class="browserupgrade"&gt; &lt;p&gt;You are using an outdated browser. Please &lt;a href="http://browsehappy.com/"&gt; upgrade your browser&lt;/a&gt; to improve your experience.&lt;/p&gt; &lt;/div&gt; </code></pre> <hr> <p><em>(1): The IE 11 CSS rule should work on IE Mobile 11 too, though haven't one to test it on.</em></p> <hr> <p>The CSS <code>@supports</code> is also available as an API, <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports" rel="noreferrer">CSS.supports()</a>. Here is a very well written <a href="https://davidwalsh.name/css-supports" rel="noreferrer">article by David Walsh</a>.</p> <hr> <p>Additionally, if one would like to automatically redirect those browser, here is a small script that does that, after a delay of 10 sec.</p> <pre><code>var el = document.querySelector('.browserupgrade'); if (window.getComputedStyle(el,null).getPropertyValue("display") != 'none') { setTimeout(function(){ window.location = 'http://browsehappy.com/'; }, 10000); } </code></pre>
13,626,956
How to refresh fragment tab content on button click
<p>I'm new in Android and I'm implementing a small project in which, I have news from one Drupal website. This app is with 3 tabs and every tab have a list of articles with specific content. The list of articles is created by textviews and imageviews arranged in linearlayout. When I click on the title, the article is opening with details. Those articles are loaded from Drupal site throught <code>HTTP POST</code> and <code>ViewJSON</code> module. Tabs are created with <code>FragmentActivity</code> and <code>TabHost</code>. Everything's ok and works fine until here.</p> <p>My problem is that I want to make one refresh button, to be placed over tabs and when I press it, the list of articles must refresh or reload and keep the current tab opened. I tried to replace tab fragment content and re-open it, but when I click on the title of one article to open it, the tab content remain in stack under all fragments. I mention that when I click on article's title, one new fragment is opening. I sent an id of the articles as an argument and in the same fragment I open the article's content.</p> <p>I was trying with this code but no success.</p> <pre><code>Button btn_refresh = (Button) findViewById(R.id.btn_refresh); btn_refresh.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String current_tab = mTabHost.getCurrentTabTag(); if(current_tab.contains(&quot;POPULARE&quot;)){ Fragment f; f = new PopulareActivity(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.tot,f); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } if(current_tab.contains(&quot;RECOMANDATE&quot;)){ Fragment f; f = new RecomandateActivity(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.tot,f); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } } }); </code></pre> <p>More exactly I enter on app, press Tab2 (show the list of articles from tab2), press refresh button, open one article, press the back button of mobile device and show me the content of tab2. Now, I enter on tab1 (and show the list of articles from tab1), open one article from the list of tab1, show me what I need, and press the back button from mobile. In this moment is shown the tab2 content (the list of articles form tab2 from where I pressed the refresh button.).</p> <p>To open details of an article I use:</p> <pre><code>tv.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Fragment f; f = new DetaliiActivity(); Bundle data = new Bundle(); data.putInt(&quot;id&quot;, nid); f.setArguments(data); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.tot,f); ft.addToBackStack(null); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } }); </code></pre> <p>Thanks in advance for help!</p>
13,627,424
2
0
null
2012-11-29 13:31:46.31 UTC
5
2022-02-17 14:08:02.957 UTC
2022-02-17 14:08:02.957 UTC
null
17,436,751
null
1,799,605
null
1
10
android|eclipse|tabs|android-fragments|refresh
74,159
<p>To refresh the contents of a fragment, you could keep a reference to the fragment, and call a public (for example) <code>refresh()</code> method in that fragment. Example:</p> <pre><code>public class ArticleTabFragmentActivity extends FragmentActivity{ private PopulareFragment populareFragment; private RecomandateFragment recomandateFragment; &lt;code&gt; private void bindView(){ Button btn_refresh = (Button) findViewById(R.id.btn_refresh); btn_refresh.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String current_tab = mTabHost.getCurrentTabTag(); if(current_tab.contains("POPULARE")){ populareFragment.refresh(); } else if(current_tab.contains("RECOMANDATE")){ recomandateFragment.refresh(); } }); } } public class PopulareFragment extends Fragment{ public void refresh(){ &lt;refresh the contents of the fragment&gt; } } &lt;Same for other fragment&gt; </code></pre> <p>Now when you create the tab fragment, like the PupulareFragment, use the pupulareFragment instance variable to store the fragment. So it is available in the refresh button onClick method.</p> <p>This way you are not replacing/creating any new fragments when refreshing. So going back to tabActivity after going to de article details activity, would probably work fine aswell.</p>
13,592,709
Retrieve album art using FFmpeg
<p>I'm developing an Android application that relies on FFmpeg to retrieve audio metadata. I know it's possible to retrieve album art programmatically using FFMpeg. However, once you have decoded the art (a video frame within an MP3) how do generate an image file (a PNG) for use within an application? I've search all over but can't seem to find a working example.</p> <p>Edit, here is the solution:</p> <pre><code>#include &lt;libavcodec/avcodec.h&gt; #include &lt;libavformat/avformat.h&gt; void retrieve_album_art(const char *path, const char *album_art_file) { int i, ret = 0; if (!path) { printf("Path is NULL\n"); return; } AVFormatContext *pFormatCtx = avformat_alloc_context(); printf("Opening %s\n", path); // open the specified path if (avformat_open_input(&amp;pFormatCtx, path, NULL, NULL) != 0) { printf("avformat_open_input() failed"); goto fail; } // read the format headers if (pFormatCtx-&gt;iformat-&gt;read_header(pFormatCtx) &lt; 0) { printf("could not read the format header\n"); goto fail; } // find the first attached picture, if available for (i = 0; i &lt; pFormatCtx-&gt;nb_streams; i++) if (pFormatCtx-&gt;streams[i]-&gt;disposition &amp; AV_DISPOSITION_ATTACHED_PIC) { AVPacket pkt = pFormatCtx-&gt;streams[i]-&gt;attached_pic; FILE* album_art = fopen(album_art_file, "wb"); ret = fwrite(pkt.data, pkt.size, 1, album_art); fclose(album_art); av_free_packet(&amp;pkt); break; } if (ret) { printf("Wrote album art to %s\n", album_art_file); } fail: av_free(pFormatCtx); // this line crashes for some reason... //avformat_free_context(pFormatCtx); } int main() { avformat_network_init(); av_register_all(); const char *path = "some url"; const char *album_art_file = "some path"; retrieve_album_art(path, album_art_file); return 0; } </code></pre>
13,677,225
2
0
null
2012-11-27 20:44:38.383 UTC
11
2019-01-07 07:41:28.96 UTC
2012-12-04 04:53:22.207 UTC
null
798,160
null
798,160
null
1
15
android|audio|ffmpeg|java-native-interface|metadata
17,617
<p>To use ffmpeg programmatically, I think you would have to call <a href="http://ffmpeg.org/doxygen/trunk/id3v2_8c-source.html#l00441" rel="noreferrer">read_apic</a>() in libavformat (which is part of ffmpeg). </p> <p>From the commandline, you can apparently do this:</p> <pre><code>ffmpeg -i input.mp3 -an -vcodec copy cover.jpg </code></pre> <p>The commandline behaviour implies that the cover art image is seen as just another video stream (containing just one frame), so using libavformat in the usual way you would to demux the video part of a stream should produce that image. </p> <p>Sample code for demuxing: <a href="http://ffmpeg.org/doxygen/trunk/demuxing_8c-source.html" rel="noreferrer">ffmpeg/docs/examples/demuxing.c</a> The first (and only) AVPacket that would be obtained from demuxing the video stream in an mp3 would contain the JPEG file (still encoded as JPEG, not decoded). </p> <pre><code>AVFormatContext* fmt_ctx; // set up fmt_ctx to read first video stream AVPacket pkt; av_read_frame(fmt_ctx, &amp;pkt); FILE* image_file = fopen("image.jpg", "wb"); int result = fwrite(pkt.data, pkt.size, 1, image_file); fclose(image_file); </code></pre> <p>If there are multiple images, I think they would be seen as separate video streams, rather than as separate packets in the same stream. The first stream would be the one with the largest resolution.</p> <p>All this is probably implemented internally in terms of read_apic().</p> <p>The ID3v2 spec allows for any image format, but recommends JPEG or PNG. In practice all images in ID3 are JPEG.</p> <p><strong>EDIT</strong>: Moved some of the less useful bits to postscript:</p> <p>P.S. <code>ffmpeg -i input.mp3 -f ffmetadata metadata.txt</code> will produce an ini-like file containing the metadata, but the image is not even referred to in there, so that is not a useful approach.</p> <p>P.S. There may be <a href="http://en.wikipedia.org/wiki/ID3#ID3v2_Embedded_Image_Extension" rel="noreferrer">multiple images</a> in an ID3v2 tag. You may have to handle the case when there is more than one image or more than one type of image present.</p> <p>P.S. ffmpeg is probably not the best software for this. Use <a href="http://id3lib.sourceforge.net/" rel="noreferrer">id3lib</a>, <a href="http://taglib.github.com/" rel="noreferrer">TagLib</a>, or one of the other <a href="http://id3.org/Implementations" rel="noreferrer">implementations of ID3</a>. These can be used either as libraries (callable from the language of your choice) or as commandline utilities. There is sample C++ code for TagLib here: <a href="https://stackoverflow.com/questions/4752020/how-do-i-use-taglib-to-read-write-coverart-in-different-audio-formats">How do I use TagLib to read/write coverart in different audio formats?</a> and for id3lib here: <a href="http://www.tejashwi.com/asknshare/7/how-to-get-album-art-from-audio-files-using-id3lib" rel="noreferrer">How to get album art from audio files using id3lib</a>.</p>
13,568,475
JPA and default locking mode
<p>With JPA, we can use manually <code>OPTIMISTIC</code> or <code>PESSIMISTIC</code> locking to handle entity changes in transactions.</p> <p>I wonder how JPA handles locking if we don't specify one of these 2 modes ? No locking mode is used?</p> <p>If we don't define an explicit locking mode, can the database integrity be lost?</p> <p>Thanks</p>
13,569,657
3
0
null
2012-11-26 15:59:38.34 UTC
8
2014-12-31 16:45:48.79 UTC
2012-11-26 16:25:06.7 UTC
null
216,021
null
1,358,752
null
1
25
java|jpa|transactions
22,965
<p>I've scanned through section 3.4.4 <em>Lock Modes</em> of the <a href="http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-eval-oth-JSpec" rel="noreferrer">Java Persistence API 2.0 Final Release</a> specification and while I couldn't find anything <em>specific</em> (it doesn't state that <em>this</em> is the default or anything like that) there is a footnote which says the following.</p> <blockquote> <p>The lock mode type NONE may be specified as a value of lock mode arguments and also provides a default value for annotations.</p> </blockquote> <p>The section is about the kinds of <a href="http://docs.oracle.com/javaee/6/api/javax/persistence/LockModeType.html" rel="noreferrer"><code>LockModeType</code></a> values available and their usages and describes which methods takes an argument of this kind and whatnot.</p> <p>So, as it said <code>LockModeType.NONE</code> is default for annotations (JPA, annotations left and right) I guess when you use <code>EntityManager.find(Class, Object)</code> the default <code>LockModeType</code> is used.</p> <p>There are some other, <em>subtle</em>, hints to reinforce this. Section 3.1.1 <em>EntityManager interface</em>.</p> <blockquote> <p>The find method (provided it is invoked without a lock or invoked with LockModeType.NONE) and the getReference method are not required to be invoked within a transaction context.</p> </blockquote> <p>It makes sense. For example if you use MySQL as your database and your database engine of choice is InnoDB then (by default) your tables will use <a href="http://dev.mysql.com/doc/refman/5.5/en/set-transaction.html#isolevel_repeatable-read" rel="noreferrer"><code>REPEATABLE READ</code></a>, if you use some other RDBMS or other database engines this could change.</p> <p>Right now I'm not exactly sure that isolation levels has anything to do with JPA lock modes (although it seems that way), but my point is that different database systems differ so JPA can't decide for you (at least according to the specification) what lock mode to use by default, so it'll use <code>LockModeType.NONE</code> if you don't instruct it otherwise.</p> <p>I've also found <a href="http://en.wikibooks.org/wiki/Java_Persistence/Locking#Isn.27t_database_transaction_isolation_all_I_need.3F" rel="noreferrer">an article regarding isolation levels and lock modes</a>, you might want to read it.</p> <p>Oh, and to answer your last question.</p> <blockquote> <p>If we don't define an explicit locking mode, can the database integrity be lost?</p> </blockquote> <p>It <em>depends</em>, but if you have concurrent transactions then the answer is probably <em>yes</em>.</p>
13,275,525
Change unhandled exception auto-generated catch code in Eclipse?
<p>If I have unhandled exception in Java, Eclipse proposes two options to me: (1) add throws declaration and (2) surround with try/catch.</p> <p>If I choose (2) it adds a code </p> <pre><code>try { myfunction(); } catch (MyUnhandledException e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre> <p>I want to change this to </p> <pre><code>try { myfunction(); } catch (MyUnhandledException e) { throw new RuntimeException(e); } </code></pre> <p>Is this possible?</p> <p><strong>UPDATE</strong></p> <p>Why are so love to change the topic people???</p> <p>If exception is catched and printed it is also no need to catch it anymore. I like my application to crash if I forget to handle an exception by mistake. So, I like to rethrow it by default.</p>
13,275,580
4
4
null
2012-11-07 18:05:40.537 UTC
7
2016-11-20 19:45:50.647 UTC
2012-11-07 18:11:56.727 UTC
null
1,171,620
null
1,171,620
null
1
29
java|eclipse|code-generation|content-assist
10,513
<p>Yes, you can change the default code added by Eclipse.</p> <ol> <li>In Preferences, navigate to <em>Java>Code Style>Code Templates</em>.</li> <li>Under <em>Code</em>, select <em>Catch block body</em>.</li> <li>Press the Edit button to change the code. When finished, press the <em>OK</em> button.</li> </ol> <p>Consider adding a TODO comment in the default catch block. For example, the default includes:</p> <pre><code> // ${todo} Auto-generated catch block </code></pre>
13,274,679
LIKE with % on column names
<p>Here is my query that results in a syntax error:</p> <pre><code>SELECT * FROM account_invoice,sale_order WHERE sale_order.name LIKE %account_invoice.origin% </code></pre> <p>The account_invoice.origin field contains the text of sale_order.name, plus other text as well, so I need to match sale_order.name string anywhere in the account_invoice.origin string. </p> <p>I'm using PostgreSQL 8.4.</p>
13,274,812
1
1
null
2012-11-07 17:11:23.683 UTC
8
2018-02-19 12:49:10.1 UTC
2018-02-19 12:49:10.1 UTC
null
696,441
null
1,806,801
null
1
47
postgresql|sql-like
37,128
<p>Try this</p> <pre><code>SELECT * FROM account_invoice,sale_order WHERE sale_order.name LIKE '%' || account_invoice.origin || '%' </code></pre> <p><code>%</code> needs single quote because the pattern is a string. </p> <p><code>||</code> is the operator for <a href="http://archives.postgresql.org/pgsql-sql/2000-07/msg00294.php" rel="noreferrer">concatenation</a>. </p>
3,239,039
Set Value of Private Static Field
<p>I want to set the value of a private field using reflection for unit testing.</p> <p>Problem is, that field is static.</p> <p>Here's what I'm working from:</p> <pre><code>/** * Use to set the value of a field you don't have access to, using reflection, for unit testing. * * Returns true/false for success/failure. * * @param p_instance an object to set a private field on * @param p_fieldName the name of the field to set * @param p_fieldValue the value to set the field to * @return true/false for success/failure */ public static boolean setPrivateField(final Object p_instance, final String p_fieldName, final Object p_fieldValue) { if (null == p_instance) throw new NullPointerException("p_instance can't be null!"); if (null == p_fieldName) throw new NullPointerException("p_fieldName can't be null!"); boolean result = true; Class&lt;?&gt; klass = p_instance.getClass(); Field field = null; try { field = klass.getDeclaredField(p_fieldName); field.setAccessible(true); field.set(p_instance, p_fieldValue); } catch (SecurityException e) { result = false; } catch (NoSuchFieldException e) { result = false; } catch (IllegalArgumentException e) { result = false; } catch (IllegalAccessException e) { result = false; } return result; } </code></pre> <p>I realize this has probably already been answered on SO, but my search didn't turn it up...</p>
3,239,068
2
2
null
2010-07-13 16:06:52.587 UTC
8
2013-03-18 13:10:43.783 UTC
null
null
null
null
187,206
null
1
39
java|unit-testing|reflection
48,656
<p>Basically the problem is your utility method, which assumes you have an instance. It's reasonably easy to set a private static field - it's exactly the same procedure as for an instance field, except you specify <code>null</code> as the instance. Unfortunately your utility method uses the instance to get the class, and requires it to be non-null...</p> <p>I'd echo Tom's caveat: don't do that. If this is a class you have under your control, I'd create a package level method:</p> <pre><code>void setFooForTesting(Bar newValue) { foo = newValue; } </code></pre> <p>However, here's a complete sample if you <em>really, really</em> want to set it with reflection:</p> <pre><code>import java.lang.reflect.*; class FieldContainer { private static String woot; public static void showWoot() { System.out.println(woot); } } public class Test { // Declared to throw Exception just for the sake of brevity here public static void main(String[] args) throws Exception { Field field = FieldContainer.class.getDeclaredField("woot"); field.setAccessible(true); field.set(null, "New value"); FieldContainer.showWoot(); } } </code></pre>
3,583,103
Network-Path Reference URI / Scheme relative URLs
<p>Scheme relative URLs (network-path references) are something that I've just found out about - where you don't specify the scheme of a URL and it picks it up from the current context.</p> <p>For example: <code>&lt;img src=&quot;//example.com/img.png&quot; /&gt;</code> will resolve to <code>https://example.com/img.png</code> if the current scheme is HTTPS or <code>http://example.com/img.png</code> if it is not.</p> <p>This seems like a very easy way to resolve those pesky problems of calling an external script or image on an SSL page without bringing up the dreaded error that some content on a page is not secure.</p> <p>The benefit seems obvious, but what I don't seem to be able to find is a huge amount of information on this and was wondering if anyone had any experience or references about scheme relative URLs (good or bad)?</p> <p>Whilst I'm trying to discover if there are any browsers that this causes issues with (I've been successful with IE6-8, Chrome and Firefox), I'm also interested to find out if anyone has any experience using this in different languages. For example, would it work if you were to issue a <code>Response.Redirect</code> with a scheme relative URL in ASP?</p>
3,583,129
2
1
null
2010-08-27 10:01:43.047 UTC
25
2022-07-01 10:29:08.71 UTC
2022-07-01 10:28:58.413 UTC
null
1,145,388
null
261,677
null
1
61
html|url|browser|response.redirect|protocol-relative
14,550
<p><code>//example.com/img.png</code> is a perfectly valid URI syntax as per <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="nofollow noreferrer">RFC 3986: Section 4.2</a>.</p> <p>It is relative to the current <a href="http://en.wikipedia.org/wiki/URI_scheme" rel="nofollow noreferrer">scheme</a>, and therefore as you mentioned, it can be very useful when switching between HTTP and HTTPS, because you won't need to explicitly specify the scheme.</p> <p>All modern browsers will understand that format, including IE 6.</p> <p>Further reading on Stack Overflow:</p> <ul> <li><a href="https://stackoverflow.com/questions/550038/is-it-valid-to-replace-http-with-in-a-script-srchttp">Is it valid to replace http:// with // in a <code>&lt;script src=&quot;http://...&quot;&gt;</code>?</a></li> <li><a href="https://stackoverflow.com/questions/2458735/using-in-a-scripts-source">Using // in a <code>&lt;script&gt;</code>'s source</a></li> </ul>
45,418,333
Jenkins: no tool named MSBuild found
<p>Setting up a Pipeline build in Jenkins (Jenkins 2.6), copying the sample script for a git-based build gives: "no tool named MSBuild found". I have set MSBuild Tool in <code>Manage Jenkins -&gt; Global Tool Configuration</code>. I am running pipeline on the slave node. <br/><br/>In Slave configuration, I have set MSBuild tool path in <code>Node Properties -&gt; Tool Locations</code>. <br/> While build process it is not able to get MSBuild tool path, if i run same source without pipeline (without using Jenkinsfile) it works fine. <br/><br/><br/>Please see Jenkinsfile Syntax</p> <pre><code>pipeline { agent { label 'win-slave-node' } stages { stage('build') { steps { bat "\"${tool 'MSBuild'}\" SimpleWindowsProject.sln /t:Rebuild /p:Configuration=Release" } } } } </code></pre> <p><br/><br/> I have also tried to change environment variable for windows slave it not refreshed. <br/><br/><br/><strong>NOTE: I have installed MS Build tool for on slave node</strong></p>
45,592,810
5
7
null
2017-07-31 14:14:46.59 UTC
8
2021-08-19 06:20:24.477 UTC
2017-08-03 05:57:22.333 UTC
null
3,511,167
null
3,511,167
null
1
10
jenkins|msbuild|jenkins-pipeline|jenkins-slave
13,431
<p>In <a href="https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline" rel="noreferrer">Declarative Pipeline</a> syntax, the tooling for MSBuild is a little clunkier. Here's how I've had to handle it, using a <code>script</code> block:</p> <pre><code>pipeline { agent { label 'win-slave-node' } stages { stage('Build') { steps { script { def msbuild = tool name: 'MSBuild', type: 'hudson.plugins.msbuild.MsBuildInstallation' bat "${msbuild} SimpleWindowsProject.sln" } } } } } </code></pre> <p>In the older Scripted Pipeline syntax, it could be like this:</p> <pre><code>node('win-slave-node') { def msbuild = tool name: 'MSBuild', type: 'hudson.plugins.msbuild.MsBuildInstallation' stage('Checkout') { checkout scm } stage('Build') { bat "${msbuild} SimpleWindowsProject.sln" } } </code></pre>
9,619,324
How to read XML file into List<>?
<p>I have a <code>List&lt;&gt;</code> which I wrote into an XML file. Now I am trying to read the same file and write it back to <code>List&lt;&gt;</code>. Is there a method to do that?</p>
9,619,418
5
2
null
2012-03-08 14:36:54.453 UTC
9
2021-02-04 06:21:02.897 UTC
2021-02-04 06:21:02.897 UTC
null
1,402,846
null
1,107,916
null
1
13
c#|xml
88,576
<p>I think the easiest way is to use the <code>XmlSerializer</code>:</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(List&lt;MyClass&gt;)); using(FileStream stream = File.OpenWrite("filename")) { List&lt;MyClass&gt; list = new List&lt;MyClass&gt;(); serializer.Serialize(stream, list); } using(FileStream stream = File.OpenRead("filename")) { List&lt;MyClass&gt; dezerializedList = (List&lt;MyClass&gt;)serializer.Deserialize(stream); } </code></pre>
9,534,484
GWT - RPC SerializationException
<p>It's been a while since I've been doing GWT and I needed something small done quickly. I set things up and now I have a RPC I need, but it fails.</p> <p>The RPC is supposed to give me a ArrayList, and Vacancy is located in #projectname#.client.model. The call is made in #projectname#.client.model. <br /> The interfaces for my Services are in #project#name.client.Service. <br /> Finally, the calls of course go to #projectname#.server. <br /> Vacancy implements IsSerializable. The Exception I get from running my RPC is the following:</p> <pre><code>Starting Jetty on port 8888 [WARN] Exception while dispatching incoming RPC call com.google.gwt.user.client.rpc.SerializationException: Type 'firsteight.client.model.Vacancy' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = firsteight.client.model.Vacancy@15fdd2f at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:619) at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126) at com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase.serialize(Collection_CustomFieldSerializerBase.java:44) at com.google.gwt.user.client.rpc.core.java.util.ArrayList_CustomFieldSerializer.serialize(ArrayList_CustomFieldSerializer.java:39) at com.google.gwt.user.client.rpc.core.java.util.ArrayList_CustomFieldSerializer.serializeInstance(ArrayList_CustomFieldSerializer.java:51) at com.google.gwt.user.client.rpc.core.java.util.ArrayList_CustomFieldSerializer.serializeInstance(ArrayList_CustomFieldSerializer.java:28) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:740) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:621) at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:126) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:153) at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:539) at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:616) at com.google.gwt.user.server.rpc.RPC.encodeResponseForSuccess(RPC.java:474) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:571) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) </code></pre> <p>The RPC I make is the following:</p> <pre><code>void getVacs() { try { homeService.getVacancies(new AsyncCallback&lt;ArrayList&lt;Vacancy&gt;&gt;() { public void onFailure(Throwable caught) { RootPanel.get("grayblock").add(new HTML("Failed:" + caught.getMessage())); } public void onSuccess(ArrayList&lt;Vacancy&gt; result) { RootPanel.get("grayblock").add(new HTML(result.get(0).getTitle())); } }); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>I thought I had done all I needed to make Vacancy Serializable, and an ArrayList of Vacancy as returntype for the RPC counts as having Vacancy as return type.. right? What am I doing wrong?</p> <p>Thanks in advance!</p>
9,534,704
6
2
null
2012-03-02 13:57:03.143 UTC
6
2019-03-10 21:35:34.21 UTC
null
null
null
null
1,021,835
null
1
16
java|gwt|rpc
38,111
<p>This is normally caused by using a non-serializable class, which can occur if your class does not implement <code>com.google.gwt.user.client.rpc.IsSerializable</code> or if you have forgotten to add an empty constructor.</p> <p>To pass a bean you have to fulfill the following requirements (from GWT site):</p> <ol> <li>It implements either Java Serializable or GWT IsSerializable interface, either directly, or because it derives from a superclass that does.</li> <li>Its non-final, non-transient instance fields are themselves serializable</li> <li>It has a default (zero argument) constructor with any access modifier (e.g. private Foo(){} will work)</li> </ol> <p>Even if you fulfill these requirements may happen that GWT compiler say:</p> <blockquote> <p> was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = @</p> </blockquote> <p>The problem may have different causes. Here his a complete check list to use for solving the problem:</p> <ol> <li>Verify that the class has a default constructor (without arguments)</li> <li>Verify that the class implements Serializable or IsSerializable or implements an Interface that extends Serializable or extends a class that implement Serializable</li> <li>Verify that the class is in a client.* package or …</li> <li>Verify, if the class is not in client.* package, that is compiled in your GWT xml module definition. By default is present. If your class is in another package you have to add it to source. For example if your class is under domain.* you should add it to xml as . Be aware that the class cannot belong to server package! More details on GWT page: <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModuleXml" rel="noreferrer">http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModuleXml</a></li> <li>If you are including the class from another GWT project you have to add the inherits to your xml module definition. For example if your class Foo is in the package com.dummy.domain you have to add to the module definition. More details here: <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideInheritingModules" rel="noreferrer">http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideInheritingModules</a></li> <li>If you are including the class from another GWT project released as a jar verify that the jar contains also the source code because GWT recompile also the Java source for the classes passed to the Client.</li> </ol> <p>PS:copied from <a href="http://isolasoftware.it/2011/03/22/gwt-serialization-policy-error/" rel="noreferrer">http://isolasoftware.it/2011/03/22/gwt-serialization-policy-error/</a> because the site is unavailable currently. If you want to read the original article search it from google using the above URL and read it from google web cache.</p>
9,301,225
Array of dictionaries in C#
<p>I would like to use something like this:</p> <pre><code>Dictionary&lt;int, string&gt;[] matrix = new Dictionary&lt;int, string&gt;[2]; </code></pre> <p>But, when I do:</p> <pre><code>matrix[0].Add(0, "first str"); </code></pre> <p>It throws " 'TargetInvocationException '...Exception has been thrown by the target of an invocation."</p> <p>What is the problem? Am I using that array of dictionaries correctly?</p>
9,301,251
5
2
null
2012-02-15 20:55:54.483 UTC
6
2012-02-15 21:01:57.107 UTC
2012-02-15 20:58:20.637 UTC
null
861,565
null
772,992
null
1
22
c#|arrays|dictionary
61,644
<p>Try this:</p> <pre><code>Dictionary&lt;int, string&gt;[] matrix = new Dictionary&lt;int, string&gt;[] { new Dictionary&lt;int, string&gt;(), new Dictionary&lt;int, string&gt;() }; </code></pre> <p>You need to instantiate the dictionaries inside the array before you can use them.</p>
9,518,687
Logback and Jboss 7 - don't work together?
<p>I am having a curious problem. I had this Java application which was previously deployed in tomcat and happily used logback classic as an slf4j implementation. Now when we tried to deploy the same app in a jboss 7.1.final server it doesn't even deploy the application maoning about <code>java.lang.ClassCastException: org.slf4j.impl.Slf4jLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext</code> This is the offending line of code </p> <pre><code>final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();</code></pre> <p>The class that has his is spring injected and that is failing - hence the whole application cannot be deployed. Anyone got a solution to this? Thanks in advance</p> <p>After looking in this site plus other forums I realised that Jboss 7 comes bundled with it's own slf4j implementation and implement the same ILoggerFactory interface that LoggerContext in logback does. Our application tried to get an instance of the same but the app server imposes it's own slf4j implementation.</p> <p>I tried to modify the module.xml in jboss\modules\org\slf4j\impl\main and pointed it to logback jars.</p> <pre><code>&lt;resources&gt; &lt;resource-root path="logback-classic-0.9.28.jar"/&gt; &lt;resource-root path="logback-core-0.9.28.jar"/&gt; &lt;/resources&gt; </code></pre> <p>Now when I start the application I am getting a serious error</p> <p><code>Exception starting filter WicketFilter: java.lang.ClassCastException: ch.qos.logback.classic.LoggerContext cannot be cast to ch.qos.logback.classic.LoggerContext</code></p> <p>I am at my wits end. Any jboss and logback experts can help? Thanks in advance</p>
9,520,699
4
2
null
2012-03-01 15:13:39.313 UTC
14
2022-03-31 14:01:24.447 UTC
2012-03-01 18:53:04.56 UTC
null
1,084,945
null
1,240,667
null
1
42
jboss7.x|logback
22,344
<p>You need to exclude the servers version of slf4j from your deployment. Create a <code>jboss-deployment-structure.xml</code> file and place it in either your WARS <code>META-INF</code> or <code>WEB-INF</code> directory.</p> <p>The contents of the file should look like this:</p> <pre><code>&lt;jboss-deployment-structure&gt; &lt;deployment&gt; &lt;!-- Exclusions allow you to prevent the server from automatically adding some dependencies --&gt; &lt;exclusions&gt; &lt;module name="org.slf4j" /&gt; &lt;module name="org.slf4j.impl" /&gt; &lt;/exclusions&gt; &lt;/deployment&gt; &lt;/jboss-deployment-structure&gt; </code></pre>
29,453,679
How do I get the current time in Elm?
<p>I'm running elm-repl to play around with the language. </p> <p>I'd like to see what the current time is. How would I do that? It doesn't appear to be possible with the current library. Why is that?</p> <hr> <p>EDIT: I made a package to help with this. <a href="http://package.elm-lang.org/packages/z5h/time-app" rel="noreferrer">http://package.elm-lang.org/packages/z5h/time-app</a></p> <p>This was asked around elm 0.15 - <strong>things are different in elm 0.17 &amp; 0.18</strong>: see <a href="https://stackoverflow.com/questions/38021777/how-do-i-get-the-current-time-in-elm-0-17">How do I get the current time in Elm 0.17/0.18?</a></p>
32,798,296
8
2
null
2015-04-05 02:59:12.923 UTC
8
2019-11-06 18:25:12.99 UTC
2019-01-10 15:58:05.837 UTC
null
7,943,564
null
131,227
null
1
21
time|elm
12,488
<p>To resolve my own question, I've created a variant of StartApp that includes a timestamp on each action.<br> So the update function has signature:<br> <code>update : action -&gt; Time -&gt; model -&gt; (model, Effects action)</code></p> <p>The Gist is here. <a href="https://gist.github.com/z5h/41ca436679591b6c3e51">https://gist.github.com/z5h/41ca436679591b6c3e51</a></p>
29,395,452
PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused
<p>I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this: </p> <pre><code>&lt;?php $servername = "127.0.0.1"; $username = "root"; $password = "root"; try { $conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password); // set the PDO error mode to exception $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e-&gt;getMessage(); } ?&gt; </code></pre> <p>I have been using postman to test to see if the connection is working, but I keep receiving this error message: </p> <blockquote> <p>Connection failed: SQLSTATE[HY000] [2002] Connection refused</p> </blockquote> <p>Before I was receiving an error message of:</p> <blockquote> <p>Connection failed: SQLSTATE[HY000] [2002] No such file or directory</p> </blockquote> <p>This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.</p> <p>Any help regarding this would be appreciated.</p>
29,400,976
11
4
null
2015-04-01 15:57:49.52 UTC
13
2022-08-12 19:49:47.597 UTC
2019-04-04 11:08:36.383 UTC
null
9,331,166
null
4,738,917
null
1
69
php|mysql|pdo
471,569
<p>I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.</p> <pre><code>$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password); </code></pre> <p>This fixed the problem, although changing the server name to localhost still gives the error.</p> <p>Connection failed: SQLSTATE[HY000] [2002] No such file or directory</p> <p>But it connects successfully when the IP address is entered for the server name.</p>
16,318,615
Try[Result], IO[Result], Either[Error,Result], which should I use in the end
<p>I'd like to know what should be the signature of my methods so that I handle different kind of failures elegantly.</p> <p>This question is somehow the summary of many questions I already had about error handling in Scala. You can find some questions here:</p> <ul> <li><a href="https://stackoverflow.com/questions/12886285/throwing-exceptions-in-scala-what-is-the-official-rule">Throwing exceptions in Scala, what is the &quot;official rule&quot;</a></li> <li><a href="https://stackoverflow.com/questions/16130039/either-options-and-for-comprehensions">Either, Options and for comprehensions</a></li> <li><a href="https://stackoverflow.com/questions/16194180/either-monadic-operations">Either monadic operations</a></li> </ul> <hr> <p>For now, I understand the following: </p> <ul> <li>Either can be used as a result wrapper for a method call that may fail</li> <li>Try is a Right biaised Either on which the failure is a non-fatal exception</li> <li>IO (scalaz) helps to build pure methods that handle IO operations</li> <li>All 3 are easily usable in a for comprehension</li> <li>All 3 are not easily mixable in a for comprehension because of incompatible flatMap methods</li> <li>In functional langages we usually don't throw exceptions unless they are fatal</li> <li>We should throw exceptions for really exceptional conditions. I guess this is the approach of Try</li> <li>Creating Throwables has a performance cost for the JVM and it is not intended to be used for business flow controle</li> </ul> <hr> <p><strong>Repository layer</strong></p> <p>Now please consider that I have a <code>UserRepository</code>. The <code>UserRepository</code> stores the users and defines a <code>findById</code> method. The following failures could happen:</p> <ul> <li>A fatal failure (<code>OutOfMemoryError</code>)</li> <li>An IO failure because the database is not accessible/readable</li> </ul> <p>Additionally, the user could be missing, leading to an <code>Option[User]</code> result</p> <p>Using a JDBC implementation of the repository, SQL, non-fatal exceptions (constraint violation or others) can be thrown so it can make sense to use Try. </p> <p>As we are dealing with IO operations, then the IO monad also makes sense if we want pure functions.</p> <p>So the result type could be:</p> <ul> <li><code>Try[Option[User]]</code></li> <li><code>IO[Option[User]]</code></li> <li>something else?</li> </ul> <hr> <p><strong>Service layer</strong></p> <p>Now let's introduce a business layer, <code>UserService</code>, which provides some method <code>updateUserName(id,newUserName)</code> that uses the previously defined <code>findById</code> of the repository. </p> <p>The following failures could happen: </p> <ul> <li>All repository failures propagated to the Service layer</li> <li>Business error: can't update the username of an user that doesn't exist</li> <li>Business error: the new username is too short</li> </ul> <p>Then the result type could be:</p> <ul> <li><code>Try[Either[BusinessError,User]]</code></li> <li><code>IO[Either[BusinessError,User]]</code></li> <li>something else?</li> </ul> <p>BusinessError here is not a Throwable because it is not an exceptional failure. </p> <hr> <p><strong>Using for-comprehensions</strong></p> <p>I would like to keep using for-comprehensions to combine method calls.</p> <p>We can't easily mix different monads on a for-comprehension, so I guess I should have some kind of uniform return type for all my operations right?</p> <p>I just wonder how do you succeed, in your real world Scala applications, to keep using for-comprehensions when different kind of failures can happen.</p> <p>For now, for-comprehension works fine for me, using services and repositories which all return <code>Either[Error,Result]</code> but all different kind of failures are melted together and it becomes kind of hacky to handle these failures. </p> <p>Do you define implicit conversions between different kind of monads to be able to use for-comprehensions?</p> <p>Do you define your own monads to handle failures?</p> <p>By the way perhaps I'll be using an asynchronous IO driver soon. So I guess my return type could be even more complicated: <code>IO[Future[Either[BusinessError,User]]]</code></p> <hr> <p>Any advice would be welcome because I don't really know what to use, while my application is not fancy: it is just an API where I should be able to make a distinction between business errors that can be shown to the client side, and technical errors. I try to find an elegant and pure solution.</p>
16,324,816
2
1
null
2013-05-01 13:03:02.633 UTC
9
2021-03-26 09:32:56.273 UTC
2017-05-23 12:09:36.44 UTC
null
-1
null
82,609
null
1
22
scala|scalaz|either
4,208
<p>This is what Scalaz's <code>EitherT</code> monad transformer is for. A stack of <code>IO[Either[E, A]]</code> is equivalent to <code>EitherT[IO, E, A]</code>, except that the former must be handled as multiple monads in sequence, whereas the latter is automatically a single monad that adds <code>Either</code> capabilities to the base monad <code>IO</code>. You can likewise use <code>EitherT[Future, E, A]</code> to add non-exceptional error handling to asynchronous operations.</p> <p>Monad transformers in general are the answer to a need to mix multiple monads in a single <code>for</code>-comprehension and/or monadic operation.</p> <hr> <p><strong>EDIT:</strong></p> <p>I will assume you are using Scalaz version 7.0.0.</p> <p>In order to use the <code>EitherT</code> monad transformer on top of the <code>IO</code> monad, you first need to import the relevant parts of Scalaz:</p> <pre><code>import scalaz._, scalaz.effect._ </code></pre> <p>You also need to define your error types: <code>RepositoryError</code>, <code>BusinessError</code>, etc. This works as usual. You just need to make sure that you can, e.g., convert any <code>RepositoryError</code> into a <code>BusinessError</code> and then pattern match to recover the exact type of error.</p> <p>Then the signatures of your methods become:</p> <pre><code>def findById(id: ID): EitherT[IO, RepositoryError, User] def updateUserName(id: ID, newUserName: String): EitherT[IO, BusinessError, User] </code></pre> <p>Within each of your methods, you can use the <code>EitherT</code>-and-<code>IO</code>-based monad stack as a single, unified monad, available in <code>for</code>-comprehensions as usual. <code>EitherT</code> will take care of threading the base monad (in this case <code>IO</code>) through the whole computation, while also handling errors the way <code>Either</code> usually does (except already right-biased by default, so you don't have to constantly deal with all the usual <code>.right</code> junk). When you want to do an <code>IO</code> operation, all you have to do is raise it into the combined monad stack by using the <code>liftIO</code> instance method on <code>IO</code>.</p> <p>As a side note, when working this way, the functions in the <code>EitherT</code> companion object can be very useful.</p>
16,073,368
onScroll gets called when I set listView.onScrollListener(this), but without any touch
<p>When I set the <code>onScrollListener</code> for my <code>ListView</code>, it calls <code>onScroll</code>. This causes a crash because certain things haven't been initialized.</p> <p>Is this normal? Note: this is happening without me even touching the phone.</p> <pre><code>public class MainActivity1 extends Activity implements OnClickListener, OnScrollListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout1); ListView lv = (ListView)findViewById(R.id.listview1); lv.setOnScrollListener(this); ... } ... public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){ if( firstVisibleItem+visibleItemCount == totalItemCount ){ pullContactList(); } } </code></pre>
16,073,621
5
5
null
2013-04-18 02:07:59.837 UTC
6
2016-12-01 06:11:57.893 UTC
2014-09-12 22:52:04.483 UTC
null
85,950
null
2,059,819
null
1
35
android|android-listview|onscroll
19,493
<p>It's normal because the source code for <code>setOnScrollListener</code> in <code>AbsListView</code> (the superclass of <code>ListView</code>) does this:</p> <pre><code> public void setOnScrollListener(OnScrollListener l) { mOnScrollListener = l; invokeOnItemScrollListener(); } </code></pre> <p>and <code>invokeOnItemScrollListener</code> does this:</p> <pre><code>/** * Notify our scroll listener (if there is one) of a change in scroll state */ void invokeOnItemScrollListener() { if (mFastScroller != null) { mFastScroller.onScroll(this, mFirstPosition, getChildCount(), mItemCount); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount); } onScrollChanged(0, 0, 0, 0); // dummy values, View's implementation does not use these. } </code></pre> <p>depending on what it is you're trying to do, there are a number of ways to avoid this problem.</p> <p>EDIT: </p> <p>Since you only want to do this if the user actually scrolled, I suppose you could do something like:</p> <pre><code> lv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if(view == lv &amp;&amp; motionEvent.getAction() == MotionEvent.ACTION_SCROLL) { userScrolled = true; } return false; } }); </code></pre> <p>Then..</p> <pre><code>lv.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){ if(userScrolled &amp;&amp; firstVisibleItem+visibleItemCount == totalItemCount ){ pullContactList(); } } }); </code></pre>
16,529,716
Save modifications in place with awk
<p>I am learning <code>awk</code> and I would like to know if there is an option to write changes to file, similar to <code>sed</code> where I would use <code>-i</code> option to save modifications to a file. </p> <p>I do understand that I could use redirection to write changes. However is there an option in <code>awk</code> to do that?</p>
16,531,920
7
2
null
2013-05-13 19:30:36.233 UTC
33
2020-08-07 21:42:59.737 UTC
2019-03-28 23:11:03.79 UTC
null
6,862,601
null
1,007,727
null
1
164
linux|unix|awk
130,353
<p>In GNU Awk <a href="https://groups.google.com/group/comp.lang.awk/browse_thread/thread/40ce7554f025c382" rel="noreferrer">4.1.0</a> (released 2013) and later, it has the option of <a href="https://www.gnu.org/software/gawk/manual/html_node/Extension-Sample-Inplace.html" rel="noreferrer">&quot;inplace&quot; file editing</a>:</p> <blockquote> <p>[...] The &quot;inplace&quot; extension, built using the new facility, can be used to simulate the GNU &quot;<code>sed -i</code>&quot; feature. [...]</p> </blockquote> <p>Example usage:</p> <pre><code>$ gawk -i inplace '{ gsub(/foo/, &quot;bar&quot;) }; { print }' file1 file2 file3 </code></pre> <p>To keep the backup:</p> <pre><code>$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, &quot;bar&quot;) } &gt; { print }' file1 file2 file3 </code></pre>
16,296,753
Can you run GUI applications in a Linux Docker container?
<p>How can you run GUI applications in a Linux <a href="http://www.docker.io" rel="noreferrer">Docker</a> container?</p> <p>Are there any images that set up <code>vncserver</code> or something so that you can - for example - add an extra speedbump sandbox around say Firefox?</p>
16,311,264
24
2
null
2013-04-30 09:40:54.487 UTC
285
2022-02-25 12:04:21.49 UTC
2021-06-03 18:16:08.81 UTC
null
3,195,477
null
15,721
null
1
487
linux|docker|x11|sandbox|vnc
384,511
<p>You can simply install a vncserver along with Firefox :)</p> <p>I pushed an image, vnc/firefox, here: <code>docker pull creack/firefox-vnc</code></p> <p>The image has been made with this Dockerfile:</p> <pre><code># Firefox over VNC # # VERSION 0.1 # DOCKER-VERSION 0.2 FROM ubuntu:12.04 # Make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" &gt; /etc/apt/sources.list RUN apt-get update # Install vnc, xvfb in order to create a 'fake' display and firefox RUN apt-get install -y x11vnc xvfb firefox RUN mkdir ~/.vnc # Setup a password RUN x11vnc -storepasswd 1234 ~/.vnc/passwd # Autostart firefox (might not be the best way to do it, but it does the trick) RUN bash -c 'echo "firefox" &gt;&gt; /.bashrc' </code></pre> <p>This will create a Docker container running VNC with the password <code>1234</code>:</p> <p>For Docker version 18 or newer:</p> <pre><code>docker run -p 5900:5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create </code></pre> <p>For Docker version 1.3 or newer:</p> <pre><code>docker run -p 5900 -e HOME=/ creack/firefox-vnc x11vnc -forever -usepw -create </code></pre> <p>For Docker before version 1.3:</p> <pre><code>docker run -p 5900 creack/firefox-vnc x11vnc -forever -usepw -create </code></pre>
53,167,490
Destruction of return value on destructor exception
<p>I have the following code:</p> <pre><code>#include &lt;stdexcept&gt; #include &lt;iostream&gt; struct ok { int _n; ok(int n) : _n(n) { std::cerr &lt;&lt; "OK" &lt;&lt; n &lt;&lt; " born" &lt;&lt; std::endl; } ~ok() { std::cerr &lt;&lt; "OK" &lt;&lt; _n &lt;&lt; " gone" &lt;&lt; std::endl; } }; struct problematic { ~problematic() noexcept(false) { throw std::logic_error("d-tor exception"); } }; ok boo() { ok ok1{1}; problematic p; ok ok2{2}; return ok{3}; // Only constructor is called... } int main(int argc, char **argv) { try {boo();} catch(...) {} } </code></pre> <p>I see that he destructor of ok{3} is not called, the output is:</p> <pre><code> OK1 born OK2 born OK3 born OK2 gone OK1 gone </code></pre> <p><strong>Is it the expected behavior for C++14?</strong></p> <p><strong>EDITs:</strong></p> <p>Compiling with gcc 6.3</p>
53,168,208
1
7
null
2018-11-06 07:29:32.367 UTC
4
2018-11-06 08:53:22.687 UTC
2018-11-06 07:46:32.817 UTC
null
917,572
null
917,572
null
1
38
c++|exception|c++14|destructor|object-lifetime
1,271
<p>As per the standard this behavior is wrong and this has already been mentioned in the comments section of the question. This is stated in the section on <a href="http://eel.is/c++draft/except.ctor#2" rel="noreferrer">Exception handling</a>. </p> <p>As per the <a href="http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#2176" rel="noreferrer">defect reports</a> at <a href="http://open-std.org" rel="noreferrer">open-std.org</a>, they have been aware that implementations (GCC and Clang) were wrong about this as early as 2015-09-28. But the proposed resolution was only in February, 2016 and the compilers (GCC and Clang) have not yet included this fix.</p> <blockquote> <p><strong>Proposed resolution (February, 2016):</strong></p> <p>Change 18.2 [except.ctor] paragraph 2 as follows:<br> The destructor is invoked for each automatic object of class type constructed, but not yet destroyed, since the try block was entered. <strong>If an exception is thrown during the destruction of temporaries or local variables for a return statement (9.6.3 [stmt.return]), the destructor for the returned object (if any) is also invoked.</strong> The objects are destroyed in the reverse order of the completion of their construction. [Example:</p> <pre><code> struct A { }; struct Y { ~Y() noexcept(false) { throw 0; } }; A f() { try { A a; Y y; A b; return {}; // #1 } catch (...) { } return {}; // #2 } </code></pre> <p>At #1, the returned object of type A is constructed. Then, the local variable b is destroyed (9.6 [stmt.jump]). Next, the local variable y is destroyed, causing stack unwinding, resulting in the destruction of the returned object, followed by the destruction of the local variable a. Finally, the returned object is constructed again at #2. —end example]</p> </blockquote> <p>There have been bugs filed against this issue both in <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=33799" rel="noreferrer">GCC</a> and <a href="https://bugs.llvm.org/show_bug.cgi?id=12286" rel="noreferrer">Clang</a>.</p> <p>The comments on the GCC bug report indicate that it is clearly a bug.</p> <p><a href="https://stackoverflow.com/users/981959/jonathan-wakely">Jonathan Wakely</a> comments: </p> <blockquote> <p>It's now 2013 so the sensible thing to do is not return by value if your destructor can throw. </p> </blockquote> <p>And another user: </p> <blockquote> <p>Yes, I noticed, and Clang has also had a bug filed against them which has languished for years. Nevertheless, the behavior is wrong.</p> </blockquote>
15,159,244
Calling a specific action of a controller on the click of HTML button(Not Submit or Form's post Button) Asp.net MVC
<p>When we click a Form's submit button, then action of the controller which is having HTTPPost attribute is called but what if i want to call or perform an action when a normal HTML button is clicked Although following articles </p> <p><a href="http://www.codeproject.com/Tips/198477/Calling-a-MVC-Controller-and-Action-Method-using-H" rel="nofollow noreferrer">http://www.codeproject.com/Tips/198477/Calling-a-MVC-Controller-and-Action-Method-using-H</a></p> <p><a href="https://stackoverflow.com/questions/2503923/html-button-calling-a-mvc-controller-and-action-method">HTML button calling an MVC Controller and Action method</a></p> <p>tells the approach but both of these are using controller name in view, So view has to know about controller, I am looking for an answer that view wont have to know about controller. because views has to be Independent from Controller, Views should not know about controller So, if you know the answer then please reply</p>
15,159,415
3
0
null
2013-03-01 13:44:46.097 UTC
1
2015-05-24 06:20:52.1 UTC
2017-05-23 12:09:14.08 UTC
null
-1
null
1,997,212
null
1
8
c#|asp.net|asp.net-mvc|asp.net-mvc-3|asp.net-mvc-4
49,109
<p>any form that directs your user to url created by </p> <pre><code>&lt;a href='@Url.Action("{action}", "{controller}")'&gt; click me &lt;/a&gt; </code></pre> <p>or</p> <pre><code>@using(BeginForm("{action}", "{controller}") </code></pre> <p>will do what you want. </p> <p>That can be with a </p> <ul> <li>form </li> <li>button link</li> </ul> <p>It's the destination that matters. The View does not "know" anything about the action or controller. The helper does.</p>
24,779,929
What happens when using make_shared
<p>I'm interested if these two lines of code are the same:</p> <pre><code>shared_ptr&lt;int&gt; sp(new int(1)); // double allocation? shared_ptr&lt;int&gt; sp(make_shared&lt;int&gt;(1)); // just one allocation? </code></pre> <p>If this is true could someone please explain why is it only one allocation in the second line?</p>
24,780,012
3
6
null
2014-07-16 11:42:42.983 UTC
9
2014-07-17 09:50:26.017 UTC
2014-07-16 21:26:33.143 UTC
null
1,708,801
null
1,659,758
null
1
26
c++|c++11|smart-pointers|make-shared
6,160
<p>The first case does not perform a double allocation, it performs two allocations, one for the <em>managed object</em> and one for the <em>control block</em> of the <code>shared_ptr</code>.</p> <p>For the second case, <a href="http://en.cppreference.com/w/">cppreference</a> has a good explanation for why <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared">std::make_shared</a> <strong>usually</strong> only performs one memory allocation it says (<em>emphasis mine going forward</em>):</p> <blockquote> <p>This function typically allocates memory for the T object and for the shared_ptr's control block with a single memory allocation <strong>(it is a non-binding requirement in the Standard)</strong>. In contrast, the declaration std::shared_ptr p(new T(Args...)) performs at least two memory allocations, which may incur unnecessary overhead.</p> </blockquote> <p>and from <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr">std::shared_ptr</a> section it says:</p> <blockquote> <p>When shared_ptr is created by calling std::make_shared or std::allocate_shared, the memory for both the control block and the managed object is created with a single allocation. The managed object is constructed in-place in a data member of the control block. When shared_ptr is created via one of the shared_ptr constructors, the managed object and the control block must be allocated separately. In this case, the control block stores a pointer to the managed object.</p> </blockquote> <p>This <code>make_shared</code> description is consistent with the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf">C++11 draft standard</a> which says in section <code>20.7.2.2.6</code> <em>shared_ptr creation</em></p> <blockquote> <pre><code>template&lt;class T, class... Args&gt; shared_ptr&lt;T&gt; make_shared(Args&amp;&amp;... args); template&lt;class T, class A, class... Args&gt; shared_ptr&lt;T&gt; allocate_shared(const A&amp; a, Args&amp;&amp;... args); </code></pre> <p>[...]</p> <p>Remarks: Implementations should perform no more than one memory allocation. [ Note: This provides efficiency equivalent to an intrusive smart pointer. —end note ]</p> <p>[ Note: These functions will typically allocate more memory than sizeof(T) to allow for internal bookkeeping structures such as the reference counts. —end note ]</p> </blockquote> <p>Herb Sutter has a more detailed explanation of the advantages of using <code>make_shared</code> in <a href="http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/">GotW #89 Solution: Smart Pointers</a> and points out some advantages:</p> <ul> <li>It reduces allocation overhead</li> <li>It improves locality. </li> <li>Avoids an explicit new.</li> <li>Avoids an exception safety issue.</li> </ul> <p>Be aware that when using <a href="http://en.cppreference.com/w/cpp/memory/weak_ptr">std::weak_ptr</a> <a href="http://lanzkron.wordpress.com/2012/04/22/make_shared-almost-a-silver-bullet/">using make_shared has some disadvantages</a>.</p>
27,355,688
Shared folder between MacOSX and Windows on Virtual Box
<p>I need to set up shared folder.</p> <p>I've got Mac OSX Yosemite host and clean Win7 x64 on the VirtualBox.</p> <p>In MacOSX, i go to the VirtualBox -> win7 settings -> "Shared Folders" -> Add shared folder -> creating folder /Users/my_name/Documents/win7 -> Make it permanent -> Click ok.</p> <p>What i should do in Windows then? </p> <p>Thank you.</p>
32,534,378
7
7
null
2014-12-08 10:15:01.91 UTC
19
2022-01-05 09:21:39.613 UTC
null
null
null
null
1,230,556
null
1
88
windows|macos|virtualbox
150,233
<h2>Edit</h2> <p>4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both <a href="https://www.virtualbox.org/manual/UserManual.html" rel="noreferrer">html</a> and <a href="http://download.virtualbox.org/virtualbox/UserManual.pdf" rel="noreferrer">pdf</a> formats, which effectively deprecates the previous version of this answer:</p> <ul> <li>Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections <a href="https://www.virtualbox.org/manual/UserManual.html#guestadd-intro" rel="noreferrer">4.1</a> and <a href="https://www.virtualbox.org/manual/UserManual.html#guestadd-install" rel="noreferrer">4.2</a></li> <li>Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section <a href="https://www.virtualbox.org/manual/UserManual.html#sharedfolders" rel="noreferrer">4.3</a></li> </ul> <h2>Original Answer</h2> <p>Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:</p> <ol> <li>VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.</li> <li>Boot Windows</li> <li>Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.</li> <li>After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.</li> </ol> <p>Hope that helps.</p>
21,650,617
HTML Form Field - How to require an input format
<p>What I want to do here is require that phone numbers be entered into my HTML form as (XXX) XXX-XXXX and that SS Numbers are entered as XXX-XX-XXXX. Thats it. </p> <p>The only reason I am doing this is so that the form submission results are consistent and easy exported to Excel.</p> <p>I have been told to use Javascript to do this but perhaps I am not advanced enough to understand all the steps in doing that.</p> <p>Can someone please point me in the right direction here keeping in mind that I am a beginner?</p> <p>Wow thank you so much Ethan and @suman-bogati! I am ALMOST there now! The field now pops an error stating to use the correct format of 555-55-5555. Thats great. But no matter what I enter enter into that field the popup persists. I tried 555-55-5555 and also 555555555 and neither are accepted. Here is the HTML for that field: </p> <pre><code>&lt;label&gt; Social Security Number: &lt;input id="ssn" required pattern="^d{3}-d{2}-d{4}$" title="Expected pattern is ###-##-####" /&gt; &lt;/label&gt; &lt;/div&gt; &lt;script&gt;$('form').on('submit', function(){ $(this).find('input[name="SocialSecurity"]').each(function(){ $(this).val() = $(this).val().replace(/-/g, ''); }); $(this).find('input[name="ssn"]').each(function(){ $(this).val() = $(this).val().replace(/-/g, ''); }); });&lt;/script&gt; &lt;br /&gt; </code></pre>
21,650,828
4
4
null
2014-02-08 19:13:19.343 UTC
1
2014-02-09 17:29:14.873 UTC
2014-02-09 17:29:14.873 UTC
null
594,235
null
3,187,816
null
1
5
javascript|html|forms|field|masking
62,754
<p>The easiest way to do that is by simply using multiple fields:</p> <pre><code>&lt;div&gt; Phone: (&lt;input type="text" name="phone-1" maxlength="3"&gt;) &lt;input type="text" name="phone-2" maxlength="3"&gt;- &lt;input type="text" name="phone-3" maxlength="4"&gt; &lt;/div&gt; &lt;div&gt; SSN: &lt;input type="text" name="ssn-1"&gt;- &lt;input type="text" name="ssn-2"&gt;- &lt;input type="text" name="ssn-3"&gt; &lt;/div&gt; </code></pre> <p>While this approach is certainly easy, it's not great. The user has to press tab or click on each field to enter the data, and there's nothing (other than common sense) from preventing them from entering things other than digits.</p> <p>I always feel that, when it comes to validation, the less you can get in the user's way, the better. Let them enter their phone number in whatever format they like, then you scrub it, removing everything but digits. That way the user can enter "5555551212" or "(555) 555-1212", but the database will always hold "5555551212".</p> <p>The other thing to consider is that HTML5 offers some nice specific types for phone numbers (but not SSNs). A modern browser will take care of all the input validation and, even better, mobile devices will show the numeric keypad instead of the whole keypad.</p> <p>Given that, the <em>best</em> way to display your form is this:</p> <pre><code>&lt;div&gt; &lt;label for="fieldPhone"&gt;Phone: &lt;/label&gt; &lt;input type="tel" id="fieldPhone" placeholder="(555) 555-1212"&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="fieldSsn"&gt;SSN: &lt;/label&gt; &lt;input type="text" id="fieldSsn" name="ssn" placeholder="555-55-5555" pattern="\d{3}-?\d{2}-?\d{4}"&gt; &lt;/div&gt; </code></pre> <p>If the user has a modern browser, this will handle the user side of the input validation for you. If they don't, you'll have to use a validation library or polyfill. There's a whole list of HTMl5 form validation polyfills here:</p> <p><a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms">https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms</a></p> <p>So all that remains is now to normalize your data when you save it to the database.</p> <p>The ideal place to do that would be the back end; it doesn't say where your form is going, though, so maybe you don't have any say on how things are processed on the back end. So you can do this in the front end instead. For example, using jQuery:</p> <pre><code>$('form').on('submit', function(){ $(this).find('input[type="tel"]').each(function(){ $(this).val() = $(this).val().replace(/[\s().+-]/g, ''); }); $(this).find('input[name="ssn"]').each(function(){ $(this).val() = $(this).val().replace(/-/g, ''); }); }); </code></pre> <p>This is not a perfect approach either: if you do validation in this function, and the validation fails, the user will see his or her input replaced by the normalized versions, which can be disconcerting.</p> <p>The best approach would be to use AJAX and <code>.serialize</code>; not only can you have better control over the UI, but you can do all the validation you want. But that's probably a little beyond what you need to do right now.</p> <p>Note that phone validation is the trickiest. The HTML5 phone validation is very permissive, allowing people to enter international phone numbers, which can have pretty complicated formats. Even people in the US will sometimes enter phone numbers like "+1 (555) 555-1212", and then you have 8 digits instead of 7. If you really want to restrict them to 7 digits, you'll have to add your own custom validation:</p> <pre><code>/^\(?\d{3}\)?[.\s-]?\d{3}[.\s-]\d{4}$/ </code></pre> <p>This will cover all the common variations people use (periods, spaces, dashes, parentheses), and still allow only 7-digit US phone numbers.</p> <p>Here's a jsfiddle demonstrating the HTML5 validation and normalization:</p> <p><a href="http://jsfiddle.net/Cj7UG/1/">http://jsfiddle.net/Cj7UG/1/</a></p> <p>I hope this helps!</p>
21,646,605
Global.asax magic functions
<p>When creating an ASP.NET Mvc project in Visual Studio, a <code>Global.asax</code> &amp; <code>Global.asax.cs</code> will be created. In this .cs file you will find the standard <code>Application_Start</code> method.</p> <p>My question is the following, how is this function called? because it is not a override. So my guess is that this method name is by convention. The same goes for the <code>Application_Error</code> method.</p> <p>I want to know where these methods are hooked. Because I write those methods (not override them) I couldn't find any documentation on them in MSDN. (I found <a href="http://msdn.microsoft.com/en-us/library/994a1482.aspx">this</a> page but it only tells you to hook to the <code>Error</code> event and shows a <code>Application_Error(object sender, EventArgs e)</code> but not how the Event and the method are linked.)</p> <pre><code>//Magicly called at startup protected void Application_Start() { //Omitted } //Magicly linked with the Error event protected void Application_Error(object sender, EventArgs e) { //Omitted } </code></pre>
21,646,790
3
4
null
2014-02-08 13:32:04.763 UTC
5
2017-12-12 10:53:55.983 UTC
null
null
null
null
637,425
null
1
29
c#|asp.net|asp.net-mvc|error-handling
28,003
<p>It isn't really magical.. the ASP.NET Pipeline wires all of this up.</p> <p>You can <a href="http://msdn.microsoft.com/en-us/library/bb470252.aspx#Overview" rel="nofollow noreferrer">see the documentation regarding this here</a>.</p> <p>Specifically you will be interested in the parts below:</p> <blockquote> <p>An <code>HttpApplication</code> object is assigned to the request.</p> </blockquote> <p>Which consists of a list of events that are fired and in what order.</p> <p>There are links all over that page (too many to contain here) that link off to various other pages with even more information.</p> <hr> <blockquote> <p>ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as <code>Application_BeginRequest</code>. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page's <code>Page_Load</code> event.</p> </blockquote> <p><sup> <em>Source</em>: <a href="http://msdn.microsoft.com/en-us/library/ms178473.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms178473.aspx</a> </sup></p>
19,390,690
CSS media queries to hide and show page elements .
<p>I'm kind of new to coding with media queries, and I think I have painted myself into a corner, using too many media queries (and probably in the wrong way).</p> <p>What I want to do is to hide some page elements when the width of the screen or device is smaller than 481px. So in the screenshot below, you might be able to see the couple of lines of text in the upper right corner.</p> <p><img src="https://i.stack.imgur.com/fF1bk.png" alt="Screenshot of Web Site&#39;s Header area"></p> <p>My problem has to do with the media queries that I've used. I am at wit's end to figure out (1) why the page elements (those two lines of text in the upper right corner) are not disappearing when the page gets smaller than 481px OR (2) why they do not appear in any larger screen/device sizes when I do manage to get the page elements to disappear.</p> <p>Here is the piece of CSS code that seems to cause some issues:</p> <pre><code>/* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px){ /* Hiding elements for this device * * * * * * * * * * * * * */ /* .poweredBy{ display: none; } */ } </code></pre> <p>With this code commented out, those two lines of text won't disappear until the window (device?) width is somewhere around 320px.</p> <p><img src="https://i.stack.imgur.com/PRf62.png" alt="enter image description here"></p> <p>Here is the entire CSS:</p> <pre><code>/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { .poweredBy{ display: none; } } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px){ .poweredBy{ display: none; } } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { .poweredBy{ display: none; } } /* iPhone 4 ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {} @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {} /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {} /* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {} /* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {} /* iPad 3 ---------------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {} @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {} /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) {} /* 960px layouts ----------- */ @media only screen and (min-width : 960px){} /* Large screens ----------- */ @media only screen and (min-width : 1824px) {} </code></pre> <p>I am using GroundworkCSS underneath, but I have added a few media queries myself -- that was most likely not an enlightened act on my behalf. So if anyone could point me in the right direction, I would be most grateful. Thanks.</p>
19,390,909
2
4
null
2013-10-15 20:44:31.78 UTC
5
2015-05-22 16:00:45.033 UTC
null
null
null
null
1,352,361
null
1
9
css|media-queries
38,190
<p>You have way to many media queries, the most you should have is three one for tablet, tablet landscape and mobile. Typically like this, </p> <p><strong>CSS</strong> </p> <pre><code>/** Mobile **/ @media only screen and (max-width: 767px), only screen and (max-device-width: 767px) { } /** Tablet **/ @media only screen and (min-width : 768px) and (max-width : 1024px) { } /** Tablet (landscape) **/ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { } </code></pre>
17,389,280
Check if window has focus
<p>I need to check if the user has windows on focus, I'm currently doing this:</p> <pre><code>var isonfocus=true; window.onblur = function(){ isonfocus=false; } window.onfocus = function(){ isonfocus=true; } </code></pre> <p>And whenever I need to check if the user has the windows on focus I just do <code>if(isonfocus==true)</code>. </p> <p>Problem: if the user loses focus before the page loads, even if I do <code>if(isonfocus==true)</code> it will return true, even though the window is not on focus, and defining the var to false <code>var isonfocus=false;</code> will do the reverse.</p> <p>Can someone help me? Thanks.</p> <p><strong>UPDATE</strong><br> Imagine a PTC (Paid-To-Click) site, when you go and click an ad to view, most sites verify if the user is actually seeing the advertiser site (has focus) or not (lost focus).<br> This is similar with what I need, I need a way to verify if the user has the window (which contains an iframe) on focus.<br> And to gain focus, the user could click the iframe, document or on the tab.<br> And please note that this needs to work on all major browsers.</p>
17,907,649
7
1
null
2013-06-30 10:11:57.233 UTC
7
2022-01-27 08:23:55.837 UTC
2013-06-30 16:02:05.533 UTC
user2536244
null
user2536244
null
null
1
39
javascript|jquery
72,862
<pre><code>var has_focus = true; function loading_time() { $(":focus").each(function() { if($(this).attr("id")=="iframeID") has_focus = true; }); if(has_focus==true) alert('page has focus'); else alert('page has not focus'); setTimeout("loading_time()", 2000); } window.onblur = function(){ has_focus=false; } window.onfocus = function(){ has_focus=true; } $(window).load(function(){ setTimeout("loading_time()", 2000); }); </code></pre> <p>To make it more efficient, you need to <code>var has_focus = false;</code> and make the user click somewhere on the page.</p>
37,071,353
How to check if a variable exists in a batch file?
<p>I am using the <code>call</code> command:</p> <pre><code>call beingcalled.bat randomnumber </code></pre> <p>In <strong>beingcalled.bat</strong>:</p> <pre><code>@echo off set call=%1 echo %call% set call=%call%%call% call caller.bat %call%` </code></pre> <p>In <strong>caller.bat</strong>:</p> <pre><code>@echo off set calltwo=%1 echo %calltwo% if "%calltwo%"== "" ( echo Error ) else ( call beingcalled.bat randomnumber ) </code></pre> <p>Why does the command <code>if "%calltwo%"== ""</code> not work? And how do I see if a variable was set?</p>
37,073,832
4
3
null
2016-05-06 11:34:02.007 UTC
4
2022-01-13 18:54:51.953 UTC
2018-06-16 22:15:07.913 UTC
null
41,956
null
6,184,644
null
1
44
windows|batch-file|cmd
99,934
<pre><code>IF "%Variable%"=="" ECHO Variable is NOT defined </code></pre> <p>This should help but this works, provided the value of Variable does not contain double quotes. Or you may try. Both worked for me.</p> <pre><code>VERIFY OTHER 2&gt;nul SETLOCAL ENABLEEXTENSIONS IF ERRORLEVEL 1 ECHO Unable to enable extensions IF DEFINED MyVar (ECHO MyVar IS defined) ELSE (ECHO MyVar is NOT defined) ENDLOCAL </code></pre> <blockquote> <p>source <a href="http://www.robvanderwoude.com/battech_defined.php" rel="noreferrer">http://www.robvanderwoude.com/battech_defined.php</a></p> </blockquote>
37,135,193
How to set default values in Go structs
<p>There are multiple answers/techniques to the below question:</p> <ol> <li>How to set default values to golang structs?</li> <li>How to initialize structs in golang</li> </ol> <p>I have a couple of answers but further discussion is required.</p>
37,521,991
11
3
null
2016-05-10 10:00:52.49 UTC
37
2022-08-15 15:35:04.777 UTC
2018-07-13 21:44:44.58 UTC
null
142,162
null
2,077,459
null
1
238
go|struct|initialization|default-value
281,497
<ol> <li><p>Force a method to get the struct (the constructor way).</p> <p>From <a href="https://stackoverflow.com/a/36826362">this post</a>:</p> <blockquote> <p>A good design is to make your type unexported, but provide an exported constructor function like <code>NewMyType()</code> in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.</p> </blockquote> <p>This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.</p> </li> <li><p>Another way to customize it for you own module is by using a <a href="https://web.archive.org/web/20160818125551/https://joneisen.tumblr.com/post/53695478114/golang-and-default-values" rel="noreferrer">Config struct to set default values</a> (Option 5 in the link). Not a good way though.</p> </li> </ol>