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
1,243,079
How to examine SharedPreferences from adb shell?
<p>Now that we can <a href="http://developer.android.com/guide/developing/tools/adb.html#sqlite" rel="noreferrer">Examining sqlite3 Databases from a Remote Shell</a>, is it possible to examine SharedPreferences from adb shell? Since it would be much more convenient to examine and manipulate SharedPreferences from command line when debugging.</p> <p>Or put in another way, in what files SharedPreferences are saved, and how to view and modify these files?</p>
1,243,134
8
0
null
2009-08-07 05:45:00.357 UTC
17
2020-10-14 09:41:50.173 UTC
2016-01-09 14:23:00.56 UTC
null
1,221,313
null
56,149
null
1
46
android|adb|android-sharedpreferences
39,163
<p>Fine, I found the file just after I raised the question above. (It seem asking questions publicly stimulate me to search answers by myself much more diligently, since I don't want my dear peers to view me as a lazy programmer.)</p> <p>It is an XML file under <code>/data/data/your.app.package.name/shared_prefs</code>, and the file name is your.app.package.name_preferences.xml. It is really easy to modify the preferences when you figure out that the content is just a key-value map.</p>
314,800
Best way to define true, false, unset state
<p>If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.</p> <p>What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?</p>
314,809
10
1
null
2008-11-24 17:11:18.053 UTC
1
2019-04-27 18:30:02.807 UTC
null
null
null
Tom Martin
5,303
null
1
28
java|boolean
39,464
<pre><code>Boolean a = true; Boolean b = false; Boolean c = null; </code></pre> <p>I would use that. It's the most straight-forward.</p> <p>Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:</p> <pre><code>public enum ThreeState { TRUE, FALSE, TRALSE }; </code></pre> <p>There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass <code>true</code> and <code>false</code>. If you don't like the <code>null</code>, since it's telling rather little about its meaning here, you can still make a <code>public static final Boolean tralse = null;</code> in your class.</p>
497,992
Why are Virtual Machines necessary?
<p>I was reading <a href="https://stackoverflow.com/questions/453610/javas-virtual-machine-and-clr">this question</a> to find out the differences between the Java Virtual Machine and the .NET CLR and Benji's answer got me wondering why Virtual Machines are necessary in the first place.</p> <p>From my understanding of Benji's explanation, the JIT compiler of a Virtual Machine interprets the intermediate code into the actual assembly code that runs on the CPU. The reason it has to do this is because CPUs often have different numbers of registers and according to Benji, "some registers are special-purpose, and each instruction expects its operands in different registers." This makes sense then that there is a need for an intermediary interpreter like the Virtual Machine so that the same code can be run on any CPU.</p> <p>But, if that's the case, then what I don't understand is why C or C++ code compiled into machine code is able to run on any computer as long as it is the correct OS. Why then would a C program I compiled on my Windows machine using a Pentium be able to run on my other Windows machine using an AMD?</p> <p>If C code can run on any CPU then what is the purpose of the Virtual Machine? Is it so that the same code can be run on any OS? I know Java has VM versions on pretty much any OS but is there a CLR for other OS's besides Windows?</p> <p>Or is there something else I'm missing? Does the OS do some other interpretation of assembly code it runs to adapt it to the particular CPU or something?</p> <p>I'm quite curious about how all this works, so a clear explanation would be greatly appreciated.</p> <p>Note: The reason I didn't just post my queries as comments in the JVM vs. CLR question is because I don't have enough points to post comments yet =b.</p> <p>Edit: Thanks for all the great answers! So it seems what I was missing was that although all processors have differences there is a common standardization, primarily the X86 architecture, which provides a large enough set of common features so that the C code compiled on one X86 processor will work for the most part on another X86 processor. This furthers the justification for Virtual Machines, not to mention I forgot about the importance of garbage collection.</p>
498,052
10
0
null
2009-01-31 01:42:04.133 UTC
16
2015-06-11 09:44:53.66 UTC
2017-05-23 12:02:11.563 UTC
null
-1
null
8,784
null
1
30
compiler-construction|vm-implementation
4,943
<p>The AMD and intel processors use the same instruction set and machine architecture (from the standpoint of execution of machine code).</p> <p>C and C++ compilers compile to machine code, with headers appropriate to the OS they are targeted at. Once compiled they cease to associate in any way, shape, or form with the language they were compiled in and are merely binary executables. (there are artifacts taht may show what language it was compiled from, but that isn't the point here)</p> <p>So once compiled, they are associated to the machine (X86, the intel and amd instruction set and architecture) and the OS.</p> <p>This is why they can run on any compatible x86 machine, and any compatible OS (win95 through winvista, for some software).</p> <p>However, they cannot run on an OSX machine, even if it's running on an intel processor - the binary isn't compatible unless you run additional emulation software (such as parallels, or a VM with windows).</p> <p>Beyond that, if you want to run them on an ARM processor, or MIPS, or PowerPC, then you have to run a full machine instruction set emulator that interprets the binary machine code from X86 into whatever machine you're running it on.</p> <p>Contrast that with .NET.</p> <p>The .NET virtual machine is fabricated as though there were much better processors out in the world - processors that understand objects, memory allocation and garbage collection, and other high level constructs. It's a very complex machine and can't be built directly in silicon now (with good performance) but an emulator can be written that will allow it to run on any existing processor.</p> <p>Suddenly you can write one machine specific emulator for any processor you want to run .NET on, and then ANY .NET program can run on it. No need to worry about the OS or the underlying CPU architecture - if there's a .NET VM, then the software will run.</p> <p>But let's go a bit further - once you have this common language, why not make compilers that convert any other written language into it?</p> <p>So now you can have a C, C#, C++, Java, javascript, Basic, python, lua, or any other language compiler that converts written code so it'll run on this virtual machine.</p> <p>You've disassociated the machine from the language by 2 degrees, and with not too much work you enable anyone to write any code and have it run on any machine, as long as a compiler and a VM exists to map the two degrees of separation.</p> <p>If you're still wondering why this is a good thing, consider early DOS machines, and what Microsoft's <em>real</em> contribution to the world was:</p> <p>Autocad had to write drivers for each printer they could print to. So did lotus 1-2-3. In fact, if you wanted your software to print, you had to write your own drivers. If there were 10 printers, and 10 programs, then 100 different pieces of essentially the same code had to be written separately and independently. </p> <p>What windows 3.1 tried to accomplish (along with GEM, and so many other abstraction layers) is make it so the printer manufacturer wrote one driver for their printer, and the programmer wrote one driver for the windows printer class. </p> <p>Now with 10 programs and 10 printers, only 20 pieces of code have to be written, and since the microsoft side of the code was the same for everyone, then examples from MS meant that you had very little work to do.</p> <p>Now a program wasn't restricted to just the 10 printers they chose to support, but all the printers whose manufacturers provided drivers for in windows.</p> <p>The same issue is occurring in application development. There are really neat applications I can't use because I don't use a MAC. There is a ton of duplication (how many world class word processors do we really need?).</p> <p>Java was meant to fix this, but it had many limitations, some of which aren't really solved.</p> <p>.NET is closer, but no one is developing world-class VMs for platforms other than Windows (mono is so close... and yet not quite there).</p> <p>So... That's why we need VMs. Because I don't want to limit myself to a smaller audience simply because they chose an OS/machine combination different from my own.</p> <p>-Adam</p>
1,300,057
Internet Explorer 6 emulator recommendation
<p>What good tool can be recommended for emulating Internet Explorer 6? I would rather not have to go and install an old copy of Windows XP somewhere.</p>
1,300,068
11
1
null
2009-08-19 13:46:59.947 UTC
14
2021-04-30 10:01:02.09 UTC
2011-01-18 20:21:39.847 UTC
null
63,550
null
117,215
null
1
51
testing|internet-explorer-6|emulation
59,174
<p><a href="http://www.microsoft.com/Downloads/details.aspx?FamilyID=21eabb90-958f-4b64-b5f1-73d0a413c8ef&amp;displaylang=en" rel="nofollow noreferrer">Microsoft offer a number of Virtual PC images with various versions of IE for download.</a></p> <p>They now also offer <a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/" rel="nofollow noreferrer">VMs to run VirtualBox, VMware and Parallels on Windows, OSX and Linux.</a></p>
787,239
What is a dynamic language, and why doesn't C# qualify?
<p>Listening to a podcast, I heard that C# is not dynamic language while Ruby is.</p> <p>What is a "dynamic language"? Does the existence of dynamic languages imply that there are static languages?</p> <p>Why is C# a dynamic language and what other languages are dynamic? If C# is <em>not</em> dynamic, why is Microsoft pushing it strongly to the market?</p> <p>As well why most of .NET programmers are going crazy over it and leaving other languages and moving to C#?</p> <p>Why is Ruby "the language of the future"? </p>
787,253
12
8
2009-04-24 19:30:15.867 UTC
2009-04-24 19:30:15.88 UTC
10
2017-12-03 03:17:34.957 UTC
2012-06-20 15:58:06.373 UTC
null
229,044
null
66,493
null
1
31
c#|ruby|static-libraries|dynamic-languages
32,142
<h2>What is a dynamic language?</h2> <p>Whether or not a language is dynamic typically refers to the type of binding the compiler does: static or late binding. </p> <p>Static binding simply means that the method (or method hierarchy for virtual methods) is bound at compile time. There may be a virtual dispatch involved at runtime but the method token is bound at compile time. If a suitable method does not exist at compile time you will receive an error. </p> <p>Dynamic languages are the opposite. They do their work at runtime. They do little or no checking for the existence of methods at compile time but instead do it all at runtime. </p> <h2>Why is C# not a dynamic language?</h2> <p>C#, prior to 4.0, is a statically bound language and hence is not a dynamic language. </p> <h2>Why is Ruby the language of the future?</h2> <p>This question is based on a false premise, namely that there does exist one language that is the future of programming. There isn't such a language today because no single language is the best at doing all the different types of programming that need to be done. </p> <p>For instance Ruby is a great language for a lot of different applications: web development is a popular one. I would not however write an operating system in it.</p>
1,163,761
Capture screenshot of active window?
<p>I am making a screen capturing application and everything is going fine. All I need to do is capture the active window and take a screenshot of this active window. Does anyone know how I can do this?</p>
1,163,781
12
2
null
2009-07-22 08:08:41.27 UTC
134
2020-11-23 16:51:41.663 UTC
2014-04-11 16:43:02.383 UTC
null
719,034
null
141,831
null
1
201
c#|screenshot|active-window
362,226
<pre><code>ScreenCapture sc = new ScreenCapture(); // capture entire screen, and save it to a file Image img = sc.CaptureScreen(); // display image in a Picture control named imageDisplay this.imageDisplay.Image = img; // capture this window, and save it sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif); </code></pre> <p><a href="http://www.developerfusion.com/code/4630/capture-a-screen-shot/" rel="noreferrer">http://www.developerfusion.com/code/4630/capture-a-screen-shot/</a></p>
845,060
What is the difference between 'my' and 'our' in Perl?
<p>I know what <code>my</code> is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does <code>our</code> do?</p> <p>How does <code>our</code> differ from <code>my</code>?</p>
885,888
12
0
null
2009-05-10 10:24:53.97 UTC
60
2021-11-05 21:27:26.58 UTC
2019-11-20 13:07:17.35 UTC
null
63,550
null
1,084
null
1
203
perl|scope
125,209
<p>How does <em><strong><code>our</code></strong></em> differ from <em><strong><code>my</code></strong></em> and what does <em><code>our</code></em> do?</p> <p>In Summary:</p> <p>Available since Perl 5, <em><strong><code>my</code></strong></em> is a way to declare non-package variables, that are:</p> <ul> <li>private</li> <li>new</li> <li>non-global</li> <li>separate from any package, so that the variable <em>cannot</em> be accessed in the form of <code>$package_name::variable</code>.</li> </ul> <br> <p>On the other hand, <em><strong><code>our</code></strong></em> variables are package variables, and thus automatically:</p> <ul> <li><em>global</em> variables</li> <li>definitely <em>not private</em></li> <li>not necessarily new</li> <li><em>can</em> be accessed outside the package (or lexical scope) with the qualified namespace, as <code>$package_name::variable</code>.</li> </ul> <br> <p>Declaring a variable with <em><strong><code>our</code></strong></em> allows you to predeclare variables in order to use them under <em><code>use strict</code></em> without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete <em><code>use vars</code></em>, which was only file-scoped, and not lexically scoped as is <em><strong><code>our</code></strong></em>.</p> <p>For example, the formal, qualified name for variable <code>$x</code> inside <code>package main</code> is <code>$main::x</code>. Declaring <em><strong><code>our $x</code></strong></em> allows you to use the bare <code>$x</code> variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses <em><code>use strict</code></em> or <em><code>use strict &quot;vars&quot;</code></em>. The scope might be one, or two, or more packages, or one small block.</p>
1,117,211
How would I tint an image programmatically on iOS?
<p>I would like to tint an image with a color reference. The results should look like the Multiply blending mode in Photoshop, where <em>whites</em> would be replaced with <em>tint</em>:</p> <p><img src="https://i.stack.imgur.com/CqiUz.png" alt="alt text"></p> <p>I will be changing the color value continuously.</p> <p><strong>Follow up:</strong> I would put the code to do this in my ImageView's drawRect: method, right?</p> <p>As always, a <em>code snippet</em> would greatly aid in my understanding, as opposed to a link.</p> <p><strong>Update:</strong> Subclassing a UIImageView with the code <strong>Ramin</strong> suggested. </p> <p>I put this in viewDidLoad: of my view controller:</p> <pre><code>[self.lena setImage:[UIImage imageNamed:kImageName]]; [self.lena setOverlayColor:[UIColor blueColor]]; [super viewDidLoad]; </code></pre> <p>I see the image, but it is not being tinted. I also tried loading other images, setting the image in IB, and calling setNeedsDisplay: in my view controller.</p> <p><strong>Update</strong>: drawRect: is not being called.</p> <p><strong>Final update:</strong> I found an old project that had an imageView set up properly so I could test Ramin's code and it works like a charm!</p> <p><strong>Final, final update:</strong></p> <p>For those of you just learning about Core Graphics, here is the simplest thing that could possibly work.</p> <p>In your subclassed UIView:</p> <pre><code>- (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); // don't make color too saturated CGContextFillRect(context, rect); // draw base [[UIImage imageNamed:@"someImage.png"] drawInRect: rect blendMode:kCGBlendModeOverlay alpha:1.0]; // draw image } </code></pre>
1,118,005
13
3
null
2009-07-12 23:38:02.05 UTC
67
2019-04-25 08:34:27.397 UTC
2019-04-25 08:34:27.397 UTC
null
1,033,581
null
23,973
null
1
87
ios|cocoa-touch|image-processing|uiimage|tint
57,825
<p>First you'll want to subclass UIImageView and override the drawRect method. Your class needs a UIColor property (let's call it overlayColor) to hold the blend color and a custom setter that forces a redraw when the color changes. Something like this:</p> <pre><code>- (void) setOverlayColor:(UIColor *)newColor { if (overlayColor) [overlayColor release]; overlayColor = [newColor retain]; [self setNeedsDisplay]; // fires off drawRect each time color changes } </code></pre> <p>In the drawRect method you'll want to draw the image first then overlay it with a rectangle filled with the color you want along with the proper blending mode, something like this:</p> <pre><code>- (void) drawRect:(CGRect)area { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); // Draw picture first // CGContextDrawImage(context, self.frame, self.image.CGImage); // Blend mode could be any of CGBlendMode values. Now draw filled rectangle // over top of image. // CGContextSetBlendMode (context, kCGBlendModeMultiply); CGContextSetFillColor(context, CGColorGetComponents(self.overlayColor.CGColor)); CGContextFillRect (context, self.bounds); CGContextRestoreGState(context); } </code></pre> <p>Ordinarily to optimize the drawing you would restrict the actual drawing to only the area passed in to drawRect, but since the background image has to be redrawn each time the color changes it's likely the whole thing will need refreshing.</p> <p>To use it create an instance of the object then set the <code>image</code> property (inherited from UIImageView) to the picture and <code>overlayColor</code> to a UIColor value (the blend levels can be adjusted by changing the alpha value of the color you pass down).</p>
653,368
How to create a decorator that can be used either with or without parameters?
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is that at all possible?</p> <p>Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve.</p>
14,412,901
14
3
null
2009-03-17 08:10:19.76 UTC
33
2022-02-11 20:00:37.867 UTC
2022-02-11 20:00:37.867 UTC
null
355,230
gooli
15,109
null
1
120
python|decorator
25,452
<p>I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read.</p> <p>Like thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see if there is a single argument and it is callabe (NOTE: extra checks will be necessary if your decorator only takes 1 argument and it happens to be a callable object):</p> <pre><code>def decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # called as @decorator else: # called as @decorator(*args, **kwargs) </code></pre> <p>In the first case, you do what any normal decorator does, return a modified or wrapped version of the passed in function.</p> <p>In the second case, you return a 'new' decorator that somehow uses the information passed in with *args, **kwargs.</p> <p>This is fine and all, but having to write it out for every decorator you make can be pretty annoying and not as clean. Instead, it would be nice to be able to automagically modify our decorators without having to re-write them... but that's what decorators are for! </p> <p>Using the following decorator decorator, we can deocrate our decorators so that they can be used with or without arguments:</p> <pre><code>def doublewrap(f): ''' a decorator decorator, allowing the decorator to be used as: @decorator(with, arguments, and=kwargs) or @decorator ''' @wraps(f) def new_dec(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # actual decorated function return f(args[0]) else: # decorator arguments return lambda realf: f(realf, *args, **kwargs) return new_dec </code></pre> <p>Now, we can decorate our decorators with @doublewrap, and they will work with and without arguments, with one caveat:</p> <p>I noted above but should repeat here, the check in this decorator makes an assumption about the arguments that a decorator can receive (namely that it can't receive a single, callable argument). Since we are making it applicable to any generator now, it needs to be kept in mind, or modified if it will be contradicted.</p> <p>The following demonstrates its use:</p> <pre><code>def test_doublewrap(): from util import doublewrap from functools import wraps @doublewrap def mult(f, factor=2): '''multiply a function's return value''' @wraps(f) def wrap(*args, **kwargs): return factor*f(*args,**kwargs) return wrap # try normal @mult def f(x, y): return x + y # try args @mult(3) def f2(x, y): return x*y # try kwargs @mult(factor=5) def f3(x, y): return x - y assert f(2,3) == 10 assert f2(2,5) == 30 assert f3(8,1) == 5*7 </code></pre>
246,961
Algorithm to find articles with similar text
<p>I have many articles in a database (with title,text), I'm looking for an algorithm to find the X most similar articles, something like Stack Overflow's "Related Questions" when you ask a question. </p> <p>I tried googling for this but only found pages about other "similar text" issues, something like comparing every article with all the others and storing a similarity somewhere. SO does this in "real time" on text that I just typed.</p> <p>How?</p>
252,155
15
0
null
2008-10-29 14:16:44.073 UTC
54
2020-08-25 18:29:51.513 UTC
2018-09-03 16:35:15.703 UTC
null
1,915,854
Osama ALASSIRY
25,544
null
1
63
string|algorithm|text|language-agnostic|similarity
37,346
<p><a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="noreferrer">Edit distance</a> isn't a likely candidate, as it would be spelling/word-order dependent, and much more computationally expensive than Will is leading you to believe, considering the size and number of the documents you'd actually be interested in searching.</p> <p>Something like Lucene is the way to go. You index all your documents, and then when you want to find documents similar to a given document, you turn your given document into a query, and search the index. Internally Lucene will be using <a href="http://en.wikipedia.org/wiki/Tf-idf" rel="noreferrer">tf-idf</a> and an <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="noreferrer">inverted index</a> to make the whole process take an amount of time proportional to the number of documents that could possibly match, not the total number of documents in the collection.</p>
657,447
Vim clear last search highlighting
<p>After doing a search in Vim, I get all the occurrences highlighted. How can I disable that? I now do another search for something gibberish that can't be found.</p> <p>Is there a way to just temporarily disable the highlight and then re-enable it when needed again?</p>
657,457
32
6
null
2009-03-18 09:00:32.31 UTC
518
2022-07-04 13:13:03.463 UTC
2020-06-08 20:42:12.403 UTC
null
4,188,795
solomongaby
65,503
null
1
2,232
vim|full-text-search|highlight
633,497
<p>To turn off highlighting until the next search:</p> <pre><code>:noh </code></pre> <p>Or turn off highlighting completely:</p> <pre><code>set nohlsearch </code></pre> <p>Or, to toggle it:</p> <pre><code>set hlsearch! nnoremap &lt;F3&gt; :set hlsearch!&lt;CR&gt; </code></pre>
6,571,312
Can't cast int to bool
<p>I'm facing the problem that C# in my case can't cast the number 1 to bool. In my scenario <code>(bool)intValue</code> doesn't work. I get an <code>InvalidCastException</code>. I know I can use <code>Convert.ToBoolean(...)</code> but I'm just wondering it doesn't work. Any explanation for this?</p> <p>My code is</p> <pre><code>if (actualValueType.Name == "Boolean" || setValueType.Name == "Boolean") { if ((bool)actualValue != (bool)setValue) ... } </code></pre>
6,571,505
11
3
null
2011-07-04 12:15:06.79 UTC
7
2017-05-26 19:11:54.81 UTC
2013-12-02 07:40:56.36 UTC
null
809,277
null
809,277
null
1
52
c#|casting|int|boolean
90,591
<p><code>int</code> and <code>bool</code> can't be converted implicitly (in contrast to C++, for example).</p> <p>It was a <strong>concious decision made by language designers</strong> in order to save code from errors when a number was used in a condition. Conditions need to take a <code>boolean</code> value explicitly.</p> <p>It is not possible to write:</p> <pre><code>int foo = 10; if(foo) { // Do something } </code></pre> <p>Imagine if the developer wanted to compare foo with 20 but missed one equality sign:</p> <pre><code>if(foo = 20) { // Do something } </code></pre> <p>The above code will compile and work - and the side-effects may not be very obvious.</p> <p>Similar improvements were done to <code>switch</code>: you cannot fall from one case to the other - you need an explicit <code>break</code> or <code>return</code>.</p>
6,981,717
Pythonic way to combine for-loop and if-statement
<p>I know how to use both for loops and if statements on separate lines, such as:</p> <pre><code>&gt;&gt;&gt; a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ... if x in a: ... print(x) 0,4,6,7,9 </code></pre> <p>And I know I can use a list comprehension to combine these when the statements are simple, such as:</p> <pre><code>print([x for x in xyz if x in a]) </code></pre> <p>But what I can't find is a good example anywhere (to copy and learn from) demonstrating a complex set of commands (not just "print x") that occur following a combination of a for loop and some if statements. Something that I would expect looks like:</p> <pre><code>for x in xyz if x not in a: print(x...) </code></pre> <p>Is this just not the way python is supposed to work?</p>
6,981,771
11
9
null
2011-08-08 11:56:16.813 UTC
78
2022-05-08 17:47:23.643 UTC
2022-05-08 17:47:23.643 UTC
null
365,102
null
413,143
null
1
358
python|loops|if-statement|for-loop
595,452
<p>You can use <a href="https://www.python.org/dev/peps/pep-0289" rel="noreferrer">generator expressions</a> like this:</p> <pre><code>gen = (x for x in xyz if x not in a) for x in gen: print(x) </code></pre>
15,527,293
Pass an entire model on form submission
<p>I understand that I can use <code>@Html.HiddenFor(m =&gt; m.parameter)</code> and when the form is submitted, that parameter will be passed to the controller. My model has many properties. </p> <p>Is there a shorter way of passing the entire model at once to the controller or must I do it one by one each time?</p>
15,527,597
5
0
null
2013-03-20 15:05:20.713 UTC
3
2018-02-21 18:44:34.83 UTC
2013-04-12 21:16:25.377 UTC
null
727,208
null
807,223
null
1
23
asp.net-mvc|model|form-submit|html.hiddenfor
46,734
<p>The model will be passed to the controller in its entirety, but the values of properties that are not bound by input or hidden fields will be lost. </p> <p>You have to either bind the properties in the form on the client-side, or re-fetch the entity on the server-side.</p> <p>You seem to be asking for something like <code>@Html.HiddenFor(m =&gt; m.Model)</code>, and that is not possible. Sorry</p> <p>One thing to keep in mind, if you have tons of hidden fields, you may be sending more data to the view than you really need. Consider employing view models</p>
15,975,877
MySQL trigger On Insert/Update events
<p>So I have two tables like this...<br></p> <pre><code>ext_words ------------- | id | word | ------------- | 1 | this | ------------- | 2 | that | ------------- | 3 | this | ------------- ext_words_count --------------------- | id | word | count | --------------------- | 1 | this | 2 | --------------------- | 2 | that | 1 | --------------------- </code></pre> <p>I am trying to create a trigger that will:</p> <ul> <li>update <code>ext_words_count.count</code> when <code>ext_words.word</code> is updated. </li> </ul> <p>To further complicate matters, </p> <ul> <li>if <code>ext_words.word</code> does not exist in <code>ext_words_count</code> when <code>ext_words</code> is updated, I would like to insert it into <code>ext_words_count</code> and set <code>count</code> as 1.</li> </ul> <p>I have been looking at similar questions:<br> 1. <a href="https://stackoverflow.com/questions/5991464/before-after-insert-trigger-using-auto-increment-field?rq=1">Before / after insert trigger using auto increment field</a>, and<br> 2. <a href="https://stackoverflow.com/questions/8910617/using-trigger-to-update-table-in-another-database?rq=1">Using Trigger to update table in another database</a><br> trying to combine the 2. Here is what I have so far:</p> <pre><code>DELIMITER $$ CREATE TRIGGER update_count AFTER UPDATE ON ext_words FOR EACH ROW BEGIN UPDATE ext_words_count SET word_count = word_count + 1 WHERE word = NEW.word; END; $$ DELIMITER ; </code></pre> <p>Any advice and direction is greatly appreciated. Or possibly another method that I have overlooked and as always thanks in advance!</p> <p><b>UPDATE:</b><br> I have opted for using 2 triggers, one for INSERT and one for UPDATE because I am not that familiar with conditional statements in MySQL.</p> <pre><code>DELIMITER $$ CREATE TRIGGER insert_word AFTER INSERT ON ext_words FOR EACH ROW BEGIN INSERT IGNORE INTO ext_words_count (word) VALUES (NEW.word); END; $$ DELIMITER ; </code></pre> <p>and</p> <pre><code>DELIMITER $$ CREATE TRIGGER update_word AFTER UPDATE ON ext_words FOR EACH ROW BEGIN UPDATE ext_words_count SET word_count = word_count + 1 WHERE word = NEW.word; END; $$ DELIMITER ; </code></pre> <p>The INSERT query is working great, however the UPDATE query is not updating <code>word_count</code>. Is there something I missed in the update query..?</p>
15,978,931
2
5
null
2013-04-12 15:57:40.03 UTC
9
2016-09-08 12:36:42.52 UTC
2017-05-23 12:25:34.51 UTC
null
-1
null
1,272,394
null
1
27
mysql|triggers|insert|insert-update
72,217
<p>With Grijesh's perfect help and his suggestion to use conditional statements, I was able to get <strong>ONE</strong> trigger that does both tasks. Thanks again Grijesh </p> <pre><code> DELIMITER $$ CREATE TRIGGER update_count AFTER INSERT ON ext_words FOR EACH ROW BEGIN IF NOT EXISTS (SELECT 1 FROM ext_words_count WHERE word = NEW.word) THEN INSERT INTO ext_words_count (word) VALUES (NEW.word); ELSE UPDATE ext_words_count SET word_count = word_count + 1 WHERE word = NEW.word; END IF; END $$ DELIMITER; </code></pre>
15,535,937
How to set log level in Winston/Node.js
<p>I am using Winston logging with my Node.js app and have defined a file transport. Throughout my code, I log using either <code>logger.error</code>, <code>logger.warn</code>, or <code>logger.info</code>.</p> <p>My question is, how do I specify the log level? Is there a config file and value that I can set so that only the appropriate log messages are logged? For example, I'd like the log level to be "info" in my development environment but "error" in production.</p>
15,536,506
5
0
null
2013-03-20 22:22:04.32 UTC
3
2020-02-15 15:15:06.483 UTC
2019-07-28 18:05:26.433 UTC
null
964,243
null
1,334,713
null
1
30
node.js|express|winston
45,250
<p>Looks like there is a level option in the options passed covered <a href="https://github.com/flatiron/winston">here</a></p> <p>From that doc:</p> <pre><code>var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ level: 'error' }), new (winston.transports.File)({ filename: 'somefile.log' }) ] }); </code></pre> <p>Now, those examples show passing level in the option object to the console transport. When you use a file transport, I believe you would pass an options object that not only contains the filepath but also the level.</p> <p>That should lead to something like:</p> <pre><code>var logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ filename: 'somefile.log', level: 'error' }) ] }); </code></pre> <p>Per that doc, note also that as of 2.0, it exposes a setLevel method to change at runtime. Look in the <strong>Using Log Levels</strong> section of that doc.</p>
32,627,519
iOS 9 Splash screen is black
<p>My apps' splash screens are all plain black after upgrading to iOS9.</p> <p>Does anybody know why this is? Some of them are using a .xib splash screen and some are using images, but they're all just black now. Does an app have to be built with Xcode 7 for the splash screen to work in iOS9? Has anyone seen some documentation on whether this is an intended breaking change from Apple?</p> <p>Thank you!</p> <p><strong>UPDATE:</strong> Looking through the apps again it seems my older apps, which only had a Launch image and no .xib are still displaying correctly, so the issue seems related to the launch screen .xib</p> <p><strong>UPDATE2:</strong> As <em>hagi</em> pointed out in the comment, after re-installing the very same binary it starts working again so the cause is probably that launch images are generated from the xib whenever the app is installed, and stored somewhere, and then when upgrading to iOS9, for some reason (unintended Apple bug most likely), the generated images are cleared, and the app ends up with no splash. And that's why the old-fashioned launch images are still safe and not affected by this, cause they're already baked into the app.</p> <p>I'll report it as a bug to Apple.</p>
32,666,462
16
7
null
2015-09-17 09:58:12.867 UTC
13
2019-11-28 08:16:58.527 UTC
2015-09-19 09:51:00.573 UTC
null
1,182,897
null
1,182,897
null
1
61
ios|xcode|splash-screen|ios9|xcode7
50,302
<p>Same problem here after I updated to iOS 9. Re-installing the app from the App Store seems to solve the problem. I guess, it's an iOS 9 glitch.</p>
35,919,103
How do I use a regex in a shell script?
<p>I am trying to match a string with a regex in a shell script. This string is a parameter of the script ( $1 ) and it is a date (MM/DD/YYYY) The regex I'm trying to use is : </p> <pre><code>^\d{2}[\/\-]\d{2}[\/\-]\d{4}$ </code></pre> <p>It seems to work, I tried it on several regex tests websites.</p> <p>My shell code is : </p> <pre><code>REGEX_DATE="^\d{2}[\/\-]\d{2}[\/\-]\d{4}$"   echo "$1" | grep -q $REGEX_DATE echo $? </code></pre> <p>The "echo $?" returns 1 no matter is the string I'm putting in parameter.</p> <p>Do you guys have an idea ?</p> <p>Thanks !</p>
35,924,143
3
6
null
2016-03-10 14:23:26.817 UTC
10
2018-10-08 18:27:23.43 UTC
2017-11-29 15:26:29.687 UTC
null
6,045,244
null
6,045,244
null
1
60
regex|bash|shell
144,848
<p>To complement the existing helpful answers:</p> <p>Using <strong>Bash's own regex-matching operator, <code>=~</code></strong>, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:</p> <pre><code>set -- '12-34-5678' # set $1 to sample value kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d [[ $1 =~ $kREGEX_DATE ]] echo $? # 0 with the sample value, i.e., a successful match </code></pre> <p>Note, however, that the <strong>caveat re using flavor-specific regex constructs such as <code>\d</code> equally applies</strong>: While <code>=~</code> supports EREs (<em>extended</em> regular expressions), it also supports the <em>host platform's specific extension</em> - it's a rare case of Bash's behavior being platform-dependent.</p> <p>To remain portable (in the context of Bash), stick to the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04" rel="noreferrer">POSIX ERE</a> specification.</p> <p>Note that <code>=~</code> even allows you to define <strong>capture groups</strong> (parenthesized subexpressions) whose matches you can later access through Bash's special <code>${BASH_REMATCH[@]}</code> array variable.</p> <p>Further notes:</p> <ul> <li><p><code>$kREGEX_DATE</code> is used <em>unquoted</em>, which is necessary for the regex to be recognized as such (quoted parts would be treated as <em>literals</em>).</p></li> <li><p>While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex <em>literals</em> containing <code>\</code>.</p> <ul> <li>E.g., on Linux, where <code>\&lt;</code> is supported to match word boundaries, <code>[[ 3 =~ \&lt;3 ]] &amp;&amp; echo yes</code> doesn't work, but <code>re='\&lt;3'; [[ 3 =~ $re ]] &amp;&amp; echo yes</code> does.</li> </ul></li> <li><p>I've changed variable name <code>REGEX_DATE</code> to <code>kREGEX_DATE</code> (<code>k</code> signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_01" rel="noreferrer">all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables</a>.</p></li> </ul>
10,306,254
Is it possible to block cookies from being set using Javascript or PHP?
<p>A lot of you are probably aware of the new EU privacy law, but for those who are not, it basically means no site operated by a company resident in the EU can set cookies classed as 'non-essential to the operation of the website' on a visitors machine unless given express permission to do so. </p> <p>So, the question becomes how to best deal with this?</p> <p>Browsers obviously have the ability to block cookies from a specific website built in to them. My question is, is there a way of doing something similar using JS or PHP?</p> <p>i.e. intercept any cookies that might be trying to be set (including 3rd party cookies like Analytics, or Facebook), and block them unless the user has given consent.</p> <p>It's obviously possible to delete all cookies once they have been set, but although this amounts to the same thing as not allowing them to be set in the first place, I'm guessing that it's not good enough in this case because it doesn't adhere to the letter of the law.</p> <p>Ideas?</p>
10,828,998
5
3
null
2012-04-24 21:28:03.477 UTC
19
2019-10-08 16:38:09.807 UTC
2012-04-24 22:00:42.37 UTC
null
1,354,771
null
1,354,771
null
1
22
php|javascript|cookies|blocking
34,977
<p>I'm pretty interested in this answer too. I've accomplished what I need to accomplish in PHP, but the JavaScript component still eludes me.</p> <p>Here's how I'm doing it in PHP:</p> <pre><code>$dirty = false; foreach(headers_list() as $header) { if($dirty) continue; // I already know it needs to be cleaned if(preg_match('/Set-Cookie/',$header)) $dirty = true; } if($dirty) { $phpversion = explode('.',phpversion()); if($phpversion[1] &gt;= 3) { header_remove('Set-Cookie'); // php 5.3 } else { header('Set-Cookie:'); // php 5.2 } } </code></pre> <p>Then I have some additional code that turns this off when the user accepts cookies.</p> <p>The problem is that there are third party plugins being used in my site that manipulate cookies via javascript and short of scanning through them to determine which ones access document.cookie - they can still set cookies.</p> <p>It would be convenient if they all used the same framework, so I might be able to override a setCookie function - but they don't.</p> <p>It would be nice if I could just delete or disable document.cookie so it becomes inaccessible...</p> <p>EDIT: It is possible to prevent javascript access to get or set cookies.</p> <pre><code>document.__defineGetter__("cookie", function() { return '';} ); document.__defineSetter__("cookie", function() {} ); </code></pre> <p>EDIT 2: For this to work in IE:</p> <pre><code>if(!document.__defineGetter__) { Object.defineProperty(document, 'cookie', { get: function(){return ''}, set: function(){return true}, }); } else { document.__defineGetter__("cookie", function() { return '';} ); document.__defineSetter__("cookie", function() {} ); } </code></pre>
10,854,329
Spinner : onItemSelected not called when selected item remains the same
<p>I have a <code>OnItemSelectedListener</code> for my <code>Spinner</code>, but it is not called when the selected item is the same as the previous one. Apparently the <code>OnClickListener</code> is not an option for a <code>Spinner</code>. I need to catch everytime a user click on an item. Any idea?</p> <p>Maybe the fact that this <code>Spinner</code> is inside the <code>ActionBar</code> disturbs normal behavior?</p> <pre><code>@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.tracklist_menu, menu); Spinner spinner = (Spinner) menu.findItem(R.id.option_ordering_spinner) .getActionView(); spinner.setAdapter(mSpinnerAdapter); spinner.setSelection(PrefsHelper.getOrderingSpinnerPos(prefs)); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { String str = "selected"; System.out.println(str); if (optionMenuInitialized) { switch (position) { case 0: // rdm getActivity() .sendBroadcast( new Intent( MyIntentAction.DO_RESHUFFLE_PLAYLIST)); smp.setCurrentTracklistCursorPos(-1); trackAdapter.notifyDataSetChanged(); break; case 1: // artist getActivity() .sendBroadcast( new Intent( MyIntentAction.DO_ORDER_PLAYLIST_BY_ARTIST)); smp.setCurrentTracklistCursorPos(-1); trackAdapter.notifyDataSetChanged(); break; case 2: // folder getActivity() .sendBroadcast( new Intent( MyIntentAction.DO_ORDER_PLAYLIST_BY_FOLDER)); smp.setCurrentTracklistCursorPos(-1); trackAdapter.notifyDataSetChanged(); break; } PrefsHelper.setOrderingSpinnerPos(prefEditor, position); prefEditor.commit(); } optionMenuInitialized = true; } @Override public void onNothingSelected(AdapterView&lt;?&gt; parent) { } }); } </code></pre>
11,227,847
11
3
null
2012-06-01 16:46:53.15 UTC
14
2021-11-27 19:06:35.033 UTC
2012-09-04 11:17:17.77 UTC
null
1,300,995
null
1,058,339
null
1
54
android|spinner|listener|android-actionbar|actionbarsherlock
38,492
<p>Ok, I finally found a solution, by creating my own class extending Spinner :</p> <pre><code>public class MySpinner extends Spinner { OnItemSelectedListener listener; public MySpinner(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setSelection(int position) { super.setSelection(position); if (listener != null) listener.onItemSelected(null, null, position, 0); } public void setOnItemSelectedEvenIfUnchangedListener( OnItemSelectedListener listener) { this.listener = listener; } } </code></pre>
10,484,164
What is the latency and throughput of the RDRAND instruction on Ivy Bridge?
<p>I cannot find any info on <a href="http://www.agner.org/optimize/#manuals" rel="noreferrer">agner.org</a> on the latency or throughput of the <a href="http://en.wikipedia.org/wiki/RdRand" rel="noreferrer">RDRAND</a> instruction. However, this processor exists, so the information must be out there.</p> <p>Edit: Actually the newest optimization manual mentions this instruction. It is documented as &lt;200 cycles, and a total bandwidth of at least 500MB/s on Ivy Bridge. But some more in-depth statistics on this instruction would be great since the latency and throughput is variable.</p>
11,042,778
4
5
null
2012-05-07 14:49:21.913 UTC
10
2017-03-07 12:02:37.967 UTC
2012-06-10 16:23:25.75 UTC
null
370,756
null
239,558
null
1
31
assembly|intel|rdrand
6,295
<p>I wrote librdrand. It's a very basic set of routines to use the RdRand instruction to fill buffers with random numbers. </p> <p>The performance data we showed at IDF is from test software I wrote that spawns a number of threads using pthreads in Linux. Each thread pulls fills a memory buffer with random numbers using RdRand. The program measures the average speed and can iterate while varying the number of threads.</p> <p>Since there is a round trip communications latency from each core to the shared DRNG and back that is longer than the time needed to generate a random number at the DRNG, the average performance obviously increases as you add threads, up until the maximum throughput is reached. The physical maximum throughput of the DRNG on IVB is 800MBytes/s. A 4 core IVB with 8 threads manages something of the order of 780Mbytes/s. With fewer threads and cores, lower numbers are achieved. The 500MB/s number is somewhat conservative, but when you're trying to make honest performance claims, you have to be.</p> <p>Since the DRNG runs at a fixed frequency (800MHz) while the core frequencies may vary, the number of core clock cycles per RdRand varies, depending on the core frequency and the number of other cores simultaneously accessing the DRNG. The curves given in the IDF presentation are a realistic representation of what to expect. The total performance is affected a little by core clock frequency, but not much. The number of threads is what dominates.</p> <p>One should be careful when measuring RdRand performance to actually 'use' the RdRand result. If you don't, I.E. you did this.. RdRand R6, RdRand R6,....., RdRand R6 repeated many times, the performance would read as being artificially high. Since the data isn't used before it is overwritten, the CPU pipeline doesn't wait for the data to come back from the DRNG before it issues the next instruction. The tests we wrote write the resulting data to memory that will be in on-chip cache so the pipeline stalls waiting for the data. That is also why hyperthreading is so much more effective with RdRand than with other sorts of code.</p> <p>The details of the specific platform, clock speed, Linux version and GCC version were given in the IDF slides. I don't remember the numbers off the top of my head. There are chips available that are slower and chips available that are faster. The number we gave for &lt;200 cycles per instruction is based on measurements of about 150 core cycles per instruction.</p> <p>The chips are available now, so anyone well versed in the use of rdtsc can do the same sort of test.</p>
24,942,538
SQL won't insert null values with BULK INSERT
<p>I have a CSV file and each line looks similar to this:</p> <pre><code>EASTTEXAS,NULL,BELLVILLE AREA,NULL,BELLVILLE AREA,RGP,NULL,NULL,0,NULL,NULL,NULL,1,1,PM,PM Settings,NULL,NULL </code></pre> <p>I couldn't find any examples on how NULL values were supposed to be handled when doing BULK INSERT, so I assumed that was OK.</p> <p>When I try to run the BULK INSERT, it gives me this error:</p> <blockquote> <p>Msg 4864, Level 16, State 1, Line 28 Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 12 (ClassificationPK).</p> </blockquote> <p>Here's my table and what not:</p> <pre><code>CREATE TABLE #Assets ( ParentID VARCHAR(255) NULL, ClassificationID VARCHAR(255) NULL, AssetID VARCHAR(255) NULL, AssetType VARCHAR(255) NULL, AssetName VARCHAR(255) NULL, RepairCenterID VARCHAR(255) NULL, LaborID VARCHAR(255) NULL, Owner VARCHAR(255) NULL, IsLocation VARCHAR(255) NULL, AssetTypeDesc VARCHAR(255) NULL, ClassificationName VARCHAR(255) NULL, ClassificationPK INT NULL, IsUp BIT NULL, RequesterCanView BIT NULL, PMCycleStartBy VARCHAR(255) NULL, PMCycleStartByDesc VARCHAR(255) NULL, PMCycleStartDate DATETIME NULL, PMCounter INT NULL, ParentPK INT NULL, ParentName VARCHAR(255) NULL, AssetPK INT NULL, RepairCenterPK INT NULL, RepairCenterName VARCHAR(255) NULL, LaborPK INT NULL) BULK INSERT #Assets FROM '\\cdmsqlint01\drop\assets.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', KEEPNULLS ) GO SELECT * FROM #Assets DROP TABLE #Assets </code></pre> <p>Any ideas on what I'm doing wrong here?</p>
24,942,791
2
5
null
2014-07-24 19:38:21.943 UTC
2
2017-06-22 13:46:54.3 UTC
null
null
null
null
1,339,826
null
1
12
sql-server|csv|bulkinsert
38,083
<p>According to: </p> <p><a href="http://msdn.microsoft.com/en-us/library/ms187887.aspx">http://msdn.microsoft.com/en-us/library/ms187887.aspx</a></p> <p>null values can be inserted by having an empty field within your file.</p> <p>Example file was:</p> <pre><code>1,,DataField3 2,,DataField3 </code></pre> <p>Example method of importing file keeping nulls is:</p> <pre><code>USE AdventureWorks; GO BULK INSERT MyTestDefaultCol2 FROM 'C:\MyTestEmptyField2-c.Dat' WITH ( DATAFILETYPE = 'char', FIELDTERMINATOR = ',', KEEPNULLS ); GO </code></pre> <p>Granted, this means you'll have to change your "NULL"s to "", and any empty strings you did want as empty string would be interpreted as nulls, but it might be enough to get you started? I would imagine to keep your empty string columns they would need to be changed from</p> <pre><code>field1,,field2 </code></pre> <p>to</p> <pre><code>field1,"",field2 </code></pre> <p>as example</p>
35,631,903
Raw SQL Query without DbSet - Entity Framework Core
<p>With Entity Framework Core removing <code>dbData.Database.SqlQuery&lt;SomeModel&gt;</code> I can't find a solution to build a raw SQL Query for my full-text search query that will return the tables data and also the rank. </p> <p>The only method I've seen to build a raw SQL query in Entity Framework Core is via <code>dbData.Product.FromSql("SQL SCRIPT");</code> which isn't useful as I have no DbSet that will map the rank I return in the query.</p> <p><strong>Any Ideas???</strong></p>
50,452,479
20
8
null
2016-02-25 15:44:12.02 UTC
48
2022-08-08 14:35:19.353 UTC
2017-03-27 04:11:33.297 UTC
null
1,857,083
null
4,241,818
null
1
219
c#|entity-framework-core
242,595
<h2>If you're using EF Core 3.0 or newer</h2> <p>You need to use <a href="https://docs.microsoft.com/ef/core/modeling/keyless-entity-types?tabs=data-annotations" rel="nofollow noreferrer">keyless entity types</a>, previously known as query types:</p> <blockquote> <p>This feature was added in EF Core 2.1 under the name of query types. In EF Core 3.0 the concept was renamed to keyless entity types. The [Keyless] Data Annotation became available in EFCore 5.0.</p> </blockquote> <p>To use them you need to first mark your class <code>SomeModel</code> with <code>[Keyless]</code> data annotation or through fluent configuration with <code>.HasNoKey()</code> method call like below:</p> <pre><code>public DbSet&lt;SomeModel&gt; SomeModels { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity&lt;SomeModel&gt;().HasNoKey(); } </code></pre> <p>After that configuration, you can use one of the methods <a href="https://docs.microsoft.com/ef/core/querying/raw-sql" rel="nofollow noreferrer">explained here</a> to execute your SQL query. For example you can use this one:</p> <pre><code>var result = context.SomeModels.FromSqlRaw(&quot;SQL SCRIPT&quot;).ToList(); var result = await context.SomeModels.FromSql(&quot;SQL_SCRIPT&quot;).ToListAsync(); </code></pre> <hr /> <h2>If you're using EF Core 2.1</h2> <p>If you're using EF Core 2.1 Release Candidate 1 available since 7 may 2018, you can take advantage of the proposed new feature which is <a href="https://docs.microsoft.com/ef/core/modeling/query-types" rel="nofollow noreferrer">query types</a>:</p> <blockquote> <p>In addition to entity types, an EF Core model can contain query types, which can be used to carry out database queries against data that isn't mapped to entity types.</p> </blockquote> <p>When to use query type?</p> <blockquote> <p>Serving as the return type for ad hoc FromSql() queries.</p> <p>Mapping to database views.</p> <p>Mapping to tables that do not have a primary key defined.</p> <p>Mapping to queries defined in the model.</p> </blockquote> <p>So you no longer need to do all the hacks or workarounds proposed as answers to your question. Just follow these steps:</p> <p>First you defined a new property of type <code>DbQuery&lt;T&gt;</code> where <code>T</code> is the type of the class that will carry the column values of your SQL query. So in your <code>DbContext</code> you'll have this:</p> <pre><code>public DbQuery&lt;SomeModel&gt; SomeModels { get; set; } </code></pre> <p>Secondly use <code>FromSql</code> method like you do with <code>DbSet&lt;T&gt;</code>:</p> <pre><code>var result = context.SomeModels.FromSql(&quot;SQL_SCRIPT&quot;).ToList(); var result = await context.SomeModels.FromSql(&quot;SQL_SCRIPT&quot;).ToListAsync(); </code></pre> <p>Also note that <code>DbContext</code>s are <a href="https://docs.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/partial-classes-and-methods" rel="nofollow noreferrer">partial classes</a>, so you can create one or more separate files to organize your 'raw SQL DbQuery' definitions as best suits you.</p>
40,073,322
Plotting list of lists in a same graph in Python
<p>I am trying to plot <code>(x,y)</code> where as <code>y = [[1,2,3],[4,5,6],[7,8,9]]</code>.</p> <p>Say, <code>len(x) = len(y[1]) = len(y[2])</code>.. The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e, <code>(x, y[1],y[2],y[3],...)</code>. When I tried using loop it says <code>dimension error</code>.</p> <p>I also tried: <code>plt.plot(x,y[i] for i in range(1,len(y)))</code></p> <p>How do I plot ? Please help.</p> <pre><code>for i in range(1,len(y)): plt.plot(x,y[i],label = 'id %s'%i) plt.legend() plt.show() </code></pre>
40,073,609
2
6
null
2016-10-16 17:38:29.623 UTC
3
2021-06-09 06:05:07.57 UTC
2021-06-09 06:05:07.57 UTC
null
7,758,804
null
5,009,494
null
1
19
python|matplotlib|nested-lists
80,110
<p>Assuming some sample values for x, below is the code that could give you the desired output.</p> <pre><code>import matplotlib.pyplot as plt x = [1,2,3] y = [[1,2,3],[4,5,6],[7,8,9]] plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("A test graph") for i in range(len(y[0])): plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i) plt.legend() plt.show() </code></pre> <p>Assumptions: <code>x</code> and any element in <code>y</code> are of the same length. The idea is reading element by element so as to construct the list <code>(x,y[0]'s)</code>, <code>(x,y[1]'s)</code> and <code>(x,y[n]'s</code>.</p> <p>Edited: Adapt the code if <code>y</code> contains more lists.</p> <p>Below is the plot I get for this case: <a href="https://i.stack.imgur.com/0wvlq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0wvlq.png" alt="Sample plot"></a></p>
13,741,946
Role of datanode, regionserver in Hbase-hadoop integration
<p>From my understanding rows are inserted into HBase tables and are getting stored as regions in different region server. So, the region server stores the data</p> <p>Similarly in terms of Hadoop, data is stored in the data nodes present in the hadoop cluster.</p> <p>Lets say that i have HBase 0.90.6 configured on top of Hadoop 1.1.1 as follows</p> <p>2 nodes - master and slave</p> <ol> <li>Master node acts as, <ul> <li>Hadoop - Namenode, Secondary Namenode, job tracker, data node, task tracker</li> <li>HBase - Master, RegionServer and zookeeper.</li> </ul></li> <li>Slave node acts as,<br> <ul> <li>Hadoop datanode and task tracker</li> <li>HBase region server</li> </ul></li> </ol> <p>Based on my statement if table data is stored in the region servers; then what is the role of the data nodes and region servers?</p>
13,742,379
1
0
null
2012-12-06 10:46:10.21 UTC
15
2016-05-04 00:10:15.437 UTC
2014-12-08 05:14:52.993 UTC
null
2,573,335
null
1,605,937
null
1
19
hadoop|hbase
20,349
<p>Data nodes store data. Region server(s) essentially buffer I/O operations; data is permanently stored on HDFS (that is, data nodes). I do not think that putting region server on your 'master' node is a good idea. </p> <p>Here is a simplified picture of how regions are managed:</p> <p>You have a cluster running HDFS (NameNode + DataNodes) with replication factor of 3 (each HDFS block is copied into 3 different DataNodes). </p> <p>You run RegionServers on the same servers as DataNodes. When write request comes to RegionServer it first writes changes into memory and commit log; then at some point it decides that it is time to write changes to permanent storage on HDFS. Here is were data locality comes into play: since you run RegionServer and DataNode on the same server, first HDFS block replica of the file will be written to the same server. Two other replicas will be written to, well, other DataNodes. As a result RegionServer serving the region will almost always have access to local copy of data.</p> <p>What if RegionServer crashes or RegionMaster decided to reassign region to another RegionServer (to keep cluster balanced)? New RegionServer will be forced to perform remote read first, but as soon as compaction is performed (merging of change log into the data) - new file will be written to HDFS by the new RegionServer, and local copy will be created on the RegionServer (again, because DataNode and RegionServer runs on the same server). </p> <p>Note: in case of RegionServer crash, regions previously assigned to it will be reassigned to multiple RegionServers.</p> <p>Good reads:</p> <ul> <li><p>Tom White, "Hadoop, The Definitive Guide" has good explanation of HDFS architecture. Unfortunately I did not read original Google GFS paper, so I cannot tell if it is easy to follow.</p></li> <li><p><a href="http://research.google.com/archive/bigtable-osdi06.pdf">Google BigTable</a> article. HBase is implementation of Google BigTable, and I found that architecture description in this article is the easiest to follow.</p></li> </ul> <p>Here is nomenclature differences between Google Bigtable and HBase implementation (from Lars George, "HBase, The Definitive Guide"):</p> <ul> <li>HBase - Bigtable</li> <li>Region - Tablet</li> <li>RegionServer - Tablet server</li> <li>Flush - Minor compaction</li> <li>Minor compaction - Merging compaction</li> <li>Major compaction - Major compaction</li> <li>Write ahead log - Commit log</li> <li>HDFS - GFS</li> <li>Hadoop MapReduce - MapReduce</li> <li>MemStore - memtable</li> <li>HFile - SSTable</li> <li>Zookeeper - Chubby</li> </ul>
13,542,175
THREE.js Ray Intersect fails by adding div
<p>My Three.js script runs fine when there is only one target div on the page (which holds renderer.domElement). As soon as I add another div with fixed height and width above the target div, ray.intersectObjects returns null. I doubt that the vector that I am creating for ray is causing the problem. Here is the code.</p> <pre><code>var vector = new THREE.Vector3( ( event.clientX / divWidth ) * 2 - 1, -( event.clientY / divHeight ) * 2 + 1, 0.5 ); projector.unprojectVector( vector, camera ); var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() ); var intersects = ray.intersectObjects( myObjects, true ); </code></pre> <p>Any ideas on how I can solve this.</p> <p>EDIT: it is now <code>THREE.Raycaster</code> (three.js r.56)</p>
13,544,277
3
0
null
2012-11-24 14:32:00.503 UTC
13
2022-08-24 16:53:23.187 UTC
2019-05-29 00:52:41.527 UTC
null
6,521,116
null
1,099,235
null
1
20
javascript|html|three.js
14,828
<p>The short answer is you have to take into consideration the <code>offset</code> of the canvas.</p> <p>The long answer depends on how your code is written, so I'll give you two answers, which should cover the bases.</p> <p>There are a lot of possible combinations, so you may have to experiment. Also, different browsers may act differently.</p> <p>Assume your HTML is something like this:</p> <pre><code>#canvas { width: 200px; height: 200px; margin: 100px; padding: 0px; position: static; /* fixed or static */ top: 100px; left: 100px; } &lt;body&gt; &lt;div id=&quot;canvas&quot;&gt; &lt;/body&gt; </code></pre> <p>Your JS is something like this:</p> <pre><code>var CANVAS_WIDTH = 200, CANVAS_HEIGHT = 200; var container = document.getElementById( 'canvas' ); document.body.appendChild( container ); renderer = new THREE.WebGLRenderer(); renderer.setSize( CANVAS_WIDTH, CANVAS_HEIGHT ); container.appendChild( renderer.domElement ); </code></pre> <p><strong>Method 1</strong> For the following method to work correctly, set the canvas position <em>static</em>; margin &gt; 0 and padding &gt; 0 are OK</p> <pre><code>mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / renderer.domElement.clientWidth ) * 2 - 1; mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / renderer.domElement.clientHeight ) * 2 + 1; </code></pre> <p><strong>Method 2</strong> For this alternate method, set the canvas position <em>fixed</em>; set top &gt; 0, set left &gt; 0; padding must be 0; margin &gt; 0 is OK</p> <pre><code>mouse.x = ( ( event.clientX - container.offsetLeft ) / container.clientWidth ) * 2 - 1; mouse.y = - ( ( event.clientY - container.offsetTop ) / container.clientHeight ) * 2 + 1; </code></pre> <p>Here is a Fiddle if you want to experiment: <a href="https://jsfiddle.net/4dnwk39v/" rel="nofollow noreferrer">https://jsfiddle.net/4dnwk39v/</a></p> <p>EDIT: Fiddle updated to three.js r.143</p>
13,550,376
PIL image to array (numpy array to array) - Python
<p>I have a .jpg image that I would like to convert to Python array, because I implemented treatment routines handling plain Python arrays. </p> <p>It seems that PIL images support conversion to numpy array, and according to the documentation I have written this:</p> <pre><code>from PIL import Image im = Image.open("D:\Prototype\Bikesgray.jpg") im.show() print(list(np.asarray(im))) </code></pre> <p>This is returning a list of numpy arrays. Also, I tried with </p> <pre><code>list([list(x) for x in np.asarray(im)]) </code></pre> <p>which is returning nothing at all since it is failing.</p> <p>How can I convert from PIL to array, or simply from numpy array to Python array?</p>
13,550,527
4
1
null
2012-11-25 10:57:52.02 UTC
12
2019-02-04 06:26:05.833 UTC
2015-12-30 15:55:08.62 UTC
null
562,769
null
1,141,493
null
1
24
python|arrays|image|numpy|python-imaging-library
116,827
<p>I think what you are looking for is:</p> <pre><code>list(im.getdata()) </code></pre> <p>or, if the image is too big to load entirely into memory, so something like that:</p> <pre><code>for pixel in iter(im.getdata()): print pixel </code></pre> <p>from <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.getdata" rel="noreferrer">PIL documentation</a>:</p> <blockquote> <p>getdata</p> <p>im.getdata() => sequence</p> <p>Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.</p> <p>Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).</p> </blockquote>
13,678,702
How is the jQuery selector $('#foo a') evaluated?
<p>As a example of jQuery code (<a href="https://coderwall.com/p/7uchvg">https://coderwall.com/p/7uchvg</a>), I read that the expression <code>$('#foo a');</code> behaves like this: </p> <blockquote> <p>Find every <code>a</code> in the page and then filter <code>a</code> inside <code>#foo</code>.</p> </blockquote> <p>And it does not look efficient.</p> <p>Is that correct? And if yes, how should we do that in a better way?</p>
13,678,739
7
2
null
2012-12-03 07:10:46.157 UTC
19
2014-05-19 16:54:01.417 UTC
2014-05-19 16:54:01.417 UTC
null
775,283
null
375,966
null
1
44
javascript|jquery|performance|jquery-selectors|sizzle
5,097
<p>That is correct - Sizzle (jQuery's selector engine) behaves the <a href="http://css-tricks.com/efficiently-rendering-css/">same way as CSS selectors</a>. CSS and Sizzle selectors are <a href="http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-think-right-to-left-with-jquery/">evaluated right-to-left</a>, and so <code>#foo a</code> will find all <code>a</code> nodes, then filter those by nodes that descend from <code>#foo</code>.</p> <p>You improve this by ensuring that your leaf selectors have a high specificity, usually by giving them a class or ID.</p>
13,439,303
Detect click event inside iframe
<p>I'm writing a plugin for TinyMCE and have a problem with detecting click events inside an iframe. </p> <p>From my search I've come up with this:</p> <p>Loading iframe:</p> <pre><code>&lt;iframe src='resource/file.php?mode=tinymce' id='filecontainer'&gt;&lt;/iframe&gt; </code></pre> <p>HTML inside iframe:</p> <pre><code>&lt;input type=button id=choose_pics value='Choose'&gt; </code></pre> <p>jQuery:</p> <pre><code>//Detect click $("#filecontainer").contents().find("#choose_pic").click(function(){ //do something }); </code></pre> <p>Other posts I've seen usually have a problem with different domains (this hasn't). But, still, the event isn't detected. </p> <p>Can something like this be done?</p>
13,782,102
10
2
null
2012-11-18 10:28:58.847 UTC
18
2021-03-01 05:43:44.18 UTC
2017-09-07 10:03:53.223 UTC
null
3,502,164
null
1,833,314
null
1
52
javascript|jquery|html|iframe|tinymce
132,177
<p>I solved it by doing like this:</p> <pre><code>$('#filecontainer').load(function(){ var iframe = $('#filecontainer').contents(); iframe.find("#choose_pics").click(function(){ alert("test"); }); }); </code></pre>
13,359,294
Date.getDay() javascript returns wrong day
<p>Hi I'm new in javascript I have such javascript code</p> <pre><code>alert(DATE.value); var d = new Date(DATE.value); var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDay(); alert(month); alert(day); if(2012 &lt; year &lt; 1971 | 1 &gt; month+1 &gt; 12 | 0 &gt;day &gt; 31){ alert(errorDate); DATE.focus(); return false; } </code></pre> <p>take for instance: <code>DATE.value = "11/11/1991"</code></p> <p>when I call <code>alert(day);</code> it shows me <code>3</code>;<br> when I call <code>alert(d);</code> it is returns me correct info.</p>
13,359,330
8
1
null
2012-11-13 10:42:45.59 UTC
21
2022-03-25 18:45:23.733 UTC
2018-09-17 14:18:56.59 UTC
null
3,995,261
null
1,599,937
null
1
184
javascript|date
114,375
<p>use <code>.getDate</code> instead of <code>.getDay</code>.</p> <blockquote> <p>The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.</p> </blockquote>
13,407,036
How does interfaces with construct signatures work?
<p>I am having some trouble working out how defining constructors in interfaces work. I might be totally misunderstanding something. But I have searched for answers for a good while and I can not find anything related to this. </p> <p>How do I implement the following interface in a TypeScript class: </p> <pre><code>interface MyInterface { new ( ... ) : MyInterface; } </code></pre> <p>Anders Hejlsberg creates an interface containing something similar to this in this <a href="http://media.ch9.ms/ch9/c3e5/e5e02f2e-5962-48db-9ddd-85e27a4fc3e5/IntroducingTSAndersH_mid.mp4">video</a> (at around 14 minutes). But for the life of me I can not implement this in a class.</p> <p>I am probably misunderstanding something, what am I not getting? </p> <p>EDIT: </p> <p>To clarify. With "new ( ... )" I meant "anything". My problem is that I can not get even the most basic version of this working: </p> <pre><code>interface MyInterface { new () : MyInterface; } class test implements MyInterface { constructor () { } } </code></pre> <p>This is not compiling for me I get "Class 'test' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a construct signature, but Type 'test' lacks one" when trying to compile it.</p> <p>EDIT: </p> <p>So after researching this a bit more given the feedback. </p> <pre><code>interface MyInterface { new () : MyInterface; } class test implements MyInterface { constructor () =&gt; test { return this; } } </code></pre> <p>Is not valid TypeScript and this does not solve the problem. You can not define the return type of the constructor. It will return "test". The signature of the following: class test { constructor () { } } Seems to be "new () => test" (obtained by hovering over "class" in the online editor with just that code pasted in). And this is what we would want and what i thought it would be. </p> <p>Can anyone provide an example of this or something similar where it is actually compiling? </p> <p>EDIT (again...):</p> <p>So I might have come up with an idea as to why it is possible to define this in an interface but not possible to implement in a TypeScript class.The following works: </p> <pre><code>var MyClass = (function () { function MyClass() { } return MyClass; })(); interface MyInterface { new () : MyInterface; } var testFunction = (foo: MyInterface) : void =&gt; { } var bar = new MyClass(); testFunction(bar); </code></pre> <p>So is this only a feature of TypeScript that lets you interface javascript? Or is it possible to implement it in TypeScript without having to implement the class using javascript? </p>
13,408,029
8
4
null
2012-11-15 22:03:36.57 UTC
50
2022-08-10 12:32:34.22 UTC
2019-02-13 20:32:52.417 UTC
null
3,345,644
null
1,827,926
null
1
206
typescript|constructor|interface
128,662
<p> Construct signatures in interfaces are not implementable in classes; they're only for defining existing JS APIs that define a 'new'-able function. Here's an example involving interfaces <code>new</code> signatures that does work:</p> <pre class="lang-js prettyprint-override"><code>interface ComesFromString { name: string; } interface StringConstructable { new(n: string): ComesFromString; } class MadeFromString implements ComesFromString { constructor (public name: string) { console.log('ctor invoked'); } } function makeObj(n: StringConstructable) { return new n('hello!'); } console.log(makeObj(MadeFromString).name); </code></pre> <p>This creates an actual constraint for what you can invoke <code>makeObj</code> with:</p> <pre class="lang-js prettyprint-override"><code>class Other implements ComesFromString { constructor (public name: string, count: number) { } } makeObj(Other); // Error! Other's constructor doesn't match StringConstructable </code></pre>
13,744,450
When should we use Observer and Observable?
<p>An interviewer asked me:</p> <p><em>What is <code>Observer</code> and <code>Observable</code> and when should we use them?</em></p> <p>I wasn't aware of these terms, so when I got back home and started Googling about <code>Observer</code> and <code>Observable</code>, I found some points from different resources:</p> <blockquote> <p>1) <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Observable.html" rel="noreferrer"><code>Observable</code></a> is a class and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Observer.html" rel="noreferrer"><code>Observer</code></a> is an interface.</p> <p>2) The <code>Observable</code> class maintains a list of <code>Observer</code>s.</p> <p>3) When an <code>Observable</code> object is updated, it invokes the <code>update()</code> method of each of its <code>Observer</code>s to notify that, it is changed.</p> </blockquote> <p>I found this example:</p> <pre><code>import java.util.Observable; import java.util.Observer; class MessageBoard extends Observable { public void changeMessage(String message) { setChanged(); notifyObservers(message); } } class Student implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("Message board changed: " + arg); } } public class MessageBoardTest { public static void main(String[] args) { MessageBoard board = new MessageBoard(); Student bob = new Student(); Student joe = new Student(); board.addObserver(bob); board.addObserver(joe); board.changeMessage("More Homework!"); } } </code></pre> <p>But I don't understand why we need <code>Observer</code> and <code>Observable</code>? What are the <code>setChanged()</code> and <code>notifyObservers(message)</code> methods for?</p>
13,744,537
10
6
null
2012-12-06 13:17:55.333 UTC
92
2019-04-24 12:54:48.527 UTC
2018-11-12 05:56:07.053 UTC
null
6,214,491
null
1,162,620
null
1
210
java|design-patterns|observable|observer-pattern|observers
171,637
<p>You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.</p> <p>Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.</p> <p>The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.</p>
20,595,227
How do I get an image from the iOS photo library and display it in UIWebView
<p>I've seen a lot of examples where you use the <code>UIImage</code> for outputting an image. I would like the output to be set to a <code>UIWebView</code> because I want to put some additional HTML formatting around the image.</p> <p>I want to get the photo library to return the relative path of an image stored on the iOS device, so that the I can put that in the 'src' attribute of the 'img' HTML tag.</p> <p>Is this possible?</p> <hr> <p>Edit 1</p> <p>I had to modify my code for what I wanted but this doesn't seem to work.</p> <pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { //Get Image URL from Library NSURL *urlPath = [info valueForKey:UIImagePickerControllerReferenceURL]; NSString *urlString = [urlPath absoluteString]; NSLog(urlString); NSURL *root = [[NSBundle mainBundle] bundleURL]; NSString *html; html = @"&lt;img src='"; html = [html stringByAppendingString:urlString]; html = [html stringByAppendingString:@"' /&gt;"]; [MemeCanvas loadHTMLString:html baseURL:root]; [picker dismissViewControllerAnimated:YES completion:^{}]; } </code></pre> <p>I am able to log the asset-library URL but it doesn't seem to be displayed the image on the <code>UIWebView</code>. I don't know what I need to change the baseURL to.</p> <p>Any help appreciated.</p> <hr> <p>Edit 2</p> <p>I changed <code>UIImagePickerControllerReferenceURL</code> to <code>UIImagePickerControllerMediaURL</code> and now it crashes because it doesnt like it when i append it to a string with <code>stringByAppendingString:urlString</code></p> <p>It gives me the error:</p> <blockquote> <p>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSCFConstantString stringByAppendingString:]: nil argument'</p> </blockquote> <p>Do you know what could be causing this?</p>
20,595,386
5
2
null
2013-12-15 13:47:21.613 UTC
8
2019-09-03 20:16:48.157 UTC
2018-03-23 06:00:08.98 UTC
null
5,624,053
null
3,104,482
null
1
23
ios|objective-c|uiwebview
45,963
<p>[<strong>Updated to swift 4</strong>] You can use <code>UIImagePickerController</code> delegate to select the image (or url) you want to edit.</p> <p>you can do this like this:</p> <pre><code>let pickerController = UIImagePickerController() pickerController.sourceType = .photoLibrary pickerController.delegate = self self.navigationController?.present(pickerController, animated: true, completion: { }) </code></pre> <p>in the delegate implementation you can use the path of the image or the image itself:</p> <pre><code>// This method is called when an image has been chosen from the library or taken from the camera. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //You can retrieve the actual UIImage let image = info[UIImagePickerControllerOriginalImage] as? UIImage //Or you can get the image url from AssetsLibrary let path = info[UIImagePickerControllerReferenceURL] as? URL picker.dismiss(animated: true, completion: nil) } </code></pre>
20,392,243
Run C# code on linux terminal
<p>How can I execute a C# code on a linux terminal as a shell script.</p> <p>I have this sample code:</p> <pre><code>public string Check(string _IPaddress,string _Port, int _SmsID) { ClassGlobal._client = new TcpClient(_IPaddress, Convert.ToInt32(_Port)); ClassGlobal.SMSID = _SmsID; string _result = SendToCAS(_IPaddress, _Port, _SmsID ); if (_result != "") return (_result); string _acoknoledgement = GetFromCAS(); return _acoknoledgement; } </code></pre> <p>When I run a shell bash I use <code>#!/bin/bash</code>. There is how to do the same with C#?</p>
44,991,753
6
2
null
2013-12-05 05:34:07.457 UTC
13
2021-08-20 19:29:50.59 UTC
2018-04-12 13:35:04.46 UTC
null
888,472
null
2,626,016
null
1
28
c#|linux|shell
100,012
<p>Of course it can be done and the process is extremely simple.</p> <p>Here I am explaining the steps for Ubuntu Linux.</p> <p>Open terminal:</p> <p><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>T</kbd> </p> <p>Type </p> <pre><code>gedit hello.cs </code></pre> <p>In the <code>gedit</code> window that opens paste the following example code:</p> <pre><code>using System; class HelloWorld { static void Main() { Console.WriteLine("Hello World!"); } } </code></pre> <p>Save and close gedit.</p> <p>Back in terminal type:</p> <pre><code>sudo apt update sudo apt install mono-complete mcs -out:hello.exe hello.cs mono hello.exe </code></pre> <p>Output:</p> <pre><code>Hello World! </code></pre>
24,253,761
How do you call an instance of a class in Python?
<p>This is inspired by a question I just saw, "Change what is returned by calling class instance", but was quickly answered with <code>__repr__</code> (and accepted, so the questioner did not actually intend to call the instance).</p> <p>Now calling an instance of a class can be done like this:</p> <pre><code>instance_of_object = object() instance_of_object() </code></pre> <p>but we'll get an error, something like <code>TypeError: 'object' object is not callable</code>.</p> <p>This behavior is defined in the CPython <a href="https://github.com/python/cpython/blob/master/Objects/call.c#L80" rel="noreferrer">source here.</a></p> <p>So to ensure we have this question on Stackoverflow:</p> <blockquote> <p>How do you actually call an instance of a class in Python?</p> </blockquote>
24,253,762
3
4
null
2014-06-16 23:40:55.823 UTC
13
2021-10-27 00:57:20.41 UTC
2017-04-24 19:49:44.033 UTC
null
541,136
null
541,136
null
1
50
python|class|call
103,220
<p>You call an instance of a class as in the following:</p> <pre><code>o = object() # create our instance o() # call the instance </code></pre> <p>But this will typically give us an error. </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'object' object is not callable </code></pre> <p>How can we call the instance as intended, and perhaps get something useful out of it?</p> <p>We have to implement Python special method, <code>__call__</code>!</p> <pre><code>class Knight(object): def __call__(self, foo, bar, baz=None): print(foo) print(bar) print(bar) print(bar) print(baz) </code></pre> <p>Instantiate the class:</p> <pre><code>a_knight = Knight() </code></pre> <p>Now we can call the class instance:</p> <pre><code>a_knight('ni!', 'ichi', 'pitang-zoom-boing!') </code></pre> <p>which prints:</p> <pre><code>ni! ichi ichi ichi pitang-zoom-boing! </code></pre> <p>And we have now actually, and successfully, <strong>called</strong> an instance of the class!</p>
3,888,033
How to convert string to xml file in java
<pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;soap:Body&gt;&lt;LoginResponse xmlns="http://tempuri.org/QuestIPhoneWebService/QuestIPhoneWebService"&gt;&lt;LoginResult&gt;&amp;lt;RETURN_VALUE&amp;gt;&amp;lt;ERROR RESULT= '-1' DESC = 'The password entered into the system is not valid. Please check your password and try again.'/&amp;gt;&amp;lt;/RETURN_VALUE&amp;gt;&lt;/LoginResult&gt;&lt;/LoginResponse&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt; </code></pre> <p>Hi I am getting the value from webservices. I want to convert above string to xml can anybody tell how to convert string to xml file in java </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;LoginResponse xmlns="http://tempuri.org/QuestIPhoneWebService/QuestIPhoneWebService"&gt; &lt;LoginResult&gt; &amp;lt;ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql"&amp;gt;&amp;lt;LOGIN_DETAILS USER_ID="testpub2" COMPANY_ID="1" USER_NAME=" aaa" SYSTEM_USER_ID="6976" USER_EMAIL_ID="[email protected]" TOKEN_STRING="A93805F1F1C340F5A8155FDD9B77E595" DISCLAIMER_AGREED="1" USER_ENABLED="1" USER_COMPANY_ENABLED="1" USER_TYPE="2" LOGIN_EXPIRY_DAYS="999" TOKEN_CREATION_DATE="2010-10-01T16:04:26" MOBILE_ENABLED="1" USER_COMPANY_MOBILE_ENABLED="1"/&amp;gt;&amp;lt;COMPANY_DETAILS CLIENT_TYPE_ID="8"/&amp;gt;&amp;lt;USER_SETTINGS&amp;gt;&amp;lt;QUEST_GROUP ID="14293" NAME="World" ASSIGN_NUM="14"/&amp;gt;&amp;lt;INDEX_PROVIDER ID="14251" NAME="QUEST (Default)"/&amp;gt;&amp;lt;STOCK_IDENTIFIER ID="57" NAME="TICKER"/&amp;gt;&amp;lt;/USER_SETTINGS&amp;gt;&amp;lt;PERMISSIONS&amp;gt;&amp;lt;QUEST_FUNCTIONS&amp;gt;&amp;lt;FUNCTION NAME="charting" ID="501" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="modeller" ID="512" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="momentum" ID="513" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="portfolio" ID="516" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="search" ID="518" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="sensitivity" ID="521" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="statistics" ID="524" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="strategy" ID="525" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="summary" ID="526" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="triangle" ID="528" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="valuation" ID="529" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="commentary" ID="530" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="CITN" ID="534" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="batch report" ID="553" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="ModellerWS" ID="557" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="Sector Analysis" ID="562" ACCESS="1"/&amp;gt;&amp;lt;/QUEST_FUNCTIONS&amp;gt;&amp;lt;ADMIN_FUNCTIONS&amp;gt;&amp;lt;FUNCTION NAME="administrator" ID="531" ACCESS="0"/&amp;gt;&amp;lt;FUNCTION NAME="author" ID="532" ACCESS="1"/&amp;gt;&amp;lt;FUNCTION NAME="publisher" ID="533" ACCESS="0"/&amp;gt;&amp;lt;FUNCTION NAME="editor" ID="539" ACCESS="0"/&amp;gt;&amp;lt;/ADMIN_FUNCTIONS&amp;gt;&amp;lt;/PERMISSIONS&amp;gt;&amp;lt;/ROOT&amp;gt; 10-04 14:30:08.696: DEBUG/login result is(439): &lt;/LoginResult&gt;&lt;/LoginResponse&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt; </code></pre> <p>the child node are coming like this USER_ID="testpub2" I have to convert xnode and get the value how to covert xml node? and take the value using saxparser. is can I take the value directly? </p>
3,888,207
2
2
null
2010-10-08 05:56:19.55 UTC
3
2015-03-01 15:01:36.74 UTC
2010-10-08 09:28:13.437 UTC
null
257,629
null
426,344
null
1
12
java|xml
68,237
<p>The below code converts a String to an XML document. Once you have the document, you can navigate the nodes or you can write to a file etc.</p> <pre><code>import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class Util { public static Document stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(xmlSource))); } } </code></pre>
28,540,598
AngularJS pass string as function to use at ng-click
<p>I want to assign a javascript function to ng-click which name is sourced by a rest service.</p> <pre><code>&lt;li ng-class="{ active: isActive('url')}" data-ng-repeat="menu in mb.data"&gt; &lt;a href="{{menu.href}}" data-ng-click="{{menu.javascript}}"&gt;{{menu.label}}&lt;/a&gt; &lt;/li&gt; </code></pre> <p>Sadly the angularjs parser throws an exception if one use {{ }} inside of ng-click. So I have tried several workarounds like using a callback function</p> <pre><code> &lt;a href="{{menu.href}}" data-ng-click="call(menu.javascript)"&gt;{{menu.label}}&lt;/a&gt; </code></pre> <p>But none of my ideas succeeded. How can I assign a javascript functions name in ng-lick? Btw. the function itself is part of the $scope.</p> <p>Edit- Here is the controller:</p> <p>The "$menu" service is simply a get rest request. The request result is a json object and only holding string values. In the current issue the result for menu.javascript is "loginModal()".</p> <pre><code>.controller('HeaderController', function($scope, $http, ModalService, $menu, $routeParams) { $scope.loginModal = function() { console.log("modal", ModalService); // Just provide a template url, a controller and call 'showModal'. ModalService.showModal({ templateUrl: "/modals/login.modal.html", controller: "LoginController" }).then(function(modal) { // The modal object has the element built, if this is a bootstrap modal // you can call 'modal' to show it, if it's a custom modal just show or hide // it as you need to. console.log(modal.element); modal.element.modal(); modal.close.then(function(result) { console.log(result ? "You said Yes" : "You said No"); }); }); }; $menu.get($routeParams, function(data){ $scope.menu = data; }); }) </code></pre> <p>Edit 2:</p> <p>Interestingly when I use {{menu.javascript}} then the correct string "loginModal()" is available in the DOM. But the angular parser stopped there due to errors.</p>
28,541,100
2
6
null
2015-02-16 11:39:15.61 UTC
6
2017-03-27 04:52:30.64 UTC
2015-10-28 18:35:15.797 UTC
null
2,435,473
null
1,298,461
null
1
17
javascript|html|angularjs|angularjs-scope|angularjs-ng-click
38,326
<p>You can do something like this </p> <p><strong>HTML</strong></p> <pre><code> &lt;div ng-controller="TodoCtrl"&gt; &lt;button ng-click="callFunction('testClick')"&gt;CLICK ME&lt;/button&gt; &lt;/div&gt; </code></pre> <p><strong>Controller</strong></p> <pre><code>function TodoCtrl($scope) { $scope.callFunction = function (name){ if(angular.isFunction($scope[name])) $scope[name](); } $scope.testClick = function(){ alert("Called"); } } </code></pre> <p><a href="http://jsfiddle.net/U3pVM/13252/"><strong>Working Fiddle</strong></a></p> <p>Hope this could help you. Thanks.</p>
9,403,609
In Symfony2, can the validation.yml file be split into multiple files using imports?
<p>Right now, I have a file called validation.yml with the validation of all the bundle's entities in one file.</p> <p>validation.yml</p> <pre><code>Blogger\BlogBundle\Entity\Comment properties: username: - NotBlank: message: You must enter your name - MaxLength: 50 comment: - NotBlank: message: You must enter a comment - MinLength: 50 Blogger\BlogBundle\Entity\Enquiry: properties: name: - NotBlank: ~ email: - Email: message: symblog does not like invalid emails. Give me a real one! subject: - NotBlank: ~ - MaxLength: 50 body: - MinLength: 50 </code></pre> <p>But I'd like to split it into two files and import them both. This is what I tried and it didn't work:</p> <p>validation.yml</p> <pre><code>imports: - { resource: comment.yml } - { resource: enquiry.yml } </code></pre> <p>comment.yml</p> <pre><code>Blogger\BlogBundle\Entity\Comment properties: username: - NotBlank: message: You must enter your name - MaxLength: 50 comment: - NotBlank: message: You must enter a comment - MinLength: 50 </code></pre> <p>enquiry.yml</p> <pre><code>Blogger\BlogBundle\Entity\Enquiry: properties: name: - NotBlank: ~ email: - Email: message: symblog does not like invalid emails. Give me a real one! subject: - NotBlank: ~ - MaxLength: 50 body: - MinLength: 50 </code></pre>
9,414,343
8
2
null
2012-02-22 21:47:52.907 UTC
11
2019-07-02 10:33:14.88 UTC
2016-02-26 12:43:42.85 UTC
null
1,262,820
null
625
null
1
18
php|symfony|yaml
9,727
<p>Add these lines in <code>load</code> method of <code>src/Blogger/BlogBundle/DependencyInjection/BloggerBlogExtension.php</code>.</p> <pre><code>public function load(array $configs, ContainerBuilder $container) { //... $yamlMappingFiles = $container-&gt;getParameter('validator.mapping.loader.yaml_files_loader.mapping_files'); $yamlMappingFiles[] = __DIR__.'/../Resources/config/comment.yml'; $yamlMappingFiles[] = __DIR__.'/../Resources/config/enquiry.yml'; $container-&gt;setParameter('validator.mapping.loader.yaml_files_loader.mapping_files', $yamlMappingFiles); } </code></pre>
16,415,827
Get reviews from google map api
<p>I have to get reviews from Google map API. details are on this page.</p> <p><a href="https://developers.google.com/places/documentation/details#PlaceDetailsResults" rel="noreferrer">https://developers.google.com/places/documentation/details#PlaceDetailsResults</a></p> <p>the details will fetch from this page:- </p> <p><a href="https://maps.googleapis.com/maps/api/place/details/json?reference=CmRYAAAAciqGsTRX1mXRvuXSH2ErwW-jCINE1aLiwP64MCWDN5vkXvXoQGPKldMfmdGyqWSpm7BEYCgDm-iv7Kc2PF7QA7brMAwBbAcqMr5i1f4PwTpaovIZjysCEZTry8Ez30wpEhCNCXpynextCld2EBsDkRKsGhSLayuRyFsex6JA6NPh9dyupoTH3g&amp;sensor=true&amp;key=AddYourOwnKeyHere" rel="noreferrer">https://maps.googleapis.com/maps/api/place/details/json?reference=CmRYAAAAciqGsTRX1mXRvuXSH2ErwW-jCINE1aLiwP64MCWDN5vkXvXoQGPKldMfmdGyqWSpm7BEYCgDm-iv7Kc2PF7QA7brMAwBbAcqMr5i1f4PwTpaovIZjysCEZTry8Ez30wpEhCNCXpynextCld2EBsDkRKsGhSLayuRyFsex6JA6NPh9dyupoTH3g&amp;sensor=true&amp;key=AddYourOwnKeyHere</a></p> <p>My problem is I can't find what is reference in request. and how I find this parameter value from my Google plus page.</p>
46,839,598
5
0
null
2013-05-07 09:38:41.983 UTC
14
2021-02-18 15:22:10.023 UTC
2013-12-30 00:33:44.84 UTC
user1841626
881,229
null
1,671,234
null
1
26
google-maps|google-plus
49,297
<p>A more recent way to do this:</p> <p><code>https://maps.googleapis.com/maps/api/place/details/json?placeid={place_id}&amp;key={api_key}</code></p> <ul> <li>place_id: <a href="https://developers.google.com/places/place-id" rel="noreferrer">https://developers.google.com/places/place-id</a></li> <li>api_key: <a href="https://developers.google.com/places/web-service/get-api-key" rel="noreferrer">https://developers.google.com/places/web-service/get-api-key</a></li> </ul> <p>Response:</p> <pre><code>{ "html_attributions": [], "result": { ... "rating": 4.6, "reviews": [ { "author_name": "John Smith", "author_url": "https://www.google.com/maps/contrib/106615704148318066456/reviews", "language": "en", "profile_photo_url": "https://lh4.googleusercontent.com/-2t1b0vo3t-Y/AAAAAAAAAAI/AAAAAAAAAHA/0TUB0z30s-U/s150-c0x00000000-cc-rp-mo/photo.jpg", "rating": 5, "relative_time_description": "in the last week", "text": "Great time! 5 stars!", "time": 1508340655 } ] } } </code></pre> <p>Reviews are limited to the 5 latest.</p>
16,244,601
Vagrant reverse port forwarding?
<p>I'm working on a web services architecture. I've got some software that I need to run on the native host machine, not in Vagrant. But I'd like to run some client services on the guest.</p> <p>Vagrant's <code>config.vm.forwarded_port</code> parameter will open a port on the host and send the data to the guest. But how can I open a port on the guest and send the data to the host? (It's still port forwarding, but in the reverse direction.)</p>
16,420,720
5
2
null
2013-04-26 20:20:46.91 UTC
57
2015-12-24 16:20:16.093 UTC
null
null
null
null
54,829
null
1
129
vagrant|portforwarding
49,518
<p>When you run <code>vagrant ssh</code>, it's actually using this underlying command:</p> <p><code>ssh -p 2222 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=ERROR -o IdentitiesOnly=yes -i ~/.vagrant.d/insecure_private_key [email protected]</code></p> <p>SSH supports forwarding ports in the direction you want with the <code>-R guestport:host:hostport</code> option. So, if you wanted to connect to port <code>12345</code> on the guest and have it forwarded to <code>localhost:80</code>, you would use this command:</p> <p><code>ssh -p 2222 -R 12345:localhost:80 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=ERROR -o IdentitiesOnly=yes -i ~/.vagrant.d/insecure_private_key [email protected]</code></p> <p>As Eero correctly comments, you can also use the command <code>vagrant ssh -- -R 12345:localhost:80</code>, which has the same effect in a much more concise command.</p>
11,224,201
Java - Exception in thread "main" java.lang.Error: Unresolved compilation problems
<p>I have some problem in my JDBC code. I am trying to connect through MySQL but it gives me an error. My error log is given below if you have some time.</p> <pre><code>Exception in thread "main" java.lang.Error: Unresolved compilation problems: BLOB cannot be resolved to a type BLOB cannot be resolved to a type at serialize.SerializeDeserialze.main(SerializeDeserialze.java:73) </code></pre> <p>My code is given below. I am using <code>mysql-connector-java-5.1.20.jar</code> driver:</p> <pre><code>package serialize; /* By vivek */ import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import oracle.sql.BLOB; /**** CREATE TABLE java_objects (object_id NUMBER, object_name varchar(128), object_value BLOB DEFAULT empty_blob(), primary key (object_id)); SQL&gt; desc java_objects; Name Null? Type ----------------------------------------- -------- ---------------------------- OBJECT_ID NOT NULL NUMBER OBJECT_NAME VARCHAR2(128) OBJECT_VALUE BLOB SQL&gt; select SEQUENCE_NAME, MIN_VALUE, MAX_VALUE, INCREMENT_BY, LAST_NUMBER from user_sequences; SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY LAST_NUMBER ------------------------------ ---------- ---------- ------------ ----------- ID_SEQ 1 1.0000E+27 1 21 JAVA_OBJECT_SEQUENCE 1 1.0000E+27 1 1 */ public class SerializeDeserialze { public static void main(String[] args) throws Exception { String WRITE_OBJECT_SQL = "BEGIN " + " INSERT INTO java_objects(object_id, object_name, object_value) " + " VALUES (?, ?, empty_blob()) " + " RETURN object_value INTO ?; " + "END;"; String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?"; Connection conn = getOracleConnection(); conn.setAutoCommit(false); List&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); list.add("This is a short string."); list.add(new Integer(1234)); list.add(new java.util.Date()); // write object to Oracle long id = 0001; String className = list.getClass().getName(); CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL); cstmt.setLong(1, id); cstmt.setString(2, className); cstmt.registerOutParameter(3, java.sql.Types.BLOB); cstmt.executeUpdate(); BLOB blob = (BLOB) cstmt.getBlob(3); OutputStream os = blob.getBinaryOutputStream(); ObjectOutputStream oop = new ObjectOutputStream(os); oop.writeObject(list); oop.flush(); oop.close(); os.close(); // Read object from oracle PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL); pstmt.setLong(1, id); ResultSet rs = pstmt.executeQuery(); rs.next(); InputStream is = rs.getBlob(1).getBinaryStream(); ObjectInputStream oip = new ObjectInputStream(is); Object object = oip.readObject(); className = object.getClass().getName(); oip.close(); is.close(); rs.close(); pstmt.close(); conn.commit(); // de-serialize list a java object from a given objectID List listFromDatabase = (List) object; System.out.println("[After De-Serialization] list=" + listFromDatabase); conn.close(); } private static Connection getHSQLConnection() throws Exception { Class.forName("org.hsqldb.jdbcDriver"); System.out.println("Driver Loaded."); String url = "jdbc:hsqldb:data/tutorial"; return DriverManager.getConnection(url, "sa", ""); } public static Connection getMySqlConnection() throws Exception { String driver = "org.gjt.mm.mysql.Driver"; String url = "jdbc:mysql://localhost/demo2s"; String username = "oost"; String password = "oost"; Class.forName(driver); Connection conn = DriverManager.getConnection(url, username, password); return conn; } public static Connection getOracleConnection() throws Exception { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@localhost:1521:databaseName"; String username = "userName"; String password = "password"; Class.forName(driver); // load Oracle driver Connection conn = DriverManager.getConnection(url, username, password); return conn; } </code></pre>
11,224,433
2
2
null
2012-06-27 10:31:23.42 UTC
0
2019-01-04 18:43:52.593 UTC
2019-01-04 18:43:52.593 UTC
null
6,214,491
null
1,439,243
null
1
4
java|mysql|database|jakarta-ee|jdbc
82,979
<p>This error happens when you use Eclipse as IDE and try to run code that doesn't even compile. Check your <em>Problems</em> view in Eclipse, and fix the compilation errors before executing the application.</p>
15,074,043
iOS otool to detect private apis
<p>I am a first time ios developer and cannot find any documentation on private apis. So I have been searching for some type of tutorial on how to use otool. The only certain thing that I can find is that I had to download the command line tools through xcode preferences. I also keep seeing references to linking it to the .app file, but I don't know where I can find this and how to use it in tool. Any links or suggestions?</p>
15,074,693
1
2
null
2013-02-25 18:41:48.71 UTC
10
2013-02-25 19:18:38.227 UTC
null
null
null
null
1,803,649
null
1
4
ios|xcode|iphone-privateapi|otool
14,444
<h1>Otool usage</h1> <p>Here is <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/otool.1.html" rel="nofollow noreferrer">official documentation</a></p> <p>Here is the question about otool usage: <a href="https://stackoverflow.com/questions/5946756/how-to-use-otool">how to use otool</a></p> <h1>Detect private api usage</h1> <p><a href="https://stackoverflow.com/questions/2842357/how-does-apple-know-you-are-using-private-api/2842873#2842873">How does Apple know you are using private API?</a></p> <p><a href="https://stackoverflow.com/questions/9815498/detecting-private-apis">Detecting Private APIs</a></p> <p>Here I have a question. Why do you want to detect private apis? Usually, this question happens when you plan to send your app to AppStore. If so, probably iphone-privateapi tag isn't good fit for the question. Since, this tag is more about how to use private api (and implication that the app won't be send to Appstore)</p> <h1>Documentation on private API</h1> <p>This one is tough. There is no good documentation. Information is scattered and becoming outdate as soon as new version of iOS are released.</p> <p>Look at these questions to find some interesting links:</p> <p><a href="https://stackoverflow.com/questions/1150360/ios-private-api-documentation">iOS Private API Documentation</a></p> <p><a href="https://stackoverflow.com/questions/2838656/how-to-use-iphone-sdk-private-apis">How to use iPhone SDK Private APIs</a></p> <p><a href="https://stackoverflow.com/questions/12734960/some-structured-information-on-ios-internals">https://stackoverflow.com/questions/12734960/some-structured-information-on-ios-internals</a></p>
17,412,826
Use mock location without setting it in settings
<p>I am writing an App which makes use of the location mocking possibility in android.</p> <p>What I would like to achive is to mock my location without setting the "allow mock locations" flag in the developer options.</p> <p>I know that it is possible, because is works with this app: <a href="https://play.google.com/store/apps/details?id=com.lexa.fakegps&amp;hl=en">https://play.google.com/store/apps/details?id=com.lexa.fakegps&amp;hl=en</a></p> <p>What I tried:</p> <p>Generate an apk, move it to /system/app, do a reboot<br> And I also tried it with and without the ACCESS_MOCK_LOCATION permission in the manifest.</p> <p>But it all lead to this exception:<br> RuntimeException: Unable to start Activity: SecurityException: Requires ACCESS_MOCK_LOCATION secure setting</p>
25,849,595
3
2
null
2013-07-01 20:11:49.113 UTC
5
2016-08-06 21:48:45.81 UTC
2013-07-02 08:50:27.9 UTC
null
1,248,485
null
1,248,485
null
1
6
java|android|gps|mocking|location
72,692
<p>I have decompiled <code>com.lexa.fakegps</code> you mentioned in question, and what it do like this:<br></p> <pre><code>private int setMockLocationSettings() { int value = 1; try { value = Settings.Secure.getInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION); Settings.Secure.putInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 1); } catch (Exception e) { e.printStackTrace(); } return value; } private void restoreMockLocationSettings(int restore_value) { try { Settings.Secure.putInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, restore_value); } catch (Exception e) { e.printStackTrace(); } } /* every time you mock location, you should use these code */ int value = setMockLocationSettings();//toggle ALLOW_MOCK_LOCATION on try { mLocationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, fake_location); } catch (SecurityException e) { e.printStackTrace(); } finally { restoreMockLocationSettings(value);//toggle ALLOW_MOCK_LOCATION off } </code></pre> <p>Because the execution time of these code is very short, other apps can hardly detect the change of ALLOW_MOCK_LOCATION.<br></p> <p>Also you need,<br> 1. require root access to your device<br> 2. move your app to <code>/system/app</code> or <code>/system/priv-app</code></p> <p>I tried it in my project and it works fine.</p>
19,310,700
What is a rune?
<p>What is a <code>rune</code> in Go?</p> <p>I've been googling but Golang only says in one line: <em><code>rune</code> is an alias for <code>int32</code></em>.</p> <p>But how come integers are used all around like swapping cases?</p> <p>The following is a function swapcase. What is all the <code>&lt;=</code> and <code>-</code>?</p> <p>And why doesn't <code>switch</code> have any arguments? </p> <p><code>&amp;&amp;</code> should mean <em>and</em> but what is <code>r &lt;= 'z'</code>?</p> <pre><code>func SwapRune(r rune) rune { switch { case 'a' &lt;= r &amp;&amp; r &lt;= 'z': return r - 'a' + 'A' case 'A' &lt;= r &amp;&amp; r &lt;= 'Z': return r - 'A' + 'a' default: return r } } </code></pre> <p>Most of them are from <a href="http://play.golang.org/p/H6wjLZj6lW">http://play.golang.org/p/H6wjLZj6lW</a></p> <pre><code>func SwapCase(str string) string { return strings.Map(SwapRune, str) } </code></pre> <p>I understand this is mapping <code>rune</code> to <code>string</code> so that it can return the swapped string. But I do not understand how exactly <code>rune</code> or <code>byte</code> works here.</p>
19,311,218
11
3
null
2013-10-11 05:14:57.673 UTC
72
2022-09-06 09:21:41.93 UTC
2022-06-13 04:42:40.42 UTC
user6169399
527,702
user2671513
null
null
1
302
go|terminology|rune
143,840
<p><strong>Rune literals are just 32-bit integer values</strong> (<em>however they're untyped constants, so their type can change</em>). They represent unicode codepoints. For example, the rune literal <code>'a'</code> is actually the number <code>97</code>.</p> <p>Therefore your program is pretty much equivalent to:</p> <pre><code>package main import "fmt" func SwapRune(r rune) rune { switch { case 97 &lt;= r &amp;&amp; r &lt;= 122: return r - 32 case 65 &lt;= r &amp;&amp; r &lt;= 90: return r + 32 default: return r } } func main() { fmt.Println(SwapRune('a')) } </code></pre> <p>It should be obvious, if you were to look at the Unicode mapping, which is identical to <a href="https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters" rel="noreferrer">ASCII</a> in that range. Furthermore, 32 is in fact the offset between the uppercase and lowercase codepoint of the character. So by adding <code>32</code> to <code>'A'</code>, you get <code>'a'</code> and vice versa.</p>
19,599,361
Append values to javascript dictionary
<p>I am trying to create the following data structure in javascript:</p> <pre><code>d = {"foo": [3, 77, 100], "bar": [10], "baz": [99], "biff": [10]} </code></pre> <p>My starting data structure is a a list of dictionaries:</p> <pre><code>input = [{"key": "foo", "val": 3}, {"key": "bar", "val": 10}, {"key": "foo", "val": 100}, {"key": "baz", "val": 99}, {"key": "biff", "val": 10}, {"key": "foo", "val": 77] </code></pre> <p>How can I generate my desired data structure? The following code doesn't seem to append values to the value array.</p> <pre><code>var d = {} for (var i in input) { var datum = input[i]; d[datum.key] = datum.val } </code></pre>
19,599,436
7
4
null
2013-10-25 21:01:02.8 UTC
1
2020-07-10 05:39:11.04 UTC
2013-10-25 21:06:22 UTC
null
1,255,817
null
1,255,817
null
1
11
javascript
63,201
<pre><code>for (var i = 0; i &lt; input.length; i++) { var datum = input[i]; if (!d[datum.key]) { d[datum.key] = []; } d[datum.key].push(datum.val); } </code></pre> <p>FYI, you shouldn't use <code>for (var i in input)</code> to iterate over an array.</p>
19,621,074
Finding JavaScript memory leaks with Chrome
<p>I've created a very simple test case that creates a Backbone view, attaches a handler to an event, and instantiates a user-defined class. I believe that by clicking the "Remove" button in this sample, everything will be cleaned up and there should be no memory leaks.</p> <p>A jsfiddle for the code is here: <a href="http://jsfiddle.net/4QhR2/" rel="noreferrer">http://jsfiddle.net/4QhR2/</a></p> <pre><code>// scope everything to a function function main() { function MyWrapper() { this.element = null; } MyWrapper.prototype.set = function(elem) { this.element = elem; } MyWrapper.prototype.get = function() { return this.element; } var MyView = Backbone.View.extend({ tagName : "div", id : "view", events : { "click #button" : "onButton", }, initialize : function(options) { // done for demo purposes only, should be using templates this.html_text = "&lt;input type='text' id='textbox' /&gt;&lt;button id='button'&gt;Remove&lt;/button&gt;"; this.listenTo(this,"all",function(){console.log("Event: "+arguments[0]);}); }, render : function() { this.$el.html(this.html_text); this.wrapper = new MyWrapper(); this.wrapper.set(this.$("#textbox")); this.wrapper.get().val("placeholder"); return this; }, onButton : function() { // assume this gets .remove() called on subviews (if they existed) this.trigger("cleanup"); this.remove(); } }); var view = new MyView(); $("#content").append(view.render().el); } main(); </code></pre> <p>However, I am unclear how to use Google Chrome's profiler to verify that this is, in fact, the case. There are a gazillion things that show up on the heap profiler snapshot, and I have no idea how to decode what's good/bad. The tutorials I've seen on it so far either just tell me to "use the snapshot profiler" or give me a hugely detailed manifesto on how the entire profiler works. Is it possible to just use the profiler as a tool, or do I really have to understand how the whole thing was engineered?</p> <p><strong>EDIT:</strong> Tutorials like these:</p> <p><a href="https://docs.google.com/presentation/d/1wUVmf78gG-ra5aOxvTfYdiLkdGaR9OhXRnOlIcEmu2s/pub?start=false&amp;loop=false&amp;delayms=3000#slide=id.g14717ff3_0_23" rel="noreferrer">Gmail memory leak fixing</a></p> <p><a href="http://addyosmani.com/blog/taming-the-unicorn-easing-javascript-memory-profiling-in-devtools/" rel="noreferrer">Using DevTools</a></p> <p>Are representative of some of the stronger material out there, from what I've seen. However, beyond introducing the concept of the <em>3 Snapshot Technique</em>, I find they offer very little in terms of practical knowledge (for a beginner like me). The 'Using DevTools' tutorial doesn't work through a real example, so its vague and general conceptual description of things aren't overly helpful. As for the 'Gmail' example:</p> <blockquote> <p><strong><em>So you found a leak. Now what?</em></strong></p> <ul> <li><p>Examine the retaining path of leaked objects in the lower half of the Profiles panel</p></li> <li><p>If the allocation site cannot be easily inferred (i.e. event listeners):</p></li> <li><p>Instrument the constructor of the retaining object via the JS console to save the stack trace for allocations</p></li> <li><p>Using Closure? Enable the appropriate existing flag (i.e. goog.events.Listener.ENABLE_MONITORING) to set the creationStack property during construction</p></li> </ul> </blockquote> <p>I find myself more confused after reading that, not less. And, again, it's just telling me to <em>do</em> things, not <em>how</em> to do them. From my perspective, all of the information out there is either too vague or would only make sense to someone who already understood the process.</p> <p>Some of these more specific issues have been raised in <a href="https://stackoverflow.com/a/19726918/20578">@Jonathan Naguin's answer</a> below.</p>
19,726,918
9
5
null
2013-10-27 17:28:06.037 UTC
121
2021-02-15 07:38:26.15 UTC
2017-05-23 12:02:51.35 UTC
null
-1
null
2,153,271
null
1
173
javascript|google-chrome|backbone.js|memory-leaks
75,950
<p>A good workflow to find memory leaks is the <strong>three snapshot</strong> technique, first used by Loreena Lee and the Gmail team to solve some of their memory problems. The steps are, in general:</p> <ul> <li>Take a heap snapshot.</li> <li>Do stuff.</li> <li>Take another heap snapshot.</li> <li>Repeat the same stuff.</li> <li>Take another heap snapshot.</li> <li>Filter objects allocated between Snapshots 1 and 2 in Snapshot 3's "Summary" view.</li> </ul> <p>For your example, I have adapted the code to show this process (you can find it <a href="http://jsfiddle.net/t2epG/" rel="noreferrer">here</a>) delaying the creation of the Backbone View until the click event of the Start button. Now:</p> <ul> <li>Run the HTML (saved locally of using this <a href="http://jsfiddle.net/t2epG/show" rel="noreferrer">address</a>) and take a snapshot.</li> <li>Click Start to create the view.</li> <li>Take another snapshot.</li> <li>Click remove.</li> <li>Take another snapshot.</li> <li>Filter objects allocated between Snapshots 1 and 2 in Snapshot 3's "Summary" view.</li> </ul> <p>Now you are ready to find memory leaks! </p> <p>You will notice nodes of a few different colors. Red nodes do not have direct references from Javascript to them, but are alive because they are part of a detached DOM tree. There may be a node in the tree referenced from Javascript (maybe as a closure or variable) but is coincidentally preventing the entire DOM tree from being garbage collected. </p> <p><img src="https://i.stack.imgur.com/os7y7.png" alt="enter image description here"></p> <p>Yellow nodes however do have direct references from Javascript. Look for yellow nodes in the same detached DOM tree to locate references from your Javascript. There should be a chain of properties leading from the DOM window to the element.</p> <p>In your particular you can see a HTML Div element marked as red. If you expand the element you will see that is referenced by a "cache" function. </p> <p><img src="https://i.stack.imgur.com/hmsdk.png" alt="enter image description here"></p> <p>Select the row and in your console type $0, you will see the actual function and location:</p> <pre><code>&gt;$0 function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) &gt; Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } jquery-2.0.2.js:1166 </code></pre> <p>This is where your element is being referenced. Unfortunally there is not much you can do, it is a internal mechanism from jQuery. But, just for testing purpose, go the function and change the method to:</p> <pre><code>function cache( key, value ) { return value; } </code></pre> <p>Now if you repeat the process you will not see any red node :)</p> <p>Documentation:</p> <ul> <li><a href="https://docs.google.com/presentation/d/1wUVmf78gG-ra5aOxvTfYdiLkdGaR9OhXRnOlIcEmu2s/pub?start=false&amp;loop=false&amp;delayms=3000#slide=id.g31ec7af_0_58" rel="noreferrer">Eliminating memory leaks in Gmail</a>.</li> <li><a href="http://addyosmani.com/blog/taming-the-unicorn-easing-javascript-memory-profiling-in-devtools/" rel="noreferrer">Easing JavaScript Memory Profiling In Chrome DevTools</a>.</li> </ul>
17,325,006
How to create a foreignkey reference with sqlalchemy
<p>Hi I am not able to understand how to make a foreignkey reference using sqlalchemy. I have created a new table client in my database:</p> <pre><code>class Client(DeclarativeBase): __tablename__ = 'client' id = Column(Integer, primary_key=True) user_id = Column( Integer, ForeignKey('user.id', ondelete='CASCADE'), nullable=False, index=True, ) orgname = Column(Unicode, nullable=False) def __init__(self, **kwargs): super(Client, self).__init__(**kwargs) </code></pre> <p>Not I am trying to do something like this</p> <pre><code> u = User(user_name=u'dusual') session.add(u) c = Client(user=u, orgname="dummy_org") session.add(c) </code></pre> <p>But sqlalchemy shouts back saying :</p> <p>(k, cls_.<strong>name</strong>)) TypeError: 'user' is an invalid keyword argument for Client</p> <p>Now shouldn't this be obvious that user should be allowed as a keyword argument how can I make sure my table is able to take user keyword argument.</p>
17,330,019
1
0
null
2013-06-26 16:00:46.51 UTC
12
2021-08-16 20:31:00.45 UTC
2021-08-16 20:31:00.45 UTC
null
792,066
null
765,836
null
1
21
python|sqlalchemy
29,346
<p>You need to define a <a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#orm-tutorial-relationship" rel="noreferrer">relationship</a> between <code>User</code> and <code>Client</code> models:</p> <pre><code>from sqlalchemy.orm import relationship class Client(DeclarativeBase): __tablename__ = 'client' id = Column(Integer, primary_key=True) user_id = Column( Integer, ForeignKey('user.id', ondelete='CASCADE'), nullable=False, # no need to add index=True, all FKs have indexes ) user = relationship('User', backref='clients') orgname = Column(Unicode, nullable=False) # no need to add a constructor </code></pre> <p>Then you can associate instances of <code>User</code> and <code>Client</code> models in two ways - either by assigning an integer to <code>Client.user_id</code>:</p> <pre><code>u = User(user_name=u'dusual') session.add(u) session.flush() # to make sure the id is fetched from the database c = Client(user_id=u.id, orgname="dummy_org") session.add(c) </code></pre> <p>or by assinging a <code>User</code> instance to <code>Client.user</code>. </p> <pre><code>u = User(user_name=u'dusual') # no need to flush, no need to add `u` to the session because sqlalchemy becomes aware of the object once we assign it to c.user c = Client(user=u, orgname="dummy_org") session.add(c) </code></pre> <p>Actually, there's a third way - since we've configured a <code>backref</code> on <code>Client.user</code>, SQLAlchemy added a list-like <code>clients</code> attribute to our <code>User</code> model:</p> <pre><code>u = User(user_name=u'dusual') u.clients.append(Client(orgname="dummy_org")) session.add(u) </code></pre>
17,191,622
Why would I not leave extglob enabled in bash?
<p>I just found out about the bash extglob shell option here:- <a href="https://stackoverflow.com/questions/216995/how-can-i-use-inverse-or-negative-wildcards-when-pattern-matching-in-a-unix-linu">How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?</a></p> <p>All the answers that used <code>shopt -s extglob</code> also mentioned <code>shopt -u extglob</code> to turn it off. Why would I want to turn something so useful off? Indeed why isn't it on by default? Presumably it has the potential for giving some nasty surprises. What are they?</p>
17,191,796
2
1
null
2013-06-19 12:49:04.173 UTC
15
2017-01-12 01:17:24.667 UTC
2017-05-23 12:26:23.92 UTC
null
-1
null
2,409,928
null
1
53
bash
13,349
<p>No nasty surprises -- default-off behavior is only there for compatibility with traditional, standards-compliant pattern syntax.</p> <hr /> <p>Which is to say: It's possible (albeit unlikely) that someone writing <code>fo+(o).*</code> <em>actually intended</em> the <code>+</code> and the parenthesis to be treated as literal parts of the pattern matched by their code. For bash to interpret this expression in a different manner than what the POSIX sh specification calls for would be to break compatibility, which is right now done by default in very few cases (<code>echo -e</code> with <code>xpg_echo</code> unset being the only one that comes immediately to mind).</p> <p>This is different from the usual case where bash extensions are extending behavior <I>undefined</I> by the POSIX standard -- cases where a baseline POSIX shell would typically throw an error, but bash instead offers some new and different explicitly documented behavior -- because the need to treat these characters as matching themselves is defined by POSIX.</p> <p>To quote <A HREF="http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_13_01" rel="noreferrer">the relevant part of the specification</A>, with emphasis added:</p> <blockquote> <p><B>An ordinary character is a pattern that shall match itself.</B> It can be <B>any character in the supported character set except for</B> NUL, those special shell characters in <A HREF="http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02" rel="noreferrer">Quoting</A> that require quoting, and <B>the following three special pattern characters</B>. Matching shall be based on the bit pattern used for encoding the character, not on the graphic representation of the character. If any character (ordinary, shell special, or pattern special) is quoted, that pattern shall match the character itself. The shell special characters always require quoting.</p> <p>When unquoted and outside a bracket expression, the following three characters shall have special meaning in the specification of patterns:</p> <ul> <li><B><code>?</code></B> - A question-mark is a pattern that shall match any character.</li> <li><B><code>*</code></B> - An asterisk is a pattern that shall match multiple characters, as described in <A HREF="http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_13_02" rel="noreferrer">Patterns Matching Multiple Characters</A>.</li> <li><B><code>[</code></B> - The open bracket shall introduce a pattern bracket expression.</li> </ul> </blockquote> <p>Thus, the standard explicitly requires any non-NUL character other than <code>?</code>, <code>*</code> or <code>[</code> or those listed elsewhere as requiring quoting to match themselves. Bash's behavior of having extglob off by default allows it to conform with this standard in its default configuration.</p> <hr /> <p>However, for your own scripts and your own interactive shell, unless you're making a habit of running code written for POSIX sh with unusual patterns included, enabling <code>extglob</code> is typically worth doing.</p>
30,367,590
Uncaught TypeError: Cannot read property 'mData' of undefined
<p>i followed <a href="https://stackoverflow.com/questions/1790065/how-to-put-multiple-jquery-datatables-in-one-page#1790065">this</a> for enabling multiple tables(on same page) using DataTables plugin. for manual tables it work but for dynamic created tables it shows the following error:</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'mData' of undefined</p> </blockquote> <p>my page srcipt:</p> <pre><code> $(document).ready(function() { $('table.datatable').dataTable( { 'bSort': false, 'aoColumns': [ { sWidth: "45%", bSearchable: false, bSortable: false }, { sWidth: "45%", bSearchable: false, bSortable: false }, { sWidth: "10%", bSearchable: false, bSortable: false } ], "scrollY": "200px", "scrollCollapse": false, "info": true, "paging": true } ); } ); </code></pre> <blockquote> <p>my HTML first table:</p> </blockquote> <pre><code>&lt;table class="table table-striped table-bordered datatable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Issue &lt;/th&gt; &lt;th&gt; Product &lt;/th&gt; &lt;th&gt; Qty &lt;/th&gt; &lt;th class="text-right"&gt; Paid &lt;/th&gt; &lt;th class="text-right"&gt; Balance &lt;/th&gt; &lt;th class="text-right"&gt; Total &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt;&lt;!-- table head --&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Normal Sim&lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs18,893.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs131,107.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs150,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;voice/7?invoice_type=1"&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Nokia 3310 &lt;/td&gt; &lt;td&gt;10000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs2,520,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs12,480,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs15,000,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Nokia 3310 &lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs404,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs1,096,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs1,500,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <blockquote> <p>second table:</p> </blockquote> <pre><code>&lt;table class="table table-striped table-bordered datatable" id="p_history"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Issue&lt;/th&gt; &lt;th&gt;Paid&lt;/th&gt; &lt;th&gt;Comments&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 15,000.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 12.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 123.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 123.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>any idea how to fix?</p> <p><strong>Note:</strong> i also read <a href="https://stackoverflow.com/questions/30121671/jquery-datatables-uncaught-typeerror-cannot-read-property-mdata-of-undefined">this</a> Unanswered Question, same error but mine is different criteria therefore it is not a duplicate.</p>
30,371,597
4
4
null
2015-05-21 07:45:24.65 UTC
2
2019-08-14 00:17:39.207 UTC
2017-05-23 12:25:29.747 UTC
null
-1
null
4,391,210
null
1
8
javascript|php|jquery|jquery-datatables
51,771
<h3>CAUSE</h3> <p>You are trying to initialize multiple table with the same options, the most important one is <code>aoColumns</code>, array holding column definitions. Your <code>aoColumns</code> array holds 3 items only, however the number of columns differ in each tables, that is why you receive an error. </p> <p>From the <a href="http://legacy.datatables.net/usage/columns" rel="nofollow noreferrer">manual</a>:</p> <blockquote> <p><code>aoColumns</code>: If specified, then the length of this array must be equal to the number of columns in the original HTML table. Use 'null' where you wish to use only the default values and automatically detected options.</p> </blockquote> <h3>SOLUTION</h3> <p>You need to assign unique <code>id</code> to the first table and initialize each table separately as shown below.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('#table_first').dataTable( { 'bSort': false, 'aoColumns': [ { sWidth: "15%", bSearchable: false, bSortable: false }, { sWidth: "15%", bSearchable: false, bSortable: false }, { sWidth: "15%", bSearchable: false, bSortable: false }, { sWidth: "15%", bSearchable: false, bSortable: false }, { sWidth: "15%", bSearchable: false, bSortable: false }, { sWidth: "15%", bSearchable: false, bSortable: false }, ], "scrollY": "200px", "scrollCollapse": false, "info": true, "paging": true }); $('#p_history').dataTable( { 'bSort': false, 'aoColumns': [ { sWidth: "45%", bSearchable: false, bSortable: false }, { sWidth: "45%", bSearchable: false, bSortable: false }, { sWidth: "10%", bSearchable: false, bSortable: false } ], "scrollY": "200px", "scrollCollapse": false, "info": true, "paging": true } ); } );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//code.jquery.com/jquery-1.10.2.min.js"&gt;&lt;/script&gt; &lt;link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.css" rel="stylesheet"/&gt; &lt;script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.js"&gt;&lt;/script&gt; &lt;table class="table table-striped table-bordered datatable" id="table_first"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; Issue &lt;/th&gt; &lt;th&gt; Product &lt;/th&gt; &lt;th&gt; Qty &lt;/th&gt; &lt;th class="text-right"&gt; Paid &lt;/th&gt; &lt;th class="text-right"&gt; Balance &lt;/th&gt; &lt;th class="text-right"&gt; Total &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt;&lt;!-- table head --&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Normal Sim&lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs18,893.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs131,107.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs150,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;voice/7?invoice_type=1"&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Nokia 3310 &lt;/td&gt; &lt;td&gt;10000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs2,520,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs12,480,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs15,000,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Nokia 3310 &lt;/td&gt; &lt;td&gt;1000&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs404,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs1,096,000.00 &lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="pull-right"&gt;Rs1,500,000.00 &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table class="table table-striped table-bordered datatable" id="p_history"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Issue&lt;/th&gt; &lt;th&gt;Paid&lt;/th&gt; &lt;th&gt;Comments&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 15,000.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 12.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 123.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;May 20, 2015, 5:15 pm&lt;/td&gt; &lt;td&gt;Rs 123.00 &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <h3>LINKS</h3> <p>See <a href="https://www.gyrocode.com/articles/jquery-datatables-common-javascript-console-errors/#typeerror-cannot-read-property-mdata-of-undefined" rel="nofollow noreferrer">jQuery DataTables: Common JavaScript console errors</a> for more information on this and other common console errors.</p>
37,084,537
How to clear the text field automatically
<p>I have a question about <code>UITextField()</code> in Swift. How can I clear the text in the text field when I click on it?</p> <p>My <code>textField.text = "0"</code>. I want to automatically remove the number "0" when I click on the text field:</p> <pre><code>import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var lbltext: UILabel! @IBOutlet var scrolview1: UIScrollView! @IBOutlet var fi: UITextField! @IBOutlet var scrolviewus: UIScrollView! @IBOutlet var counterLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() fi.text = "0" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func button(sender: AnyObject) { lbltext.numberOfLines = 0 lbltext.text! = lbltext.text! + "\n" + fi.text! + "\n" + "--- " } } </code></pre>
37,084,618
8
4
null
2016-05-07 04:36:48.08 UTC
8
2022-08-05 10:40:45.993 UTC
2020-05-27 22:52:05.19 UTC
null
128,421
null
6,116,829
null
1
19
ios|swift|iphone|swift2|uitextfield
59,735
<p>Use this method,</p> <p>If you want to manually clear the text field use this code:</p> <pre><code>textField.text = "" </code></pre> <p>If you want the text field to empty when you begin editing, use the delegate method below:</p> <pre><code>func textFieldDidBeginEditing(textField: UITextField) { textField.text = "" } </code></pre> <p>If you are using multiple text fields, use the method below:</p> <pre><code>func textFieldDidBeginEditing(textField: UITextField) { if (textField == oneTextField) { textField.text = "" } else if (textField == anotherTextField) { // Perform any other operation } } </code></pre>
22,991,387
How to set default value for ASP.NET MVC DropDownList from model
<p>i am new in mvc. so i populate dropdown this way</p> <pre><code>public ActionResult New() { var countryQuery = (from c in db.Customers orderby c.Country ascending select c.Country).Distinct(); List&lt;SelectListItem&gt; countryList = new List&lt;SelectListItem&gt;(); string defaultCountry = "USA"; foreach(var item in countryQuery) { countryList.Add(new SelectListItem() { Text = item, Value = item, Selected=(item == defaultCountry ? true : false) }); } ViewBag.Country = countryList; ViewBag.Country = "UK"; return View(); } @Html.DropDownList("Country", ViewBag.Countries as List&lt;SelectListItem&gt;) </code></pre> <p>i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks</p>
22,991,766
3
4
null
2014-04-10 14:44:45.293 UTC
2
2016-11-25 16:31:48.553 UTC
null
null
null
null
508,127
null
1
5
asp.net-mvc
57,509
<p>Well this is not a great way to do this.</p> <p>Create a ViewModel that will hold everything you want to be rendered at the view.</p> <pre><code>public class MyViewModel{ public List&lt;SelectListItem&gt; CountryList {get; set} public string Country {get; set} public MyViewModel(){ CountryList = new List&lt;SelectListItem&gt;(); Country = "USA"; //default values go here } </code></pre> <p>Fill it with the data you need.</p> <pre><code>public ActionResult New() { var countryQuery = (from c in db.Customers orderby c.Country ascending select c.Country).Distinct(); MyViewModel myViewModel = new MyViewModel (); foreach(var item in countryQuery) { myViewModel.CountryList.Add(new SelectListItem() { Text = item, Value = item }); } myViewModel.Country = "UK"; //Pass it to the view using the `ActionResult` return ActionResult( myViewModel); } </code></pre> <p>At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file</p> <pre><code>@model namespace.MyViewModel </code></pre> <p>And at anytime you may use the Model as you please</p> <pre><code>@Html.DropDownList("Country", Model.CountryList, Model.Country) </code></pre>
5,514,367
Why are there two kinds of JavaScript strings?
<p>This one just stabbed me hard. I don't know if it's the case with all browsers (I don't have any other competent browser to test with), but at least Firefox has two kind of string objects.</p> <p>Open up the Firebugs console and try the following:</p> <pre><code>&gt;&gt;&gt; "a" "a" &gt;&gt;&gt; new String("a") String { 0="a"} </code></pre> <p>As you can visually observe, Firefox treats <code>new String("a")</code> and <code>"a"</code> differently. Otherwise however, both kinds of strings seem to behave the same. There is, for instance, evidence that both use the same prototype object:</p> <pre><code>&gt;&gt;&gt; String.prototype.log = function() { console.log("Logged string: " + this); } function() &gt;&gt;&gt; "hello world".log() Logged string: hello world &gt;&gt;&gt; new String("hello world").log() Logged string: hello world </code></pre> <p>So apparently, both are the same. That is, until you ask for the type.</p> <pre><code>&gt;&gt;&gt; typeof("a") "string" &gt;&gt;&gt; typeof(new String("a")) "object" </code></pre> <p>We can also notice that when <code>this</code> is a string, it's always the object form:</p> <pre><code>&gt;&gt;&gt; var identity = function() { return this } &gt;&gt;&gt; identity.call("a") String { 0="a"} &gt;&gt;&gt; identity.call(new String("a")) String { 0="a"} </code></pre> <p>Going a bit further, we can see that the non-object string representation doesn't support any additional properties, but the object string does:</p> <pre><code>&gt;&gt;&gt; var a = "a" &gt;&gt;&gt; var b = new String("b") &gt;&gt;&gt; a.bar = 4 4 &gt;&gt;&gt; b.bar = 4 4 &gt;&gt;&gt; a.bar undefined &gt;&gt;&gt; b.bar 4 </code></pre> <p>Also, fun fact! You can turn a string object into a non-object string by using the <code>toString()</code> function:</p> <pre><code>&gt;&gt;&gt; new String("foo").toString() "foo" </code></pre> <p>Never thought it could be useful to call <code>String.toString()</code>! Anyways.</p> <p>So all these experiments beg the question: why are there two kinds of strings in JavaScript?</p> <hr> <p>Comments show this is also the case for every primitive JavaScript type (numbers and bools included).</p>
5,514,409
3
5
null
2011-04-01 13:54:36.21 UTC
5
2011-08-16 01:00:38.003 UTC
2011-04-01 14:00:47.283 UTC
null
251,153
null
251,153
null
1
37
javascript|string
835
<p>There are two types of strings in Javascript -- literal strings and String objects. They do behave a little differently. The main difference between the two is that you can add additional methods and properties to a String object. For instance:</p> <pre><code>var strObj = new String("object mode"); strObj.string_mode = "object" strObj.get_string_mode = function() { return this.string_mode; } // this converts it from an Object to a primitive string: str = strObj.toString(); </code></pre> <p>A string literal is just temporarily cast to a String object to perform any of the core methods.</p> <p>The same kinds of concepts apply to other data types, too. <a href="http://en.wikipedia.org/wiki/JavaScript_syntax#Primitive_data_types" rel="noreferrer">Here's more on primitive data types and objects</a>.</p> <p><strong>EDIT</strong></p> <p>As noted in the comments, string literals are not primitive strings, rather a "literal constant whose type is a built-in primitive [string] value", citing <a href="http://www.ssicom.org/js/x17038.htm" rel="noreferrer">this source</a>.</p>
9,384,758
What is the 'Execution Context' in JavaScript exactly?
<p>My title pretty much sums it all.</p> <p>Can anyone enlighten me on...</p> <p><strong>"What is the 'Execution Context' in JavaScript?"</strong></p> <p>and on how it relates to 'this,' hoisting, prototype chaining, scope and garbage collection?</p>
9,384,894
9
3
null
2012-02-21 20:36:38.307 UTC
54
2021-03-04 05:25:32.903 UTC
2013-12-09 09:39:54.127 UTC
null
985,895
null
985,895
null
1
90
javascript
48,791
<p>You're asking about several different concepts that aren't very closely related. I'll try to briefly address each.</p> <hr> <p><em>Execution context</em> is a concept in the language spec that&mdash;in layman's terms&mdash;roughly equates to the 'environment' a function executes in; that is, variable scope (and the <em>scope chain</em>, variables in closures from outer scopes), function arguments, and the value of the <code>this</code> object.</p> <p>The <em>call stack</em> is a collection of execution contexts.</p> <p>See also <a href="https://stackoverflow.com/a/7722057/201952">this answer</a> and <a href="http://dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts/" rel="noreferrer">this article</a>.</p> <hr> <p><em>Scope</em> is literally that: the scope in which a variable can be accessed. Simplistically:</p> <pre><code>var x; function a() { var y; } </code></pre> <p><code>x</code> can be accessed from anywhere. When <code>a</code> is invoked, <code>x</code> will be in the outer scope. (Stored in the <em>scope chain</em>.)</p> <p>In contrast, <code>y</code> can only be accessed by code in <code>a()</code> because it is limited to <code>a</code>'s scope. This is what the <code>var</code> keyword does: restricts a variable to the local scope. If we omitted <code>var</code>, <code>y</code> would end up in the <em>global scope</em>, generally considered a bad thing.</p> <hr> <p>Think of <em>hoisting</em> as more of a compile-time thing. In JavaScript, function <strong>declarations</strong> are "hoisted" to the top of their scope. In other words, they are parsed and evaluated <em>before</em> any other code. (This is opposed to function <strong>expressions</strong>, which are evaluated inline.) Consider the following:</p> <pre><code>a(); b(); function a() { } var b = function() { } </code></pre> <p>The call to <code>a()</code> will succeed because its declaration was hoisted to the top; <code>a</code> was assigned to automatically before program execution began. The call to <code>b()</code> will fail with a <code>TypeError</code> because <code>b</code> will not be defined until line 4.</p>
9,184,141
How do you get centered content using Twitter Bootstrap?
<p>I'm trying to follow a very basic example. Using the <a href="http://getbootstrap.com/css/#grid" rel="noreferrer">starter page and the grid system</a>, I was hoping the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="row"&gt; &lt;div class="span12"&gt; &lt;h1&gt;Bootstrap starter template&lt;/h1&gt; &lt;p&gt;Example text.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>...would produce centered text.</p> <p>However, it still appears on the far left. What am I doing wrong?</p>
9,184,443
24
4
null
2012-02-07 21:21:55.823 UTC
80
2022-07-24 15:57:32.843 UTC
2017-10-28 10:09:54.247 UTC
null
63,550
null
1,011,816
null
1
585
html|css|twitter-bootstrap
954,780
<h2>This is for Text Centering (<em>which is what the question was about</em>)</h2> <p>For other types of content, see <a href="https://stackoverflow.com/a/13099189/2812842">Flavien's answer</a>.</p> <p><strong>Update: Bootstrap 2.3.0+ Answer</strong></p> <p>The original answer was for an early version of bootstrap. As of bootstrap 2.3.0, <strong>you can simply give the div the class <code>.text-center</code></strong>.</p> <hr> <p><strong>Original Answer (pre 2.3.0)</strong></p> <p>You need to define one of the two classes, <code>row</code> or <code>span12</code> with a <code>text-align: center</code>. See <a href="http://jsfiddle.net/xKSUH/" rel="noreferrer">http://jsfiddle.net/xKSUH/</a> or <a href="http://jsfiddle.net/xKSUH/1/" rel="noreferrer">http://jsfiddle.net/xKSUH/1/</a></p>
18,406,713
How to conditionally enable or disable scheduled jobs in Spring?
<p>I am defining scheduled jobs with cron style patterns in Spring, using the <code>@Scheduled</code> annotation.</p> <p>The cron pattern is stored in a config properties file. Actually there are two properties files: one default config, and one profile config that is environment dependent (e.g. dev, test, prod customer 1, prod customer 2 etc.) and overrides some of the default values.</p> <p>I configured a property placeholder bean in my spring context which allows me to use <code>${}</code> style placeholders to import values from my properties files.</p> <p>The job beans looks like this:</p> <pre><code>@Component public class ImagesPurgeJob implements Job { private Logger logger = Logger.getLogger(this.getClass()); @Override @Transactional(readOnly=true) @Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}") public void execute() { //Do something //can use DAO or other autowired beans here } } </code></pre> <p>Relevant parts of my context XML :</p> <pre><code>&lt;!-- Enable configuration of scheduled tasks via annotations --&gt; &lt;task:annotation-driven/&gt; &lt;!-- Load configuration files and allow '${}' style placeholders --&gt; &lt;bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;classpath:config/default-config.properties&lt;/value&gt; &lt;value&gt;classpath:config/environment-config.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="ignoreUnresolvablePlaceholders" value="true"/&gt; &lt;property name="ignoreResourceNotFound" value="false"/&gt; &lt;/bean&gt; </code></pre> <p>I really like this. It's quite simple and clean with minimal XML.</p> <p>However I have one more requirement: some of these jobs can be totally disabled in some cases.</p> <p>So, before I used Spring to manage them I created them manually and there is a boolean parameter along with the cron parameter in the config files, to specify if the job has to be enabled or not:</p> <pre><code>jobs.mediafiles.imagesPurgeJob.enable=true or false jobs.mediafiles.imagesPurgeJob.schedule=0 0 0/12 * * ? </code></pre> <p>How can I use this parameter in Spring to conditionally create or just plainly ignore the bean, depending on this config parameter?</p> <p>One obvious workaround would be to define a cron pattern that would never evaluate, so the job is never executed. But the bean would still be created and the config would be a bit obscure, so I feel there must be a better solution.</p>
18,406,954
11
4
null
2013-08-23 15:36:28.18 UTC
18
2021-04-21 18:24:55.687 UTC
2018-09-11 11:19:05.427 UTC
null
1,481,116
null
315,677
null
1
97
java|spring|cron|scheduled-tasks
136,114
<pre><code>@Component public class ImagesPurgeJob implements Job { private Logger logger = Logger.getLogger(this.getClass()); @Value("${jobs.mediafiles.imagesPurgeJob.enable}") private boolean imagesPurgeJobEnable; @Override @Transactional(readOnly=true) @Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}") public void execute() { //Do something //can use DAO or other autowired beans here if(imagesPurgeJobEnable){ Do your conditional job here... } } } </code></pre>
18,414,804
android edittext remove focus after clicking a button
<p>I have an Activity with an EditText and a Button. When the User clicks on the EditText, the keyboard is shown and he can type in some Text - fine. But when the user clicks on the Button I want the EditText to be no more in focus i.e. the keyboard hides til the user clicks again on the EditText. </p> <p>What can I do to 'hide the focus' of the EditText, after the Button is clicked. Some Code I can add in the OnClick Method of the Button to do that?</p> <p>EDIT:</p> <pre class="lang-xml prettyprint-override"><code>&lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;EditText android:id="@+id/edt_SearchDest" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="0.8" android:textSize="18sp" android:hint="Enter your look-up here.." /&gt; &lt;Button android:id="@+id/btn_SearchDest" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="0.2" android:text="Search" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Best Regards</p>
18,415,233
12
2
null
2013-08-24 04:02:58.007 UTC
7
2021-12-15 09:13:11.667 UTC
2013-12-26 02:44:27.433 UTC
null
2,554,605
null
2,660,921
null
1
24
android|android-edittext
62,632
<p>Put this in your button listener:</p> <pre class="lang-java prettyprint-override"><code>InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); </code></pre> <p><strong>EDIT</strong> </p> <p>The solution above will break your app if no <code>EditText</code> is focused on. Modify your code like this:</p> <p>add this method to you class:</p> <pre class="lang-java prettyprint-override"><code>public static void hideSoftKeyboard (Activity activity, View view) { InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0); } </code></pre> <p>Then, in your button listener, call the method like this:</p> <pre class="lang-java prettyprint-override"><code>hideSoftKeyboard(MainActivity.this, v); // MainActivity is the name of the class and v is the View parameter used in the button listener method onClick. </code></pre>
15,195,578
how to explain return statement within constructor?
<p>as far as i know , the constructor return nothing , not even void , </p> <p>and also</p> <pre><code>return ; </code></pre> <p>inside any method means to return void .</p> <p>so in my program</p> <pre><code>public class returnTest { public static void main(String[] args) { returnTest obj = new returnTest(); System.out.println("here1"); } public returnTest () { System.out.println("here2"); return ; } } </code></pre> <p>i am calling </p> <pre><code>return; </code></pre> <p>which will be returning VOID , but constructor is not supposed to return anything , the program compiles just fine .</p> <p>please explain .</p>
15,195,610
6
4
null
2013-03-04 06:09:43.527 UTC
8
2018-06-01 01:15:59.567 UTC
2013-03-04 06:28:05.503 UTC
null
1,283,215
null
1,283,215
null
1
14
java|constructor|return
22,148
<p><code>return</code> in a constructor just jumps out of the constructor at the specified point. You might use it if you don't need to fully initialize the class in some circumstances.</p> <p>e.g.</p> <pre><code>// A real life example class MyDate { // Create a date structure from a day of the year (1..366) MyDate(int dayOfTheYear, int year) { if (dayOfTheYear &lt; 1 || dayOfTheYear &gt; 366) { mDateValid = false; return; } if (dayOfTheYear == 366 &amp;&amp; !isLeapYear(year)) { mDateValid = false; return; } // Continue converting dayOfTheYear to a dd/mm. // ... </code></pre>
43,804,503
Jackson Converting String to Object
<p><strong>Link.java</strong></p> <pre><code>@JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "rel", "href","method" }) public class Link { @JsonProperty("rel") private String rel; @JsonProperty("href") private String href; @JsonProperty("method") private Method method; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } </code></pre> <p>I have this third party class with fasterxml jackson annotations. I can convert a given object into a string using the specified toString() method. Is there any way of using that String to get an object of type Link?</p> <p>Note: The object itself has an embedded object (which has several more embedded objects) and these too needs to be converted into a Method object from the string itself.</p>
43,933,606
1
4
null
2017-05-05 12:05:10.243 UTC
2
2017-05-12 09:02:30.963 UTC
2017-05-05 12:13:57.12 UTC
null
3,162,450
null
3,162,450
null
1
10
java|json|spring-boot|jackson|fasterxml
46,653
<p>Just putting the comment by @pvpkiran in an answer.</p> <p>Use <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html" rel="noreferrer">ObjectMapper</a> class from <em>com.fasterxml.jackson.databind</em></p> <pre><code>ObjectMapper objectMapper = new ObjectMapper(); </code></pre> <p><strong>Converting from Object to String:</strong></p> <pre><code>String jsonString = objectMapper.writeValueAsString(link); </code></pre> <p><strong>Converting from String to Object:</strong></p> <pre><code>Link link = objectMapper.readValue(jsonString, type) </code></pre>
8,012,799
Do we still need to use <font> tags in HTML emails?
<p>I'm taking over from someone who builds our HTML emails and the templates are filled with font tags. Is this really necessary? I know CSS support isn't great in emails, but if I set an inline style for text on the container <code>&lt;td&gt;</code> like this...</p> <pre><code>&lt;td style="font-family:Arial, Helvetica;color:#555555;font-size:12px"&gt; </code></pre> <p>...then surely this will work across the majority of email clients. From the tests I've performed this seems to be the case, and <a href="http://24ways.org/2009/rock-solid-html-emails">this article</a> seems to confirm this.</p> <p>Anyone have any input as to whether <code>&lt;font&gt;</code> tags are really necessary in HTML emails?</p>
8,012,836
2
0
null
2011-11-04 16:43:36.28 UTC
12
2015-11-09 18:50:18.98 UTC
2011-11-04 16:52:14.593 UTC
null
20,578
null
467,859
null
1
36
html|email|html-email
32,831
<p>Your assumption is correct. They're unnecessary. Also, technically the <code>&lt;font&gt;</code> tag was deprecated starting with HTML 4, so you might as well remove it for that sake alone.</p> <p>If you needed inline css styles on specific text, you would be better of using an inline-styled <code>&lt;span&gt;</code> tag than a <code>&lt;font&gt;</code> tag.</p> <p>Campaign Monitor has a great and up-to-date resource on current <a href="http://www.campaignmonitor.com/css/" rel="nofollow noreferrer">CSS support in emails</a>.</p>
8,749,186
How to detect if a long type is actually NULL?
<p>We have a nullable (type long) column (named referral) in our MySQL database. We use hibernate for ORM.</p> <p>I am trying to get the value of the column for a given member. Some are null, and if its not, its an id that points to another member whose is the referrer.</p> <p>The problem is in the java code I am trying to detect if that member's column is null, if not, do something.</p> <pre><code>String referrerAffiliateId = Long.toString(member.getReferral()); if (referrerAffiliateId != null){ //do something } </code></pre> <p>member.getReferral() returns the value (type long) of the referral column. Some of those columns are null and some are not.</p> <p>The above code compiles fine, but I get a nullPointerException when I call the method on a user whose referral column is null.</p> <p>How do I properly do a detection on this?</p> <p>Thanks in advance!</p> <p><strong>Full Answer:</strong></p> <p>Thanks to @Marcelo for the best correct answer.</p> <p>Here is the code in its final state:</p> <pre><code>Long referrerAffiliateId = member.getReferral(); if (referrerAffiliateId != null) { //... } </code></pre>
8,749,227
4
3
null
2012-01-05 20:19:56.063 UTC
null
2020-06-18 23:17:03.06 UTC
2012-01-05 20:41:38.317 UTC
null
358,834
null
358,834
null
1
6
java|hibernate|nullpointerexception|long-integer
45,174
<p>Assuming <code>member.getReferral()</code> returns a <code>Long</code>, use:</p> <pre><code>if (member.getReferral() != null) </code></pre> <p>In Hibernate, if you want to be able to detect nullability in a property, you must not use <em>primitive types</em>, because they will always have a default value <code>0</code> for longs.</p>
5,159,352
Error converting data type bigint to varchar.
<pre><code>DECLARE @ID BIGINT set @ID = 1323 UPDATE School SET RegistrationFee = 'fee_' + @ID --&lt;&lt;&lt;&lt;error Where SchoolRegistrationId = 123 </code></pre> <p>Error converting data type varchar to bigint.</p>
5,159,362
4
0
null
2011-03-01 19:30:35.12 UTC
1
2019-03-29 15:51:51.94 UTC
2014-05-28 18:39:07.78 UTC
null
1,378,356
null
275,390
null
1
12
sql-server|sql-server-2008
57,803
<p>You need to explicitly convert your bigint to varchar:</p> <pre><code>DECLARE @ID BIGINT set @ID = 1323 UPDATE School SET RegistrationFee = 'fee_' + CAST(@ID AS VARCHAR(15)) WHERE SchoolRegistrationId = 123 </code></pre> <p>T-SQL will not do this automatically for you - you need to be explicit and clear about it.</p>
5,356,133
How to replace underscores with spaces using a regex in Javascript
<p>How can I replace underscores with spaces using a regex in Javascript?</p> <pre><code>var ZZZ = "This_is_my_name"; </code></pre>
5,356,251
4
4
null
2011-03-18 18:13:21.077 UTC
5
2012-08-15 13:48:18.83 UTC
2011-03-18 18:48:48.717 UTC
null
19,719
null
603,380
null
1
24
javascript|regex|replace
71,745
<p>If it is a JavaScript code, write this, to have transformed string in <code>ZZZ2</code>:</p> <pre><code>var ZZZ = "This_is_my_name"; var ZZZ2 = ZZZ.replace(/_/g, " "); </code></pre> <p>also, you can do it in less efficient, but more funky, way, without using regex:</p> <pre><code>var ZZZ = "This_is_my_name"; var ZZZ2 = ZZZ.split("_").join(" "); </code></pre>
5,085,656
How to get the current port number in Flask?
<p>Using <a href="http://flask.pocoo.org/" rel="noreferrer">Flask</a>, how can I get the current port number that flask is connected to? I want to start a server on a random port using port 0 but I also need to know which port I am on.</p> <p><strong>Edit</strong></p> <p>I think I've found a work around for my issue, although it isn't an answer to the question. I can iterate through ports starting with 49152 and attempt to use that port through <code>app.run(port=PORT)</code>. I can do this in a try catch block so that if I get an <code>Address already in use</code> error, I can try the next port.</p>
5,089,963
5
1
null
2011-02-23 00:14:43.2 UTC
12
2018-08-24 22:03:16.21 UTC
2011-02-23 08:03:41.1 UTC
null
477,933
null
477,933
null
1
27
python|networking|web-frameworks|flask
33,679
<p>You can't easily get at the server socket used by Flask, as it's hidden in the internals of the standard library (Flask uses Werkzeug, whose development server is based on the stdlib's <code>BaseHTTPServer</code>).</p> <p>However, you can create an ephemeral port yourself and then close the socket that creates it, then use that port yourself. For example:</p> <pre><code># hello.py from flask import Flask, request import socket app = Flask(__name__) @app.route('/') def hello(): return 'Hello, world! running on %s' % request.host if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) port = sock.getsockname()[1] sock.close() app.run(port=port) </code></pre> <p>will give you the port number to use. An example run:</p> <pre><code>$ python hello.py * Running on http://127.0.0.1:34447/ </code></pre> <p>and, on browsing to <a href="http://localhost:34447/" rel="noreferrer">http://localhost:34447/</a>, I see</p> <blockquote> <p>Hello, world! running on localhost:34447</p> </blockquote> <p>in my browser.</p> <p>Of course, if something else uses that port between you closing the socket and then Flask opening the socket with that port, you'd get an "Address in use" error, but you may be able to use this technique in your environment.</p>
5,322,642
SSIS - Flat file always ANSI never UTF-8 encoded
<p>Have a pretty straight forward SSIS package:</p> <ul> <li>OLE DB Source to get data via a view, (all string columns in db table nvarchar or nchar).</li> <li>Derived Column to format existing date and add it on to the dataset, (data type DT_WSTR).</li> <li>Multicast task to split the dataset between: <ul> <li>OLE DB Command to update rows as "processed". </li> <li>Flat file destination - the connection manager of which is set to Code Page 65001 UTF-8 and Unicode is unchecked. All string columns map to DT_WSTR.</li> </ul></li> </ul> <p>Everytime I run this package an open the flat file in Notepad++ its ANSI, never UTF-8. If I check the Unicode option, the file is UCS-2 Little Endian.</p> <p>Am I doing something wrong - how can I get the flat file to be UTF-8 encoded?</p> <p>Thanks</p>
5,518,350
6
2
null
2011-03-16 08:26:01.223 UTC
8
2020-11-18 18:54:03.67 UTC
null
null
null
null
298,426
null
1
21
utf-8|ssis|flat-file
69,551
<p>OK - seemed to have found an acceptable work-around on <a href="http://social.msdn.microsoft.com/forums/en-us/sqlintegrationservices/thread/9B68C357-A5B4-47BF-8EFD-A05945210CA2" rel="nofollow">SQL Server Forums</a>. Essentially I had to create two UTF-8 template files, use a File Task to copy them to my destination then make sure I was appending data rather than overwriting.</p>
5,227,295
How do I delete all lines in a file starting from after a matching line?
<p>I have a file which is made up of several lines of text:</p> <pre><code>The first line The second line The third line The fourth line </code></pre> <p>I have a string which is one of the lines: <code>The second line</code></p> <p>I want to delete the string and all lines after it in the file, so it will delete <code>The third line</code> and <code>The fourth line</code> in addition to the string. The file would become:</p> <pre><code>The first line </code></pre> <p>I've searched for a solution on google, and it seems that I should use <code>sed</code>. Something like:</p> <pre><code>sed 'linenum,$d' file </code></pre> <p>But how to find the line number of the string? Or, how else should I do it?</p>
5,227,429
6
4
null
2011-03-08 01:23:43.233 UTC
32
2018-01-25 18:21:03.867 UTC
2011-10-27 14:44:35.76 UTC
null
115,845
null
500,281
null
1
107
linux|bash|sed
110,319
<p>If you don't want to print the matched line (or any following lines):</p> <pre><code>sed -n '/The second line/q;p' inputfile </code></pre> <p>This says "when you reach the line that matches the pattern quit, otherwise print each line". The <code>-n</code> option prevents implicit printing and the <code>p</code> command is required to explicitly print lines.</p> <p>or</p> <pre><code>sed '/The second line/,$d' inputfile </code></pre> <p>This says "delete all lines from the output starting at the matched line and continuing to the end of the file".</p> <p>but the first one is faster. However it will quit processing completely so if you have multiple files as arguments, the ones after the first matching file won't be processed. In this case, the delete form is better.</p> <p>If you do want to print the matched line, but not any following lines:</p> <pre><code>sed '/The second line/q' inputfile </code></pre> <p>This says "print all lines and quit when the matched line is reached" (the <code>-n</code> option (no implicit print) is not used).</p> <p>See <a href="https://linux.die.net/man/1/sed" rel="noreferrer">man sed</a> for additional information.</p>
5,416,872
Using export keyword with templates
<p>As i Understand "export" keyword can be used so that one can expose template classes or function signatures through an header file and abstract the actual implementation in a library file.<br> Can anyone please provide a practical sample program which shows how to do this?<br> Are there any disadvantages or important points to note while using this? </p> <p>EDIT: A follow up question based on the answers. As mentioned in the answers 'export' is deprecated in C++0x and rarely supported by compilers even for C++03x. Given this situation, in what way can one hide actual implementations in lib files and just expose declarations through header files, So that end user can know what are the signatures of the exposed API but not have access to the source code implementing the same?</p>
5,416,981
7
5
null
2011-03-24 09:07:26.817 UTC
8
2022-09-19 12:01:18.31 UTC
2011-03-24 09:38:37.32 UTC
null
452,307
null
452,307
null
1
38
c++|templates|c++11|export
31,269
<p><strong>Attention: This answer is about the historical use of <code>export</code> pre-C++20; C++20 repurposes the keyword for use in modules.</strong></p> <p>First of all: most compilers (including gcc, Clang and Visual Studio) do not support the <code>export</code> keyword.</p> <p>It has been implemented in a single front-end: the EDG front-end, and thus only the compilers that use it (Comeau and icc) support this feature. The feedback from the implementers at EDG was extremely simple: <em>it took us time, was extremely complicated, we recommend not to implement it</em> (1), as a consequence it has been dropped in C++0x.</p> <p>Now, the standard allows (and this is implemented by at least gcc):</p> <ul> <li>to declare a specialized version of a template function in a header</li> <li>to define this specialization in a single source file</li> </ul> <p>and to have it behave as you'd expect from a regular function.</p> <p><em>Note: as Johannes points out in a comment, if a full specialization of a function is defined in a header, it must be marked as inline otherwise the linker will complains.</em></p> <p><strong>EDIT:</strong></p> <p>(1) Finally found my reference <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf" rel="nofollow noreferrer">Why can't we afford export (PDF)</a> by Tom Plum, reviewed by Steve Adamczyk, John Spicer, and Daveed Vandevoorde of Edison Design Group who originally implemented it in the EDG front end.</p>
5,433,977
What about Line Breaks in Jade?
<p>I'm pretty sure that this is a no-brainer but I didn't find any snippet of sample code. What's the best way to insert line breaks (aka the good ol' br/)?</p> <p>As far as I can see if I put a "br" at the beginning of an empty line, it is rendered as <code>&lt;br/&gt;</code> but if I have to show several lines of text, the resulting code is quite verbose:</p> <pre><code>.poem p | Si chiamava Tatiana, la sorella… br | Noi siamo i primi, almeno lo crediamo br | Che un tale nome arditamente nella br | Cornice d’un romanzo introduciamo. br | E che dunque? E’ piacevole, sonoro. br | Lo so che a molti privo di decoro br | Apparirà, già fuori moda, e degno br | Piuttosto d’un ancella, certo segno, br | confessiamolo pur senza paura, br | di quanto s’è noialtri al gusto avversi br | nei nostri nomi (a non parlar di versi). |br br | Credemmo conquistare la cultura, br | e non ne abbiamo preso, in conclusione, br | che la ricerca dell’affettazione. </code></pre> <p>Is there a better way to solve this? (incidentally I'm asking for the same thing with the image tag...)</p>
6,752,736
12
2
null
2011-03-25 14:43:25.13 UTC
11
2022-01-24 17:01:12.83 UTC
2015-05-23 09:03:27.35 UTC
null
2,476,755
null
162,293
null
1
73
node.js|pug
81,313
<p>The cleanest and easiest solution is to use the style attribute <code>white-space: pre;</code> eg:</p> <pre><code>.poem p(style='white-space:pre;') | Si chiamava Tatiana, la sorella… | Noi siamo i primi, almeno lo crediamo | Che un tale nome arditamente nella | Cornice d’un romanzo introduciamo. | E che dunque? E’ piacevole, sonoro. | Lo so che a molti privo di decoro | Apparirà, già fuori moda, e degno | Piuttosto d’un ancella, certo segno, | confessiamolo pur senza paura, | di quanto s’è noialtri al gusto avversi | nei nostri nomi (a non parlar di versi). |br | Credemmo conquistare la cultura, | e non ne abbiamo preso, in conclusione, | che la ricerca dell’affettazione. </code></pre>
5,207,162
Define a fixed-size list in Java
<p>Is it possible to define a list with a fixed size that's 100? If not why isn't this available in Java?</p>
5,968,535
14
8
null
2011-03-05 22:17:24.193 UTC
16
2022-08-11 17:55:43.057 UTC
2017-07-08 14:53:29.99 UTC
null
964,243
null
184,730
null
1
72
java|list|collections
177,211
<h1><code>FixedSizeList</code></h1> <p><strong>Yes</strong>,</p> <p>The <a href="https://commons.apache.org/collections/" rel="nofollow noreferrer"><em>Apache Commons</em></a> library provides the <a href="https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/list/FixedSizeList.html" rel="nofollow noreferrer"><code>FixedSizeList</code></a> class which does not support the <code>add</code>, <code>remove</code> and <code>clear</code> methods (but the set method is allowed because it does not modify the <code>List</code>'s size). Ditto for <a href="https://www.eclipse.org/collections/javadoc/11.1.0/org/eclipse/collections/api/list/FixedSizeList.html" rel="nofollow noreferrer"><code>FixedSizeList</code></a> in <a href="https://www.eclipse.org/collections/" rel="nofollow noreferrer">Eclipse Collections</a>. If you try to call one of these methods, your list remains the same size.</p> <p>To create your fixed size list, just call</p> <pre><code>List&lt;YourType&gt; fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100])); </code></pre> <hr /> <p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-" rel="nofollow noreferrer"><code>unmodifiableList</code></a> if you want an unmodifiable view of the specified list, or <strong>read-only access to internal lists</strong>.</p> <pre><code>List&lt;YourType&gt; unmodifiable = java.util.Collections.unmodifiableList(internalList); </code></pre>
5,309,190
android pick images from gallery
<p>I want to create a picture chooser from gallery. I use code </p> <pre><code> intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, TFRequestCodes.GALLERY); </code></pre> <p>My problem is that in this activity and video files are displayed. Is there a way to filter displayed files so that no video files will be displayed in this activity?</p>
5,309,217
19
2
null
2011-03-15 08:33:46.763 UTC
88
2022-09-17 11:25:48.057 UTC
2013-03-12 15:20:23.647 UTC
null
489,741
null
517,558
null
1
235
android|gallery|action
414,650
<p>Absolutely. Try this:</p> <pre><code>Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); </code></pre> <p>Don't forget also to create the constant <strong>PICK_IMAGE</strong>, so you can recognize when the user comes back from the image gallery Activity:</p> <pre><code>public static final int PICK_IMAGE = 1; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_IMAGE) { //TODO: action } } </code></pre> <p>That's how I call the image gallery. Put it in and see if it works for you.</p> <p>EDIT:</p> <p>This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:</p> <pre><code> Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); getIntent.setType("image/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, "Select Image"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); startActivityForResult(chooserIntent, PICK_IMAGE); </code></pre>
5,014,632
How can I parse a YAML file from a Linux shell script?
<p>I wish to provide a structured configuration file which is as easy as possible for a non-technical user to edit (unfortunately it has to be a file) and so I wanted to use YAML. I can't find any way of parsing this from a Unix shell script however. </p>
13,179,142
23
5
null
2011-02-16 09:25:38.033 UTC
111
2022-07-05 12:26:50.797 UTC
null
null
null
null
190,822
null
1
309
shell|yaml
393,425
<p>My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.</p> <p>I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.</p> <p>YAML looks like so:</p> <pre><code>KEY: value ANOTHER_KEY: another_value OH_MY_SO_MANY_KEYS: yet_another_value LAST_KEY: last_value </code></pre> <p>Output like-a dis:</p> <pre><code>KEY="value" ANOTHER_KEY="another_value" OH_MY_SO_MANY_KEYS="yet_another_value" LAST_KEY="last_value" </code></pre> <p>I achieved the output with this line:</p> <pre><code>sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml &gt; file.sh </code></pre> <ul> <li><code>s/:[^:\/\/]/="/g</code> finds <code>:</code> and replaces it with <code>="</code>, while ignoring <code>://</code> (for URLs)</li> <li><code>s/$/"/g</code> appends <code>"</code> to the end of each line</li> <li><code>s/ *=/=/g</code> removes all spaces before <code>=</code></li> </ul>
16,718,699
Map Many to Many relationship without navigation property
<p>Is is possible to map a many to many relationship without having a navigation property on one of the ends? For example I have some widgets and some users who can star particular widgets. I'd like to be able to see what widgets a user cares stars, but I don't really care about seeing all the users who have starred a particular widget</p> <p>Widget.cs</p> <pre><code>public int Id { get; set; } public string Name { get; set; } </code></pre> <p>User.cs</p> <pre><code>public int Id { get; set; } public string Username { get; set; } public ICollection&lt;Widget&gt; StarredWidgets { get; set; } </code></pre> <p>With this setup, EF will generate a one-to-many relationship from Widgets to Users. However, it needs to be a many to many. I realize I could add a <code>public ICollection&lt;User&gt; Users</code> to <code>Widget.cs</code>, but just seeing if there was another way around this.</p>
16,719,203
1
0
null
2013-05-23 16:01:58.387 UTC
10
2013-05-23 16:27:49.863 UTC
null
null
null
null
228,014
null
1
13
ef-code-first|entity-framework-5
8,271
<p>You can and this case <em>must</em> define the many-to-many relationship with Fluent API:</p> <pre><code>modelBuilder.Entity&lt;User&gt;() .HasMany(u =&gt; u.StarredWidgets) .WithMany() // &lt;- no parameter here because there is no navigation property .Map(m =&gt; { m.MapLeftKey("UserId"); m.MapRightKey("WidgetId"); m.ToTable("UserWidgets"); }); </code></pre>
41,458,859
How do you create a boolean mask for a tensor in Keras?
<p>I am building a custom metric to measure the accuracy of one class in my multi-class dataset during training. I am having trouble selecting the class. </p> <p>The targets are one hot (e.g: the class <code>0</code> label is <code>[1 0 0 0 0]</code>):</p> <pre><code>from keras import backend as K def single_class_accuracy(y_true, y_pred): idx = bool(y_true[:, 0]) # boolean mask for class 0 class_preds = y_pred[idx] class_true = y_true[idx] class_acc = K.mean(K.equal(K.argmax(class_true, axis=-1), K.argmax(class_preds, axis=-1))) # multi-class accuracy return class_acc </code></pre> <p>The trouble is, we have to use Keras functions to index tensors. How do you create a boolean mask for a tensor?</p>
41,717,938
1
3
null
2017-01-04 07:58:47.49 UTC
12
2020-01-22 14:40:24.06 UTC
2020-01-22 14:40:24.06 UTC
null
3,924,118
null
4,013,781
null
1
20
python|tensorflow|neural-network|keras
8,948
<p>Note that when talking about the <em>accuracy</em> of one class one may refer to either of the following (not equivalent) two amounts:</p> <ul> <li>The <strong>recall</strong>, which, for class <em>C</em>, is the ratio of examples labelled with class <em>C</em> that are predicted to have class <em>C</em>.</li> <li>The <strong>precision</strong>, which, for class <em>C</em>, is the ratio of examples predicted to be of class <em>C</em> that are in fact labelled with class <em>C</em>.</li> </ul> <p>Instead of doing complex indexing, you can just rely on masking for you computation. Assuming we are talking about precision here (changing to recall would be trivial).</p> <pre><code>from keras import backend as K INTERESTING_CLASS_ID = 0 # Choose the class of interest def single_class_accuracy(y_true, y_pred): class_id_true = K.argmax(y_true, axis=-1) class_id_preds = K.argmax(y_pred, axis=-1) # Replace class_id_preds with class_id_true for recall here accuracy_mask = K.cast(K.equal(class_id_preds, INTERESTING_CLASS_ID), 'int32') class_acc_tensor = K.cast(K.equal(class_id_true, class_id_preds), 'int32') * accuracy_mask class_acc = K.sum(class_acc_tensor) / K.maximum(K.sum(accuracy_mask), 1) return class_acc </code></pre> <p>If you want to be more flexible, you can also have the class of interest parametrised:</p> <pre><code>from keras import backend as K def single_class_accuracy(interesting_class_id): def fn(y_true, y_pred): class_id_true = K.argmax(y_true, axis=-1) class_id_preds = K.argmax(y_pred, axis=-1) # Replace class_id_preds with class_id_true for recall here accuracy_mask = K.cast(K.equal(class_id_preds, interesting_class_id), 'int32') class_acc_tensor = K.cast(K.equal(class_id_true, class_id_preds), 'int32') * accuracy_mask class_acc = K.sum(class_acc_tensor) / K.maximum(K.sum(accuracy_mask), 1) return class_acc return fn </code></pre> <p>And the use it as:</p> <pre><code>model.compile(..., metrics=[single_class_accuracy(INTERESTING_CLASS_ID)]) </code></pre>
12,112,259
how to reuse stringstream
<p>These threads do NOT answer me:</p> <p><a href="https://stackoverflow.com/questions/7623650/">resetting a stringstream</a></p> <p><a href="https://stackoverflow.com/questions/20731/">How do you clear a stringstream variable?</a></p> <pre class="lang-cpp prettyprint-override"><code>std::ifstream file( szFIleName_p ); if( !file ) return false; // create a string stream for parsing std::stringstream szBuffer; std::string szLine; // current line std::string szKeyWord; // first word on the line identifying what data it contains while( !file.eof()){ // read line by line std::getline(file, szLine); // ignore empty lines if(szLine == &quot;&quot;) continue; szBuffer.str(&quot;&quot;); szBuffer.str(szLine); szBuffer&gt;&gt;szKeyWord; </code></pre> <p><code>szKeyword</code> will always contain the first word, <code>szBuffer</code> is not being reset. I can't find a clear example anywhere on how to use stringstream.</p> <p>New code after answer:</p> <pre class="lang-cpp prettyprint-override"><code>... szBuffer.str(szLine); szBuffer.clear(); szBuffer&gt;&gt;szKeyWord; ... </code></pre> <p>Ok, thats my final version:</p> <pre class="lang-cpp prettyprint-override"><code>std::string szLine; // current line std::string szKeyWord; // first word on the line identifying what data it contains // read line by line while( std::getline(file, szLine) ){ // ignore empty lines if(szLine == &quot;&quot;) continue; // create a string stream for parsing std::istringstream szBuffer(szLine); szBuffer&gt;&gt;szKeyWord; </code></pre>
12,112,355
6
1
null
2012-08-24 15:21:55.573 UTC
2
2021-03-04 05:07:49.477 UTC
2021-03-04 05:07:49.477 UTC
null
65,863
null
1,513,481
null
1
22
c++|file|parsing|text|stringstream
38,468
<p>You didn't <code>clear()</code> the stream after calling <code>str("")</code>. Take another look at <a href="https://stackoverflow.com/questions/20731/in-c-how-do-you-clear-a-stringstream-variable">this answer</a>, it also explains why you should reset using <code>str(std::string())</code>. And in your case, you could also reset the contents using only <code>str(szLine)</code>.</p> <p>If you don't call <code>clear()</code>, the flags of the stream (like <code>eof</code>) wont be reset, resulting in surprising behaviour ;)</p>
12,168,587
How to synchronize multiple Backbone.js fetches?
<p>I’m a bit new to Backbone.js, but am already impressed by everything it can do for me, and am trying to learn the patterns and best practices now.</p> <p>I have two collections:</p> <pre><code>var CollA = Backbone.Collection.extend({ model: ModelA, url: '/urlA' }); var CollB = Backbone.Collection.extend({ model: ModelB, url: '/urlB' }); var collA = new CollA; var collB = new CollB; </code></pre> <p>When loading my app, I need to fetch both of these collections from the server, and run some bootstrap code when it’s guaranteed that both fetches have completed.</p> <p>Here’s how I did it for now:</p> <pre><code>collA.fetch({success: function() { collB.fetch({success: function() { // run the needed code here. }}); }}); </code></pre> <p>This works, the needed code is guaranteed to run only after both fetches complete successfully. It is clearly inefficient though, because the fetches run serially, one after another.</p> <p>What would be a better pattern to do this, to run the fetches in parallel and then run some code once both fetches have completed successfully?</p>
12,168,628
3
0
null
2012-08-28 22:44:56.673 UTC
12
2016-05-19 17:01:53.633 UTC
null
null
null
null
49,951
null
1
24
concurrency|backbone.js
12,220
<p>If you're using jQuery, use <code>when</code>:</p> <pre><code>$.when(collA.fetch(),collB.fetch()).done(function(){ //success code here. }); </code></pre> <p>Background:</p> <ul> <li><a href="http://api.jquery.com/jQuery.when/">http://api.jquery.com/jQuery.when/</a></li> <li><a href="http://documentcloud.github.com/backbone/#Collection-fetch">http://documentcloud.github.com/backbone/#Collection-fetch</a></li> </ul> <p>You pass in one or more deferreds to <code>$.when</code>. It so happens that the "jqXHR" that collections return implements the promise/Deferred interface that can be combined into a new promise using <code>$.when</code>. The requests will essentially be concurrent (well, as much as javascript allows) and the function passed to <code>.done</code> will execute only when both fetches are successful. </p>
12,569,568
Shopping cart persistence: $_SESSION or browser cookie?
<p>On an e-commerce site with no username/login to persist cart data, would it be better to use the PHP $_SESSION variable or a browser cookie to persist items in the shopping cart? I am leaning toward $_SESSION since cookies can be disabled, but would like to hear thoughts from you.</p> <p>Thank you in advance for your consideration.</p>
12,569,786
6
5
null
2012-09-24 16:58:28.03 UTC
25
2015-08-06 06:58:02.497 UTC
null
null
null
user1193509
null
null
1
35
php|cookies|session-variables
34,319
<h2>Neither</h2> <p>No large sites would dare store a user's cart in a session or cookie - that data is just to valuable.</p> <p>What customers are buying, when they select items, how many they purchase, why they don't finish the checkout, etc.. are all <em>very, very</em> important to your business.</p> <p>Use a database table to store this information and then link it to the user's session. That way you don't lose the information and you can go back and build statistics based on users carts or solve problems with your checkout process.</p> <p>Log everything you can.</p> <h2>Database Schema</h2> <p>Below is a simplified example of how this might look at the database level.</p> <pre><code>user { id email } product { id name price } cart { id product_id user_id quantity timestamp (when was it created?) expired (is this cart still active?) } </code></pre> <p>You might also want to split the cart table out into more tables so you can track revisions to the cart.</p> <h2>Sessions</h2> <p>Normal PHP Sessions consist of two parts</p> <ol> <li>The data (stored in a file on the server)</li> <li>A unique identifier given to the user agent (browser)</li> </ol> <p>Therefore, it's not <code>$_SESSION</code> vs <code>$_COOKIE</code> - it's <code>$_SESSION</code> <strong>+</strong> <code>$_COOKIE</code> = "session". However, there are ways you can modify this by using a single encrypted cookie which contains the data (and therefore you don't need an identifier to find the data). Another common approach is to store the data in memcached or a database instead of the filesystem so that multiple servers can access it.</p> <p>What @Travesty3 is saying is that you can have <strong>two</strong> cookies - one for the session, and another that is either a "keep me logged in" cookie (which exists longer than the session cookie), or a copy of the data inside separate cookie.</p>
19,035,186
How to select element using XPATH syntax on Selenium for Python?
<p>consider following HTML:</p> <pre><code>&lt;div id='a'&gt; &lt;div&gt; &lt;a class='click'&gt;abc&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to click abc, but the wrapper div could change, so</p> <pre><code>driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']") </code></pre> <p>is not what I want</p> <p>i tried:</p> <pre><code> driver.get_element_by_xpath("//div[@id='a']").get_element_by_xpath(.//a[@class='click']") </code></pre> <p>but this would not work with deeper nesting</p> <p>any ideas?</p>
19,035,495
2
7
null
2013-09-26 17:51:20.063 UTC
9
2021-02-11 13:02:28.077 UTC
2019-05-29 16:42:25.237 UTC
null
5,780,109
null
2,534,633
null
1
34
python|xpath|selenium
172,547
<p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div id='a'&gt; &lt;div&gt; &lt;a class='click'&gt;abc&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>You could use the <strong>XPATH</strong> as :</p> <pre class="lang-xpath prettyprint-override"><code>//div[@id='a']//a[@class='click'] </code></pre> <p><strong>output</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;a class="click"&gt;abc&lt;/a&gt; </code></pre> <p>That said your Python code should be as :</p> <pre class="lang-python prettyprint-override"><code>driver.find_element_by_xpath("//div[@id='a']//a[@class='click']") </code></pre>
24,408,143
WAMP: Missing http://localhost/ in urls , wrong wamp projects links
<p>I have a problem with Wamp which never happened to me before, cannot find what's wrong. I have a few projects located in my www folder ( running windows 7 ). </p> <p>My hostfile has the line <code>127.0.0.1 localhost</code> uncommented </p> <p>When I go to <code>http://localhost/</code> or <code>http://127.0.0.1/</code> and click on a project name like "mysite" from the main Wamp panel page, the link just points to "mysite" and not <code>"http://localhost/mysite"</code></p> <p>Therefore I can't see any sites, what should I do ? </p>
27,345,153
14
5
null
2014-06-25 12:02:45.623 UTC
7
2022-06-21 17:28:00.997 UTC
2014-07-01 20:21:04.763 UTC
null
3,679,739
null
1,143,651
null
1
12
localhost|wamp|local|wampserver
47,936
<p>After thorough research, I found out the solution which worked for me as well.. </p> <pre><code>open wamp/www/index.php. </code></pre> <p>Change this line:</p> <pre><code>$suppress_localhost = true; </code></pre> <p>To :</p> <pre><code>$suppress_localhost = false; </code></pre>
3,634,023
Should I use List[A] or Seq[A] or something else?
<p>I was writing a class that contained some functional-esque methods. First I wrote them using List as parameters and return types. Then I thought "Hey, you could also use a more generic type!" so I replaced the Lists with Seq, hoping that I could make my stuff faster one day by feeding them something else than lists.</p> <p>So which general purpose stack-like data-structure shall I write my methods and algorithms for? Is there a general pattern I can stick to? All this is because the methods might need to get optimized in the future in case they will form a bottle-neck.</p> <h3>Update</h3> <p>I'll try to be a bit more precise: Given you know which operations you are using, like reversing, .tail, direct element access, or for comprehensions. Can I choose a type that will <em>force</em> efficiency on those operations?</p> <h3>Update 2</h3> <p>I'm quite aware of the performance of concrete data structures for various tasks. What I'm not aware of is which data structure might appear as a sub-class of some super type.</p> <p>For example shall I use TraversableOnce or IndexedSeq instead of List or Array? Will it buy me anything?</p> <h3>Additional Question</h3> <p>What is <em>your</em> default List-like data-structure signature? Do you write </p> <pre><code>def a(b: List[A]): List[A] </code></pre> <p>or </p> <pre><code>def a(b: TraversableOnce[A]): TraversableOnce[A] </code></pre> <p>Can you explain why?</p>
3,640,446
3
1
null
2010-09-03 08:13:02.23 UTC
10
2013-09-30 11:24:05.353 UTC
2013-09-30 11:24:05.353 UTC
null
108,915
null
108,915
null
1
16
design-patterns|scala
7,948
<p>I think, in general, you should use <code>Seq</code> for your parameters and design your methods to work efficiently with <code>List</code>. This way your methods will work ok with most <code>Seq</code> implementations and you will not have to convert your seqs prior to use your methods.</p> <p><strong>Edit</strong></p> <p>Your question has many questions inside.</p> <ol> <li>So which general purpose stack-like data-structure shall I write my methods and algorithms for? <ul> <li>I think the answer here is <code>List</code>. It's a stack and it's very fast</li> </ul></li> <li>Can I choose a type that will force efficiency on those operations? <ul> <li>In general you'll have to rely on a concerete implementation. The performance characteristics are here <a href="http://www.scala-lang.org/docu/files/collections-api/collections_40.html" rel="noreferrer">http://www.scala-lang.org/docu/files/collections-api/collections_40.html</a></li> </ul></li> <li>For example shall I use TraversableOnce or IndexedSeq instead of List or Array? Will it buy me anything? <ul> <li>Some abstractions have performance characteristics defined, some others don't. For example <code>IndexedSeq</code> scaladoc says "Indexed sequences support constant-time or near constant-time element access and length computation". If you have an <code>IndexedSeq</code> parameter and someone passes an <code>IndexedSeq</code> implementation that does not have "near-constant time element access", then that someone is breaking the contract and it's not your problem. </li> </ul></li> <li>What is your default List-like data-structure signature? <ul> <li>Seq</li> </ul></li> </ol>
3,664,440
Android - how to intercept a form POST in android WebViewClient on API level 4
<p>I have a <code>WebViewClient</code> attached to my <code>WebView</code> like so:</p> <pre><code>webView.setWebViewClient(new MyWebViewClient()); </code></pre> <p>Here is my implementation of <code>MyWebViewClient</code>:</p> <pre><code>private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { webView.loadUrl(url); return true; } } </code></pre> <p>I give the <code>WebView</code> a URL to load via <code>loadUrl()</code>. If I have a link (<code>a href...</code>) in the page, my <code>shouldOverrideUrlLoading</code> method is called and I can intercept the link click.</p> <p>However, if I have a form whose method is <code>POST</code>, the <code>shouldOverrideUrlLoading</code> method is not called.</p> <p>I noticed a similar issue here: <a href="http://code.google.com/p/android/issues/detail?id=9122" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=9122</a> which seems to suggest overriding <code>postUrl</code> in my <code>WebView</code>. However, this API is only available starting from API level 5.</p> <p>What can I do if I'm on API level 4? Is there any other way to intercept form posts?</p>
11,562,391
3
4
null
2010-09-08 03:23:42.607 UTC
8
2014-09-05 03:01:00.237 UTC
2014-09-05 03:01:00.237 UTC
null
1,725,980
null
409,127
null
1
32
android|forms|post|webviewclient
31,528
<p>This is known issue, that <code>shouldOverrideUrlLoading</code> don't catch POST. See <a href="http://code.google.com/p/android/issues/detail?id=9122" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=9122</a> for details. </p> <p>Use GET! I personally tried using POST, because I expected some limitation of GET parameters (i.e. length of URL), but I just successfully passed 32000 bytes through GET locally without any problems. </p>
3,479,737
Sinatra - API - Authentication
<p>We going to develop a little API application in Sinatra. What are the authentication options available to secure the API calls?</p>
3,482,605
3
0
null
2010-08-13 18:37:17.657 UTC
46
2020-01-28 17:43:46.997 UTC
2014-03-26 11:18:01.863 UTC
null
23,855
null
170,311
null
1
59
api|authentication|sinatra
14,780
<p>Sinatra has no built-in authentication support. There are some gems available, but most are designed for user authentication (i.e. for a website). For an API, they seem like overkill. It’s easy enough to make your own. Simply check the request params in each of your routes to see if they contain a valid API key, and if not, return a 401 error.</p> <pre><code>helpers do def valid_key? (key) false end end get "/" do error 401 unless valid_key?(params[:key]) "Hello, world." end # $ irb -r open-uri # &gt;&gt; open("http://yourapp.com/api/?key=123") # OpenURI::HTTPError: 401 Unauthorized </code></pre> <p>Nothing after the call to <code>error</code> will happen if your <code>valid_key?</code> method returns false — <code>error</code> calls <code>halt</code> internally, which stops the request from continuing.</p> <p>Of course, it’s not ideal to repeat the check at the beginning of each route. Instead, you can create a small extension that adds conditions to your routes:</p> <pre><code>class App &lt; Sinatra::Base register do def check (name) condition do error 401 unless send(name) == true end end end helpers do def valid_key? params[:key].to_i % 2 &gt; 0 end end get "/", :check =&gt; :valid_key? do [1, 2, 3].to_json end end </code></pre> <p>If you just want authentication on all your routes, use a <code>before</code> handler:</p> <pre><code>before do error 401 unless params[:key] =~ /^xyz/ end get "/" do {"e" =&gt; mc**2}.to_json end </code></pre>
36,794,433
Python: using multiprocessing on a pandas dataframe
<p>I want to use <code>multiprocessing</code> on a large dataset to find the distance between two gps points. I constructed a test set, but I have been unable to get <code>multiprocessing</code> to work on this set.</p> <pre><code>import pandas as pd from geopy.distance import vincenty from itertools import combinations import multiprocessing as mp df = pd.DataFrame({'ser_no': [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 'co_nm': ['aa', 'aa', 'aa', 'bb', 'bb', 'bb', 'bb', 'cc', 'cc', 'cc'], 'lat': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'lon': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]}) def calc_dist(x): return pd.DataFrame( [ [grp, df.loc[c[0]].ser_no, df.loc[c[1]].ser_no, vincenty(df.loc[c[0], x], df.loc[c[1], x]) ] for grp,lst in df.groupby('co_nm').groups.items() for c in combinations(lst, 2) ], columns=['co_nm','machineA','machineB','distance']) if __name__ == '__main__': pool = mp.Pool(processes = (mp.cpu_count() - 1)) pool.map(calc_dist, ['lat','lon']) pool.close() pool.join() </code></pre> <p>I am using Python 2.7.11 and Ipython 4.1.2 with Anaconda 2.5.0 64-bit on Windows7 Professional when this error occurs.</p> <blockquote> <p>runfile('C:/.../Desktop/multiprocessing test.py', wdir='C:/.../Desktop') Traceback (most recent call last):</p> <p>File "", line 1, in runfile('C:/.../Desktop/multiprocessing test.py', wdir='C:/.../Desktop')</p> <p>File "C:...\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile execfile(filename, namespace)</p> <p>File "C:...\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc)</p> <p>File "C:/..../multiprocessing test.py", line 33, in pool.map(calc_dist, ['lat','lon'])</p> <p>File "C:...\AppData\Local\Continuum\Anaconda2\lib\multiprocessing\pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get()</p> <p>File "C:...\Local\Continuum\Anaconda2\lib\multiprocessing\pool.py", line 567, in get raise self._value</p> <p>TypeError: Failed to create Point instance from 1.</p> </blockquote> <pre><code>def get(self, timeout=None): self.wait(timeout) if not self._ready: raise TimeoutError if self._success: return self._value else: raise self._value </code></pre>
36,851,214
4
10
null
2016-04-22 12:54:24.533 UTC
29
2022-05-17 03:19:31.227 UTC
2016-04-22 16:17:14.893 UTC
null
2,213,669
null
2,213,669
null
1
52
python|pandas|multiprocessing
95,600
<h2>What's wrong</h2> <p>This line from your code:</p> <pre><code>pool.map(calc_dist, ['lat','lon']) </code></pre> <p>spawns 2 processes - one runs <code>calc_dist('lat')</code> and the other runs <code>calc_dist('lon')</code>. Compare the first example in <a href="https://docs.python.org/2.7/library/multiprocessing.html" rel="noreferrer">doc</a>. (Basically, <code>pool.map(f, [1,2,3])</code> calls <code>f</code> three times with arguments given in the list that follows: <code>f(1)</code>, <code>f(2)</code>, and <code>f(3)</code>.) If I'm not mistaken, your function <code>calc_dist</code> can only be called <code>calc_dist('lat', 'lon')</code>. And it doesn't allow for parallel processing.</p> <h2><strong>Solution</strong></h2> <p>I believe you want to split the work between processes, probably sending each tuple <code>(grp, lst)</code> to a separate process. The following code does exactly that. </p> <p>First, let's prepare for splitting:</p> <pre><code>grp_lst_args = list(df.groupby('co_nm').groups.items()) print(grp_lst_args) [('aa', [0, 1, 2]), ('cc', [7, 8, 9]), ('bb', [3, 4, 5, 6])] </code></pre> <p>We'll send each of these tuples (here, there are three of them) as an argument to a function in a separate process. We need to rewrite the function, let's call it <code>calc_dist2</code>. For convenience, it's argument is a tuple as in <code>calc_dist2(('aa',[0,1,2]))</code></p> <pre><code>def calc_dist2(arg): grp, lst = arg return pd.DataFrame( [ [grp, df.loc[c[0]].ser_no, df.loc[c[1]].ser_no, vincenty(df.loc[c[0], ['lat','lon']], df.loc[c[1], ['lat','lon']]) ] for c in combinations(lst, 2) ], columns=['co_nm','machineA','machineB','distance']) </code></pre> <p>And now comes the multiprocessing:</p> <pre><code>pool = mp.Pool(processes = (mp.cpu_count() - 1)) results = pool.map(calc_dist2, grp_lst_args) pool.close() pool.join() results_df = pd.concat(results) </code></pre> <p><code>results</code> is a list of results (here data frames) of calls <code>calc_dist2((grp,lst))</code> for <code>(grp,lst)</code> in <code>grp_lst_args</code>. Elements of <code>results</code> are later concatenated to one data frame.</p> <pre><code>print(results_df) co_nm machineA machineB distance 0 aa 1 2 156.876149391 km 1 aa 1 3 313.705445447 km 2 aa 2 3 156.829329105 km 0 cc 8 9 156.060165391 km 1 cc 8 0 311.910998169 km 2 cc 9 0 155.851498134 km 0 bb 4 5 156.665641837 km 1 bb 4 6 313.214333025 km 2 bb 4 7 469.622535339 km 3 bb 5 6 156.548897414 km 4 bb 5 7 312.957597466 km 5 bb 6 7 156.40899677 km </code></pre> <p>BTW, In Python 3 we could use a <code>with</code> construction:</p> <pre><code>with mp.Pool() as pool: results = pool.map(calc_dist2, grp_lst_args) </code></pre> <p><strong>Update</strong></p> <p>I tested this code only on linux. On linux, the read only data frame <code>df</code> can be accessed by child processes and is not copied to their memory space, but I'm not sure how it exactly works on Windows. You may consider splitting <code>df</code> into chunks (grouped by <code>co_nm</code>) and sending these chunks as arguments to some other version of <code>calc_dist</code>.</p>
26,225,191
Breakpoint debugging minfied/mangled/compiled variables
<p>Working on building JavaScript sourcemaps into my workflow and I've been looking for some documentation on a particular part of debugging source maps. In the picture below I'm running compressed Javascript code, but through the magic of source maps Chrome debugger was able to reconstruct the seemingly uncompressed code for me to debug: </p> <p><img src="https://i.stack.imgur.com/UFYyc.png" alt="Source Maps"></p> <p>However, if you look at the local variables, <code>someNumber</code> and <code>someOtherNumber</code> are not defined. Instead, we have <code>a</code> and <code>r</code>, which are the compiled variable names for this function. This is the same for both Mozilla Firefox and Chrome. </p> <p>I tried looking through the <a href="https://developer.chrome.com/devtools/docs/javascript-debugging#source-maps" rel="noreferrer">Chrome DevTools Documentation</a> on sourcemaps, but I didn't see anything written about this. Is it a current limitation of sourcemap debugging and are there any workarounds for this? </p> <p><strong>update</strong>:</p> <p>I've since found <a href="https://code.google.com/p/chromium/issues/detail?id=327092" rel="noreferrer">this thread</a> in chromium project issues. It doesn't look like it has been or is being implemented. This is becoming an increasingly more important problem as teams are beginning to implement Babel in their build systems to write ES2015 code. Have any teams found a way around this? </p>
36,050,428
3
6
null
2014-10-06 21:31:37.31 UTC
12
2016-03-17 02:09:24.39 UTC
2015-09-17 19:03:27.657 UTC
null
1,506,980
null
1,506,980
null
1
49
javascript|google-chrome|chromium|source-maps|babeljs
2,772
<p>Looks like it's been addressed and will become available <a href="https://codereview.chromium.org/1770263002" rel="nofollow">in the next Chromium update</a></p>
11,217,832
how to run a MySQL query using JavaScript
<p>I want to run MySQL query's on command without reloading the page. I think JavaScript can do this but i am unsure how. What i want to do is have a form with an return id field and when you fill out the form once with the return id and come back later and use that return id and it fills in in a lot of the content for them to save time.</p>
11,217,844
6
1
null
2012-06-27 00:34:29.717 UTC
3
2021-08-31 06:40:08.85 UTC
null
null
null
null
1,399,388
null
1
7
javascript|mysql
66,143
<p>Javascript cannot run MySQL Queries itself; however, you can use <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">ajax</a> to make a call to the server to retrieve the data. I like to use jQuery's <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">ajax()</a> for my ajax needs. </p> <p>Here is an example of how jquery's ajax() method works:</p> <pre><code>$.ajax({ url: "pathToServerFile", type: "POST", data: yourParams, dataType: "json" }); </code></pre>
11,406,628
VBA code doesn't run when cell is changed by a formula
<p><strong>Worksheet A</strong> has ranges of data that are collected from <strong>Worksheet B</strong>. <strong>Worksheet A</strong> has a macro that calculates if the data is above a value then calls an email module to email selected users. </p> <p>When the data is manually input on <strong>Worksheet A</strong> the Macro works, however when data is pulled from <strong>Worksheet B</strong> it doesn't fire.</p> <p>I'm not sure what I need to change in my VBA code. </p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) Call MailAlert(Target, "B5:M5", 4) Call MailAlert(Target, "B8:M8", 7) Call MailAlert(Target, "B11:M11", 6) Call MailAlert(Target, "B14:M14", 2) Call MailAlert(Target, "B17:M17", 4) Call MailAlert(Target, "B20:M20", 1) Call MailAlert(Target, "B23:M23", 3) Call MailAlert(Target, "B26:M26", 1) Call MailAlert(Target, "B29:M29", 5) Call MailAlert(Target, "B32:M32", 1) Call MailAlert(Target, "B35:M35", 7) Call MailAlert(Target, "B38:M38", 20) Call MailAlert(Target, "B41:M41", 0) End Sub Private Sub MailAlert(ByVal Target As Range, ByVal Address As String, ByVal Value As Integer) If Target.Cells.Count &gt; 1 Then Exit Sub If Not Application.Intersect(Range(Address), Target) Is Nothing Then If IsNumeric(Target.Value) And Target.Value &gt; Value Then Call Mail_small_Text_Outlook End If Application.EnableEvents = True End If End Sub </code></pre>
11,409,569
2
0
null
2012-07-10 04:30:39.36 UTC
11
2014-01-06 07:33:23.397 UTC
null
null
null
null
1,402,361
null
1
9
excel|vba|worksheet
52,621
<p>To capture the changes by a formula you have to use the <code>Worksheet_Calculate()</code> event. To understand how it works, let's take an example.</p> <ol> <li>Create a New Workbook.</li> <li>In Sheet1 Cell A1, put this formula <code>=Sheet2!A1+1</code></li> </ol> <p>Now In a module paste this code</p> <pre><code>Public PrevVal As Variant </code></pre> <p>Paste this in the Sheet Code area</p> <pre><code>Private Sub Worksheet_Calculate() If Range("A1").Value &lt;&gt; PrevVal Then MsgBox "Value Changed" PrevVal = Range("A1").Value End If End Sub </code></pre> <p>And lastly in the <code>ThisWorkbook</code> Code area paste this code</p> <pre><code>Private Sub Workbook_Open() PrevVal = Sheet1.Range("A1").Value End Sub </code></pre> <p>Close and Save the workbook and reopen it. Now Make any change to the cell A1 of <code>Sheet2</code>. You will notice that you will get the message box <code>MsgBox "Value Changed"</code></p> <p><strong>SNAPSHOTS</strong></p> <p><img src="https://i.stack.imgur.com/2OMbY.png" alt="enter image description here"></p>
11,328,909
UIImagePickerController tutorial?
<p>I am currently developing an application and I need to be able when pressing a button to open the camera and take a snapshot that I will attach to a .json file and send to my server. I am searching on google and StackOverflow for the last couple of hours but all the tutorials seem very old (08'-09') or not match my needs. I know that all the work is done with <code>UIImagePickerController</code> class but I would like to have a working example. Does anyone know a good tutorial to get started for something like this?</p>
11,329,034
4
0
null
2012-07-04 12:15:10.917 UTC
5
2016-04-18 17:58:31.383 UTC
2016-04-18 17:58:31.383 UTC
null
1,192,728
user1498477
null
null
1
10
ios|objective-c|swift|class|uiimagepickercontroller
43,669
<p>Well if you google something like:</p> <blockquote> <p>UIImagePickerController and take snapshot put in json and send to server</p> </blockquote> <p>Will be a bit hard. So, use <a href="http://blog.hanpo.tw/2012/01/uiimagepickercontroller-and-simple.html" rel="noreferrer">this</a> tutorial for the <code>UIImagePickerController</code>. By the way, the term for the search was:</p> <blockquote> <p>UIImagePickerController Tutorial 2012</p> </blockquote>
11,336,713
How do I create an expression tree for run time sorting?
<p>Using Entity Framework 4, I'm trying to implement dynamic sorting based on a collection of member names. Basically, the user can select fields to sort and the order of the sorting. I've looked at expression tree examples and can't piece this together. Here are some details:</p> <p>Collection of column names:</p> <pre><code>public List&lt;string&gt; sortColumns; sortColumns = new List&lt;string&gt;(); /// Example subset of video fields. The collection will vary. sortColumns.Add("Width"); sortColumns.Add("Height"); sortColumns.Add("Duration"); sortColumns.Add("Title"); </code></pre> <p>The video class is defined as follows:</p> <pre><code>public class Video { public string Title { get; set; } public int Width { get; set; } public int Height { get; set; } public float Duration { get; set; } public string Filename { get; set; } public DateTime DateCreated { get; set; } . . . } public List&lt;Video&gt; Videos; </code></pre> <p>What I would like to do is enumerate through the sortColumns collection to build an expression tree at run time. Also, the user could specify either ascending or descending sorting and the expression tree should handle either.</p> <p>I tried the Dynamic LINQ library for VS 2008, but it doesn't appear to work in VS 2010. (I could be doing something wrong.)</p> <p>The bottom line is I need an expression tree to dynamically sort the Videos collection based on user input. Any help would be appreciated.</p>
11,337,472
2
0
null
2012-07-05 00:49:04.177 UTC
10
2022-07-22 15:41:40.19 UTC
null
null
null
null
1,376,876
null
1
14
c#|entity-framework-4|lambda
5,900
<p>First you need the <code>OrderBy</code> extension method that @Slace wrote <a href="https://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on-an-iqueryable-using-a-string-column-name-within-a-gene">here</a>. All credit to <a href="https://stackoverflow.com/users/11388/slace">Slace</a> for an awesome piece of code and by far the most difficult part of the solution! I made a slight modification for it to work with your specific situation:</p> <pre class="lang-cs prettyprint-override"><code>public static class QueryableExtensions { public static IQueryable&lt;T&gt; OrderBy&lt;T&gt;(this IQueryable&lt;T&gt; source, string sortProperty, ListSortDirection sortOrder) { var type = typeof(T); var property = type.GetProperty(sortProperty); var parameter = Expression.Parameter(type, &quot;p&quot;); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); var typeArguments = new Type[] { type, property.PropertyType }; var methodName = sortOrder == ListSortDirection.Ascending ? &quot;OrderBy&quot; : &quot;OrderByDescending&quot;; var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp)); return source.Provider.CreateQuery&lt;T&gt;(resultExp); } } </code></pre> <p>Create a method to sort the list. A couple of things to note in the method below:</p> <ol> <li>The <code>List&lt;string&gt;</code> is converted to an <code>IQueryable&lt;string&gt;</code> since <code>Enumerable</code> operators don't take expression trees.</li> <li>The method iterates through the list of sort columns in reverse order (assuming you want to give the first item in the list the highest sort priority).</li> </ol> <pre class="lang-cs prettyprint-override"><code>private void PrintVideoList(IEnumerable&lt;string&gt; sortColumns, ListSortDirection sortOrder) { var videos = this.GetVideos(); var sortedVideos = videos.AsQueryable(); foreach (var sortColumn in sortColumns.Reverse()) { sortedVideos = sortedVideos.OrderBy(sortColumn, sortOrder); } // Test the results foreach (var video in sortedVideos) { Console.WriteLine(video.Title); } } </code></pre> <p>You should then be able to use the method like this:</p> <pre class="lang-cs prettyprint-override"><code>// These values are entered by the user var sortColumns = new List&lt;string&gt; { &quot;Width&quot;, &quot;Title&quot;, &quot;Height&quot; }; var sortOrder = ListSortDirection.Ascending; // Print the video list base on the user selection this.PrintVideoList(sortColumns, sortOrder); </code></pre>
10,969,366
vim - automatically formatting golang source code when saving
<p>I'm using vim with the <a href="https://github.com/jnwhiteh/vim-golang">vim-golang</a> plugin. This plugin comes with <a href="https://github.com/jnwhiteh/vim-golang/blob/master/ftplugin/go/fmt.vim">a function called :Fmt</a> that "reformats" the source code using <a href="http://gofmt.com/">gofmt</a>, a command-line executable.</p> <p>I want to invoke the :Fmt function each time that I save the file, so it is continuously re-formatted. I think this should be done with a <a href="http://vimdoc.sourceforge.net/htmldoc/autocmd.html">autocmd</a> directive. But I have two doubts:</p> <ol> <li>I could not find a way to execute the function. I tried writting Fmt and :Fmt at the end of the autocmd line, but it didn't seem to work. I think I miss something, like "call".</li> <li>I want this to happen only when saving a file of filetype 'go'. I don't know how to combine those two conditions - I can activate variables depending on the file type, and I can do small stuff, like removing trailing spaces, whenever a file is saved, but separatedly.</li> </ol> <p>So this is what I have so far:</p> <pre><code>" I can set variables for go like this autocmd FileType go setlocal noexpandtab shiftwidth=4 tabstop=4 softtabstop=4 nolist " I can clean trailing spaces(conserving cursor position) on save like this autocmd BufWritePre * kz|:%s/\s\+$//e|'z " None of these worked: autocmd BufWritePre,FileType go Fmt autocmd BufWritePre,FileType go :Fmt </code></pre>
10,969,574
3
0
null
2012-06-10 14:12:17.38 UTC
10
2020-12-29 18:58:30.03 UTC
null
null
null
null
312,586
null
1
28
go|vim
14,293
<p>The <code>FileType</code> event doesn't fire on buffer writes; <code>BufWritePre</code> is the correct one, but you need to provide a file pattern, e.g. <code>*.go</code>:</p> <pre><code>autocmd BufWritePre *.go Fmt </code></pre> <p>The only downside is that this duplicates the detection of the <em>go</em> filetype. You could delegate this by hooking into the <code>FileType</code> event, and then define the formatting autocmd for each Go buffer by using the special <code>&lt;buffer&gt;</code> pattern:</p> <pre><code>autocmd FileType go autocmd BufWritePre &lt;buffer&gt; Fmt </code></pre> <p>This has the downside that if the filetype ever gets set multiple times, you'll run the formatting multiple times, too. That could be solved via a custom <code>:augroup</code>, but now it becomes really complex. Or, if you're really sure that this is the only <code>BufWritePre</code> autocmd for Go buffers, you could use <code>:autocmd! BufWritePre ...</code> (with a <code>!</code>).</p>
10,902,643
Can't Activate WCF service
<p>I'm working over WCF and it worked fine on localhost. After I placed it on the production server, it thows an exception </p> <blockquote> <p>The requested service, '<a href="http://global-kazway.kz/Service1.svc" rel="noreferrer">http://global-kazway.kz/Service1.svc</a>' could not be activated. See the server's diagnostic trace logs for more information</p> </blockquote> <p>I'm new in Services and have been trying to solve this problem for almost 3 hours. </p> <p>Here is the <code>App.config</code> of the client;</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;configSections&gt;&lt;/configSections&gt; &lt;connectionStrings&gt; &lt;add name="TestProject.Properties.Settings.DBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\visual studio 2010\Projects\TestProject\TestProject\AppData\DB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /&gt;&lt;add name="DBEntities" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=.\SQLEXPRESS;attachdbfilename=C:\Users\1\Documents\visual studio 2010\Projects\TestProject\TestProject\AppData\DB.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt;&lt;add name="DBEntities1" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\AppData\DB.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt;&lt;/connectionStrings&gt; &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="None" proxyCredentialType="None" realm="" /&gt; &lt;message clientCredentialType="UserName" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://global-kazway.kz/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="kazwayServiceReference.IService1" name="BasicHttpBinding_IService1" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre>
10,902,740
7
1
null
2012-06-05 18:19:06.677 UTC
3
2020-05-12 15:44:20.207 UTC
2018-03-14 07:59:03.19 UTC
null
3,077,495
null
1,184,452
null
1
28
wcf
84,720
<p>First step in troubleshooting a WCF application is to bring up a browser and type in the service URI. So based on the client: you'd navigate to <a href="http://global-kazway.kz/Service1.svc" rel="noreferrer">http://global-kazway.kz/Service1.svc</a></p> <p>Now see what kind of results you get. Exception? The service screen? Usually you can get your best information from this screen! Sometimes it points out what your issue is such as missing a behavior. </p> <p>Compare your web.config with the deployed web.config entries. You may find something there as well. Finally you may just have to manage security on your folder. But the browser display could spell everything out for you very clearly.</p>
11,089,732
Display image from blob using javascript and websockets
<p>I'm currently working on a WebSocket application that is displaying images send by a C++ server. I've seen a couple of topics around there but I can't seem to get rid of this error in Firefox:</p> <blockquote> <p>Image corrupt or truncated: data:image/png;base64,[some data]</p> </blockquote> <p>Here's the Javascript code I'm using to display my blob:</p> <pre><code>socket.onmessage = function(msg) { var blob = msg.data; var reader = new FileReader(); reader.onloadend = function() { var string = reader.result; var buffer = Base64.encode(string); var data = "data:image/png;base64,"+buffer; var image = document.getElementById('image'); image.src = data; }; reader.readAsBinaryString(blob); } </code></pre> <p>I'm using the image of a red dot that I found on this topic: <a href="https://stackoverflow.com/a/4478878/1464608">https://stackoverflow.com/a/4478878/1464608</a> And the Base64 class is from here: <a href="https://stackoverflow.com/a/246813/1464608">https://stackoverflow.com/a/246813/1464608</a></p> <p>But the base64 outcome I get doesn't match and Firefox retrieves me an error of the image being corrupted.</p> <p>I know this ain't much informations but I don't have a clue where to look :/ Any help is more than welcome!!</p>
11,092,371
6
4
null
2012-06-18 19:31:40.447 UTC
20
2021-12-25 09:47:12.41 UTC
2017-05-23 12:10:31.1 UTC
null
-1
null
1,464,608
null
1
32
javascript|html|websocket|blob|filereader
79,008
<p>I think the cleanest solution would be to change the base64 encoder to operate directly on a Uint8Array instead of a string.</p> <p>Important: You'll need to set the binaryType of the web socket to "arraybuffer" for this. </p> <p>The onmessage method should look like this:</p> <pre><code>socket.onmessage = function(msg) { var arrayBuffer = msg.data; var bytes = new Uint8Array(arrayBuffer); var image = document.getElementById('image'); image.src = 'data:image/png;base64,'+encode(bytes); }; </code></pre> <p>The converted encoder should then look like this (based on <a href="https://stackoverflow.com/a/246813/1464608">https://stackoverflow.com/a/246813/1464608</a>):</p> <pre><code>// public method for encoding an Uint8Array to base64 function encode (input) { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; while (i &lt; input.length) { chr1 = input[i++]; chr2 = i &lt; input.length ? input[i++] : Number.NaN; // Not sure if the index chr3 = i &lt; input.length ? input[i++] : Number.NaN; // checks are needed here enc1 = chr1 &gt;&gt; 2; enc2 = ((chr1 &amp; 3) &lt;&lt; 4) | (chr2 &gt;&gt; 4); enc3 = ((chr2 &amp; 15) &lt;&lt; 2) | (chr3 &gt;&gt; 6); enc4 = chr3 &amp; 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } </code></pre>
11,102,645
Java Serialization vs JSON vs XML
<p>I am wondering what serialized mechanism should we choose when dealing with object transferring over the network. What are the pros and cons ?</p> <p>I know most of the time we use <code>JSON</code> or <code>XML</code> for <code>AJAX</code> since the transfer format are pretty much <code>Javascript</code> format, and plus <code>JSON</code> is pretty lightweight with its small footprint, therefore is <code>Java</code> serialization totally out of the table ?</p>
11,103,591
5
0
null
2012-06-19 14:01:44.577 UTC
14
2020-09-21 23:07:12.287 UTC
2019-04-12 20:55:50.343 UTC
null
4,574,309
null
1,389,813
null
1
41
java|json|serialization|xml-serialization|data-serialization
28,841
<p>In general the important question is which client will receive the serialized objects - browsers/JavaScript engines like (node-js), Java client, unknown/multiple clients.</p> <p>JSON - JSON syntax is basically JavaScript and therefore any component with a JS engine will handle its parsing very well - even complicated data-structures will be converted to "living" objects efficiently. JSON parsers exist for practically any language and it is easy to use even when not using a JS engine, (Take Google Gson for example that is able to convert JSON into corresponding objects with ease) which makes is a good candidate for cross-language communication - for example in a <a href="http://en.wikipedia.org/wiki/Messaging_pattern" rel="noreferrer">messaging architecture</a>.</p> <p>XML - Shares many of JSON's benefits - cross-language, lightweight, etc. Adobe Flex for example handles XML very well, even better than JSON. It's definitely an appropriate substitute for JSON. I personally prefer JSON for its JS like syntax, but XML is also good.</p> <p>Java Serialization - Should be considered only for Java-to-Java communication. An important note is that the <em>class definitions</em> should be on the sending and the receiving ends and often you wouldn't gain much by passing the entire object. I wouldn't rule out RMI as a communication protocol, it does simplify development. However the resulting application components will be hard coupled which will make it very difficult to replace.</p> <p>One more notes - Serialization in general has its overhead. However when the communication is performed over a network the bottleneck is often the network rather than the serialization/deserialization itself.</p>
10,947,159
Writing robust R code: namespaces, masking and using the `::` operator
<h2>Short version</h2> <p>For those that don't want to read through my "case", this is the essence:</p> <ol> <li>What is the recommended way of minimizing the chances of new packages breaking existing code, i.e. of making the code you write <strong>as robust as possible</strong>?</li> <li><p>What is the recommended way of making the best use of the <strong>namespace mechanism</strong> when </p> <p>a) just <em>using</em> contributed packages (say in just some R Analysis Project)?</p> <p>b) with respect to <em>developing</em> own packages?</p></li> <li><p>How best to avoid conflicts with respect to <strong>formal classes</strong> (mostly <a href="http://stat.ethz.ch/R-manual/R-devel/library/methods/html/refClass.html" rel="noreferrer">Reference Classes</a> in my case) as there isn't even a namespace mechanism comparable to <code>::</code> for classes (AFAIU)?</p></li> </ol> <hr> <h2>The way the R universe works</h2> <p>This is something that's been nagging in the back of my mind for about two years now, yet I don't feel as if I have come to a satisfying solution. Plus I feel it's getting worse.</p> <p>We see an ever increasing number of packages on <a href="http://cran.at.r-project.org/web/packages/available_packages_by_name.html" rel="noreferrer">CRAN</a>, <a href="https://github.com/" rel="noreferrer">github</a>, <a href="http://r-forge.r-project.org/" rel="noreferrer">R-Forge</a> and the like, which is simply terrific.</p> <p>In such a decentralized environment, it is natural that the code base that makes up R (let's say that's <em>base R</em> and <em>contributed R</em>, for simplicity) will deviate from an ideal state with respect to robustness: people follow different conventions, there's S3, S4, S4 Reference Classes, etc. Things can't be as "aligned" as they would be if there were a "<em>central clearing instance</em>" that enforced conventions. That's okay.</p> <h2>The problem</h2> <p>Given the above, it can be very hard to use R to write robust code. Not everything you need will be in base R. For certain projects you will end up loading quite a few contributed packages.</p> <p><strong>IMHO, the biggest issue in that respect is the way the namespace concept is put to use in R: R allows for simply writing the name of a certain function/method without explicitly requiring it's namespace (i.e. <code>foo</code> vs. <code>namespace::foo</code>)</strong>. </p> <p>So for the sake of simplicity, that's what everyone is doing. But that way, name clashes, broken code and the need to rewrite/refactor your code are just a matter of time (or of the number of different packages loaded). </p> <p>At best, you will <strong>know</strong> about which existing functions are masked/overloaded by a newly added package. At worst, you will have no clue until your code breaks.</p> <p>A couple of examples: </p> <ul> <li>try loading <a href="http://cran.at.r-project.org/web/packages/RMySQL/index.html" rel="noreferrer">RMySQL</a> and <a href="http://cran.at.r-project.org/web/packages/RSQLite/index.html" rel="noreferrer">RSQLite</a> at the same time, they don't go along very well</li> <li>also <a href="http://cran.at.r-project.org/web/packages/RMongo/index.html" rel="noreferrer">RMongo</a> will overwrite certain functions of <a href="http://cran.at.r-project.org/web/packages/RMySQL/index.html" rel="noreferrer">RMySQL</a></li> <li><a href="http://cran.at.r-project.org/web/packages/forecast/index.html" rel="noreferrer">forecast</a> masks a lot of stuff with respect to ARIMA-related functions</li> <li><a href="http://cran.at.r-project.org/web/packages/R.utils/index.html" rel="noreferrer">R.utils</a> even masks the <code>base::parse</code> routine </li> </ul> <p>(I can't recall which functions in particular were causing the problems, but am willing to look it up again if there's interest)</p> <p>Surprisingly, this doesn't seem to bother a lot of programmers out there. I tried to raise interest a couple of times at <a href="http://tolstoy.newcastle.edu.au/R/e15/devel/11/08/0416.html" rel="noreferrer">r-devel</a>, to no significant avail.</p> <h2>Downsides of using the <code>::</code> operator</h2> <ol> <li>Using the <code>::</code> operator might significantly hurt efficiency in certain contexts as Dominick Samperi <a href="http://tolstoy.newcastle.edu.au/R/e15/devel/11/10/0716.html" rel="noreferrer">pointed out</a>.</li> <li>When <strong>developing</strong> your own package, you can't even use the <code>::</code> operator throughout your own code as your code is no real package yet and thus there's also no namespace yet. So I would have to initially stick to the <code>foo</code> way, build, test and then go back to changing everything to <code>namespace::foo</code>. Not really.</li> </ol> <h2>Possible solutions to avoid these problems</h2> <ol> <li><strong>Reassign</strong> each function from each package to a variable that follows certain naming conventions, e.g. <code>namespace..foo</code> in order to avoid the inefficiencies associated with <code>namespace::foo</code> (I outlined it once <a href="http://tolstoy.newcastle.edu.au/R/e15/devel/11/08/0416.html" rel="noreferrer">here</a>). Pros: it works. Cons: it's clumsy and you double the memory used.</li> <li><strong>Simulate</strong> a namespace when developing your package. AFAIU, this is not really possible, at least I was <a href="http://tolstoy.newcastle.edu.au/R/e13/devel/11/01/0039.html" rel="noreferrer">told so back then</a>.</li> <li>Make it <strong>mandatory</strong> to use <code>namespace::foo</code>. IMHO, that would be the best thing to do. Sure, we would lose some extend of simplicity, but then again the R universe just isn't simple anymore (at least it's not as simple as in the early 00's).</li> </ol> <h2>And what about (formal) classes?</h2> <p>Apart from the aspects described above, <code>::</code> way works quite well for functions/methods. But what about class definitions?</p> <p>Take package <a href="http://cran.at.r-project.org/web/packages/timeDate/index.html" rel="noreferrer">timeDate</a> with it's class <code>timeDate</code>. Say another package comes along which also has a class <code>timeDate</code>. I don't see how I could explicitly state that I would like a new instance of class <code>timeDate</code> from either of the two packages. </p> <p>Something like this will not work:</p> <pre><code>new(timeDate::timeDate) new("timeDate::timeDate") new("timeDate", ns="timeDate") </code></pre> <p>That can be a huge problem as more and more people switch to an OOP-style for their R packages, leading to lots of class definitions. If there <strong>is</strong> a way to explicitly address the namespace of a class definition, I would very much appreciate a pointer!</p> <h2>Conclusion</h2> <p>Even though this was a bit lengthy, I hope I was able to point out the core problem/question and that I can raise more awareness here.</p> <p>I think <a href="http://cran.at.r-project.org/web/packages/devtools/index.html" rel="noreferrer">devtools</a> and <a href="http://cran.at.r-project.org/web/packages/mvbutils/index.html" rel="noreferrer">mvbutils</a> do have some approaches that might be worth spreading, but I'm sure there's more to say.</p>
10,951,283
2
21
null
2012-06-08 10:30:01.13 UTC
28
2018-03-27 01:36:26.077 UTC
2012-06-12 11:56:40.373 UTC
null
989,691
null
989,691
null
1
47
r|coding-style|namespaces|package|masking
4,176
<p>GREAT question.</p> <h2>Validation</h2> <p>Writing robust, stable, and production-ready R code IS hard. You said: "Surprisingly, this doesn't seem to bother a lot of programmers out there". That's because most R programmers are not writing <strong>production</strong> code. They are performing one-off academic/research tasks. I would seriously question the skillset of any coder that claims that R is easy to put into production. Aside from my post on search/find mechanism which you have already linked to, I also wrote a post about the dangers of <a href="http://obeautifulcode.com/R/A-Warning-About-Warning/" rel="noreferrer">warning</a>. The suggestions will help reduce complexity in your production code.</p> <h2>Tips for writing robust/production R code</h2> <ol> <li>Avoid packages that use Depends and favor packages that use Imports. A package with dependencies stuffed into Imports only is completely safe to use. If you absolutely must use a package that employs Depends, then email the author immediately after you call <code>install.packages()</code>. </li> </ol> <p>Here's what I tell authors: "Hi Author, I'm a fan of the XYZ package. I'd like to make a request. Could you move ABC and DEF from Depends to Imports in the next update? I cannot add your package to my own package's Imports until this happens. With R 2.14 enforcing NAMESPACE for every package, the general message from R Core is that packages should try to be "good citizens". If I have to load a Depends package, it adds a significant burden: I have to check for conflicts every time I take a dependency on a new package. With Imports, the package is free of side-effects. I understand that you might break other people's packages by doing this. I think its the right thing to do to demonstrate a commitment to Imports and in the long-run it will help people produce more robust R code."</p> <ol start="2"> <li><p>Use importFrom. Don't add an entire package to Imports, add only those specific functions that you require. I accomplish this with Roxygen2 function documentation and roxygenize() which automatically generates the NAMESPACE file. In this way, you can import two packages that have conflicts where the conflicts aren't in the functions you actually need to use. Is this tedious? Only until it becomes a habit. The benefit: you can quickly identify all of your 3rd-party dependencies. That helps with...</p></li> <li><p>Don't upgrade packages blindly. Read the changelog line-by-line and consider how the updates will affect the stability of your own package. Most of the time, the updates don't touch the functions you actually use.</p></li> <li><p>Avoid S4 classes. I'm doing some hand-waving here. I find S4 to be complex and it takes enough brain power to deal with the search/find mechanism on the functional side of R. Do you really need these OO feature? Managing state = managing complexity - leave that for Python or Java =)</p></li> <li><p>Write unit tests. Use the testthat package.</p></li> <li><p>Whenever you R CMD build/test your package, parse the output and look for NOTE, INFO, WARNING. Also, physically scan with your own eyes. There's a part of the build step that notes conflicts but doesn't attach a WARN, etc. to it.</p></li> <li><p>Add assertions and invariants right after a call to a 3rd-party package. In other words, don't fully trust what someone else gives you. Probe the result a little bit and <code>stop()</code> if the result is unexpected. You don't have to go crazy - pick one or two assertions that imply valid/high-confidence results.</p></li> </ol> <p>I think there's more but this has become muscle memory now =) I'll augment if more comes to me.</p>
11,329,917
Restart python-script from within itself
<p>I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:</p> <p><code>./myscript.py --some-flag setting</code></p> <p>From within the program the user can download (using Git) newer versions. If such exists/are downloaded, a button appear that I wish would restart the program with newly compiled contents (including dependencies/imports). Preferably it would also restart it using the contents of <code>sys.argv</code> to keep all the flags as they were.</p> <p>So what I fail to find/need is a nice restart procedure that kills the current instance of the program and starts a new using the same arguments.</p> <p>Preferably the solution should work for Windows and Mac as well but it is not essential.</p>
11,329,970
15
2
null
2012-07-04 13:19:22.92 UTC
19
2022-09-11 20:31:34.787 UTC
null
null
null
null
1,099,682
null
1
63
python
147,443
<p>You're looking for <a href="http://docs.python.org/library/os.html#os.execl" rel="noreferrer"><code>os.exec*()</code></a> family of commands.</p> <p>To restart your current program with exact the same command line arguments as it was originally run, you could use the following:</p> <pre><code>os.execv(sys.argv[0], sys.argv) </code></pre>
11,126,315
What are optimal scrypt work factors?
<p>I'm using a <a href="https://github.com/wg/scrypt" rel="noreferrer">Java scrypt library</a> for password storage. It calls for an <code>N</code>, <code>r</code> and <code>p</code> value when I encrypt things, which its documentation refers to as "CPU cost", "memory cost" and "parallelization cost" parameters. Only problem is, I don't actually know what they specifically mean, or what good values would be for them; perhaps they correspond somehow to the -t, -m and -M switches on <a href="http://www.tarsnap.com/scrypt.html" rel="noreferrer">Colin Percival's original app</a>?</p> <p>Does anyone have any suggestions for this? The library itself lists N = 16384, r = 8 and p = 1, but I don't know if this is strong or weak or what.</p>
12,581,268
3
7
null
2012-06-20 18:57:07.127 UTC
44
2021-05-14 22:31:11.427 UTC
null
null
null
null
331,598
null
1
71
java|cryptography|scrypt
16,183
<p>As a start:</p> <p><em>cpercival</em> mentioned <a href="http://www.tarsnap.com/scrypt/scrypt-slides.pdf" rel="noreferrer">in his slides from 2009</a> something around</p> <ul> <li>(N = 2^14, r = 8, p = 1) for &lt; 100ms (interactive use), and</li> <li>(N = 2^20, r = 8, p = 1) for &lt; 5s (sensitive storage).</li> </ul> <p>These values happen to be good enough for general use (password-db for some WebApp) even today (2012-09). Of course, specifics depend on the application.</p> <p>Also, those values (mostly) mean:</p> <ul> <li><code>N</code>: General work factor, iteration count.</li> <li><code>r</code>: blocksize in use for underlying hash; fine-tunes the relative memory-cost.</li> <li><code>p</code>: parallelization factor; fine-tunes the relative cpu-cost.</li> </ul> <p><code>r</code> and <code>p</code> are meant to accommodate for the potential issue that CPU speed and memory size and bandwidth do not increase as anticipated. Should CPU performance increase faster, you increase <code>p</code>, should instead a breakthrough in memory technology provide an order of magnitude improvement, you increase <code>r</code>. And <code>N</code> is there to keep up with the general doubling of performance per <em>some timespan</em>.</p> <p><em>Important:</em> All values change the result. (Updated:) This is the reason why all scrypt parameters are stored in the result string.</p>
12,812,570
Differences between gevent and tornado
<p>I understand that both <code>tornado</code> and <code>gevent</code> are asynchronous python frameworks.</p> <p>While reading the <a href="http://bottlepy.org/docs/stable/async.html#the-limits-of-synchronous-wsgi" rel="noreferrer">bottle documentation</a> I found that gevent actually is NOT asynchronous, and you can create thousands to pseudo-threads that work synchronously.</p> <p>Seondly, in gevent, you can not terminate the request handler early and you need to return the full response, while in tornado you can. (correct me if I'm wrong here)</p> <p>Can some one describe in detail how these systems work internally, and in what ways they are different. Also, how does WSGI play with the asynchronous nature of these systems? Do these frameworks conform to WSGI, if yes, how?</p>
12,812,839
2
1
null
2012-10-10 05:34:09.043 UTC
13
2014-07-30 13:09:25.857 UTC
null
null
null
null
1,206,051
null
1
14
wsgi|tornado|gevent
10,398
<p>Have a read of:</p> <p><a href="http://en.wikipedia.org/wiki/Coroutines" rel="noreferrer">http://en.wikipedia.org/wiki/Coroutines</a></p> <p>and:</p> <p><a href="http://en.wikipedia.org/wiki/Event-driven_architecture" rel="noreferrer">http://en.wikipedia.org/wiki/Event-driven_architecture</a></p> <p><a href="http://en.wikipedia.org/wiki/Event-driven_programming" rel="noreferrer">http://en.wikipedia.org/wiki/Event-driven_programming</a></p> <p>The gevent package uses coroutines and Tornado is event driven.</p> <p>Even driven systems don't readily map to WSGI, but a coroutine system, because it looks like threads, can be made to support WSGI if blocking points can be patched to switch coroutines when things would block.</p>
12,763,890
Exclude Blank and NA in R
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4862178/r-remove-rows-with-nas-in-data-frame">R - remove rows with NAs in data.frame</a> </p> </blockquote> <p>I have a dataframe named sub.new with multiple columns in it. And I'm trying to exclude any cell containing <code>NA</code> or a <code>blank space</code> "<code></code>".<br> I tried to use <code>subset()</code>, but it's targeting specific column conditional. Is there anyway to scan through the whole dataframe and create a subset that no cell is either <code>NA</code> or <code>blank space</code> ?</p> <p>In the example below, only the first line should be kept:</p> <pre><code># ID SNP ILMN_Strand Customer_Strand ID1234 [A/G] TOP BOT Non-Specific NSB (Bgnd) Green Non-Polymorphic NP (A) Red Non-Polymorphic NP (T) Purple Non-Polymorphic NP (C) Green Non-Polymorphic NP (G) Blue Restoration Restore Green </code></pre> <p>Any suggestions? Thanks</p>
12,764,040
2
5
null
2012-10-06 21:08:00.08 UTC
13
2016-03-23 10:58:17.3 UTC
2017-05-23 11:47:06.12 UTC
null
-1
null
1,301,840
null
1
20
r|na
197,812
<p>A good idea is to set all of the "" (blank cells) to NA before any further analysis.</p> <p>If you are reading your input from a file, it is a good choice to cast all "" to NAs:</p> <pre><code>foo &lt;- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited </code></pre> <p>If you have already your table loaded, you can act as follows:</p> <pre><code>foo[foo==""] &lt;- NA </code></pre> <p>Then to keep only rows with no NA you may just use <code>na.omit()</code>:</p> <pre><code>foo &lt;- na.omit(foo) </code></pre> <p>Or to keep columns with no NA:</p> <pre><code>foo &lt;- foo[, colSums(is.na(foo)) == 0] </code></pre>
12,883,088
Python: pass statement in lambda form
<p>A Python newbie question, why is this syntax invalid: <code>lambda: pass</code>, while this: <code>def f(): pass</code> is correct?</p> <p>Thanks for your insight.</p>
12,883,120
3
0
null
2012-10-14 14:20:45.83 UTC
4
2016-07-27 14:27:18.2 UTC
null
null
null
null
1,306,142
null
1
49
python|lambda|anonymous-function
19,645
<p>That is an error because after the colon you have to put the return value, so:</p> <pre><code>lambda: pass </code></pre> <p>is equal to:</p> <pre><code>def f(): return pass </code></pre> <p>that indeed makes no sense and produces a <code>SyntaxError</code> as well.</p>
13,020,246
Remove special symbols and extra spaces and replace with underscore using the replace method
<p>I want to remove all special characters and spaces from a string and replace with an underscore. The string is</p> <pre><code> var str = "hello world &amp; hello universe"; </code></pre> <p>I have this now which replaces only spaces:</p> <pre><code> str.replace(/\s/g, "_"); </code></pre> <p>The result I get is <code>hello_world_&amp;_hello_universe</code>, but I would like to remove the special symbols as well.</p> <p>I tried this <code>str.replace(/[^a-zA-Z0-9]\s/g, "_")</code> but this does not help.</p>
13,020,280
5
0
null
2012-10-22 21:34:18.953 UTC
19
2019-10-14 05:24:56.423 UTC
2018-10-11 18:09:58.027 UTC
null
63,550
null
1,361,669
null
1
65
javascript
139,946
<p>Your regular expression <code>[^a-zA-Z0-9]\s/g</code> says match any character that is not a number or letter followed by a space.</p> <p>Remove the \s and you should get what you are after if you want a _ for every special character.</p> <pre><code>var newString = str.replace(/[^A-Z0-9]/ig, "_"); </code></pre> <p>That will result in <code>hello_world___hello_universe</code></p> <p>If you want it to be single underscores use a + to match multiple</p> <pre><code>var newString = str.replace(/[^A-Z0-9]+/ig, "_"); </code></pre> <p>That will result in <code>hello_world_hello_universe</code></p>
12,788,487
$(document).scrollTop() always returns 0
<p>I'm simply trying to do something once the scroll position of the page reaches a certain height. However <code>scrollTop()</code> is returning 0 or <code>null</code> no matter how far down I scroll. This is the help function I'm using to check the <code>scrollTop()</code> value: </p> <pre><code>$('body').click(function(){ var scrollPost = $(document).scrollTop(); alert(scrollPost); }); </code></pre> <p>I've tried attaching <code>scrollTop()</code> to <code>$('body')</code>, <code>$('html')</code> and of course <code>$(window)</code>, but nothing changes. </p> <p>Any ideas?</p>
12,789,956
9
15
null
2012-10-08 19:50:01.06 UTC
12
2020-05-11 07:00:44.703 UTC
2012-10-08 19:58:29.053 UTC
null
1,267,663
null
484,358
null
1
74
javascript|jquery|scrolltop
78,768
<p>For some reason, removing 'height: 100%' from my html and body tags fixed this issue.</p> <p>I hope this helps someone else!</p>
12,833,514
Paused in debugger in chrome?
<p>When debugging in chrome, the scripts are always paused in the debugger even if there are no break points set, and if the the pause is un-paused, it again pauses itself.</p> <p>What can be done? </p>
12,897,543
18
1
null
2012-10-11 06:31:05.843 UTC
27
2021-07-05 06:55:29.593 UTC
2012-10-18 09:32:51.5 UTC
null
297,408
null
1,585,332
null
1
170
debugging|google-chrome|google-chrome-devtools
244,545
<p>One possible cause, it that you've enabled the &quot;pause on exceptions&quot; (the little stop-sign shaped icon with the pause (||) symbol within in the lower left of the window). Try clicking that back to the off/grey state (not red nor blue states) and reload the page.</p> <p><a href="https://i.stack.imgur.com/QltAW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QltAW.png" alt="enter image description here" /></a></p>
17,113,149
What is the difference between MySQL's create index and alter add index?
<p>I have a table "data" with column id(varchar), text(varchar), date(date). Creating index on mysql, I use heidiSQL.</p> <p>When I right click on the column and select create new index (key), the code shows it's using <code>alter table data add index 'index1' ('id,date(10)')</code></p> <p>What is the difference between this and <code>create index index1 on data ('id,date(10)')</code></p>
17,113,555
1
0
null
2013-06-14 16:27:56.527 UTC
4
2018-05-11 16:44:03.81 UTC
2013-06-14 16:52:25.697 UTC
null
212,555
null
1,828,260
null
1
37
mysql|indexing
11,593
<p>The implementation is the same on the server-side.</p> <p>The only difference is that with CREATE INDEX syntax, you <em>must</em> specify a name for the index.</p> <p>Whereas with ALTER TABLE, you <em>may</em> specify a name for the index, but you don't have to.</p> <p>If you don't specify a name, the server generates a default name, as the name of the first column in the index, with a number suffix if necessary.</p>