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
804,961
How do I use CSS with a ruby on rails application?
<p>How do I use CSS with RoR? When I link externally, I'm never able to see the files. I cp'd the .css file to every folder I could think of...views, controller, template, and nothing seems to work.</p> <p>What do I need to do to enable external CSS files with a rails application? I'm new to rails, so forgive me if this is basic.</p>
804,972
8
0
null
2009-04-30 00:57:16.35 UTC
14
2019-11-26 09:59:29.423 UTC
2015-11-13 20:37:20.817 UTC
null
1,223,693
null
78,182
null
1
67
ruby-on-rails|css|ruby
115,942
<p>Put the CSS files in public/stylesheets and then use:</p> <pre><code>&lt;%= stylesheet_link_tag "filename" %&gt; </code></pre> <p>to link to the stylesheet in your layouts or erb files in your views.</p> <p>Similarly you put images in public/images and javascript files in public/javascripts. </p>
4,545
What was the <XMP> tag used for?
<p>Does anyone remember the <code>XMP</code> tag?</p> <p>What was it used for and why was it deprecated?</p>
4,549
8
1
null
2008-08-07 09:21:41.563 UTC
13
2018-12-17 15:49:59.753 UTC
2017-05-26 09:38:53.863 UTC
null
1,402,846
null
383
null
1
79
html|tags
52,678
<p>A quick Google search on W3C reveals that <code>XMP</code> was introduced for displaying <strong>preformatted text</strong> in HTML 3.2 and earlier. When W3C deprecated the <code>XMP</code> tag, it suggested using the <code>PRE</code> tag as a preferred alternative.</p> <p>Update: <a href="http://www.w3.org/TR/REC-html32#xmp" rel="noreferrer">http://www.w3.org/TR/REC-html32#xmp</a>, <a href="http://www.w3.org/MarkUp/html-spec/html-spec_5.html#SEC5.5.2.1" rel="noreferrer">http://www.w3.org/MarkUp/html-spec/html-spec_5.html#SEC5.5.2.1</a></p>
54,867
What is the difference between old style and new style classes in Python?
<p>What is the difference between old style and new style classes in Python? When should I use one or the other?</p>
54,873
8
0
null
2008-09-10 18:01:27.163 UTC
304
2020-02-02 11:31:19.547 UTC
2018-10-29 14:02:48.583 UTC
J.F. Sebastian
10,388,629
Tim
4,883
null
1
1,108
python|class|oop|types|new-style-class
261,220
<p>From <em><a href="http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes" rel="noreferrer">New-style and classic classes</a></em>:</p> <blockquote> <p><strong>Up to Python 2.1, old-style classes were the only flavour available to the user.</strong></p> <p>The concept of (old-style) class is unrelated to the concept of type: if <code>x</code> is an instance of an old-style class, then <code>x.__class__</code> designates the class of <code>x</code>, but <code>type(x)</code> is always <code>&lt;type 'instance'&gt;</code>. </p> <p>This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.</p> <p><strong>New-style classes were introduced in Python 2.2 to unify the concepts of class and type</strong>. A new-style class is simply a user-defined type, no more, no less.</p> <p>If x is an instance of a new-style class, then <code>type(x)</code> is typically the same as <code>x.__class__</code> (although this is not guaranteed – a new-style class instance is permitted to override the value returned for <code>x.__class__</code>).</p> <p><strong>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model</strong>. </p> <p>It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.</p> <p><strong>For compatibility reasons, classes are still old-style by default</strong>. </p> <p>New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. </p> <p>The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. </p> <p>Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.</p> <p><strong>Python 3 only has new-style classes</strong>. </p> <p>No matter if you subclass from <code>object</code> or not, classes are new-style in Python 3.</p> </blockquote>
280,566
Run once a day in C#
<p>Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler?</p>
280,772
9
1
null
2008-11-11 10:44:54.397 UTC
6
2020-11-19 12:42:20.087 UTC
2019-12-10 15:08:43.13 UTC
Robert Gould
1,033,581
Anders R
36,504
null
1
18
c#|scheduling
42,218
<p>Take a look at <a href="http://quartznet.sourceforge.net/" rel="noreferrer">quartz.net</a>. It is a scheduling library for .net.</p> <p>More specifically take a look <a href="http://quartznet.sourceforge.net/tutorial/lesson_4.html" rel="noreferrer">here</a>.</p>
1,036,347
How do I use boolean variables in Perl?
<p>I have tried:</p> <pre><code>$var = false; $var = FALSE; $var = False; </code></pre> <p>None of these work. I get the error message</p> <pre>Bareword "false" not allowed while "strict subs" is in use.</pre>
1,036,353
9
1
null
2009-06-24 04:08:11.387 UTC
32
2022-06-15 13:51:10.023 UTC
2009-06-24 21:17:16.01 UTC
null
48,771
null
48,771
null
1
236
perl|boolean
264,489
<p>In Perl, the following evaluate to false in conditionals:</p> <pre><code>0 '0' undef '' # Empty scalar () # Empty list ('') </code></pre> <p>The rest are true. There are no barewords for <code>true</code> or <code>false</code>.</p>
134,158
How would you sort 1 million 32-bit integers in 2MB of RAM?
<p>Please, provide code examples in a language of your choice.</p> <p><strong>Update</strong>: No constraints set on external storage.</p> <p>Example: Integers are received/sent via network. There is a sufficient space on local disk for intermediate results.</p>
228,866
10
0
null
2008-09-25 15:53:47.07 UTC
19
2013-01-16 05:43:37.217 UTC
2008-09-25 19:04:58.39 UTC
J.F. Sebastian
4,279
J.F. Sebastian
4,279
null
1
14
algorithm|language-agnostic|google-moderator
32,027
<p><a href="http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html" rel="noreferrer">Sorting a million 32-bit integers in 2MB of RAM using Python by Guido van Rossum</a></p>
627,916
Check if URL scheme is supported in javascript
<p>Is there any way to check if a URL scheme is currently registered on the phone... with javascript?</p>
627,942
10
1
null
2009-03-09 20:34:17.25 UTC
48
2019-12-31 17:24:33.443 UTC
2013-08-11 01:37:07.343 UTC
null
1,371,070
jackb
null
null
1
65
javascript|iphone|safari|url-scheme
80,060
<p>No, not from a webpage.</p>
237,432
python properties and inheritance
<p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p> <pre><code>class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 </code></pre> <p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p> <pre><code>age = property(lambda self: self._get_age()) </code></pre> <p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
237,858
11
0
null
2008-10-26 02:49:09.75 UTC
19
2021-05-16 16:29:46.597 UTC
2008-10-26 03:16:07.667 UTC
Peter Hoffmann
720
Peter Hoffmann
720
null
1
62
python|inheritance|properties|polymorphism
48,781
<p>I simply prefer to repeat the <code>property()</code> as well as you will repeat the <code>@classmethod</code> decorator when overriding a class method. </p> <p>While this seems very verbose, at least for Python standards, you may notice:</p> <p>1) for read only properties, <code>property</code> can be used as a decorator:</p> <pre><code>class Foo(object): @property def age(self): return 11 class Bar(Foo): @property def age(self): return 44 </code></pre> <p>2) in Python 2.6, <a href="http://docs.python.org/library/functions.html#property" rel="noreferrer">properties grew a pair of methods</a> <code>setter</code> and <code>deleter</code> which can be used to apply to general properties the shortcut already available for read-only ones:</p> <pre><code>class C(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = value </code></pre>
1,195,206
Is there a Java equivalent or methodology for the typedef keyword in C++?
<p>Coming from a C and C++ background, I found judicious use of <strong><code>typedef</code></strong> to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?</p>
1,195,221
12
5
null
2009-07-28 16:23:22.423 UTC
16
2020-05-08 15:10:06.9 UTC
2012-11-09 02:40:54.897 UTC
null
139,010
null
89,339
null
1
277
java|c++|c|design-patterns|typedef
132,945
<p>Java has primitive types, objects and arrays and that's it. No typedefs.</p>
1,100,311
What is the ideal growth rate for a dynamically allocated array?
<p>C++ has std::vector and Java has ArrayList, and many other languages have their own form of dynamically allocated array. When a dynamic array runs out of space, it gets reallocated into a larger area and the old values are copied into the new array. A question central to the performance of such an array is how fast the array grows in size. If you always only grow large enough to fit the current push, you'll end up reallocating every time. So it makes sense to double the array size, or multiply it by say 1.5x.</p> <p>Is there an ideal growth factor? 2x? 1.5x? By ideal I mean mathematically justified, best balancing performance and wasted memory. I realize that theoretically, given that your application could have any potential distribution of pushes that this is somewhat application dependent. But I'm curious to know if there's a value that's "usually" best, or is considered best within some rigorous constraint.</p> <p>I've heard there's a paper on this somewhere, but I've been unable to find it.</p>
1,100,359
12
0
null
2009-07-08 20:15:48.523 UTC
60
2021-11-22 13:56:33.057 UTC
null
null
null
null
50,385
null
1
101
arrays|math|vector|arraylist|dynamic-arrays
25,348
<p>It will entirely depend on the use case. Do you care more about the time wasted copying data around (and reallocating arrays) or the extra memory? How long is the array going to last? If it's not going to be around for long, using a bigger buffer may well be a good idea - the penalty is short-lived. If it's going to hang around (e.g. in Java, going into older and older generations) that's obviously more of a penalty.</p> <p>There's no such thing as an "ideal growth factor." It's not just <em>theoretically</em> application dependent, it's <em>definitely</em> application dependent.</p> <p>2 is a pretty common growth factor - I'm pretty sure that's what <code>ArrayList</code> and <code>List&lt;T&gt;</code> in .NET uses. <code>ArrayList&lt;T&gt;</code> in Java uses 1.5.</p> <p>EDIT: As Erich points out, <code>Dictionary&lt;,&gt;</code> in .NET uses "double the size then increase to the next prime number" so that hash values can be distributed reasonably between buckets. (I'm sure I've recently seen documentation suggesting that primes aren't actually that great for distributing hash buckets, but that's an argument for another answer.)</p>
907,680
CSS Printing: Avoiding cut-in-half DIVs between pages?
<p>I'm writing a plug-in for a piece of software that takes a big collection of items and pops them into HTML in a WebView in Cocoa (which uses WebKit as its renderer, so basically you can assume this HTML file is being opened in Safari).</p> <p>The DIVs it makes are of dynamic height, but they don't vary too much. They're usually around 200px. Anyway, with around six-hundred of these items per document, I'm having a really rough time getting it to print. Unless I get lucky, there's an entry chopped in half at the bottom and top of every page, and that makes actually using printouts very difficult.</p> <p>I've tried page-break-before, page-break-after, page-break-inside, and combinations of the three to no avail. I think it might be WebKit not properly rendering the instructions, or maybe it's my lack of understanding of how to use them. At any rate, I need help. How can I prevent the cutting-in-half of my DIVs when printing?</p>
907,719
12
3
null
2009-05-25 18:40:43.287 UTC
54
2022-07-03 20:24:35.543 UTC
2009-05-25 18:45:12.437 UTC
null
27,637
null
112,224
null
1
252
css|cocoa|printing|page-break
174,250
<p>Using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside" rel="noreferrer">break-inside</a> should work:</p> <pre class="lang-css prettyprint-override"><code>@media print { div { break-inside: avoid; } } </code></pre> <p>It works on <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside" rel="noreferrer">all major browsers</a>:</p> <ul> <li>Chrome 50+</li> <li>Edge 12+</li> <li>Firefox 65+</li> <li>Opera 37+</li> <li>Safari 10+</li> </ul> <p>Using <code>page-break-inside: avoid;</code> instead should work too, but has been <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-inside" rel="noreferrer">exactly deprecated</a> by <code>break-inside: avoid</code>.</p>
137,006
Redefine Class Methods or Class
<p>Is there any way to redefine a class or some of its methods without using typical inheritance? For example:</p> <pre><code>class third_party_library { function buggy_function() { return 'bad result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>What can I do to replace <code>buggy_function()</code>? Obviously this is what I would like to do</p> <pre><code>class third_party_library redefines third_party_library{ function buggy_function() { return 'good result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.</p> <p>I've found this <a href="http://pecl.php.net/package/classkit" rel="noreferrer">library</a> that says it can do it, but I'm wary as it's 4 years old.</p> <p>EDIT:</p> <p>I should have clarified that I cannot rename the class from <code>third_party_library</code> to <code>magical_third_party_library</code> or anything else because of framework limitations.</p> <p>For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a &quot;partial class.&quot;</p>
137,028
13
2
null
2008-09-26 00:00:45.06 UTC
15
2020-04-26 19:44:19.103 UTC
2020-06-20 09:12:55.06 UTC
SeanDowney
-1
SeanDowney
5,261
null
1
54
php|class|methods|redefine
77,528
<p>It's called <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="noreferrer">monkey patching</a>. But, PHP doesn't have native support for it.</p> <p>Though, as others have also pointed out, the <a href="http://docs.php.net/runkit" rel="noreferrer">runkit library</a> is available for adding support to the language and is the successor to <a href="http://docs.php.net/manual/en/book.classkit.php" rel="noreferrer">classkit</a>. And, though it seemed to have been <a href="http://pecl.php.net/package/runkit" rel="noreferrer">abandoned</a> by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a <a href="https://github.com/zenovich/runkit" rel="noreferrer">new home and maintainer</a>.</p> <p>I still <a href="https://stackoverflow.com/revisions/137028/3">can't say I'm a fan</a> of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug.</p> <p>Still, <a href="http://us2.php.net/manual/en/function.runkit-method-redefine.php" rel="noreferrer"><code>runkit_method_redefine</code></a> appears to be what you're looking for, and an example of its use can be found in <a href="https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt" rel="noreferrer"><code>/tests/runkit_method_redefine.phpt</code></a> in the repository:</p> <pre class="lang-php prettyprint-override"><code>runkit_method_redefine('third_party_library', 'buggy_function', '', 'return \'good result\'' ); </code></pre>
25,765
Java configuration framework
<p>I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. </p> <p>Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...</p>
25,768
14
1
2009-06-29 06:54:39.35 UTC
2008-08-25 08:17:54.297 UTC
28
2015-05-06 18:00:22.02 UTC
2010-12-21 10:26:03.277 UTC
Keith
63,550
Steen
1,448,983
null
1
76
java|xml|configuration|frameworks|configurationmanager
30,542
<p>If your hardcoded values are just simple key-value pairs, you should look at <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html" rel="noreferrer">java.util.Properties</a>. It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement.</p> <p>If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution.</p> <p>I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it.</p> <p>Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.</p>
476,163
NAnt or MSBuild, which one to choose and when?
<p>I am aware there are other <a href="http://en.wikipedia.org/wiki/NAnt" rel="noreferrer">NAnt</a> and <a href="http://en.wikipedia.org/wiki/MSBuild" rel="noreferrer">MSBuild</a> related questions on Stack&nbsp;Overflow, but I could not find a direct comparison between the two and so here is the question.</p> <p>When should one choose NAnt over MSBuild? Which one is better for what? Is NAnt more suitable for home/open source projects and MSBuild for work projects? What is the experience with any of the two?</p>
483,505
14
0
null
2009-01-24 15:39:24.337 UTC
91
2017-10-18 16:39:52.917 UTC
2013-08-30 08:38:09.17 UTC
Fabian Steeg
63,550
Yordan Pavlov
54,968
null
1
162
.net|msbuild|automation|nant
32,088
<p>I've done a similar investigation this week. Here's what I've been able to determine:</p> <p><strong>NAnt:</strong></p> <ul> <li>Cross-platform (supports Linux/Mono). It may be handy for installing a web site to multiple targets (that is, Linux Apache and Windows IIS), for example.</li> <li>95% similar in syntax to Ant (easy for current Ant users or Java builders to pick up)</li> <li>Integration with NUnit for running unit tests as part of the build, and with NDoc for producting documentation.</li> </ul> <p><strong>MSBuild:</strong></p> <ul> <li>Built-in to .NET.</li> <li>Integrated with Visual Studio</li> <li>Easy to get started with MSBuild in Visual Studio - it's all behind the scenes. If you want to get deeper, you can hand edit the files.</li> </ul> <p><strong>Subjective Differences:</strong> <em>(YMMV)</em></p> <ul> <li>NAnt documentation is a little more straightforward. For example, the <a href="http://msdn.microsoft.com/en-us/library/7z253716.aspx" rel="noreferrer">MSBuild Task Reference</a> lists "Csc Task - Describes the Csc task and its parameters. " (thanks for the "help"?), vs the <a href="http://nant.sourceforge.net/release/latest/help/tasks/" rel="noreferrer">NAnt Task Reference</a> "csc - Compiles C# programs." <strong><em>UPDATE:</em></strong> I've noticed the <a href="http://msdn.microsoft.com/en-us/library/7z253716.aspx" rel="noreferrer">MSBuild documentation</a> has been improved and is much better now (probably on par with NAnt).</li> <li>Not easy to figure out how to edit the build script source (*.*proj file) directly from within Visual Studio. With NAnt I just have Visual Studio treat the .build script as an XML file.</li> <li>Apparently, in Visual Studio, Web Application Projects don't get a *.*proj file by default, so I had great difficulty figuring out how to even get MSBuild to run on mine to create a deployment script.</li> <li>NAnt is not built-in to Visual Studio and has to be added, either with an Add-In, or as an "External Tool". This is a bit of a pain to set up.</li> <li>(Edit:) One of my coworkers brought this up--if you want to set up a build machine using <a href="http://cruisecontrol.sourceforge.net/" rel="noreferrer">CruiseControl</a> for continuous integration, CruiseControl integrates with NAnt nicely out of the box. <strong><em>UPDATE:</em></strong> CruiseControl also has an <a href="http://www.cruisecontrolnet.org/projects/ccnet/wiki/MsBuild_Task" rel="noreferrer">MSBuild task</a>.</li> <li><em>Please see comments below for full and up-to-date discussion of subjective differences.</em></li> </ul>
383,692
What is JSON and what is it used for?
<p>I've looked on Wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it.</p> <p>I have been building applications using PHP, MySQL and JavaScript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?</p>
383,699
16
4
null
2008-12-20 20:19:11.093 UTC
361
2021-06-18 20:36:48.107 UTC
2021-06-18 20:36:48.107 UTC
Dreas Grech
2,756,409
Ben
11,522
null
1
562
json
579,618
<p><strong>JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.</strong> It is based on a subset of JavaScript language (the way objects are built in JavaScript). As <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON" rel="noreferrer">stated in the MDN</a>, some JavaScript is not JSON, and some JSON is not JavaScript.</p> <p>An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (<em>The JSON format is specified in <a href="https://www.rfc-editor.org/rfc/rfc4627" rel="noreferrer">RFC 4627</a> by Douglas Crockford</em>), it has been the preferred format because it is much more <strong>lightweight</strong></p> <p>You can find a lot more info on the official <a href="http://www.json.org/" rel="noreferrer">JSON web site</a>.</p> <p>JSON is built on two structures:</p> <ul> <li>A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.</li> <li>An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.</li> </ul> <hr /> <h2>JSON Structure</h2> <p><br/><br/></p> <p><a href="http://www.json.org/object.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/VHjrV.gif" alt="JSON Object diagram" /></a><br/><br/> <a href="http://www.json.org/array.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/OCsS0.gif" alt="JSON Array diagram" /></a><br/><br/> <a href="http://www.json.org/value.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/7zOHB.gif" alt="JSON Value diagram" /></a><br/><br/> <a href="http://www.json.org/string.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/pzAPZ.gif" alt="JSON String diagram" /></a><br/><br/> <a href="http://www.json.org/number.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/EK6wD.gif" alt="JSON Number diagram" /></a><br/><br/></p> <p>Here is an example of JSON data:</p> <pre><code>{ &quot;firstName&quot;: &quot;John&quot;, &quot;lastName&quot;: &quot;Smith&quot;, &quot;address&quot;: { &quot;streetAddress&quot;: &quot;21 2nd Street&quot;, &quot;city&quot;: &quot;New York&quot;, &quot;state&quot;: &quot;NY&quot;, &quot;postalCode&quot;: 10021 }, &quot;phoneNumbers&quot;: [ &quot;212 555-1234&quot;, &quot;646 555-4567&quot; ] } </code></pre> <hr /> <h1>JSON in JavaScript</h1> <p><strong>JSON (in Javascript) is a string!</strong></p> <p>People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.</p> <p>In Javascript <code>var x = {x:y}</code> is <strong>not JSON</strong>, this is a <strong>Javascript object</strong>. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be <code>var x = '{&quot;x&quot;:&quot;y&quot;}'</code>. <code>x</code> is an object of type <strong>string</strong> not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, <code>var x = JSON.parse('{&quot;x&quot;:&quot;y&quot;}');</code>, <code>x</code> is now an object but this is not JSON anymore.</p> <p>See <a href="https://stackoverflow.com/questions/8294088/javascript-object-vs-json">Javascript object Vs JSON</a></p> <hr /> <p>When working with JSON and JavaScript, you may be tempted to use the <code>eval</code> function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 &amp; U+2029) valid in JSON but not in JavaScript (read more of this <a href="https://web.archive.org/web/20110622075541/http://timelessrepo.com/json-isnt-a-javascript-subset" rel="noreferrer" title="JSON: The Javascript subset that isn't">here</a>).</p> <p>Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found <a href="http://www.json.org/js.html" rel="noreferrer">here</a> and here is a <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">direct link</a> to the js file. Every major browser nowadays has <a href="https://stackoverflow.com/q/891299/1505348">its own implementation</a> for this.</p> <p>Example on how to use the JSON parser (with the json from the above code snippet):</p> <pre><code>//The callback function that will be executed once data is received from the server var callback = function (result) { var johnny = JSON.parse(result); //Now, the variable 'johnny' is an object that contains all of the properties //from the above code snippet (the json example) alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith' }; </code></pre> <p>The JSON parser also offers another very useful method, <code>stringify</code>. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to <em>send data back to the server:</em></p> <pre><code>var anObject = {name: &quot;Andreas&quot;, surname : &quot;Grech&quot;, age : 20}; var jsonFormat = JSON.stringify(anObject); //The above method will output this: {&quot;name&quot;:&quot;Andreas&quot;,&quot;surname&quot;:&quot;Grech&quot;,&quot;age&quot;:20} </code></pre> <p>The above two methods (<code>parse</code> and <code>stringify</code>) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this <a href="http://www.json.org/js.html" rel="noreferrer">here</a>)</p> <p>Btw, for all of you out there who think JSON is just for JavaScript, check out <a href="http://simonwillison.net/2006/Dec/20/json/" rel="noreferrer">this post</a> that explains and confirms otherwise.</p> <hr /> <h2>References</h2> <ul> <li><a href="http://www.json.org/" rel="noreferrer">JSON.org</a></li> <li><a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">Wikipedia</a></li> <li><a href="http://secretgeek.net/json_3mins.asp" rel="noreferrer">Json in 3 minutes</a> (Thanks <a href="https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it#384026">mson</a>)</li> <li><a href="http://developer.yahoo.com/javascript/json.html" rel="noreferrer">Using JSON with Yahoo! Web Services</a> (Thanks <a href="https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it#383716">gljivar</a>)</li> <li><a href="https://json-csv.com" rel="noreferrer">JSON to CSV Converter</a></li> <li>Alternative <a href="https://jsontoexcel.com" rel="noreferrer">JSON to CSV Converter</a></li> <li><a href="https://jsonlint.com/" rel="noreferrer">JSON Lint (JSON validator)</a></li> </ul>
706,382
Multiline strings in VB.NET
<p>Is there a way to have multiline strings in VB.NET like Python</p> <pre><code>a = """ multi line string """ </code></pre> <p>or PHP?</p> <pre><code>$a = &lt;&lt;&lt;END multi line string END; </code></pre> <p>Of course something that is not</p> <pre><code>"multi" &amp; _ "line </code></pre>
1,674,434
21
3
null
2009-04-01 16:36:48.567 UTC
25
2019-08-02 15:34:00.087 UTC
2019-08-02 15:34:00.087 UTC
null
3,170,982
pistacchio
42,636
null
1
154
string|vb.net
156,767
<p>You can use <strong><a href="https://msdn.microsoft.com/en-us/library/bb384629.aspx" rel="noreferrer">XML Literals</a></strong> to achieve a similar effect:</p> <pre><code>Imports System.XML Imports System.XML.Linq Imports System.Core Dim s As String = &lt;a&gt;Hello World&lt;/a&gt;.Value </code></pre> <p>Remember that if you have special characters, you should use a CDATA block:</p> <pre><code>Dim s As String = &lt;![CDATA[Hello World &amp; Space]]&gt;.Value </code></pre> <hr /> <h2>2015 UPDATE:</h2> <p>Multi-line string literals were introduced in <strong>Visual Basic 14</strong> (in <strong>Visual Studio 2015</strong>). The above example can be now written as:</p> <pre class="lang-vb prettyprint-override"><code>Dim s As String = &quot;Hello World &amp; Space&quot; </code></pre> <p><s> <code>MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.</code> </s></p> <p>Details are added to the <a href="https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-VB-14#multiline-string-literals" rel="noreferrer">Roslyn <em>New-Language-Features-in-VB-14</em></a> Github repository.</p>
1,085,162
Commit only part of a file in Git
<p>When I make changes to a file in Git, how can I commit only some of the changes?</p> <p>For example, how could I commit only 15 lines out of 30 lines that have been changed in a file?</p>
1,085,191
28
2
null
2009-07-06 02:25:02.39 UTC
1,134
2022-09-06 02:47:21.023 UTC
2017-03-07 18:03:41.677 UTC
null
-1
null
76,509
null
1
3,336
git|git-commit
540,073
<p>You can use:</p> <pre class="lang-bash prettyprint-override"><code>git add --patch &lt;filename&gt; </code></pre> <p>or for short:</p> <pre class="lang-bash prettyprint-override"><code>git add -p &lt;filename&gt; </code></pre> <p>Git will break down your file into what it thinks are sensible &quot;hunks&quot; (portions of the file). It will then prompt you with this question:</p> <pre><code>Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]? </code></pre> <p>Here is a description of each option:</p> <ul> <li><kbd>y</kbd> stage this hunk for the next commit</li> <li><kbd>n</kbd> do not stage this hunk for the next commit</li> <li><kbd>q</kbd> quit; do not stage this hunk or any of the remaining hunks</li> <li><kbd>a</kbd> stage this hunk and all later hunks in the file</li> <li><kbd>d</kbd> do not stage this hunk or any of the later hunks in the file</li> <li><kbd>g</kbd> select a hunk to go to</li> <li><kbd>/</kbd> search for a hunk matching the given regex</li> <li><kbd>j</kbd> leave this hunk undecided, see next undecided hunk</li> <li><kbd>J</kbd> leave this hunk undecided, see next hunk</li> <li><kbd>k</kbd> leave this hunk undecided, see previous undecided hunk</li> <li><kbd>K</kbd> leave this hunk undecided, see previous hunk</li> <li><kbd>s</kbd> split the current hunk into smaller hunks</li> <li><kbd>e</kbd> manually edit the current hunk <ul> <li>You can then edit the hunk manually by replacing <code>+</code>/<code>-</code> by <code>#</code> (thanks <a href="https://stackoverflow.com/users/1732521/veksen">veksen</a>)</li> </ul> </li> <li><kbd>?</kbd> print hunk help</li> </ul> <p>If the file is not in the repository yet, you can first do <code>git add -N &lt;filename&gt;</code>. Afterwards you can go on with <code>git add -p &lt;filename&gt;</code>.</p> <p>Afterwards, you can use:</p> <ul> <li><code>git diff --staged</code> to check that you staged the correct changes</li> <li><code>git reset -p</code> to unstage mistakenly added hunks</li> <li><code>git commit -v</code> to view your commit while you edit the commit message.</li> </ul> <p>Note this is far different than the <code>git format-patch</code> command, whose purpose is to parse commit data into a <code>.patch</code> files.</p> <p>Reference for future: <a href="https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging" rel="noreferrer">Git Tools - Interactive Staging</a></p>
1,175,208
Elegant Python function to convert CamelCase to snake_case?
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
1,176,023
30
4
2009-07-24 00:22:02.287 UTC
2009-07-24 00:22:02.287 UTC
158
2022-03-09 19:33:48.003 UTC
2016-02-23 13:22:54.103 UTC
null
1,079,110
null
55,246
null
1
332
python|camelcasing
289,924
<h2>Camel case to snake case</h2> <pre class="lang-py prettyprint-override"><code>import re name = 'CamelCaseName' name = re.sub(r'(?&lt;!^)(?=[A-Z])', '_', name).lower() print(name) # camel_case_name </code></pre> <p>If you do this many times and the above is slow, compile the regex beforehand:</p> <pre><code>pattern = re.compile(r'(?&lt;!^)(?=[A-Z])') name = pattern.sub('_', name).lower() </code></pre> <p>To handle more advanced cases specially (this is not reversible anymore):</p> <pre class="lang-py prettyprint-override"><code>def camel_to_snake(name): name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() print(camel_to_snake('camel2_camel2_case')) # camel2_camel2_case print(camel_to_snake('getHTTPResponseCode')) # get_http_response_code print(camel_to_snake('HTTPResponseCodeXYZ')) # http_response_code_xyz </code></pre> <p>To add also cases with two underscores or more:</p> <pre class="lang-py prettyprint-override"><code>def to_snake_case(name): name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) name = re.sub('__([A-Z])', r'_\1', name) name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name) return name.lower() </code></pre> <h2>Snake case to camel case</h2> <pre class="lang-py prettyprint-override"><code>name = 'snake_case_name' name = ''.join(word.title() for word in name.split('_')) print(name) # SnakeCaseName </code></pre>
596,351
How can I know which radio button is selected via jQuery?
<p>I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery?</p> <p>I can get all of them like this:</p> <pre><code>$("form :radio") </code></pre> <p>How do I know which one is selected?</p>
596,369
40
0
null
2009-02-27 19:53:27.18 UTC
394
2022-09-13 05:12:25.84 UTC
2020-01-10 15:06:37.937 UTC
Juan Manuel
1,782
Juan Manuel
1,782
null
1
2,987
javascript|jquery|html|jquery-selectors|radio-button
2,438,741
<p>To get the value of the <strong>selected</strong> <code>radioName</code> item of a form with id <code>myForm</code>:</p> <pre><code>$('input[name=radioName]:checked', '#myForm').val() </code></pre> <p>Here's an example:</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-js lang-js prettyprint-override"><code>$('#myForm input').on('change', function() { alert($('input[name=radioName]:checked', '#myForm').val()); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;form id="myForm"&gt; &lt;fieldset&gt; &lt;legend&gt;Choose radioName&lt;/legend&gt; &lt;label&gt;&lt;input type="radio" name="radioName" value="1" /&gt; 1&lt;/label&gt; &lt;br /&gt; &lt;label&gt;&lt;input type="radio" name="radioName" value="2" /&gt; 2&lt;/label&gt; &lt;br /&gt; &lt;label&gt;&lt;input type="radio" name="radioName" value="3" /&gt; 3&lt;/label&gt; &lt;br /&gt; &lt;/fieldset&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
6,315,323
How can I sort strings in NSMutableArray into alphabetical order?
<p>I have a list of strings in an <code>NSMutableArray</code>, and I want to sort them into alphabetical order before displaying them in my table view.</p> <p>How can I do that?</p>
6,315,442
4
0
null
2011-06-11 10:15:26.16 UTC
9
2016-02-22 06:15:07.97 UTC
2013-10-11 23:41:49.773 UTC
null
1,709,587
null
461,396
null
1
42
objective-c|ios|cocoa-touch|sorting|nsmutablearray
37,623
<p>There is the following Apple's working example, using <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/doc/uid/20000137-BABBHAGJ" rel="noreferrer"><code>sortedArrayUsingSelector:</code></a> and <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/localizedCaseInsensitiveCompare:" rel="noreferrer"><code>localizedCaseInsensitiveCompare:</code></a> in the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html#//apple_ref/doc/uid/20000132-SW8" rel="noreferrer">Collections Documentation</a>:</p> <pre><code>sortedArray = [anArray sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)]; </code></pre> <p>Note that this will return a new sorted array. If you want to sort your <code>NSMutableArray</code> in place, then use <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector:" rel="noreferrer"><code>sortUsingSelector:</code></a> instead, like so:</p> <pre><code>[mutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; </code></pre>
6,805,963
How to pass parameters with `include`?
<p>I have a PHP script called customers.php that is passed a parameter via the URL, e.g.:</p> <p><a href="http://www.mysite,com/customers.php?employeeId=1" rel="noreferrer">http://www.mysite,com/customers.php?employeeId=1</a></p> <p>Inside my customers.php script, I pick up the parameter thus:</p> <pre><code>$employeeId = $_GET['employeeId']; </code></pre> <p>That works just fine. I also have an HTML file with a form that inputs the parameter, and runs another php script, viz:</p> <pre><code>&lt;form method="post" action="listcustomers.php"&gt; Employee ID:&amp;nbsp; &lt;input name="employeeId" type="text"&gt;&lt;br&gt; &lt;input type="submit" value="Show"&gt; &lt;/form&gt; </code></pre> <p>Then in my listcustomers.php script, I pick up the parameter so:</p> <pre><code>$employeeId = $_POST['employeeId']; </code></pre> <p>So far so good. But his is where I am stuck. I want to run my customers.php script, and pass it the parameter that I pave picked up in the form. I am sure this is really simple, but just cannot get it to work. I have tried:</p> <pre><code>include "customers.php?employeeId=$employeeId&amp;password=password"; </code></pre> <p>But that does not work. Nor does anything else that I have tried. Please help me.</p>
6,805,978
6
5
null
2011-07-24 09:13:56.1 UTC
3
2021-09-27 12:53:29.83 UTC
2011-07-24 09:23:56.873 UTC
null
9,535
null
619,852
null
1
8
php
40,306
<p>You can't add a query string (Something like ?x=yyy&amp;vv=www) onto an include like that. Fortunately your includes have access to all the variables before them, so if <code>$_GET['employeeId']</code> is defined before you call:</p> <pre><code>include 'customers.php'; </code></pre> <p>Then customers.php will also have access to <code>$_GET['employeeId'];</code></p>
15,980,963
Opinion on ASP.NET MVC Onion-based architecture
<p>What is your opinion on the following 'generic' code-first Onion-inspired ASP.NET MVC architecture: <img src="https://i.stack.imgur.com/Q1Ngh.png" alt="screenshot of the solution explorer"></p> <p>The layers, explained:</p> <p><strong>Core</strong> - contain the Domain model. e.g. that's the business objects and their relationship. I am using Entity Framework to visually design the entities and the relations between them. It lets me generate a script for a database. I am getting automatically-generated POCO-like models, which I can freely refer to in the next layer (Persistence), since they are simple (i.e. they are not database-specific).</p> <p><strong>Persistence</strong> - Repository interface and implementations. Basically CRUD operations on the Domain model. </p> <p><strong>BusinessServices</strong> - A business layer around the repository. All the business logic should be here (e.g. <code>GetLargestTeam()</code>, etc). Uses CRUD operations to compose return objects or get/filter/store data. Should contain all business rules and validations.</p> <p><strong>Web (or any other UI)</strong> - In this particular case it's an MVC application, but the idea behind this project is to provide UI, driven by what the Business services offer. The UI project consumes the Business layer and has no direct access to the Repository. The MVC project has its own View models, which are specific to each View situation. I am not trying to force-feed it Domain Models.</p> <p><strong>So the references go like this:</strong> UI -> Business Services -> Repository -> Core objects</p> <p><strong>What I like about it:</strong></p> <ul> <li>I can design my objects, rather than code them manually. I am getting code-generated Model objects.</li> <li>UI is driven/enforced by the Business layer. Different UI applications can be coded against the same Business model.</li> </ul> <p><strong>Mixed feelings about:</strong></p> <ul> <li>Fine, we have a pluggable repository implementation, but how often do you really have different implementations of the same persistence interface?</li> <li>Same goes for the UI - we have the technical ability to implement different UI apps against the same business rules, but why would we do that, when we can simply render different views (mobile, desktop, etc)?</li> <li>I am not sure if the UI should only communicate with the Business Layer via View models, or should I use Domain Models to transfer data, as I do now. For display, I am using view models, but for data transfer I am using Domain models. Wrong?</li> </ul> <p><strong>What I don't like:</strong></p> <ul> <li>The Core project is now referenced in every other project - because I want/have to access the Domain models. In classic Onion architecture, the core is referenced only by the next layer.</li> <li>The DbContext is implemented in the .Core project, because it is being generated by the Entity Framework, in the same place where the .edmx is. I actually want to use the .EDMX for the visual model design, but I feel like the DbContext belongs to the Persistence layer, somewhere within the database-specific repository implementation.</li> </ul> <p>As a final question - what is a good architecture which is not over-engineered (such as a full-blown Onion, where we have injections, service locators, etc) but at the same time provides some reasonable flexibility, in places where you would realistically need it?</p> <p>Thanks</p>
16,019,657
4
6
null
2013-04-12 21:15:17.09 UTC
20
2020-11-05 11:55:51.18 UTC
null
null
null
null
253,266
null
1
20
entity-framework|asp.net-mvc-4|onion-architecture
8,599
<p>Wow, there’s a lot to say here! ;-)</p> <p>First of all, let’s talk about the overall architecture. </p> <p>What I can see here is that it’s not really an Onion architecture. You forgot the outermost layer, the “Dependency Resolution” layer. In an Onion architecture, it’s up to this layer to wires up Core interfaces to Infrastructure implementations (where your Persistence project should reside). </p> <p>Here’s a brief description of what you should find in an Onion application. What goes in the Core layer is everything unique to the business: Domain model, business workflows... This layer defines all technical implementation needs as interfaces (i.e.: repositories’ interfaces, logging interfaces, session’s interfaces …). The Core layer cannot reference any external libraries and has no technology specific code. The second layer is the Infrastructure layer. This layer provides implementations for non-business Core interfaces. This is where you call your DB, your web services … You can reference any external libraries you need to provide implementations, deploy as many nugget packages as you want :-). The third layer is your UI, well you know what to put in there ;-) And the latest layer, it’s the Dependency Resolution I talked about above.</p> <p>Direction of dependency between layers is toward the center.</p> <p>Here’s how it could looks like:</p> <p><img src="https://i.stack.imgur.com/bpfhF.jpg" alt="Onion App Structure"></p> <p>The question now is: how to fit what you’ve already coded in an Onion architecture.</p> <blockquote> <p>Core: contain the Domain model</p> </blockquote> <p>Yes, this is the right place! </p> <blockquote> <p>Persistence - Repository interface and implementations</p> </blockquote> <p>Well, you’ll need to separate interfaces with implementations. Interfaces need to be moved into Core and implementations need to be moved into Infrastructure folder (you can call this project Persistence). </p> <blockquote> <p>BusinessServices - A business layer around the repository. All the business logic should be here</p> </blockquote> <p>This needs to be moved in Core, but you shouldn’t use repositories implementations here, just manipulate interfaces!</p> <blockquote> <p>Web (or any other UI) - In this particular case it's an MVC application</p> </blockquote> <p>cool :-)</p> <p>You will need to add a “Bootstrapper“ project, just have a look <a href="https://stackoverflow.com/questions/14891371/dependency-resolution-in-onion-architecture">here</a> to see how to proceed. </p> <p>About your mixed feelings:</p> <p>I won’t discuss about the need of having repositories or not, you’ll find plenty of answers on stackoverflow.</p> <p>In my ViewModel project I have a folder called “Builder”. It’s up to my Builders to discuss with my Business services interfaces in order to get data. The builder will receive lists of Core.Domain objects and will map them into the right ViewModel.</p> <p>About what you don’t like:</p> <blockquote> <p>In classic Onion architecture, the core is referenced only by the next layer.</p> </blockquote> <p>False ! :-) Every layer needs the Core to have access to all the interfaces defined in there.</p> <blockquote> <p>The DbContext is implemented in the .Core project, because it is being generated by the Entity Framework, in the same place where the .edmx is</p> </blockquote> <p>Once again, it’s not a problem as soon as it’s really easy to edit the T4 template associated with your EDMX. You just need to change the path of the generated files and you can have the EDMX in the Infrastructure layer and the POCO’s in your Core.Domain project.</p> <p>Hope this helps!</p>
15,759,195
Reduce size of Bitmap to some specified pixel in Android
<p>I would like to reduce My Bitmap image size to maximum of 640px. For example I have Bitmap image of size 1200 x 1200 px .. How can I reduce it to 640px.</p>
15,759,464
4
0
null
2013-04-02 08:14:55.667 UTC
7
2018-04-20 08:56:52.373 UTC
null
null
null
null
232,988
null
1
33
android|bitmap|compression
43,152
<p>If you pass bitmap <code>width</code> and <code>height</code> then use:</p> <pre><code>public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth, int bitmapHeight) { return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight, true); } </code></pre> <p>If you want to keep the bitmap ratio the same, but reduce it to a maximum side length, use:</p> <pre><code>public Bitmap getResizedBitmap(Bitmap image, int maxSize) { int width = image.getWidth(); int height = image.getHeight(); float bitmapRatio = (float) width / (float) height; if (bitmapRatio &gt; 1) { width = maxSize; height = (int) (width / bitmapRatio); } else { height = maxSize; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(image, width, height, true); } </code></pre>
15,604,140
Replace multiple strings with multiple other strings
<p>I'm trying to replace multiple words in a string with multiple other words. The string is "I have a cat, a dog, and a goat."</p> <p>However, this does not produce "I have a dog, a goat, and a cat", but instead it produces "I have a cat, a cat, and a cat". Is it possible to replace multiple strings with multiple other strings at the same time in JavaScript, so that the correct result will be produced?</p> <pre><code>var str = "I have a cat, a dog, and a goat."; str = str.replace(/cat/gi, "dog"); str = str.replace(/dog/gi, "goat"); str = str.replace(/goat/gi, "cat"); //this produces "I have a cat, a cat, and a cat" //but I wanted to produce the string "I have a dog, a goat, and a cat". </code></pre>
67,374,697
27
6
null
2013-03-24 21:19:55.123 UTC
144
2022-05-23 08:42:37.097 UTC
2018-09-17 06:42:44.84 UTC
null
4,652,706
null
975,097
null
1
293
javascript|node.js|regex|string|replace
394,091
<p>As an answer to:</p> <blockquote> <p>looking for an up-to-date answer</p> </blockquote> <p>If you are using &quot;words&quot; as in your current example, you might extend the answer of <a href="https://stackoverflow.com/a/15604206/5424988">Ben McCormick</a> using a non capture group and add word boundaries <code>\b</code> at the left and at the right to prevent partial matches.</p> <pre><code>\b(?:cathy|cat|catch)\b </code></pre> <ul> <li><code>\b</code> A word boundary to prevent a partial match</li> <li><code>(?:</code> Non capture group <ul> <li><code>cathy|cat|catch</code> match one of the alternatives</li> </ul> </li> <li><code>)</code> Close non capture group</li> <li><code>\b</code> A word boundary to prevent a partial match</li> </ul> <p>Example for the original question:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "I have a cat, a dog, and a goat."; const mapObj = { cat: "dog", dog: "goat", goat: "cat" }; str = str.replace(/\b(?:cat|dog|goat)\b/gi, matched =&gt; mapObj[matched]); console.log(str);</code></pre> </div> </div> </p> <p>Example for the example in the comments that not seems to be working well:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "I have a cat, a catch, and a cathy."; const mapObj = { cathy: "cat", cat: "catch", catch: "cathy" }; str = str.replace(/\b(?:cathy|cat|catch)\b/gi, matched =&gt; mapObj[matched]); console.log(str);</code></pre> </div> </div> </p>
15,942,880
mocking a method that return generics with wildcard using mockito
<p>I'm using mockito 1.9.5. I have the following code:</p> <pre><code>public class ClassA { public List&lt;? extends MyInterface&gt; getMyInterfaces() { return null; } public static void testMock() { List&lt;MyInterface&gt; interfaces = new ArrayList&lt;&gt;(); ClassA classAMock = mock(ClassA.class); when(classAMock.getMyInterfaces()).thenReturn(interfaces); } </code></pre> <p>I get a compilation error for the <code>thenReturn(interfaces)</code> saying:</p> <pre><code>"The method thenReturn(List&lt;capture#1-of ? extends MyInterface&gt;) in the type OngoingStubbing&lt;List&lt;capture#1-of ? extends MyInterface&gt;&gt; is not applicable for the arguments (List&lt;MyInterface&gt;)" </code></pre> <p>However, when I use the <code>thenAnswer</code> method of mockito, I don't get the error. Can anyone tell me what's going on? Why do I get the error when I use the <code>thenReturn</code> method? Is there any other way to solve this problem when <code>ClassA</code> is provided by a 3rd party and cannot be modified?</p>
15,944,985
2
3
null
2013-04-11 07:21:08.337 UTC
10
2018-10-02 13:27:49.7 UTC
null
null
null
null
1,504,992
null
1
50
java|generics|mockito
27,206
<p><strong>EDIT</strong> : Starting from Mockito 1.10.x, generics types that are embedded in the class are now used by Mockito for deep stubs. ie. </p> <pre><code>public interface A&lt;T extends Observer &amp; Comparable&lt;? super T&gt;&gt; { List&lt;? extends B&gt; bList(); T observer(); } B b = deep_stubbed.bList().iterator().next(); // returns a mock of B ; mockito remebers that A returns a List of B Observer o = deep_stubbed.observer(); // mockito can find that T super type is Observer Comparable&lt;? super T&gt; c = deep_stubbed.observer(); // or that T implements Comparable </code></pre> <p>Mockito tries its best to get type information that the compiler embeds, but when erasure applies, mockito cannot do anything but return a mock of <code>Object</code>.</p> <hr> <p><strong>Original</strong> : Well that's more of an issue with generics than with Mockito. For generics, you should read what <strong>Angelika Langer</strong> wrote on them. And for the current topic, i.e. wildcards, read this <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#Wildcards" rel="noreferrer">section</a>.</p> <p>But for short, what you could use is the other syntax of Mockito to help with your current situation :</p> <pre><code>doReturn(interfaces).when(classAMock).getMyInterfaces(); </code></pre> <p>Or with the BDD aliases : </p> <pre><code>willReturn(interfaces).given(classAMock).getMyInterfaces(); </code></pre> <p>Nevertheless, you could write wrappers that are more generic friendly. That will help future developers working with same 3rd party API.</p> <hr> <p>As a side note: you shouldn't mocks type you don't own, it can lead to many errors and issues. Instead you should have some wrapper. DAO and repositories for example represent such idea, one will mock the DAO or repository interface, but not the JDBC / JPA / hibernate stuff. There are many blog posts about that: </p> <ul> <li><a href="http://davesquared.net/2011/04/dont-mock-types-you-dont-own.html" rel="noreferrer">http://davesquared.net/2011/04/dont-mock-types-you-dont-own.html</a></li> <li><a href="http://blog.8thlight.com/eric-smith/2011/10/27/thats-not-yours.html" rel="noreferrer">http://blog.8thlight.com/eric-smith/2011/10/27/thats-not-yours.html</a></li> <li><a href="https://web.archive.org/web/20140923101818/http://freshbrewedcode.com/derekgreer/2012/04/01/tdd-best-practices-dont-mock-others/" rel="noreferrer">https://web.archive.org/web/20140923101818/http://freshbrewedcode.com/derekgreer/2012/04/01/tdd-best-practices-dont-mock-others/</a></li> <li>...</li> </ul>
50,391,868
python 3.5 in statsmodels ImportError: cannot import name '_representation'
<p>I cannot manage to import statsmodels.api correctly when i do that I have this error:</p> <blockquote> <p>File "/home/mlv/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/tools.py", line 59, in set_mode from . import (_representation, _kalman_filter, _kalman_smoother, ImportError: cannot import name '_representation'</p> </blockquote> <p>I already try to re-install or update it, that does not change. plese i need help =) </p>
50,403,307
3
5
null
2018-05-17 12:47:07.493 UTC
2
2021-06-16 06:49:58.603 UTC
2018-05-17 12:47:34.423 UTC
null
3,337,070
null
9,696,340
null
1
15
python|python-3.x|python-3.5|importerror|statsmodels
40,265
<p>Please see <a href="https://github.com/statsmodels/statsmodels/issues/4654" rel="noreferrer">the github report</a> for more detail.</p> <p>It turns out that statsmodels is dependent upon several packages being installed before it so that it can key on them to compile its own modules. I don't completely understand the dependencies, or why they aren't specified in the package's setup, but this solves the problem for me.</p> <p>If you need to clean out what you already have, you can uninstall with the following:</p> <pre><code>pip3 uninstall statsmodels </code></pre> <p>then make sure your dependencies are there</p> <pre><code>pip3 install numpy scipy patsy pandas </code></pre> <p>then, only after these four are installed first:</p> <pre><code>pip3 install statsmodels </code></pre> <p>Then move on with your imports and code.</p> <p>==== additionally / alternately =====</p> <p>It is recommended to use <a href="https://docs.python.org/3.5/library/venv.html" rel="noreferrer">virtualenv</a> in most cases. It also would allow you to create your own environments where you can control your own libraries. You can create all you want, and name them whatever you like for each project. It is likely that you are now using a mix of python modules installed at the system level and the user level, and they could change out from under you when the system packages are updated. It's possible you have a system version of scipy that conflicts with a newer user version of statsmodels. For python 3.5, you have to install venv; but with 3.6 it becomes part of the distribution.</p> <p>First, look at your system paths from when you just run python3.</p> <pre><code>python3 &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) &gt;&gt;&gt; quit() </code></pre> <p>And then create a clean, independent environment and do the same.</p> <pre><code>sudo apt install python3-venv python3 -m venv ~/name_me source ~/name_me/bin/activate python3 &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) &gt;&gt;&gt; quit() </code></pre> <p>It should have paths to base libaries, but avoid paths to the installed additional packages. You have a clean environment to install them into. Then, from within this virtualenv, which you should be able to detect by your changed shell prompt, you can do the pip installs from before and see if they work.</p> <pre><code>pip install numpy scipy patsy pandas pip install statsmodels python &gt;&gt;&gt; import statsmodels.api as sm </code></pre> <p>And when you are done, you can exit the virtualenv</p> <pre><code>deactivate </code></pre>
51,032,328
Angular component default style css display block
<p>I am sick of all my angular elements being 0x0 pixels, because they have names like app-card, app-accordion, which the browser does not recognise as HTML5 compliant elements and as thus, will not give any default styles to.</p> <p>This is means that inspecting it in Chrome, I fail to see the container dimensions and when the DOM is really deep, it is hard to understand which element encompasses which area on the screen, etc.</p> <p>It feels logical to me that all angular elements should be block displayed by default, because for the majority, it makes sense.</p> <p>As an example, consider these elements </p> <pre><code>bbs-accordion-header //(width 0px, height 0px) </code></pre> <p>contains </p> <pre><code>bbs-accordion-header-regular //(width 1920px, height 153px) </code></pre> <p><a href="https://i.stack.imgur.com/0TT72.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0TT72.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/8x6mR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8x6mR.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/ovWRh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ovWRh.png" alt="enter image description here"></a></p> <p>So bbs-accordion-header does not have any dimensions, even though it's children do have them.</p> <p>I solve this, by manually adding one line to each elements .scss file</p> <pre><code>:host { display: block; } </code></pre> <p>But it is very tedious to add this manually every time. Does anyone know of a better solution?</p>
60,098,592
1
2
null
2018-06-25 21:57:52.663 UTC
1
2020-03-27 20:27:00.547 UTC
2019-03-24 19:00:19.373 UTC
null
1,702,592
null
1,702,592
null
1
28
angular|angular6|angular5|angular2-template|angular7
10,657
<p><a href="https://github.com/angular/angular-cli/pull/16299" rel="noreferrer">My pull-request has been merged</a>.</p> <p>With the upcoming release of Angular CLI <strong>v9.1.0</strong> a new option is going to be available:<br></p> <pre><code>--displayBlock=true|false </code></pre> <p>Docs: <a href="https://next.angular.io/cli/generate#component" rel="noreferrer">https://next.angular.io/cli/generate#component</a></p> <p>For the impatient: <strong>It's available right now in <a href="https://github.com/angular/angular-cli/releases/tag/v9.1.0-next.0" rel="noreferrer">v9.1.0-next.0</a></strong></p> <br> <h2>When using the CLI:</h2> <pre><code>ng generate component dashboard --displayBlock=true </code></pre> <h2>Settting a default value in <strong>angular.json</strong>:</h2> <pre><code>... &quot;projectType&quot;: &quot;application&quot;, &quot;schematics&quot;: { &quot;@schematics/angular:component&quot;: { &quot;displayBlock&quot;: true } } ... </code></pre> <p>From now on any generated component, be it with the css inlined or not, will contain the css:</p> <p><code>:host { display: block; }</code></p> <p>More detailed information is available here: <a href="https://blog.rryter.ch/2020/01/19/angular-cli-generating-block-components-by-default/" rel="noreferrer">https://blog.rryter.ch/2020/01/19/angular-cli-generating-block-components-by-default/</a></p>
10,552,016
How to prevent the cron job execution, if it is already running
<p>I have one php script, and I am executing this script via cron every 10 minutes on CentOS.</p> <p>The problem is that if the cron job will take more than 10 minutes, then another instance of the same cron job will start.</p> <p>I tried one trick, that is:</p> <ol> <li>Created one lock file with php code (same like pid files) when the cron job started.</li> <li>Removed the lock file with php code when the job finished.</li> <li>And when any new cron job started execution of script, I checked if lock file exists and if so, aborted the script.</li> </ol> <p>But there can be one problem that, when the lock file is not deleted or removed by script because of any reason. The cron will never start again.</p> <p>Is there any way I can stop the execution of a cron job again if it is already running, with Linux commands or similar to this?</p>
10,552,054
9
3
null
2012-05-11 13:09:06.947 UTC
19
2017-10-22 20:21:00.66 UTC
2014-08-08 22:08:37.127 UTC
null
12,892
null
1,358,434
null
1
33
php|cron|centos
47,732
<p>Advisory locking is made for exactly this purpose.</p> <p>You can accomplish advisory locking with <a href="http://php.net/flock" rel="noreferrer"><code>flock()</code></a>. Simply apply the function to a previously opened lock file to determine if another script has a lock on it.</p> <pre><code>$f = fopen('lock', 'w') or die ('Cannot create lock file'); if (flock($f, LOCK_EX | LOCK_NB)) { // yay } </code></pre> <p>In this case I'm adding <code>LOCK_NB</code> to prevent the next script from waiting until the first has finished. Since you're using cron there will always be a next script.</p> <p>If the current script prematurely terminates, any file locks will get released by the OS.</p>
35,520,160
python logging performance comparison and options
<p>I am researching high performance logging in Python and so far have been disappointed by the performance of the python standard logging module - but there seem to be no alternatives. Below is a piece of code to performance test 4 different ways of logging:</p> <pre><code>import logging import timeit import time import datetime from logutils.queue import QueueListener, QueueHandler import Queue import threading tmpq = Queue.Queue() def std_manual_threading(): start = datetime.datetime.now() logger = logging.getLogger() hdlr = logging.FileHandler('std_manual.out', 'w') logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) def logger_thread(f): while True: item = tmpq.get(0.1) if item == None: break logging.info(item) f = open('manual.out', 'w') lt = threading.Thread(target=logger_thread, args=(f,)) lt.start() for i in range(100000): tmpq.put("msg:%d" % i) tmpq.put(None) lt.join() print datetime.datetime.now() - start def nonstd_manual_threading(): start = datetime.datetime.now() def logger_thread(f): while True: item = tmpq.get(0.1) if item == None: break f.write(item+"\n") f = open('manual.out', 'w') lt = threading.Thread(target=logger_thread, args=(f,)) lt.start() for i in range(100000): tmpq.put("msg:%d" % i) tmpq.put(None) lt.join() print datetime.datetime.now() - start def std_logging_queue_handler(): start = datetime.datetime.now() q = Queue.Queue(-1) logger = logging.getLogger() hdlr = logging.FileHandler('qtest.out', 'w') ql = QueueListener(q, hdlr) # Create log and set handler to queue handle root = logging.getLogger() root.setLevel(logging.DEBUG) # Log level = DEBUG qh = QueueHandler(q) root.addHandler(qh) ql.start() for i in range(100000): logging.info("msg:%d" % i) ql.stop() print datetime.datetime.now() - start def std_logging_single_thread(): start = datetime.datetime.now() logger = logging.getLogger() hdlr = logging.FileHandler('test.out', 'w') logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) for i in range(100000): logging.info("msg:%d" % i) print datetime.datetime.now() - start if __name__ == "__main__": """ Conclusion: std logging about 3 times slower so for 100K lines simple file write is ~1 sec while std logging ~3. If threads are introduced some overhead causes to go to ~4 and if QueueListener and events are used with enhancement for thread sleeping that goes to ~5 (probably because log records are being inserted into queue). """ print "Testing" #std_logging_single_thread() # 3.4 std_logging_queue_handler() # 7, 6, 7 (5 seconds with sleep optimization) #nonstd_manual_threading() # 1.08 #std_manual_threading() # 4.3 </code></pre> <ol> <li>The nonstd_manual_threading option works best since there is no overhead of the logging module but obviously you miss out on a lot of features such as formatters, filters and the nice interface</li> <li>The std_logging in a single thread is the next best thing but still about 3 times slower than nonstd manual threading. </li> <li>The std_manual_threading option dumps messages into a threadsafe queue and in a separate thread uses the standard logging module. That comes out to be about 25% higher than option 2, probably due to context switching costs.</li> <li>Finally, the option using "logutils"'s QueueHandler comes out to be the most expensive. I tweaked the code of logutils/queue.py's _monitor method to sleep for 10 millis after processing 500 messages as long as there are less than 100K messages in the queue. That brings the runtime down from 7 seconds to 5 seconds (probably due to avoiding context switching costs).</li> </ol> <p>My question is, why is there so much performance overhead with the logging module and are there any alternatives? Being a performance sensitive app does it even make sense to use the logging module?</p> <p>p.s.: I have profiled the different scenarios and seems like LogRecord creation is expensive.</p>
35,522,577
3
5
null
2016-02-20 06:53:56.517 UTC
9
2021-10-26 16:23:05.677 UTC
null
null
null
null
559,095
null
1
24
python|multithreading|performance|logging|python-multithreading
17,556
<p>The stdlib <code>logging</code> package provides a lot of flexibility and functionality for developers / devops / support staff, and that flexibility comes at some cost, obviously. If the need for performance trumps the need for flexibility, you need to go with something else. Did you take the steps to optimise described <a href="https://docs.python.org/2/howto/logging.html#optimization" rel="noreferrer">in the docs</a>? A typical logging call takes of the order of <em>tens of microseconds</em> on reasonable hardware, which hardly seems excessive. However, logging in tight loops is seldom advisable, if only because the amount of info generated might take too much time to wade through.</p> <p>The code to find the caller can be quite expensive, but is needed if you want e.g. filename and line number where the logging call was made.</p> <p><code>QueueHandler</code> is intended for scenarios where the logging I/O will take significant time and can't be done in-band. For example, a web application whose logs need to be sent by email to site administrators cannot risk using <code>SMTPHandler</code> directly, because the email handshake can be slow.</p> <p>Don't forget that thread context switching in Python is slow. Did you try <code>SocketHandler</code>? There is a suitable starting point <a href="https://docs.python.org/2/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network" rel="noreferrer">in the docs</a> for a separate receiver process that does the actual I/O to file, email etc. So your process is only doing socket I/O and not doing context switches just for logging. And using domain sockets or UDP might be faster still, though the latter is of course lossy.</p> <p>There are other ways to optimise. For example, standard handlers in logging do locking around <code>emit()</code>, for thread safety - if in a specific scenario under your control there is no contention for the handler, you could have a handler subclass that no-ops the lock acquisition and release. And so on.</p>
33,415,388
What's the difference between hex code (\x) and unicode (\u) chars?
<p>From <code>?Quotes</code>:</p> <blockquote> <pre><code>\xnn character with given hex code (1 or 2 hex digits) \unnnn Unicode character with given code (1--4 hex digits) </code></pre> </blockquote> <p>In the case where the Unicode character has only one or two digits, I would expect these characters to be the same. In fact, one of the examples on the <code>?Quotes</code> help page shows:</p> <pre><code>"\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21" ## [1] "Hello World!" "\u48\u65\u6c\u6c\u6f\u20\u57\u6f\u72\u6c\u64\u21" ## [1] "Hello World!" </code></pre> <p>However, under Linux, when trying to print a pound sign, I see</p> <pre><code>cat("\ua3") ## £ cat("\xa3") ## � </code></pre> <p>That is, the <code>\x</code> hex code fails to display correctly. (This behaviour persisted with any locale that I tried.) Under Windows 7 both versions show a pound sign.</p> <p>If I convert to integer and back then the pound sign displays correctly under Linux.</p> <pre><code>cat(intToUtf8(utf8ToInt("\xa3"))) ## £ </code></pre> <p>Incidentally, this doesn't work under Windows, since <code>utf8ToInt("\xa3")</code> returns <code>NA</code>.</p> <p>Some <code>\x</code> characters return <code>NA</code> under Windows but throw an error under Linux. For example:</p> <pre><code>utf8ToInt("\xf0") ## Error in utf8ToInt("\xf0") : invalid UTF-8 string </code></pre> <p>(<code>"\uf0"</code> is a valid character.)</p> <p>These examples show that there are some differences between <code>\x</code> and <code>\u</code> forms of characters, which seem to be OS-specific, but I can't see any logic in how they are defined. </p> <p>What are the difference between these two character forms?</p>
33,417,168
1
6
null
2015-10-29 13:19:45.423 UTC
11
2018-02-11 09:02:09.1 UTC
2018-02-11 09:02:09.1 UTC
null
1,030,110
null
134,830
null
1
31
r|unicode|hex
23,015
<p>The escape sequence <code>\xNN</code> inserts the raw byte <code>NN</code> into a string, whereas <code>\uNN</code> inserts the UTF-8 bytes for the Unicode code point <code>NN</code> into a UTF-8 string:</p> <pre><code>&gt; charToRaw('\xA3') [1] a3 &gt; charToRaw('\uA3') [1] c2 a3 </code></pre> <p>These two types of escape sequence cannot be mixed in the same string:</p> <pre><code>&gt; '\ua3\xa3' Error: mixing Unicode and octal/hex escapes in a string is not allowed </code></pre> <p>This is because the escape sequences also define the <em>encoding</em> of the string. A <code>\uNN</code> sequence explicitly sets the encoding of the entire string to "UTF-8", whereas <code>\xNN</code> leaves it in the default "unknown" (aka. native) encoding:</p> <pre><code>&gt; Encoding('\xa3') [1] "unknown" &gt; Encoding('\ua3') [1] "UTF-8" </code></pre> <p>This becomes important when printing strings, as they need to be converted into the appropriate output encoding (e.g., that of your console). Strings with a defined encoding can be converted appropriately (see <code>enc2native</code>), but those with an "unknown" encoding are simply output as-is:</p> <ul> <li>On Linux, your console is probably expecting UTF-8 text, and as <code>0xA3</code> is not a valid UTF-8 sequence, it gives you "�".</li> <li>On Windows, your console is probably expecting Windows-1252 text, and as <code>0xA3</code> is the correct encoding for "£", that's what you see. (When the string is <code>\uA3</code>, a conversion from UTF-8 to Windows-1252 takes place.)</li> </ul> <p>If the encoding is set explicitly, the appropriate conversion will take place on Linux:</p> <pre><code>&gt; s &lt;- '\xa3' &gt; Encoding(s) &lt;- 'latin1' &gt; cat(s) £ </code></pre>
13,467,034
Add elements from one list to another C#
<p>What is the simplest way to add elements of one list to another?</p> <p>For example, I have two lists:</p> <p>List A which contains x items List B which contains y items.</p> <p>I want to add elements of B to A so that A now contains X+Y items. I know this can done using a loop but is there a built in method for this? Or any other technique?</p>
13,467,046
2
0
null
2012-11-20 05:21:34.18 UTC
2
2012-11-20 05:35:04.84 UTC
null
null
null
null
1,081,402
null
1
22
c#
63,987
<p>Your question describes the <a href="http://msdn.microsoft.com/en-us/library/z883w3dc.aspx">List.AddRange</a> method, which copies all the elements of its argument into the list object on which it is called.</p> <p>As an example, the snippet</p> <pre><code>List&lt;int&gt; listA = Enumerable.Range(0, 10).ToList(); List&lt;int&gt; listB = Enumerable.Range(11, 10).ToList(); Console.WriteLine("Old listA: [{0}]", string.Join(", ", listA)); Console.WriteLine("Old listB: [{0}]", string.Join(", ", listB)); listA.AddRange(listB); Console.WriteLine("New listA: [{0}]", string.Join(", ", listA)); </code></pre> <p>prints</p> <pre><code>Old listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Old listB: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] New listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] </code></pre> <p>showing that all the elements of <code>listB</code> were added to <code>listA</code> in the <code>AddRange</code> call.</p>
13,389,398
Finding out how many times an array element appears
<p>I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.</p> <p>For instance, in <code>[1, 2, 3, 4, 4, 4, 3]</code>, 1 appears one time, 4 appears three times, and so on.</p> <p>How could I possibly ask my computer to tell me how many times an array element appears?</p> <p>Solved, here's the final product.</p> <pre><code> &lt;script type="text/javascript"&gt; var deck = []; var cards = []; var convertedcards = []; var kinds = []; var phase = 1; var displaycard = []; var options = 0; var endgame = false; // Fill Deck // for(i = 0; i &lt; 52; i++){ deck[deck.length] = i; } // Distribute Cards // for(i = 0; i &lt; 7; i++){ cards[cards.length] = Number(Math.floor(Math.random() * 52)); if(deck.indexOf(cards[cards.length - 1]) === -1){ cards.splice(cards.length - 1, cards.length); i = i - 1; }else{ deck[cards[cards.length - 1]] = "|"; } } // Convert Cards // for(i = 0; i &lt; 7; i++){ convertedcards[i] = (cards[i] % 13) + 1; } // Cards Kind // for(i = 0; i &lt; 7; i++){ if(cards[i] &lt; 13){ kinds[kinds.length] = "H"; }else if(cards[i] &lt; 27 &amp;&amp; cards[i] &gt; 12){ kinds[kinds.length] = "C"; }else if(cards[i] &lt; 40 &amp;&amp; cards[i] &gt; 26){ kinds[kinds.length] = "D"; }else{ kinds[kinds.length] = "S"; } } // Card Display // for(i = 0; i &lt; 7; i++){ displaycard[i] = convertedcards[i] + kinds[i]; } // Hand Strenght // var handstrenght = function(){ var usedcards = []; var count = 0; var pairs = []; for(i = 0, a = 1; i &lt; 7; a++){ if(convertedcards[i] === convertedcards[a] &amp;&amp; a &lt; 7 &amp;&amp; usedcards[i] != "|"){ pairs[pairs.length] = convertedcards[i]; usedcards[a] = "|"; }else if(a &gt; 6){ i = i + 1; a = i; } } // Flush &gt;.&lt; // var flush = false; for(i = 0, a = 1; i &lt; 7; i++, a++){ if(kinds[i] === kinds[a] &amp;&amp; kinds[i] != undefined){ count++; if(a &gt;= 6 &amp;&amp; count &gt;= 5){ flush = true; count = 0; }else if(a &gt;= 6 &amp;&amp; count &lt; 5){ count = 0; } } } // Straight &gt;.&lt; // var straight = false; convertedcards = convertedcards.sort(function(a,b){return a-b}); if(convertedcards[2] &gt; 10 &amp;&amp; convertedcards[3] &gt; 10 &amp;&amp; convertedcards[4] &gt; 10){ convertedcards[0] = 14; convertedcards = convertedcards.sort(function(a,b){return a-b}); } alert(convertedcards); if(convertedcards[0] + 1 === convertedcards[1] &amp;&amp; convertedcards[1] + 1 === convertedcards[2] &amp;&amp; convertedcards[2] + 1 === convertedcards[3] &amp;&amp; convertedcards[3] + 1 === convertedcards[4]){ straight = true; }else if(convertedcards[1] + 1 === convertedcards[2] &amp;&amp; convertedcards[2] + 1 === convertedcards[3] &amp;&amp; convertedcards[3] + 1 === convertedcards[4] &amp;&amp; convertedcards[4] + 1 === convertedcards[5]){ straight = true; }else if(convertedcards[2] + 1 === convertedcards[3] &amp;&amp; convertedcards[3] + 1 === convertedcards[4] &amp;&amp; convertedcards[4] + 1 === convertedcards[5] &amp;&amp; convertedcards[5] + 1 === convertedcards[6]){ straight = true; } // Royal Flush, Straight Flush, Flush, Straight &gt;.&lt; // var royalflush = false; if(straight === true &amp;&amp; flush === true &amp;&amp; convertedcards[6] === 14){ royalflush = true; alert("You have a Royal Flush"); } else if(straight === true &amp;&amp; flush === true &amp;&amp; royalflush === false){ alert("You have a straight flush"); }else if(straight === true &amp;&amp; flush === false){ alert("You have a straight"); }else if(straight === false &amp;&amp; flush === true){ alert("You have a flush"); } // Full House &gt;.&lt; // if(pairs[0] === pairs[1] &amp;&amp; pairs[1] != pairs[2] &amp;&amp; pairs.length &gt;= 3){ fullhouse = true; alert("You have a fullhouse"); }else if(pairs[0] != pairs[1] &amp;&amp; pairs[1] === pairs[2] &amp;&amp; pairs.length &gt;= 3){ fullhouse = true; alert("You have a fullhouse"); }else if(pairs[0] != pairs[1] &amp;&amp; pairs[1] != pairs[2] &amp;&amp; pairs[2] === pairs[3] &amp;&amp; pairs.length &gt;= 3){ fullhouse = true; alert("You have a fullhouse"); } // Four of a kind &gt;.&lt; // else if(pairs[0] === pairs[1] &amp;&amp; pairs[1] === pairs[2] &amp;&amp; pairs.length &gt; 0){ alert("You have four of a kind"); } // Three of a kind &gt;.&lt; // else if(pairs[0] === pairs[1] &amp;&amp; flush === false &amp;&amp; straight === false &amp;&amp; pairs.length === 2){ alert("You have three of a kind"); } // Double Pair &gt;.&lt; // else if(pairs[0] != pairs[1] &amp;&amp; flush === false &amp;&amp; straight === false &amp;&amp; pairs.length &gt; 1){ alert("You have a double pair"); } // Pair &gt;.&lt; // else if(pairs.length === 1 &amp;&amp; flush === false &amp;&amp; straight === false &amp;&amp; pairs.length === 1 ){ alert("You have a pair"); } alert(pairs); }; while(endgame === false){ if(phase === 1){ options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold")); }else if(phase === 2){ options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold")); }else if(phase === 3){ options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold")); }else if(phase === 4){ options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold")); } switch(options){ case 1: if(phase === 5){ handstrenght(); endgame = true; }else{ phase++; } break; case 2: endgame = true; break; default: endgame = true; break; } } &lt;/script&gt; </code></pre>
13,389,463
6
3
null
2012-11-14 23:49:02.027 UTC
6
2017-01-30 17:33:08.473 UTC
2012-11-18 05:45:06.123 UTC
null
23,897
null
1,825,277
null
1
22
javascript|arrays
65,019
<ul> <li>Keep a variable for the total count</li> <li>Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one</li> <li>After the loop, total count contains the number of times the number you were looking for is in the array</li> </ul> <p>Show your code and we can help you figure out where it went wrong</p> <p>Here's a simple implementation (since you don't have the code that didn't work)</p> <pre><code>var list = [2, 1, 4, 2, 1, 1, 4, 5]; function countInArray(array, what) { var count = 0; for (var i = 0; i &lt; array.length; i++) { if (array[i] === what) { count++; } } return count; } countInArray(list, 2); // returns 2 countInArray(list, 1); // returns 3 </code></pre> <p>countInArray could also have been implemented as</p> <pre><code>function countInArray(array, what) { return array.filter(item =&gt; item == what).length; } </code></pre> <p>More elegant, but maybe not as performant since it has to create a new array.</p>
51,979,553
Is it recommended to run systemd inside docker container?
<p>I am planning to use 'systemd' inside the container. Based on the articles I have read, it is preferable to limit only one process per container. </p> <p>But if I configure 'systemd' inside the container, I will end up running many processes. </p> <p>It would be great to understand the pros and cons of using systemd inside the container before I take any decision.</p>
51,985,145
3
4
null
2018-08-23 06:28:54.633 UTC
8
2019-02-26 07:48:19.233 UTC
2018-08-23 08:08:20.573 UTC
null
8,590,936
null
10,263,095
null
1
16
docker|systemd
19,425
<p>I'd advise you to avoid systemd in a container if at all possible.</p> <p><a href="https://www.freedesktop.org/wiki/Software/systemd/" rel="noreferrer">Systemd</a> mounts filesystems, controls several kernel parameters, has its own internal system for capturing process output, configures system swap space, configures huge pages and POSIX message queues, starts an inter-process message bus, starts per-terminal login prompts, and manages a swath of system services. Many of these are things Docker does for you; others are system-level controls that Docker by default prevents (for good reason).</p> <p>Usually you want a container to do <em>one</em> thing, which occasionally requires multiple coordinating processes, but you usually don't want it to do any of the things systemd does beyond provide the process manager. Since systemd changes so many host-level parameters you often need to run it as <code>--privileged</code> which breaks the Docker isolation, which is usually a bad idea.</p> <p>As you say in the question, running one "piece" per container is usually considered best. If you can't do this then a light-weight process manager like <a href="http://supervisord.org" rel="noreferrer">supervisord</a> that does the very minimum an init process is required to is a better match, both for the Docker and Unix philosophies.</p>
20,637,435
Xcode: What is a target and scheme in plain language?
<p>Yeah the title says it :-) What do they mean in plain English language? I really don't understand the explanation on Apple's website and I need to rename my target and I'm afraid that nothing works after that..</p>
20,637,892
6
2
null
2013-12-17 14:59:23.653 UTC
108
2021-06-28 15:13:20.23 UTC
2021-03-04 19:57:24.643 UTC
null
5,175,709
null
1,833,434
null
1
268
ios|xcode|xcode-scheme|xcode-target
75,252
<p>I've added in Workspace and Project too!</p> <ul> <li><strong>Workspace</strong> - Contains one or more <em>projects</em>. These projects usually relate to one another</li> <li><strong>Project</strong> - Contains code and resources, etc. (You'll be used to these!)</li> <li><strong>Target</strong> - Each project has one or more targets. <ul> <li>Each target defines a list of build settings for that project</li> <li>Each target also defines a list of classes, resources, custom scripts etc to include/ use when building.</li> <li>Targets are usually used for different distributions of the same project. <ul> <li>For example, my project has two targets, a "normal" build and an "office" build that has extra testing features and may contain several background music tracks and a button to change the track (as it currently does).</li> <li>You'll be used to adding classes and resources to your default target as you add them.</li> <li>You can pick and choose which classes / resources are added to which target. <ul> <li>In my example, I have a "DebugHandler" class that is added to my office build</li> </ul></li> <li>If you add tests, this also adds a new target. </li> </ul></li> </ul></li> <li><strong>Scheme</strong> - A scheme defines what happens when you press "Build", "Test", "Profile", etc. <ul> <li>Usually, each target has at least one scheme</li> <li>You can autocreate schemes for your targets by going to Scheme > Manage Schemes and pressing "Autocreate Schemes Now"</li> </ul></li> </ul>
29,413,942
C# anonymous object with properties from dictionary
<p>I'm trying to convert an dictionary to an anonymous type with one property for every Key.</p> <p>I tried google it but all I could find was how to convert a anonymous object to a dictionary. </p> <p>My dictionary looks something like this:</p> <pre><code>var dict = new Dictionary&lt;string, string&gt; { {"Id", "1"}, {"Title", "My title"}, {"Description", "Blah blah blah"}, }; </code></pre> <p>And i would like to return a anonymous object that looks like this.</p> <pre><code>var o = new { Id = "1", Title = "My title", Description = "Blah blah blah" }; </code></pre> <p>So I would like it to loop thru every keyValuePair in the dictionary and create a property in the object for every key.</p> <p>I don't know where to begin.</p> <p>Please help.</p>
29,414,014
6
4
null
2015-04-02 13:15:35.077 UTC
7
2022-02-18 07:56:20.717 UTC
2016-09-15 19:43:14.287 UTC
null
5,120,235
null
3,082,887
null
1
42
c#|object|dictionary
52,828
<p>You can't, basically. Anonymous types are created by the compiler, so they exist in your assembly with all the property names baked into them. (The property <em>types</em> aren't a problem in this case - as an implementation detail, the compiler creates a generic type and then creates an instance of that using appropriate type arguments.)</p> <p>You're asking for a type with properties which are determined at <em>execution</em> time - which just doesn't fit with how anonymous types work. You'd have to basically compile code using it at execution time - which would then be a pain as it would be in a different assembly, and anonymous types are internal...</p> <p>Perhaps you should use <a href="https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject"><code>ExpandoObject</code></a> instead? Then anything using <code>dynamic</code> will be able to access the properties as normal.</p>
16,089,304
JavaFX ImageView without any smoothing
<p>Is it possible to render a scaled image in an ImageView in JavaFX 2.2 without any smoothing applied? I'm rendering a 50x50 image into a 200x200 ImageView, with setSmooth(false), so each pixel in the source image should map to a 4x4 square on the screen.</p> <p>However, the resulting render still smooths the source pixel across all 16 destination pixels. Does anyone know of a way to do this without manually copying over each pixel into a new image?</p>
16,092,631
4
3
null
2013-04-18 17:17:06.98 UTC
8
2021-04-08 18:23:41.09 UTC
2016-11-03 09:03:23.033 UTC
null
2,991,525
null
710,342
null
1
20
javafx|javafx-2
14,387
<p>In JavaFX 2.2 <code>ImageView</code> is always going to do some smoothing regardless of the <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/ImageView.html#smoothProperty" rel="noreferrer">smooth</a> hint you provide to the <code>ImageView</code>. </p> <p>(Based on testing using Java 7u15 and Windows 7 with an ATI HD4600 graphics card).</p> <p>Perhaps it is a bug that <code>ImageView</code> will always smooth the <code>Image</code>, but the documentation doesn't really specify exactly what smoothing does or doesn't do, so it's hard to say what its real intent is. You may want to post a reference to this question to the <a href="http://mail.openjdk.java.net/mailman/listinfo/openjfx-dev" rel="noreferrer">openjfx-dev mailing list</a> or log an issue in the <a href="https://javafx-jira.kenai.com" rel="noreferrer">JavaFX issue tracker</a> to get a more expert opinion from a developer.</p> <hr> <p>I tried a few different methods for scaling the Image:</p> <ol> <li>Scale in the <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/Image.html#Image%28java.lang.String,%20double,%20double,%20boolean,%20boolean%29" rel="noreferrer">Image constructor</a>.</li> <li>Scale in <code>ImageView</code> with <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/ImageView.html#fitWidthProperty" rel="noreferrer">fitWidth</a>/<a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/ImageView.html#fitHeightProperty" rel="noreferrer">fitHeight</a>.</li> <li>Scale by using the <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#scaleXProperty%28%29" rel="noreferrer">scaleX</a>/<a href="http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#scaleYProperty%28%29" rel="noreferrer">scaleY</a> properties on an <code>ImageView</code>.</li> <li>Scale by sampling the <code>Image</code> with a <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/PixelReader.html" rel="noreferrer">PixelReader</a> and creating a new Image with a <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/image/PixelWriter.html" rel="noreferrer">PixelWriter</a>.</li> </ol> <p>I found that methods 1 &amp; 4 resulted in a sharp pixelated image as you wish for and 2 &amp; 3 resulted in a blurry aliased image.</p> <p><img src="https://i.stack.imgur.com/ifGkJ.png" alt="robot-sampling"></p> <p><a href="https://gist.github.com/jewelsea/5415891" rel="noreferrer">Sample code</a> to generate the above output.</p> <hr> <p><em>Update with ideas on implementing your own image filter</em></p> <p>A JavaFX Effect is not the same as the Filter used for the Image loading routines, though an Effect to filter an image could be created. In JavaFX 2.2 publicly documented API to support creation of custom effects, so creating of a custom effect may prove difficult.</p> <p>The <a href="http://hg.openjdk.java.net/openjfx/8/graphics/rt/rev/f0ec60f0a4b8" rel="noreferrer">native code for image support</a> was recently open sourced as part of the <a href="http://openjdk.java.net/projects/openjfx/" rel="noreferrer">openjfx project</a>, so you could look at that to see how the filtering is currently implemented. </p> <p>You may also want to file a <a href="https://javafx-jira.kenai.com" rel="noreferrer">feature request against the JavaFX runtime project</a> to "allow us to make our own 2D filters".</p>
16,331,887
Get product id and product type in magento?
<p>I am creating magento store. I am beginner in magento. I want to get product id and product input type in my phtml file is this possible? please guide me..</p> <p>I am trying to this way to get product type. but its not working for me</p> <pre><code>$product=Mage::getModel('catalog/product')-&gt;load($product_id); $productType=$product-&gt;getTypeID(); </code></pre> <p>Please guide me...</p>
16,332,019
8
0
null
2013-05-02 06:40:25.273 UTC
8
2017-07-12 16:10:46.797 UTC
null
user2564627
2,585,850
user2564627
2,585,850
null
1
22
php|magento|magento-1.7
127,160
<p>Try below code to get currently loaded product id:</p> <pre><code>$product_id = $this-&gt;getProduct()-&gt;getId(); </code></pre> <p>When you don’t have access to $this, you can use Magento registry:</p> <pre><code>$product_id = Mage::registry('current_product')-&gt;getId(); </code></pre> <p>Also for product type i think </p> <pre><code>$product = Mage::getModel('catalog/product')-&gt;load($product_id); $productType = $product-&gt;getTypeId(); </code></pre>
29,104,643
HttpClientError: The target server failed to respond
<p>I am trying to hit a server using HTTP client using <code>PoolingClientConnectionManager</code> setting max connections for individual hosts</p> <pre class="lang-java prettyprint-override"><code>//Code that initializes my connection manager and HTTP client HttpParams httpParam = httpclient.getParams(); HttpConnectionParams.setSoTimeout(httpParam, SOCKET_TIMEOUT); HttpConnectionParams.setConnectionTimeout(httpParam, CONN_TIMEOUT); httpclient.setParams(httpParam); //Run a thread which closes Expired connections new ConnectionManager(connManager).start(); //Code that executes my request HttpPost httpPost = new HttpPost(url); HttpEntity httpEntity = new StringEntity(request, &quot;UTF-8&quot;); httpPost.setEntity(httpEntity); Header acceptEncoding = new BasicHeader(&quot;Accept-Encoding&quot;, &quot;gzip,deflate&quot;); httpPost.setHeader(acceptEncoding); if(contenttype != null &amp;&amp; !contenttype.equals(&quot;&quot;)){ Header contentType = new BasicHeader(&quot;Content-Type&quot;, contenttype); httpPost.setHeader(contentType); } InputStream inputStream = null; LOG.info(dataSource + URL + url + REQUEST + request); HttpResponse response = httpclient.execute(httpPost); </code></pre> <p>That is we are using Connection pooling for http persistence .</p> <p>We are getting this error sporadically :</p> <pre><code>The target server failed to respond org.apache.http.NoHttpResponseException: The target server failed to respond at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62) at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254) at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289) at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252) at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:517) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906) </code></pre> <p>Does any one know how to resolve this?</p> <p>We are shutting down idle connections as well.</p> <p>Can some Please help.</p> <p><a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html" rel="noreferrer">http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html</a></p>
29,642,453
2
5
null
2015-03-17 16:32:37.687 UTC
7
2021-02-26 21:58:46.79 UTC
2021-02-26 21:58:46.79 UTC
null
185,123
null
3,481,360
null
1
21
java|apache|httpclient|connection-pooling
71,217
<p>Probably, it is a bug in the HttpClient.</p> <p>If you are using the HttpClient 4.4, please try to upgrade to 4.4.1.</p> <p>If you want for more information, please look at <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1610">this link</a>.</p> <p>If you can't upgrade, the following links might be helpful.</p> <p><a href="http://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/">http://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/</a></p> <p>Good luck!</p>
17,186,866
How to style HTML select/option tag?
<p>I would like to create a dropdown menu with html select thus I would like to style it as well. I would like to set a padding to the option tags so they wouldn't be so overcrowded, but I can't do so. (it doesn't work) any idea?</p> <pre><code>#categories { padding: 10px 10px 10px 10px; background-color: #826B78; font-size: 20px; color: white; margin: 10px 10px 10px 10px; border: none; outline: none; } #categories option { margin: 30px 30px 30px 30px; padding: 30px 30px 30px 30px; font-size: 20px; } </code></pre> <p>the categories id belongs to the select tag</p>
17,188,284
5
7
null
2013-06-19 08:51:05.913 UTC
1
2017-05-15 21:01:19.323 UTC
null
null
null
null
1,509,744
null
1
3
html|css|drop-down-menu|menu|styles
41,593
<p>It is difficult to style select menu with css. The Best way of doing it is with jquery u can style and have a better control over the code with jquery. Just use a custom jquery like <a href="http://gregfranko.com/jquery.selectBoxIt.js/" rel="nofollow noreferrer">http://gregfranko.com/jquery.selectBoxIt.js/</a></p> <p>I have just made an example of styling select with jquery, you can check the demo here</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Code to convert select to UL $('.select').each(function() { var $select = $(this).find('select'), $list = $('&lt;ul /&gt;'); $select.find('option').each(function() { $list.append('&lt;li&gt;' + $(this).text() + '&lt;/li&gt;'); }); //Remove the select after the values are taken $select.after($list).remove(); //Append Default text to show the selected $(this).append('&lt;span&gt;select&lt;/span&gt;') var firsttxt = $(this).find('li:first-child').text(); $(this).find('span').text(firsttxt) // On click show the UL $(this).on('click', 'span', function(e) { e.stopPropagation(); $(this).parent().find('ul').show(); }); // On select of list select the item $(this).on('click', 'li', function() { var gettext = $(this).text(); $(this).parents('.select').find('span').text(gettext); $(this).parent().fadeOut(); }); }) // On click out hide the UL $(document).on('click', function() { $('.select ul').fadeOut(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: 'arial', san-serif; } .select { width: 200px; height: 30px; border: 1px solid #ddd; line-height: 30px; position: relative; margin-bottom: 40px; } .select span { display: block; color: #333; font-size: 12px; padding: 0 10px; } .select ul { display: none; background: #fff; border: 1px solid #ddd; min-width: 300px; position: absolute; top: 100%; left: 0; list-style-type: none; margin: 0; padding: 0; z-index: 10; } .select ul &gt; li { font-size: 12px; } .select ul &gt; li { color: #333; display: block; padding: 2px 8px; text-decoration: none; line-height: 24px; } .select ul &gt; li:hover { background: #e4f4fa; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;label&gt;First Select&lt;/label&gt; &lt;div class="select"&gt; &lt;select&gt; &lt;option&gt;Item&lt;/option&gt; &lt;option&gt;Item 2&lt;/option&gt; &lt;option&gt;Item 3&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;label&gt;Second Select&lt;/label&gt; &lt;div class="select"&gt; &lt;select&gt; &lt;option&gt;this 1&lt;/option&gt; &lt;option&gt;this 2&lt;/option&gt; &lt;option&gt;this 3&lt;/option&gt; &lt;/select&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
17,623,445
Set printing area In Excel 2013 using macro
<p>In Excel 2013, having sheet named <em>"Tags"</em>, I am trying to <strong>set a printing area</strong> from <code>A2</code> till end of page, ending with column <code>L</code>.</p> <pre><code>Worksheets("Tags").PageSetup.PrintArea = Worksheets("Tags").Range( _ Cells(2, 1), Cells(Worksheets("Tags").Range("A65536").End(xlUp).Row, 12)) </code></pre> <p>My code compiles okay, but it does not seems to work - no printing area has been set.</p> <p>What should be a correct macro to set printing area?</p>
17,623,610
2
0
null
2013-07-12 20:23:51 UTC
3
2015-02-25 21:58:23.207 UTC
2018-07-09 18:41:45.953 UTC
null
-1
null
1,215,106
null
1
3
excel|vba
71,131
<p>It's easier to see what is happening if you declare a few variables and decompose your statement.</p> <p>Try this:</p> <pre><code>Sub SetPrintArea() Dim ws As Worksheet Dim lastRow As Long Set ws = ThisWorkbook.Sheets("Tags") ' find the last row with formatting, to be included in print range lastRow = ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row ws.PageSetup.PrintArea = ws.Range("A2:L" &amp; lastRow).Address End Sub </code></pre> <p>Alternatively, if you want to find the lastRow with data, you can find the lastrow like this:</p> <pre><code>lastRow = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row </code></pre> <p>Note that the 65536 value you're using as the starting point to find the last row is obsolete (although it will frequently still work) as of Excel 2007, which has over a million rows per sheet.</p> <p>A few things to note about your approach:</p> <ol> <li><code>Cells(2,1)</code> is A2. The syntax is <code>Cells([row], [column])</code></li> <li>You want the last populated row in column L, but are looking in column A instead. <code>Range("A65536").End(xlUp).Row</code></li> </ol> <p>This results in a print area (once you've added the .Address to your range) of A1:L2. Why A1? Because the column A is empty, and the lastrow is therefore row 1. You have set the range to be A2:L1, which becomes A1:L2.</p>
17,574,916
How to convert array of byte to String in Java?
<p>How can I convert a array of <code>bytes</code> to <code>String</code> without conversion?.</p> <p>I tried:</p> <pre><code> String doc=new String( bytes); </code></pre> <p>But the doc file is not the same than the bytes (the bytes are <strong>binary information</strong>). For example:</p> <pre><code> String doc=new String( bytes); byte[] bytes2=doc.getBytes(); </code></pre> <p><code>bytes</code> and <code>bytes2</code> are different.</p> <p>PS: UTF-8 Does not work because it convert some bytes in different values. I tested and it does not work.</p> <p>PS2: And no, I don't want <code>BASE64</code>.</p>
17,575,021
3
4
null
2013-07-10 15:34:58.237 UTC
5
2017-07-29 03:47:11.95 UTC
2017-07-29 03:47:11.95 UTC
null
4,972,721
null
202,705
null
1
18
java|arrays|string
93,016
<p>You need to specify the encoding you want e.g. for UTF-8</p> <pre><code>String doc = .... byte[] bytes = doc.getBytes("UTF-8"); String doc2 = new String(bytes, "UTF-8"); </code></pre> <p><code>doc</code> and <code>doc2</code> will be the same.</p> <p>To decode a <code>byte[]</code> you need to know what encoding was used to be sure it will decode correctly.</p>
24,623,559
NSStatusItem change image for dark tint
<p>With OSX 10.10 beta 3, Apple released their dark tint option. Unfortunately, it also means that pretty much all status bar icons (with the exception of Apple's and Path Finder's that I've seen), including mine, remain dark on a dark background. How can I provide an alternate image for when dark tint is applied?</p> <p>I don't see an API change on <code>NSStatusBar</code> or <code>NSStatusItem</code> that shows me a change, I'm assuming it's a notification or something reactive to easily make the change as the user alters the tint.</p> <p>Current code to draw the image is encased within an <code>NSView</code>:</p> <pre><code>- (void)drawRect:(NSRect)dirtyRect { // set view background color if (self.isActive) { [[NSColor selectedMenuItemColor] setFill]; } else { [[NSColor clearColor] setFill]; } NSRectFill(dirtyRect); // set image NSImage *image = (self.isActive ? self.alternateImage : self.image); _imageView.image = image; } </code></pre>
24,644,754
6
7
null
2014-07-08 04:09:51.7 UTC
21
2018-10-22 03:59:38.243 UTC
2017-09-13 17:13:49.75 UTC
null
1,000,551
null
1,221,798
null
1
26
objective-c|macos|osx-yosemite|nsstatusitem|nsstatusbar
11,830
<p>TL;DR: You don't have to do anything special in Dark Theme. Give NSStatusItem (or NSStatusBarButton) a template image and it will style it correctly in any menubar context.</p> <hr> <p>The reason why some apps' status items (such as PathFinder's) already work in Dark Theme is because they're not setting their own custom view on the StatusItem, but only setting a template image on the StatusItem.</p> <p>Something like:</p> <pre><code>_statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength]; NSImage *image = [NSImage imageNamed:@"statusItemIcon"]; [image setTemplate:YES]; [_statusItem setImage:image]; </code></pre> <p>This works exactly as you'd expect in Mavericks and earlier, as well as Yosemite and any future releases <em>because it allows AppKit</em> to do all of the styling of the image depending on the status item state.</p> <h3>Mavericks</h3> <p>In Mavericks (and earlier) there were only 2 unique styles of the items. Unpressed and Pressed. These two styles pretty much looked purely black and purely white, respectively. (Actually "purely black" isn't entirely correct -- there was a small effect that made them look slightly inset).</p> <p>Because there were only two possible state, status bar apps could set their own view and easily get the same appearance by just drawing black or white depending on their highlighted state. (But again note that it wasn't purely black, so apps either had to build the effect in the image or be satisfied with a hardly-noticeable out of place icon).</p> <h3>Yosemite</h3> <p>In Yosemite there are at least 32 unique styling of items. Unpressed in Dark Theme is only one of those. There is no practical (or unpractical) way for an app to be able to do their own styling of items and have it look correct in all contexts. </p> <p>Here are examples of six of those possible stylings:</p> <p><img src="https://i.stack.imgur.com/9igcm.png" alt="Six possible status item stylings"></p> <p>Status items on an inactive menubar now have a specific styling, as opposed to a simple opacity change as in the past. Disabled appearance is one other possible variation; there are also other additional <em>dimensions</em> to this matrix of possibilities. </p> <h3>API</h3> <p>Arbitrary views set as NSStatusItem's <code>view</code> property have no way to capture all of these variations, hence it (and other related API) is deprecated in 10.10.</p> <p>However, seed 3 introduces new API on NSStatusItem:</p> <pre><code>@property (readonly, strong) NSStatusBarButton *button NS_AVAILABLE_MAC(10_10); </code></pre> <p>This piece of API has a few purposes:</p> <ol> <li>An app can now get the screen position (or show a popover from) a status item without setting its own custom view. </li> <li>Removes the need for API like <code>image</code>, <code>title</code>, <code>sendActionOn:</code> on NSStatusItem.</li> <li>Provides a class for new API: i.e. <code>looksDisabled</code>. This allows apps to get the standard disabled/off styling (like Bluetooth/Time Machine when off) without requiring a custom image.</li> </ol> <p>If there's something that can't be done with the current (non- custom view) API, please file an enhancement request for it. StatusItems should provide behavior or appearances in a way that it standard across all status items.</p> <hr> <p>More discussion is at <a href="https://devforums.apple.com/thread/234839">https://devforums.apple.com/thread/234839</a>, although I've summarized most everything here.</p>
22,275,079
pySerial write() won't take my string
<p>Using Python 3.3 and pySerial for serial communications.</p> <p>I'm trying to write a command to my COM PORT but the write method won't take my string. (Most of the code is from here <a href="https://stackoverflow.com/questions/676172/full-examples-of-using-pyserial-package">Full examples of using pySerial package</a></p> <p>What's going on?</p> <pre><code>import time import serial ser = serial.Serial( port='\\\\.\\COM4', baudrate=115200, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) if ser.isOpen(): ser.close() ser.open() ser.isOpen() ser.write("%01#RDD0010000107**\r") out = '' # let's wait one second before reading output (let's give device time to answer) time.sleep(1) while ser.inWaiting() &gt; 0: out += ser.read(40) if out != '': print("&gt;&gt;" + out) ser.close() </code></pre> <p>Error is at ser.write("%01#RDD0010000107**\r") where it gets Traceback is like this data = to_bytes(data) b.append(item) TypeError: an integer is required.</p>
22,315,432
3
3
null
2014-03-08 21:05:29.23 UTC
2
2020-11-23 13:09:21.35 UTC
2017-05-23 12:32:26.74 UTC
null
-1
null
2,877,001
null
1
28
python|pyserial
154,963
<p>It turns out that the string needed to be turned into a bytearray and to do this I editted the code to </p> <pre><code>ser.write("%01#RDD0010000107**\r".encode()) </code></pre> <p>This solved the problem</p>
26,794,198
Spring MVC @Path variable with { } braces
<p>Am developing an application using spring boot. In REST controller i prefer to use path variable(<code>@PathVariabale</code> annotation). My code fetching the path variable but it contatins <strong>{ }</strong> braces as it is in the url. Please any one suggest me to solve this issue</p> <pre><code>@RequestMapping(value = "/user/item/{loginName}", method = RequestMethod.GET) public void getSourceDetails(@PathVariable String loginName) { try { System.out.println(loginName); // it print like this {john} } catch (Exception e) { LOG.error(e); } } </code></pre> <p>URL</p> <pre><code>http://localhost:8080/user/item/{john} </code></pre> <p>Out put in controller</p> <p>{john} </p>
26,794,709
1
2
null
2014-11-07 04:42:59.573 UTC
2
2016-09-15 08:26:06.35 UTC
2016-09-15 08:26:06.35 UTC
null
1,479,414
null
2,549,636
null
1
24
java|spring|spring-mvc|spring-boot
68,222
<p>Use <code>http://localhost:8080/user/item/john</code> to submit your request instead. </p> <p>You give Spring a value of "{john}" to the path variable <code>loginName</code>, so Spring get it with the "{}"</p> <p><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html" rel="noreferrer">Web MVC framework</a> states that </p> <blockquote> <h2>URI Template Patterns</h2> <p>URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.</p> <p>A URI Template is a <strong>URI-like string</strong>, containing one or more variable names. <strong>When you substitute values for these variables, the template becomes a URI</strong>. The proposed RFC for URI Templates defines how a URI is parameterized. For example, the URI Template <a href="http://www.example.com/users/" rel="noreferrer">http://www.example.com/users/</a>{userId} <strong>contains the variable userId</strong>. <strong>Assigning the value fred to the variable yields <a href="http://www.example.com/users/fred" rel="noreferrer">http://www.example.com/users/fred</a>.</strong></p> <p>In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable:</p> </blockquote> <pre><code>@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable String ownerId, Model model) { Owner owner = ownerService.findOwner(ownerId); model.addAttribute("owner", owner); return "displayOwner"; } </code></pre> <blockquote> <p>The URI Template " /owners/{ownerId}" specifies the variable name ownerId. When the controller handles this request, the value of ownerId is set to the value found in the appropriate part of the URI. For example, when a request comes in for /owners/fred, the value of ownerId is fred.</p> </blockquote>
17,485,297
How to instantiate an inner class with reflection in Java?
<p>I try to instantiate the inner class defined in the following Java code:</p> <pre><code> public class Mother { public class Child { public void doStuff() { // ... } } } </code></pre> <p>When I try to get an instance of Child like this</p> <pre><code> Class&lt;?&gt; clazz= Class.forName("com.mycompany.Mother$Child"); Child c = clazz.newInstance(); </code></pre> <p>I get this exception:</p> <pre><code> java.lang.InstantiationException: com.mycompany.Mother$Child at java.lang.Class.newInstance0(Class.java:340) at java.lang.Class.newInstance(Class.java:308) ... </code></pre> <p>What am I missing ?</p>
17,485,341
2
3
null
2013-07-05 09:15:56.25 UTC
19
2019-01-21 23:40:57.2 UTC
2019-01-21 23:40:57.2 UTC
null
363,573
null
363,573
null
1
68
java|reflection|instantiationexception
39,478
<p>There's an extra "hidden" parameter, which is the instance of the enclosing class. You'll need to get at the constructor using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredConstructor%28java.lang.Class...%29" rel="noreferrer"><code>Class.getDeclaredConstructor</code></a> and then supply an instance of the enclosing class as an argument. For example:</p> <pre><code>// All exception handling omitted! Class&lt;?&gt; enclosingClass = Class.forName("com.mycompany.Mother"); Object enclosingInstance = enclosingClass.newInstance(); Class&lt;?&gt; innerClass = Class.forName("com.mycompany.Mother$Child"); Constructor&lt;?&gt; ctor = innerClass.getDeclaredConstructor(enclosingClass); Object innerInstance = ctor.newInstance(enclosingInstance); </code></pre> <p>EDIT: Alternatively, if the nested class doesn't actually need to refer to an enclosing instance, make it a nested <em>static</em> class instead:</p> <pre><code>public class Mother { public static class Child { public void doStuff() { // ... } } } </code></pre>
17,225,229
Using multiple conditions (AND) in SASS IF statement
<p>Using SASS, I would like to have multiple condition in IF statement </p> <p><strong>What I use right now :</strong></p> <pre><code>@function color-x ($alpha) { @if $accent == red {@return red($alpha)} @else if $accent == green {@return green($alpha)} @else if $accent == blue {@return blue($alpha)} } </code></pre> <p><strong>My naive (failed) attempt to use multiple conditions :</strong></p> <pre><code>@function color-x ($alpha) { @if $accent == red &amp;&amp; theme == light {@return red($alpha)} @else if $accent == green &amp;&amp; theme == light {@return green($alpha)} @else if $accent == blue &amp;&amp; theme == light {@return blue($alpha)} } </code></pre> <p>Is it possible to have multiple conditions?</p>
17,226,136
2
0
null
2013-06-20 23:00:14.85 UTC
19
2015-06-12 16:51:14.797 UTC
2013-06-21 01:03:13.853 UTC
null
344,543
null
769,551
null
1
74
if-statement|sass
62,122
<p>From the Sass language reference documentation:</p> <blockquote> <p><strong>Boolean Operations</strong></p> <p>SassScript supports <code>and</code>, <code>or</code>, and <code>not</code> operators for boolean values.</p> </blockquote> <p><a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#boolean_operations" rel="noreferrer">(link)</a></p> <p>So an if statement expression with a compound condition would look like this:</p> <pre><code>@if $var1 == value1 and $var2 == value2 { // ... } </code></pre> <p>Further, parentheses can be used to affect the order of operations in a more complicated expression:</p> <pre><code>@if ($var1 == value1 and not ($var2 == value2)) or ($var3 == value3) { // ... } </code></pre>
17,575,790
Environment detection: node.js or browser
<p>I'm developping a JS-app that needs to work both on the client side and the server side (in Javascript on a browser and in Node.js), and I would like to be able to reuse the parts of the code that are used for both sides.</p> <p>I have found out that <code>window</code> was a variable only accessible on Browsers, and <code>global</code> in node, so I can detect in which environment the code is executing (assuming that no script declares the <code>window</code> variable)</p> <p>They are two problems.</p> <ol> <li><p>How should I detect in which browser the code is running. For example, is this code OK. (This code is inline, meaning that it is surrounded by some global code, reused for both environments)</p> <pre><code>if window? totalPath= "../examples/#{path}" else totalPath= "../../examples/#{path}" </code></pre></li> <li><p>How can I use global variables for both environments ? Now, I'm doing the following, but this really doesn't feel right.</p> <pre><code>if window? window.DocUtils = {} window.docX = [] window.docXData= [] else global.DocUtils= {} global.docX = [] global.docXData = [] </code></pre></li> </ol>
31,090,240
11
1
null
2013-07-10 16:15:57.99 UTC
25
2022-05-15 13:42:04.847 UTC
2013-07-10 16:23:26.943 UTC
null
1,993,501
null
1,993,501
null
1
74
javascript|node.js|coffeescript|browser-detection
39,156
<p><em>NOTE: This question had two parts, but because the title was &quot;Environment detection: node.js or browser&quot; - I will get to this part first, because I guess many people are coming here to look for an answer to that. A separate question might be in order.</em></p> <p>In JavaScript variables can be redefined by the inner scopes, thus assuming that environment has not created variables named as process, global or window could easily fail, for example if one is using node.js jsdom module, the <a href="https://github.com/tmpvar/jsdom" rel="noreferrer">API usage example has</a></p> <pre><code>var window = doc.defaultView; </code></pre> <p>After which detecting the environment based on the existence of <code>window</code> variable would systematically fail by any module running under that scope. With the same logic any browser based code could easily overwrite <code>global</code> or <code>process</code>, because they are not reserved variables in that environment.</p> <p>Fortunately there is a way of requiring the global scope and testing what it is - if you create a new function using a <code>new Function()</code> constructor, the execution scope of <code>this</code> is bound to the global scope and you can compare the global scope directly to the expected value. *)</p> <p>So to create a function check if the global scope is &quot;window&quot; would be</p> <pre><code>var isBrowser=new Function(&quot;try {return this===window;}catch(e){ return false;}&quot;); // tests if global scope is bound to window if(isBrowser()) console.log(&quot;running under browser&quot;); </code></pre> <p>And function to test if global scope is bound to &quot;global&quot; would be</p> <pre><code>var isNode=new Function(&quot;try {return this===global;}catch(e){return false;}&quot;); // tests if global scope is bound to &quot;global&quot; if(isNode()) console.log(&quot;running under node.js&quot;); </code></pre> <p>the try... catch -part will makes sure that if variable is not defined, <code>false</code> is returned.</p> <p>The <code>isNode()</code>could also compare <code>this.process.title===&quot;node&quot;</code> or some other global scope variable found inside node.js if you will, but comparing to the global should be enough in practice.</p> <p><a href="http://jsfiddle.net/p6yedbqk/" rel="noreferrer">http://jsfiddle.net/p6yedbqk/</a></p> <p><em><strong>NOTE</strong>: detecting the running environment is not recommended. However, it can be useful in a specific environment, like development and testing environment which has some known characteristics for the global scope.</em></p> <p><strong>Now - the second part of the answer.</strong> after the environment detection has been done, you can select which environment based strategy you want to use (if any) to bind your variable which are &quot;global&quot; to your application.</p> <p>The recommended strategy here, in my opinion, would be to use a singleton pattern to bind your settings inside a class. There is a good list of alternatives already in SO</p> <p><a href="https://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript">Simplest/cleanest way to implement a singleton in JavaScript</a></p> <p>So, it may turn out if you do not need a &quot;global&quot; variable, and you do not need the environment detection at all, just use the singleton pattern to defined a module, which will store the values for you. OK, one can argue that the module itself is a global variable, which in JavaScript it actually is, but at least in theory it looks a bit cleaner way of doing it.</p> <p>*) <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function</a></p> <blockquote> <p>Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called.</p> </blockquote>
30,324,532
How to find text in a string using google script?
<p>I tried indexOf(), findText() and other few methods for finding a string pattern in a text in google app script. None of the above method works.</p> <pre><code>var str="task is completed"; </code></pre> <p>I'm getting this string from google spreadsheet.</p> <p>I just want to find whether the above string contains a string "task" .</p>
30,324,576
2
2
null
2015-05-19 11:36:36.307 UTC
3
2022-06-30 18:11:40.47 UTC
2015-05-19 11:38:03.66 UTC
null
4,911,834
null
4,911,834
null
1
7
javascript|google-apps-script|google-sheets
48,570
<p>You need to check if the <code>str</code> is present:</p> <pre><code>if (str) { if (str.indexOf('task') &gt; -1) { // Present } } </code></pre> <p>Alternatively, you can use <code>test</code> and <code>regex</code>:</p> <pre><code>/task/.test("task is completed"); /task/.test(str); </code></pre> <ol> <li><code>/task/</code>: Regex to match the 'task'</li> <li><code>test</code>: Test the string against regex and return boolean</li> </ol>
26,003,086
Launching into portrait-orientation from an iPhone 6 Plus home screen in landscape orientation results in wrong orientation
<p>The actual title for this question is longer than I can possibly fit:</p> <p>Launching an app whose root view controller only supports portrait-orientation but which otherwise supports landscape orientations on an iPhone 6 Plus while the home screen is in a landscape orientation results in a limbo state where the app's window is in a landscape orientation but the device is in a portrait orientation.</p> <p>In short, it looks like this:</p> <p><img src="https://i.stack.imgur.com/sQ1o7.jpg" width="160"></p> <p>When it is supposed to look like this:</p> <p><img src="https://i.stack.imgur.com/msCDu.jpg" width="160"></p> <p><strong>Steps to Reproduce:</strong></p> <ol> <li><p>iPhone 6 Plus running iOS 8.0.</p></li> <li><p>An app whose plist supports all-but-portrait-upside-down orientations.</p></li> <li><p>The root view controller of the app is a UITabBarController.</p></li> <li><p>Everything, the tab bar controller and all its descendent child view controllers return <code>UIInterfaceOrientationMaskPortrait</code> from <code>supportedInterfaceOrientations</code>.</p></li> <li><p>Start at iOS home screen.</p></li> <li><p>Rotate to landscape orientation (requires iPhone 6 Plus).</p></li> <li><p>Cold-launch the app.</p></li> <li><p>Result: broken interface orientations.</p></li> </ol> <p>I can't think of any other way to enforce a portrait orientation <em>except</em> to disable landscape altogether, which I can't do: our web browser modal view controllers need landscape.</p> <p>I even tried subclassing UITabBarController and overriding supportedInterfaceOrientations to return the portrait-only mask, but this (even with all the other steps above) did not fix the issue.</p> <hr> <p><a href="https://www.dropbox.com/sh/m4rfosexlwkv3h9/AAD7QsiCqG7UTyhF-TjELra6a?dl=0">Here's a link to a sample project showing the bug.</a></p> <hr>
26,003,087
13
3
null
2014-09-23 19:22:15.683 UTC
25
2018-05-31 09:22:07.817 UTC
2014-09-23 21:41:47.78 UTC
null
1,078,579
null
1,078,579
null
1
58
ios|iphone|ios8|uiinterfaceorientation
26,540
<p>This appears to be a bug in iOS 8 when using a UITabBarController as a root view controller. A workaround is to use a mostly vanilla UIViewController as the root view controller. This vanilla view controller will serve as the parent view controller of your tab bar controller:</p> <pre><code>///------------------------ /// Portrait-Only Container ///------------------------ @interface PortraitOnlyContainerViewController : UIViewController @end @implementation PortraitOnlyContainerViewController - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } @end // Elsewhere, in app did finish launching ... PortraitOnlyContainerViewController *container = nil; container = [[PortraitOnlyContainerViewController alloc] initWithNibName:nil bundle:nil]; [container addChildViewController:self.tabBarController]; self.tabBarController.view.frame = container.view.bounds; [container.view addSubview:self.tabBarController.view]; [self.tabBarController didMoveToParentViewController:container]; [self.window setRootViewController:container]; </code></pre>
5,411,026
List of CSS vendor prefixes?
<p>Besides the following list, are there other CSS vendor prefixes that are important for <em>web development</em>? Are my definitions correct? Should I be more specific about mobile browsers (mobile Webkit, e.g.)</p> <ul> <li><code>-khtml-</code> (Konqueror, <em>really</em> old Safari)</li> <li><code>-moz-</code> (Firefox)</li> <li><code>-o-</code> (Opera)</li> <li><code>-ms-</code> (Internet Explorer)</li> <li><code>-webkit-</code> (Safari, Chrome)</li> </ul> <p>Does <a href="http://reference.sitepoint.com/css/vendorspecific" rel="noreferrer">this list</a> (which also contains <code>mso-</code>, <code>-wap-</code>, and <code>-atsc-</code>) add anything of value?</p>
5,411,098
3
0
null
2011-03-23 20:11:17.38 UTC
40
2021-10-29 08:20:25.33 UTC
2016-09-30 18:12:14.827 UTC
null
1,696,030
null
177,633
null
1
69
css|vendor-prefix
51,912
<p>These are the ones I'm aware of:</p> <ul> <li><code>-ms-</code> Microsoft</li> <li><code>mso-</code> Microsoft Office</li> <li><code>-moz-</code> Mozilla Foundation (Gecko-based browsers)</li> <li><code>-o-</code>, <code>-xv-</code> Opera Software</li> <li><code>-atsc-</code> Advanced Television Standards Committee</li> <li><code>-wap-</code> The WAP Forum</li> <li><code>-webkit-</code> Safari, Chrome (and other WebKit-based browsers)</li> <li><code>-khtml-</code>, <code>-konq-</code> Konqueror browser</li> <li><code>-apple-</code> Webkit supports properties using the -apple- prefixes as well</li> <li><code>prince-</code> YesLogic</li> <li><code>-ah-</code> Antenna House</li> <li><code>-hp-</code> Hewlett Packard</li> <li><code>-ro-</code> Real Objects</li> <li><code>-rim-</code> Research In Motion</li> <li><code>-tc-</code> Tall Components</li> </ul> <p>These are officially listed in the <a href="http://www.w3.org/TR/CSS21/syndata.html#vendor-keyword-history" rel="noreferrer">CSS 2.1 Specification, informative section 4.1.2.2</a>.</p>
15,069,764
Autocomplete Not Showing Results That Are Returned
<p>I cannot get the results of a jquery autocomplete to show, although the php code returns json results. The jquery code is as follows:</p> <pre><code>$("#newName").autocomplete({ source: function(request, response) { $.ajax({ url: root + "/assets/php/autocomplete.php", dataType: "json", data: { term : request.term, field : "name" }, success: function(data) { response(data); } }); }); </code></pre> <p>The php code is:</p> <pre><code>while ($row = $result-&gt;fetch(PDO::FETCH_ASSOC)) { $row_array['value'] = $row[$field]; array_push($return_arr,$row_array); } echo json_encode($return_arr); </code></pre> <p>When checking the results in Firebug, I get a response such as:</p> <p>[{"value":"jdoe"}]</p> <p>However, I never see a list of suggestions showing in the html page. Any suggestions on what the problem is.</p> <p>Thanks, AB</p>
15,072,283
8
0
null
2013-02-25 14:53:06.717 UTC
null
2022-05-23 15:07:08.093 UTC
null
null
null
null
1,267,341
null
1
15
jquery|autocomplete|jquery-ui-autocomplete
44,280
<p>I fixed the problem by adding to my master css file a z-index style for the autocomplete. Everything now works properly.</p> <pre><code>.ui-autocomplete { z-index: 100; } </code></pre>
15,020,734
Using NTLM authentication in Java applications
<p>I want to use Windows NTLM authentication in my Java application to authenticate intranet users transparently. The users should not notice any authentication if using their browsers (single sign-on).</p> <p>I've found a few libs with NTLM support, but don't know which one to use:</p> <ul> <li><a href="http://spnego.sourceforge.net/">http://spnego.sourceforge.net/</a></li> <li><a href="http://sourceforge.net/projects/ntlmv2auth/">http://sourceforge.net/projects/ntlmv2auth/</a></li> <li><a href="http://jcifs.samba.org/">http://jcifs.samba.org/</a></li> <li><a href="http://www.ioplex.com/jespa.html">http://www.ioplex.com/jespa.html</a></li> <li><a href="http://www.luigidragone.com/software/ntlm-authentication-in-java/">http://www.luigidragone.com/software/ntlm-authentication-in-java/</a></li> </ul> <p>Any suggestions where to start?</p>
15,028,292
5
1
null
2013-02-22 09:25:37.987 UTC
9
2021-04-20 16:07:17.103 UTC
null
null
null
null
238,134
null
1
17
java|windows|security|authentication|ntlm
60,999
<p>Out of the above list, only ntlmv2-auth and Jespa support NTLMv2. Jespa is workable but commercial. ntlmv2-auth I haven't tried but it's based on the code from Liferay, which I've seen working before.</p> <p>'ntlm-authentication-in-java' is only NTLMv1, which is old, insecure, and works in a dwindling number of environments as people upgrade to newer Windows versions. JCIFS used to have an NTLMv1 HTTP auth filter, but it was removed in later versions, as the way it was implemented amounts to a man-in-the-middle attack on the insecure protocol. (The same appears to be true of 'ntlm-authentication-in-java'.)</p> <p>The 'spnego' project is Kerberos not NTLM. If you want to replicate full IWA as IIS does it, you'd need to support both NTLMv2 and Kerberos ('NTLM' auth, 'Negotiate' auth, NTLMSSP-in-SPNego auth and NTLM-masquerading-as-Negotiate auth).</p>
15,344,955
Hudson/Jenkins Git build all branches
<p>We have a lot of developers creating feature branches that I would like to build. Nightly we run a code quality tool that needs to run on every branch. I also would not like a static configuration because the number of branches changes every few weeks.</p>
15,355,489
4
0
null
2013-03-11 17:35:44.53 UTC
11
2021-03-17 12:43:39.243 UTC
null
null
null
null
673,289
null
1
38
git|jenkins|hudson
27,991
<p>In Git configuration there is a field 'Branch Specifier (blank for default): ' if you put there ** it will build all branches from all remotes.</p> <p>having that you can use an environment variable ${GIT_BRANCH} e.g. to set a title for the build using <a href="https://wiki.jenkins-ci.org/display/JENKINS/Build+Name+Setter+Plugin">https://wiki.jenkins-ci.org/display/JENKINS/Build+Name+Setter+Plugin</a> or for other purposes</p>
14,970,412
Initialize Array of Objects using NSArray
<p>I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age.</p> <pre><code>#import "Person.h" @implementation Person @synthesize personName, age; -(id)init { self = [super init]; if(self) { personName = [self randomName]; age = [self randomAge]; } return self; } -(NSString *) randomName { NSString* name; NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut", @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great", @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers", @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair", nil]; NSUInteger randomIndex = arc4random() % [nameArr count]; name = [nameArr objectAtIndex: randomIndex]; return name; } -(NSInteger *) randomAge { //lowerBound + arc4random() % (upperBound - lowerBound); NSInteger* num = (NSInteger*)(1 + arc4random() % (99 - 1)); return num; } @end </code></pre> <p>Now I want to make an array of Persons so I can throw a bunch into the picker, pick one Person and show their age. First though I need to make an array of Persons. How do I make an array of objects, initialize and allocate them?</p>
14,970,464
5
0
null
2013-02-20 00:48:26.917 UTC
4
2019-05-28 07:36:36.583 UTC
2015-07-02 13:37:55.423 UTC
null
800,452
null
800,452
null
1
42
ios|objective-c|arrays|nsarray
166,737
<pre><code>NSMutableArray *persons = [NSMutableArray array]; for (int i = 0; i &lt; myPersonsCount; i++) { [persons addObject:[[Person alloc] init]]; } NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array </code></pre> <p>also you can reach this without using NSMutableArray:</p> <pre><code>NSArray *persons = [NSArray array]; for (int i = 0; i &lt; myPersonsCount; i++) { persons = [persons arrayByAddingObject:[[Person alloc] init]]; } </code></pre> <p>One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array! </p> <pre><code>[persons addObject:[[[Person alloc] init] autorelease]; </code></pre>
14,948,441
Vim Can't Save File (E212)
<p>Sometimes when I create a file using <code>vim some/path/newfile</code>, vim lets me edit it, only to complain when I attempt to save my changes.</p> <pre><code>E212 Can't open file for writing. </code></pre> <p>This appears to happen only when the new file is located in a system directory.</p> <p><code>:w!</code> does not override this error.</p> <p>How can I write the current buffer, without having to save it to a temporary location, exit, then rename it using sudo?</p>
14,948,510
11
1
null
2013-02-19 01:42:37.187 UTC
25
2022-03-26 11:07:30.253 UTC
null
null
null
null
2,085,347
null
1
64
macos|vim
128,274
<p>This will ask you for the root password, then save your changes as you requested:</p> <pre><code>:w !sudo tee % </code></pre> <p>Then type (L)oad at the prompt, to re-load the file after it is saved.</p>
28,037,539
Prevent duplicates across multiple executions of copying records back into source table while changing one column
<p>I want to select <code>CustomerID</code>, <code>OrderTypeID</code>, and <code>LoanNumber</code> from <code>tblOrder</code> and insert it with a new <code>OrderTypeID</code> but same <code>CustomerID</code> and <code>LoanNumber</code>. My query does that but it duplicates the values, every time the query is executed it duplicates the rows.</p> <pre><code>insert into tblOrder (CustomerID, OrderTypeID, LoanNumber) Select o.CustomerID,3, o.LoanNumber from tblOrder as o where o.OrderTypeID = 1; </code></pre> <p>this is what the query does:</p> <p>OrderID 9 - 12 are duplicates or OrderID 5 - 8. The query was executed 2 times hence the records got duplicated.</p>
28,038,088
6
3
null
2015-01-20 03:58:43.547 UTC
10
2022-01-11 22:29:40.273 UTC
2022-01-11 22:29:40.273 UTC
null
577,765
null
4,466,209
null
1
15
sql-server|tsql|sql-server-2008|duplicates
71,279
<p>The first, and most important, issue here is <em>not</em> that your query inserts duplicates; it is that your table <em>allows</em> it to happen in the first place. Hence, you first need to create a UNIQUE INDEX on those 3 fields to disallow duplicates.</p> <p>The second issue is how to handle the situation of when an operation attempts to insert a duplicate. You have two main choices:</p> <ol> <li><p>You can check for the record's existence first and skip the INSERT if it is found, or</p></li> <li><p>You can set the UNIQUE INDEX to "ignore" duplicates in which case you don't need to check first as the operation will silently fail, with just a warning that the duplicate was not inserted.</p></li> </ol> <hr> <p>If you pick <strong>Option #1</strong> (check first), then:</p> <pre class="lang-sql prettyprint-override"><code>CREATE UNIQUE NONCLUSTERED INDEX [UIX_tblOrder_CustomerID_OrderTypeID_LoanNumber] ON [tblOrder] ( [CustomerID] ASC, [OrderTypeID] ASC, [LoanNumber] ASC ); </code></pre> <p>And then:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO tblOrder (CustomerID, OrderTypeID, LoanNumber) SELECT o.CustomerID, 3, o.LoanNumber FROM tblOrder as o WHERE o.OrderTypeID = 1 AND NOT EXISTS (SELECT * FROM tblOrder tmp WHERE tmp.CustomerID = o.CustomerID AND tmp.OrderTypeID = 3 AND tmp.LoanNumber = o.LoanNumber); </code></pre> <p>If you pick <strong>Option #2</strong> (don't check), then:</p> <pre class="lang-sql prettyprint-override"><code>CREATE UNIQUE NONCLUSTERED INDEX [UIX_tblOrder_CustomerID_OrderTypeID_LoanNumber] ON [tblOrder] ( [CustomerID] ASC, [OrderTypeID] ASC, [LoanNumber] ASC ) WITH (IGNORE_DUP_KEY = ON); </code></pre> <p>And then:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO tblOrder (CustomerID, OrderTypeID, LoanNumber) SELECT o.CustomerID, 3, o.LoanNumber FROM tblOrder as o WHERE o.OrderTypeID = 1; </code></pre> <hr> <p>Example of how <code>IGNORE_DUP_KEY</code> behaves:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE #IgnoreDuplicateTest (Col1 INT); CREATE UNIQUE NONCLUSTERED INDEX [UIX_#IgnoreDuplicateTest_Col1] ON #IgnoreDuplicateTest ( [Col1] ASC ) WITH (IGNORE_DUP_KEY = ON); INSERT INTO #IgnoreDuplicateTest (Col1) VALUES (1); -- (1 row(s) affected) INSERT INTO #IgnoreDuplicateTest (Col1) VALUES (1); -- Duplicate key was ignored. -- (0 row(s) affected) INSERT INTO #IgnoreDuplicateTest (Col1) SELECT tmp.val FROM (VALUES (1),(2)) AS tmp(val); -- Duplicate key was ignored. -- (1 row(s) affected) SELECT * FROM #IgnoreDuplicateTest; -- Col1 -- 1 -- 2 </code></pre>
8,011,581
ARC, ivars in Blocks and Reference Cycles via Captured Self
<p>I’m working in a pure iOS5/ARC environment, so I can use __weak references as needed. I do reference ivars in a block in many situations, most notably, animation blocks that move views around, which are properties of say, my view controller class.</p> <h3>My question:</h3> <blockquote> <p>In the most trivial use of ivars in a block, am I creating a reference cycle? Do I need to use the __weak self / strong self technique <em>everytime</em> I write a block that manipulates instance variables of the containing object?</p> </blockquote> <p>I’ve been re-watching the 2011 WWDC Session #322 (Objective-C Advancements in Depth) to understand the nuances regarding the 3 minute segment starting at time index 25:03 about “Reference Cycle Via Captured Self”. To me, this implies any usage of ivars in a block should be safeguarded with the weak self / strong self setup as described in that segment.</p> <p>The sample method below on a view controller, is typical of animations I do.</p> <p>In the openIris block, is it wrong to reference ivars “_topView” and “_bottomView” as I have?</p> <p>Should I always setup a __weak reference to self before the block, then a strong reference inside the block to the weak reference just setup prior, and then access the ivars through that strong reference within my block?</p> <p>From the WWDC session, I understand that referencing ivars in a block is really creating a reference to the implied self that these ivars hang off of.</p> <p>To me, this implies that there really isn’t any simple or trivial case where it is correct to access ivars in a block without the weak/strong dance to ensure no cycles. Or am I reading to much into a corner case that doesn’t apply to simple cases, such as my example?</p> <pre><code>- (void)openIrisAnimated:(BOOL)animated { if (_isIrisOpened) { NSLog(@"Asked to open an already open iris."); return; // Bail } // Put the common work into a block. // Note: “_topView” and “_bottomView” are the backing ivars of // properties “topView” and “bottomView” void (^openIris)() = ^{ _topView.frame = CGRectMake(....); _bottomView.frame = CGRectMake(....); }; // Now do the actual opening of the iris, whether animated or not: if (animated) { [UIView animateWithDuration:0.70f animations:^{ openIris(); }]; } else { openIris(); } _irisOpened = YES; // Because we have now just opened it } </code></pre> <p>Here’s how I’d re-write the openIris block piece using the guidance from Session #322, but I’m just wondering if all my similar blocks require this weak/strong reference dance to ensure correctness and stability:</p> <pre><code>__weak MyClass *weakSelf = self; void (^openIris)() = ^{ MyClass *strongSelf = weakSelf; if (strongSelf) { strongSelf.topView.frame = CGRectMake(....); strongSelf.bottomView.frame = CGRectMake(....); } }; </code></pre> <p>Is this in fact, necessary?</p>
8,011,611
2
0
null
2011-11-04 15:19:47.567 UTC
15
2011-12-15 21:08:40.52 UTC
2011-11-04 16:16:33.757 UTC
null
19,679
null
535,054
null
1
26
objective-c|ios|ios5|objective-c-blocks|automatic-ref-counting
6,737
<p>There is only a cycle here if self then goes on to hold a reference to the block (or something owned by self). If not you're good to go as the lifetime of the block is not dictated by the self it retained.</p> <p>So in your particular example, you seem to be in the clear. Animation blocks don't need to participate in the weak/strong self dance.</p>
8,352,260
Why does the SqlParameter name/value constructor treat 0 as null?
<p>I observed a strange problem in a piece of code where an adhoc SQL query was not producing the expected output, even though its parameters matched records in the data source. I decided to enter the following test expression into the immediate window:</p> <pre><code>new SqlParameter("Test", 0).Value </code></pre> <p>This gave a result of <code>null</code>, which leaves me scratching my head. It seems that the <code>SqlParameter</code> constructor treats zeroes as nulls. The following code produces the correct result:</p> <pre><code>SqlParameter testParam = new SqlParameter(); testParam.ParameterName = "Test"; testParam.Value = 0; // subsequent inspection shows that the Value property is still 0 </code></pre> <p>Can anyone explain this behaviour? Is it somehow intentional? If so, it's potentially rather dangerous...</p>
8,352,277
2
1
null
2011-12-02 05:48:07.273 UTC
3
2016-03-18 11:02:12.407 UTC
null
null
null
null
428,051
null
1
32
c#|sql-server|ado.net|sqlparameter
8,273
<p>As stated in the <a href="http://msdn.microsoft.com/en-us/library/0881fz2y.aspx" rel="noreferrer">documentation</a> for that constructor:</p> <blockquote> <p>When you specify an Object in the value parameter, the SqlDbType is inferred from the Microsoft .NET Framework type of the Object.</p> <p>Use caution when you use this overload of the <a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx" rel="noreferrer">SqlParameter</a> constructor to specify integer parameter values. Because this overload takes a value of type <a href="https://msdn.microsoft.com/en-us/library/system.object.aspx" rel="noreferrer">Object</a>, you must convert the integral value to an <a href="https://msdn.microsoft.com/en-us/library/system.object.aspx" rel="noreferrer">Object</a> type when the value is zero, as the following C# example demonstrates.</p> <pre><code>Parameter = new SqlParameter("@pname", (object)0); </code></pre> <p>If you do not perform this conversion, the compiler assumes that you are trying to call the <a href="http://msdn.microsoft.com/en-us/library/h8f14f0z.aspx" rel="noreferrer"><strong>SqlParameter</strong> <em>(string, SqlDbType)</em></a> constructor overload.</p> </blockquote> <p>You simply were calling a different constructor than you thought in your case.</p> <p>The reason for this is that C# allows an <em>implicit</em> conversion from the integer literal <code>0</code> to enum types (which are just integral types underneath), and this implicit conversion causes the <code>(string, SqlDbType)</code> constructor to be a better match for overload resolution than the boxing conversion necessary to convert <code>int</code> to <code>object</code> for the <code>(string, object)</code> constructor.</p> <p>This will never be a problem when you pass an <code>int</code> <em>variable</em>, even if the value of that variable is <code>0</code> (because it is not a zero literal), or any other expression that has the type <code>int</code>. It will also not happen if you explicitly cast the <code>int</code> to <code>object</code> as seen above, because then there is only one matching overload.</p>
7,942,597
Supporting Open In... menu item in my app for iOS Mail And Safari
<p>I need to have my app open documents from the Safari and Mail apps with that "Open In..." thing in the <code>UIDocumentInteractionController</code> class. How do I accomplish this?</p>
8,023,211
2
0
null
2011-10-30 00:30:35.727 UTC
42
2017-11-23 02:03:38.647 UTC
2011-11-06 03:02:57.29 UTC
null
224,988
null
945,847
null
1
49
objective-c|ios|cocoa-touch|uidocumentinteraction
34,012
<p>I know this was extremely frustrating for me as a beginning programmer, or even as a moderately skilled one now. File I/O through the Mail and Safari apps involves very... interestingly named conventions within the app itself. So let's get our hands dirty with an Xcode project for iPhone. Open Xcode (I will be using 4.2 for this Tutorial) and select the 'Single View' application template (or create an empty project, then add a single view with a .xib). </p> <p><img src="https://i.stack.imgur.com/2OSRI.png" alt="Screenshot showing Xcode template selection sheet"></p> <p>In that newly created application, rename the view controller (and associated xib) to <code>OfflineReaderViewController</code>, and then we'll get down to the code. (We will touch every file but the prefix header and main.m, so be aware that you'll need everything in front of you!) </p> <p>Enter the AppDelegate header and paste the following code into it: </p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @class OfflineReaderViewController; @interface AppDelegate : UIResponder &lt;UIApplicationDelegate&gt; @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) OfflineReaderViewController *viewController; @end </code></pre> <p>Then enter the Delegate's .m file and paste the following code in verbatim:</p> <pre><code>#import "AppDelegate.h" #import "OfflineReaderViewController.h" @implementation AppDelegate @synthesize window; @synthesize viewController; -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { // Make sure url indicates a file (as opposed to, e.g., http://) if (url != nil &amp;&amp; [url isFileURL]) { // Tell our OfflineReaderViewController to process the URL [self.viewController handleDocumentOpenURL:url]; } // Indicate that we have successfully opened the URL return YES; } </code></pre> <pre><code>- (void)dealloc { [window release]; [viewController release]; [super dealloc]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[OfflineReaderViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { /* Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ } - (void)applicationDidEnterBackground:(UIApplication *)application { /* Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. */ } - (void)applicationWillEnterForeground:(UIApplication *)application { /* Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. */ } - (void)applicationDidBecomeActive:(UIApplication *)application { /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ } - (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. */ } @end </code></pre> <p>This: </p> <pre><code>-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { if (url != nil &amp;&amp; [url isFileURL]) { [self.viewController handleDocumentOpenURL:url]; } return YES; } </code></pre> <p>Is the singular most important part of this tutorial. To break it down into its respective parts: <code>-(BOOL)application:(UIApplication *)application</code> is our sample app; <code>openURL:(NSURL *)url</code> is the URL that's sent to tell us what to open; <code>sourceApplication:(NSString *)sourceApplication</code> is the application that sent the link; and <code>annotation:(id)annotation</code> is an extra feature we won't get into.</p> <p>Now, we must layout our xib. Enter the xib (which should be entitled 'OfflineReaderViewController', but it doesn't matter with a xib, unless we call <code>initWithNibName:</code> (which we won't)), and make it look like the picture below:</p> <p><img src="https://i.stack.imgur.com/GH4PR.png" alt="Screenshot of IB layout"></p> <p>It is VERY important that you go into the <code>UIWebView</code>'s Attributes and check "Scales Pages To Fit", as this let's us zoom in and out on web pages with pinches. Don't worry about the connections just yet, we will be creating those shortly.</p> <p>Enter the <code>OfflineReaderViewController</code> header and paste in the following:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface OfflineReaderViewController : UIViewController &lt;UIDocumentInteractionControllerDelegate&gt; { IBOutlet UIWebView *webView; } -(void)openDocumentIn; -(void)handleDocumentOpenURL:(NSURL *)url; -(void)displayAlert:(NSString *) str; -(void)loadFileFromDocumentsFolder:(NSString *) filename; -(void)listFilesFromDocumentsFolder; - (IBAction) btnDisplayFiles; @end </code></pre> <p>Now the .m:</p> <pre><code>#import "OfflineReaderViewController.h" @implementation OfflineReaderViewController UIDocumentInteractionController *documentController; -(void)openDocumentIn { NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Minore" ofType:@"pdf"]; documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]]; documentController.delegate = self; [documentController retain]; documentController.UTI = @"com.adobe.pdf"; [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES]; } -(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application { } -(void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application { } -(void)documentInteractionControllerDidDismissOpenInMenu: (UIDocumentInteractionController *)controller { } -(void) displayAlert:(NSString *) str { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } - (void)handleDocumentOpenURL:(NSURL *)url { [self displayAlert:[url absoluteString]]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView setUserInteractionEnabled:YES]; [webView loadRequest:requestObj]; } -(void)loadFileFromDocumentsFolder:(NSString *) filename { //---get the path of the Documents folder--- NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename]; NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; [self handleDocumentOpenURL:fileUrl]; } -(void)listFilesFromDocumentsFolder { //---get the path of the Documents folder--- NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSFileManager *manager = [NSFileManager defaultManager]; NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil]; NSMutableString *filesStr = [NSMutableString stringWithString:@"Files in Documents folder \n"]; for (NSString *s in fileList){ [filesStr appendFormat:@"%@ \n", s]; } [self displayAlert:filesStr]; [self loadFileFromDocumentsFolder:@"0470918020.pdf"]; } - (IBAction) btnDisplayFiles { [self listFilesFromDocumentsFolder]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; [self openDocumentIn]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end </code></pre> <p>Those of you who are actively watching and not just copying everything I tell you to (just kidding) will know that this line: <code>[[NSBundle mainBundle] pathForResource:@"Minore" ofType:@"pdf"];</code> will give us a SIGABRT because, well, the file doesn't exist! So, drag in any generic PDF that you've pulled from wherever (I recommend <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/OOP_ObjC.pdf" rel="nofollow noreferrer">here</a> because who doesnt spend their free time reading massive amounts of documentation?), then copy its title and paste it in with the suffix (.pdf) removed; the <code>ofType:@"pdf"</code> part takes care of that for us. The line should look like this when you're done with it: <code>[[NSBundle mainBundle] pathForResource:@"//file name//" ofType:@"pdf"];</code></p> <p>Now go back into the xib and hook up those <code>IBOutlets</code>! All told, here's what your "File's owner" tab should look like: </p> <p><img src="https://i.stack.imgur.com/PW29H.png" alt="Screenshot showing established connections"></p> <p>It seems we're done...but wait! We didn't do anything to get an "Open In..." menu up and running! Well, it turns out that there is some mucking around in the .plist file necessary. Open up the app .plist (with a quick right click, then select Open As > Source Code) and paste in the following: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt; &lt;string&gt;en&lt;/string&gt; &lt;key&gt;CFBundleDisplayName&lt;/key&gt; &lt;string&gt;${PRODUCT_NAME}&lt;/string&gt; &lt;key&gt;CFBundleExecutable&lt;/key&gt; &lt;string&gt;${EXECUTABLE_NAME}&lt;/string&gt; &lt;key&gt;CFBundleIconFiles&lt;/key&gt; &lt;array/&gt; &lt;key&gt;CFBundleIdentifier&lt;/key&gt; &lt;string&gt;CodaFi.${PRODUCT_NAME:rfc1034identifier}&lt;/string&gt; &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt; &lt;string&gt;6.0&lt;/string&gt; &lt;key&gt;CFBundleName&lt;/key&gt; &lt;string&gt;${PRODUCT_NAME}&lt;/string&gt; &lt;key&gt;CFBundlePackageType&lt;/key&gt; &lt;string&gt;APPL&lt;/string&gt; &lt;key&gt;CFBundleShortVersionString&lt;/key&gt; &lt;string&gt;1.0&lt;/string&gt; &lt;key&gt;CFBundleSignature&lt;/key&gt; &lt;string&gt;????&lt;/string&gt; &lt;key&gt;CFBundleVersion&lt;/key&gt; &lt;string&gt;1.0&lt;/string&gt; &lt;key&gt;LSRequiresIPhoneOS&lt;/key&gt; &lt;true/&gt; &lt;key&gt;UIRequiredDeviceCapabilities&lt;/key&gt; &lt;array&gt; &lt;string&gt;armv7&lt;/string&gt; &lt;/array&gt; &lt;key&gt;UISupportedInterfaceOrientations&lt;/key&gt; &lt;array&gt; &lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeLeft&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeRight&lt;/string&gt; &lt;/array&gt; &lt;key&gt;UIFileSharingEnabled&lt;/key&gt; &lt;true/&gt; &lt;key&gt;CFBundleDocumentTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;CFBundleTypeName&lt;/key&gt; &lt;string&gt;PDF Document&lt;/string&gt; &lt;key&gt;LSHandlerRank&lt;/key&gt; &lt;string&gt;Alternate&lt;/string&gt; &lt;key&gt;CFBundleTypeRole&lt;/key&gt; &lt;string&gt;Viewer&lt;/string&gt; &lt;key&gt;LSItemContentTypes&lt;/key&gt; &lt;array&gt; &lt;string&gt;com.adobe.pdf&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>[Side note: be careful mucking around in the source code of any plist, if you don't know what you're doing, you could get the dreaded 'This file has been corrupted' error from Xcode]</p> <p>If one were to right click and select Open As > Property List, it would look like this: </p> <p><img src="https://i.stack.imgur.com/avV2R.png" alt="Shot of Xcode plist editor window"></p> <p>There's another VERY important field in there called 'Application supports iTunes file sharing'. That must be set to "YES", or your app will not show up in iTunes as supporting file sharing.</p> <p>The 'Document Types' field specifies the kinds of documents our example can open. Expand the arrow to find its role and UTI's. These are unique identifiers (Unique Type Identifiers; seems obvious what that acronym means now, doesn't it?) that every kind of file has. UTI's are what let the finder replace a generic document image with that nice localized image of the file type (don't believe me, rename an unimportant file extension to .ouhbasdvluhb and try to get a nice picture!) If I wanted to open my own custom format (lets say a .code file) then I would put something like <code>com.CodaFi.code</code> (reverse DNS notation for those with no clue) in the UTI field and Document Type Name would be 'CodaFi Document'. Handler Rank and Role should be straightforward as our handler rank is alternate (because we don't own the file) and our role is viewer (because we don't need anything more important. Our example is just a viewer and not an editor, so we'll leave it as such.</p> <p>For future reference, UTI's have official system-declared naming schemes when they come from respected sources (Oracle, Microsoft, even Apple itself) which can be found in the <a href="http://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Introduction/Introduction.html" rel="nofollow noreferrer">Uniform Type Identifier Reference Guide</a>, but are listed <a href="http://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html#//apple_ref/doc/uid/TP40009259-SW1" rel="nofollow noreferrer">here</a> for pedantry's sake.</p> <p>Now, let's run 'er! The code should build with no errors, assuming you copied verbatim and got those darned xib hookups right. Now when you first launch your application, you should be presented with the option to open a document in iBooks. Deselect it, the real meat of the code is opening other documents! Launch Safari and search for any PDF that Safari can QuickLook or open. Then in the "Open in..." menu, our app shows up! Click it. You'll get the little switcheroo animation and an alert will come up with the location of the file. When you dismiss it, the <code>UIWebView</code> will have loaded the PDF. The Mail app has similar functionality with attachments. You can also call those PDFs up to your app. </p> <p>That's it, it's all done. Enjoy and happy coding!</p>
5,110,292
Why is Clojure dynamically typed?
<p>One thing I like very much is reading about different programming languages. Currently, I'm learning Scala but that doesn't mean I'm not interested in Groovy, Clojure, Python, and many others. All these languages have a unique look and feel and some characteristic features. In the case of Clojure I don't understand one of these design decisions. As far as I know, Clojure puts great emphasis on its functional paradigm and pretty much forces you to use immutable "variables" wherever possible. So if half of your values are immutable, why is the language dynamically typed?</p> <p>The Clojure website says:</p> <blockquote> <p>First and foremost, Clojure is dynamic. That means that a Clojure program is not just something you compile and run, but something with which you can interact.</p> </blockquote> <p>Well, that sounds completely strange. If a program is compiled you can't change it anymore. Sure you can "interact" with it, that's what UIs are used for but the website certainly doesn't mean a neat "dynamic" GUI.</p> <p><strong>How does Clojure benefit from dynamical typing</strong></p> <p>I mean the special case of Clojure and not general advantages of dynamic typing.</p> <p><strong>How does the dynamic type system help improve functional programming</strong></p> <p>Again, I know the pleasure of not spilling "int a;" all over the source code but type inference can ease a lot of the pain. Therefore I would just like to know how dynamic typing supports the concepts of a functional language.</p>
5,110,590
5
5
null
2011-02-24 20:49:39.723 UTC
10
2020-12-09 15:04:32.003 UTC
2019-07-18 06:07:56.867 UTC
null
1,303,324
null
497,600
null
1
59
dynamic|functional-programming|clojure|language-design|paradigms
17,007
<p>I agree, a purely functional language can still have an interactive read-eval-print-loop, and would have an easier time with type inference. I assume Clojure wanted to attract lisp programmers by being "lisp for the jvm", and chose to be dynamic like other lisps. Another factor is that type systems need to be designed as the very first step of the language, and it's faster for language implementors to just skip that step.</p>
4,944,750
How to subtract date/time in JavaScript?
<p>I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?</p> <p>The dates are stored like <code>"2011-02-07 15:13:06"</code>.</p>
4,944,782
5
3
null
2011-02-09 12:20:26.167 UTC
22
2021-03-05 18:38:01.113 UTC
2019-08-14 13:59:12.71 UTC
null
4,642,212
null
132,640
null
1
215
javascript|date
431,205
<p>This will give you the difference between two dates, in milliseconds</p> <pre><code>var diff = Math.abs(date1 - date2); </code></pre> <p>In your example, it'd be</p> <pre><code>var diff = Math.abs(new Date() - compareDate); </code></pre> <p>You need to make sure that <code>compareDate</code> is a valid <code>Date</code> object.</p> <p>Something like this will probably work for you</p> <pre><code>var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/'))); </code></pre> <p>i.e. turning <code>"2011-02-07 15:13:06"</code> into <code>new Date('2011/02/07 15:13:06')</code>, which is a format the <code>Date</code> constructor can comprehend.</p>
4,883,891
Ruby on Rails production log rotation
<p>What is the best way to enable log rotation on a Ruby on Rails production app?</p> <p>Is it by using logrotate on the hosting server or is there a set of options to use when initializing logger from the app?</p>
4,883,967
6
1
null
2011-02-03 08:36:44.1 UTC
97
2022-09-20 07:44:43.78 UTC
2022-09-20 07:44:43.78 UTC
null
5,409,748
null
449,483
null
1
183
ruby-on-rails|logging|production-environment
70,733
<h1>Option 1: syslog + logrotate</h1> <p>You can configure rails, to use the systems log tools. </p> <p>An example in <em>config/environments/production.rb</em>.</p> <pre><code># Use a different logger for distributed setups config.logger = SyslogLogger.new </code></pre> <p>That way, you log to syslog, and can use default logrotate tools to rotate the logs. </p> <h1>Option 2: normal Rails logs + logrotate</h1> <p>Another option is to simply configure logrotate to pick up the logs left by rails. On Ubuntu and Debian that would be, for example, in a file called <code>/etc/logrotate.d/rails_example_com</code>.</p> <pre><code>/path/to/rails.example.com/tmp/log/*.log { weekly missingok rotate 52 compress delaycompress notifempty copytruncate } </code></pre> <p>As per suggestions below, in Rails it is advised to use <code>copytruncate</code>, to avoid having to restart the Rails app.</p> <p>Edit: removed "sharedscripts/endscript" since they are not used here and cause problems according to comment. And removed <code>create 640 root adm</code> as per comment suggested.</p>
5,186,394
Using conditional (?:) operator for method selection in C# (3.0)?
<p>I'm refactoring some code.</p> <p>Right now there are quite a few places with functions like this:</p> <pre><code>string error; if (a) { error = f1(a, long, parameter, list); } else { error = f2(the_same, long, parameter, list); } </code></pre> <p>before refactoring f1 and f2 (which are large, but do similar things), I'd like to refactor to:</p> <pre><code>string error = (a ? f1 : f2)(a, long, parameter, list); </code></pre> <p>As one would do in C. (The function signatures are identical)</p> <p>But I get an error:</p> <p><strong>"Error 13 Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'"</strong></p> <p>This would allow me to recognize that the parameter lists are identical by the initial refactoring giving invariant behavior, and also refactor the calls in a single place, ensuring that all during these various refactorings, nothing gets broken as I change the calling interface to the method.</p> <p>Am I missing something small which would allow a syntax close to this to work (as opposed to a whole bunch of extra delegate type definitions etc)?</p> <p>Sorry to edit, but there is actually a return value, and yes, unfortunately, it is a string. ;-(</p> <p>Right now, I'm settling for this:</p> <pre><code>string error = a ? f1(a, long, parameter, list) : f2(a, long, parameter, list); </code></pre> <p>The problem is that the parameter list are indeed very long, and are going to get refactored, and I'd prefer to have them consolidated first and deal with compiler errors as I change them.</p>
5,186,445
7
1
null
2011-03-03 20:52:44.653 UTC
7
2011-03-03 21:07:30 UTC
2011-03-03 21:07:30 UTC
null
18,255
null
18,255
null
1
32
c#|.net|.net-3.5
10,431
<p>You can do that by declaring a delegate, as you pointed out.</p> <p>I notice that you wrote that you are doing this in quite a few places. Another alternative that might be more suitable is to use interfaces. Instantiate one of two different types depending on the value of a, then call the method on that object.</p> <pre><code>IFoo foo = a ? new Foo1() : new Foo2(); foo.f(a, long, parameter, list); </code></pre> <p>If you have multiple methods that need to change simultaneously depending on the value of <code>a</code> then you can include them all in the same interface and you will only need to test <code>a</code> once.</p>
4,948,190
git repository sync between computers, when moving around?
<p>Let's say that I have a desktop pc and a laptop, and sometimes I work on the desktop and sometimes I work on the laptop.</p> <p>What is the easiest way to move a git repository back and forth?</p> <p>I want the git repositories to be identical, so that I can continue where I left of at the other computer.</p> <p>I would like to make sure that I have the same branches and tags on both of the computers.</p> <p>Thanks Johan</p> <p>Note: I know how to do this with SubVersion, but I'm curious on how this would work with git. If it is easier, I can use a third pc as classical server that the two pc:s can sync against.</p> <p>Note: Both computers are running Linux.</p> <hr> <p><strong>Update</strong>:</p> <p>So let's try XANI:s idea with a bare git repo on a server, and the push command syntax from KingCrunch. In this example there is two clients and one server.</p> <p>So let's create the server part first.</p> <pre><code>ssh user@server mkdir -p ~/git_test/workspace cd ~/git_test/workspace git --bare init </code></pre> <p>So then from one of the other computers I try to get a copy of the repo with clone:</p> <pre><code>git clone user@server:~/git_test/workspace/ Initialized empty Git repository in /home/user/git_test/repo1/workspace/.git/ warning: You appear to have cloned an empty repository. </code></pre> <p>Then go into that repo and add a file:</p> <pre><code>cd workspace/ echo "test1" &gt; testfile1.txt git add testfile1.txt git commit testfile1.txt -m "Added file testfile1.txt" git push origin master </code></pre> <p>Now the server is updated with testfile1.txt.</p> <p>Anyway, let's see if we can get this file from the other computer.</p> <pre><code>mkdir -p ~/git_test/repo2 cd ~/git_test/repo2 git clone user@server:~/git_test/workspace/ cd workspace/ git pull </code></pre> <p>And now we can see the testfile.</p> <p>At this point we can edit it with some more content and update the server again.</p> <pre><code>echo "test2" &gt;&gt; testfile1.txt git add testfile1.txt git commit -m "Test2" git push origin master </code></pre> <p>Then we go back to the first client and do a git pull to see the updated file. And now I can move back and forth between the two computers, and add a third if I like to.</p>
4,948,264
8
1
null
2011-02-09 17:18:05.453 UTC
51
2020-07-26 19:25:16.293 UTC
2011-02-14 07:21:08.937 UTC
null
51,425
null
51,425
null
1
92
git|version-control
54,428
<p>I think, there are multiple approaches. I will just describe, how I handle this</p> <p>I have one netbook as a 24/7 server, that holds multiple git-repositories. From/To there I push and pull changes via SSH. For access from outside I use dyndns.org. It works fine, especially because I have more than two systems, that needs access to some of the repositories.</p> <p>Update: A little example. Lets say my netbook is called "netbook". I create a repository there</p> <pre><code>$ ssh [email protected] $ cd ~/git $ mkdir newThing $ cd newThing $ git init --bare </code></pre> <p>On my desktop I will than create a clone of it. Maybe I will add some files also</p> <pre><code>$ git clone [email protected]:/home/username/git/newThing $ git add . $ git commit -m "Initial" $ git push origin master </code></pre> <p>On my portables I will (first) do the same, but for remote access (from outside my LAN), I will also add the external address.</p> <pre><code>$ git clone [email protected]:/home/username/git/newThing $ git remote add externalName [email protected]:/home/username/git/newThing $ git pull externalName master </code></pre> <p>Its just the way git (/git workflows) works. You can add as many remote repositories as you like. It doesnt matters, if two or more refers to the same "physical" repositories. You dont need an own local "server", you can use any public server, to which you have ssh access. And of course you dont need a public server at all, if you dont need access from outside. The bare repository can also be on the desktop system and you can then create a working-copy-repository within the local filesystem.</p> <pre><code>$ mkdir myRepo; cd myRepo $ git init --bare $ cd /path/to/myProject $ git remote add origin /path/to/myRepo $ git add .; git commit -m "Initial"; git push origin master </code></pre> <p>This is the way, how I handle this, and I for me it works quite fine (if not perfect ;))</p> <p>Something to read: <a href="http://progit.org/">http://progit.org/</a> Really good book.-</p>
12,586,340
Regex to find special characters in Java
<p>I can use </p> <pre><code>var regex = /[$&amp;+,:;=?@#|]/; if(elem.match(regex)) { // do something } </code></pre> <p>to find whether there is any special characters in string in Javascript.</p> <p>How can I use the similar regular expression in Java?</p> <p>I have tried:</p> <pre><code>str.match("\\="); // return false </code></pre> <p>For example:</p> <pre><code>String str = "123=456"; </code></pre> <p>I tried to detect "=" in str.</p> <p>That did not work. What am I doing wrong?</p>
12,586,471
4
1
null
2012-09-25 15:34:54.553 UTC
2
2016-12-31 21:16:58.84 UTC
2012-09-25 16:20:14.88 UTC
null
5,640
null
924,578
null
1
6
java|regex
58,778
<p>Try this.</p> <pre><code>Pattern regex = Pattern.compile("[$&amp;+,:;=?@#|]"); Matcher matcher = regex.matcher("123=456"); if (matcher.find()){ // Do something } </code></pre> <p>EDIT: <code>matches()</code> checks all the string and <code>find()</code> finds it in any part of the string.</p> <p>A link: <a href="http://docs.oracle.com/javase/tutorial/essential/regex/index.html"><code>http://docs.oracle.com/javase/tutorial/essential/regex/index.html</code></a></p>
12,264,970
Why is my program slow when looping over exactly 8192 elements?
<p>Here is the extract from the program in question. The matrix <code>img[][]</code> has the size SIZE×SIZE, and is initialized at:</p> <p><code>img[j][i] = 2 * j + i</code></p> <p>Then, you make a matrix <code>res[][]</code>, and each field in here is made to be the average of the 9 fields around it in the img matrix. The border is left at 0 for simplicity.</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; for(k=-1;k&lt;2;k++) for(l=-1;l&lt;2;l++) res[j][i] += img[j+l][i+k]; res[j][i] /= 9; } </code></pre> <p>That's all there's to the program. For completeness' sake, here is what comes before. No code comes after. As you can see, it's just initialization.</p> <pre><code>#define SIZE 8192 float img[SIZE][SIZE]; // input image float res[SIZE][SIZE]; //result of mean filter int i,j,k,l; for(i=0;i&lt;SIZE;i++) for(j=0;j&lt;SIZE;j++) img[j][i] = (2*j+i)%8196; </code></pre> <p>Basically, this program is slow when SIZE is a multiple of 2048, e.g. the execution times:</p> <pre><code>SIZE = 8191: 3.44 secs SIZE = 8192: 7.20 secs SIZE = 8193: 3.18 secs </code></pre> <p>The compiler is GCC. From what I know, this is because of memory management, but I don't really know too much about that subject, which is why I'm asking here.</p> <p>Also how to fix this would be nice, but if someone could explain these execution times I'd already be happy enough.</p> <p>I already know of malloc/free, but the problem is not amount of memory used, it's merely execution time, so I don't know how that would help.</p>
12,265,928
2
15
null
2012-09-04 13:51:31.017 UTC
320
2017-10-11 12:08:18.863 UTC
2012-09-18 14:59:40.147 UTC
null
50,776
anon
null
null
1
791
c++|performance|memory-management|gcc
96,084
<p>The difference is caused by the same super-alignment issue from the following related questions:</p> <ul> <li><a href="https://stackoverflow.com/q/11413855/922184">Why is transposing a matrix of 512x512 much slower than transposing a matrix of 513x513?</a></li> <li><a href="https://stackoverflow.com/q/7905760/922184">Matrix multiplication: Small difference in matrix size, large difference in timings</a></li> </ul> <p>But that's only because there's one other problem with the code.</p> <p>Starting from the original loop:</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; for(k=-1;k&lt;2;k++) for(l=-1;l&lt;2;l++) res[j][i] += img[j+l][i+k]; res[j][i] /= 9; } </code></pre> <p>First notice that the two inner loops are trivial. They can be unrolled as follows:</p> <pre><code>for(i=1;i&lt;SIZE-1;i++) { for(j=1;j&lt;SIZE-1;j++) { res[j][i]=0; res[j][i] += img[j-1][i-1]; res[j][i] += img[j ][i-1]; res[j][i] += img[j+1][i-1]; res[j][i] += img[j-1][i ]; res[j][i] += img[j ][i ]; res[j][i] += img[j+1][i ]; res[j][i] += img[j-1][i+1]; res[j][i] += img[j ][i+1]; res[j][i] += img[j+1][i+1]; res[j][i] /= 9; } } </code></pre> <p>So that leaves the two outer-loops that we're interested in.</p> <p>Now we can see the problem is the same in this question: <a href="https://stackoverflow.com/q/9936132/922184">Why does the order of the loops affect performance when iterating over a 2D array?</a></p> <p>You are iterating the matrix column-wise instead of row-wise.</p> <hr> <p>To solve this problem, you should interchange the two loops.</p> <pre><code>for(j=1;j&lt;SIZE-1;j++) { for(i=1;i&lt;SIZE-1;i++) { res[j][i]=0; res[j][i] += img[j-1][i-1]; res[j][i] += img[j ][i-1]; res[j][i] += img[j+1][i-1]; res[j][i] += img[j-1][i ]; res[j][i] += img[j ][i ]; res[j][i] += img[j+1][i ]; res[j][i] += img[j-1][i+1]; res[j][i] += img[j ][i+1]; res[j][i] += img[j+1][i+1]; res[j][i] /= 9; } } </code></pre> <p>This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.</p> <hr> <p><strong>Core i7 920 @ 3.5 GHz</strong></p> <p>Original code:</p> <pre><code>8191: 1.499 seconds 8192: 2.122 seconds 8193: 1.582 seconds </code></pre> <p>Interchanged Outer-Loops:</p> <pre><code>8191: 0.376 seconds 8192: 0.357 seconds 8193: 0.351 seconds </code></pre>
12,179,271
Meaning of @classmethod and @staticmethod for beginner
<p>What do <code>@classmethod</code> and <code>@staticmethod</code> mean in Python, and how are they different? <em>When</em> should I use them, <em>why</em> should I use them, and <em>how</em> should I use them?</p> <p>As far as I understand, <code>@classmethod</code> tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just define the class method without adding <code>@classmethod</code> or <code>@staticmethod</code> or any <code>@</code> definitions?</p>
12,179,752
12
0
null
2012-08-29 13:37:33.443 UTC
1,071
2022-08-18 22:34:33.607 UTC
2022-08-18 22:16:08.813 UTC
null
4,621,513
user1632861
null
null
1
1,834
python|oop|static-methods|class-method
737,727
<p>Though <code>classmethod</code> and <code>staticmethod</code> are quite similar, there's a slight difference in usage for both entities: <code>classmethod</code> must have a reference to a class object as the first parameter, whereas <code>staticmethod</code> can have no parameters at all.</p> <h2>Example</h2> <pre><code>class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) date1 = cls(day, month, year) return date1 @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day &lt;= 31 and month &lt;= 12 and year &lt;= 3999 date2 = Date.from_string('11-09-2012') is_date = Date.is_date_valid('11-09-2012') </code></pre> <h2>Explanation</h2> <p>Let's assume an example of a class, dealing with date information (this will be our boilerplate):</p> <pre><code>class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.month = month self.year = year </code></pre> <p>This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).</p> <p>Here we have <code>__init__</code>, a typical initializer of Python class instances, which receives arguments as a typical instance method, having the first non-optional argument (<code>self</code>) that holds a reference to a newly created instance.</p> <p><strong>Class Method</strong></p> <p>We have some tasks that can be nicely done using <code>classmethod</code>s.</p> <p><em>Let's assume that we want to create a lot of <code>Date</code> class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.</em></p> <p>So what we must do here is:</p> <ol> <li>Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.</li> <li>Instantiate <code>Date</code> by passing those values to the initialization call.</li> </ol> <p>This will look like:</p> <pre><code>day, month, year = map(int, string_date.split('-')) date1 = Date(day, month, year) </code></pre> <p>For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use <code>classmethod</code>. Let's create another <em>constructor</em>.</p> <pre><code> @classmethod def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) date1 = cls(day, month, year) return date1 date2 = Date.from_string('11-09-2012') </code></pre> <p>Let's look more carefully at the above implementation, and review what advantages we have here:</p> <ol> <li>We've implemented date string parsing in one place and it's reusable now.</li> <li>Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).</li> <li><code>cls</code> is the <strong>class itself</strong>, not an instance of the class. It's pretty cool because if we inherit our <code>Date</code> class, all children will have <code>from_string</code> defined also.</li> </ol> <p><strong>Static method</strong></p> <p>What about <code>staticmethod</code>? It's pretty similar to <code>classmethod</code> but doesn't take any obligatory parameters (like a class method or instance method does).</p> <p>Let's look at the next use case.</p> <p><em>We have a date string that we want to validate somehow. This task is also logically bound to the <code>Date</code> class we've used so far, but doesn't require instantiation of it.</em></p> <p>Here is where <code>staticmethod</code> can be useful. Let's look at the next piece of code:</p> <pre><code> @staticmethod def is_date_valid(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day &lt;= 31 and month &lt;= 12 and year &lt;= 3999 # usage: is_date = Date.is_date_valid('11-09-2012') </code></pre> <p>So, as we can see from usage of <code>staticmethod</code>, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and other methods), which <code>classmethod</code> does have.</p>
12,459,779
query specified join fetching, but the owner of the fetched association was not present in the select list
<p>I'm selecting two id columns but get error specified:</p> <pre><code>org.hibernate.QueryException: **query specified join fetching, but the owner of the fetched association was not present in the select list** [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=r,role=null,tableName=REVISIONS,tableAlias=revision1_,origin=ENTITY_CHANGED_IN_REVISION entitychan0_,columns={entitychan0_.REV_ID ,className=ru.csbi.registry.domain.envers.Revision}}] [ select ec.id as entityChangeId, r.id as revisionId from ru.csbi.registry.domain.envers.EntityChange as ec inner join fetch ec.revision as r where ec.groupEntityId = :groupEntityId and ec.groupName = :groupName and r.timestamp &lt; :entityDateFrom and r.timestamp &gt; :entityDateTo and ( ec.revisionType in (0, 5, 1, 4, 2 ) and not ( ec.otherGroupEntityModified = false and ec.thisGroupEntityModified = true and ec.rowDataModified = false and ec.collectionOfNotGroupEntityModified = false ) ) group by ec.id, r.id having count(*) &gt; :start order by r.id desc] </code></pre> <p>Some code:</p> <pre><code>String hql = " select ec.id as entityChangeId, r.id as revisionId from EntityChange as ec " + " inner join fetch ec.revision as r " + " where ec.groupEntityId = :groupEntityId" + " and ec.groupName = :groupName " + " and r.timestamp &lt; :entityDateFrom " + " and r.timestamp &gt; :entityDateTo " + " and ( " + " ec.revisionType in (" + RevisionType.ADD.getRepresentation() + ", " + RevisionType.ONLY_DATA_PROPERTY_MOD.getRepresentation() + ", " + RevisionType.BOTH_COLLECTION_AND_PROPERTY_MOD.getRepresentation() + ", " + RevisionType.ONLY_COLLECTION_PROPERTY_MOD.getRepresentation() + ", " + RevisionType.DEL.getRepresentation() + " ) " + " and not ( "+ "ec.otherGroupEntityModified = false and " + "ec.thisGroupEntityModified = true and " + "ec.rowDataModified = false and " + "ec.collectionOfNotGroupEntityModified = false " + " ) " + " ) " + " group by ec.id, r.id " + " having count(*) &gt; :start" + " order by r.id desc"; </code></pre> <p>How to fix the error and what am I doing wrong?</p>
12,459,909
5
2
null
2012-09-17 13:02:15.167 UTC
8
2022-06-01 01:39:36.547 UTC
2017-09-01 19:27:45.567 UTC
null
711,129
null
1,035,646
null
1
111
hibernate|join|fetch
129,315
<p>Use regular <code>join</code> instead of <code>join fetch</code> (by the way, it's <code>inner</code> by default):</p> <pre><code>String hql = " select ec.id as entityChangeId, r.id as revisionId from EntityChange as ec " + " join ec.revision as r " + ... </code></pre> <p>As error message tells you, <code>join fetch</code> doesn't make sense here, because it's a performance hint that forces eager loading of collection.</p>
12,433,695
Extract elements of list at odd positions
<p>So I want to create a list which is a sublist of some existing list.</p> <p>For example,</p> <p><code>L = [1, 2, 3, 4, 5, 6, 7]</code>, I want to create a sublist <code>li</code> such that <code>li</code> contains all the elements in <code>L</code> at odd positions.</p> <p>While I can do it by</p> <pre><code>L = [1, 2, 3, 4, 5, 6, 7] li = [] count = 0 for i in L: if count % 2 == 1: li.append(i) count += 1 </code></pre> <p>But I want to know if there is another way to do the same efficiently and in fewer number of steps. </p>
12,433,705
4
4
null
2012-09-15 01:05:25.1 UTC
35
2021-10-03 09:46:08.537 UTC
2016-01-20 09:27:42.737 UTC
null
231,298
null
976,093
null
1
132
python|list|slice
178,688
<h2>Solution</h2> <p>Yes, you can:</p> <pre><code>l = L[1::2] </code></pre> <p>And this is all. The result will contain the elements placed on the following positions (<code>0</code>-based, so first element is at position <code>0</code>, second at <code>1</code> etc.):</p> <pre><code>1, 3, 5 </code></pre> <p>so the result (actual numbers) will be:</p> <pre><code>2, 4, 6 </code></pre> <h2>Explanation</h2> <p>The <code>[1::2]</code> at the end is just a notation for list slicing. Usually it is in the following form:</p> <pre><code>some_list[start:stop:step] </code></pre> <p>If we omitted <code>start</code>, the default (<code>0</code>) would be used. So the first element (at position <code>0</code>, because the indexes are <code>0</code>-based) would be selected. In this case the second element will be selected.</p> <p>Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated <strong>from the second element to the end</strong>.</p> <p>We also provided third argument (<code>step</code>) which is <code>2</code>. Which means that one element will be selected, the next will be skipped, and so on...</p> <p>So, to sum up, in this case <code>[1::2]</code> means:</p> <ol> <li>take the second element (which, by the way, is an odd element, if you judge from the index),</li> <li>skip one element (because we have <code>step=2</code>, so we are skipping one, as a contrary to <code>step=1</code> which is default),</li> <li>take the next element,</li> <li>Repeat steps 2.-3. until the end of the list is reached,</li> </ol> <p><strong>EDIT</strong>: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: <a href="https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">Explain Python&#39;s slice notation</a></p> <h2>Extras - replacing counter with <code>enumerate()</code></h2> <p>In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using <a href="http://docs.python.org/library/functions.html#enumerate" rel="noreferrer"><code>enumerate()</code></a>:</p> <pre><code>for count, i in enumerate(L): if count % 2 == 1: l.append(i) </code></pre> <p>The above serves exactly the same purpose as the code you were using:</p> <pre><code>count = 0 for i in L: if count % 2 == 1: l.append(i) count += 1 </code></pre> <p>More on emulating <code>for</code> loops with counter in Python: <a href="https://stackoverflow.com/q/522563/548696">Accessing the index in Python &#39;for&#39; loops</a></p>
18,771,963
pandas efficient dataframe set row
<p>First I have the following empty DataFrame preallocated:</p> <pre><code>df=DataFrame(columns=range(10000),index=range(1000)) </code></pre> <p>Then I want to update the <code>df</code> row by row (efficiently) with a length-10000 numpy array as data. My problem is: I don't even have an idea what method of DataFrame I should use to accomplish this task.</p> <p>Thank you!</p>
18,772,565
2
4
null
2013-09-12 18:40:02.79 UTC
2
2013-09-12 19:23:14.1 UTC
null
null
null
null
765,398
null
1
20
python|pandas|dataframe
42,889
<p>Here's 3 methods, only 100 columns, 1000 rows</p> <pre><code>In [5]: row = np.random.randn(100) </code></pre> <p>Row wise assignment</p> <pre><code>In [6]: def method1(): ...: df = DataFrame(columns=range(100),index=range(1000)) ...: for i in xrange(len(df)): ...: df.iloc[i] = row ...: return df ...: </code></pre> <p>Build up the arrays in a list, create the frame all at once</p> <pre><code>In [9]: def method2(): ...: return DataFrame([ row for i in range(1000) ]) ...: </code></pre> <p>Columnwise assignment (with transposes at both ends)</p> <pre><code>In [13]: def method3(): ....: df = DataFrame(columns=range(100),index=range(1000)).T ....: for i in xrange(1000): ....: df[i] = row ....: return df.T ....: </code></pre> <p>These all have the same output frame</p> <pre><code>In [22]: (method2() == method1()).all().all() Out[22]: True In [23]: (method2() == method3()).all().all() Out[23]: True In [8]: %timeit method1() 1 loops, best of 3: 1.76 s per loop In [10]: %timeit method2() 1000 loops, best of 3: 7.79 ms per loop In [14]: %timeit method3() 1 loops, best of 3: 1.33 s per loop </code></pre> <p>It is CLEAR that building up a list, THEN creating the frame all at once is orders of magnitude faster than doing any form of assignment. Assignment involves copying. Building up all at once only copies once.</p>
3,468,177
RESTful way to send commands
<p>How do you send "commands" to a RESTful server?</p> <p>Use case: My server caches certain information so that it does not have to read the database every time that information is requested. I need a way to send a command from my client application to tell the server to flush the cache. Would you use <code>POST</code> or <code>PUT</code> on some URL like "<code>.../flush_cache</code>"?</p> <p>The "command" is not really data that needs "Representational State Transfer", unless the state being transferred is the result of the command -- "switch is off", "cache is flushed", etc. As a general rule, how does REST send commands to the server?</p>
5,625,525
3
2
null
2010-08-12 13:32:30.663 UTC
28
2019-03-21 16:40:30.443 UTC
2019-03-21 16:40:30.443 UTC
null
1,746,685
null
96,233
null
1
61
rest|web-applications
28,533
<p>I have come across such a situation a lot in a past project. Since REST is well...about resource, it is not always clear how to deal with things that are Really RPC in nature.</p> <p>An easy way to get around this is to think of it as the <em>bureaucratic part of rest</em>, the request can be a resource itself :</p> <p>1 . "You want to trigger a command on my server ? first fill this form I90292 and send it to us" :</p> <pre><code>POST /bureaucracy/command-request Content-Type: application/x-www-form-urlencoded Content-Length: ... </code></pre> <ol start="2"> <li><p>"Ok we will see what we can do. your case number is 999"</p> <p>201 Created (or 202 Accepted as per Kugel's comment) Location /bureaucracy/command-request/999</p></li> <li><p>And then the client checks regularly</p> <p>GET /bureaucracy/command-request/999 </p></li> </ol> <p>Hopefully he gets a response like the following</p> <pre><code>200 OK &lt;command-request&gt; &lt;number&gt;999&lt;/number&gt; ... &lt;result&gt;Success&lt;/result&gt; &lt;/command-request&gt; </code></pre> <p>Of course if the bureaucratic service has great customer care it would offer the customer to call him when it is done if he wants :<br> "You want to trigger a command on our server? Kindly fill this form and send it to us. Note that you can join your contact info so we can call you when it is done"</p> <pre><code>POST /bureaucracy/command-request?callback=client.com/bureaucracy/inbox </code></pre> <p>Or as a custom http header <code>X-Callback: http://client.com/bureaucracy/inbox</code> </p>
18,880,654
Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?
<p>I use the following code to test the C++ <code>&lt;random&gt;</code> library.</p> <p>Why do I get the exact same sequence for every run of the compiled executable? Is <code>rd()</code> deterministic upon compilation? How do I get different output for each run?</p> <p>GCC 4.8.1 on Windows 7 64bit. Using MinGW distribution from <a href="http://nuwen.net/mingw.html" rel="nofollow noreferrer">http://nuwen.net/mingw.html</a>.</p> <p><strong>EDIT:</strong> I tested the same piece code with Visual Studio. There is no problem. The outputs are non deterministic. This could be a bug in mingw gcc 4.8.1 that I used.</p> <pre><code>#include &lt;iostream&gt; #include &lt;random&gt; using namespace std; int main(){ random_device rd; mt19937 mt(rd()); uniform_int_distribution&lt;int&gt; dist(0,99); for (int i = 0; i&lt; 16; ++i){ cout&lt;&lt;dist(mt)&lt;&lt;" "; } cout &lt;&lt;endl; } </code></pre>
18,880,689
5
10
null
2013-09-18 19:27:11.68 UTC
17
2020-06-19 21:15:18.767 UTC
2020-05-01 02:04:21.337 UTC
null
65,863
null
305,669
null
1
71
c++|c++11|random|stl
20,822
<p>From <a href="http://en.cppreference.com/w/cpp/numeric/random/random_device" rel="noreferrer">http://en.cppreference.com/w/cpp/numeric/random/random_device</a>:</p> <blockquote> <p>Note that std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation.</p> </blockquote> <p>I would expect a decent implementation to at least seed the RNG though.</p> <p><strong>Edit:</strong> I suspect they deliberately chose to deliver the same sequence each time, to make obvious the fact that the stream wasn't as random as promised.</p>
11,445,523
python & smtplib: Is sending mail via gmail using oauth2 possible?
<p>So I can login to and send mail through gmail using smtplib (using the script below), but I was just wondering if using oauth2 was an option like with imaplib? I didn't see anything on the smtplib documentation page about oauth and I haven't found anything googling. Thanks.</p> <pre><code>#! /usr/bin/python import smtplib to = 'myemailaddress' gmail_user = 'myemailaddress' gmail_pwd = 'passwd' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' print header msg = header + '\n this is test msg from me \n\n' smtpserver.sendmail(gmail_user, to, msg) print 'done!' smtpserver.close(); </code></pre> <p><strong>Edit:</strong></p> <p>Thanks to samy.vilar for the very detailed explaination provided in his answer. However, I'm having a little trouble. Here is my script:</p> <pre><code>#! /usr/bin/python import oauth2 as oauth import oauth2.clients.smtp as smtplib consumer = oauth.Consumer('anonymous', 'anonymous') token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') url = "https://mail.google.com/mail/b/[email protected]/smtp/" conn = smtplib.SMTP('smtp.googlemail.com', 587) conn.set_debuglevel(True) conn.ehlo('test') conn.starttls() conn.authenticate(url, consumer, token) header = 'To:[email protected]\n' + 'From: [email protected]\n' + 'Subject:testing \n' msg = header + '\n this is test msg from me \n\n' conn.sendmail('[email protected]', '[email protected]', msg) </code></pre> <p>What is puzzling me, is that it appears to authenticate ok:</p> <pre><code>send: 'ehlo test\r\n' reply: '250-mx.google.com at your service, [75.173.8.127]\r\n' reply: '250-SIZE 35882577\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250 ENHANCEDSTATUSCODES\r\n' reply: retcode (250); Msg: mx.google.com at your service, [75.173.8.127] SIZE 35882577 8BITMIME STARTTLS ENHANCEDSTATUSCODES send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS send: 'AUTH XOAUTH R0VUIGh0dHBzOi8vbWFpbC5nb29nbGUuY29tL21haWwvYi90ZXN0aW5nLm9hdXRoLjFAZ21haWwuY29tL3NtdHAvIG9hdXRoX2JvZHlfaGFzaD0iMmptajdsNXJTdzB5VmIlMkZ2bFdBWWtLJTJGWUJ3ayUzRCIsb2F1dGhfY29uc3VtZXJfa2V5PSJhbm9ueW1vdXMiLG9hdXRoX25vbmNlPSI3Nzc0ODMyIixvYXV0aF9zaWduYXR1cmU9IkxuckZHODdxdHRxZUhsUlQ1emRndmtEZ1UzTSUzRCIsb2F1dGhfc2lnbmF0dXJlX21ldGhvZD0iSE1BQy1TSEExIixvYXV0aF90aW1lc3RhbXA9IjEzNDIxNDI3NzIiLG9hdXRoX3Rva2VuPSIxJTJGTUk2QjJEcUpQNEZFa0RSTFVLckQ1bDQ2c1EwNzU4LTJ1Y0VLQlktRGVCMCIsb2F1dGhfdmVyc2lvbj0iMS4wIg==\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted </code></pre> <p>But then when it comes to sending the email, it seems to forget that <code>conn</code> was already authenticated:</p> <pre><code>send: 'ehlo [192.168.2.4]\r\n' reply: '250-mx.google.com at your service, [75.173.8.127]\r\n' reply: '250-SIZE 35882577\r\n' reply: '250-8BITMIME\r\n' reply: '250-AUTH LOGIN PLAIN XOAUTH\r\n' reply: '250 ENHANCEDSTATUSCODES\r\n' reply: retcode (250); Msg: mx.google.com at your service, [75.173.8.127] SIZE 35882577 8BITMIME AUTH LOGIN PLAIN XOAUTH ENHANCEDSTATUSCODES send: 'mail FROM:&lt;[email protected]&gt; size=107\r\n' reply: '530-5.5.1 Authentication Required. Learn more at\r\n' reply: '530 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 tu7sm3163839pbc.55\r\n' reply: retcode (530); Msg: 5.5.1 Authentication Required. Learn more at 5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 tu7sm3163839pbc.55 send: 'rset\r\n' reply: '250 2.1.5 Flushed tu7sm3163839pbc.55\r\n' reply: retcode (250); Msg: 2.1.5 Flushed tu7sm3163839pbc.55 Traceback (most recent call last): File "./gmail_send3.py", line 47, in &lt;module&gt; conn.sendmail('[email protected]', '[email protected]', msg) File "/usr/lib/python2.7/smtplib.py", line 713, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 tu7sm3163839pbc.55', '[email protected]') </code></pre>
11,448,844
1
1
null
2012-07-12 05:32:21.447 UTC
11
2016-03-03 20:30:59.383 UTC
2012-11-15 14:13:40.097 UTC
null
569,101
null
813,149
null
1
10
python|oauth|oauth-2.0|smtplib
14,778
<p>Interesting, I think it is possible, I found the following links <br/> <a href="https://developers.google.com/google-apps/gmail/oauth_overview" rel="noreferrer">https://developers.google.com/google-apps/gmail/oauth_overview</a><br/></p> <p><b>UPDATE</b><br/> <a href="https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough" rel="noreferrer">https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough</a><br/> This is the new walk through using oauth2, it seems like xoauth has being declared obsolete, I've update the URL to get the older version <code>xoauth.py</code> file, in case any one still needs it, though it looks like Google has changed their API and this walkthrough is no longer applicable.</p> <p>you can use xoauth directly or <a href="https://github.com/simplegeo/python-oauth2/" rel="noreferrer">https://github.com/simplegeo/python-oauth2/</a> to actually communicate I recommend the latter, its more versatile.</p> <p>Apparently you first need to download <code>xoauth.py</code> script.</p> <pre><code>$ wget https://raw.githubusercontent.com/google/gmail-oauth2-tools/master/obsolete/python/xoauth.py $ python xoauth.py --generate_oauth_token [email protected] xoauth.py:74: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha oauth_token_secret: HFJEvjcTfiXSPxgLzDh-1yaH oauth_token: 4/EwUxCtY9ye1kdtb4uNJIcaUe9KXl oauth_callback_confirmed: true To authorize token, visit this url and follow the directions to generate a verification code: https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=4%2FEwUxCtY9ye1kdtb4uNJIcaUe9KXl Enter verification code: 7XjT15fqk1aNe8152d9oTRcJ oauth_token: 1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0 oauth_token_secret: NysqNqVTulFsdHpSRrPP56sF </code></pre> <p>lets test it:</p> <pre><code>$ python xoauth.py --test_imap_authentication [email protected] \ --oauth_token=1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0 --oauth_token_secret=NysqNqVTulFsdHpSRrPP56sF xoauth.py:74: DeprecationWarning: the sha module is deprecated; use the hashlib module instead xoauth string (before base64-encoding): GET https://mail.google.com/mail/b/[email protected]/imap/ oauth_consumer_key="anonymous",oauth_nonce="18010070659685102619",oauth_signature="jTJv%2FAFATpzfq%2BZTLAAxFNmWPi0%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1342084141",oauth_token="1%2FMI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0",oauth_version="1.0" XOAUTH string (base64-encoded): R0VUIGh0dHBzOi8vbWFpbC5nb29nbGUuY29tL21haWwvYi90ZXN0aW5nLm9hdXRoLjFAZ21haWwuY29tL2ltYXAvIG9hdXRoX2NvbnN1bWVyX2tleT0iYW5vbnltb3VzIixvYXV0aF9ub25jZT0iMTgwMTAwNzA2NTk2ODUxMDI2MTkiLG9hdXRoX3NpZ25hdHVyZT0ialRKdiUyRkFGQVRwemZxJTJCWlRMQUF4Rk5tV1BpMCUzRCIsb2F1dGhfc2lnbmF0dXJlX21ldGhvZD0iSE1BQy1TSEExIixvYXV0aF90aW1lc3RhbXA9IjEzNDIwODQxNDEiLG9hdXRoX3Rva2VuPSIxJTJGTUk2QjJEcUpQNEZFa0RSTFVLckQ1bDQ2c1EwNzU4LTJ1Y0VLQlktRGVCMCIsb2F1dGhfdmVyc2lvbj0iMS4wIg== 09:01.40 &gt; COKI1 AUTHENTICATE XOAUTH 09:01.44 &lt; + 09:01.45 write literal size 444 09:02.68 &lt; * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE 09:02.68 &lt; COKI1 OK [email protected] Testing Oauth authenticated (Success) 09:02.68 &gt; COKI2 SELECT INBOX 09:03.09 &lt; * FLAGS (\Answered \Flagged \Draft \Deleted \Seen) 09:03.09 &lt; * OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen \*)] Flags permitted. 09:03.09 &lt; * OK [UIDVALIDITY 3] UIDs valid. 09:03.09 &lt; * 3 EXISTS 09:03.09 &lt; * 0 RECENT 09:03.09 &lt; * OK [UIDNEXT 4] Predicted next UID. 09:03.09 &lt; COKI2 OK [READ-WRITE] INBOX selected. (Success) </code></pre> <p>looks like we are good to go. you may want to set up a <code>virtualenv</code> </p> <pre><code>$ git clone https://github.com/simplegeo/python-oauth2.git $ cd python-oauth2/ $ sudo python setup.py install </code></pre> <p>and taken right from the docs:</p> <pre><code>import oauth2 as oauth import oauth2.clients.imap as imaplib # Set up your Consumer and Token as per usual. Just like any other # three-legged OAuth request. consumer = oauth.Consumer('anonymous', 'anonymous') token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') # Setup the URL according to Google's XOAUTH implementation. Be sure # to replace the email here with the appropriate email address that # you wish to access. url = "https://mail.google.com/mail/b/[email protected]/imap/" conn = imaplib.IMAP4_SSL('imap.googlemail.com') conn.debug = 4 # This is the only thing in the API for impaplib.IMAP4_SSL that has # changed. You now authenticate with the URL, consumer, and token. conn.authenticate(url, consumer, token) # Once authenticated everything from the impalib.IMAP4_SSL class will # work as per usual without any modification to your code. conn.select('INBOX') print conn.list() &gt;&gt;&gt; conn.authenticate(url, consumer, token) 20:11.73 &gt; EPKK1 AUTHENTICATE XOAUTH 20:11.78 &lt; + 20:11.78 write literal size 496 20:11.93 &lt; * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE 20:11.93 &lt; EPKK1 OK [email protected] Testing Oauth authenticated (Success) &gt;&gt;&gt; conn.select('INBOX') 20:17.47 &gt; EPKK2 SELECT INBOX 20:17.58 &lt; * FLAGS (\Answered \Flagged \Draft \Deleted \Seen) 20:17.58 &lt; * OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen \*)] Flags permitted. 20:17.58 &lt; * OK [UIDVALIDITY 3] UIDs valid. 20:17.58 &lt; * 3 EXISTS 20:17.58 &lt; * 0 RECENT 20:17.58 &lt; * OK [UIDNEXT 4] Predicted next UID. 20:17.58 &lt; EPKK2 OK [READ-WRITE] INBOX selected. (Success) ('OK', ['3']) &gt;&gt;&gt; print conn.list() 20:20.23 &gt; EPKK3 LIST "" * 20:20.28 &lt; * LIST (\HasNoChildren) "/" "INBOX" 20:20.28 &lt; * LIST (\Noselect \HasChildren) "/" "[Gmail]" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/All Mail" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Drafts" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Important" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Sent Mail" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Spam" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Starred" 20:20.28 &lt; * LIST (\HasNoChildren) "/" "[Gmail]/Trash" 20:20.28 &lt; EPKK3 OK Success ('OK', ['(\\HasNoChildren) "/" "INBOX"', '(\\Noselect \\HasChildren) "/" "[Gmail]"', '(\\HasNoChildren) "/" "[Gmail]/All Mail"', '(\\HasNoChildren) "/" "[Gmail]/Drafts"', '(\\HasNoChildren) "/" "[Gmail]/Important"', '(\\HasNoChildren) "/" "[Gmail]/Sent Mail"', '(\\HasNoChildren) "/" "[Gmail]/Spam"', '(\\HasNoChildren) "/" "[Gmail]/Starred"', '(\\HasNoChildren) "/" "[Gmail]/Trash"']) &gt;&gt;&gt; </code></pre> <p>for smtp:</p> <pre><code>import oauth2 as oauth import oauth2.clients.smtp as smtplib # Set up your Consumer and Token as per usual. Just like any other # three-legged OAuth request. # Set up your Consumer and Token as per usual. Just like any other # three-legged OAuth request. consumer = oauth.Consumer('anonymous', 'anonymous') token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') # Setup the URL according to Google's XOAUTH implementation. Be sure # to replace the email here with the appropriate email address that # you wish to access. url = "https://mail.google.com/mail/b/[email protected]/smtp/" conn = smtplib.SMTP('smtp.googlemail.com', 587) conn.set_debuglevel(True) conn.ehlo('test') conn.starttls() # Again the only thing modified from smtplib.SMTP is the authenticate # method, which works identically to the imaplib.IMAP4_SSL method. conn.authenticate(url, consumer, token) &gt;&gt;&gt; conn.ehlo('test') send: 'ehlo test\r\n' reply: '250-mx.google.com at your service, [142.255.57.49]\r\n' reply: '250-SIZE 35882577\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250 ENHANCEDSTATUSCODES\r\n' reply: retcode (250); Msg: mx.google.com at your service, [142.255.57.49] SIZE 35882577 8BITMIME STARTTLS ENHANCEDSTATUSCODES (250, 'mx.google.com at your service, [142.255.57.49]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES') &gt;&gt;&gt; conn.starttls() send: 'STARTTLS\r\n' reply: '220 2.0.0 Ready to start TLS\r\n' reply: retcode (220); Msg: 2.0.0 Ready to start TLS (220, '2.0.0 Ready to start TLS') &gt;&gt;&gt; conn.authenticate(url, consumer, token) send: 'AUTH XOAUTH R0VUIGh0dHBzOi8vbWFpbC5nb29nbGUuY29tL21haWwvYi90ZXN0aW5nLm9hdXRoLjFAZ21haWwuY29tL3NtdHAvIG9hdXRoX2JvZHlfaGFzaD0iMmptajdsNXJTdzB5VmIlMkZ2bFdBWWtLJTJGWUJ3ayUzRCIsb2F1dGhfY29uc3VtZXJfa2V5PSJhbm9ueW1vdXMiLG9hdXRoX25vbmNlPSI4MTEyMDkxNCIsb2F1dGhfc2lnbmF0dXJlPSJSaUFsTGdQWnpBSkNQJTJGWmx5aGRpYU1CV0xiTSUzRCIsb2F1dGhfc2lnbmF0dXJlX21ldGhvZD0iSE1BQy1TSEExIixvYXV0aF90aW1lc3RhbXA9IjEzNDIwODU2NzIiLG9hdXRoX3Rva2VuPSIxJTJGTUk2QjJEcUpQNEZFa0RSTFVLckQ1bDQ2c1EwNzU4LTJ1Y0VLQlktRGVCMCIsb2F1dGhfdmVyc2lvbj0iMS4wIg==\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted &gt;&gt;&gt; </code></pre> <p>and to send emails:</p> <pre><code>&gt;&gt;&gt; conn.authenticate(url, consumer, token) send: 'AUTH XOAUTH R0VUIGh0dHBzOi8vbWFpbC5nb29nbGUuY29tL21haWwvYi90ZXN0aW5nLm9hdXRoLjFAZ21haWwuY29tL3NtdHAvIG9hdXRoX2JvZHlfaGFzaD0iMmptajdsNXJTdzB5VmIlMkZ2bFdBWWtLJTJGWUJ3ayUzRCIsb2F1dGhfY29uc3VtZXJfa2V5PSJhbm9ueW1vdXMiLG9hdXRoX25vbmNlPSI2OTg3ODM3NiIsb2F1dGhfc2lnbmF0dXJlPSIlMkZjUGslMkJRVWVJY1RaYXp1ekkwR1FzdkdtbDFBJTNEIixvYXV0aF9zaWduYXR1cmVfbWV0aG9kPSJITUFDLVNIQTEiLG9hdXRoX3RpbWVzdGFtcD0iMTM0MjA4NjAxNCIsb2F1dGhfdG9rZW49IjElMkZNSTZCMkRxSlA0RkVrRFJMVUtyRDVsNDZzUTA3NTgtMnVjRUtCWS1EZUIwIixvYXV0aF92ZXJzaW9uPSIxLjAi\r\n' reply: '235 2.7.0 Accepted\r\n' reply: retcode (235); Msg: 2.7.0 Accepted &gt;&gt;&gt; header = 'To:[email protected]\n' + 'From: [email protected]\n' + 'Subject:testing \n' &gt;&gt;&gt; msg = header + '\n this is test msg from me \n\n' &gt;&gt;&gt; conn.sendmail('[email protected]', '[email protected]', msg) send: 'mail FROM:&lt;[email protected]&gt; size=107\r\n' reply: '250 2.1.0 OK gb7sm6540492qab.12\r\n' reply: retcode (250); Msg: 2.1.0 OK gb7sm6540492qab.12 send: 'rcpt TO:&lt;[email protected]&gt;\r\n' reply: '250 2.1.5 OK gb7sm6540492qab.12\r\n' reply: retcode (250); Msg: 2.1.5 OK gb7sm6540492qab.12 send: 'data\r\n' reply: '354 Go ahead gb7sm6540492qab.12\r\n' reply: retcode (354); Msg: Go ahead gb7sm6540492qab.12 data: (354, 'Go ahead gb7sm6540492qab.12') send: 'To:[email protected]\r\nFrom: [email protected]\r\nSubject:testing \r\n\r\n this is test msg from me \r\n\r\n.\r\n' reply: '250 2.0.0 OK 1342086030 gb7sm6540492qab.12\r\n' reply: retcode (250); Msg: 2.0.0 OK 1342086030 gb7sm6540492qab.12 data: (250, '2.0.0 OK 1342086030 gb7sm6540492qab.12') {} &gt;&gt;&gt; </code></pre> <p>make sure you authenticate before sending out emails.<br/> hope this helps ...</p> <p><b>UPDATE</b><br/> There may be a bug that requires re-authentication, the following should work.</p> <pre><code>import oauth2 as oauth import oauth2.clients.smtp as smtplib consumer = oauth.Consumer('anonymous', 'anonymous') token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') url = "https://mail.google.com/mail/b/[email protected]/smtp/" conn = smtplib.SMTP('smtp.googlemail.com', 587) conn.set_debuglevel(True) conn.ehlo('test') conn.starttls() conn.authenticate(url, consumer, token) header = 'To:[email protected]\n' + 'From: [email protected]\n' + 'Subject:testing \n' msg = header + '\n this is test msg from me \n\n' try: conn.sendmail('[email protected]', '[email protected]', msg) except Exception as ex: print str(ex) print 'retying ...' conn.authenticate(url, consumer, token) conn.sendmail('[email protected]', '[email protected]', msg) </code></pre> <p>though you can also use <code>xoauth</code> directly as such:</p> <pre><code>import time import smtplib import xoauth consumer = xoauth.OAuthEntity('anonymous', 'anonymous') access_token = xoauth.OAuthEntity('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') xoauth_string = xoauth.GenerateXOauthString(consumer, access_token, '[email protected]', 'smtp', '[email protected]', str(xoauth.random.randrange(2**64 - 1)), str(int(time.time()))) smtp_conn = smtplib.SMTP('smtp.gmail.com', 587) smtp_conn.set_debuglevel(True) smtp_conn.ehlo() smtp_conn.starttls() smtp_conn.ehlo() smtp_conn.docmd('AUTH', 'XOAUTH ' + xoauth.base64.b64encode(xoauth_string)) header = 'To:[email protected]\n' + 'From: [email protected]\n' + 'Subject:testing \n' msg = header + '\n this is test msg from me \n\n' smtp_conn.sendmail('[email protected]', '[email protected]', msg) </code></pre> <p>this seems to always work, I should submit a ticket to <code>python-oauth2</code> team, thank you.</p> <p><b>THOUGH THIS ALSO SEEM TO ALWAYS WORK</b></p> <pre><code>import oauth2 as oauth import oauth2.clients.smtp as smtplib consumer = oauth.Consumer('anonymous', 'anonymous') token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF') url = "https://mail.google.com/mail/b/[email protected]/smtp/" conn = smtplib.SMTP('smtp.googlemail.com', 587) conn.set_debuglevel(True) conn.ehlo('test') conn.starttls() conn.ehlo() conn.authenticate(url, consumer, token) header = 'To:[email protected]\n' + 'From: [email protected]\n' + 'Subject:testing \n' msg = header + '\n this is test msg from me \n\n' conn.sendmail('[email protected]', '[email protected]', msg) </code></pre> <p>it looks you need to call <code>conn.ehlo()</code> before authenticating.</p>
11,433,886
Sorting A List Comprehension In One Statement
<p>I noticed something I didn't expect when writing a script this morning. I tried to use a list comprehension and sort it all in one statement and got a surprising result. The following code summarizes my general use case, but is simplified for this question:</p> <pre><code>Transaction = namedtuple('Transaction', ['code', 'type']) my_list = [Transaction('code1', 'AAAAA'), Transaction('code2', 'BBBBB'), Transaction('code3', 'AAAAA')] types = ['AAAAA', 'CCCCC'] result = [trans for trans in my_list if trans.type in types].sort(key = lambda x: x.code) print result </code></pre> <p>Output:</p> <pre><code>None </code></pre> <p>If I create the list using the comprehension, then sort it after the fact, everything is fine. I'm curious why this happens?</p>
11,433,911
3
1
null
2012-07-11 13:36:50.87 UTC
6
2012-07-11 13:46:47.617 UTC
null
null
null
null
1,432,934
null
1
31
python|list-comprehension
31,869
<p>The method <code>list.sort()</code> is sorting the list in place, and as all mutating methods it returns <code>None</code>. Use the built-in function <a href="http://docs.python.org/library/functions.html#sorted"><code>sorted()</code></a> to return a new sorted list.</p> <pre><code>result = sorted((trans for trans in my_list if trans.type in types), key=lambda x: x.code) </code></pre> <p>Instead of <code>lambda x: x.code</code>, you could also use the slightly faster <code>operator.attrgetter("code")</code>.</p>
11,270,509
putting a remote file into hadoop without copying it to local disk
<p>I am writing a shell script to put data into hadoop as soon as they are generated. I can ssh to my master node, copy the files to a folder over there and then put them into hadoop. I am looking for a shell command to get rid of copying the file to the local disk on master node. to better explain what I need, here below you can find what I have so far:</p> <p>1) copy the file to the master node's local disk:</p> <pre><code>scp test.txt username@masternode:/folderName/ </code></pre> <p>I have already setup SSH connection using keys. So no password is needed to do this.</p> <p>2) I can use ssh to remotely execute the hadoop put command:</p> <pre><code>ssh username@masternode "hadoop dfs -put /folderName/test.txt hadoopFolderName/" </code></pre> <p>what I am looking for is how to pipe/combine these two steps into one and skip the local copy of the file on masterNode's local disk.</p> <p>thanks</p> <p>In other words, I want to pipe several command in a way that I can</p>
11,270,559
5
1
null
2012-06-30 00:33:44.437 UTC
21
2021-09-15 08:52:34.443 UTC
null
null
null
null
793,677
null
1
37
unix|ssh|hadoop|copying|piping
50,888
<p>Try this (untested):</p> <pre><code>cat test.txt | ssh username@masternode "hadoop dfs -put - hadoopFoldername/test.txt" </code></pre> <p>I've used similar tricks to copy directories around:</p> <pre><code>tar cf - . | ssh remote "(cd /destination &amp;&amp; tar xvf -)" </code></pre> <p>This sends the output of local-<code>tar</code> into the input of remote-<code>tar</code>.</p>
11,299,208
How to Synchronize Android Database with an online SQL Server?
<p>I am developing an Android App that stores different types of data in the built-in SQLite provided by the Android Platform.</p> <p>Inside the App I have placed a "Sync" button which is supposed to Sync the data between the local SQLite Database, with an Online SQL Server database on my server.</p> <p>What is the workaround to handle this? This feature can be found in Google Calendar, where you can view the calendar's events on your mobile, and when you add a new event and Sync the data, you can view the updated data by going to your online account too.</p> <p>Note: I don't want to centralize my database online, because I also want to give the mobile users the ability to use the App without internet connection.</p>
11,299,639
1
4
null
2012-07-02 18:31:05.557 UTC
34
2018-05-07 08:53:25.91 UTC
2018-05-07 08:53:25.91 UTC
null
1,143,634
null
1,496,831
null
1
55
android|sql|sqlite|synchronization
41,533
<p>You should take a look at the SampleSyncAdapter project in the Android SDK demos (<a href="http://developer.android.com/training/sync-adapters/index.html" rel="noreferrer">Transferring Data Using Sync Adapters</a>). It shows you how to do synchronization "Android style", which requires no user interaction by manually tapping a sync button all the time.</p> <p>On top of that you need to write server software that is able to provide your SyncAdapter with a "delta" of all changes since the last commit. The most basic approach is keeping a "last synchronized" time stamp in your app which has to come from the server, otherwise you could get into trouble because of time differences between client and server. Normalize all time stamps as GMT or any timezone of your choice, but stick with that decision. If your app needs to display a time stamp in local time, then you need to use the Java Calendar and TimeZone class for converting the normalized time stamp into local time.</p> <p>Your app also needs to flag changed local records as "dirty", so your SyncAdapter knows that it needs to upload these changed or new records to the server.</p> <p>Following minimum features are needed for your server software:</p> <ul> <li>Update existing record(s) function</li> <li>Add new record(s) function</li> <li>Get updated records since last synchronization (app provides time stamp)</li> <li>Get new records since last synchronization (app provides time stamp)</li> </ul> <p>You also may want to read through some Google API (like Google Calendar) for getting an idea of how all of this works and how to design the server API interface for the communication.</p>
11,162,406
Open and write data to text file using Bash?
<p>How can I write data to a text file automatically by shell scripting in Linux?</p> <p>I was able to open the file. However, I don't know how to write data to it.</p>
11,162,510
12
1
null
2012-06-22 18:52:22.533 UTC
64
2022-03-15 13:14:53.943 UTC
2019-03-15 02:58:08.413 UTC
null
608,639
null
1,055,090
null
1
329
bash|shell
890,769
<p>The short answer:</p> <pre class="lang-sh prettyprint-override"><code>echo &quot;some data for the file&quot; &gt;&gt; fileName </code></pre> <p>However, <a href="https://unix.stackexchange.com/a/58312/364698"><code>echo</code> doesn't deal with end of line characters (EOFs) in an ideal way</a>. So, if you're gonna append more than one line, do it with <code>printf</code>:</p> <pre class="lang-sh prettyprint-override"><code>printf &quot;some data for the file\nAnd a new line&quot; &gt;&gt; fileName </code></pre> <p>The <code>&gt;&gt;</code> and <code>&gt;</code> operators are very useful for <em>redirecting output of commands</em>, they work with multiple other bash commands.</p>
13,213,378
What is causing a "Maximum function nesting level" error in Symfony 2.1 and Twig?
<p>I have a project on Symfony 2.1. After updating composer components (Gedemo, Symfony core, Doctrine, Twig, etc..) I have the following error:</p> <pre><code>Fatal error: Maximum function nesting level of '100' reached, aborting! in /var/www/{path}/vendor/twig/twig/lib/Twig/Token.php on line 78 </code></pre> <p>I have PHP 5.4. What can cause this error?</p>
13,213,409
5
5
null
2012-11-03 20:51:20.267 UTC
5
2018-06-16 22:16:31.37 UTC
2013-02-02 18:12:20.287 UTC
null
19,679
null
1,787,682
null
1
29
symfony|twig
31,482
<p>Find the <code>xdebug.ini</code> file:</p> <pre><code>$ locate xdebug.ini /etc/php5/conf.d/20-xdebug.ini /etc/php5/mods-available/xdebug.ini </code></pre> <p>In my case the file is <code>/etc/php5/conf.d/20-xdebug.ini</code>. Open it and add this line:</p> <pre><code>xdebug.max_nesting_level = 1000 </code></pre> <p>Don't forget to restart the FPM server.</p>
13,019,942
Why can't I get `pip install lxml` to work within a virtualenv?
<p>Note: I'm using virtualenvwrapper.</p> <p>Before activating the virtual environment:</p> <pre><code>$ pip install lxml Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/lib/python2.7/dist-packages Cleaning up... </code></pre> <p>After activating the virtual environment:</p> <pre><code>(test-env)$ pip install lxml force/build/lxml/src/lxml/includes/etree_defs.h:9:31: fatal error: libxml/xmlversion.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command /home/chaz/dev/envs/test-with-system-python-force/bin/python2 .7 -c "import setuptools;__file__='/home/chaz/dev/envs/test-with- system-python-force/build/lxml/setup.py';exec(compile(open(__file__). read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-bJ6Q_B-record/install-record.txt --single-version-externally -managed --install-headers /home/chaz/dev/envs/test-env/include/site/python2.7 failed with error code 1 in /home/chaz/dev/envs/test-env/build/lxml Storing complete log in /home/chaz/.pip/pip.log </code></pre>
13,020,013
4
3
null
2012-10-22 21:11:10.197 UTC
18
2018-07-18 17:24:07.773 UTC
2013-11-22 11:43:50.233 UTC
null
785,400
null
785,400
null
1
70
python|virtualenv|virtualenvwrapper
60,962
<p>You probably already have lxml installed on your system, perhaps installed due to a system package. Thus, the first attempt (<code>pip install lxml</code> without an active virtualenv) doesn't fail, but it also doesn't install it; it really doesn't do anything.</p> <p>In a virtualenv, by default, the system packages are ignored. Therefore, pip thinks that lxml is not installed. Therefore, it tries to install it into your virtual environment.</p> <p>lxml contains C modules that need to be compiled in order to install properly. However, the compilation of those C modules rely on your having some "development libraries" already installed as well. These development libraries are C libraries, not Python, and as such pip won't be able to automatically fetch them from the internet and install them for you.</p> <p>Therefore, you will need to install these development libraries on your own, most likely using your package manager. In a Debian system (like Ubuntu), this is...</p> <pre><code>apt-get install libxml2-dev libxslt-dev </code></pre> <p>This will install the libxml2 and libxslt development libraries to your local system. If you try again to install lxml, the C module compilation step should work because now these development libraries are on your system.</p> <p>The error message you were receiving was due to the fact that these libraries were missing (the <code>libxml/xmlversion.h: No such file or directory</code> part of the error message).</p> <p>See also: <a href="https://stackoverflow.com/questions/6504810/how-to-install-lxml-with-easy-install">How to install lxml on Ubuntu</a></p>
12,674,572
Proper usage of .net MVC Html.CheckBoxFor
<p>All I want to know is the proper syntax for the <code>Html.CheckBoxFor</code> HTML helper in ASP.NET MVC.</p> <p>What I'm trying to accomplish is for the check-box to be initially checked with an ID value so I can reference it in the Controller to see if it's still checked or not.</p> <p>Would below be the proper syntax?</p> <pre><code>@foreach (var item in Model.Templates) { &lt;td&gt; @Html.CheckBoxFor(model =&gt; true, item.TemplateId) @Html.LabelFor(model =&gt; item.TemplateName) &lt;/td&gt; } </code></pre>
12,674,731
7
3
null
2012-10-01 13:47:26.95 UTC
15
2017-08-03 20:07:14.577 UTC
2013-11-12 14:48:22.173 UTC
null
27,756
null
856,488
null
1
79
asp.net-mvc|checkboxfor
341,905
<h2>That isn't the proper syntax</h2> <p>The first parameter is <strong>not</strong> checkbox value but rather view model binding for the checkbox hence:</p> <pre><code>@Html.CheckBoxFor(m =&gt; m.SomeBooleanProperty, new { @checked = "checked" }); </code></pre> <p>The first parameter must identify a boolean property within your model (it's an <a href="https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(v=vs.110).aspx" rel="noreferrer">Expression</a> not an anonymous method returning a value) and second property defines any additional HTML element attributes. I'm not 100% sure that the above attribute will initially check your checkbox, but you can try. But beware. Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to <code>false</code>.</p> <h2>The correct way</h2> <p>Although my <em>proper suggestion</em> would be to provide initialized model to your view with that particular boolean property initialized to <code>true</code>.</p> <h2>Property types</h2> <p>As per Asp.net MVC <code>HtmlHelper</code> extension methods and inner working, checkboxes need to bind to boolean values and not integers what seems that you'd like to do. In that case a hidden field could store the <code>id</code>.</p> <h2>Other helpers</h2> <p>There are of course other helper methods that you can use to get greater flexibility about checkbox values and behaviour:</p> <pre><code>@Html.CheckBox("templateId", new { value = item.TemplateID, @checked = true }); </code></pre> <blockquote> <p><strong><em>Note</strong>:</em> <code>checked</code> <em>is an HTML element boolean property and not a value attribute which means that you can assign any value to it. The correct HTML syntax doesn't include any assignments, but there's no way of providing an anonymous C# object with undefined property that would render as an HTML element property.</em></p> </blockquote>
13,032,701
How to remove folders with a certain name
<p>In Linux, how do I remove folders with a certain name which are nested deep in a folder hierarchy?</p> <p>The following paths are under a folder and I would like to remove all folders named <code>a</code>. </p> <pre><code>1/2/3/a 1/2/3/b 10/20/30/a 10/20/30/b 100/200/300/a 100/200/300/b </code></pre> <p>What Linux command should I use from the parent folder?</p>
13,032,768
12
1
null
2012-10-23 14:26:23.213 UTC
70
2022-03-01 03:41:31.07 UTC
2013-11-19 20:33:43.383 UTC
null
445,131
null
136,088
null
1
209
linux|unix|rm
152,749
<p>If the target directory is empty, use find, filter with only directories, filter by name, execute rmdir:</p> <pre><code>find . -type d -name a -exec rmdir {} \; </code></pre> <p>If you want to recursively delete its contents, replace <code>-exec rmdir {} \;</code> with <code>-delete</code> or <code>-prune -exec rm -rf {} \;</code>. Other answers include details about these versions, credit them too.</p>
16,667,251
Query to get only numbers from a string
<p>I have data like this:</p> <pre><code>string 1: 003Preliminary Examination Plan string 2: Coordination005 string 3: Balance1000sheet </code></pre> <p>The output I expect is </p> <pre><code>string 1: 003 string 2: 005 string 3: 1000 </code></pre> <p>And I want to implement it in SQL.</p>
16,667,431
22
1
null
2013-05-21 10:00:54.127 UTC
36
2022-08-24 10:07:50.893 UTC
2019-11-25 10:05:20.013 UTC
null
1,127,428
null
2,404,950
null
1
93
sql|sql-server
415,288
<p>First create this <strong><code>UDF</code></strong></p> <pre><code>CREATE FUNCTION dbo.udf_GetNumeric ( @strAlphaNumeric VARCHAR(256) ) RETURNS VARCHAR(256) AS BEGIN DECLARE @intAlpha INT SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric) BEGIN WHILE @intAlpha &gt; 0 BEGIN SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' ) SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric ) END END RETURN ISNULL(@strAlphaNumeric,0) END GO </code></pre> <p>Now use the <strong><code>function</code></strong> as</p> <pre><code>SELECT dbo.udf_GetNumeric(column_name) from table_name </code></pre> <p><strong><a href="http://www.sqlfiddle.com/#!3/45f11/2" rel="noreferrer">SQL FIDDLE</a></strong></p> <p>I hope this solved your problem.</p> <p><strong><a href="http://blog.sqlauthority.com/2008/10/14/sql-server-get-numeric-value-from-alpha-numeric-string-udf-for-get-numeric-numbers-only/" rel="noreferrer">Reference</a></strong></p>
16,908,084
Bash script to calculate time elapsed
<p>I am writing a script in bash to calculate the time elapsed for the execution of my commands, consider:</p> <pre><code>STARTTIME=$(date +%s) #command block that takes time to complete... #........ ENDTIME=$(date +%s) echo "It takes $($ENDTIME - $STARTTIME) seconds to complete this task..." </code></pre> <p>I guess my logic is correct however I end up with the following print out:</p> <p>"It takes seconds to complete this task..."</p> <p>Anything wrong with my string evaluation?</p> <p>I believe bash variables are untyped, I would love if there is a "string to integer" method in bash nevertheless.</p>
16,908,239
11
1
null
2013-06-04 00:41:27.847 UTC
37
2022-07-30 08:49:34.39 UTC
2018-06-14 23:06:10.543 UTC
null
6,862,601
null
175,296
null
1
153
linux|bash|shell
149,535
<p>Either <code>$(())</code> or <code>$[]</code> will work for computing the result of an arithmetic operation. You're using <code>$()</code> which is simply taking the string and evaluating it as a command. It's a bit of a subtle distinction. Hope this helps.</p> <p>As tink pointed out in the comments on this answer, <code>$[]</code> is deprecated, and <code>$(())</code> should be favored.</p>
4,228,261
Understanding the purpose of some assembly statements
<p>I am trying to understand some assembly code and managed to finish most of it except a few lines. I am able to understand most of what is happening inside but am not able to fully understand what (and why it) is happening at the beginning and ending of the code. Can someone shed some light on this?</p> <pre><code>int main() { int a, b; a = 12; b = 20; b = a + 123; return 0; } </code></pre> <p>Disassembled Version:</p> <pre><code> 8048394:8d 4c 24 04 lea 0x4(%esp),%ecx ; ?? 8048398:83 e4 f0 and $0xfffffff0,%esp ; ?? 804839b:ff 71 fc pushl -0x4(%ecx) ; ?? 804839e:55 push %ebp ; Store the Base pointer 804839f:89 e5 mov %esp,%ebp ; Initialize the Base pointer with the stack pointer 80483a1:51 push %ecx ; ?? 80483a2:83 ec 4c sub $0x4c,%esp ; ?? 80483a5:c7 45 f8 0c 00 00 00 movl $0xc,-0x8(%ebp) ; Move 12 into -0x8(%ebp) 80483ac:c7 45 f4 14 00 00 00 movl $0x14,-0xc(%ebp) ; Move 20 into -0xc(%ebp) 80483b3:8b 45 f8 mov -0x8(%ebp),%eax ; Move 12@-0x8(%ebp) into eax 80483b6:83 c0 7b add $0x7b,%eax ; Add 123 to 12@eax 80483b9:89 45 f4 mov %eax,-0xc(%ebp) ; Store the result into b@-0xc(%ebp) 80483bc:b8 00 00 00 00 mov $0x0,%eax ; Move 0 into eax 80483c1:83 c4 10 add $0x10,%esp ; ?? 80483c4:59 pop %ecx ; ?? 80483c5:5d pop %ebp ; ?? 80483c6:8d 61 fc lea -0x4(%ecx),%esp ; ?? </code></pre>
4,228,936
2
5
null
2010-11-19 18:39:54.263 UTC
18
2015-07-08 14:37:42.373 UTC
2010-11-19 18:43:32.27 UTC
null
459,640
null
184,046
null
1
11
c|assembly|x86
17,023
<p>The stack grows <strong>downward</strong>. A <code>push</code> subtracts from the stack pointer (esp) and a <code>pop</code> adds to esp. You have to keep that in mind to understand a lot of this.</p> <pre><code>8048394:8d 4c 24 04 lea 0x4(%esp),%ecx ; ?? </code></pre> <p>lea = Load Effective Address</p> <p>This saves the address of the thing that lies 4 bytes into the stack. Since this is 32 bit (4 byte word) x86 code that means the second item on the stack. Since this is the code of a function (main in this case) the 4 bytes that are at the top of the stack is the return address.</p> <pre><code>8048398:83 e4 f0 and $0xfffffff0,%esp ; ?? </code></pre> <p>This code makes sure that the stack is aligned to 16 bytes. After this operation esp will be less than or equal to what it was before this operation, so the stack may grow, which protects anything that might already be on the stack. This is sometimes done in <code>main</code> just in case the function is called with an unaligned stack, which can cause things to be really slow (16 byte is a cache line width on x86, I think, though 4 byte alignment is what is really important here). If main has a unaligned stack the rest of the program will too.</p> <pre><code> 804839b:ff 71 fc pushl -0x4(%ecx) ; ?? </code></pre> <p>Since ecx was loaded before as a pointer to the thing on the other side of the return address from the previous top of the stack, so since this has a -4 index this refers to back to the return address for the current function being pushed back to the top of the stack so that main can return normally. (Push is magic and seems to be able to both load and store from to different places in RAM in the same instruction).</p> <pre><code> 804839e:55 push %ebp ; Store the Base pointer 804839f:89 e5 mov %esp,%ebp ; Initialize the Base pointer with the stack pointer 80483a1:51 push %ecx ; ?? 80483a2:83 ec 4c sub $0x4c,%esp ; ?? </code></pre> <p>This is mostly the standard function prologue (the previous stuff was special for main). This is making a stack frame (area between ebp and esp) where local variables can live. ebp is pushed so that the old stack frame can be restored in the epilogue (at the end of the current function).</p> <pre><code>80483a5:c7 45 f8 0c 00 00 00 movl $0xc,-0x8(%ebp) ; Move 12 into -0x8(%ebp) 80483ac:c7 45 f4 14 00 00 00 movl $0x14,-0xc(%ebp) ; Move 20 into -0xc(%ebp) 80483b3:8b 45 f8 mov -0x8(%ebp),%eax ; Move 12@-0x8(%ebp) into eax 80483b6:83 c0 7b add $0x7b,%eax ; Add 123 to 12@eax 80483b9:89 45 f4 mov %eax,-0xc(%ebp) ; Store the result into b@-0xc(%ebp) 80483bc:b8 00 00 00 00 mov $0x0,%eax ; Move 0 into eax </code></pre> <p>eax is where integer function return values are stored. This is setting up to return 0 from main.</p> <pre><code>80483c1:83 c4 10 add $0x10,%esp ; ?? 80483c4:59 pop %ecx ; ?? 80483c5:5d pop %ebp ; ?? 80483c6:8d 61 fc lea -0x4(%ecx),%esp ; ?? </code></pre> <p>This is the function epilogue. It is more difficult to understand because of the weird stack alignment code at the beginning. I'm having a little bit of trouble figuring out why the stack is being adjusted by a lower amount this time than in the prologue, though.</p> <p>It if obvious that this particular code was not compiled with optimizations on. If it were there probably wouldn't be much there since the compiler can see that even if it did not do the math listed in your <code>main</code> the end result of the program is the same. With programs that do actually do something (have side effects or results) it sometimes easier to read lightly optimized code (-O1 or -0s arguments to gcc).</p> <p>Reading assembly generated by a compiler is often much easier for functions that aren't <code>main</code>. If you want to read to understand the code then write yourself a function that takes some arguments to produce a result or that works on global variables, and you will be able to understand it better.</p> <p>Another thing that will probably help you is to just have gcc generate the assembly files for you, rather than disassembling them. The <code>-S</code> flag tells it to generate this (but not to generate other files), and names the assembly files with a <code>.s</code> on the end. This should be easier for you to read than the disassembled versions.</p>
4,731,774
How to Read / Improve C.R.A.P Index Calculated by PHP
<p>I just started working with PHPUnit and its colorful code coverage reports. I understand all the numbers and percentages save one: The C.R.A.P index. Can anyone offer me a solid explanation of what it means, how to analyze it and how to lower it?</p>
4,733,574
2
0
null
2011-01-19 04:36:23.963 UTC
39
2018-05-24 09:42:43.477 UTC
2013-09-12 02:56:51.217 UTC
null
385,273
null
122,164
null
1
76
php|unit-testing|phpunit
17,621
<p><a href="https://stackoverflow.com/a/4731869/5441">@Toader Mihai offered a solid explanation.</a> (+1 from me)</p> <h2>How to lower it:</h2> <p>Write less complex code OR write better tested code. (See the graph below)</p> <p><strong>Better tested Code ?</strong></p> <p>In this context this just means: A higher code coverage and usually results in writing more tests.</p> <p><strong>Less complex code ?</strong></p> <p>For example: Refactor your methods into smaller ones:</p> <pre><code>// Complex function doSomething() { if($a) { if($b) { } if($c) { } } else { if($b) { } if($c) { } } } // 3 less complex functions function doSomething() { if($a) { doA(); } else { doNotA(); } } function doA() { if($b) { } if($c) { } } function doNotA() { if($b) { } if($c) { } } </code></pre> <p>(just a trivial example, you'll find more resources for that i'm sure)</p> <h2>Additional resources:</h2> <p>First off let me provide some additional resources: </p> <p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=210575" rel="noreferrer">Creators blog post about the crap index</a></p> <p>just in case: <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">Cyclomatic complexity explained</a>. Tools like PHP_CodeSniffer and PHPMD will tell you that number in case you want to know.</p> <p>And while it is for you to decide what number is "ok" one often suggested number (that is a litte high imho) is a crap index of <strong>30</strong> resulting in a Graph like this:</p> <p><img src="https://i.stack.imgur.com/x3XAY.png" alt="alt text"> (You can get the .ods file here: <a href="https://www.dropbox.com/s/3bihb9thlp2fyg8/crap.ods?dl=1" rel="noreferrer">https://www.dropbox.com/s/3bihb9thlp2fyg8/crap.ods?dl=1</a> )</p>
41,511,587
JavaScript error: Cannot read property 'includes' of undefined
<p>I want to check if a <code>data.objectId</code> already exists in the array <code>msgArr</code>. For that I am running the code below:</p> <pre><code>var exists = msgArr.objectId.includes(data.objectId); if(exists === false){ msgArr.push({"objectId":data.objectId,"latLont":data.latLont,"isOnline":data.isOnline}); } </code></pre> <p>The array looks like the following:</p> <pre><code>var msgArr = [ {isOnline:true,latLont:"123",objectId:"on0V04v0Y9"}, {isOnline:true,latLont:"1",objectId:"FpWBmpo0RY"}, {isOnline:true,latLont:"48343",objectId:"Qt6CRXQuqE"} ] </code></pre> <p>I am getting the error below:</p> <blockquote> <p>Cannot read property 'includes' of undefined</p> </blockquote>
41,511,712
3
6
null
2017-01-06 18:02:43.767 UTC
4
2019-08-08 18:09:11.837 UTC
2019-08-08 18:09:11.837 UTC
null
1,264,804
null
6,287,404
null
1
8
javascript|typescript|ecmascript-6
82,156
<p>As the comments say: the javascript array object has no property <code>objectId</code>.<br> Looking at the objects in this array it's clear that they have it, so to check if a certain element exists you can do so using <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some" rel="noreferrer">Array.prototype.some</a> method:</p> <pre><code>var exists = msgArr.some(o =&gt; o.objectId === data.objectId); </code></pre>
41,272,257
mcrypt is deprecated, what is the alternative?
<p>The mcrypt-extension is <a href="http://php.net/manual/en/migration71.deprecated.php#migration71.deprecated.ext-mcrypt" rel="noreferrer">deprecated</a> will be removed in PHP 7.2 according to the comment posted <a href="https://bugs.php.net/bug.php?id=73734" rel="noreferrer">here</a>. So I am looking for an alternative way to encrypt passwords.</p> <p>Right now I am using something like</p> <pre><code>mcrypt_encrypt(MCRYPT_RIJNDAEL_128, md5($key, true), $string, MCRYPT_MODE_CBC, $iv) </code></pre> <p>I need your opinion for the best/strongest way to encrypt passwords, the encrypted password should of course supported by PHP 7.xx and should also be decryptable because my customers do want to have an option to 'recover' their passwords without generating a new one. </p>
41,272,680
10
11
null
2016-12-21 21:34:12.417 UTC
30
2020-08-18 13:15:45.377 UTC
2018-01-05 11:06:31.01 UTC
null
55,075
null
4,977,904
null
1
118
php|encryption|passwords|php-7|mcrypt
194,413
<p>It's best practice to hash passwords so they are not decryptable. This makes things slightly more difficult for attackers that may have gained access to your database or files.</p> <p>If you must encrypt your data and have it decryptable, a guide to secure encryption/decryption is available at <a href="https://paragonie.com/white-paper/2015-secure-php-data-encryption" rel="noreferrer">https://paragonie.com/white-paper/2015-secure-php-data-encryption</a>. To summarize that link:</p> <ul> <li>Use <a href="https://github.com/jedisct1/libsodium" rel="noreferrer">Libsodium</a> - A PHP extension</li> <li>If you can't use Libsodium, use <a href="https://github.com/defuse/php-encryption" rel="noreferrer">defuse/php-encryption</a> - Straight PHP code</li> <li>If you can't use Libsodium or defuse/php-encryption, use <a href="http://php.net/manual/en/book.openssl.php" rel="noreferrer">OpenSSL</a> - A lot of servers will already have this installed. If not, it can be compiled with --with-openssl[=DIR]</li> </ul>
41,596,121
Does VBA Have a Ternary Operator?
<p>I come from the beautiful world of Obj C, which is based on the C programming language, and I've fallen in love with finding quirky ways to save space. However, I've looked through as much documentation as I can and I can't find anything juicy on VBA that will shorten this syntax:</p> <pre><code>If boolVar = True Then 'Do something Else 'Do nothing End If </code></pre> <p>In Obj C, and naturally C, I'm extremely familiar with doing this:</p> <pre><code>boolVar ? "Nope, tis false" : "Yup, tis true" </code></pre> <p>This is very similar to what most other languages use, some may use extra logical operators like <code>!=</code> or <code>==</code> but that leaves me optimistic. I may not have looked in the right places, if that's the case PLEASE <strong>let me know</strong> where you get your documentation.</p> <p>TLDR, can we shorten If/Then/Else to one line of code in VBA? <em>This is extremely handy</em> when the 'Do Somethings' are nothing more then setting another variable's single parameter, or enabling/disabling a button. </p>
41,596,160
3
13
null
2017-01-11 16:39:24.853 UTC
3
2020-01-28 10:22:54.867 UTC
2020-01-28 10:22:54.867 UTC
null
11,636,588
null
2,353,523
null
1
32
excel|vba
30,046
<pre><code>Sub test() Dim x As Long Dim y As Long y = 1 x = IIf(y = 1, 1, 2) End Sub </code></pre>
9,858,654
"ORA-00922: missing or invalid option" when creating tables
<p>I entered the following SQL commands in Oracle but it complained "ORA-00922: missing or invalid option"</p> <pre><code>CREATE TABLE Student ( StuID NUMBER(15), StuName VARCHAR2(50), Phone VARCHAR2(20), PRIMARY KEY (StuID)) CREATE TABLE Program ( ProCode VARCHAR2(12), ProTitle VARCHAR2(50), PRIMARY KEY (ProCode)) </code></pre> <p>WHY???</p>
9,859,157
3
9
null
2012-03-25 07:51:45.6 UTC
1
2021-08-12 01:52:14.14 UTC
2012-03-25 07:55:04.943 UTC
null
601,179
null
1,276,521
null
1
5
sql|oracle
59,067
<p>If you are using the dreaded HTML GUI (inside the browser) of OracleXE then that does not support running more than one statement. </p> <p>Use SQL Developer, SQL*Plus or any other GUI tool instead.</p>
10,238,826
CSS class and descendant selectors practices
<p>I would like to form a better understanding of when it is appropriate to use classes to target content as opposed to other available options, specifically, descendant selectors.</p> <p>In many cases, instead of using classes, it is possible to use descendant selectors to target the same elements. If the same thing can be accomplished in both ways, what is the logic between deciding an option ?</p> <p>Here are some example scenarios:</p> <p>1.</p> <p>a.</p> <pre><code>&lt;div class="main"&gt; &lt;div&gt; &lt;div&gt; /* target */ &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .main &gt; div &gt; div </code></pre> <p>b.</p> <pre><code>&lt;div class="main"&gt; &lt;div&gt; &lt;div class="content"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .content </code></pre> <p>2.</p> <p>a.</p> <pre><code>&lt;div class="main"&gt; &lt;div&gt; /* target */ &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div&gt; /* target */ &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .main &gt; div:first-child .main &gt; div:last-child </code></pre> <p>b.</p> <pre><code>&lt;div class="main"&gt; &lt;div class="content1"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="content2"&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .content1 .content2 </code></pre> <p>3.</p> <p>a.</p> <pre><code>&lt;div class="main"&gt; &lt;div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .main &gt; div div </code></pre> <p>b.</p> <pre><code>&lt;div class="main"&gt; &lt;div class="content"&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .content div </code></pre> <p>What is the logic between deciding to use classes or descendant selectors ?</p>
10,238,984
3
1
null
2012-04-20 00:48:37.667 UTC
8
2012-04-20 02:56:23.843 UTC
2012-04-20 00:56:00.873 UTC
null
825,789
null
1,343,020
null
1
8
html|css-selectors|css
13,979
<p>Descendant selectors allow you to avoid embedding class information in your html. This may be convenient when the wrapping block is a logical container. For example, if you have constructed a table using <code>div</code> tags and you have hundreds, or thousands, of rows you could potentially cut down your document size, and increase readability, by specifying a descendant style instead of specifying <code>class='...'</code> repeatedly.</p> <pre><code> &lt;div class='mytable'&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;!-- A LOT MORE ROWS --&gt; &lt;/div&gt; </code></pre> <p>The advantage of specifying a class is that you aren't tied to a particular ordering. It can be extremely frustrating having to alter your descendant tags each time you want to rearrange your view. The other nice thing about specifying a class is that when working with CSS, it's far easier to search for a specific class name than have to decipher your descendant blocks.</p> <p>To my knowledge, there aren't black &amp; white guidelines as far as when each is appropriate. Use your own discretion and consider the benefits/shortfalls of each as you design.</p>
9,989,785
Technique for carrying metadata to View Models with AutoMapper
<p>I use AutoMapper to map my domain objects to my view models. I have metadata in my domain layer, that I would like to carry over to the view layer and into ModelMetadata. (This metadata is not UI logic, but provides necessary information to my views). </p> <p>Right now, my solution is to use a separate MetadataProvider (independently of ASP.NET MVC), and use conventions to apply the relevant metadata to the ModelMetadata object via an AssociatedMetadataProvider. The problem with this approach is that I have to test for the same conventions when binding the ModelMetadata from the domain as I do with my AutoMapping, and it seems like there should be a way to make this more orthogonal. Can anyone recommend a better way to accomplish this?</p>
10,100,042
3
1
null
2012-04-03 08:35:34.143 UTC
17
2017-03-03 09:36:26.98 UTC
null
null
null
null
344,211
null
1
16
asp.net-mvc-3|asp.net-mvc-2|automapper|modelmetadata|modelmetadataprovider
5,308
<p>I use the approach below to automatically copy data annotations from my entities to my view model. This ensures that things like StringLength and Required values are always the same for entity/viewmodel.</p> <p>It works using the Automapper configuration, so works if the properties are named differently on the viewmodel as long as AutoMapper is setup correctly.</p> <p>You need to create a custom ModelValidatorProvider and custom ModelMetadataProvider to get this to work. My memory on why is a little foggy, but I believe it's so both server and client side validation work, as well as any other formatting you do based on the metadata (eg an asterix next to required fields).</p> <p>Note: I have simplified my code slightly as I added it below, so there may be a few small issues.</p> <p><strong>Metadata Provider</strong></p> <pre><code>public class MetadataProvider : DataAnnotationsModelMetadataProvider { private IConfigurationProvider _mapper; public MetadataProvider(IConfigurationProvider mapper) { _mapper = mapper; } protected override System.Web.Mvc.ModelMetadata CreateMetadata(IEnumerable&lt;Attribute&gt; attributes, Type containerType, Func&lt;object&gt; modelAccessor, Type modelType, string propertyName) { //Grab attributes from the entity columns and copy them to the view model var mappedAttributes = _mapper.GetMappedAttributes(containerType, propertyName, attributes); return base.CreateMetadata(mappedAttributes, containerType, modelAccessor, modelType, propertyName); } } </code></pre> <p><strong>Validator Provivder</strong></p> <pre><code>public class ValidatorProvider : DataAnnotationsModelValidatorProvider { private IConfigurationProvider _mapper; public ValidatorProvider(IConfigurationProvider mapper) { _mapper = mapper; } protected override System.Collections.Generic.IEnumerable&lt;ModelValidator&gt; GetValidators(System.Web.Mvc.ModelMetadata metadata, ControllerContext context, IEnumerable&lt;Attribute&gt; attributes) { var mappedAttributes = _mapper.GetMappedAttributes(metadata.ContainerType, metadata.PropertyName, attributes); return base.GetValidators(metadata, context, mappedAttributes); } } </code></pre> <p><strong>Helper Method Referenced in above 2 classes</strong></p> <pre><code>public static IEnumerable&lt;Attribute&gt; GetMappedAttributes(this IConfigurationProvider mapper, Type sourceType, string propertyName, IEnumerable&lt;Attribute&gt; existingAttributes) { if (sourceType != null) { foreach (var typeMap in mapper.GetAllTypeMaps().Where(i =&gt; i.SourceType == sourceType)) { foreach (var propertyMap in typeMap.GetPropertyMaps()) { if (propertyMap.IsIgnored() || propertyMap.SourceMember == null) continue; if (propertyMap.SourceMember.Name == propertyName) { foreach (ValidationAttribute attribute in propertyMap.DestinationProperty.GetCustomAttributes(typeof(ValidationAttribute), true)) { if (!existingAttributes.Any(i =&gt; i.GetType() == attribute.GetType())) yield return attribute; } } } } } if (existingAttributes != null) { foreach (var attribute in existingAttributes) { yield return attribute; } } } </code></pre> <p><strong>Other Notes</strong></p> <ul> <li>If you're using dependency injection, make sure your container isn't already replacing the built in metadata provider or validator provider. In my case I was using the Ninject.MVC3 package which bound one of them after creating the kernel, I then had to rebind it afterwards so my class was actually used. I was getting exceptions about Required only being allowed to be added once, took most of a day to track it down.</li> </ul>
10,046,027
Having trouble downloading Git archive tarballs from Private Repo
<p>I need the ability to download our application at specific tags, but I am unable to find a working solution for this. Downloading tarballs based on git tag seems promising but I am unable to get it working using Curl. I have tried the following but all I get back is the source for the github 404 page.</p> <pre><code>curl -sL https://github.com/$ACCOUNT/$PRIVATE_REPO/tarball/0.2.0.257m?login=$MY_USER_NAME&amp;token=$MY_TOKEN &gt; 0.2.0.257m.tar </code></pre>
10,053,425
3
2
null
2012-04-06 16:05:24.77 UTC
11
2015-05-29 15:02:32.373 UTC
2012-04-19 13:11:39.34 UTC
null
1,317,806
null
1,317,806
null
1
22
git|github
23,274
<p>For public repo, you have <a href="https://gist.github.com/758124" rel="nofollow noreferrer">this gist</a> listing some examples:</p> <pre><code>wget --no-check-certificate https://github.com/sebastianbergmann/phpunit/tarball/3.5.5 -O ~/tmp/cake_phpunit/phpunit.tgz </code></pre> <p>For a private repo, try passing your credential information in a post directive:</p> <pre><code>wget --quiet --post-data="login=${login}&amp;token=${token}" --no-check-certificate https://github.com/$ACCOUNT/$PRIVATE_REPO/tarball/0.2.0.257m </code></pre> <p>Or use a curl command as in SO question "<a href="https://stackoverflow.com/a/9329607/6309">git equivalent to <code>svn export</code> or github workaround</a>", also explained in great details in:<br> "<a href="https://gist.github.com/2288960" rel="nofollow noreferrer"><strong>A curl tutorial using GitHub's API</strong></a>".</p> <hr> <p>The <a href="https://stackoverflow.com/users/1317806/steven-jp">OP Steven Jp</a> reports having made the <code>curl</code> command work:</p> <blockquote> <p>The final curl command ended up looking something like this:</p> </blockquote> <pre><code>curl -sL --user "${username}:${password}" https://github.com/$account/$repo/tarball/$tag_name &gt; tarball.tar </code></pre> <p>(in multiple lines for readability)</p> <pre><code>curl -sL --user "${username}:${password}" https://github.com/$account/$repo/tarball/$tag_name &gt; tarball.tar </code></pre>
28,220,636
View SQLite database on device in Android Studio
<p>I am using the latest version of Android Studio. When I run my app on the emulator, I am able to view my database by going through:</p> <p><code>tools -&gt; Android Device Monitor -&gt; clicking on the emulator in the left panel -&gt; file explorer -&gt; data -&gt; data -&gt; com.project-name</code></p> <p>But this option isn't available when running my app on a device.</p> <p>I have checked related questions:</p> <ol> <li><a href="https://stackoverflow.com/questions/2877567/android-viewing-sqlite-databases-on-device">Android - viewing SQLite databases on device?</a> The most voted answer here suggests copying the database to SDcard, and it's even for eclipse.</li> <li><a href="https://stackoverflow.com/questions/4856210/access-sqlite-database-on-android-device">Access sqlite database on android device</a></li> </ol> <p>and these questions are from 2011 and 2010. Are there any plugins I can use or other external tools?</p>
33,233,232
5
6
null
2015-01-29 17:14:26.78 UTC
9
2021-10-12 01:49:51.363 UTC
2017-05-23 12:25:50.553 UTC
null
-1
null
2,058,547
null
1
22
android|sqlite|android-studio
59,718
<h1>Connect to Sqlite3 via ADB Shell</h1> <p>I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.</p> <p>Find all info here: <a href="http://developer.android.com/tools/help/adb.html#sqlite" rel="noreferrer">http://developer.android.com/tools/help/adb.html#sqlite</a></p> <p>1- Go to your platform-tools folder in a command prompt</p> <p>2- Enter the command <code>adb devices</code> to get the list of your devices</p> <pre><code>C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools&gt;adb devices List of devices attached emulator-xxxx device </code></pre> <p>3- Connect a shell to your device:</p> <pre><code>C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools&gt;adb -s emulator-xxxx shell </code></pre> <p>4- Navigate to the folder containing your db file: </p> <pre><code>cd data/data/&lt;your-package-name&gt;/databases/ </code></pre> <p>5- run sqlite3 to connect to your db:</p> <pre><code>sqlite3 &lt;your-db-name&gt;.db </code></pre> <p>6- run sqlite3 commands that you like eg:</p> <pre><code>Select * from table1 where ...; </code></pre> <blockquote> <p><strong>Note:</strong> Find more commands to run below.</p> </blockquote> <h1>SQLite cheatsheet</h1> <p>There are a few steps to see the tables in an SQLite database:</p> <ol> <li><p>List the tables in your database:</p> <pre><code>.tables </code></pre></li> <li><p>List how the table looks:</p> <pre><code>.schema tablename </code></pre></li> <li><p>Print the entire table:</p> <pre><code>SELECT * FROM tablename; </code></pre></li> <li><p>List all of the available SQLite prompt commands:</p> <pre><code>.help </code></pre></li> </ol> <p>Source : <a href="https://stackoverflow.com/a/18280430/3913366">This</a> SO answer..</p>
11,787,558
SQL Injection attack - What does this do?
<p>I have detected some failed SQL injection attacks on my website. The failed queries are of the form:</p> <blockquote> <p><code>SELECT 6106 FROM(SELECT COUNT(*),':sjw:1:ukt:1'x FROM information_schema.tables GROUP BY x)</code></p> </blockquote> <p>The <code>':sjw:1:ukt:1'</code> part is specially constructed with variables concatenated together to give random 0s or 1s etc.</p> <p>I would like to know what these queries do?</p> <p>The database is MySQL.</p> <p><strong>Update:</strong> Here is the original injected SQL:</p> <pre><code>(SELECT 6106 FROM (SELECT COUNT(*), CONCAT( CHAR(58, 115, 106, 119, 58), (SELECT ( CASE WHEN ( 6106 = 6106 ) THEN 1 ELSE 0 END )), CHAR(58, 117, 107, 116, 58), FLOOR(RAND(0) * 2) ) x FROM INFORMATION_SCHEMA.TABLES GROUP BY x)a) </code></pre> <p>It fails with message</p> <blockquote> <p>Duplicate entry ':sjw:1:ukt:1' for key 'group_key'</p> </blockquote>
19,620,164
3
3
null
2012-08-03 00:07:03.287 UTC
9
2014-03-28 15:38:00.983 UTC
2014-03-28 15:38:00.983 UTC
null
177,663
null
219,564
null
1
14
mysql|security|sql-injection
9,508
<h2>What the attack really does</h2> <p>There is a subtle but clever detail about this attack that other answerers missed. Notice the error message <code>Duplicate entry ':sjw:1:ukt:1' for key 'group_key'</code>. The string <code>:sjw:1:ukt:1</code> is actually the result of an expression evaluated by your MySQL server. If your application sends the MySQL error string back to the browser, then the <strong>error message can leak data</strong> from your database.</p> <p>This kind of attack is used in cases where the query result isn't otherwise sent back to the browser (blind SQL injection), or when a classical UNION SELECT attack is complicated to pull off. It also works in INSERT/UPDATE/DELETE queries.</p> <p>As Hawili notes, the original particular query wasn't supposed leak any information, it was just a test to see whether your application is vulnerable to this kind of injection.</p> <p>The attack <em>didn't</em> fail like MvG suggested, causing this error is the purpose of the query.</p> <p>A better example of how this may be used:</p> <pre><code>&gt; SELECT COUNT(*),CONCAT((SELECT CONCAT(user,password) FROM mysql.user LIMIT 1), &gt; 0x20, FLOOR(RAND(0)*2)) x &gt; FROM information_schema.tables GROUP BY x; ERROR 1062 (23000): Duplicate entry 'root*309B17546BD34849D627A4DE183D3E35CD939E68 1' for key 'group_key' </code></pre> <h2>Why the error is raised</h2> <p>Why the query causes this error in MySQL is somewhat of a mystery for me. It looks like a MySQL bug, since GROUP BY is supposed to deal with duplicate entries by aggregating them. Hawili's simplification of the query doesn't, in fact, cause the error!</p> <p>The expression <code>FLOOR(RAND(0)*2)</code> gives the following results in order, based on the random seed argument 0:</p> <pre><code>&gt; SELECT FLOOR(RAND(0)*2)x FROM information_schema.tables; +---+ | x | +---+ | 0 | | 1 | | 1 | &lt;-- error happens here | 0 | | 1 | | 1 | ... </code></pre> <p>Because the 3rd value is a duplicate of the 2nd, this error is thrown. Any FROM table with at least 3 rows can be used, but information_schema.tables is a common one. The COUNT(*) and GROUP BY parts are necessary to provoke the error in MySQL:</p> <pre><code>&gt; SELECT COUNT(*),FLOOR(RAND(0)*2)x FROM information_schema.tables GROUP BY x; ERROR 1062 (23000): Duplicate entry '1' for key 'group_key' </code></pre> <p>This error doesn't occur in the PostgreSQL-equivalent query:</p> <pre><code># SELECT SETSEED(0); # SELECT COUNT(*),FLOOR(RANDOM()*2)x FROM information_schema.tables GROUP BY x; count | x -------+--- 83 | 0 90 | 1 </code></pre> <p>(Sorry about answering 1 year late, but I just stumbled upon this today. This question is interesting to me because I wasn't aware there are ways to leak data via error messages from MySQL)</p>
11,743,809
How can a border be set around multiple cells in excel using C#
<p>I am working on a project that creates excel files.</p> <p>I am having trouble placing a border on multiple cells to organize the excel file. </p> <p>Let's say I want a border from cell B5 to B10. There shouldn't be borders between B5, B6, B7,...</p> <p>Currently, I have this code: </p> <pre><code>workSheet_range = worksheet.get_Range("B5", "B10"); workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb(); </code></pre> <p>It makes the borders, however it places a border around every cell instead of one big border for all cells. </p> <p>How can I accomplish this? </p>
11,744,272
8
1
null
2012-07-31 15:37:13.2 UTC
1
2020-06-14 15:07:52.473 UTC
2015-08-07 22:14:42.36 UTC
null
2,940,627
null
1,565,785
null
1
14
c#|excel|border
61,592
<p>You need to individually set these</p> <pre><code>.Borders[Excel.XlBordersIndex.xlEdgeBottom] .Borders[Excel.XlBordersIndex.xlEdgeRight] .Borders[Excel.XlBordersIndex.xlEdgeLeft] .Borders[Excel.XlBordersIndex.xlEdgeTop] </code></pre>
12,018,681
Android TLS connection and self signed certificate
<p>I'm trying to connect to a node.js based TLS server from my Android app. Naturally it fails becouse I'm using a self-signed certificate.</p> <p>Is there anyway I can just add the certificate to my app and have Android trust it somehow? Note, I'm not using HTTPS, this is a TLS over TCP connection.</p>
12,150,903
2
0
null
2012-08-18 12:45:02.137 UTC
10
2016-01-20 02:14:26.757 UTC
null
null
null
null
636,967
null
1
17
android|ssl
16,962
<p>After a lot of reading around, I came up with an answer.</p> <p>A pretty good guide is here: <a href="http://nelenkov.blogspot.no/2011/12/using-custom-certificate-trust-store-on.html" rel="noreferrer">http://nelenkov.blogspot.no/2011/12/using-custom-certificate-trust-store-on.html</a></p> <p>Now, since I'm not using HTTPS, I had to come up with a slightly different approach for getting a clean SSL socket with the new keystore:</p> <pre><code>KeyStore store = KeyStore.getInstance("BKS"); InputStream truststore = mainActivity.getResources().openRawResource(R.raw.trust); store.load(truststore, "PASSWORD".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); tmf.init(store); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), new SecureRandom()); Socket socket = context.getSocketFactory().createSocket(ip, port); </code></pre>
11,801,278
Accessing Meteor production database
<p>To check out what's in the (production) database for <code>blah.meteor.com</code> I thought we would just do:</p> <pre><code>meteor mongo --url http://blah.meteor.com/ </code></pre> <p>But instead I get a URI:</p> <pre><code>mongodb://client:984dae4c-04fb-c8bb-68f6-ed83602435cc@skybreak.member1.mongolayer.com:27017/blah_meteor_com </code></pre> <p>How would I use this URI to access the db?</p>
11,801,719
3
0
null
2012-08-03 18:28:09.427 UTC
27
2017-08-02 07:06:43.697 UTC
2017-09-22 17:57:57.377 UTC
null
-1
null
594,601
null
1
44
mongodb|meteor|production|database
36,280
<p>You should use <code>meteor mongo http://blah.meteor.com</code>; or even shorter <code>meteor mongo blah.meteor.com</code>.</p> <p>For documentation you can run <code>meteor help mongo</code>. Extract from running the help command above:</p> <blockquote> <p>Instead of opening a shell, specifying --url (-U) will return a URL suitable for an external program to connect to the database. For remote databases on deployed applications, the URL is valid for one minute.</p> </blockquote> <p>So what it's saying is, the url provided by running the command with the <code>--url</code> option is for connecting to the database by some external application, i.e. other than <code>meteor</code>.</p> <p><strong>UPDATE:</strong></p> <p>When you connect to MongoDB, you should get a greeting message similar to this:</p> <pre><code>MongoDB shell version: 2.0.2 connecting to: skybreak.member1.mongolayer.com:27017/userdb_meteor_com </code></pre> <p>Enter the following command: <code>use userdb_meteor_com</code> (where <strong>userdb_meteor_com</strong> is taken from the URL in the greeting message above).</p> <p>To see your collections (usually they refer to collections created in your Meteor app): <code>show collections</code>. You should get something like this:</p> <pre><code>system.indexes system.users users </code></pre> <p>Now you can run usual commands, e.g.: <code>db.users.find({});</code>.</p>
19,962,608
Javascript character count
<p>Example here: <a href="http://jsfiddle.net/67XDq/1/" rel="noreferrer">http://jsfiddle.net/67XDq/1/</a></p> <p>I have the following HTML:</p> <pre><code>&lt;tr id="rq17"&gt; &lt;td class='qnum'&gt;17.&lt;/td&gt; &lt;td class='qtext'&gt;Questions? &lt;i&gt;Maximum of 500 characters - &lt;input style="color:red;font-size:12pt;font-style:italic;" readonly type="text" name="q17length" size="3" maxlength="3" value="500"&gt; characters left&lt;/i&gt;&lt;br/&gt; &lt;textarea onKeyDown="textCounter(document.frmSurvey.q17,document.frmSurvey.q17length,500);" onKeyUp="textCounter(document.frmSurvey.q17,document.frmSurvey.q17length,500)" class="scanwid" name="q17" id="q17" rows="5" cols=""&gt; &lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>And the following Javascript:</p> <pre><code>function textCounter(field,cntfield,maxlimit) { if (field.value.length &gt; maxlimit) // if too long...trim it! field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter else cntfield.value = maxlimit - field.value.length; } </code></pre> <p>For some reason, which I am completely missing, this doesn't seem to be working as intended.</p> <p>It should limited the number of characters in the <code>textarea</code> and also countdown the number within the <code>label</code> but it is doing neither.</p>
19,962,742
4
5
null
2013-11-13 19:26:13.143 UTC
4
2019-02-14 22:17:40.71 UTC
2013-11-13 19:31:14.36 UTC
null
322,131
null
322,131
null
1
6
javascript|html|character
46,604
<p>There are two issues in the fiddle</p> <ul> <li>no form element</li> <li>script mode was onload, which means that window object didnt have <code>textCounter</code> function</li> </ul> <p>see updated fiddle <a href="http://jsfiddle.net/67XDq/7/" rel="nofollow noreferrer">http://jsfiddle.net/67XDq/7/</a>, markup:</p> <pre><code>&lt;tr id="rq17"&gt; &lt;td class='qnum'&gt;17.&lt;/td&gt; &lt;td class='qtext'&gt; Questions? &lt;i&gt;Maximum of 500 characters - &lt;input style="color:red;font-size:12pt;font-style:italic;" readonly="readonly" type="text" id='q17length' name="q17length" size="3" maxlength="3" value="500" /&gt; characters left&lt;/i&gt; &lt;br /&gt; &lt;textarea onKeyDown="textCounter(this,'q17length',500);" onKeyUp="textCounter(this,'q17length',500)" class="scanwid" name="q17" id="q17" rows="5" cols=""&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>and code</p> <pre><code>function textCounter(field, cnt, maxlimit) { var cntfield = document.getElementById(cnt) if (field.value.length &gt; maxlimit) // if too long...trim it! field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter else cntfield.value = maxlimit - field.value.length; } </code></pre>
3,736,210
How to execute a shell script from C in Linux?
<p>How can I execute a shell script from C in Linux?</p>
3,736,607
6
0
null
2010-09-17 14:29:13.093 UTC
31
2017-07-20 15:34:05.28 UTC
null
null
null
null
218,471
null
1
69
c|linux|shell
142,921
<p>It depends on what you want to do with the script (or any other program you want to run).</p> <p>If you just want to run the script <a href="http://man7.org/linux/man-pages/man3/system.3.html" rel="noreferrer"><code>system</code></a> is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).</p> <p>If you want to either feed the shell script via its standard input or consume its standard output you can use <code>popen</code> (and <code>pclose</code>) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.</p> <p>Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.</p> <p>The system calls of interest are <code>fork</code>, <code>execve</code>, and <code>waitpid</code>. You may want to use one of the library wrappers around <code>execve</code> (type <code>man 3 exec</code> for a list of them). You may also want to use one of the other wait functions (<code>man 2 wait</code> has them all). Additionally you may be interested in the system calls <code>clone</code> and <code>vfork</code> which are related to fork.</p> <p><code>fork</code> duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.</p> <p><code>execve</code> replaces the current program with a new program (keeping the same process id).</p> <p><code>waitpid</code> is used by a parent process to wait on a particular child process to finish.</p> <p>Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.</p> <p>You may also be interested in the <code>pipe</code> and <code>dup2</code> system calls. <code>pipe</code> creates a pipe (with both an input and an output file descriptor). <code>dup2</code> duplicates a file descriptor as a specific file descriptor (<code>dup</code> is similar but duplicates a file descriptor to the lowest available file descriptor).</p>
3,354,330
Difference between string and text in rails?
<p>I'm making a new web app using Rails, and was wondering, what's the difference between <code>string</code> and <code>text</code>? And when should each be used?</p>
3,354,452
9
0
null
2010-07-28 15:15:33.407 UTC
99
2020-10-22 04:59:03.333 UTC
2012-01-13 23:06:17.033 UTC
null
71,421
null
218,183
null
1
475
ruby-on-rails
215,392
<p>The difference relies in how the symbol is converted into its respective column type in query language.</p> <blockquote> <p>with MySQL :string is mapped to VARCHAR(255)</p> <ul> <li><a href="https://edgeguides.rubyonrails.org/active_record_migrations.html" rel="noreferrer">https://edgeguides.rubyonrails.org/active_record_migrations.html</a></li> </ul> </blockquote> <pre><code>:string | VARCHAR | :limit =&gt; 1 to 255 (default = 255) :text | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit =&gt; 1 to 4294967296 (default = 65536) </code></pre> <p>Reference:</p> <blockquote> <p><a href="https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/" rel="noreferrer">https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/</a></p> </blockquote> <p><strong>When should each be used?</strong></p> <p>As a general rule of thumb, use <code>:string</code> for short text input (username, email, password, titles, etc.) and use <code>:text</code> for longer expected input such as descriptions, comment content, etc.</p>