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
19,688,314
How do you attach and detach from Docker's process?
<p>I can attach to a docker process but <kbd>Ctrl</kbd>+<kbd>c</kbd> doesn't work to detach from it. <code>exit</code> basically halts the process. </p> <p>What's the recommended workflow to have the process running, occasionally attaching to it to make some changes, and then detaching?</p>
19,689,048
17
2
null
2013-10-30 16:20:14.473 UTC
176
2022-06-03 12:15:33.973 UTC
2014-10-17 14:22:03.58 UTC
null
33,204
null
671,573
null
1
544
docker
445,112
<p>To detach the tty without exiting the shell, use the escape sequence <kbd>Ctrl</kbd>+<kbd>P</kbd> followed by <kbd>Ctrl</kbd>+<kbd>Q</kbd>. More details <a href="https://docs.docker.com/engine/reference/commandline/attach/" rel="noreferrer">here</a>.</p> <p>Additional info from <a href="https://groups.google.com/forum/#!msg/docker-user/nWXAnyLP9-M/kbv-FZpF4rUJ" rel="noreferrer">this source</a>:</p> <ul> <li>docker run -t -i → can be detached with <code>^P^Q</code>and reattached with docker attach</li> <li>docker run -i → cannot be detached with <code>^P^Q</code>; will disrupt stdin</li> <li>docker run → cannot be detached with <code>^P^Q</code>; can SIGKILL client; can reattach with docker attach</li> </ul>
44,971,954
How to get am pm from the date time string using moment js
<p>I have a string as <code>Mon 03-Jul-2017, 11:00 AM/PM</code> and I have to convert this into a string like <code>11:00 AM/PM</code> using moment js.</p> <p>The problem here is that I am unable to get <code>AM</code> or <code>PM</code> from the date time string.</p> <p>I am doing this:</p> <pre><code>moment(Mon 03-Jul-2017, 11:00 AM, 'dd-mm-yyyy hh:mm').format('hh:mm A') </code></pre> <p>and it is working fine as I am getting <code>11:00 AM</code> but if the string has <code>PM</code> in it it is still giving <code>AM</code> in the output.</p> <p>like this <code>moment(Mon 03-Jul-2017, 11:00 PM, 'dd-mm-yyyy hh:mm').format('hh:mm A')</code> is also giving <code>11:00 AM</code> in output instead of <code>11:00 PM</code></p>
44,972,009
3
2
null
2017-07-07 13:24:45.243 UTC
4
2022-07-19 10:43:26.02 UTC
null
null
null
null
6,574,017
null
1
95
javascript|momentjs
162,553
<p>You are using the wrong format tokens when parsing your input. You should use <code>ddd</code> for an abbreviation of the name of day of the week, <code>DD</code> for day of the month, <code>MMM</code> for an abbreviation of the month's name, <code>YYYY</code> for the year, <code>hh</code> for the <code>1-12</code> hour, <code>mm</code> for minutes and <code>A</code> for <code>AM/PM</code>. See <a href="http://momentjs.com/docs/#/parsing/string-format/" rel="noreferrer"><code>moment(String, String)</code></a> docs.</p> <p>Here is a working live sample:</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>console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') ); console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
984,050
C# Strategy Design Pattern by Delegate vs OOP
<p>I wonder what's the pros/cons of using delegate vs OOP when implementing strategy design pattern?</p> <p>Which one do you recommend to use? or what kind of problem does delegate solve? and why should we use OOP if OOP is better?</p> <p>Thanks!</p> <p>-tep</p>
984,111
5
0
null
2009-06-11 22:15:51.843 UTC
14
2019-04-25 13:49:02.16 UTC
2009-09-20 18:12:23.76 UTC
null
364
null
119,397
null
1
26
c#|design-patterns
6,061
<p>Both techniques can be powerful and valuable - here are some of my opinions about when to use which.</p> <p>Use an Interface/Implementation approach when the strategy:</p> <ol start="2"> <li>maintains state</li> <li>needs configuration</li> <li>uses dependency injection</li> <li>needs to be configured by an IoC container (think ConnectionProvider)</li> <li>combines multiple responsibilities (think DataAdapter from ADO.NET)</li> <li>is too complex or long as a single method</li> <li>is likely to be subclassed to create new strategies</li> <li>needs to return state information to the caller</li> <li>needs to access internals of the object is applies to</li> <li>Would require too many direct parameters</li> </ol> <p>Otherwise, tend to use delegates based on Func&lt;> or Action&lt;>, especially if</p> <ol> <li>There are likely to be a very large variety of strategies (think sort expressions)</li> <li>The strategy is best expressed as as lambda</li> <li>There's an existing method you want to leverage</li> </ol>
918,026
List<? extends MyType>
<p>I have a Java question about generics. I declared a generic list: </p> <pre><code>List&lt;? extends MyType&gt; listOfMyType; </code></pre> <p>Then in some method I try instantiate and add items to that list:</p> <pre><code>listOfMyType = new ArrayList&lt;MyType&gt;(); listOfMyType.add(myTypeInstance); </code></pre> <p>Where <code>myTypeInstance</code> is just an object of type <code>MyType</code>; it won't compile. It says:</p> <blockquote> <p>The method add(capture#3-of ? extends MyType) in the type List&lt;capture#3-of ? extends MyType> is not applicable for the arguments (MyType)</p> </blockquote> <p>Any idea?</p>
918,047
5
1
null
2009-05-27 21:10:08.367 UTC
9
2020-11-09 10:29:48.16 UTC
2013-04-17 12:55:56.923 UTC
null
4,725
null
78,793
null
1
41
java|list|generics|bounded-wildcard
62,676
<p>You cannot do a "put" with extends . Look at <a href="https://stackoverflow.com/questions/1292109/generics-get-and-put-rule">Generics - Get and Put rule</a>.</p>
164,648
Where can I find a good collection of public domain owl ontologies for various domains?
<p>I am building an ontology-processing tool and need lots of examples of various owl ontologies, as people are building and using them in the real world. I'm not talking about foundational ontologies such as Cyc, I'm talking about smaller, domain-specific ones.</p>
174,396
6
0
null
2008-10-02 21:14:56.637 UTC
12
2014-10-03 13:35:26.203 UTC
null
null
null
Kevin Pauli
19,269
null
1
15
semantic-web|owl|ontology
3,960
<p>There's no definitive collection afaik, but these links all have useful collections of OWL and RDFS ontologies:</p> <ul> <li><a href="http://www.schemaweb.info/" rel="noreferrer">schemaweb.info</a></li> <li><a href="http://vocab.org/" rel="noreferrer">vocab.org</a></li> <li><a href="http://www.owlseek.com/master.html" rel="noreferrer">owlseek</a></li> <li><a href="http://www.umbel.org/lod_constellation.html" rel="noreferrer">linking open data constellation</a></li> <li><a href="http://139.91.183.30:9090/RDF/Examples.html" rel="noreferrer">RDF schema registry</a> (rather old now)</li> </ul> <p>In addition, there are some general-purpose RDF/RDFS/OWL search engines you may find helpful:</p> <ul> <li><a href="http://sindice.com/" rel="noreferrer">sindice</a></li> <li><a href="http://swoogle.umbc.edu/" rel="noreferrer">swoogle</a></li> </ul> <p>Ian</p>
1,085,584
How do I programmatically retrieve the actual path to the "Program Files" folder?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/194157/c-sharp-how-to-get-program-files-x86-on-windows-vista-64-bit">C# - How to get Program Files (x86) on Windows Vista 64 bit</a> </p> </blockquote> <p>I realize the odds of a user changing the Windows default of <code>C:\Program Files</code> is fairly slim, but stranger things have happened!</p> <p>How can I get the correct path to <code>Program Files</code> from the system?</p>
1,085,592
6
3
null
2009-07-06 05:48:15.59 UTC
6
2012-08-04 18:53:54.18 UTC
2017-05-23 12:10:35.467 UTC
null
-1
null
6,340
null
1
22
c#|.net|windows|windows-xp|program-files
39,888
<p>.NET provides an enumeration of '<a href="http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx" rel="noreferrer">special folders</a>' for Program Files, My Documents, etc.</p> <p>The code to convert from the enumeration to the actual path looks like this:</p> <pre><code>Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/14tx8hby.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/14tx8hby.aspx</a></p>
1,051,989
Regex for alphanumeric, but at least one letter
<p>In my ASP.NET page, I have an input box that has to have the following validation on it:</p> <blockquote> <p>Must be alphanumeric, with at least <em>one</em> letter (i.e. can't be ALL numbers).</p> </blockquote>
1,051,998
6
0
null
2009-06-27 02:25:57.427 UTC
9
2021-09-08 19:17:32.213 UTC
2021-09-08 19:17:32.213 UTC
null
814,702
null
68,183
null
1
27
regex|alphanumeric
71,478
<pre><code>^\d*[a-zA-Z][a-zA-Z0-9]*$ </code></pre> <p>Basically this means:</p> <ul> <li>Zero or more ASCII digits;</li> <li>One alphabetic ASCII character;</li> <li>Zero or more alphanumeric ASCII characters.</li> </ul> <p>Try a few tests and you'll see this'll pass any alphanumeric ASCII string where at least one non-numeric ASCII character is required.</p> <p>The key to this is the <code>\d*</code> at the front. Without it the regex gets much more awkward to do.</p>
35,733,647
Mongoose instance .save() not working
<p>I have a problem with Mongoose and MongoDb</p> <p>It is very interesting that only <code>Model.update</code> works and <code>save</code> never works and does not even fire callback.</p> <p>Mongoose: 4.4.5 MongoDB: 3.0.8</p> <p><strong>Express Route</strong></p> <pre><code>var mongoose = require('mongoose'); mongoose.connect("mongodb://127.0.0.1:27017/db"); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function(callback) { console.log("connection to db open") }); var User = require("../models/user.js"); </code></pre> <p><strong>User Model</strong></p> <pre><code>var user = new Schema({ uid: { type: Number, required: true, unique: true}, hwid: { type: String, default:""}, bol:{type:String,default:""} }); </code></pre> <p><strong>Update Enpoint</strong></p> <blockquote> <p>Working version: <strong>Model.update()</strong></p> </blockquote> <pre><code>User.update({_id: id}, { uid: 5, }, function(err, numberAffected, rawResponse) { console.log(err); }) </code></pre> <blockquote> <p>Not working version and I have to solve this: <strong>Object.save()</strong></p> </blockquote> <pre><code>User.find({_id:id}, function(err,user){ if(err){ console.log(err); } if(!user){ console.log("No user"); }else{ user.uid = 5; user.save(function(err,news){ console.log("Tried to save..."); }); } console.log("At least worked"); }) </code></pre> <p>Even callback is not firing. Connection successfully opens. It never invokes callback. </p> <hr> <ol> <li>Tried to use <code>var User = connection.model('User', schema)</code> didn't work.</li> </ol>
35,734,665
7
5
null
2016-03-01 21:14:34.477 UTC
8
2020-06-22 05:31:59.98 UTC
2016-03-01 21:47:00.197 UTC
null
836,048
null
836,048
null
1
33
node.js|mongodb|mongoose
47,136
<p>I am not going to delete this question because people may encounter this problem too. Actually problem was not related with MongoDb or Mongoose. When you call <code>Object.save()</code> responsibility chain is like below:</p> <blockquote> <ol> <li>Schema.pre("save")</li> <li>Save data to dabe</li> <li>Schema.post("save")</li> </ol> </blockquote> <p>So if you block <code>pre("save")</code> and don't call <code>next()</code> handler you won't be able to save your document. This was my case, I forgot the <code>next()</code> call inside an if statement and tried to find the error for more than 3 hours.</p> <pre><code>user.pre("save", function(next) { if(!this.trial){ //do your job here next(); } } </code></pre> <p>When <code>this.trial == true</code>, next handler won't be reachable. </p> <p>To prevent errors like this we should take care of branch coverage, reporters can show us untested codes. Your problem might be related with this too. <strong>Be sure you are calling <code>next()</code> if your document should be saved.</strong></p> <p><strong>Fixed Version</strong></p> <pre><code>user.pre("save", function(next) { if(!this.trial){ //do your job here } next(); } </code></pre>
18,057,090
Can I declare / use some variable in LINQ? Or can I write following LINQ clearer?
<p>Can I declare / use some variable in <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a>?</p> <p>For example, can I write following LINQ clearer?</p> <pre><code>var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance) where (t.ComponentType.GetProperty(t.Name) != null) select t.ComponentType.GetProperty(t.Name); </code></pre> <p>Are there ways to not write / call <code>t.ComponentType.GetProperty(t.Name)</code> two times here?</p>
18,057,121
4
0
null
2013-08-05 11:32:14.323 UTC
6
2013-08-16 11:45:19.747 UTC
2013-08-07 22:22:34.76 UTC
null
63,550
null
238,232
null
1
52
c#|linq
8,971
<pre><code>var q = from PropertyDescriptor t in TypeDescriptor.GetProperties(instance) let u = t.ComponentType.GetProperty(t.Name) where (u != null) select u; </code></pre>
33,199,193
How to fill dataframe Nan values with empty list [] in pandas?
<p>This is my dataframe: </p> <pre><code> date ids 0 2011-04-23 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 1 2011-04-24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 2 2011-04-25 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 3 2011-04-26 Nan 4 2011-04-27 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... 5 2011-04-28 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,... </code></pre> <p>I want to replace <code>Nan</code> with []. How to do that? Fillna([]) did not work. I even tried <code>replace(np.nan, [])</code> but it gives error: </p> <pre><code> TypeError('Invalid "to_replace" type: \'float\'',) </code></pre>
33,200,667
13
4
null
2015-10-18 14:35:45.66 UTC
17
2022-09-16 12:12:09.383 UTC
null
null
null
null
1,061,008
null
1
68
python|pandas|nan
53,328
<p>You can first use <code>loc</code> to locate all rows that have a <code>nan</code> in the <code>ids</code> column, and then loop through these rows using <code>at</code> to set their values to an empty list:</p> <pre><code>for row in df.loc[df.ids.isnull(), 'ids'].index: df.at[row, 'ids'] = [] &gt;&gt;&gt; df date ids 0 2011-04-23 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 1 2011-04-24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 2 2011-04-25 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 3 2011-04-26 [] 4 2011-04-27 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 5 2011-04-28 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] </code></pre>
2,273,474
KornShell - Set "-x" (debug) flag globally?
<p>Is there a way to set the debug mode (<a href="http://www2.research.att.com/sw/download/man/man1/ksh.html" rel="nofollow noreferrer"><code>set -x</code></a>) on a KornShell (ksh) script globally? Currently it seems I have do something like the following:</p> <pre><code>a(){ set -x #commands } b(){ set -x #more commands } set-x a #commands b </code></pre> <p>I would really like to only have to call the <code>set -x</code> command in one place.</p> <p><strong>Note:</strong> This is all in KSH88 on AIX.</p> <p>Example:</p> <pre><code>#!/bin/ksh set -x a(){ echo &quot;This is A!&quot; } b(){ echo &quot;This is B!&quot; } a echo &quot;Outside&quot; b </code></pre> <pre><code>dev2:/home/me-&gt; ./testSetX + a This is A! + echo Outside Outside + b This is B! dev2:/home/me-&gt; </code></pre>
2,274,727
5
2
null
2010-02-16 14:16:20.3 UTC
3
2021-08-14 01:04:13.487 UTC
2021-08-14 01:04:13.487 UTC
null
995,714
null
16,487
null
1
8
shell|debugging|scripting|ksh|script-debugging
73,004
<p>This is ksh88 on an HP-UX machine:</p> <pre><code>me@host ..dev/ $ cat ./test/verbose #!/bin/ksh set -x hello() { print $1 } hello kapow! exit [email protected]/ $ ./test/verbose + hello kapow! + print kapow! kapow! + exit </code></pre> <p>It sure <em>looks</em> like that works fine. I validated that it also works with a "set -x" anywhere before the first function call.</p> <p>I moved to an AIX system, and experienced the problem you described. When functions are defined as either <code>function a {</code> or <code>a() {</code> in AIX ksh88, the <code>set -x</code> doesn't appear to carry forward into the function-local scope. Switching to ksh93 on the same AIX box, functions declared using the new <code>function a {</code> syntax also don't carry the outer <code>set -x</code> into the inner scope. However, ksh93 behaves like POSIX sh (and ksh88 on other platforms) used to behave, carrying the <code>set -x</code> through to the function when the function is defined in the old <code>a(){</code> method. This is probably due to the backwards compatability in ksh93, where it tries to emulate the old behavior when functions are defined the old way.</p> <p>Therefore, you might be able to temporarily switch the interpreter over to ksh93 for debugging purposes, and then switch back to ksh88 if you don't like having the longer arrays, associative arrays, floating point math, namespace support, and rougly 10x improvement in execution speed which ksh93 brings. ;) Because it looks like the answer is "no, you can't do that" with ksh88 on AIX. :(</p>
1,814,517
Get ServletContext in JAX-RS resource
<p>I'm playing around with JAX-RS, deploying on Tomcat. It's basically:</p> <pre><code>@Path("/hello") @Produces({"text/plain"}) public class Hellohandler { @GET public String hello() { return "Hello World"; } } </code></pre> <p>Is there any way I can get hold of the <code>ServletContext</code> within my JAX-RS resource?</p>
1,814,788
5
0
null
2009-11-29 03:09:48.243 UTC
14
2016-05-30 08:03:15.82 UTC
2016-05-30 08:03:15.82 UTC
null
157,882
null
157,404
null
1
67
tomcat|servlets|jakarta-ee|jax-rs|application-variables
56,453
<p>Furthermore, <code>@Resource</code> annotation might not work. Try this </p> <pre><code>@javax.ws.rs.core.Context ServletContext context; </code></pre> <p>The injection doesn't happen until you hit the service method</p> <pre><code>public class MyService { @Context ServletContext context; public MyService() { print("Constructor " + context); // null here } @GET @Path("/thing") { print("in wizard service " + context); // available here </code></pre>
2,152,848
Compile time polymorphism vs. run time polymorphism
<p>Why is overloading called compile time polymorphism and Overriding run time polymorphism in C#?</p>
2,153,116
9
0
null
2010-01-28 07:06:01.963 UTC
33
2022-08-28 09:07:15.2 UTC
2012-12-24 20:36:08.233 UTC
null
1,845,869
null
260,727
null
1
40
c#|oop
50,953
<p>Overridden functions are functions that have the same signature, but are implemented in different derived classes. At compile time, usually the base class type is used to reference an object, though at run time this object could be of a derived type, so when an overridden method is called, the implementation that is called is dependent on what kind of object is doing the calling (base vs. a derived type) which is unknown at compile time. </p> <p>Overloading (not really polymorphism) is simply multiple functions which have the same name but different signatures (think multiple constructors for an object taking different numbers of arguments). Which method is called is known at compile time, because the arguments are specified at this time. </p>
2,055,784
What is the best approach to change primary keys in an existing Django app?
<p>I have an application which is in BETA mode. The model of this app has some classes with an explicit primary_key. As a consequence Django use the fields and doesn't create an id automatically.</p> <pre><code>class Something(models.Model): name = models.CharField(max_length=64, primary_key=True) </code></pre> <p>I think that it was a bad idea (see <a href="https://stackoverflow.com/questions/2011629/unicode-error-when-saving-an-object-in-django-admin">unicode error when saving an object in django admin</a>) and I would like to move back and have an id for every class of my model.</p> <pre><code>class Something(models.Model): name = models.CharField(max_length=64, db_index=True) </code></pre> <p>I've made the changes to my model (replace every primary_key=True by db_index=True) and I want to migrate the database with <a href="http://south.aeracode.org/wiki/Tutorial" rel="noreferrer">south</a>.</p> <p>Unfortunately, the migration fails with the following message: <code>ValueError: You cannot add a null=False column without a default value.</code></p> <p>I am evaluating the different workarounds for this problem. Any suggestions?</p> <p>Thanks for your help</p>
2,056,129
10
3
null
2010-01-13 10:00:16.813 UTC
17
2021-09-22 14:27:17.787 UTC
2017-05-23 12:10:32.943 UTC
null
-1
null
117,092
null
1
54
python|django|data-migration|django-south
66,786
<p>Agreed, your model is probably wrong.</p> <p>The formal primary key should always be a surrogate key. Never anything else. [Strong words. Been database designer since the 1980's. Important lessoned learned is this: everything is changeable, even when the users swear on their mothers' graves that the value cannot be changed is is truly a natural key that can be taken as primary. It isn't primary. Only surrogates can be primary.]</p> <p>You're doing open-heart surgery. Don't mess with schema migration. You're <em>replacing</em> the schema.</p> <ol> <li><p>Unload your data into JSON files. Use Django's own internal django-admin.py tools for this. You should create one unload file for each that will be changing and each table that depends on a key which is being created. Separate files make this slightly easier to do.</p></li> <li><p>Drop the tables which you are going to change from the old schema.</p> <p>Tables which depend on these tables will have their FK's changed; you can either update the rows in place or -- it might be simpler -- to delete and reinsert these rows, also.</p></li> <li><p>Create the new schema. This will only create the tables which are changing.</p></li> <li><p>Write scripts to read and reload the data with the new keys. These are short and very similar. Each script will use <code>json.load()</code> to read objects from the source file; you will then create your schema objects from the JSON tuple-line objects that were built for you. You can then insert them into the database.</p> <p>You have two cases.</p> <ul> <li><p>Tables with PK's change changed will be inserted and will get new PK's. These must be "cascaded" to other tables to assure that the other table's FK's get changed also.</p></li> <li><p>Tables with FK's that change will have to locate the row in the foreign table and update their FK reference.</p></li> </ul></li> </ol> <p>Alternative.</p> <ol> <li><p>Rename all your old tables.</p></li> <li><p>Create the entire new schema.</p></li> <li><p>Write SQL to migrate all the data from old schema to new schema. This will have to cleverly reassign keys as it goes.</p></li> <li><p>Drop the renamed old tables.</p></li> </ol> <p>&nbsp;</p>
1,406,808
Wait for file to be freed by process
<p>How do I wait for the file to be free so that <code>ss.Save()</code> can overwrite it with a new one? If I run this twice close together(ish), I get a <code>generic GDI+</code> error.</p> <pre><code>///&lt;summary&gt; /// Grabs a screen shot of the App and saves it to the C drive in jpg ///&lt;/summary&gt; private static String GetDesktopImage(DevExpress.XtraEditors.XtraForm whichForm) { Rectangle bounds = whichForm.Bounds; // This solves my problem but creates a clutter issue // var timeStamp = DateTime.Now.ToString("ddd-MMM-dd-yyyy-hh-mm-ss"); // var fileName = "C:\\HelpMe" + timeStamp + ".jpg"; var fileName = "C:\\HelpMe.jpg"; File.Create(fileName); using (Bitmap ss = new Bitmap(bounds.Width, bounds.Height)) using (Graphics g = Graphics.FromImage(ss)) { g.CopyFromScreen(whichForm.Location, Point.Empty, bounds.Size); ss.Save(fileName, ImageFormat.Jpeg); } return fileName; } </code></pre>
1,406,853
11
2
null
2009-09-10 18:02:22.137 UTC
16
2020-07-19 03:43:40.727 UTC
2020-03-03 09:35:22.043 UTC
null
850,848
null
46,724
null
1
42
c#|.net|winforms|file-io|ioexception
97,931
<p>A function like this will do it:</p> <pre><code>public static bool IsFileReady(string filename) { // If the file can be opened for exclusive access it means that the file // is no longer locked by another process. try { using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) return inputStream.Length &gt; 0; } catch (Exception) { return false; } } </code></pre> <p>Stick it in a <code>while</code> loop and you have something which will block until the file is accessible:</p> <pre><code>public static void WaitForFile(string filename) { //This will lock the execution until the file is ready //TODO: Add some logic to make it async and cancelable while (!IsFileReady(filename)) { } } </code></pre>
1,537,116
IllegalMonitorStateException on wait() call
<p>I am using multi-threading in java for my program. I have run thread successfully but when I am using <code>Thread.wait()</code>, it is throwing <code>java.lang.IllegalMonitorStateException</code>. How can I make a thread wait until it will be notified?</p>
1,537,133
12
1
null
2009-10-08 11:09:00.747 UTC
33
2022-08-09 03:38:53.07 UTC
2009-10-08 11:31:23.93 UTC
null
40,342
null
160,577
null
1
168
java|multithreading|wait
282,140
<p>You need to be in a <code>synchronized</code> block in order for <code>Object.wait()</code> to work.</p> <p>Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/Condition.html" rel="nofollow noreferrer">easier to work with</a>.</p> <p><strong>EDIT</strong></p> <p>I assumed you meant <code>Object.wait()</code> as your exception is what happens when you try to gain access without holding the objects lock.</p>
8,524,401
How can I place a table on a plot in Matplotlib?
<p>I'm not having any success in getting the matplotlib table commands to work. Here's an example of what I'd like to do:</p> <p>Can anyone help with the table construction code?</p> <pre><code>import pylab as plt plt.figure() ax=plt.gca() y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1] plt.plot([10,10,14,14,10],[2,4,4,2,2],'r') col_labels=['col1','col2','col3'] row_labels=['row1','row2','row3'] table_vals=[11,12,13,21,22,23,31,32,33] # the rectangle is where I want to place the table plt.text(11,4.1,'Table Title',size=8) plt.plot(y) plt.show() </code></pre>
8,531,491
2
2
null
2011-12-15 17:46:53.1 UTC
11
2017-03-17 19:50:58.097 UTC
2017-03-17 19:50:58.097 UTC
null
4,370,109
null
1,032,355
null
1
26
python|matplotlib
46,409
<p>AFAIK, you can't <em>arbitrarily</em> place a table on the <code>matplotlib</code> plot using only native <code>matplotlib</code> features. What you can do is take advantage of the possibility of <a href="http://matplotlib.sourceforge.net/users/usetex.html"><code>latex</code> text rendering</a>. However, in order to do this you should have working <code>latex</code> environment in your system. If you have one, you should be able to produce graphs such as below:</p> <pre><code>import pylab as plt import matplotlib as mpl mpl.rc('text', usetex=True) plt.figure() ax=plt.gca() y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1] #plt.plot([10,10,14,14,10],[2,4,4,2,2],'r') col_labels=['col1','col2','col3'] row_labels=['row1','row2','row3'] table_vals=[11,12,13,21,22,23,31,32,33] table = r'''\begin{tabular}{ c | c | c | c } &amp; col1 &amp; col2 &amp; col3 \\\hline row1 &amp; 11 &amp; 12 &amp; 13 \\\hline row2 &amp; 21 &amp; 22 &amp; 23 \\\hline row3 &amp; 31 &amp; 32 &amp; 33 \end{tabular}''' plt.text(9,3.4,table,size=12) plt.plot(y) plt.show() </code></pre> <p>The result is:</p> <p><img src="https://i.stack.imgur.com/QZ4Hx.png" alt="enter image description here"></p> <p>Please take in mind that this is quick'n'dirty example; you should be able to place the table correctly by playing with text coordinates. Please also refer to the <a href="http://matplotlib.sourceforge.net/users/usetex.html">docs</a> if you need to change fonts etc.</p> <p><strong>UPDATE: more on <code>pyplot.table</code></strong></p> <p>According to the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.table">documentation</a>, <code>plt.table</code> adds a table to current axes. From sources it's obvious, that table location on the graph is determined in relation to axes. <code>Y</code> coordinate can be controlled with keywords <code>top</code> (above graph), <code>upper</code> (in the upper half), <code>center</code> (in the center), <code>lower</code> (in the lower half) and <code>bottom</code> (below graph). <code>X</code> coordinate is controlled with keywords <code>left</code> and <code>right</code>. Any combination of the two works, e.g. any of <code>top left</code>, <code>center right</code> and <code>bottom</code> is OK to use. </p> <p>So the closest graph to what you want could be made with: </p> <pre><code>import matplotlib.pylab as plt plt.figure() ax=plt.gca() y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1] #plt.plot([10,10,14,14,10],[2,4,4,2,2],'r') col_labels=['col1','col2','col3'] row_labels=['row1','row2','row3'] table_vals=[[11,12,13],[21,22,23],[31,32,33]] # the rectangle is where I want to place the table the_table = plt.table(cellText=table_vals, colWidths = [0.1]*3, rowLabels=row_labels, colLabels=col_labels, loc='center right') plt.text(12,3.4,'Table Title',size=8) plt.plot(y) plt.show() </code></pre> <p>And this gives you</p> <p><img src="https://i.stack.imgur.com/FSoqz.png" alt="enter image description here"></p> <p>Hope this helps!</p>
17,795,053
If else statements in .html.erb in views
<p>In rails, I often run into the situation where inside the views I'll do something like</p> <pre><code>&lt;% if @some_condition_previusly_established_in_a_controller %&gt; &lt;div class="one"&gt;123&lt;/div&gt; &lt;% else %&gt; &lt;div class="two"&gt;something else&lt;/div&gt; &lt;% end %&gt; </code></pre> <p>It looks a bit cluttery. Is this an acceptable way of working with views or not?</p>
17,795,098
6
1
null
2013-07-22 18:44:54.343 UTC
6
2017-10-26 15:59:42.037 UTC
null
null
null
null
705,725
null
1
52
ruby-on-rails|ruby|model-view-controller
107,948
<p>Unless you can think of a way to re-write this as a helper method, you're basically stuck with it looking kind of ugly. That's just how ERB is, as it was intended to be a minimal way of injecting Ruby into an otherwise plain-text template, not as something necessarily streamlined or elegant.</p> <p>The good news is a syntax-highlighting editor will usually make your <code>&lt;% ... %&gt;</code> ERB blocks look visually different from your HTML so that can dramatically improve readability.</p> <p>It's also why other representations like <a href="http://haml.info" rel="noreferrer">HAML</a> have been created where that syntax is a lot less cluttered:</p> <pre><code>- if some_condition_previusly_established_in_a_controller .one 123 - else .two something else </code></pre>
17,764,680
Check if a character is a vowel or consonant?
<p>Is there a code to check if a character is a vowel or consonant? Some thing like char = IsVowel? Or need to hard code?</p> <pre><code>case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: case ‘A’: case ‘E’: case ‘I’: case ‘O’: case ‘U’: </code></pre>
17,764,745
13
2
null
2013-07-20 17:19:38.037 UTC
5
2018-04-19 17:35:56.813 UTC
null
null
null
null
2,493,889
null
1
18
c#|character
51,988
<p>You could do this:</p> <pre><code>char c = ... bool isVowel = "aeiouAEIOU".IndexOf(c) &gt;= 0; </code></pre> <p>or this:</p> <pre><code>char c = ... bool isVowel = "aeiou".IndexOf(c.ToString(), StringComparison.InvariantCultureIgnoreCase) &gt;= 0; </code></pre> <p>Once you add international support for things like <code>éèe̋ȅëêĕe̊æøи</code> etc. this string will get long, but the basic solution is the same.</p>
6,755,361
How to execute VBA Access module?
<p>Ok I'm using Access 2003 and I've just started learning Access and VBA a few days ago.<br> I wrote some code in a module and there are no errors when I press the play button on the debugger toolbar up top. <br> How do I actually execute this code on my database so that it will do something.<br> In other words how do I make use of the module?</p> <p>Please help me out I'm struggling hard and the deadline for this is thursday!</p> <p>Thanks!</p>
6,755,402
3
0
null
2011-07-19 23:32:00.437 UTC
null
2013-09-20 14:14:32.12 UTC
2011-07-20 01:11:48.377 UTC
null
93,528
null
679,114
null
1
8
ms-access|vba
106,578
<p>Well it depends on how you want to call this code. </p> <p>Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.</p> <p>Similar to this:</p> <pre><code>Private Sub Command1426_Click() mdl_ExportMorning.ExportMorning End Sub </code></pre> <p>This button click event calls the <code>Module mdl_ExportMorning</code> and the <code>Public Sub ExportMorning</code>.</p>
719,705
What is the purpose of python's inner classes?
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
719,718
9
0
2009-04-05 21:13:28 UTC
2009-04-05 21:13:28.017 UTC
42
2020-07-22 13:07:19.48 UTC
2016-08-10 21:47:59.067 UTC
null
197,283
Geo
31,610
null
1
116
python|class|oop|language-features
67,785
<p>Quoted from <a href="http://www.geekinterview.com/question_details/64739" rel="noreferrer">http://www.geekinterview.com/question_details/64739</a>:</p> <blockquote> <h3>Advantages of inner class:</h3> <ul> <li><strong>Logical grouping of classes</strong>: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.</li> <li><strong>Increased encapsulation</strong>: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world.</li> <li><strong>More readable, maintainable code</strong>: Nesting small classes within top-level classes places the code closer to where it is used.</li> </ul> </blockquote> <p>The main advantage is organization. Anything that can be accomplished with inner classes <strong>can</strong> be accomplished without them.</p>
814,548
How to replace a string in a SQL Server Table Column
<p>I have a table (<code>SQL Sever</code>) which references paths (<code>UNC</code> or otherwise), but now the path is going to change. </p> <p>In the path column, I have many records and I need to change just a portion of the path, but not the entire path. And I need to change the same string to the new one, in every record.</p> <p>How can I do this with a simple <code>update</code>?</p>
814,551
10
0
null
2009-05-02 09:43:52.523 UTC
58
2019-05-10 13:30:54.17 UTC
2018-03-27 11:08:51.9 UTC
null
3,876,565
null
98,655
null
1
389
sql|sql-server|database|database-administration
854,992
<p>It's this easy:</p> <pre><code>update my_table set path = replace(path, 'oldstring', 'newstring') </code></pre>
582,596
Base class includes the field 'X', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager)
<p>The full error is</p> <blockquote> <p>The base class includes the field 'ScriptManager1', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager).</p> </blockquote> <p>Anyone else come across this error?</p>
1,230,607
12
1
null
2009-02-24 17:06:55.25 UTC
2
2018-10-10 16:41:52.253 UTC
2017-10-31 18:11:32.637 UTC
null
6,332,918
Collin Estes
20,748
null
1
24
asp.net|asp.net-ajax
45,694
<p>I managed to fix it by adding this to web.config:</p> <pre><code>&lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/&gt; &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; </code></pre> <p>I believe it forces the .net runtime to use the new versions of those assemblies.</p>
707,615
Simple way of turning off observers during rake task?
<p>I'm using restful_authentication in my app. I'm creating a set of default users using a rake task, but every time I run the task an activation email is sent out because of the observer associated with my user model. I'm setting the activation fields when I create the users, so no activation is necessary. </p> <p>Anyone know of an easy way to bypass observers while running a rake task so that no emails get sent out when I save the user?</p> <p>Thanks.</p>
711,602
12
0
null
2009-04-01 22:36:39.433 UTC
12
2015-08-11 06:46:58.617 UTC
null
null
null
Brad
84,497
null
1
40
ruby-on-rails|ruby|observer-pattern|restful-authentication
11,839
<p>You could add an accessor to your user model, something like "skip_activation" that wouldn't need to be saved, but would persist through the session, and then check the flag in the observer. Something like</p> <pre><code>class User attr_accessor :skip_activation #whatever end </code></pre> <p>Then, in the observer:</p> <pre><code>def after_save(user) return if user.skip_activation #rest of stuff to send email end </code></pre>
1,008,246
How to create a UITableViewCell with a transparent background
<p>I'm trying to set the background color of a <code>UITableViewCell</code> to transparent. But nothing seems to work. I have some images/buttons inside the <code>tableViewCell</code> and I would like to make the white <code>grouptableview</code> background disappear to get a 'floating' effect for the images and buttons (as if they were not inside the <code>tableview</code>).</p> <p>Any idea how this could be accomplished?</p>
1,010,140
13
0
null
2009-06-17 16:43:55.903 UTC
34
2022-04-23 08:49:11.88 UTC
2015-07-03 11:02:00.633 UTC
null
2,630,337
null
102,211
null
1
75
iphone|cocoa-touch|uitableview
74,523
<p>If both the other options didn't work try this</p> <pre><code>UIView *backView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease]; backView.backgroundColor = [UIColor clearColor]; cell.backgroundView = backView; </code></pre>
557,827
What's the need for XHTML?
<p>In an interview I was asked a question that I'd never thought about, which was "We already have HTML which fulfills all the requirements of writing a web page, so what's the need for XHTML?"</p> <p>I Googled a lot and also read many articles, but I'm not able to get properly why XHTML has been introduced. Please explain to me.</p>
557,931
16
0
null
2009-02-17 17:22:11.463 UTC
8
2013-04-11 16:37:34.503 UTC
2009-10-13 13:10:16.41 UTC
null
1,450
Prashant
45,261
null
1
34
html|css|xhtml
3,601
<p>I am actually writing this to ask why the above three posts which speak about <strong>browser-consistence</strong> and <strong>well formed</strong> html have been voted down?</p> <p>As it is known HTML is a industry standard. Browsers are implemented so that they render the marked up content as described in the HTML standard. Unfortunately there are areas that have not been well defined in HTML: what happens if user forgot a closing tag or what to do if a referred image is not found? some browsers use the 'alt' tag to have a place holder text item and some browsers display the 'alt' tag as a tool tip. The famous 'quirks' mode of browsers is a result of this lack of clarity. Because of this, it became quite possible that the same web page would display differently on different browsers. </p> <p>Also as HTML usage grew there was one more problem: it was not extensible - there was no way to add user-defined tags. </p> <p><strong>XHTML solves the above problems</strong>:</p> <ul> <li>adopt XML to provide extensible tags. </li> <li>provide a 'strict' standard for web browsers</li> </ul> <p>XHTML has well defined rules about the structure and these can be programatically enforced. Check the various online "XHTML Validators". They will tell if your XHTML is well formed or not (and highlight the problem areas). Because of these strict rules your page is more or less guaranteed to look the same on all browsers implementing XHTML. </p> <p>[<strong>note</strong>] if you want to verify the above, please refer to the text "Head First XHTML and CSS"</p>
534,575
How do I invert BooleanToVisibilityConverter?
<p>I'm using a <code>BooleanToVisibilityConverter</code> in WPF to bind the <code>Visibility</code> property of a control to a <code>Boolean</code>. This works fine, but I'd like one of the controls to hide if the boolean is <code>true</code>, and show if it's <code>false</code>.</p>
534,591
17
4
null
2009-02-10 22:41:50.033 UTC
35
2022-01-06 14:56:57.147 UTC
2015-10-28 15:16:55.007 UTC
null
11,635
Andy
null
null
1
164
.net|wpf|binding|visibility
113,992
<p>Implement your own implementation of IValueConverter. A sample implementation is at </p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx</a></p> <p>In your Convert method, have it return the values you'd like instead of the defaults.</p>
133,965
Find CRLF in Notepad++
<p>How can I find/replace all CR/LF characters in Notepad++?</p> <p>I am looking for something equivalent to the ^p special character in Microsoft Word.</p>
133,989
18
6
null
2008-09-25 15:24:27.157 UTC
78
2019-10-10 07:45:13.053 UTC
2018-06-11 07:59:15.063 UTC
null
63,550
polara
8,754
null
1
335
regex|notepad++
612,690
<p><strong><code>[\r\n]+</code></strong> should work too</p> <p>Update March, 26th 2012, release date of <strong><a href="http://notepad-plus-plus.org/news/notepad-6.0-release.html" rel="noreferrer">Notepad++ 6.0</a></strong>:</p> <p>OMG, it actually does work now!!!</p> <p><img src="https://i.stack.imgur.com/ZiyXX.png" alt="PCRE regexp in Notepad++"></p> <hr> <p>Original answer 2008 (Notepad++ 4.x) - 2009-2010-2011 (Notepad++ 5.x)</p> <p>Actually no, it does not seem to work with regexp...</p> <p>But if you have Notepad++ 5.x, you can use the '<strong>extended</strong>' search mode and look for <code>\r\n</code>. That does find all your <code>CRLF</code>.</p> <p>(I realize this is the same answer than the others, but again, 'extended mode' is only available with Notepad++ 4.9, 5.x and more)</p> <hr> <p>Since April 2009, you have a wiki article on the Notepad++ site on this topic:<br> "<strong><a href="http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Replacing_Newlines" rel="noreferrer">How To Replace Line Ends, thus changing the line layout</a></strong>".<br> (mentioned by <a href="https://stackoverflow.com/users/467509/georgiecasey">georgiecasey</a> in his/her <a href="https://stackoverflow.com/questions/133965/find-crlf-in-notepad/4608574#4608574">answer below</a>)</p> <p>Some relevant extracts includes the following search processes:</p> <blockquote> <h3>Simple search (<kbd>Ctrl</kbd>+<kbd>F</kbd>), Search Mode = <code>Normal</code></h3> <p>You can select an <code>EOL</code> in the editing window. </p> <ul> <li>Just move the cursor to the end of the line, and type <kbd>Shift</kbd>+<kbd>Right</kbd> Arrow. </li> <li>or, to select <code>EOL</code> with the mouse, start just at the line end and drag to the start of the next line; dragging to the right of the <code>EOL</code> won't work. You can manually copy the <code>EOL</code> and paste it into the field for Unix files (<code>LF</code>-only).</li> </ul> <h3>Simple search (Ctrl+F), Search Mode = Extended</h3> <p>The "Extended" option shows <code>\n</code> and <code>\r</code> as characters that could be matched.<br> As with the Normal search mode, Notepad++ is looking for the exact character.<br> Searching for <code>\r</code> in a UNIX-format file will not find anything, but searching for <code>\n</code> will. Similarly, a Macintosh-format file will contain <code>\r</code> but not <code>\n</code>.</p> <h3>Simple search (Ctrl+F), Search Mode = Regular expression</h3> <p>Regular expressions use the characters <code>^</code> and <code>$</code> to anchor the match string to the beginning or end of the line. For instance, searching for <code>return;$</code> will find occurrences of "return;" that occur with no subsequent text on that same line. The anchor characters work identically in all file formats.<br> The '.' dot metacharacter does not match line endings.</p> <p>[Tested in Notepad++ 5.8.5]: <strong>a regular expression search with an explicit <code>\r</code> or <code>\n</code> does not work (contrary to the <a href="http://www.scintilla.org/ScintillaDoc.html" rel="noreferrer">Scintilla documentation</a>)</strong>.<br> Neither does a search on an explicit (pasted) LF, or on the (invisible) EOL characters placed in the field when an EOL is selected. Advanced search (<kbd>Ctrl</kbd>+<kbd>R</kbd>) without regexp</p> <p><kbd>Ctrl</kbd>+<kbd>M</kbd> will insert something that matches newlines. They will be replaced by the replace string.<br> I recommend this method as the most reliable, unless you really need to use regex.<br> As an example, to remove every second newline in a double spaced file, enter <kbd>Ctrl</kbd>+<kbd>M</kbd> twice in the search string box, and once in the replace string box.</p> <h3>Advanced search (<kbd>Ctrl</kbd>+<kbd>R</kbd>) with Regexp.</h3> <p>Neither <kbd>Ctrl</kbd>+<kbd>M</kbd>, <code>$</code> nor <code>\r\n</code> are matched. </p> </blockquote> <hr> <p>The same wiki also mentions the <strong>Hex editor alternative</strong>:</p> <blockquote> <ul> <li>Type the new string at the beginning of the document. </li> <li>Then select to <strong>view the document in Hex mode</strong>. </li> <li>Select one of the new lines and hit <kbd>Ctrl</kbd>+<kbd>H</kbd>. </li> <li>While you have the Replace dialog box up, select on the background the new replacement string and <kbd>Ctrl</kbd>+<kbd>C</kbd> copy it to paste it in the Replace with text input. </li> <li>Then Replace or Replace All as you wish. </li> </ul> <p>Note: the character selected for new line usually appears as <strong><code>0a</code></strong>.<br> It may have a different value if the file is in Windows Format. In that case you can always go to <code>Edit -&gt; EOL Conversion -&gt; Convert to Unix Format</code>, and after the replacement switch it back and <code>Edit -&gt; EOL Conversion -&gt; Convert to Windows Format</code>.</p> </blockquote>
804,045
Preferred method to store PHP arrays (json_encode vs serialize)
<p>I need to store a multi-dimensional associative array of data in a flat file for caching purposes. I might occasionally come across the need to convert it to JSON for use in my web app but the vast majority of the time I will be using the array directly in PHP.</p> <p>Would it be more efficient to store the array as JSON or as a PHP serialized array in this text file? I've looked around and it seems that in the newest versions of PHP (5.3), <code>json_decode</code> is actually faster than <code>unserialize</code>.</p> <p>I'm currently leaning towards storing the array as JSON as I feel its easier to read by a human if necessary, it can be used in both PHP and JavaScript with very little effort, and from what I've read, it might even be faster to decode (not sure about encoding, though).</p> <p>Does anyone know of any pitfalls? Anyone have good benchmarks to show the performance benefits of either method?</p>
804,089
20
1
null
2009-04-29 20:09:43.56 UTC
218
2020-07-24 22:49:47.78 UTC
2015-03-06 22:58:23.753 UTC
null
3,614,835
null
83,304
null
1
649
php|performance|arrays|json|serialization
221,317
<p>Depends on your priorities.</p> <p>If performance is your absolute driving characteristic, then by all means use the fastest one. Just make sure you have a full understanding of the differences before you make a choice</p> <ul> <li>Unlike <code>serialize()</code> you need to add extra parameter to keep UTF-8 characters untouched: <code>json_encode($array, JSON_UNESCAPED_UNICODE)</code> (otherwise it converts UTF-8 characters to Unicode escape sequences).</li> <li>JSON will have no memory of what the object's original class was (they are always restored as instances of stdClass).</li> <li>You can't leverage <code>__sleep()</code> and <code>__wakeup()</code> with JSON</li> <li>By default, only public properties are serialized with JSON. (in <code>PHP&gt;=5.4</code> you can implement <a href="http://php.net/manual/en/class.jsonserializable.php" rel="noreferrer">JsonSerializable</a> to change this behavior).</li> <li>JSON is more portable</li> </ul> <p>And there's probably a few other differences I can't think of at the moment.</p> <p>A simple speed test to compare the two</p> <pre><code>&lt;?php ini_set('display_errors', 1); error_reporting(E_ALL); // Make a big, honkin test array // You may need to adjust this depth to avoid memory limit errors $testArray = fillArray(0, 5); // Time json encoding $start = microtime(true); json_encode($testArray); $jsonTime = microtime(true) - $start; echo "JSON encoded in $jsonTime seconds\n"; // Time serialization $start = microtime(true); serialize($testArray); $serializeTime = microtime(true) - $start; echo "PHP serialized in $serializeTime seconds\n"; // Compare them if ($jsonTime &lt; $serializeTime) { printf("json_encode() was roughly %01.2f%% faster than serialize()\n", ($serializeTime / $jsonTime - 1) * 100); } else if ($serializeTime &lt; $jsonTime ) { printf("serialize() was roughly %01.2f%% faster than json_encode()\n", ($jsonTime / $serializeTime - 1) * 100); } else { echo "Impossible!\n"; } function fillArray( $depth, $max ) { static $seed; if (is_null($seed)) { $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10); } if ($depth &lt; $max) { $node = array(); foreach ($seed as $key) { $node[$key] = fillArray($depth + 1, $max); } return $node; } return 'empty'; } </code></pre>
327,082
EXC_BAD_ACCESS signal received
<p>When deploying the application to the device, the program will quit after a few cycles with the following error:</p> <pre><code>Program received signal: "EXC_BAD_ACCESS". </code></pre> <p>The program runs without any issue on the iPhone simulator, it will also debug and run as long as I step through the instructions one at a time. As soon as I let it run again, I will hit the <code>EXC_BAD_ACCESS</code> signal.</p> <p>In this particular case, it happened to be an error in the accelerometer code. It would not execute within the simulator, which is why it did not throw any errors. However, it would execute once deployed to the device.</p> <p>Most of the answers to this question deal with the general <code>EXC_BAD_ACCESS</code> error, so I will leave this open as a catch-all for the dreaded Bad Access error.</p> <p><code>EXC_BAD_ACCESS</code> is typically thrown as the result of an illegal memory access. You can find more information in the answers below.</p> <p>Have you encountered the <code>EXC_BAD_ACCESS</code> signal before, and how did you deal with it?</p>
328,164
36
0
null
2008-11-29 02:50:26.887 UTC
107
2022-05-27 21:21:02.77 UTC
2016-12-22 19:14:05.337 UTC
Ned Batchelder
1,104,384
Hector Ramos
19,617
null
1
297
ios|cocoa-touch
275,930
<p>From your description I suspect the most likely explanation is that you have some error in your memory management. You said you've been working on iPhone development for a few weeks, but not whether you are experienced with Objective C in general. If you've come from another background it can take a little while before you really internalise the memory management rules - unless you make a big point of it.</p> <p>Remember, anything you get from an allocation function (usually the static alloc method, but there are a few others), or a copy method, you own the memory too and must release it when you are done.</p> <p>But if you get something back from just about anything else <em>including</em> factory methods (e.g. <code>[NSString stringWithFormat]</code>) then you'll have an autorelease reference, which means it could be released at some time in the future by other code - so it is vital that if you need to keep it around beyond the immediate function that you retain it. If you don't, the memory may remain allocated while you are using it, or be released but coincidentally still valid, during your emulator testing, but is more likely to be released and show up as bad access errors when running on the device.</p> <p>The best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option.</p>
6,416,017
Json.NET: Deserializing nested dictionaries
<p>When deserializing an object to a <code>Dictionary</code> (<code>JsonConvert.DeserializeObject&lt;IDictionary&lt;string,object&gt;&gt;(json)</code>) nested objects are deserialized to <code>JObject</code>s. Is it possible to force nested objects to be deserialized to <code>Dictionary</code>s?</p>
6,417,753
6
2
null
2011-06-20 18:58:25.57 UTC
14
2022-05-21 06:48:50.437 UTC
2011-06-20 19:11:23.553 UTC
null
162,396
null
162,396
null
1
45
c#|json|serialization|json.net|deserialization
31,259
<p>I found a way to convert all nested objects to <code>Dictionary&lt;string,object&gt;</code> by providing a <code>CustomCreationConverter</code> implementation:</p> <pre><code>class MyConverter : CustomCreationConverter&lt;IDictionary&lt;string, object&gt;&gt; { public override IDictionary&lt;string, object&gt; Create(Type objectType) { return new Dictionary&lt;string, object&gt;(); } public override bool CanConvert(Type objectType) { // in addition to handling IDictionary&lt;string, object&gt; // we want to handle the deserialization of dict value // which is of type object return objectType == typeof(object) || base.CanConvert(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null) return base.ReadJson(reader, objectType, existingValue, serializer); // if the next token is not an object // then fall back on standard deserializer (strings, numbers etc.) return serializer.Deserialize(reader); } } class Program { static void Main(string[] args) { var json = File.ReadAllText(@"c:\test.json"); var obj = JsonConvert.DeserializeObject&lt;IDictionary&lt;string, object&gt;&gt;( json, new JsonConverter[] {new MyConverter()}); } } </code></pre> <p>Documentation: <strong><a href="http://james.newtonking.com/projects/json/help/index.html?topic=html/CustomCreationConverter.htm" rel="noreferrer">CustomCreationConverter with Json.NET</a></strong></p>
6,566,318
Javascript inline output
<p>In javascript suppose you have this piece of code:</p> <pre><code>&lt;div&gt; &lt;script type="text/javascript"&gt;var output = 'abcdefg';&lt;/script&gt; &lt;/div&gt; </code></pre> <p>Is there any way to simply "echo" (using PHP terminology) the contents of <code>output</code> into <code>#test</code>? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?</p> <p><code>document.write("...");</code> does write the contents of <code>output</code>, but in doing so, it replaces the entire document with the <code>output</code>. </p> <p>The solution I'm looking for should act the same way a PHP <code>echo</code> would: write the output into the document inline.</p>
6,566,324
7
6
null
2011-07-04 00:07:39.043 UTC
1
2014-01-01 10:53:28.84 UTC
2013-11-24 03:08:41.077 UTC
null
445,131
null
257,878
null
1
14
javascript|echo
54,165
<p>"Kosher" code aside, yes.</p> <p><code>document.write()</code></p>
6,972,701
Remove text after clicking in the textbox
<p>When you activate an application, a textbox with text "hello" will appear.</p> <p>My question is:<br> When you click on the textbox in order to make input data, I want to remove the text automatically in XAML code, how do I do it?</p>
6,972,726
8
1
null
2011-08-07 12:13:36.097 UTC
7
2015-10-09 18:09:14.33 UTC
2015-07-20 06:04:36.973 UTC
null
591,656
null
484,390
null
1
16
c#|.net|wpf|xaml
68,927
<p>Handle the <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotfocus.aspx"><code>UIElement.GotFocus</code></a> event, and in the handler, clear the text. You'll also want to remove the handler, so that if you click on the <code>TextBox</code> a second time you don't lose what you've already entered.</p> <p>Something like this:</p> <p>XAML:</p> <pre><code>&lt;TextBox Text="Hello" GotFocus="TextBox_GotFocus" /&gt; </code></pre> <p>Code-behind:</p> <pre><code>public void TextBox_GotFocus(object sender, RoutedEventArgs e) { TextBox tb = (TextBox)sender; tb.Text = string.Empty; tb.GotFocus -= TextBox_GotFocus; } </code></pre>
6,548,837
How do I get an event callback when a Tkinter Entry widget is modified?
<p>Exactly as the question says. <code>Text</code> widgets have the <code>&lt;&lt;Modified&gt;&gt;</code> event, but <code>Entry</code> widgets don't appear to.</p>
6,549,535
9
0
null
2011-07-01 13:49:24.137 UTC
18
2022-04-03 12:55:59.917 UTC
null
null
null
null
417,803
null
1
80
python|tkinter
109,368
<p>Add a Tkinter StringVar to your Entry widget. Bind your callback to the StringVar using the trace method.</p> <pre><code>from Tkinter import * def callback(sv): print sv.get() root = Tk() sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: callback(sv)) e = Entry(root, textvariable=sv) e.pack() root.mainloop() </code></pre>
6,947,612
Generating m distinct random numbers in the range [0..n-1]
<p>I have two methods of generating m distinct random numbers in the range [0..n-1]</p> <p><strong>Method 1:</strong></p> <pre><code>//C++-ish pseudocode int result[m]; for(i = 0; i &lt; m; ++i) { int r; do { r = rand()%n; }while(r is found in result array at indices from 0 to i) result[i] = r; } </code></pre> <p><strong>Method 2:</strong></p> <pre><code>//C++-ish pseudocode int arr[n]; for(int i = 0; i &lt; n; ++i) arr[i] = i; random_shuffle(arr, arr+n); result = first m elements in arr; </code></pre> <p>The first method is more efficient when n is much larger than m, whereas the second is more efficient otherwise. But "much larger" isn't that strict a notion, is it? :) </p> <p><em><strong>Question:</em></strong> What formula of n and m should I use to determine whether method1 or method2 will be more efficient? (in terms of mathematical expectation of the running time)</p>
6,953,958
11
3
null
2011-08-04 19:42:31.933 UTC
14
2018-12-20 13:25:18.94 UTC
2011-08-04 19:51:03.583 UTC
null
246,263
null
469,935
null
1
33
c++|algorithm|random|performance
33,825
<p>Pure mathematics:<br/> Let's calculate the quantity of <code>rand()</code> function calls in both cases and compare the results:</p> <p><strong>Case 1:</strong> let's see the mathematical expectation of calls on step <code>i = k</code>, when you already have k numbers chosen. The probability to get a number with one <code>rand()</code> call is equal to <code>p = (n-k)/n</code>. We need to know the mathematical expectation of such calls quantity which leads to obtaining a number we don't have yet. </p> <p>The probability to get it using <code>1</code> call is <code>p</code>. Using <code>2</code> calls - <code>q * p</code>, where <code>q = 1 - p</code>. In general case, the probability to get it exactly after <code>n</code> calls is <code>(q^(n-1))*p</code>. Thus, the mathematical expectation is <br/> <code>Sum[ n * q^(n-1) * p ], n = 1 --&gt; INF</code>. This sum is equal to <code>1/p</code> (proved by wolfram alpha). </p> <p>So, on the step <code>i = k</code> you will perform <code>1/p = n/(n-k)</code> calls of the <code>rand()</code> function.</p> <p>Now let's sum it overall:</p> <p><code>Sum[ n/(n - k) ], k = 0 --&gt; m - 1 = n * T</code> - the number of <code>rand</code> calls in method 1. <br/> Here <code>T = Sum[ 1/(n - k) ], k = 0 --&gt; m - 1</code></p> <p><strong>Case 2:</strong></p> <p>Here <code>rand()</code> is called inside <code>random_shuffle</code> <code>n - 1</code> times (in most implementations).</p> <p>Now, to choose the method, we have to compare these two values: <code>n * T ? n - 1</code>.<br/> So, to choose the appropriate method, calculate <code>T</code> as described above. If <code>T &lt; (n - 1)/n</code> it's better to use the first method. Use the second method otherwise. </p>
6,784,894
Add commas or spaces to group every three digits
<p>I have a function to add commas to numbers:</p> <pre><code>function commafy( num ) { num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," ); } </code></pre> <p>Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?</p> <pre><code>commafy( "123" ) // "123" commafy( "1234" ) // "1234" // Don't add commas until 5 integer digits commafy( "12345" ) // "12,345" commafy( "1234567" ) // "1,234,567" commafy( "12345.2" ) // "12,345.2" commafy( "12345.6789" ) // "12,345.6789" // Again, nothing until 5 commafy( ".123456" ) // ".123 456" // Group with spaces (no leading digit) commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8" </code></pre> <p>Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?</p>
6,786,040
13
3
null
2011-07-22 01:52:11.403 UTC
20
2022-05-29 13:53:35.183 UTC
2011-07-22 21:24:57.147 UTC
null
49,485
null
49,485
null
1
52
javascript|string-formatting
81,133
<p>Just split into two parts with '.' and format them individually.</p> <pre><code>function commafy( num ) { var str = num.toString().split('.'); if (str[0].length &gt;= 5) { str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,'); } if (str[1] &amp;&amp; str[1].length &gt;= 5) { str[1] = str[1].replace(/(\d{3})/g, '$1 '); } return str.join('.'); } </code></pre>
45,322,118
Error: The given id must not be null for GeneratedValue in JPA
<p>My object:</p> <pre class="lang-java prettyprint-override"><code>@Entity @Table(name="user") public class User { @Id @Column(name="uid") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; //more code } </code></pre> <p>When I <code>POST</code> <code>user</code> <code>JSON</code> without <code>uid</code>, I am getting error as <em>the given id must not be null</em>. Which should not be the case while <code>uid</code> should be generated by the database. Please point what am I missing.</p> <p>JSON:</p> <pre class="lang-json prettyprint-override"><code>{ "email": "[email protected]", "name": "John Doe", "phone": "98-765-4445" } </code></pre> <p>Error:</p> <pre class="lang-json prettyprint-override"><code>{ "timestamp": 1501058952038, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.dao.InvalidDataAccessApiUsageException", "message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!", "path": "/api/user/" } </code></pre>
45,324,494
2
3
null
2017-07-26 08:57:55.153 UTC
3
2021-11-30 02:20:09.353 UTC
2017-07-26 09:03:01.85 UTC
null
1,327,585
null
1,327,585
null
1
5
java|rest|jpa|spring-boot|spring-rest
45,781
<p>It was my bad, I was calling <code>foo(user.getId())</code> before saving the <code>User</code> object into the database. Takeaways from this: <code>@GeneratedValue(strategy=GenerationType.IDENTITY)</code> is the correct code and generates identical ids while saving to database<sup>1</sup>. And <code>Long</code> is not a problem. Thanks.</p> <p>[1]: I am saving the object into the database by, something like: <code>userRepository.save(user)</code>.</p>
15,987,091
Imagemagick - Resize images to 25px height and aspect ratio
<p>OK, so I have a folder of like 16 images all between the dimensions of 205x150 to 103x148. I want to size them down to the pixel height and width of 25px and stack them horizontally on a transparent background... is that possible?</p> <p>I should probably be using ImageMagick for this...</p>
15,987,280
2
0
null
2013-04-13 11:04:11.183 UTC
11
2019-05-23 10:44:28.26 UTC
null
null
null
null
272,501
null
1
50
image|imagemagick|image-manipulation
32,193
<p>You can do all that with ImageMagick. </p> <p>You're question is not very specific, so here's a quick cheat sheet of command examples that may help you:</p> <pre><code># resize image to width 25, keeping aspect ratio convert -geometry 25x src/image1.png out/image1.png # resize image to height 25, keeping aspect ratio convert -geometry x25 src/image1.png out/image1.png # concatenate images horizontally convert +append src/image1.png src/image2.png out/image12horiz.png # concatenate images vertically convert -append src/image1.png src/image2.png out/image12vert.png </code></pre> <p>In addition, the <code>montage</code> command is probably perfect to create the final image you are looking for (on a transparent bg with some padding, etc), but I don't remember the syntax.</p> <p>Another useful command is <code>identify</code>, to find the dimensions of images (along with other details).</p> <p>After you install ImageMagick, you can see the list of commands in <code>man ImageMagick</code>, and get further details on each command in the man pages. There are an awful lot of functions, but it should not be too difficult to figure out the rest on Google. (I do that all the time.)</p>
35,821,184
Implement an interactive shell over ssh in Python using Paramiko?
<p>I want to write a program (in Python 3.x on Windows 7) that executes multiple commands on a remote shell via ssh. After looking at paramikos' <code>exec_command()</code> function, I realized it's not suitable for my use case (because the channel gets closed after the command is executed), as the commands depend on environment variables (set by prior commands) and can't be concatenated into one <code>exec_command()</code> call as they are to be executed at different times in the program.</p> <p>Thus, I want to execute commands in the same channel. The next option I looked into was implementing an interactive shell using paramikos' <code>invoke_shell()</code> function:</p> <pre><code>ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=psw, port=22) channel = ssh.invoke_shell() out = channel.recv(9999) channel.send('cd mivne_final\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) channel.send('cd ..\n') channel.send('cd or_fail\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) channel.send('cd ..\n') channel.send('cd simulator\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) ssh.close() </code></pre> <p>There are some problems with this code:</p> <ol> <li>The first <code>print</code> doesn't always print the <code>ls</code> output (sometimes it is only printed on the second <code>print</code>).</li> <li>The first <code>cd</code> and <code>ls</code> commands are always present in the output (I get them via the <code>recv</code> command, as part of the output), while all the following <code>cd</code> and <code>ls</code> commands are printed sometimes, and sometimes they aren't.</li> <li>The second and third <code>cd</code> and <code>ls</code> commands (when printed) always appear before the first <code>ls</code> output.</li> </ol> <p>I'm confused with this "non-determinism" and would very much appreciate your help.</p>
36,948,840
1
5
null
2016-03-05 23:26:30.047 UTC
12
2019-05-02 00:55:20.553 UTC
2019-05-02 00:55:20.553 UTC
null
1,971,003
null
6,023,729
null
1
22
python|shell|ssh|paramiko|interactive
66,262
<pre><code>import paramiko import re class ShellHandler: def __init__(self, host, user, psw): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(host, username=user, password=psw, port=22) channel = self.ssh.invoke_shell() self.stdin = channel.makefile('wb') self.stdout = channel.makefile('r') def __del__(self): self.ssh.close() def execute(self, cmd): """ :param cmd: the command to be executed on the remote computer :examples: execute('ls') execute('finger') execute('cd folder_name') """ cmd = cmd.strip('\n') self.stdin.write(cmd + '\n') finish = 'end of stdOUT buffer. finished with exit status' echo_cmd = 'echo {} $?'.format(finish) self.stdin.write(echo_cmd + '\n') shin = self.stdin self.stdin.flush() shout = [] sherr = [] exit_status = 0 for line in self.stdout: if str(line).startswith(cmd) or str(line).startswith(echo_cmd): # up for now filled with shell junk from stdin shout = [] elif str(line).startswith(finish): # our finish command ends with the exit status exit_status = int(str(line).rsplit(maxsplit=1)[1]) if exit_status: # stderr is combined with stdout. # thus, swap sherr with shout in a case of failure. sherr = shout shout = [] break else: # get rid of 'coloring and formatting' special characters shout.append(re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]').sub('', line). replace('\b', '').replace('\r', '')) # first and last lines of shout/sherr contain a prompt if shout and echo_cmd in shout[-1]: shout.pop() if shout and cmd in shout[0]: shout.pop(0) if sherr and echo_cmd in sherr[-1]: sherr.pop() if sherr and cmd in sherr[0]: sherr.pop(0) return shin, shout, sherr </code></pre>
56,847,571
Equivalent to UserSettings / ApplicationSettings in WPF .NET 5, .NET 6 or .Net Core
<p>What is the prefered way for persisting user settings for WPF applications with .NET 5, .NET 6 or .Net Core &gt;=3.0?<br> Where are the .NET user settings gone?</p> <p>Created WPF .Net Core 3.0 Project (VS2019 V16.3.1) Now I have seen there is no Properties.Settings section anymore. [<strong>Update 2022</strong>: With .NET 6 it is still the same]</p> <p><a href="https://i.stack.imgur.com/bTION.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bTION.png" alt="SolutionExplorer" /></a></p> <p>After online search, started to dive into Microsoft.Extensions.Configuration.</p> <p>Beside the bloated code to access the settings, now even worse -&gt; No save?<br> <a href="https://stackoverflow.com/q/51351464/3090544">User Configuration Settings in .NET Core</a></p> <blockquote> <p>Fortunately or unfortunately the Microsoft.Extensions.Configuration does not support saving by design. Read more in this Github issue <a href="https://github.com/aspnet/Configuration/issues/385" rel="nofollow noreferrer">Why there is no save in ConfigurationProvider?</a></p> </blockquote> <br> What is the prefered (and easy/fast/simple) way for persisting user settings for WPF applications with .Net Core >=3.0 / .NET5 / .NET6? <br> Before &lt;= .Net 4.8 it was as easy as: <br> <ul> <li><p>add the variables to the Properties. <a href="https://i.stack.imgur.com/J3C8Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J3C8Y.png" alt="User Settings" /></a> <br><br></p> </li> <li><p>Read the variables at startup<br> <code>var culture = new CultureInfo(Properties.Settings.Default.LanguageSettings);</code> <br><br></p> </li> <li><p>when a variable changes -&gt; immediately save it<br> <code>Properties.Settings.Default.LanguageSettings = selected.TwoLetterISOLanguageName; Properties.Settings.Default.Save();</code></p> </li> </ul>
58,423,458
7
10
null
2019-07-02 07:39:39.667 UTC
14
2022-07-29 07:07:34.087 UTC
2022-07-29 07:07:34.087 UTC
null
3,090,544
null
3,090,544
null
1
87
c#|wpf|.net-core|.net-5|.net-6.0
29,522
<p><a href="https://i.stack.imgur.com/C5yI0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C5yI0.png" alt="enter image description here"></a></p> <p>You can add the same old good settings file e.g. via the right click on the Properties -> Add -> New Item and search for the "Settings". The file can be edited in the settings designer and used as in the .net framework projects before (ConfigurationManager, Settings.Default.Upgrade(), Settings.Default.Save, etc. works).</p> <p>Add also the app.config file to the project root folder (the same way via the Add -> New Item), save the settings once again, compile the project and you will find a .dll.config file in the output folder. You can change now default app values as before.</p> <p>Tested with Visual Studio 1.16.3.5 and a .net core 3.0 WPF project.</p>
13,737,370
Cmake error: Invalid escape sequence \U
<p>While running my OpenCL code in VC++ 10 by using CMake I am getting the following error:</p> <pre><code>CMake Error at CMakeLists.txt:6 (set): Syntax error in cmake code at C:/Users/Shreedhar/Desktop/testCL/CMakeLists.txt:6 when parsing string C:\Users\Shreedhar\Desktop\test_CL\CMakeLists Invalid escape sequence \U </code></pre>
13,742,066
3
0
null
2012-12-06 05:14:19.797 UTC
4
2017-04-04 14:29:47.167 UTC
2012-12-06 16:59:40.54 UTC
null
208,997
null
1,770,678
null
1
32
path|cmake
35,831
<p>Use forward slashes <code>/</code> in your paths</p> <pre><code>C:/Users/Shreedhar/Desktop/test_CL/CMakeLists </code></pre>
24,265,981
Json.NET JsonConvert.DeserializeObject() return null value
<p>i tried to <strong>Deserialize</strong> this string : </p> <pre><code>string _jsonObject = {\"Ad\":{\"Type\":\"Request"\, \"IdAd\":\"[email protected]\", \"Category\":\"cat\", \"SubCategory\":\"subcat\"}, \"Position\":{\"Latitude\":\"38.255\", \"Longitude\":\"1.2\", \"Imei\":\"0123456789\"}; }"; Message _message = JsonConvert.DeserializeObject&lt;Message&gt;(_jsonObject); </code></pre> <p>Works pretty for "Ad" but not instanciate "Position". Any idea ? </p>
26,024,471
9
2
null
2014-06-17 14:07:09.683 UTC
2
2021-11-24 16:20:59.983 UTC
2014-06-17 14:14:06.057 UTC
null
3,164,795
null
3,164,795
null
1
13
c#|json|serialization|json.net
72,317
<p>In the interest of helping others that may be experiencing this issue, or one related to it...</p> <p>In my case, I had an object with an array of other objects, and one of the reference-type properties on those sub-objects was always null after deserialization. I tried all kinds of things, including downloading the JSON.Net source and stepping through it to find the failure point. </p> <p>To make a long story short, the problem was, of course, my own. Here is a highly simplified version of my JSON and classes.</p> <h2>JSON</h2> <pre><code>{ "$id": "1", "RowCount": 10, "Rows": [{ "$id": 2", "ItemId": "1", "ItemName": "Some Item", "Owner": { "Name": "John Doe", "Id": "711D04F5-586F-4FD4-8369-4C00B51DD86F", // other properties... }, "OwnerId": "711D04F5-586F-4FD4-8369-4C00B51DD86F" }, // more rows ] } </code></pre> <h2>Classes</h2> <pre><code>public class Items { public int RowCount { get; set; } public IEnumerable&lt;Item&gt; Rows { get; set; } } public class Item { private string ownerId; public string ItemId { get; set; } public string ItemName { get; set; } public Person Owner { get; set; } public string OwnerId { get { return this.ownerId; } set { if (value != this.ownerId) { this.Owner = null; } this.ownerId = value; } } } public class Person { public string Name { get; set; } public string Id { get; set; } // other properties } </code></pre> <p>What was happening is that, because the <code>Owner</code> property appeared in the JSON prior to the <code>OwnerId</code> property, when the <code>OwnerId</code> property was set, the setter code determined that the current value was not the same as the value being set (since the current value was null), so it set the <code>Owner</code> property to null.</p> <p>To fix it I also check the value being set against the id of the <code>Owner</code> object as well, and skip setting <code>Owner</code> to null if they are the same.</p> <p>Admittedly, the cause of my problem may not be the same for everyone, but this is at least a cautionary tale to double-check what is happening when your objects are being initialized during deserialization.</p>
24,060,704
Achieving a complex grid in bootstrap
<p>Would it be possible to achieve the attached grid in bootstrap? Each of the squares would probably be an image... or perhaps text!</p> <p>I've had a go, but hit a wall when it comes to the top-left box for example that spans over two rows.</p> <p>Grid:</p> <p><img src="https://i.stack.imgur.com/cuCY0.png" alt="enter image description here"></p>
24,060,899
2
3
null
2014-06-05 12:50:04.167 UTC
9
2021-01-26 23:06:25.437 UTC
2014-06-05 12:56:40.913 UTC
null
616,443
null
2,901,131
null
1
5
css|twitter-bootstrap|grid-layout
6,400
<p>Use nested blocks whenever you need your grid to span several rows. Something like this:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-sm-6"&gt;&lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6"&gt;&lt;/div&gt; &lt;div class="col-sm-6"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6"&gt;&lt;/div&gt; &lt;div class="col-sm-6"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8"&gt;&lt;/div&gt; &lt;div class="col-sm-4"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-4"&gt;&lt;/div&gt; &lt;div class="col-sm-8"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-4"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then you can set the height for your blocks and your grid is good to go.</p>
3,818,745
AndroidRuntime error: Parcel: unable to marshal value
<p>I am trying to pass a HashMap to a new activity using the intent.puExtra function. Stepping through the debugger it seems that it adds the HashMap no problem, however when startActivty() is called I get a runtime error stating that Parcel: unable to marshal value com.appName.Liquor.</p> <p>Liquor is a custom class that I created, and I believe it, in combination with a HashMap, is causing the problem. If I pass a string rather than my HashMap it loads the next activity no problem.</p> <p>Main Activity</p> <pre><code>lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { String cat = ((TextView) view).getText().toString(); Intent i = new Intent(OhioLiquor.this, Category.class); i.putExtra("com.appName.cat", _liquorBase.GetMap()); startActivity(i); </code></pre> <p>Liquor Class</p> <pre><code>public class Liquor { public String name; public int code; public String category; private HashMap&lt;String, Bottle&gt; _bottles; public Liquor() { _bottles = new HashMap&lt;String, Bottle&gt;(); } public void AddBottle(Bottle aBottle) { _bottles.put(aBottle.size, aBottle); } } </code></pre> <p>Sub Activity</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); HashMap&lt;Integer, Liquor&gt; map = (HashMap&lt;Integer, Liquor&gt;)getIntent().getSerializableExtra("com.appName.cat"); setListAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.list_item, GetNames(map))); ListView lv = getListView(); lv.setTextFilterEnabled(true); </code></pre> <p>When the runtime error exists it never makes it into the sub activity class. So I'm pretty sure the problem exists in the adding of the HashMap to the intent, and based off the error I believe my Liquor class is the cause, but I can't figure out why.</p> <p>Your help will be much appreciated. Thanks!</p>
3,819,146
2
0
null
2010-09-29 04:32:50.523 UTC
14
2021-11-16 14:08:15.697 UTC
null
null
null
null
280,980
null
1
132
java|android
109,467
<p>Your <code>HashMap</code> itself is serializable but is the <code>Bottle</code> class serializable? If not, it will not serialize and will throw errors at runtime. Make the <code>Bottle</code> class implement the <code>java.io.Serializable</code> interface</p>
28,706,428
Invalid active developer path on MAC OS X after installing Ruby
<p>I get this error:</p> <p><code>xcrun: error: invalid active developer path (/Applications/Xcode.app), missing xcrun at: /Applications/Xcode.app/usr/bin/xcrun</code></p> <p>This <a href="https://stackoverflow.com/questions/14334708/xcrun-cant-find-xcode-path">solution</a> works, but the error occurs again after closing my terminal and reopening it; I then have to run the same commands every time I open a new terminal window.</p> <p>How can I apply these changes such that they will save after closing the terminal window out?</p>
58,601,435
11
4
null
2015-02-24 21:15:27.987 UTC
14
2020-01-06 16:15:17.51 UTC
2019-08-23 02:19:35.77 UTC
null
483,802
null
4,101,056
null
1
88
ruby|xcode|macos|xcrun
45,512
<p>Partial diagnosis: <a href="https://github.com/microsoft/vcpkg/issues/8781#issuecomment-547248760" rel="nofollow noreferrer">https://github.com/microsoft/vcpkg/issues/8781#issuecomment-547248760</a></p> <p>It seems that upgrading from one MacOS version to another either uninstalls some dev tools or it moves them to another path, and this breaks compatibility with any tool using the environment variable that points to the old location where the tools were located.</p> <pre><code>sudo xcode-select --install </code></pre> <p>Using the install command worked for me, but it is not clear whether this simply downloaded and unpacked files and then skipped installation and simply updated an environment variable or whether it physically installed the files at the expected path. (Or it could have made links to the new folder path).</p> <p>Testing my theory, I probe the folder structure with <code>ls</code> (I should have done this before using the install command):</p> <pre><code>rej@Ryans-MacBook-Air:~$ ls /Library/Developer/CommandLineTools/usr/bin/ rej@Ryans-MacBook-Air:~$ ls -la /Library/Developer/CommandLineTools/usr/bin/ total 243776 drwxr-xr-x 124 root wheel 3.9K Oct 28 23:03 ./ drwxr-xr-x 7 root admin 224B Oct 28 23:05 ../ lrwxr-xr-x 1 root wheel 64B Oct 28 23:03 2to3@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/2to3 lrwxr-xr-x 1 root wheel 68B Oct 28 23:03 2to3-3.7@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/2to3-3.7 -rwxr-xr-x 1 root wheel 116K Sep 5 22:51 DeRez* -rwxr-xr-x 1 root wheel 31K Sep 5 22:51 GetFileInfo* -rwxr-xr-x 1 root wheel 33K Sep 5 22:51 ResMerger* -rwxr-xr-x 1 root wheel 126K Sep 5 22:51 Rez* -rwxr-xr-x 1 root wheel 31K Sep 5 22:51 SetFile* -rwxr-xr-x 1 root wheel 32K Sep 5 22:51 SplitForks* -rwxr-xr-x 1 root wheel 41K Sep 5 22:51 ar* -rwxr-xr-x 1 root wheel 40K Sep 5 22:51 as* -rwxr-xr-x 1 root wheel 27K Sep 5 22:51 asa* -rwxr-xr-x 1 root wheel 216K Sep 5 22:51 bison* -rwxr-xr-x 1 root wheel 159K Sep 5 22:51 bitcode_strip* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 c++@ -&gt; clang -rwxr-xr-x 1 root admin 31K Sep 5 22:51 c89* -rwxr-xr-x 1 root admin 31K Sep 5 22:51 c99* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 cc@ -&gt; clang -rwxr-xr-x 1 root wheel 80M Sep 5 22:51 clang* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 clang++@ -&gt; clang -rwxr-xr-x 1 root wheel 125K Sep 5 22:51 cmpdylib* -rwxr-xr-x 1 root wheel 154K Sep 5 22:51 codesign_allocate* lrwxr-xr-x 1 root wheel 17B Oct 28 23:03 codesign_allocate-p@ -&gt; codesign_allocate -rwxr-xr-x 1 root admin 3.3K Aug 16 06:55 cpp* -rwxr-xr-x 1 root wheel 36K Sep 5 22:51 ctags* -rwxr-xr-x 1 root wheel 150K Sep 5 22:51 ctf_insert* -rwxr-xr-x 1 root wheel 30M Sep 5 22:51 dsymutil* lrwxr-xr-x 1 root wheel 14B Oct 28 23:03 dwarfdump@ -&gt; llvm-dwarfdump -rwxr-xr-x 1 root wheel 477K Sep 5 22:51 dwarfdump-classic* -rwxr-xr-x 1 root wheel 211K Sep 5 22:51 dyldinfo* -rwxr-xr-x 1 root wheel 239B Sep 5 19:18 easy_install-3.7* -rwxr-xr-x 1 root wheel 572K Sep 5 22:51 flex* -rwxr-xr-x 1 root wheel 572K Sep 5 22:51 flex++* lrwxr-xr-x 1 root wheel 3B Oct 28 23:03 g++@ -&gt; gcc -rwxr-xr-x 1 root wheel 101K Aug 16 07:31 gatherheaderdoc* -rwxr-xr-x 1 root admin 27K Sep 5 22:51 gcc* lrwxr-xr-x 1 root wheel 8B Oct 28 23:03 gcov@ -&gt; llvm-cov -rwxr-xr-x 1 root wheel 2.4M Sep 5 22:51 git* lrwxr-xr-x 1 root wheel 3B Oct 28 23:03 git-receive-pack@ -&gt; git -rwxr-xr-x 1 root wheel 1.4M Sep 5 22:51 git-shell* lrwxr-xr-x 1 root wheel 3B Oct 28 23:03 git-upload-archive@ -&gt; git lrwxr-xr-x 1 root wheel 3B Oct 28 23:03 git-upload-pack@ -&gt; git -rwxr-xr-x 1 root wheel 148K Sep 5 22:51 gm4* -rwxr-xr-x 1 root wheel 166K Sep 5 22:51 gnumake* -rwxr-xr-x 1 root wheel 98K Sep 5 22:51 gperf* -rwxr-xr-x 1 root wheel 33K Sep 5 22:51 hdxml2manxml* -rwxr-xr-x 1 root wheel 158K Aug 16 07:31 headerdoc2html* -rwxr-xr-x 1 root wheel 73K Sep 5 22:51 indent* -rwxr-xr-x 1 root wheel 142K Sep 5 22:51 install_name_tool* -rwxr-xr-x 1 root wheel 2.5M Sep 5 22:51 ld* -rwxr-xr-x 1 root wheel 230B Aug 16 07:13 lex* -rwxr-xr-x 1 root wheel 163K Sep 5 22:51 libtool* -rwxr-xr-x 1 root wheel 73K Sep 5 22:51 lipo* -rwxr-xr-x 1 root wheel 332K Sep 5 22:51 lldb* -rwxr-xr-x 1 root wheel 3.6M Sep 5 22:51 llvm-cov* -rwxr-xr-x 1 root wheel 7.9M Sep 5 22:51 llvm-dwarfdump* -rwxr-xr-x 1 root wheel 9.8M Sep 5 22:51 llvm-nm* -rwxr-xr-x 1 root wheel 11M Sep 5 22:51 llvm-objdump* -rwxr-xr-x 1 root wheel 40K Sep 5 22:51 llvm-otool* -rwxr-xr-x 1 root wheel 1.6M Sep 5 22:51 llvm-profdata* -rwxr-xr-x 1 root wheel 2.9M Sep 5 22:51 llvm-size* -rwxr-xr-x 1 root wheel 3.5K Aug 16 07:19 lorder* -rwxr-xr-x 1 root wheel 148K Sep 5 22:51 m4* -rwxr-xr-x 1 root wheel 166K Sep 5 22:51 make* -rwxr-xr-x 1 root wheel 7.7K Aug 16 07:16 mig* lrwxr-xr-x 1 root wheel 7B Oct 28 23:03 nm@ -&gt; llvm-nm -rwxr-xr-x 1 root wheel 142K Sep 5 22:51 nm-classic* -rwxr-xr-x 1 root wheel 171K Sep 5 22:51 nmedit* lrwxr-xr-x 1 root wheel 12B Oct 28 23:03 objdump@ -&gt; llvm-objdump lrwxr-xr-x 1 root wheel 10B Oct 28 23:03 otool@ -&gt; llvm-otool -rwxr-xr-x 1 root wheel 644K Sep 5 22:51 otool-classic* -rwxr-xr-x 1 root wheel 138K Sep 5 22:51 pagestuff* -rwxr-xr-x 1 root wheel 221B Sep 5 19:18 pip3* -rwxr-xr-x 1 root wheel 221B Sep 5 19:18 pip3.7* -rwxr-xr-x 1 root wheel 32K Sep 5 22:51 projectInfo* lrwxr-xr-x 1 root wheel 66B Oct 28 23:03 pydoc3@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/pydoc3 lrwxr-xr-x 1 root wheel 68B Oct 28 23:03 pydoc3.7@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/pydoc3.7 lrwxr-xr-x 1 root wheel 67B Oct 28 23:03 python3@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3 lrwxr-xr-x 1 root wheel 74B Oct 28 23:03 python3-config@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3-config lrwxr-xr-x 1 root wheel 69B Oct 28 23:03 python3.7@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3.7 lrwxr-xr-x 1 root wheel 76B Oct 28 23:03 python3.7-config@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3.7-config lrwxr-xr-x 1 root wheel 70B Oct 28 23:03 python3.7m@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3.7m lrwxr-xr-x 1 root wheel 77B Oct 28 23:03 python3.7m-config@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/python3.7m-config lrwxr-xr-x 1 root wheel 66B Oct 28 23:03 pyvenv@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/pyvenv lrwxr-xr-x 1 root wheel 70B Oct 28 23:03 pyvenv-3.7@ -&gt; ../../Library/Frameworks/Python3.framework/Versions/3.7/bin/pyvenv-3.7 lrwxr-xr-x 1 root wheel 7B Oct 28 23:03 ranlib@ -&gt; libtool -rwxr-xr-x 1 root wheel 70K Sep 5 22:51 resolveLinks* -rwxr-xr-x 1 root wheel 85K Sep 5 22:51 rpcgen* -rwxr-xr-x 1 root wheel 56K Sep 5 22:51 segedit* lrwxr-xr-x 1 root wheel 12B Oct 28 23:03 size@ -&gt; size-classic -rwxr-xr-x 1 root wheel 125K Sep 5 22:51 size-classic* -rwxr-xr-x 1 root admin 138K Sep 5 22:51 stapler* -rwxr-xr-x 1 root wheel 126K Sep 5 22:51 strings* -rwxr-xr-x 1 root wheel 179K Sep 5 22:51 strip* -rwxr-xr-x 1 root wheel 330K Sep 5 22:51 svn* -rwxr-xr-x 1 root wheel 118K Sep 5 22:51 svnadmin* -rwxr-xr-x 1 root wheel 105K Sep 5 22:51 svnbench* -rwxr-xr-x 1 root wheel 64K Sep 5 22:51 svndumpfilter* -rwxr-xr-x 1 root wheel 71K Sep 5 22:51 svnfsfs* -rwxr-xr-x 1 root wheel 98K Sep 5 22:51 svnlook* -rwxr-xr-x 1 root wheel 70K Sep 5 22:51 svnmucc* -rwxr-xr-x 1 root wheel 89K Sep 5 22:51 svnrdump* -rwxr-xr-x 1 root wheel 122K Sep 5 22:51 svnserve* -rwxr-xr-x 1 root wheel 90K Sep 5 22:51 svnsync* -rwxr-xr-x 1 root wheel 44K Sep 5 22:51 svnversion* -rwxr-xr-x 1 root wheel 90M Sep 5 22:51 swift* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 swift-autolink-extract@ -&gt; swift -rwxr-xr-x 1 root admin 6.1M Sep 5 22:51 swift-build* -rwxr-xr-x 1 root admin 734K Sep 5 22:51 swift-build-tool* -rwxr-xr-x 1 root wheel 687K Sep 5 22:51 swift-demangle* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 swift-format@ -&gt; swift -rwxr-xr-x 1 root admin 6.1M Sep 5 22:51 swift-package* -rwxr-xr-x 1 root admin 6.1M Sep 5 22:51 swift-run* -rwxr-xr-x 1 root wheel 61K Sep 5 22:51 swift-stdlib-tool* -rwxr-xr-x 1 root admin 6.1M Sep 5 22:51 swift-test* lrwxr-xr-x 1 root wheel 5B Oct 28 23:03 swiftc@ -&gt; swift -rwxr-xr-x 1 root wheel 12M Sep 5 22:51 tapi* -rwxr-xr-x 1 root wheel 41K Sep 5 22:51 unifdef* -rwxr-xr-x 1 root wheel 2.9K Aug 16 07:19 unifdefall* -rwxr-xr-x 1 root wheel 63K Sep 5 22:51 unwinddump* -rwxr-xr-x 1 root wheel 49K Sep 5 22:51 vtool* -rwxr-xr-x 1 root wheel 45K Sep 5 22:51 xml2man* -rwxr-xr-x 1 root wheel 135B Aug 16 07:22 yacc* </code></pre> <p>It is apparent that the files are physically located at that folder location and the installer installed missing components. The fact that MacOS's upgrade process uninstalls my development environment is unfriendly and Apple should be reprimanded.</p>
16,504,816
How to set HTML content into an iframe
<p>I have a HTML string </p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;body&gt;Hello world&lt;/body&gt; &lt;/html&gt; </code></pre> <p>and I want to set it to an iframe with JavaScript. I am trying to set the HTML like this: </p> <pre class="lang-js prettyprint-override"><code>contentWindow.document.body.innerHTML </code></pre> <p>or</p> <pre class="lang-js prettyprint-override"><code>contentDocument.body.innerHTML </code></pre> <p>or</p> <pre class="lang-js prettyprint-override"><code>document.body.innerHTML </code></pre> <p>but IE gives "Access is denied." or "Object does not support this property or method." or "Invalid final element to the action." errors.</p> <p>Here is my full code:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery_1.7.0.min.js"/&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ var htmlString = "&lt;html&gt;&lt;body&gt;Hello world&lt;/body&gt;&lt;/html&gt;"; var myIFrame = document.getElementById('iframe1'); // open needed line commentary //myIFrame.contentWindow.document.body.innerHTML = htmlString; //myIFrame.contentDocument.body.innerHTML = htmlString; //myIFrame.document.body.innerHTML = htmlString; //myIFrame.contentWindow.document.documentElement.innerHTML = htmlString; }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;This is iframe: &lt;br&gt; &lt;iframe id="iframe1"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
16,557,787
6
1
null
2013-05-12 06:33:53.327 UTC
13
2020-04-14 14:05:04.563 UTC
2020-04-14 14:05:04.563 UTC
null
11,683
null
1,942,750
null
1
46
javascript|html|iframe|internet-explorer-8|internet-explorer-9
90,215
<p>You could use:</p> <pre><code>document.getElementById('iframe1').contentWindow.document.write("&lt;html&gt;&lt;body&gt;Hello world&lt;/body&gt;&lt;/html&gt;"); </code></pre> <p>Here's a <a href="http://jsfiddle.net/3yu6a/1" rel="noreferrer">jsFiddle</a>, which works in all major browsers.</p> <p>Note that instead of <code>contentDocument.write</code> you should use <code>contentWindow.document.write</code>: this makes it work in IE7 as well.</p>
16,281,366
ASP.NET MVC rendering seems slow
<p>I've created a brand new MVC4 web application in Visual Studio, and done nothing more with it than add a Home controller and a "Hello world" index view for it. I then installed the MiniProfiler NuGet package and put the necessary couple of lines in <code>_Layout.cshtml</code>. This is what I get when I run the site in Release mode (hosted in IIS):</p> <p><img src="https://i.stack.imgur.com/cboLY.png" alt="MVC rendering picture"></p> <p>The rendering time varies by pageload, but 130ms is about as fast as it gets. This seems a bit slow to me, as I've seen other people who get pages rendered in 30ms or quicker. Any ideas why the rendering would be this slow with a brand new empty MVC4 project? My processor is an Intel Core i5-2400 and the machine has 16GB RAM.</p> <p>By the way, this is <em>not</em> the first time the page is loaded; I reloaded the page a few times before getting this 130ms result.</p> <p><strong>UPDATE:</strong><br> I followed the advice in the answer from PSCoder (remove all but the RazorViewEngine), and it halved the rendering time:</p> <p><img src="https://i.stack.imgur.com/wqAxU.png" alt="MVC rendering picture 2"></p> <p>This is really good, but I still get about 70ms or higher for the main <code>Render</code> action of the page; ideally I'd like to halve that or better.</p> <p>Specifically, I'd like to ask:</p> <ul> <li>Does this rendering time seem overly slow or is it average for my machine?</li> <li>Is there any way I can speed it up?</li> </ul>
16,281,515
4
12
null
2013-04-29 14:35:26.143 UTC
29
2019-12-12 06:40:44.76 UTC
2013-10-15 01:28:02.743 UTC
null
1,009,603
null
178,757
null
1
49
c#|asp.net-mvc|performance|asp.net-mvc-4
46,910
<p>This could help improve ASP.NET MVC related performance issue , one performance improvement that you can do is to clear all the view engines and add the one(s) that you use. say for ex:- <code>RazorViewEngine</code>. MVC registers 2 view engines by default <code>Webforms</code> and <code>Razor</code> view engines, so clearing and adding the ones that is used alone will improve the look up performance.</p> <p>You can add this in <code>global.asax</code> <code>Application_Start</code>. </p> <pre><code> ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); </code></pre> <p>In order to completely utilize view look up caching and thus again performance gain compile the code in release mode and make sure that your <code>web.config</code> file is configured with <code>&lt;compilation debug="false" /&gt;</code> for view look up caching to kick in. </p>
15,109,109
SQL SUM GROUP BY two tables
<p>I'm having difficulty writing an SQL query that will correctly group account_no together and subtracting an amount.</p> <p>Firstly I wrote this query which updates everything fine except ACCOUNT_NO A-102 should end up as 4500 not as two different correct balances.</p> <pre><code>select transactions.account_no, account.balance, transactions.amount, (account.balance + transactions.amount) AS "CORRECT BALANCE" from transactions, account where account.account_no = transactions.account_no; ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE A-102 | 4000 | 2000 | 6000 A-102 | 4000 | -1500 | 2500 A-222 | 8000 | -1000 | 7000 A-305 | 2000 | 1300 | 3300 </code></pre> <p>I tried to sum and group by the account_no but I cannot work out how to do this with the two tables. This was just something I tried but could not get to work.</p> <pre><code>select transactions.account_no, SUM(transactions.amount) from transactions group by transactions.account_no; ACCOUNT_NO| SUM(TRANSACTIONS.AMOUNT) A-305 | 1300 A-102 | 500 A-222 | -1000 </code></pre> <p>The expected outcome should be:</p> <pre><code>ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE A-102 | 4000 | 500 | 4500 A-222 | 8000 | -1000 | 7000 A-305 | 2000 | 1300 | 3300 </code></pre> <p>This is because the account A-102 it has two different amounts coming out, but from the same balance.</p>
15,109,361
2
3
null
2013-02-27 09:59:09.133 UTC
4
2020-12-15 11:41:56.737 UTC
2013-02-27 10:43:36.363 UTC
null
2,114,634
null
2,114,634
null
1
5
sql|group-by|sum
45,208
<p>For your query, to get the two rows grouped on one row, you can try grouping on the account number AND the balance:</p> <pre><code>SELECT T.account_no ,A.balance ,SUM(T.amount) AS TotalAmount ,(A.balance + SUM(T.amount)) AS "CORRECT BALANCE" FROM transactions AS T INNER JOIN account AS A ON T.account_no = A.account_no GROUP BY T.account_no, A.balance; </code></pre> <p>(By the way, I've used the ANSI join instead of the 'old' way of joining tables, because it's much more clear what you're doing that way.)</p> <p><strong>EDIT</strong> </p> <p>To make things a bit more clear, I've made a <strong><a href="http://www.sqlfiddle.com/#!3/22cf8/2" rel="nofollow noreferrer">SQL Fiddle</a></strong>. Does this represent your situation more or less correctly?</p> <p><strong>EDIT2</strong></p> <p>The above query would not show any accounts without transactions, as <a href="https://stackoverflow.com/users/412923">Kaf</a> commented. That might be what you want, but in case it's not you can switch the join tables like this:</p> <pre><code>SELECT A.account_no ,A.balance ,SUM(T.amount) AS TotalAmount ,(A.balance + SUM(T.amount)) AS "CORRECT BALANCE" FROM account AS A LEFT OUTER JOIN transactions AS T ON T.account_no = A.account_no GROUP BY A.account_no, A.balance; </code></pre>
17,546,497
Adding Elements to List Java
<p>Why I am unable to Add element to List after assigning values from to Arrays.asList</p> <pre><code>List&lt;Integer&gt; sam = Arrays.asList(1,2,3,4); sam.add(5); for (Integer integer : sam) { System.out.println(integer); } </code></pre>
17,546,544
5
1
null
2013-07-09 10:58:39.6 UTC
1
2015-03-25 18:44:44.033 UTC
2013-07-09 11:12:57.107 UTC
null
2,345,933
null
1,973,669
null
1
7
java
57,427
<p><code>Arrays.asList(1,2,3,4)</code> creates a "list view" on an array whose size can't change. That way we can use and access an array through the <code>List</code> interface.</p> <p>If you want a list in which you can add values but still use the convenient <code>Arrays.asList(..)</code>, simply do:</p> <pre><code>List&lt;Integer&gt; sam = new ArrayList&lt;&gt;(Arrays.asList(1,2,3,4)); </code></pre>
17,281,446
How to request.getParameterNames into List of strings?
<p>Is it possible to get <code>request.getParameterNames()</code> as a list of Strings? I need to have it in this form.</p>
17,281,974
4
0
null
2013-06-24 17:29:41.137 UTC
3
2017-04-24 18:32:33.673 UTC
2013-06-24 18:05:19.263 UTC
null
157,882
null
1,393,593
null
1
15
java|servlets
56,962
<p>Just <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29" rel="noreferrer">construct</a> a new <code>ArrayList</code> wrapping the keyset of the <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap%28%29" rel="noreferrer">request parameter map</a>.</p> <pre><code>List&lt;String&gt; parameterNames = new ArrayList&lt;String&gt;(request.getParameterMap().keySet()); // ... </code></pre> <p>I only wonder how it's useful to have it as <code>List&lt;String&gt;</code>. A <code>Set&lt;String&gt;</code> would make much more sense as parameter names are supposed to be <strong>unique</strong> (a <code>List</code> can contain duplicate elements). A <code>Set&lt;String&gt;</code> is also exactly what the map's keyset already represents.</p> <pre><code>Set&lt;String&gt; parameterNames = request.getParameterMap().keySet(); // ... </code></pre> <p>Or perhaps you don't need it at all for the particular functional requirement for which you <a href="https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">thought</a> that massaging the parameter names into a <code>List&lt;String&gt;</code> would be the solution. Perhaps you <em>actually</em> intented to iterate over it in an enhanced loop, for example? That's also perfectly possible on a <code>Map</code>.</p> <pre><code>for (Entry&lt;String, String[]&gt; entry : request.getParameterMap().entrySet()) { String name = entry.getKey(); String value = entry.getValue()[0]; // ... } </code></pre>
17,613,582
Fullcalendar: Change the color for specific days
<p>I'm stuck with a project I get at work. I need to change the background color of some days. It's a calendar where the user should see, which days are available and which not. I found out that there is an attribute called "data-date", but I didn't found a possibility to use it.</p> <p>Is there any way to manipulate the background of specific days?</p> <p>I think there must be a way, cause the cell which shows the current date has another color too.</p>
17,615,045
8
0
null
2013-07-12 11:09:02.463 UTC
8
2020-12-22 04:44:23.157 UTC
2020-12-22 04:44:23.157 UTC
null
270,302
null
2,576,127
null
1
17
css|fullcalendar|cell|background-color
70,217
<p>For the views <code>month</code>, <code>basicWeek</code> and <code>basicDay</code> you can change the rendering of the days by providing a <code>dayRender</code> function. E.g.:</p> <pre><code>$("#calendar").fullCalendar({ dayRender: function (date, cell) { cell.css("background-color", "red"); } }); </code></pre> <p>The documentation for <code>dayRender</code> is available here: <a href="http://arshaw.com/fullcalendar/docs/display/dayRender/" rel="noreferrer">http://arshaw.com/fullcalendar/docs/display/dayRender/</a></p> <p>And here's a working example on jsfiddle: <a href="http://jsfiddle.net/kvakulo/CYnJY/4/" rel="noreferrer">http://jsfiddle.net/kvakulo/CYnJY/4/</a></p>
39,490,839
Alamofire Swift 3.0 Extra argument in call
<p>I have migrated my project to Swift 3 (and updated Alamofire to latest Swift 3 version with <code>pod 'Alamofire', '~&gt; 4.0'</code> in the Podfile).</p> <p>I now get an "Extra argument in call" error on every Alamofire.request. Eg:</p> <pre><code>let patientIdUrl = baseUrl + nextPatientIdUrl Alamofire.request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding: .JSON) </code></pre> <p>Can anybody tell me why ?</p>
39,498,990
14
10
null
2016-09-14 12:46:52.577 UTC
17
2019-10-27 04:59:06.743 UTC
2017-11-09 23:14:56.427 UTC
null
117,014
null
361,211
null
1
54
alamofire|swift3
72,959
<p>According to <a href="https://github.com/Alamofire/Alamofire">Alamofire</a> documentation for version 4.0.0 URL request with <strong>HTTP</strong> method would be followings:</p> <pre><code>Alamofire.request("https://httpbin.org/get") // method defaults to `.get` Alamofire.request("https://httpbin.org/post", method: .post) Alamofire.request("https://httpbin.org/put", method: .put) Alamofire.request("https://httpbin.org/delete", method: .delete) </code></pre> <p>So your url request will be: </p> <pre><code>Alamofire.request(patientIdUrl, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil) </code></pre> <p>and a sample request will be:</p> <pre><code>Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [AUTH_TOKEN_KEY : AUTH_TOKEN]) .responseJSON { response in print(response.request as Any) // original URL request print(response.response as Any) // URL response print(response.result.value as Any) // result of response serialization } </code></pre> <p>Hope this helps!</p>
19,699,367
"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte
<p>Here is my code,</p> <pre><code>for line in open('u.item'): # Read each line </code></pre> <p>Whenever I run this code it gives the following error:</p> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte</p> </blockquote> <p>I tried to solve this and add an extra parameter in open(). The code looks like:</p> <pre><code>for line in open('u.item', encoding='utf-8'): # Read each line </code></pre> <p>But again it gives the same error. What should I do then?</p>
19,706,723
19
4
null
2013-10-31 05:55:32.643 UTC
81
2022-08-03 19:25:18.86 UTC
2021-01-30 16:27:36.823 UTC
null
63,550
null
2,925,295
null
1
331
python|python-3.x|character-encoding
803,631
<p>As <a href="https://stackoverflow.com/questions/19699367/for-line-in-results-in-unicodedecodeerror-utf-8-codec-cant-decode-byte/19699399#19699399">suggested by Mark Ransom</a>, I found the right encoding for that problem. The encoding was <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="noreferrer"><code>&quot;ISO-8859-1&quot;</code></a>, so replacing <code>open(&quot;u.item&quot;, encoding=&quot;utf-8&quot;)</code> with <code>open('u.item', encoding = &quot;ISO-8859-1&quot;)</code> will solve the problem.</p>
17,544,048
Multi-level tables (inside another if clicked)
<h2><strong>Scenario</strong></h2> <p>Lets say I am owner of a big company that has many stores. Depending on what role (place in the organization) I have within the company, I will have different access to data. There will be different modules and for this specific question there is one where users that have access can go through daily cost and sales. (If that's legal or not...don't care, it's just for an example.)</p> <p>The user thereby get all data through REST API from BackEnd (Java application) with all data for all stores the user has access to. The user should then be able to filter the data, by different filter combinations. Most relevant for my question is the date interval by days.</p> <p>There will be some charts showing data on different levels and below there will be a table area where I want the multi-level tables, hence my question.</p> <h2>Done so far</h2> <ol> <li>I first created accordions that have stores on accordion-group level and then next level of data in a table, within the accordion-body. (Only hard coded data at the moment.) The problem here was that an according heading is a string and after some discussion we felt that this was not a good solution since the heading would consist of parts of data that in a table would have been separate columns. It would therefore be difficult to "columnize" the heading data to match horizontally the different "stores" (between the accordion headings) when collapsed (and of course even more messy when one or more accordion are expanded).</li> <li>I replaced the accordions with table and ng-repeat. Have successfully populated the first table level with both data from the figurative API with JSON data as well as got i18next working for the headings.</li> </ol> <h2>JSON</h2> <pre><code>{ "metadata":{ "storesInTotal":"25", "storesInRepresentation":"2" }, "storedata":[ { "store" : { "storeId" : "1000", "storeName" : "Store 1", "storePhone" : "+46 31 1234567", "storeAddress": "Some street 1", "storeCity" : "Gothenburg" }, "data" : { "startDate" : "2013-07-01", "endDate" : "2013-07-02", "costTotal" : "100000", "salesTotal" : "150000", "revenueTotal" : "50000", "averageEmployees" : "3.5", "averageEmployeesHours" : "26.5", "dayData" : [ { "date" : "2013-07-01", "cost" : "25000", "sales" : "15000", "revenue" : "4000", "employees" : "3", "employeesHoursSum" : "24" }, { "date" : "2013-07-02", "cost" : "25000", "sales" : "16000", "revenue" : "5000", "employees" : "4", "employeesHoursSum" : "29" } ] } }, { "store" : { "storeId" : "2000", "storeName" : "Store 2", "storePhone" : "+46 8 9876543", "storeAddress": "Big street 100", "storeCity" : "Stockholm" }, "data" : { "startDate" : "2013-07-01", "endDate" : "2013-07-02", "costTotal" : "170000", "salesTotal" : "250000", "revenueTotal" : "80000", "averageEmployees" : "4.5", "averageEmployeesHours" : "35", "dayData" : [ { "date" : "2013-07-01", "cost" : "85000", "sales" : "120000", "revenue" : "35000", "employees" : "5", "employeesHoursSum" : "38" }, { "date" : "2013-07-02", "cost" : "85000", "sales" : "130000", "revenue" : "45000", "employees" : "4", "employeesHoursSum" : "32" } ] } } ], "_links":{ "self":{ "href":"/storedata/between/2013-07-01/2013-07-02" } } } </code></pre> <h2>Visual example - JSFiddle</h2> <p>Check the values in the result frame, top left corner. Try clicking for example row with Store ID 2000, then with 3000 and then 3000 again to see how the values change. <a href="http://jsfiddle.net/Pixic/juLk7/">Current update of my JSFiddle</a></p> <h2>Wanted functionality</h2> <p>When a row is clicked (as shown in the JSFiddle), I want a directive or something triggered, to go and fetch underlying data (dayData) for the store clicked and show all days in the date interval. I.e expanding the row, and including a new table under the clicked row, which also should use ng-repeat to get all data displayed similar to the existing one, but inline.</p> <h2>Question</h2> <p>So I have already got the functionality to get the $index and also the specific data from the clicked row. What kind of directive or any other solution do I need additionally to get the "data when row clicked" and presented in a table under the clicked row?</p> <p>I don't want it in the DOM all the time, since there might be many dayData for each store and many stores. (And will use pagination later, but even so, not in the DOM all the time.) This means that I have to be able to ADD when clicking a row, and when clicking the same or another REMOVE from the previously clicked.</p> <hr> <h2>EDIT</h2> <p><a href="http://jsfiddle.net/Pixic/6Texj/">New updated JSFiddle</a>.</p>
18,115,474
3
6
null
2013-07-09 08:59:26.197 UTC
18
2018-02-14 22:09:25.79 UTC
2013-08-01 07:49:10.143 UTC
null
243,557
null
1,763,484
null
1
21
angularjs|angularjs-directive
42,759
<p>The requirement was to not fill the DOM with all second level tables and I came up with a solution for it.</p> <p>First I tried creating a custom directive and I got it to insert a row at the right place (beneath the clicked row) and created a second level table with headers but could not get it to populate with rows using ng-repeat.</p> <p>Since I could not find a solution that worked fully I went back to what I already had created, with ng-show and sought a solution like it...and there exist one. Instead of using ng-show/ng-hide, Angular has a directive called ng-switch.</p> <p>In level one</p> <pre><code>&lt;tbody data-ng-repeat="storedata in storeDataModel.storedata" data-ng-switch on="dayDataCollapse[$index]"&gt; </code></pre> <p>...and then in the second level, i.e. the second tr </p> <pre><code>&lt;tr data-ng-switch-when="true"&gt; </code></pre> <p>, in which you have the second level ng-repeat.</p> <p>Here's a new <strong><a href="http://jsfiddle.net/Pixic/VGgbq/" rel="noreferrer">JSFiddle</a></strong>.</p> <p>Inspect elements, and you will see that there is a comment placeholder for each "collapsed" level 2 table.</p> <hr> <h2>UPDATE (2014-09-29)</h2> <p>Upon request of also expanding/collapsing level 3, here's a new <strong><a href="http://jsfiddle.net/Pixic/sd5318kL/" rel="noreferrer">JSFIDDLE</a></strong>.</p> <p><strong>NOTE!</strong> - This solution have all information in the DOM at all times, i.e. not as the earlier solution, which only added a notation for where the information should be added upon request.</p> <p>(I can't take credit of this one though, since my friend Axel forked mine and then added the functionality.)</p>
17,411,966
printing stdout in realtime from a subprocess that requires stdin
<p>This is a follow up to <a href="https://stackoverflow.com/questions/17395243/printing-stdout-in-realtime-from-subprocess">this question</a>, but if I want to pass an argument to <code>stdin</code> to <code>subprocess</code>, how can I get the output in real time? This is what I currently have; I also tried replacing <code>Popen</code> with <code>call</code> from the <code>subprocess</code> module and this just leads to the script hanging.</p> <pre><code>from subprocess import Popen, PIPE, STDOUT cmd = 'rsync --rsh=ssh -rv --files-from=- thisdir/ servername:folder/' p = Popen(cmd.split(), stdout=PIPE, stdin=PIPE, stderr=STDOUT) subfolders = '\n'.join(['subfolder1','subfolder2']) output = p.communicate(input=subfolders)[0] print output </code></pre> <p>In the former question where I did not have to pass <code>stdin</code> I was suggested to use <code>p.stdout.readline</code>, there there is no room there to pipe anything to <code>stdin</code>.</p> <p>Addendum: This works for the transfer, but I see the output only at the end and I would like to see the details of the transfer while it's happening.</p>
17,413,045
3
1
null
2013-07-01 19:14:03.62 UTC
7
2019-02-14 08:28:53.227 UTC
2017-05-23 10:30:52.53 UTC
null
-1
null
143,476
null
1
25
python|subprocess
47,482
<p>In order to grab stdout from the subprocess in real time you need to decide exactly what behavior you want; specifically, you need to decide whether you want to deal with the output line-by-line or character-by-character, and whether you want to block while waiting for output or be able to do something else while waiting. </p> <p>It looks like it will probably suffice for your case to read the output in line-buffered fashion, blocking until each complete line comes in, which means the convenience functions provided by <code>subprocess</code> are good enough:</p> <pre><code>p = subprocess.Popen(some_cmd, stdout=subprocess.PIPE) # Grab stdout line by line as it becomes available. This will loop until # p terminates. while p.poll() is None: l = p.stdout.readline() # This blocks until it receives a newline. print l # When the subprocess terminates there might be unconsumed output # that still needs to be processed. print p.stdout.read() </code></pre> <p>If you need to write to the stdin of the process, just use another pipe:</p> <pre><code>p = subprocess.Popen(some_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) # Send input to p. p.stdin.write("some input\n") p.stdin.flush() # Now start grabbing output. while p.poll() is None: l = p.stdout.readline() print l print p.stdout.read() </code></pre> <p><em>Pace</em> the other answer, there's no need to indirect through a file in order to pass input to the subprocess.</p>
17,665,565
Is there a way to run R code from JavaScript?
<p>I am working on a project which requires some R code to be run for some data analysis. The project is primarily in JavaScript, and I need a way to run R code from JS. My research has not found any good way to do it yet. Is there any way to do so?</p> <p>Also, I have next to no experience with R (another person is supplying the R code).</p>
24,288,062
3
6
null
2013-07-15 23:23:25.44 UTC
28
2018-10-18 10:23:41.073 UTC
null
null
null
null
1,701,791
null
1
51
javascript|r
48,070
<p>If you're ok with having the R code run on a server, then you should take a look at <a href="https://www.opencpu.org/" rel="nofollow noreferrer">OpenCPU</a>. It provides a REST API and corresponding JavaScript library for sending R code to the server and getting the results back. In particular, it takes care of the security problems that can arise from running R as a server (R code can run arbitrary shell commands, among other things). There are public demo instances that you can use to try it out, and <a href="https://github.com/abresler/ramnathv.github.io/blob/master/posts/making-rcharts-live-app/index.md" rel="nofollow noreferrer">this page</a> provides a simple tutorial.</p>
17,452,247
Validate form field only on submit or user input
<p>I have form fields that are validated using <code>required</code>. The problem is, that the error is displayed immediately when the form is rendered. I want it only to be displayed after the user actually typed in the text field, or on submit.</p> <p>How can I implement this?</p>
17,452,805
5
0
null
2013-07-03 15:36:29.55 UTC
27
2018-12-20 03:13:18.52 UTC
null
null
null
user187676
null
null
1
59
angularjs
168,486
<p>Use <code>$dirty</code> flag to show the error only after user interacted with the input:</p> <pre class="lang-html prettyprint-override"><code>&lt;div&gt; &lt;input type="email" name="email" ng-model="user.email" required /&gt; &lt;span ng-show="form.email.$dirty &amp;&amp; form.email.$error.required"&gt;Email is required&lt;/span&gt; &lt;/div&gt; </code></pre> <p>If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:</p> <pre class="lang-html prettyprint-override"><code>&lt;form ng-submit="submit()" name="form" ng-controller="MyCtrl"&gt; &lt;div&gt; &lt;input type="email" name="email" ng-model="user.email" required /&gt; &lt;span ng-show="(form.email.$dirty || submitted) &amp;&amp; form.email.$error.required"&gt; Email is required &lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } }; </code></pre> <p>Then, if all that JS inside <code>ng-show</code>expression looks too much for you, you can abstract it into a separate method:</p> <pre class="lang-js prettyprint-override"><code>function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } $scope.hasError = function(field, validation){ if(validation){ return ($scope.form[field].$dirty &amp;&amp; $scope.form[field].$error[validation]) || ($scope.submitted &amp;&amp; $scope.form[field].$error[validation]); } return ($scope.form[field].$dirty &amp;&amp; $scope.form[field].$invalid) || ($scope.submitted &amp;&amp; $scope.form[field].$invalid); }; }; </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;form ng-submit="submit()" name="form"&gt; &lt;div&gt; &lt;input type="email" name="email" ng-model="user.email" required /&gt; &lt;span ng-show="hasError('email', 'required')"&gt;required&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
17,531,684
n-grams in python, four, five, six grams?
<p>I'm looking for a way to split a text into n-grams. Normally I would do something like:</p> <pre><code>import nltk from nltk import bigrams string = "I really like python, it's pretty awesome." string_bigrams = bigrams(string) print string_bigrams </code></pre> <p>I am aware that nltk only offers bigrams and trigrams, but is there a way to split my text in four-grams, five-grams or even hundred-grams?</p> <p>Thanks!</p>
17,547,860
17
3
null
2013-07-08 16:35:31.22 UTC
58
2021-12-28 15:00:28.21 UTC
2015-11-09 03:42:23.547 UTC
null
1,797,250
null
2,001,008
null
1
169
python|string|nltk|n-gram
234,740
<p>Great native python based answers given by other users. But here's the <code>nltk</code> approach (just in case, the OP gets penalized for reinventing what's already existing in the <code>nltk</code> library). </p> <p>There is an <a href="http://www.nltk.org/_modules/nltk/model/ngram.html" rel="noreferrer">ngram module</a> that people seldom use in <code>nltk</code>. It's not because it's hard to read ngrams, but training a model base on ngrams where n > 3 will result in much data sparsity.</p> <pre><code>from nltk import ngrams sentence = 'this is a foo bar sentences and i want to ngramize it' n = 6 sixgrams = ngrams(sentence.split(), n) for grams in sixgrams: print grams </code></pre>
26,254,287
HoughCircles circle detection using opencv and python-
<p>I am trying to use OpenCV's (Hough)Circle detection to.. detect circles. I created a solid circle on a black background, tried to play with the parameters, used blur and everything, but I am just not able to make it find anything. </p> <p>Any ideas, suggestions etc. would be great, thank you!</p> <p>my current code is something like this:</p> <pre><code>import cv2 import numpy as np """ params = dict(dp=1, minDist=1, circles=None, param1=300, param2=290, minRadius=1, maxRadius=100) """ img = np.ones((200,250,3), dtype=np.uint8) for i in range(50, 80, 1): for j in range(40, 70, 1): img[i][j]*=200 cv2.circle(img, (120,120), 20, (100,200,80), -1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) canny = cv2.Canny(gray, 200, 300) cv2.imshow('shjkgdh', canny) gray = cv2.medianBlur(gray, 5) circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1, 20, param1=100, param2=30, minRadius=0, maxRadius=0) print circles circles = np.uint16(np.around(circles)) for i in circles[0,:]: cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2) cv2.circle(img,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('circles', img) k = cv2.waitKey(0) if k == 27: cv2.destroyAllWindows() </code></pre>
26,258,665
3
2
null
2014-10-08 10:07:47.827 UTC
9
2021-09-13 06:43:10.983 UTC
null
null
null
null
3,602,302
null
1
10
python|opencv|geometry|detection
41,967
<p>Your code is working just fine. The problem is in your <code>HoughCircles</code> threshold parameters.</p> <p>Let's try to understand the parameters that you're using from <a href="http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghcircles" rel="noreferrer">OpenCV Docs</a>:</p> <blockquote> <p>param1 – First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller).</p> <p>param2 – Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.</p> </blockquote> <p>So, as you can see, internally the HoughCircles function calls the Canny edge detector, this means that you can use a gray image in the function, instead of their contours.</p> <p>Now reduce the <code>param1</code> to 30 and <code>param2</code> to 15 and see the results in the code that follows:</p> <pre><code>import cv2 import numpy as np img = np.ones((200,250,3), dtype=np.uint8) for i in range(50, 80, 1): for j in range(40, 70, 1): img[i][j]*=200 cv2.circle(img, (120,120), 20, (100,200,80), -1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1, 20, param1=30, param2=15, minRadius=0, maxRadius=0) print circles circles = np.uint16(np.around(circles)) for i in circles[0,:]: cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2) cv2.circle(img,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('circles', img) k = cv2.waitKey(0) if k == 27: cv2.destroyAllWindows() </code></pre> <p><img src="https://i.stack.imgur.com/VFvC8.png" alt="HoughCircles"></p>
23,385,434
A good date converter for Jalali Calendar in Java?
<p>I'm developing a Java App and I have a <code>timeStamp</code> (in <code>long</code>). I can easily use this code to change it to a Gregorian date:</p> <pre><code>Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timeStamp); </code></pre> <p>But I need to have the date in Jalali Calendar. I searched but didn't found any good library. Do you know a reliable and good library for converting (or creating dates in Jalali format from <code>timeStamp</code>)? I don't need an implementation or an algorithm, cause this issue is too buggy and has a lot of rules, I need a reliable solution</p>
23,385,553
5
5
null
2014-04-30 10:16:01.793 UTC
20
2021-05-26 11:56:00.243 UTC
2018-12-07 17:36:49.847 UTC
null
1,841,194
null
374,752
null
1
56
java|date|localization|calendar|jalali-calendar
27,772
<p>Take a look on this: <a href="https://github.com/amirmehdizadeh/JalaliCalendar" rel="noreferrer">https://github.com/amirmehdizadeh/JalaliCalendar</a> </p> <p>The code looks nice, maven based project, a lot of unit tests. </p>
5,448,044
Sass Background Image mixin
<p>I'm kind of new to Sass, but I'm attempting to create a workflow for myself. I generate "color packs" for my theme designs and need to specify the following variables for my mixin. Is there a better way to do this?:</p> <pre><code>// folder,filename,extension,repeat,x-pos,y-pos @mixin background ($folder:style1, $img:file, $type:png, $repeat:no-repeat, $x:0, $y:0) { background-image: url(./images/#{$folder}/#{$img}.#{$type}); background-repeat: #{$repeat}; background-position: #{$x}px #{$y}px; } </code></pre> <p>I'm inserting like so:</p> <pre><code>#nav { @include background(style2,myimage,png,repeat-x,10,10); } </code></pre> <p>which yields this:</p> <pre><code>#nav { background-image: url(./images/style2/myimage.png); background-repeat: repeat-x; background-position: 10px 10px; } </code></pre> <p>I'd prefer to use CSS shorthand when possible, but I ran into errors with the output. I'd appreciate any expert advice if this is not the best way to do it.</p>
5,448,100
3
0
null
2011-03-27 08:24:46.937 UTC
10
2016-06-15 09:03:18.03 UTC
2014-09-30 11:39:52.937 UTC
null
1,696,030
null
674,276
null
1
23
css|haml|sass|compass-sass
106,759
<p>depending on how your packs are structured/applied you might be able to use a loop to generate a bunch of generic styles. See the documentation here: <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#id35">http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#id35</a></p> <p>Do you really need 3 separate components to get your image url? wouldn't: <code>$img</code> and then setting that to <code>/folder/img.ext</code> be far easier?</p> <p>Also, you don't need the <code>#{}</code> for repeat by the way.</p> <p>I hope this is what you're after… the question is not very specific in terms of what you need the outcome to actually be.</p> <p>Cheers, Jannis</p> <p><strong>Update:</strong></p> <p>Okay, I see you've updated your question (thanks for that). I believe this could be a little better for general use:</p> <pre><code>@mixin background($imgpath,$position:0 0,$repeat: no-repeat) { background: { image: url($imgpath); position: $position; repeat: $repeat; } } .testing { @include background('/my/img/path.png'); } </code></pre> <p>This will then output:</p> <pre><code>.testing { background-image: url("/my/img/path.png"); background-position: 0 0; background-repeat: no-repeat; } </code></pre> <p>Or you can use the shorthand version:</p> <pre><code>@mixin backgroundShorthand($imgpath,$position:0 0,$repeat: no-repeat) { background: transparent url(#{$imgpath}) $repeat $position; } .testing2 { @include backgroundShorthand('/my/img/path.png'); } </code></pre> <p>Which will generate:</p> <pre><code>.testing2 { background: transparent url(/my/img/path.png) no-repeat 0 0; } </code></pre> <p>Lastly <em>if you want to specify your base path to your image directory separately</em> you can do the following:</p> <pre><code>$imagedir:'/static/images/'; // define the base path before the mixin @mixin backgroundShorthandWithExternalVar($filename,$position:0 0,$repeat: no-repeat) { background: transparent url(#{$imagedir}#{$filename}) $repeat $position; } .testing3 { @include backgroundShorthandWithExternalVar('filename.png'); } </code></pre> <p>This will then generate:</p> <pre><code>.testing3 { background: transparent url(/static/images/filename.png) no-repeat 0 0; } </code></pre> <p>Is this what you needed?</p> <p>If not feel free to update the question or reply/comment.</p>
5,279,733
Slide down and slide up div on click
<p>I am using the following code to open and close a div ( slide up/down ) using js</p> <p>I have the slide down event attached to a button and the slide up event sttached to close text.</p> <p>What I want is the button onclick to open and onclick again close the slide element.</p> <p>Here is the JS</p> <pre><code>// slide down effect $(function(){ $('.grabPromo').click(function(){ var parent = $(this).parents('.promo'); $(parent).find('.slideDown').slideDown(); }); $('.closeSlide').click(function(){ var parent = $(this).parents('.promo'); $(parent).find('.slideDown').slideUp(); }); }); </code></pre> <p>The HTML:</p> <pre><code>&lt;span class="grabPromo"&gt;Open&lt;/span&gt; </code></pre> <p>and in the slide down area i have</p> <pre><code>&lt;a class="closeSlide"&gt;Close&lt;/a&gt; </code></pre> <p>Any help appreciated.</p> <p>Ideally I want a down pointing arrow on the slide down button and a up pointing arrow to replace it to slide up on same button. And do away with the close link altogether.</p> <p>Any help appreciated. Cheers</p>
5,279,818
4
0
null
2011-03-12 00:04:11.223 UTC
null
2020-12-24 14:50:00.56 UTC
2011-03-12 00:06:53.287 UTC
null
459,688
null
501,173
null
1
6
javascript|jquery
73,818
<p>try this. it allows multiple items so isn't ID specific. and supports any content loaded via AJAX as well. <a href="http://jsfiddle.net/UezUj/1/" rel="noreferrer">jsfiddle is here</a></p> <pre><code>&lt;div class='toggle_parent'&gt; &lt;div class='toggleHolder'&gt; &lt;span class='toggler'&gt;Open&lt;/span&gt; &lt;span class-'toggler' style='display:none;'&gt;Close&lt;/span&gt; &lt;/div&gt; &lt;div class='toggled_content' style='display:none;'&gt; My Content &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and </p> <pre><code>$('.toggler').live('click',function(){ $(this).parent().children().toggle(); //swaps the display:none between the two spans $(this).parent().parent().find('.toggled_content').slideToggle(); //swap the display of the main content with slide action }); </code></pre>
9,598,629
MDM workflow in Android
<p><em>Can any one help me out how to do MDM Integration in Android from client and server prespective?</em></p> <p>I want to do an enterprise application which having lock and wipe functionality. I have no any clue of workflow of MDM in Android. </p> <p>Thanks.</p>
11,663,694
3
4
null
2012-03-07 09:17:45.123 UTC
12
2017-06-17 12:45:03.587 UTC
null
null
null
null
1,109,344
null
1
22
android|workflow|mdm
11,226
<p><em>Android <a href="http://developer.android.com/guide/topics/admin/device-admin.html" rel="nofollow noreferrer">Device Admin API</a> will do both things what you want to do (lock/wipe device and even more). <a href="http://developer.android.com/guide/topics/admin/device-admin.html" rel="nofollow noreferrer">An example</a> is given and also you can find this <a href="http://developer.android.com/tools/samples/index.html" rel="nofollow noreferrer">complete source code</a> in your Android SDK directory.</em></p> <p><strong><em>Now as client server perspective:</em></strong></p> <p>You have to implement your task (lock and wipe) in your android application (in client, i.e. known as agent). Now your application <strong><em>should be capable to communicate</em></strong> with your server or vice-verse.</p> <p>I am 100% agree with <a href="https://stackoverflow.com/users/293929/adamk">adamk</a> as he said "Remote controlling your application remains exclusively your responsibility - the Android framework does not provide (or enforce) any solution for that."</p> <p>And Android gives your this feature too, as <a href="https://stackoverflow.com/users/293929/adamk">adamk</a> said to use C2DM, he was right but now <strong><em>C2DM is deprecated</em></strong>, and <a href="http://developer.android.com/guide/google/gcm/index.html" rel="nofollow noreferrer">GCM</a> has been introduced, <em><code>“a service that helps developers send data from servers to their Android applications on Android devices.” The service can send a message of up to 4 kb to an application on an Android device, most often to tell the application to retrieve a larger set of data. GCM will now handle all queueing and delivery for messages to Android applications.</code></em></p> <p>You should read <a href="http://developer.android.com/guide/google/gcm/gs.html" rel="nofollow noreferrer">how to use GCM</a>, and you can find sample code too. Download GCM Android Library from SDK Manager <img src="https://i.stack.imgur.com/cHHoU.png" alt="enter image description here"> and check <code>android-sdk/extras/google/GCM</code> directory </p> <p><strong><em>After establishing successful communication between your agent and server, evaluate msg in agent sent by server and perform desire action (lock/ wipe).</em></strong> This is again up to you how you define your message payload and how you handle those payloads in agent application. </p> <p>Here is an article about <a href="http://intrepidusgroup.com/insight/2012/03/android-mdm-part-i-build-up/" rel="nofollow noreferrer">Android MDM.</a></p> <p><strong><em>Happy Coding :)</em></strong></p>
9,446,387
How to retry urllib2.request when fails?
<p>When <code>urllib2.request</code> reaches timeout, a <code>urllib2.URLError</code> exception is raised. What is the pythonic way to retry establishing a connection?</p>
9,446,765
4
5
null
2012-02-25 17:46:16.157 UTC
20
2020-09-01 19:04:56.433 UTC
2020-07-27 09:35:59.01 UTC
null
8,192,635
null
288,280
null
1
38
python|decorator|urllib2|urllib3
32,522
<p>I would use a <a href="http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/">retry</a> decorator. There are other ones out there, but this one works pretty well. Here's how you can use it:</p> <pre><code>@retry(urllib2.URLError, tries=4, delay=3, backoff=2) def urlopen_with_retry(): return urllib2.urlopen("http://example.com") </code></pre> <p>This will retry the function if <code>URLError</code> is raised. Check the link above for documentation on the parameters, but basically it will retry a maximum of 4 times, with an exponential backoff delay doubling each time, e.g. 3 seconds, 6 seconds, 12 seconds.</p>
18,646,756
How to run function in AngularJS controller on document ready?
<p>I have a function within my angular controller, I'd like this function to be run on document ready but I noticed that angular runs it as the dom is created.</p> <pre><code> function myController($scope) { $scope.init = function() { // I'd like to run this on document ready } $scope.init(); // doesn't work, loads my init before the page has completely loaded } </code></pre> <p>Anyone know how I can go about this?</p>
18,646,795
10
0
null
2013-09-05 22:09:20.527 UTC
76
2019-05-31 01:19:35.317 UTC
2019-05-31 01:19:35.317 UTC
null
1,540,468
null
257,558
null
1
261
javascript|angularjs|onload
424,456
<p>We can use the <code>angular.element(document).ready()</code> method to attach callbacks for when the document is ready. We can simply attach the callback in the controller like so:</p> <pre><code>angular.module('MyApp', []) .controller('MyCtrl', [function() { angular.element(document).ready(function () { document.getElementById('msg').innerHTML = 'Hello'; }); }]); </code></pre> <p><a href="http://jsfiddle.net/jgentes/stwyvq38/1/">http://jsfiddle.net/jgentes/stwyvq38/1/</a></p>
19,954,485
extract multiple directories using git-filter-branch
<p>I have a big repository which currently contains multiple projects in top level subfolders, say <code>/a</code>, <code>/b</code>, <code>/c</code>, and <code>/d</code>.</p> <p>Now I want to split up that repository into two different repositories: one containing <code>/a</code> and <code>/b</code> and the other containing <code>/c</code> and <code>/d</code>.</p> <p>I am aware of <code>git filter-branch --subdirectory-filter</code>, which is perfect for extracting a single directory, but it seems not to be able to extract multiple directories at once.</p> <p>I am also aware of <code>git filter-branch --prune-empty --tree-filter</code>, which would allow me to delete everything, but the two wanted directories. This feels not completely right, as I have to manually specify all toplevel directories that might exist.</p> <p>Is there a better way to extract two directories out of a big repository?</p> <p>PS: Of course any good solution using something other than <code>git filter-branch</code> is fine. ;)</p>
19,957,874
4
3
null
2013-11-13 12:59:31.04 UTC
24
2020-09-08 13:18:40.873 UTC
2013-11-13 15:58:11.62 UTC
null
1,870,481
null
1,870,481
null
1
26
git|git-svn|git-rebase|git-filter-branch
11,442
<p>Use</p> <pre><code>git filter-branch -f --prune-empty --tree-filter 'bash preserve-only.sh a b' -- --all </code></pre> <p>where <code>preserve-only.sh</code> is:</p> <pre><code>IFS=':' GLOBIGNORE="$*" rm -rf * </code></pre> <p>This should remove everything but <code>a</code> and <code>b</code> from all commits of all branches, which should be the same as extracting exactly the given directories.</p> <p>To complete the actual split you can use a filter like <code>rm -rf a b</code> to get all the changes not extracted in the first run.</p> <hr> <p>Update: While trying to speed things up using <code>--index-filter</code> I came to an even easier solution:</p> <pre><code>git filter-branch -f --prune-empty --index-filter \ 'git rm --cached -r -q -- . ; git reset -q $GIT_COMMIT -- a b' -- --all </code></pre> <p>This just removes everything and afterwards restores the given directories afterwards.</p>
15,205,750
Breakpoint will not currently be hit. No executable code associated with this line
<p>I have a class in a .h file:</p> <pre><code>class Blah { public: Blah(){} virtual ~Blah(){} void WriteMessage( bool MessageReceived ) { if(MessageReceived) { cout &lt;&lt; "Message Recieved\n"; } } }; </code></pre> <p>I was trying to figure out why my code isn't working, so I set a breakpoint on the conditional inside the <code>WriteMessage()</code> funcition, but as soon as I started running the project in debug mode the breakpoint faded out and the tooltip for it said:</p> <blockquote> <p>Breakpoint will not currently be hit.<br> No executable code associated with this line.</p> </blockquote> <p>I have no idea why this is happening, because all of my other member functions for other classes work just fine when implemented in the .h file. What is causing this?</p> <p><strong>Edit:</strong> Okay as requested, here's a stripped down version of the real code I'm working with:</p> <p><strong>VimbaBridgeAPI.h</strong> (header file for .dll)</p> <pre><code>#pragma once #ifdef VIMBABRIDGEAPI_EXPORTS #define VIMBABRIDGEAPI_API __declspec(dllexport) #else #define VIMBABRIDGEAPI_API __declspec(dllimport) #endif #include "AlCamIncludes.h" #include "VimbaSystem.h" //////////////////////////////////////////// // Global Variables /////////////////////// //////////////////////////////////////////// extern HBITMAP hbit; extern CEdit* global_filenamehandle; //////////////////////////////////////////// // Global Flags /////////////////////////// //////////////////////////////////////////// extern bool imageReady; extern bool take_picture; using namespace AVT::VmbAPI; VIMBABRIDGEAPI_API void BridgedGetImage(FramePtr framepoint, VmbUchar_t** imgDat); VIMBABRIDGEAPI_API HBITMAP ExternalFrameRecieved( const FramePtr pFrame ); ////////////////////////////////////////////////////////////////////////// ////////// MyObserver class /////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// class VIMBABRIDGEAPI_API MyObserver : public IFrameObserver { private: MyObserver( MyObserver&amp; ); MyObserver&amp; operator=( const MyObserver&amp; ); //class member variables //BITMAPINFO* pbmi; CEdit* m_filenameedit; public: MyObserver(CameraPtr pCamera) : IFrameObserver(pCamera) {} virtual ~MyObserver() {} void FrameReceived ( const FramePtr pFrame ); }; </code></pre> <p><strong>NOTE:</strong> IFrameObserver is not written by me, but the FrameReceived function is a pure virtual declared in the IFrameObserver class. Their documentation says that FrameRecieved gets called by their API whenever a frame comes in, and I had to implement the function. I have tested this functions and it works, but only when defined outside the class (inside I get the error I'm getting now)</p> <p><strong>VimbaBridgeAPI.cpp</strong> (code hidden from user)</p> <pre><code>void FrameRecieved( const FramePtr pFrame ) { DbgMsg(L"Frame Received\n"); //////////////////////////////////////////////////////////////////////// ////////// Setup Bitmap //////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //// FILEHEADER //// BITMAPFILEHEADER* bf = new BITMAPFILEHEADER; bf-&gt;bfType = 0x4d42; bf-&gt;bfSize = 6054400 + 54 + sizeof(BITMAPINFO); bf-&gt;bfOffBits = 54; //// INFOHEADER //// BITMAPINFOHEADER* bih = new BITMAPINFOHEADER; bih-&gt;biSize = 40; bih-&gt;biWidth = 2752; bih-&gt;biHeight = -2200; bih-&gt;biPlanes = 1; bih-&gt;biBitCount = 32; bih-&gt;biCompression = 0; //bi-&gt;biSizeImage = 6054400; //not required bih-&gt;biXPelsPerMeter = 2835; bih-&gt;biYPelsPerMeter = 2835; bih-&gt;biClrUsed = 0; bih-&gt;biClrImportant = 0; //// INFO //// BITMAPINFO* pbmi = (BITMAPINFO*)alloca( sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256); pbmi-&gt;bmiHeader.biSize = sizeof (pbmi-&gt;bmiHeader); pbmi-&gt;bmiHeader.biWidth = 2752; pbmi-&gt;bmiHeader.biHeight = -2200; pbmi-&gt;bmiHeader.biPlanes = 1; pbmi-&gt;bmiHeader.biBitCount = 8; pbmi-&gt;bmiHeader.biCompression = BI_RGB; pbmi-&gt;bmiHeader.biSizeImage = 0; pbmi-&gt;bmiHeader.biXPelsPerMeter = 14173; pbmi-&gt;bmiHeader.biYPelsPerMeter = 14173; pbmi-&gt;bmiHeader.biClrUsed = 0; pbmi-&gt;bmiHeader.biClrImportant = 0; //create grayscale color palette for(int i=0; i&lt;256; i++) { pbmi-&gt;bmiColors[i].rgbRed = BYTE(i); pbmi-&gt;bmiColors[i].rgbGreen = BYTE(i); pbmi-&gt;bmiColors[i].rgbBlue = BYTE(i); pbmi-&gt;bmiColors[i].rgbReserved = BYTE(0); } //// IMAGE DATA //// VmbUchar_t* imageData = NULL; BridgedGetImage(pFrame, &amp;imageData); ////////////////////////////////////////////////////////////////////////// ////// Create image that's printed to dialog box ///////////////////////// ////////////////////////////////////////////////////////////////////////// HDC hdc = ::GetDC(NULL); hbit = CreateDIBitmap(hdc, bih, CBM_INIT, imageData, pbmi, DIB_RGB_COLORS); //clean up DeleteObject(bf); DeleteObject(bih); DeleteObject(hdc); } </code></pre>
15,206,052
9
19
null
2013-03-04 16:03:29.91 UTC
1
2021-01-02 19:40:59.577 UTC
2013-03-04 16:31:38.617 UTC
null
1,963,990
null
1,963,990
null
1
15
c++|windows|visual-studio-2010|class|debugging
42,748
<p>I would suggest you firstly <strong>Delete the output files</strong> : Physically delete all generated DLLs, PDBs and EXEs. Then compile (rebuild) again to generate the files. Sometimes Visual Studio can "get lost" and "forget" to overwrite the output files when you build your solution.</p> <p>This can happen for a few other reasons:</p> <ul> <li>The code the debugger is using is different from the code that the application is running</li> <li>The pdb file that the debugger is using is different from the code that the application is running</li> <li>The code the application is running has been optimized and debug information has been stripped out.</li> <li>The code in which you have breakpoints on hasn't been loaded into the process yet </li> </ul>
15,429,420
Given the IP and netmask, how can I calculate the network address using bash?
<p>In a bash script I have an IP address like 192.168.1.15 and a netmask like 255.255.0.0. I now want to calculate the start address of this network, that means using the &amp;-operator on both addresses. In the example, the result would be 192.168.0.0. Does someone have something like this ready? I'm looking for an elegant way to deal with ip addresses from bash</p>
15,429,733
7
4
null
2013-03-15 10:03:30.717 UTC
11
2021-07-14 18:28:04.637 UTC
2013-03-15 16:19:27.807 UTC
null
20,088
null
20,088
null
1
18
bash|ip|subnet|netmask
36,683
<p>Use bitwise <code>&amp;</code> (<code>AND</code>) operator:</p> <pre><code>$ IFS=. read -r i1 i2 i3 i4 &lt;&lt;&lt; "192.168.1.15" $ IFS=. read -r m1 m2 m3 m4 &lt;&lt;&lt; "255.255.0.0" $ printf "%d.%d.%d.%d\n" "$((i1 &amp; m1))" "$((i2 &amp; m2))" "$((i3 &amp; m3))" "$((i4 &amp; m4))" 192.168.0.0 </code></pre> <p>Example with another IP and mask:</p> <pre><code>$ IFS=. read -r i1 i2 i3 i4 &lt;&lt;&lt; "10.0.14.97" $ IFS=. read -r m1 m2 m3 m4 &lt;&lt;&lt; "255.255.255.248" $ printf "%d.%d.%d.%d\n" "$((i1 &amp; m1))" "$((i2 &amp; m2))" "$((i3 &amp; m3))" "$((i4 &amp; m4))" 10.0.14.96 </code></pre>
15,462,122
Assign console.log value to a variable
<p>How can I assign a JavaScript object to a variable which was printed using <code>console.log</code>? </p> <p>I am in Chrome console. With Ruby I would use <code>test = _</code> to access the most recent item printed. </p>
15,462,376
5
0
null
2013-03-17 14:53:02.36 UTC
8
2019-12-07 20:26:07.93 UTC
2019-12-07 20:26:07.93 UTC
null
42,223
null
830,554
null
1
31
javascript|ruby|console.log|language-comparisons
34,415
<p>You could override standard <code>console.log()</code> function with your own, adding the behaviour you need:</p> <pre><code>console.oldLog = console.log; console.log = function(value) { console.oldLog(value); window.$log = value; }; // Usage console.log('hello'); $log // Has 'hello' in it </code></pre> <p>This way, you don't have to change your existing logging code. You could also extend it adding an array and storing the whole history of printed objects/values.</p>
15,434,817
Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"
<p>I'm trying to use JSTL, but I get the following error:</p> <pre class="lang-none prettyprint-override"><code>Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" </code></pre> <p>How is this caused and how can I solve it? </p>
15,435,124
8
2
null
2013-03-15 14:23:05.987 UTC
17
2020-07-22 07:17:35.79 UTC
2013-03-25 10:16:22.073 UTC
null
573,032
null
2,174,215
null
1
31
java|jsp|jstl
127,935
<p>Use taglib definition in your JSP or better include it in every page by the first line.</p> <pre><code>&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; </code></pre> <p>There's also fix <code>jstl-1.2</code> dependency in your project. Also use servlet specification at least 2.4 in your <code>web.xml</code>. </p> <p>The maven dependencies are (maven is a open source development tool) </p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jstl&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>In the <code>web.xml</code> start writing</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; </code></pre> <p><strong>EDIT:</strong></p> <p>I'd like to add a note that @informatik01 has mentioned in the comment about newer version of JSTL libraries available from Maven repository: <a href="http://search.maven.org/#artifactdetails%7Cjavax.servlet.jsp.jstl%7Cjavax.servlet.jsp.jstl-api%7C1.2.1%7Cjar" rel="noreferrer">JSTL version 1.2.1 API</a> and <a href="http://search.maven.org/#artifactdetails|org.glassfish.web|javax.servlet.jsp.jstl|1.2.1|jar" rel="noreferrer">JSTL 1.2.1</a> .</p>
15,349,761
Get called function name as string
<p>I'd like to display the name of a function I'm calling. Here is my code</p> <pre><code>void (*tabFtPtr [nbExo])(); // Array of function pointers int i; for (i = 0; i &lt; nbExo; ++i) { printf ("%d - %s", i, __function__); } </code></pre> <p>I used <code>__function__</code> as an exemple because it's pretty close from what I'd like but I want to display the name of the function pointed by <code>tabFtPtr [nbExo]</code>.</p> <p>Thanks for helping me :)</p>
15,350,089
2
6
null
2013-03-11 22:16:23.94 UTC
5
2013-03-20 09:27:36.693 UTC
2013-03-11 22:17:54.227 UTC
null
139,010
null
1,033,967
null
1
32
c
34,787
<p>You need a C compiler that follows the C99 standard or later. There is a pre-defined identifier called <code>__func__</code> which does what you are asking for.</p> <pre><code>void func (void) { printf("%s", __func__); } </code></pre> <p>Edit:</p> <p>As a curious reference, the C standard 6.4.2.2 dictates that the above is exactly the same as if you would have explicitly written:</p> <pre><code>void func (void) { static const char f [] = "func"; // where func is the function's name printf("%s", f); } </code></pre> <p>Edit 2:</p> <p>So for getting the name through a function pointer, you could construct something like this:</p> <pre><code>const char* func (bool whoami, ...) { const char* result; if(whoami) { result = __func__; } else { do_work(); result = NULL; } return result; } int main() { typedef const char*(*func_t)(bool x, ...); func_t function [N] = ...; // array of func pointers for(int i=0; i&lt;N; i++) { printf("%s", function[i](true, ...); } } </code></pre>
14,944,333
Get name of a field
<p>Is it possible in Java to get a name of field in string from the actual field? like:</p> <pre><code>public class mod { @ItemID public static ItemLinkTool linkTool; public void xxx{ String fieldsName = *getFieldsName(linkTool)*; } } </code></pre> <p>PS: I'm <strong>not</strong> looking for a field's class/class name or getting Field from name in String.</p> <hr> <p>EDIT: When I'm looking at it I probably wouldn't need a method to get a field's name, the Field instance (from field's "code name") would suffice. [e.g. <code>Field myField = getField(linkTool)</code>] </p> <p>There probably isn't anything like I want in Java itself. I'll take a look at the ASM library, but in the end I might end up using the string as an identifier for fields :/</p> <hr> <p>EDIT2: My english isn't great (but even in my native language I'd have problems explaining this), so I'm adding one more example. Hopefuly it will be more clear now:</p> <pre><code>public class mod2 { @ItemID public static ItemLinkTool linkTool; @ItemID public static ItemLinkTool linkTool2; @ItemID public static ItemPipeWrench pipeWrench; public void constructItems() { // most trivial way linkTool = new ItemLinkTool(getId("linkTool")); linkTool2 = new ItemLinkTool(getId("linkTool2")); pipeWrench = new ItemPipeWrench(getId("pipeWrench")); // or when constructItem would directly write into field just constructItem("linkTool"); constructItem("linkTool2"); constructItem("pipeWrench"); // but I'd like to be able to have it like this constructItemIdeal(linkTool); constructItemIdeal(linkTool2); constructItemIdeal(pipeWrench); } // not tested, just example of how I see it private void constructItem(String name){ Field f = getClass().getField(name); int id = getId(name); // this could be rewritten if constructors take same parameters // to create a new instance using reflection if (f.getDeclaringClass() == ItemLinkTool){ f.set(null, new ItemLinkTool(id)); }else{ f.set(null, new ItemPipeWrench(id)); } } } </code></pre> <p>The question is: how could look the constructItemIdeal method? (From answers and googling around I thing it's not possible in Java, but who knows..)</p>
14,970,042
8
9
null
2013-02-18 20:00:25.763 UTC
10
2022-02-03 07:37:44.33 UTC
2013-02-19 12:59:20.987 UTC
null
1,017,211
null
1,017,211
null
1
39
java|reflection|field
102,173
<p>Unfortunately, there is no way to do what you wish. <em>Why?</em></p> <p>In an era where we are still trying to prove that Java is not slow, storing metadata of where or how an object was constructed would have a large overhead, and since it has a very minimal range of use, it does not exist. Not only that: there are a bunch of technical reasons as well.</p> <p>One reason is because of how the JVM is implemented. The specification for the Java <code>class</code> file format can be found <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html" rel="noreferrer">here</a>. It's quite a mouthful, but it is very informative. </p> <p>As I said previously, an object can be constructed from anywhere, even situations where <em>objects do not have names</em>. Only objects defined as class members have names (for the obvious reason of access): objects constructed in methods do not. The JVM has a local variable table with a maximum of 65535 entries. These are loaded unto the stack and stored into the table via the *load and *store opcodes.</p> <p>In other words, a class like</p> <pre><code>public class Test { int class_member = 42; public Test() { int my_local_field = 42; } } </code></pre> <p>gets compiled into</p> <pre><code>public class Test extends java.lang.Object SourceFile: "Test.java" minor version: 0 major version: 50 Constant pool: --snip-- { int class_member; public Test(); Code: Stack=2, Locals=2, Args_size=1 0: aload_0 1: invokespecial #1; //Method java/lang/Object."&lt;init&gt;":()V 4: aload_0 5: bipush 42 7: putfield #2; //Field class_member:I 10: bipush 42 12: istore_1 13: return LineNumberTable: --snip-- } </code></pre> <p>There, you can see a clear example from <code>javap -v Test</code> that while the name <code>class_member</code>is preserved, the <code>my_local_field</code> has been abstracted to index 1 in the local variable table (0 is reserved for <code>this</code>).</p> <p>This in itself would be a pain for debuggers and such, so a set of attributes (think metadata for class files) was designed. These include the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.12" rel="noreferrer">LocalVariableTable</a>, <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.12" rel="noreferrer">LineNumberTable</a>, and <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.14" rel="noreferrer">LocalVariableTypeTable</a>. These attributes are useful for stacktraces (LineNumberTable), and debuggers (LocalVariableTable and LocalVariableTypeTable). However, these are <em>completely optional to include in files, and there is no guarantee that they are:</em></p> <blockquote> <p>The LineNumberTable attribute is an optional variable-length attribute in the attributes table</p> </blockquote> <p>The same holds for the rest of them.</p> <p>Additionally, most compilers do not produce anything but the LineNumberTable by default, so you'd be out of luck even if it was possible.</p> <p>Basically, it would be quite frustrating for developers to have a <code>getFieldName(object)</code> (which wouldn't be possible in the first place for local variables), and only have it work when those attributes are present. </p> <p>So you are stuck for the foreseeable future with using <code>getField</code> with Strings. Shameless plug: <a href="http://www.jetbrains.com/idea/" rel="noreferrer">IntelliJ</a> seems to handle refactors with reflection quite well: having written Minecraft mods as well I know the feeling, and can say that work in refactoring is significantly reduces by IntelliJ. But the same is probably true for most modern IDEs: I'm sure the big players, Eclipse, Netbeans <em>et al.</em> have well-implemented refactoring systems in place.</p>
45,117,519
iFrames not loading on mobile or tablet
<p>I haven't been able to find an answer that works. I have an iframe (yes, I have to use an iframe on this occasion) that works fine on PC, but won't load on mobile or tablet at all.</p> <p>There is some Javascript on the page but removing it doesn't fix the problem. I have also tried changing the iframe height and width from percentages to fixed values. I have also tried removing all attributes from the iframe other than <code>src</code> and it still doesn't load anything in the iframe.</p> <p>Below is a simplified version of my page, using what I have been able to find from other suggestions.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta content='width=device-width, initial-scale=1.0' name='viewport'&gt; &lt;style type="text/css"&gt; body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; -webkit-backface-visibility: visible; } #content { position:absolute; left: 0; right: 0; bottom: 0; top: 0px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function onFrameLoad() { do stuff }; &lt;/script&gt; &lt;div id="content"&gt; &lt;iframe onload="onFrameLoad(this)" id="app" src="https://subdomain.mydomain.com" frameborder="0" height="100%" width="100%"&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can anyone tell me why it isn't working on mobile? Thanks</p> <p><strong>UPDATE:</strong> Clearing the browser cache on tablet fixed it for that, but doing the same on mobile didn't do anything. I also tried using my friend's iPhone (they have never visited the site before) and it didn't load.</p> <p>The URL I am trying to display in the iframe works in iframes on demo sites like w3schools on my mobile so it's not an <code>x-frame options</code> or browser not allowing any iframes problem (though the x-frame options would stop it working on all devices, but I've checked everything I can think of)</p> <p>I can provide a live example URL via message if required.</p>
45,286,695
4
10
null
2017-07-15 11:13:17.727 UTC
0
2020-09-20 03:55:06.303 UTC
2017-07-17 16:46:38.583 UTC
null
4,952,851
null
4,952,851
null
1
16
android|html|ios|iframe
38,110
<p>The problem was as I had suspected - the URL of the iframe was calling some unsecured elements and certain browsers on mobile and tablet (and Firefox on desktop) do not display anything if the content is mixed between secure and non-secure (my domain is all https).</p> <p>Now that those are fixed and everything is hosted/called securely, clearing the cache completely and reloading the page fixes the problem even on mobile browsers.</p> <p>The reason it was working on tablet and not mobile was purely down to timing and when the different elements https links were broken (redirecting to http instead) and when the different pages were cached.</p>
8,309,261
How to get session attribute with a dynamic key in EL?
<p>If I set session like this:</p> <pre><code>&lt;% session.setAttribute("taintedAttribute", "what ever we want"); %&gt; </code></pre> <p>normally we can get session variable like this in EL</p> <pre><code>${sessionScope.taintedAttribute } </code></pre> <p>But how about if I want to do like this</p> <pre><code>&lt;% String name = "taintedAttribute"; //session.setAttribute(name, "what ever we want"); session.getAttribute(name); %&gt; </code></pre> <p>Then how can we call it in EL?</p> <p>Can EL get something like <code>${sessionScope.---dynamic name ---}</code>?</p> <p>If I do this:</p> <pre><code>&lt;c:set var="name" value="taintedAttribute" /&gt; &lt;c:out value="${sessionScope.[name]}"/&gt; </code></pre> <p>the name will be replaced by <code>taintedAttribute</code> as the same as this line</p> <pre><code>${sessionScope.taintedAttribute} </code></pre> <p>Is that possible? How can I do that?</p>
8,320,924
2
4
null
2011-11-29 10:29:54.67 UTC
3
2011-11-30 03:50:02.53 UTC
2011-11-30 03:50:02.53 UTC
null
157,882
null
868,602
null
1
23
java|jsp|jstl|el
38,188
<pre class="lang-html prettyprint-override"><code>&lt;c:set var="name" value="taintedAttribute" /&gt; &lt;c:out value="${sessionScope.[name]}"/&gt; </code></pre> <p>You were close. Remove the period.</p> <pre class="lang-html prettyprint-override"><code>&lt;c:set var="name" value="taintedAttribute" /&gt; &lt;c:out value="${sessionScope[name]}"/&gt; </code></pre> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/tags/el/info">Our EL wiki page</a></li> <li><a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnaim.html" rel="noreferrer">Java EE 6 tutorial - Examples of EL expressions</a></li> </ul>
8,777,724
Store derived class objects in base class variables
<p>I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible.</p> <p>Imagine this program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class Base { public: virtual void identify () { cout &lt;&lt; &quot;BASE&quot; &lt;&lt; endl; } }; class Derived: public Base { public: virtual void identify () { cout &lt;&lt; &quot;DERIVED&quot; &lt;&lt; endl; } }; int main () { Derived derived; vector&lt;Base&gt; vect; vect.push_back(derived); vect[0].identify(); return 0; } </code></pre> <p>I expected it to print <code>&quot;DERIVED&quot;</code>, because the <code>identify()</code> method is <code>virtual</code>. Instead <code>vect[0]</code> seems to be a <code>Base</code> instance and it prints <code>&quot;BASE&quot;</code>.</p> <p>I guess I could write my own container (probably derived from <code>vector</code>) somehow that is capable of doing this (maybe holding only pointers...).</p> <p>I just wanted to ask if there is a more C++'ish way to do this. AND I would like to be completely <code>vector</code>-compatible (just for convenience if other users should ever use my code).</p>
8,777,747
6
3
null
2012-01-08 13:00:17.107 UTC
36
2022-09-18 21:44:09.6 UTC
2022-06-14 13:37:07.987 UTC
null
3,841,734
null
584,475
null
1
74
c++|polymorphism|object-slicing
55,527
<p>What you are seeing is <strong><a href="http://en.wikipedia.org/wiki/Object_slicing" rel="noreferrer">Object Slicing</a></strong>.<br> You are storing object of Derived class in an vector which is supposed to store objects of Base class, this leads to Object slicing and the derived class specific members of the object being stored get sliced off, thus the object stored in the vector just acts as object of Base class.</p> <p><strong>Solution:</strong> </p> <p>You should store pointer to object of Base class in the vector: </p> <pre><code>vector&lt;Base*&gt; </code></pre> <p>By storing a pointer to Base class there would be no slicing and you can achieve the desired polymorphic behavior as well.<br> Since you ask for a <code>C++ish</code> way of doing this, the right approach is to use a suitable <strong><a href="https://stackoverflow.com/questions/8706192/which-kind-of-pointer-do-i-use-when">Smart pointer</a></strong> instead of storing a raw pointer in the vector. That will ensure you do not have to manually manage the memory, <strong><a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a></strong> will do that for you automatically.</p>
8,399,100
R plot: size and resolution
<p>I have stacked into the question: I need to plot the image with DPI=1200 and specific print size.</p> <p>By default the png looks ok... <img src="https://i.stack.imgur.com/v51Aj.png" alt="enter image description here"></p> <pre><code>png("test.png",width=3.25,height=3.25,units="in",res=1200) par(mar=c(5,5,2,2),xaxs = "i",yaxs = "i",cex.axis=1.3,cex.lab=1.4) plot(perf,avg="vertical",spread.estimate="stddev",col="black",lty=3, lwd=3) dev.off() </code></pre> <p>But when I apply this code, the image became really terrible it's not scaling (fit) to the size that is needed. What did I miss? How to "fit" the image to the plot?</p> <p><img src="https://i.stack.imgur.com/sueTP.png" alt="enter image description here">,</p>
8,400,798
3
4
null
2011-12-06 11:22:40.983 UTC
30
2022-06-21 13:20:52.423 UTC
2011-12-06 12:22:30.82 UTC
null
322,912
null
596,719
null
1
74
r|png|plot
148,657
<p>A reproducible example:</p> <pre><code>the_plot &lt;- function() { x &lt;- seq(0, 1, length.out = 100) y &lt;- pbeta(x, 1, 10) plot( x, y, xlab = "False Positive Rate", ylab = "Average true positive rate", type = "l" ) } </code></pre> <p>James's suggestion of using <code>pointsize</code>, in combination with the various <code>cex</code> parameters, can produce reasonable results.</p> <pre><code>png( "test.png", width = 3.25, height = 3.25, units = "in", res = 1200, pointsize = 4 ) par( mar = c(5, 5, 2, 2), xaxs = "i", yaxs = "i", cex.axis = 2, cex.lab = 2 ) the_plot() dev.off() </code></pre> <hr> <p>Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,</p> <pre><code>library(ggplot2) ggplot_alternative &lt;- function() { the_data &lt;- data.frame( x &lt;- seq(0, 1, length.out = 100), y = pbeta(x, 1, 10) ) ggplot(the_data, aes(x, y)) + geom_line() + xlab("False Positive Rate") + ylab("Average true positive rate") + coord_cartesian(0:1, 0:1) } ggsave( "ggtest.png", ggplot_alternative(), width = 3.25, height = 3.25, dpi = 1200 ) </code></pre>
8,564,833
ios Upload Image and Text using HTTP POST
<p>Thanks for reading.</p> <p>I am new to iOS and I am trying to upload an Image and a text using <code>multi-part form encoding</code> in iOS. </p> <p>The <code>curl</code> equivalent is something like this: <code>curl -F "param1=value1" -F "[email protected]" "<a href="http://some.ip.address:5000/upload" rel="noreferrer">http://some.ip.address:5000/upload</a>"</code></p> <p>The <code>curl</code> command above returns the expected correct response in <code>JSON.</code></p> <p><strong>Problem:</strong> I keep getting a HTTP 400 request which means I am doing something wrong while composing the HTTP POST Body. </p> <p><strong>What I Did:</strong> For some reference, I tried <a href="https://stackoverflow.com/questions/4683559/flickr-api-ios-app-post-size-too-large">Flickr API iOS app &quot;POST size too large!&quot;</a> and <a href="https://stackoverflow.com/questions/5422028/objective-c-how-to-upload-image-and-text-using-http-post">Objective C: How to upload image and text using HTTP POST?</a>. But, I keep getting a HTTP 400. </p> <p>I tried the <code>ASIHttpRequest</code> but had a different problem there (the callback never got called). But, I didn't investigate further on that since I've heard the developer has stopped supporting the library: <a href="http://allseeing-i.com/[request_release]" rel="noreferrer">http://allseeing-i.com/[request_release]</a>; </p> <p>Could someone please help me out?</p>
8,567,771
10
4
null
2011-12-19 17:07:40.417 UTC
111
2019-10-11 07:04:46.94 UTC
2017-05-23 11:55:03.39 UTC
null
-1
null
302,969
null
1
96
ios|file-upload|curl|http-post|image-uploading
140,858
<p>Here's code from my app to post an image to our web server:</p> <pre><code>// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; [_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]]; [_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]]; [_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]]; [_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]]; // the boundary string : a random string, that will not repeat in post data, to separate post data fields. NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"]; // string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ NSString* FileParamConstant = [NSString stringWithString:@"file"]; // the server url to which the image (or the media) is uploaded. Use your server url here NSURL* requestURL = [NSURL URLWithString:@""]; // create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } // add image data NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long) [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; </code></pre>
5,479,691
Is there any standard way of embedding resources into Linux executable image?
<p>It is quite easy to embed binary resources into PE images (EXE, DLL) via Windows API (refer to <a href="http://msdn.microsoft.com/en-us/library/ms648008(v=VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms648008(v=VS.85).aspx</a>). </p> <p><strong>Is there any similar standard API in Linux?</strong></p> <p>or maybe some kind of de-facto approach to resource embedding?</p> <p>The goal is to embed some static binary and/or textual data into executable, e.g. pictures, HTMLs, etc.. so that program binary distribution is as simple as making one file copy? (<em>assuming all library dependencies are ok</em>)</p> <p><strong>Update:</strong> </p> <p>following <em>bdk</em>'s suggestion, I've tried solution described in <a href="https://stackoverflow.com/questions/2627004/embedding-binary-blobs-using-gcc-mingw" title="Embedding binary blobs using gcc mingwquot;">Embedding binary blobs using gcc mingw</a> and it worked for me. Though, there were some issues that are worth mentioning: my project (in Code::Blocks) consists of a number of C++ files and adding binary data into any of corresponding object files rendered them useless breaking the build - <code>objdump -x</code> would show that most of the symbols have gone after embedding (and I didn't find how to fix it). To overcome this issue I added an empty dummy .cpp file into the project with the only purpose of providing an object file to play with and wrote the following custom build step for that file which did the job nicely (example uses Code::Blocks macros):</p> <pre><code>$compiler $options $includes -c $file -o $object ld -Ur -b binary -o $object &lt;binary payload path&gt; </code></pre>
10,692,876
4
2
null
2011-03-29 22:27:52.987 UTC
12
2012-05-21 21:28:07.71 UTC
2017-05-23 12:25:36.667 UTC
null
-1
null
106,688
null
1
26
c++|linux|embedded-resource
16,985
<p>Make yourself an assembler file, blob.S:</p> <pre><code> .global blob .global blob_size .section .rodata blob: .incbin "blob.bin" 1: blob_size: .int 1b - blob </code></pre> <p>Compile with gcc -c blob.S -o blob.o The blob can now be accessed from within your C program with:</p> <pre><code>extern uint8_t blob[]; extern int blob_size; </code></pre> <p>Using a bin2c converter usually works fine, but if the blob is large, the incbin solution is much faster, and uses much less memory (compile time)</p>
5,374,546
Passing ArrayList through Intent
<p>I am trying to pass an arrayList to another activity using intents. Here is the code in the first activity.</p> <pre><code>case R.id.editButton: Toast.makeText(this, "edit was clicked", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, editList.class); intent.putStringArrayListExtra("stock_list", stock_list); startActivity(intent); break; </code></pre> <p>This is where I try to retrieve the list in the second activity. Is something wrong here?</p> <pre><code>Intent i = new Intent(); //This should be getIntent(); stock_list = new ArrayList&lt;String&gt;(); stock_list = i.getStringArrayListExtra("stock_list"); </code></pre>
5,374,603
6
0
null
2011-03-21 06:38:04.497 UTC
17
2019-01-16 13:26:23.393 UTC
2011-03-21 07:09:53.573 UTC
null
382,906
null
382,906
null
1
85
android|arraylist|android-intent
130,388
<p>In your receiving intent you need to do:</p> <pre><code>Intent i = getIntent(); stock_list = i.getStringArrayListExtra("stock_list"); </code></pre> <p>The way you have it you've just created a new empty intent without any extras.</p> <p>If you only have a single extra you can condense this down to:</p> <pre><code>stock_list = getIntent().getStringArrayListExtra("stock_list"); </code></pre>
5,370,482
What's the advantage of load() vs get() in Hibernate?
<p>Can anyone tell me what's the advantage of <code>load()</code> vs <code>get()</code> in Hibernate?</p>
32,964,515
10
0
null
2011-03-20 18:26:10.307 UTC
47
2021-07-19 07:04:09.737 UTC
2019-07-30 10:28:46.317 UTC
null
203,204
null
203,204
null
1
76
java|hibernate
73,919
<h6 id="whats-the-advantage-of-load-vs-get-in-hibernate-ejuc">Whats the advantage of load() vs get() in Hibernate?</h6> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>load()</th> <th>get()</th> </tr> </thead> <tbody> <tr> <td>Only use <code>load()</code> method if you are sure that the object exists.</td> <td>If you are not sure that the object exist, then use one of <code>get()</code> methods.</td> </tr> <tr> <td><code>load()</code> method will throw an exception if the unique id is not found in the database.</td> <td><code>get()</code> method will return null if the unique id is not found in the database.</td> </tr> <tr> <td><code>load()</code> just returns a proxy by default and database won't be hit until the proxy is first invoked.</td> <td><code>get()</code> will hit the database immediately.</td> </tr> </tbody> </table> </div> <p><a href="http://www.developersbook.com/hibernate/interview-questions/hibernate-interview-questions-faqs-2.php" rel="nofollow noreferrer">source</a></p> <p><strong>Proxy</strong> means, hibernate will prepare some fake object with given identifier value in the memory without hitting a database.<br /> <a href="https://i.stack.imgur.com/5HteU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5HteU.jpg" alt="enter image description here" /></a></p> <p><strong>For Example:</strong><br /> If we call <code>session.load(Student.class,new Integer(107));</code></p> <p>hibernate will create one fake Student object [row] in the memory with id 107, but remaining properties of Student class will not even be initialized.</p> <p><a href="http://www.java4s.com/hibernate/difference-between-hibernate-get-and-load-methods/" rel="nofollow noreferrer">Source</a></p>
12,294,400
Windows 7 Command Prompt: How do I execute a batch script from the command line?
<p>I'm using Windows 7, and my problem is running this file from a console (cmd.exe):</p> <pre><code>W:\software\projects\myproject\build\msvc\build.bat </code></pre> <p>When I move into the folder containing the file manually and run it from there using the following command sequence, it works:</p> <pre><code>W:\&gt;cd software W:\software&gt;cd projects W:\software\projects&gt;cd myproject W:\software\projects\myproject&gt;cd build W:\software\projects\myproject\build&gt;cd msvc W:\software\projects\myproject\build\msvc&gt;build.bat </code></pre> <p>However, when I try to run the file from the root directory in any of these ways:</p> <pre><code>W:\&gt;software\projects\myproject\build\msvc\build.bat W:\&gt;call software\projects\myproject\build\msvc\build.bat W:\&gt;@call software\projects\myproject\build\msvc\build.bat W:\&gt;"software\projects\myproject\build\msvc\build.bat" W:\&gt;call "software\projects\myproject\build\msvc\build.bat" W:\&gt;@call "software\projects\myproject\build\msvc\build.bat" </code></pre> <p>I get the following error message:</p> <pre><code>The system cannot find the path specified. </code></pre> <p>I'm pretty sure you didn't have to navigate to the folder containing the file in order to run it when I was using Windows XP (though I could be wrong, of course), but this apparently seems to be the case with Windows 7. Or am I missing something?</p>
12,294,486
1
0
null
2012-09-06 06:47:26.683 UTC
null
2012-09-06 08:35:16.94 UTC
null
null
null
null
877,194
null
1
9
windows-7|batch-file|cmd|command-prompt
48,189
<p>You are correct. You do not need to navigate to the batch scripts folder before executing. The error "The system cannot find the path specified." is most likely caused by something inside your batch-file.</p> <p>Try to add</p> <pre><code>cd W:\software\projects\myproject\build\msvc w: </code></pre> <p>or in a single command (as suggested by James K, Thanks!)</p> <pre><code>cd /d W:\software\projects\myproject\build\msvc </code></pre> <p>Searched a bit more and found this generic solution:</p> <pre><code>cd /d %~dp0 </code></pre> <p>at the top of your batch file to set the working directory to the directory of the script to check whether this is the cause.</p> <p>If you execute your file from W:\ this is where the commands are executed (working directory). It is most likely that your script cannot find some file it uses in this location.</p>
12,177,796
What is the difference between - 1) Preprocessor,linker, 2)Header file,library? Is my understanding correct?
<p>Okay, until this morning I was thoroughly confused between these terms. I guess I have got the difference, hopefully.</p> <p>Firstly, the confusion was that since the preprocessor already includes the header files into the code which contains the functions, what library functions does linker link to the object file produced by the assembler/compiler? Part of the confusion primarily arose due to my ignorance about the difference between a header file and a library.</p> <p>After a bit of googling, and stack-overflowing (is that the term? :p), I gathered that the header file mostly contains the function declarations whereas the actual implementation is in another binary file called the library (I am still not 100% sure about this).</p> <p>So, suppose in the following program:-</p> <pre><code>#include&lt;stdio.h&gt; int main() { printf("whatever"); return 0; } </code></pre> <p>The preprocessor includes the contents of the header file in the code. The compiler/compiler+assembler does its work, and then finally linker combines this object file with another object file which actually has stored the way <code>printf()</code> works.</p> <p>Am I correct in my understanding? I may be way off...so could you please help me? </p> <p><strong>Edit:</strong> I have always wondered about the C++ STL. It always confused me as to what it exactly is, a collection of all those headers or what? Now after reading the responses, can I say that STL is an object file/something that resembles an object file?</p> <p>And also, I thought where I could read the function definitions of functions like <code>pow()</code>, <code>sqrt()</code> etc etc. I would open the header files and not find anything. So, is the function definition in the library in binary unreadable form?</p>
12,181,369
3
3
null
2012-08-29 12:19:20.263 UTC
15
2018-02-13 14:34:34.233 UTC
2018-02-13 14:34:34.233 UTC
null
1,466,970
null
1,443,801
null
1
19
c|compiler-construction|linker|preprocessor|header-files
16,288
<p>A C source file goes through two main stages, (1) the preprocessor stage where the C source code is processed by the preprocessor utility which looks for preprocessor directives and performs those actions and (2) the compilation stage where the processed C source code is then actually compiled to produce object code files.</p> <p>The preprocessor is a utility that does text manipulation. It takes as input a file that contains text (usually C source code) that may contain preprocessor directives and outputs a modified version of the file by applying any directives found to the text input to generate a text output.</p> <p>The file does not have to be C source code because the preprocessor is doing text manipulation. I have seen the C Preprocssor used to extend the <code>make</code> utility by allowing preprossor directives to be included in a make file. The make file with the C Preprocessor directives is run through the C Preprocessor utility and the resulting output then fed into <code>make</code> to do the actual build of the make target.</p> <p><strong>Libraries and linking</strong></p> <p>A library is a file that contains object code of various functions. It is a way to package the output from several source files when they are compiled into a single file. Many times a library file is provided along with a header file (include file), typically with a .h file extension. The header file contains the function declarations, global variable declarations, as well as preprocessor directives needed for the library. So to use the library, you include the header file provided using the <code>#include</code> directive and you link with the library file.</p> <p>A nice feature of a library file is that you are providing the compiled version of your source code and not the source code itself. On the other hand since the library file contains compiled source code, the compiler used to generate the library file must be compatible with the compiler being used to compile your own source code files.</p> <p>There are two types of libraries commonly used. The first and older type is the static library. The second and more recent is the dynamic library (Dynamic Link Library or DLL in Windows and Shared Library or SO in Linux). The difference between the two is when the functions in the library are bound to the executable that is using the library file.</p> <p>The linker is a utility that takes the various object files and library files to create the executable file. When an external or global function or variable is used the C source file, a kind of marker is used to tell the linker that the address of the function or variable needs to be inserted at that point.</p> <p>The C compiler only knows what is in the source it compiles and does not know what is in other files such as object files or libraries. So the linker's job is to take the various object files and libraries and to make the final connections between parts by replacing the markers with actual connections. So a linker is a utility that "links" together the various components, replacing the marker for a global function or variable in the object files and libraries with a link to the actual object code that was generated for that global function or variable. </p> <p>During the linker stage is when the difference between a static library and a dynamic or shared library becomes evident. When a static library is used, the actual object code of the library is included in the application executable. When a dynamic or shared library is used, the object code included in the application executable is code to find the shared library and connect with it when the application is run.</p> <p>In some cases the same global function name may be used in several different object files or libraries so the linker will normally just use the first one it comes across and issue a warning about others found.</p> <p><strong>Summary of compile and link</strong></p> <p>So the basic process for a compile and link of a C program is:</p> <ul> <li><p>preprocessor utility generates the C source to be compiled</p></li> <li><p>compiler compiles the C source into object code generating a set of object files</p></li> <li><p>linker links the various object files along with any libraries into executable file</p></li> </ul> <p>The above is the basic process however when using dynamic libraries it can get more complicated especially if part of the application being generated has dynamic libraries that it is generating.</p> <p><strong>The loader</strong></p> <p>There is also the stage of when the application is actually loaded into memory and execution starts. An operating system provides a utility, the loader, which reads the application executable file and loads it into memory and then starts the application running. The starting point or entry point for the executable is specified in the executable file so after the loader reads the executable file into memory it will then start the executable running by jumping to the entry point memory address.</p> <p>One problem the linker can run into is that sometimes it may come across a marker when it is processing the object code files that requires an actual memory address. However the linker does not know the actual memory address because the address will vary depending on where in memory the application is loaded. So the linker marks that as something for the loader utility to fix when the loader is loading the executable into memory and getting ready to start it running.</p> <p>With modern CPUs with hardware supported virtual address to physical address mapping or translation, this issue of actual memory address is seldom a problem. Each application is loaded at the same virtual address and the hardware address translation deals with the actual, physical address. However older CPUs or lower cost CPUs such as micro-controllers that are lacking the memory management unit (MMU) hardware support for address translation still need this issue addressed. </p> <p><strong>Entry points and the C Runtime</strong></p> <p>A final topic is the C Runtime and the <code>main()</code> and the executable entry point.</p> <p>The C Runtime is object code provided by the compiler manufacturer that contains the entry point for an application that is written in C. The <code>main()</code> function is the entry point provided by the programmer writing the application however this is not the entry point that the loader sees. The <code>main()</code> function is called by the C Runtime after the application is started and the C Runtime code sets up the environment for the application.</p> <p>The C Runtime is not the Standard C Library. The purpose of the C Runtime is to manage the runtime environment for the application. The purpose of the Standard C Library is to provide a set of useful utility functions so that a programmer doesn't have to create their own.</p> <p>When the loader loads the application and jumps to the entry point provided by the C Runtime, the C Runtime then performs the various initialization actions needed to provide the proper runtime environment for the application. Once this is done, the C Runtime then calls the <code>main()</code> function so that the code created by the application developer or programmer starts to run. When the <code>main()</code> returns or when the <code>exit()</code> function is called, the C Runtime performs any actions needed to clean up and close out the application.</p>
12,448,592
How to add delta to python datetime.time?
<p>From:</p> <p><a href="http://docs.python.org/py3k/library/datetime.html#timedelta-objects" rel="noreferrer">http://docs.python.org/py3k/library/datetime.html#timedelta-objects</a></p> <blockquote> <p>A timedelta object represents a duration, the difference between two dates or times.</p> </blockquote> <p>So why i get error with this:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta, time &gt;&gt;&gt; datetime.now() + timedelta(hours=12) datetime.datetime(2012, 9, 17, 6, 24, 9, 635862) &gt;&gt;&gt; datetime.now().date() + timedelta(hours=12) datetime.date(2012, 9, 16) &gt;&gt;&gt; datetime.now().time() + timedelta(hours=12) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' </code></pre>
12,448,721
5
0
null
2012-09-16 16:24:21.497 UTC
6
2022-06-21 23:40:57.887 UTC
null
null
null
null
740,067
null
1
59
python|datetime|time|timedelta
117,715
<p><code>datetime.time</code> objects <a href="https://bugs.python.org/issue1487389#msg54803" rel="noreferrer">do not support addition</a> with <code>datetime.timedelta</code>s.</p> <p>There is one natural definition though, clock arithmetic. You could compute it like this:</p> <pre><code>import datetime as dt now = dt.datetime.now() delta = dt.timedelta(hours = 12) t = now.time() print(t) # 12:39:11.039864 print((dt.datetime.combine(dt.date(1,1,1),t) + delta).time()) # 00:39:11.039864 </code></pre> <p><code>dt.datetime.combine(...)</code> lifts the datetime.time <code>t</code> to a <code>datetime.datetime</code> object, the delta is then added, and the result is dropped back down to a <code>datetime.time</code> object.</p>
12,141,150
From list of integers, get number closest to a given value
<p>Given a list of integers, I want to find which number is the closest to a number I give in input:</p> <pre><code>&gt;&gt;&gt; myList = [4, 1, 88, 44, 3] &gt;&gt;&gt; myNumber = 5 &gt;&gt;&gt; takeClosest(myList, myNumber) ... 4 </code></pre> <p>Is there any quick way to do this?</p>
12,141,207
10
3
null
2012-08-27 11:32:07.733 UTC
68
2021-08-31 09:25:34.933 UTC
2021-08-31 09:25:34.933 UTC
null
4,865,723
null
497,180
null
1
237
python|list|sorting|integer
289,475
<p>If we are not sure that the list is sorted, we could use the <a href="http://docs.python.org/library/functions.html?highlight=min#min" rel="noreferrer">built-in <code>min()</code> function</a>, to find the element which has the minimum distance from the specified number.</p> <pre><code>&gt;&gt;&gt; min(myList, key=lambda x:abs(x-myNumber)) 4 </code></pre> <p>Note that it also works with dicts with int keys, like <code>{1: "a", 2: "b"}</code>. This method takes O(n) time.</p> <hr> <p>If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in <a href="https://stackoverflow.com/a/12141511/224671">@Lauritz's answer</a> which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)</p>
3,455,297
MySQL - using String as Primary Key
<p>I saw a similar post on Stack Overflow already, but wasn't quite satisfied.</p> <p>Let's say I offer a Web service. <a href="http://foo.com/SERVICEID" rel="noreferrer">http://foo.com/SERVICEID</a></p> <p>SERVICEID is a unique String ID used to reference the service (base 64, lower/uppercase + numbers), similar to how URL shortener services generate ID's for a URL.</p> <p>I understand that there are inherent performance issues with comparing strings versus integers. </p> <p>But I am curious of how to maximally optimize a primary key of type String.</p> <p>I am using MySQL, (currently using MyISAM engine, though I admittedly don't understand all the engine differences).</p> <p>Thanks. </p> <p><strong>update</strong> for my purpose the string was actually just a base62 encoded integer, so the primary key was an integer, and since you're not likely to ever exceed bigint's size it just doesn't make too much sense to use anything else (for my particular use case)</p>
3,455,478
3
0
null
2010-08-11 04:31:17.313 UTC
5
2021-09-11 13:50:28.713 UTC
2012-08-23 13:45:32.693 UTC
null
403,682
null
403,682
null
1
37
mysql|optimization|primary-key-design
33,120
<p>There's nothing wrong with using a CHAR or VARCHAR as a primary key.</p> <p>Sure it'll take up a little more space than an INT in many cases, but there are many cases where it is the most logical choice and may even reduce the number of columns you need, improving efficiency, by avoiding the need to have a separate ID field.</p> <p>For instance, country codes or state abbreviations already have standardised character codes and this would be a good reason to use a character based primary key rather than make up an arbitrary integer ID for each in addition.</p>
22,673,218
Default route in Express.js
<p>I'm writing an application with node.js and express.</p> <p>I have setup a default route as this :</p> <pre><code>app.get('/', function(req, res){ res.sendfile('./views/index.html'); }); </code></pre> <p>This works fine when I goto /localhost:port/</p> <p>But in the URL when I type anything after that, /localhost:port/blah I get 404 ERROR which makes sense.</p> <p>I want to setup a default route so that no matter what I type in the URL after localhost:port/ it should all get back the same html file.</p> <p>I tried changing / to * : </p> <pre><code>app.get('*', function(req, res){ res.sendfile('./views/index.html'); }); </code></pre> <p>but after I do this I start getting this error in the console and nothing shows up:</p> <p>Uncaught SyntaxError: Unexpected token &lt; </p> <p>in all of my Javascript files: :3000/scripts/myscript.js:1 </p> <p>somehow my javascript file show the content of HTML</p> <p>===EDIT====</p> <p>I used this and it worked fine for first level urls: like loclhost:port/blah</p> <pre><code>app.use(function(req, res){ res.sendfile('./views/index.html'); }); </code></pre> <p>but when the URLs are multilevel, I see the same problem as described earlier localhost:port/blah/foo The problem here is that router is looking for public directory under /blah folder for all the javascript and CSS files in this case, which does not exist. And it's returning the default HTML file. How do I fix this?</p> <p>==================EDIT POSTING THE WHOLE CODE =========================================</p> <pre><code>var http = require('http'); var express = require('express'); var api = require('./routes/api'); var mongoose = require('mongoose'); var app = express(); mongoose.connect('mongodb://localhost/mydb'); app.set('port', process.env.PORT || 3000); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); app.get('/api/user/:userid', api.getUserInfo); app.get('/', function(req, res){ res.sendfile('./views/index.html'); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); </code></pre> <p>In addition to this, I have an HTML with a myscript linked in it,</p> <pre><code>&lt;script type="text/javascript" src="./scripts/myscript.js" &gt;&lt;/script&gt; </code></pre>
22,673,384
3
4
null
2014-03-26 21:15:13.18 UTC
2
2021-05-02 11:14:37.593 UTC
2019-04-13 08:26:21.03 UTC
null
10,221,765
null
1,870,109
null
1
26
javascript|node.js|express|url-routing
57,735
<p>As stated <a href="https://groups.google.com/d/msg/express-js/aYLM4e1I4XU/jr7YloDfsbkJ" rel="nofollow noreferrer">here</a>, you can add this middleware just after your routing logic:</p> <pre><code> app.use(function(req, res){ res.send(404); }); </code></pre> <p>You might find <a href="https://stackoverflow.com/a/9802006">this answer</a> also useful.</p> <p>Of course, you need to adapt the <code>res.send()</code> part to meet your needs.</p>
22,490,842
Finding the reason for DBUpdateException
<p>When calling <code>DbContext.SaveChanges</code>, I get a DbUpdateException: </p> <blockquote> <p>An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll. Additional information: An error occurred while updating the entries. See the inner exception for details.</p> </blockquote> <p>Unfortunately, there is no inner exception (at least, not as far as I can see). Is there any way to see exactly why <code>SaveChanges</code> threw an exception? At the very least, it would be helpful to see what table SaveChanges tried to update with when the error occured.</p>
22,491,956
9
8
null
2014-03-18 20:55:48.197 UTC
11
2021-08-13 02:49:07.743 UTC
2018-02-27 18:20:03.277 UTC
null
2,780,791
null
292,936
null
1
54
c#|.net|entity-framework
95,870
<p>When it seems that the real exception gets lost somewhere, your best bet is to break on every exception. Regardless of if it's catched or swallowed somewhere, in or out your reach, the debugger will break and allow you to see what's going on.</p> <p>See this MSDN link for more info:</p> <p><a href="https://msdn.microsoft.com/en-us/library/vstudio/d14azbfh(v=vs.110).aspx" rel="nofollow">How to: Break When an Exception is Thrown</a></p>
19,225,372
Waiting for multiple futures?
<p>I'd like to run tasks (worker threads) of the same type, but not more than a certain number of tasks at a time. When a task finishes, its result is an input for a new task which, then, can be started.</p> <p>Is there any good way to implement this with async/future paradigm in C++11?</p> <p>At first glance, it looks straight forward, you just spawn multiple tasks with:</p> <pre><code>std::future&lt;T&gt; result = std::async(...); </code></pre> <p>and, then, run <code>result.get()</code> to get an async result of a task.</p> <p>However, the problem here is that the future objects has to be stored in some sort of queue and be waited one by one. It is, though, possible to iterate over the future objects over and over again checking if any of them are ready, but it's not desired due to unnecessary CPU load.</p> <p>Is it possible somehow to wait for <strong>any</strong> future from a given set to be ready and get its result?</p> <p>The only option I can think of so far is an old-school approach without any async/future. Specifically, spawning multiple worker threads and at the end of each thread push its result into a mutex-protected queue notifying the waiting thread via a condition variable that the queue has been updated with more results. </p> <p>Is there any other better solution with async/future possible?</p>
19,228,992
4
8
null
2013-10-07 12:48:50.703 UTC
13
2021-11-15 09:54:53.683 UTC
2013-10-07 15:55:01.007 UTC
null
1,968
null
565,368
null
1
56
c++|multithreading|c++11
25,596
<p>Thread support in C++11 was just a first pass, and while <code>std::future</code> rocks, it does not support multiple waiting as yet.</p> <p>You can fake it relatively inefficiently, however. You end up creating a helper thread for each <code>std::future</code> (ouch, very expensive), then gathering their "this <code>future</code> is ready" into a synchronized many-producer single-consumer message queue, then setting up a consumer task that dispatches the fact that a given <code>std::future</code> is ready.</p> <p>The <code>std::future</code> in this system doesn't add much functionality, and having tasks that directly state that they are ready and sticks their result into the above queue would be more efficient. If you go this route, you could write wrapper that match the pattern of <code>std::async</code> or <code>std::thread</code>, and return a <code>std::future</code> like object that represents a queue message. This basically involves reimplementing a chunk of the the concurrency library.</p> <p>If you want to stay with <code>std::future</code>, you could create <code>shared_future</code>s, and have each dependent task depend on the set of <code>shared_future</code>s: ie, do it without a central scheduler. This doesn't permit things like abort/shutdown messages, which I consider essential for a robust multi threaded task system.</p> <p>Finally, you can wait for <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4107.html" rel="noreferrer">C++2x</a>, or whenever the concurrency TS is folded into the standard, to solve the problem for you.</p>
8,570,243
Infinite loops in Java
<p>Look at the following infinite <code>while</code> loop in Java. It causes a compile-time error for the statement below it.</p> <pre><code>while(true) { System.out.println("inside while"); } System.out.println("while terminated"); //Unreachable statement - compiler-error. </code></pre> <hr> <p>The following same infinite <code>while</code> loop, however works fine and doesn't issue any errors in which I just replaced the condition with a boolean variable.</p> <pre><code>boolean b=true; while(b) { System.out.println("inside while"); } System.out.println("while terminated"); //No error here. </code></pre> <hr> <p>In the second case also, the statement after the loop is obviously unreachable because the boolean variable <code>b</code> is true still the compiler doesn't complain at all. Why?</p> <hr> <p><strong>Edit :</strong> The following version of <code>while</code> gets stuck into an infinite loop as obvious but issues no compiler errors for the statement below it even though the <code>if</code> condition within the loop is always <code>false</code> and consequently, the loop can never return and can be determined by the compiler at the compile-time itself.</p> <pre><code>while(true) { if(false) { break; } System.out.println("inside while"); } System.out.println("while terminated"); //No error here. </code></pre> <hr> <pre><code>while(true) { if(false) { //if true then also return; //Replacing return with break fixes the following error. } System.out.println("inside while"); } System.out.println("while terminated"); //Compiler-error - unreachable statement. </code></pre> <hr> <pre><code>while(true) { if(true) { System.out.println("inside if"); return; } System.out.println("inside while"); //No error here. } System.out.println("while terminated"); //Compiler-error - unreachable statement. </code></pre> <hr> <p><strong>Edit :</strong> Same thing with <code>if</code> and <code>while</code>.</p> <pre><code>if(false) { System.out.println("inside if"); //No error here. } </code></pre> <hr> <pre><code>while(false) { System.out.println("inside while"); // Compiler's complain - unreachable statement. } </code></pre> <hr> <pre><code>while(true) { if(true) { System.out.println("inside if"); break; } System.out.println("inside while"); //No error here. } </code></pre> <hr> <p>The following version of <code>while</code> also gets stuck into an infinite loop.</p> <pre><code>while(true) { try { System.out.println("inside while"); return; //Replacing return with break makes no difference here. } finally { continue; } } </code></pre> <p>This is because the <code>finally</code> block is always executed even though the <code>return</code> statement encounters before it within the <code>try</code> block itself.</p>
8,570,265
15
6
null
2011-12-20 02:54:06.933 UTC
9
2014-10-11 17:50:13.81 UTC
2014-10-11 17:50:13.81 UTC
null
1,391,249
null
1,037,210
null
1
83
java|halting-problem
13,854
<p>The compiler can easily and unequivocally prove that the first expression <em>always</em> results in an infinite loop, but it's not as easy for the second. In your toy example it's simple, but what if:</p> <ul> <li>the variable's contents were read from a file? </li> <li>the variable wasn't local and could be modified by another thread?</li> <li>the variable relied on some user input?</li> </ul> <p>The compiler is clearly not checking for your simpler case because it's forgoing that road altogether. Why? Because it's <s>much harder</s> forbidden by the spec. See <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21-300-M" rel="nofollow noreferrer">section 14.21</a>:</p> <ul> <li><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21-300-M" rel="nofollow noreferrer">http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21-300-M</a></li> </ul> <p>(By the way, my compiler <em>does</em> complain when the variable is declared <code>final</code>.)</p>
26,053,982
setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
<p>When I try to install <code>odoo-server</code>, I got the following error: </p> <pre><code>error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 </code></pre> <p>Could anyone help me to solve this issue?</p>
26,333,011
36
5
null
2014-09-26 07:12:25.05 UTC
111
2022-07-11 22:31:26.133 UTC
2021-12-14 10:34:43.953 UTC
null
5,471,709
null
3,440,631
null
1
463
python|gcc|pip|odoo
730,152
<p>Try installing these packages.</p> <pre><code>sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libssl-dev sudo easy_install greenlet sudo easy_install gevent </code></pre>
10,966,689
Set Client-Side Accessible Cookie In Express
<p>I'm working on a Node app that uses Express and SocketIO. I want to set a cookie in my Express controller which is then accessible from my client-side Javascript code. Everything that I try doesn't seem to work:</p> <pre><code>res.setHeader('Set-Cookie','test=value'); res.cookie('rememberme', 'yes', { maxAge: 900000 }); </code></pre> <p>Is there something I'm missing here? Thanks in advance!</p>
10,974,675
3
2
null
2012-06-10 06:03:42.137 UTC
13
2017-10-06 08:50:42.127 UTC
null
null
null
null
553,725
null
1
34
node.js|cookies|express|socket.io
29,436
<p>Figured it out! By default Express sets the option httpOnly to true. This means that your cookies cannot be accessed by the client-side Javascript. In order to correctly set cookies accessible on the client just use a snippet like the following:</p> <pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false}); </code></pre> <p>I've also noticed that if you call this command and then call res.redirect, the cookie won't get set. This command needs to be followed by res.render at some point in order for it to work. Not sure why this is.</p>
12,814,117
How to filter rows with null values in any of its columns in SSRS
<p>I want to filter out the output without rows containing null values or blank columns. I am using SQL Server 2012 there is no option named <strong>'Blank'</strong> as in SS2005 where I can filter the rows. I also tried following expression but it gives me error or not showing correct output</p> <pre><code>=IsNothing(Fields!ABC.Value)!= True =Fields!ABC.Value = '' </code></pre> <p>Please suggest the solution.</p>
13,854,952
3
1
null
2012-10-10 07:26:37.34 UTC
4
2021-12-13 03:14:53.937 UTC
2021-12-13 03:14:53.937 UTC
null
1,127,428
null
857,475
null
1
24
ssrs-2008|reporting-services|reportingservices-2005
86,772
<p>We should use the isNothing method in the Expression, change the Text to Boolean and then Value will be "True"</p> <p>for example:</p> <pre><code>Expression =IsNothing(Fields!TestA.Value)&lt;&gt;True (Expression type should be Boolean) Operator = Value =True </code></pre>
12,678,819
How to copy a string of std::string type in C++?
<p>I used the <code>strcpy()</code> function and it only works if I use C-string arrays like:</p> <pre><code>char a[6] = &quot;text&quot;; char b[6] = &quot;image&quot;; strcpy(a,b); </code></pre> <p>but whenever I use</p> <pre><code>string a = &quot;text&quot;; string b = &quot;image&quot;; strcpy(a,b); </code></pre> <p>I get this error:</p> <blockquote> <p>functions.cpp: no matching function for call to <code>strcpy(std::string&amp;, std::string&amp;)</code></p> </blockquote> <p>How to copy 2 strings of string data type in C++?</p>
12,678,854
4
2
null
2012-10-01 18:23:31.087 UTC
11
2020-06-23 21:56:27.3 UTC
2020-06-23 21:56:27.3 UTC
null
12,139,179
null
1,032,593
null
1
53
c++|string|copy
160,342
<p>You shouldn't use <code>strcpy()</code> to copy a <code>std::string</code>, only use it for <a href="http://www.cprogramming.com/tutorial/lesson9.html" rel="noreferrer">C-Style strings</a>.</p> <p>If you want to copy <code>a</code> to <code>b</code> then just use the <code>=</code> operator.</p> <pre><code>string a = &quot;text&quot;; string b = &quot;image&quot;; b = a; </code></pre>
12,756,423
Is there an alias for 'this' in TypeScript?
<p>I've attempted to write a class in TypeScript that has a method defined which acts as an event handler callback to a jQuery event.</p> <pre><code>class Editor { textarea: JQuery; constructor(public id: string) { this.textarea = $(id); this.textarea.focusin(onFocusIn); } onFocusIn(e: JQueryEventObject) { var height = this.textarea.css('height'); // &lt;-- This is not good. } } </code></pre> <p>Within the onFocusIn event handler, TypeScript sees 'this' as being the 'this' of the class. However, jQuery overrides the this reference and sets it to the DOM object associated with the event. </p> <p>One alternative is to define a lambda within the constructor as the event handler, in which case TypeScript creates a sort of closure with a hidden _this alias.</p> <pre><code>class Editor { textarea: JQuery; constructor(public id: string) { this.textarea = $(id); this.textarea.focusin((e) =&gt; { var height = this.textarea.css('height'); // &lt;-- This is good. }); } } </code></pre> <p>My question is, is there another way to access the this reference within the method-based event handler using TypeScript, to overcome this jQuery behavior?</p>
12,757,025
12
1
null
2012-10-06 03:26:15.477 UTC
15
2020-06-05 12:38:45.737 UTC
null
null
null
null
51,558
null
1
77
jquery|typescript
31,152
<p>So as stated there is no TypeScript mechanism for ensuring a method is always bound to its <code>this</code> pointer (and this isn't just a jQuery issue.) That doesn't mean there isn't a reasonably straightforward way to address this issue. What you need is to generate a proxy for your method that restores the <code>this</code> pointer before calling your callback. You then need to wrap your callback with that proxy before passing it into the event. jQuery has a built in mechanism for this called <code>jQuery.proxy()</code>. Here's an example of your above code using that method (notice the added <code>$.proxy()</code> call.)</p> <pre><code>class Editor { textarea: JQuery; constructor(public id: string) { this.textarea = $(id); this.textarea.focusin($.proxy(onFocusIn, this)); } onFocusIn(e: JQueryEventObject) { var height = this.textarea.css('height'); // &lt;-- This is not good. } } </code></pre> <p>That's a reasonable solution but I've personally found that developers often forget to include the proxy call so I've come up with an alternate TypeScript based solution to this problem. Using, the <code>HasCallbacks</code> class below all you need do is derive your class from <code>HasCallbacks</code> and then any methods prefixed with <code>'cb_'</code> will have their <code>this</code> pointer permanently bound. You simply can't call that method with a different <code>this</code> pointer which in most cases is preferable. Either mechanism works so its just whichever you find easier to use.</p> <pre><code>class HasCallbacks { constructor() { var _this = this, _constructor = (&lt;any&gt;this).constructor; if (!_constructor.__cb__) { _constructor.__cb__ = {}; for (var m in this) { var fn = this[m]; if (typeof fn === 'function' &amp;&amp; m.indexOf('cb_') == 0) { _constructor.__cb__[m] = fn; } } } for (var m in _constructor.__cb__) { (function (m, fn) { _this[m] = function () { return fn.apply(_this, Array.prototype.slice.call(arguments)); }; })(m, _constructor.__cb__[m]); } } } class Foo extends HasCallbacks { private label = 'test'; constructor() { super(); } public cb_Bar() { alert(this.label); } } var x = new Foo(); x.cb_Bar.call({}); </code></pre>
13,147,210
HTML Body shows cz-shortcut-listen="true" with Chrome's Developer Tools?
<p>I was testing some HTML code I'm making, and while using the Developer Tools on Google Chrome version 22.0.1229.94 m, I saw the <code>&lt;body&gt;</code> tag has the attribute <code>cz-shortcut-listen="true"</code> (which of course is not on my code). <strong>What does it mean and why is it showing up?</strong> (I tried looking it up in google, but found nothing relevant)</p> <p><img src="https://i.stack.imgur.com/xBiYX.jpg" alt="Screenshot"></p>
13,147,219
1
0
null
2012-10-30 20:35:36.437 UTC
8
2020-12-11 18:57:13.533 UTC
2020-12-11 18:57:13.533 UTC
null
1,046,057
null
1,046,057
null
1
167
html|google-chrome|google-chrome-devtools
62,529
<p>It's being added by the Colorzilla browser extension.</p> <p><a href="https://twitter.com/brianpemberton/status/201455628143689728">https://twitter.com/brianpemberton/status/201455628143689728</a></p>
11,301,138
How to check if variable is string with python 2 and 3 compatibility
<p>I'm aware that I can use: <code>isinstance(x, str)</code> in python-3.x but I need to check if something is a string in python-2.x as well. Will <code>isinstance(x, str)</code> work as expected in python-2.x? Or will I need to check the version and use <code>isinstance(x, basestr)</code>?</p> <p>Specifically, in python-2.x:</p> <pre><code>&gt;&gt;&gt;isinstance(u"test", str) False </code></pre> <p>and python-3.x does not have <code>u"foo"</code></p>
11,301,392
10
2
null
2012-07-02 21:03:29.02 UTC
25
2019-10-07 23:05:41.897 UTC
2018-02-12 13:13:36.447 UTC
null
1,709,587
null
240,004
null
1
184
python|string|python-3.x|python-2.x
100,551
<p>If you're writing 2.x-and-3.x-compatible code, you'll probably want to use <a href="http://packages.python.org/six/#six.string_types" rel="noreferrer">six</a>:</p> <pre><code>from six import string_types isinstance(s, string_types) </code></pre>
16,730,364
Add ArrayList to another ArrayList in java
<p>I am having the following java code, in which I am trying to copy the ArrayList to another ArrayList.</p> <pre class="lang-java prettyprint-override"><code>ArrayList&lt;String&gt; nodes = new ArrayList&lt;String&gt;(); ArrayList NodeList = new ArrayList(); ArrayList list = new ArrayList(); for (int i = 0; i &lt; PropertyNode.getLength() - 1; i++) { Node childNode = PropertyNode.item(i); NodeList Children = childNode.getChildNodes(); if (Children != null) { nodes.clear(); nodes.add(&quot;PropertyStart&quot;); nodes.add(Children.item(3).getTextContent()); nodes.add(Children.item(7).getTextContent()); nodes.add(Children.item(9).getTextContent()); nodes.add(Children.item(11).getTextContent()); nodes.add(Children.item(13).getTextContent()); nodes.add(&quot;PropertyEnd&quot;); } NodeList.addAll(nodes); list.add(NodeList); } </code></pre> <p>I want the &quot;list&quot; array to be in this format:</p> <pre><code>[[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,d,e,f,PropertyEnd],[PropertyStart,......]] </code></pre> <p>But from the above code, the &quot;list&quot; array output is seen like this:</p> <pre><code>[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,....PropertyEnd] </code></pre> <p>I think you might have noticed the difference. I am not able to achieve the result in expected format.</p>
16,730,401
6
3
null
2013-05-24 08:05:46.7 UTC
5
2021-05-31 21:11:17.26 UTC
2021-05-31 21:11:17.26 UTC
null
-1
null
1,522,886
null
1
32
java|arraylist
162,576
<p>Then you need a <code>ArrayList</code> of <code>ArrayLists</code>:</p> <pre><code>ArrayList&lt;ArrayList&lt;String&gt;&gt; nodes = new ArrayList&lt;ArrayList&lt;String&gt;&gt;(); ArrayList&lt;String&gt; nodeList = new ArrayList&lt;String&gt;(); nodes.add(nodeList); </code></pre> <p>Note that <code>NodeList</code> has been changed to <code>nodeList</code>. In <a href="http://java.about.com/od/javasyntax/a/nameconventions.htm" rel="noreferrer">Java Naming Conventions</a> variables start with a lower case. Classes start with an upper case.</p>
16,971,831
Better Way to Prevent IE Cache in AngularJS?
<p>I currently use service/$resource to make ajax calls (GET in this case), and IE caches the calls so that fresh data cannot be retrieved from the server. I have used a technique I found by googling to create a random number and append it to the request, so that IE will not go to cache for the data.</p> <p>Is there a better way than adding the cacheKill to every request?</p> <p>factory code</p> <pre><code>.factory('UserDeviceService', function ($resource) { return $resource('/users/:dest', {}, { query: {method: 'GET', params: {dest: "getDevicesByUserID"}, isArray: true } }); </code></pre> <p>Call from the controller</p> <pre><code>$scope.getUserDevices = function () { UserDeviceService.query({cacheKill: new Date().getTime()},function (data) { //logic }); } </code></pre>
16,994,496
10
3
null
2013-06-06 20:44:01.997 UTC
32
2017-07-14 13:21:19.23 UTC
2013-06-06 20:49:43.563 UTC
null
205,859
null
1,119,895
null
1
60
caching|angularjs
64,805
<p>As binarygiant requested I am posting my comment as an answer. I have solved this problem by adding No-Cache headers to the response on server side. Note that you have to do this for GET requests only, other requests seems to work fine.</p> <p>binarygiant posted how you can do this on node/express. You can do it in ASP.NET MVC like this:</p> <pre><code>[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] public ActionResult Get() { // return your response } </code></pre>
16,857,450
How to register users in Django REST framework?
<p>I'm coding a REST API with <a href="http://www.django-rest-framework.org/" rel="noreferrer">Django REST framework</a>. The API will be the backend of a social mobile app. After following the tutorial, I can serialise all my models and I am able to create new resources and update them.</p> <p>I'm using AuthToken for authentication.</p> <p>My question is:</p> <p>Once I have the <code>/users</code> resource, I want the app user to be able to register. So, is it better to have a separate resource like <code>/register</code> or allow anonymous users to POST to <code>/users</code> a new resource?</p> <p>Also, some guidance about permissions would be great.</p>
17,749,567
11
1
null
2013-05-31 12:36:27.55 UTC
70
2021-09-05 07:50:28.683 UTC
2016-02-11 03:27:32.603 UTC
null
1,402,846
null
788,180
null
1
100
django|python-2.7|django-models|django-rest-framework
103,165
<p>I went ahead and made my own custom view for handling registration since my serializer doesn't expect to show/retrieve the password. I made the url different from the /users resource.</p> <p>My url conf:</p> <pre><code>url(r'^users/register', 'myapp.views.create_auth'), </code></pre> <p>My view:</p> <pre><code>@api_view(['POST']) def create_auth(request): serialized = UserSerializer(data=request.DATA) if serialized.is_valid(): User.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'] ) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>I may be wrong, but it doesn't seem like you'll need to limit permissions on this view since you'd want unauthenticated requests ...</p>
9,985,013
How do you draw a line across a multiple-figure environment in R?
<p>Take a very simple example, <code>mfrow=c(1,3)</code>; each figure is a different histogram; how would I draw a horizontal line (akin to <code>abline(h=10)</code>) that went across <em>all</em> 3 figures? (That is, even the margins between them.) Obviously, I could add an abline to each figure, but that's not what I want. I can think of a very complicated way to do this by <em>really</em> only having 1 figure, and drawing each 'figure' within it using <code>polygon</code> etc. That would be ridiculous. Isn't there an easy way to do this?</p>
9,985,936
3
1
null
2012-04-02 23:02:31.72 UTC
8
2012-04-04 16:56:55.04 UTC
null
null
null
null
1,217,536
null
1
11
r|graph
4,740
<p>As @joran noted, the <strong>grid</strong> graphical system offers more flexible control over arrangement of multiple plots on a single device.</p> <p>Here, I first use <code>grconvertY()</code> to query the location of a height of 50 on the y-axis <em>in units of</em> "normalized device coordinates". (i.e. as a proportion of the total height of the plotting device, with 0=bottom, and 1=top). I then use <strong>grid</strong> functions to: (1) push a <code>viewport</code> that fills the device; and (2) plot a line at the height returned by <code>grconvertY()</code>.</p> <pre><code>## Create three example plots par(mfrow=c(1,3)) barplot(VADeaths, border = "dark blue") barplot(VADeaths, border = "yellow") barplot(VADeaths, border = "green") ## From third plot, get the "normalized device coordinates" of ## a point at a height of 50 on the y-axis. (Y &lt;- grconvertY(50, "user", "ndc")) # [1] 0.314248 ## Add the horizontal line using grid library(grid) pushViewport(viewport()) grid.lines(x = c(0,1), y = Y, gp = gpar(col = "red")) popViewport() </code></pre> <p><img src="https://i.stack.imgur.com/jOMq2.png" alt="enter image description here"></p> <p><strong>EDIT</strong>: @joran asked how to plot a line that extends from the y-axis of the 1st plot to the edge of the last bar in the 3rd plot. Here are a couple of alternatives:</p> <pre><code>library(grid) library(gridBase) par(mfrow=c(1,3)) # barplot #1 barplot(VADeaths, border = "dark blue") X1 &lt;- grconvertX(0, "user", "ndc") # barplot #2 barplot(VADeaths, border = "yellow") # barplot #3 m &lt;- barplot(VADeaths, border = "green") X2 &lt;- grconvertX(tail(m, 1) + 0.5, "user", "ndc") # default width of bars = 1 Y &lt;- grconvertY(50, "user", "ndc") ## Horizontal line pushViewport(viewport()) grid.lines(x = c(X1, X2), y = Y, gp = gpar(col = "red")) popViewport() </code></pre> <p><img src="https://i.stack.imgur.com/7CSQB.png" alt="enter image description here"></p> <p>Finally, here's an <em>almost</em> equivalent, and more generally useful approach. It employs the functions <code>grid.move.to()</code> and <code>grid.line.to()</code> demo'd by Paul Murrell in the article linked to in @mdsumner's answer:</p> <pre><code>library(grid) library(gridBase) par(mfrow=c(1,3)) barplot(VADeaths); vps1 &lt;- do.call(vpStack, baseViewports()) barplot(VADeaths) barplot(VADeaths); vps3 &lt;- do.call(vpStack, baseViewports()) pushViewport(vps1) Y &lt;- convertY(unit(50,"native"), "npc") popViewport(3) grid.move.to(x = unit(0, "npc"), y = Y, vp = vps1) grid.line.to(x = unit(1, "npc"), y = Y, vp = vps3, gp = gpar(col = "red")) </code></pre>