pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
787,436
0
How to set width to 100% in WPF <p>Is there any way how to tell component in <strong>WPF</strong> to take 100% of available space? </p> <p>Like </p> <pre><code>width: 100%; </code></pre> <p>in CSS </p> <p>I've got this XAML, and I don't know how to force Grid to take 100% width.</p> <pre><code>&lt;ListBox Name="lstConnections"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid Background="LightPink"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>Result looks like </p> <p><img src="http://foto.darth.cz/pictures/wpf_width.jpg" alt="alt text"></p> <p>I made it pink so it's obvious how much space does it take. I need to make the pink grid 100% width.</p>
36,447,203
0
<p>If you don't mind losing all the data, you can run </p> <pre><code>rake db:drop </code></pre> <p>BIG CAVEAT - this will delete your database and all your data.</p> <p>Then you can run</p> <pre><code>rake db:create db:migrate </code></pre> <p>If this is a new app, exists solely on your localhost i.e. has not been deployed to production, and you don't mind losing all your data, then this option is fine.</p> <p>Generally, I would recommend not amending your migrations but creating new ones to change column names etc.</p>
32,014,132
0
<p>Yes, multiple directives creating their own isolate and/or child scopes (both could require <code>scope: true</code>, though) is not allowed, which is unfortunate, if only because with <code>scope: {}</code> binding to attributes is so effortless.</p> <p>But, you could still achieve the same result by doing a bit more manual work and using the <code>$parse</code> service. Here's an illustrative example of how to achieve two-way binding:</p> <pre><code>.directive("foo", function($parse){ return { restrict: "A", link: function(scope, element, attrs){ var fooGetFn = $parse(attrs.foo), fooSetFn = fooGetFn.assign; var foo0 = fooGetFn(scope); // get the current value of foo expression // watch for changes in foo expression scope.$watch( function(){ return fooGetFn(scope); }, function fooWatchAction(newVal, oldVal){ // do whatever needed }); // set value to foo expression, if it's assignable if (fooSetFn) fooSetFn(scope, "abc"); } } }); </code></pre> <p>You could do the same with <code>bar</code> and have them working side-by-side:</p> <pre><code>&lt;div foo="vm.p1" bar="vm.p2"&gt; </code></pre> <p>In your specific case, you don't even need to assign the value back since you are only assigning to properties of the bound object (which you only need to get), so it is simpler.</p> <p>Here's your forked <strong><a href="http://jsfiddle.net/7an9dc9o/" rel="nofollow">fiddle</a></strong> that works.</p>
24,411,388
0
<p>Since a list comprehension definitionally generates another list, you can't use it to generate a single value. The aren't <em>for</em> that. (Well... there is <a href="http://stackoverflow.com/a/16632125/12779">this nasty trick</a> that uses a leaked implementation detail in old versions of python that can do it. I'm not even going to copy the example code here. Don't do this.)</p> <p>If you're worried about the stylistic aspects of <code>reduce()</code> and its ilk, don't be. Name your reductions and you'll be fine. So while:</p> <pre><code>all_union = reduce(lambda a, b: a.union(b), L[1:], L[0]) </code></pre> <p>isn't great, this:</p> <pre><code>def full_union(input): """ Compute the union of a list of sets """ return reduce(lambda a, b: a.union(b), input[1:], input[0]) result = full_union(L) </code></pre> <p>is pretty clear.</p> <p>If you're worried about <em>speed,</em> check out the <a href="https://pypi.python.org/pypi/toolz/" rel="nofollow">toolz</a> and <a href="https://pypi.python.org/pypi/cytoolz/0.6.1" rel="nofollow">cytoolz</a> packages, which are 'fast' and 'insanely fast,' respectively. On large datasets, they'll often let you avoid processing your data more than once or loading the whole set in memory at once, in contrast to list comprehensions.</p>
11,395,304
0
How to call the callback in a CakePhp Component? <p>I'm using CakePhp 2.2 and I have this simple controller, named <strong>ProvidersController</strong>:</p> <pre><code>&lt;?php class ProvidersController extends AppController { public $components = array('Session', 'Social'); public $layout = false; public function facebook(){ $this-&gt;Social-&gt;auth('facebook', 'success', 'error'); $this-&gt;render(false); } public function google(){ $this-&gt;Social-&gt;auth('google', 'success', 'error'); $this-&gt;render(false); } private function success(){ } private function error(){ } } ?&gt; </code></pre> <p>and this Component, named <strong>SocialComponent</strong>:</p> <pre><code>&lt;?php class SocialComponent extends Component { public function auth($provider, $success, $error){ } } ?&gt; </code></pre> <p>as you can see I have created success() and error() methods inside the controller. Now I pass these names and I would like to call them back from the component.</p> <p>I only pass the name of the callback, how to call them from the component?</p> <p>Thank you!</p>
30,150,872
0
<p>Here's the basic pattern, see comments:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// === Projectile // The constructor function Projectile(x, y) { // Do things to initialize instances... this.x = x; this.y = y; } // Add some methods to its prototype Projectile.prototype.update = function() { // This is a method on `Projectile` snippet.log("Projectile#update"); }; Projectile.prototype.checkIfWallHit = function(){ snippet.log("Projectile#checkIfWallHit"); }; // ==== BasicShot // The constructor function BasicShot(x, y, left) { // Give Projectile a chance to do its thing Projectile.call(this, x, y); this.left = left; } // Hook it up to `Projectile` BasicShot.prototype = Object.create(Projectile.prototype); BasicShot.prototype.constructor = BasicShot; // JavaScript does this by default, so let's maintain it when replacing the object // Add methods to its prototype BasicShot.prototype.update = function() { snippet.log("BasicShot#update"); }; // === Usage snippet.log("Using Projectile"); var p = new Projectile(1, 2); p.update(); // Projectile#update p.checkIfWallHit(); // Projectile#checkIfWallHit snippet.log("Using BasicShot"); var c = new BasicShot(1, 2, 3); c.update(); // BasicShot#update p.checkIfWallHit(); // Projectile#checkIfWallHit</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --&gt; &lt;script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <p>As of ES6, the next version of JavaScript, that gets a <strong>lot</strong> simpler:</p> <pre><code>// REQUIRES ES6!! class Projectile { constructor(x, y) { this.x = x; this.y = y; } update() { snippet.log("Projectile#update"); } checkIfWallHit() { snippet.log("Projectile#checkIfWallHit"); } }; class BasicShot extends Projectile { constructor(x, y, left) { super(x, y); this.left = left; } update() { snippet.log("BasicShot#update"); } } </code></pre> <p>It does the same thing as first example above under the covers, the new syntax is just syntactic sugar. But it's really good sugar.</p>
15,481,081
0
<pre><code>iframe.style.visibility="hidden"; </code></pre> <p>and to show it:</p> <pre><code>iframe.style.visibility="visible"; </code></pre> <p>Edit: And you can use the onsubmit="JavaScriptCode" event to trigger the change.</p> <p>Reference: <a href="http://www.w3schools.com/jsref/event_form_onsubmit.asp" rel="nofollow">http://www.w3schools.com/jsref/event_form_onsubmit.asp</a></p>
2,343,990
0
<p>Localization can be made quite simple in .NET or as complex as you like.</p> <p>The simpler way, would be to create localized resource DLL's for each supported language, and then set the <code>CultureInfo.CurrentUICulture</code> for the user's selected, or detected, language, falling back to a default (preferably English) in case the language isn't supported.</p> <p>And set up a watcher in case the of a language change.</p> <p>Some programs requires to reload, others simply to repaint (as it seems the case with the sample you provided).</p>
16,605,176
0
how to separate one array into two, base on its id using jquery <p>Im strugling with this array:</p> <p>first id = 1</p> <p>items for the second id = 12,21,34,33; </p> <p>second id = 2</p> <p>items for the second id = 21,12,34</p> <p>It looks like this in my array : </p> <p>arr = [12 1,21 1,34 1,33 1,21 2,12 2,34 2]</p> <p>i want to store it like this:</p> <p>id | item_id</p> <p>1 12</p> <p>1 21</p> <p>1 34</p> <p>1 33</p> <p>2 21</p> <p>2 12</p> <p>2 34</p> <p>here's my code :</p> <p>var item_id = new Array();</p> <p>$("td.items").each(function() {</p> <p>if(this){</p> <p>item_id.push($(this).attr('id'));</p> <p>}</p> <p>});</p>
36,357,032
0
<p>If you just began, restart your project. If you want to build up a site, first check whether there are any core functions for your usage or not. If it can be done through them, do it like that, as this is better for updating your site. (Maybe your plugin will not be supported later on...)</p> <p>Then restart by building up your site: <br/> Category - Article - Menu <br/> Firstly, create the categories you wish. For example, you want the category "News" where you put news articles and a category "Events" where you put articles about your events.<br/> Secondly create some articles for your category. You can use the "read-more" to preview your articles in your blog.<br/> Last, create the menu. You can use a category blog and it's options to show your articles the way you want.</p>
15,396,003
0
<pre><code>public static double MinIsNumber(double[,] array) { return array.Cast&lt;double&gt;() .Where(n =&gt; !double.IsNaN(n)) .Min(); } </code></pre>
9,805,110
0
<p>I think the reason you found it difficult to find the source code is that <code>getcontext</code> and <code>setcontext</code> are (generally?) <strong>implemented in assembly</strong> than in C. Here are the source codes</p> <p><a href="http://www.koders.com/noncode/fid466DE9347BF79B388783D3F5D94BAF6748F618C9.aspx?s=readdir64" rel="nofollow">setcontext</a> and <a href="http://www.koders.com/noncode/fid62EE9446C4DEED004E74CD6D61D7C81435E413FE.aspx?s=queue" rel="nofollow">getcontext</a></p> <p>However, these assembly codes are not so easy to read. I think <code>man getcontext</code> is better. Anyways, good luck :)</p>
39,505,527
0
How to get current logged in user details in Twitter using API <p>I'm using Socialite to login using twitter and using Abrahams' TwitterOauth to make API working. In laravel, I've set API Key information as:</p> <pre><code>'twitter' =&gt; [ 'client_id' =&gt; '**************', 'client_secret' =&gt; '**************', 'access_token' =&gt; '***************', 'access_token_key' =&gt; '***************', 'redirect' =&gt; '***********', ], </code></pre> <p>To connect to Twitter I've used:</p> <pre><code>public function getTwitterConnection() { $this-&gt;connection = new TwitterOAuth(Config::get('services.twitter.client_id'), Config::get('services.twitter.client_secret'), Config::get('services.twitter.access_token'), Config::get('services.twitter.access_token_key')); } </code></pre> <p>Using Socialite, I'm able to make users login via their credentials. But while I try to access:</p> <pre><code>public function getCurrentLoggedInUser() { $this-&gt;getTwitterConnection(); return $this-&gt;connection-&gt;get("account/verify_credentials"); } </code></pre> <p>I'm getting the information of developer's twitter account i.e. mine. I think I'm not being able synchronize between Socialite and TwitterOauth. How can I fix this issue? Please suggest me the better way of getting the information of logged in user.</p>
31,916,340
0
<p><strong>Swift</strong></p> <pre><code>UIApplication.sharedApplication().networkActivityIndicatorVisible = true </code></pre> <p><strong>Swift 3, XCode 8</strong> (Thanks @sasho)</p> <p><code>UIApplication.shared.isNetworkActivityIndicatorVisible = true</code></p>
11,550,956
0
The correct way to set a default search value in CakePHP <p>I have a CakePHP Application with many many screens using data from a specific model. Most of the time, I need a specific field to be checked against (like the "user_active=>1" example in the cookbook), however I'd still like to be able to specify that field as a condition and override the default. My code works, but is this the best way to do this?</p> <p>Also, the $queryData field is mixed — what are the possibilities other than array? just NULL?</p> <pre><code>&lt;?php public function beforeFind($queryData) { if(is_array($queryData)) { //query data was an array if(!is_array($queryData['conditions'])) { $queryData['conditions'] = array('Course.semester_id'=&gt;SEMESTER_ID); } else if (!isset($queryData['conditions']['Course.semester_id'])) { $queryData['conditions']['Course.semester_id'] = SEMESTER_ID; } } } ?&gt; </code></pre>
9,662,439
0
<p>Try this <a href="https://github.com/gekitz/UIDevice-with-UniqueIdentifier-for-iOS-5" rel="nofollow">UIDevice-with-UniqueIdentifier-for-iOS-5</a>, it uses the device's <strong>mac address</strong> as unique identifier.</p>
6,970,217
0
<p>I have found the best way to regain syntax coloring is just to quit Xcode and re-launch it. I couldn't tell you why, but that works every time.</p>
34,371,499
0
<p>Alright three things here.</p> <p><strong>1.</strong> Your <code>res.end</code> is sending <code>Hell world</code> but it should send <code>data</code></p> <p><code>res.end("Hell World");</code></p> <p>should be</p> <p><code>res.end(data);</code></p> <p><em>This is because we want to display the index.html file not a hello world</em></p> <p><strong>2.</strong> Your index.html is calling the socket.io js file wrong</p> <p><code>&lt;script src="/node_modules/socket.io/socket.io.js"&gt;&lt;/script&gt;</code></p> <p>should be</p> <p><code>&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;</code></p> <p><em>This is because you cannot reference a file like that because there is no logic for it in your code. socket.io does however have the logic for it and can be called this way</em></p> <p><strong>3.</strong> Use emit on the client side</p> <p>In your index.html change this code</p> <p><code>socket.on('dataChanged', function(data){console.log("Hello World")});</code></p> <p>to </p> <p><code>socket.emit('dataChanged', 'this is a test')</code></p> <p>and remove </p> <p><code>io.emit('dataChanged', 'this is a test')</code></p> <p>from your nodejs file</p> <p><strong>Now you can see Hello World from your console</strong></p>
34,375,670
0
<p>According to <strong><a href="https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx" rel="nofollow">Composer docs</a></strong>:</p> <blockquote> <p>Note: On some versions of OSX the /usr directory does not exist by default. If you receive the error "/usr/local/bin/composer: No such file or directory" <strong>then you must create the directory manually</strong> before proceeding: mkdir -p /usr/local/bin.</p> </blockquote> <p>Hope this helps.</p>
10,023,924
0
<p>If you don't mind adding an extra step of selecting the camera roll from an album list you can try changing your sourceType from SavedPhotoAlbums to PhotoLibrary:</p> <pre><code>imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; </code></pre> <p>After selecting the desired album, the next photo selection view will show the most recent images at the bottom.</p>
35,614,007
0
<p><a href="https://en.wikipedia.org/wiki/Apache_Thrift" rel="nofollow">Apache Thrift</a> was designed to communicate with high efficiency. It was developed by Facebook (now open source), and an implementation is <a href="https://thrift.apache.org/lib/csharp" rel="nofollow">available for C#</a>.</p> <p><a href="https://developers.google.com/protocol-buffers/" rel="nofollow">Google developed</a> the highly efficient <a href="https://en.wikipedia.org/wiki/Protocol_Buffers" rel="nofollow">protocol buffers</a> serialization mechanism. Protocol buffers does not include RPC (remote procedure call) but can be used to send data over a variety of transport mechanisms. It is also <a href="https://www.nuget.org/packages/protobuf-net/" rel="nofollow">available for C#</a> (project by SO's own Marc Gravell).</p>
26,675,319
0
<p>you probably need to bind the context of the <code>resizeWindowFrame</code> function.</p> <pre><code>resizeMovieFrame: =&gt; </code></pre>
40,380,610
0
How to set up embedded WildFly server on the fly for testing with Maven <p>I have a question about how to set up an embedded Wildfly 10 server on the fly for integration testing.</p> <pre><code>&lt;!-- Loading Wildfly 10 on the fly and copy it into the target folder. --&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;unpack&lt;/id&gt; &lt;phase&gt;process-test-classes&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;unpack&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;org.wildfly&lt;/groupId&gt; &lt;artifactId&gt;wildfly-dist&lt;/artifactId&gt; &lt;version&gt;10.0.0.Final&lt;/version&gt; &lt;type&gt;zip&lt;/type&gt; &lt;overWrite&gt;false&lt;/overWrite&gt; &lt;outputDirectory&gt;target&lt;/outputDirectory&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.wildfly.plugins&lt;/groupId&gt; &lt;artifactId&gt;wildfly-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.1.0.Alpha1&lt;/version&gt; &lt;configuration&gt; &lt;jbossHome&gt;target/wildfly-10.0.0.Final&lt;/jbossHome&gt; &lt;hostname&gt;127.0.0.1&lt;/hostname&gt; &lt;!-- &lt;port&gt;9990&lt;/port&gt; --&gt; &lt;filename&gt;${project.build.finalName}.war&lt;/filename&gt; &lt;java-opts&gt; &lt;java-opt&gt;-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005&lt;/java-opt&gt; &lt;/java-opts&gt; &lt;commands&gt; &lt;command&gt;/subsystem=logging/file-handler=debug:add(level=DEBUG,autoflush=true,file={"relative-to"=&gt;"jboss.server.log.dir", "path"=&gt;"debug.log"})&lt;/command&gt; &lt;command&gt;/subsystem=logging/logger=org.jboss.as:add(level=DEBUG,handlers=[debug])&lt;/command&gt; &lt;/commands&gt; &lt;/configuration&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;version&gt;1.6.4&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;deploy&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;start-wildfly&lt;/id&gt; &lt;phase&gt;test-compile&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;run&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;shutdown-wildfly&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;shutdown&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>First Maven download the server on the fly, saves it to the target folder. Later I want to copy a new standalone.xml, start the server, run the integration test and stop the server.</p> <p>Until now I can't see that I have started the server.</p> <pre><code>------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.example.FunctionalTest Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.071 sec &lt;&lt;&lt; FAILURE! - in com.example.FunctionalTest basicPingTest(com.example.FunctionalTest) Time elapsed: 0.07 sec &lt;&lt;&lt; ERROR! java.net.ConnectException: Connection refused at com.example.FunctionalTest.basicPingTest(FunctionalTest.java:39) Results : Tests in error: FunctionalTest.basicPingTest:39 » Connect Connection refused Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 </code></pre> <p>Does anybody knows how to set up a Maven for start and stop a embedded Wildfly server, start the test cases and hopefully see some logging?</p>
6,635,674
0
CSS equivalent of <big> <p>What is the CSS equivalent of the <code>&lt;big&gt;</code> element? If I'm not mistaken then wrapping your text in the <code>&lt;big&gt;</code> element is not the same as setting a larger <code>font-size</code>.</p>
27,210,618
0
<p>You need to specify your definition of a week. </p> <h1>String Representation Of A Year-Week</h1> <p>One option is strings. The ISO 8601 standard <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow">defines a week</a> as beginning on a Monday, ending on Sunday, with the first week of the year being the first to contain a Thursday, resulting in 52 or 53 weeks a year. </p> <p>The standard also defines a string <a href="https://en.wikipedia.org/wiki/ISO_8601#Week_dates" rel="nofollow">representation for this week-of-year</a> span of time in the format of <code>YYYY-Www</code> (or omitting hypen, <code>YYYYWww</code>) such as <code>2014-W07</code>. A day within the week is represented by a digit where Monday is 1 and Sunday is 7, in the format <code>YYYY-Www-D</code> (or omitting hyphen, <code>YYYYWwwD</code>) such as <code>2014-W07-2</code> (a Tuesday in 7th week of year). The <code>W</code> is important to disambiguate from a year-month such as <code>2014-07</code> being July of 2014.</p> <hr> <h1>Joda-Time</h1> <p>The <a href="http://www.joda.org/joda-time/" rel="nofollow">Joda-Time</a> 2.5 library offers the <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/Interval.html" rel="nofollow"><code>Interval</code></a> class to represent a span of time as a pair of specific moments in time along the timeline of the Universe. Each moment is represented by the <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html" rel="nofollow"><code>DateTime</code></a> class.</p> <h2>Half-Open</h2> <p>Joda-Time uses the Half-Open <code>[)</code> approach to defining spans of time. The beginning is inclusive while the ending is exclusive. This is generally the best way to work with such spans of time. Search StackOverflow for many examples and discussions.</p> <h2>ISO 8601 in Joda-Time</h2> <p>Joda-Time uses the ISO 8601 definition of weeks. Also, Joda-Time uses ISO 8601 as its defaults for parsing and generating string representations of date-time values.</p> <pre><code>DateTimeZone zone = DateTimeZone( "America/Montreal" ); // Get first moment of a Monday. Inclusive. DateTime start = new DateTime( 2014, 11, 24, 0, 0, 0, zone ); // Handle exception thrown if occurring during a Daylight Saving Time gap. DateTime stop = start.plusWeeks( 1 ); // First moment of following Monday. Exclusive. Interval week = new Interval ( start, stop ); </code></pre> <h2>First Monday</h2> <p>Search StackOverflow for many questions and answers on finding the first Monday of a week.</p> <h2><code>LocalDate</code> (date-only)</h2> <p>While you might well be tempted to use <code>LocalDate</code> objects (date only, no time-of-day) to build an <code>Interval</code>. That would be sensible and useful. Unfortunately, the implementation of <code>Interval</code> supports only <code>DateTime</code> objects, not <code>LocalDate</code>.</p> <hr> <h1>java.time</h1> <p>The <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="nofollow">java.time</a> package built into Java 8 and later is inspired by Joda-Time but entirely re-architected. See <a href="https://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="nofollow">Tutorial</a>.</p> <p>In java.time, an <code>Instant</code> is a moment on the timeline in UTC. Apply a time zone (<code>ZoneId</code>) to get a <code>ZonedDateTime</code>. Use <code>LocalDate</code> to get a date-only value with no time-of-day and no time zone.</p> <p>Note that determining the first moment of a day in java.time requires an extra step when compared to Joda-Time: We must go through the <code>LocalDate</code> class to call its <code>atStartOfDay</code> method.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); LocalDate firstDayOfThisWeek = now.toLocalDate ().with ( DayOfWeek.MONDAY ); LocalDate firstDayOfNextWeek = firstDayOfThisWeek.plusWeeks ( 1 ); ZonedDateTime thisWeekStart = firstDayOfThisWeek.atStartOfDay ( zoneId ); ZonedDateTime nextWeekStart = firstDayOfNextWeek.atStartOfDay ( zoneId ); </code></pre> <p>Unfortunately, java.time lacks the equivalent of Joda-Time's <code>Interval</code>. </p> <p>Fortunately we have <a href="http://www.threeten.org/threeten-extra/" rel="nofollow">ThreeTen Extra</a>, the project that extends java.time (310 being the number of <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow">the JSR defining java.time</a>). This library includes an <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="nofollow"><code>Interval</code></a> class that integrates with java.time. This <code>Interval</code> class is more limited than that of Joda-Time as it supports only <code>Instant</code> objects without time zones (always in UTC).</p> <p>Caution: The ThreeTen-Extra project reserves the right to change its interfaces and/or implementations. While intended to be useful as-is, it also serves as an experimental proving ground for classes that may be eventually incorporated into java.time. I gladly make use of ThreeTen-Extra, but you must make your own risk-benefit decision.</p> <pre><code>// This next line requires adding the `ThreeTen Extra` library to your project. Interval interval = Interval.of ( thisWeekStart.toInstant () , nextWeekStart.toInstant () ); // "Interval" is part of ThreeTen-Extra project, not built into Java 8. </code></pre> <p>Dump to console.</p> <pre><code>System.out.println ( "now: " + now + " thisWeekStart: " + thisWeekStart + " nextWeekStart: " + nextWeekStart + " interval: " + interval ); </code></pre> <blockquote> <p>now: 2016-01-15T18:10:48.143-05:00[America/Montreal] thisWeekStart: 2016-01-11T00:00-05:00[America/Montreal] nextWeekStart: 2016-01-18T00:00-05:00[America/Montreal] interval: 2016-01-11T05:00:00Z/2016-01-18T05:00:00Z</p> </blockquote> <p>You can determine the week-of-year as defined by the ISO 8601 standard. Note the "week based" terms. Near the beginning or ending of the year, a date will be in one calendar year while its ISO 8601 week’s year may be ±1.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); int weekOfYear = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR ); int weekBasedYear = now.get ( IsoFields.WEEK_BASED_YEAR ); System.out.println ( "weekOfYear: " + weekOfYear + " of weekBasedYear: " + weekBasedYear ); </code></pre> <blockquote> <p>weekOfYear: 2 of weekBasedYear: 2016</p> </blockquote>
9,809,347
0
Spring MVC - URL display in browser and Encoding support <p>This might be an obvious question. But am not able to figure it out so far.</p> <p>In my Spring application, I make a GET request to the following url</p> <p><a href="http://www.example.com/firstpage" rel="nofollow">http://www.example.com/firstpage</a></p> <p>This request goes to the front controller where I have a request mapping as below:</p> <pre><code>@RequestMapping(value = "/firstpage") public String handlerMethod(HttpServletRequest request, HttpSession session) throws CustomException { ... return "secondpage"; } </code></pre> <p>This "secondpage" corresponds to secondpage.jsp and its contents are correctly displayed. But the problem is the browser URL still displays</p> <p><a href="http://www.example.com/firstpage" rel="nofollow">http://www.example.com/firstpage</a></p> <p>Why is this happening? Any suggestions as to how to make the browser URL change? Also does Spring have any default support for encoding URL ?</p>
21,210,276
0
Skrollr background: position property applied to an image does not work <p>I am trying to animate opacity and parrallax position property of a few images using the scrollr.</p> <p>Opacity works flawlessly on img and div tags, but position property will not work.</p> <p>I tried applying the background-position property to img tag and div tag but it just doesn't work.</p> <pre><code>&lt;div class="image1" data-bottom="opacity:0;background-position: 0px -250px;" data-center="opacity:1;background-position: 0px 0px;" data-top="opacity:0;background-position: 0px 250px;"&gt;&lt;/div&gt; </code></pre> <p>What am I doing wrong?</p> <p><a href="http://jsfiddle.net/Eq87X/3/" rel="nofollow">http://jsfiddle.net/Eq87X/3/</a></p> <p>Thanks</p>
29,673,953
0
<p>Another option is to put your alert UI in a group and show/hide it as necessary. Depending on your app's design this can work quite well. I do something similar for showing loading UI.</p>
19,919,899
0
arquillian using a random port with tomcat7 embeded <p>I'd like to use a random port for arquillian. So in arquillian.xml I do:</p> <pre><code> &lt;arquillian&gt; &lt;container qualifier="tomcat7" default="true"&gt; &lt;configuration&gt; ... &lt;property name="bindHttpPort"&gt;0&lt;/property&gt; ... &lt;/configuration&gt; &lt;/container&gt; &lt;/arquillian&gt; </code></pre> <p>In my unit test:</p> <pre><code>@ArquillianResource private URL base; </code></pre> <p>I hope to have the real port (localPort) used by Apache Tomcat (because yes it start with a random port) but this URL is with 0 port the one from configuration not random one.</p> <p>So how to have access to this?</p>
32,925,068
0
<p><code>R.id.stackView1</code> is not found when you try to assign <code>stackView</code>, so it is <code>null</code></p>
8,139,047
0
grappelli admin show image <p>I have a new project on django, in which im using Grappelli and filebrowser, and I have extended the User to have a UserProfile related to it, my question is, how can I modify my code to be able to show on the UserProfile information of a user the profile picture uploaded, and also show it on the Users list?</p> <p>This is my code now, I dont see any image on the admin!</p> <p>Admin.py</p> <pre><code>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from models import UserProfile class UserProfileInline(admin.StackedInline): model = UserProfile verbose_name_plural = 'User Profile' list_display = ('city', 'tel', 'description', 'image_thumbnail',) class MyUserAdmin(UserAdmin): list_display = ('username','email','first_name','last_name','date_joined', 'last_login','is_staff', 'is_active',) inlines = [ UserProfileInline ] admin.site.unregister(User) admin.site.register(User, MyUserAdmin) </code></pre> <p>Models.py</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from apps.common.utils.abstract_models import BaseModel from apps.common.utils.model_utils import unique_slugify from filebrowser.base import FileObject from django.conf import settings class UserProfile(BaseModel): user = models.OneToOneField(User, related_name="profile") city = models.CharField(_("City"), max_length=200) tel = models.CharField(_("Phone Number"), max_length=50, help_text=_("(Area Code) (Your phone number)")) description = models.TextField(null=True, blank=True, help_text = _("Small description about yourself.")) photo = models.ImageField(max_length=255, upload_to="profiles/", null=True, blank=True, default="img/default_profile_image.png") def image_thumbnail(self): if self.photo: return u'&lt;img src="%s" width="80" height="80" /&gt;' % self.photo.version(ADMIN_THUMBNAIL).url return u'&lt;img src="/site_media/%s" width="80" height="80" /&gt;' % settings.DEFAULT_PROFILE_IMAGE image_thumbnail.allow_tags = True def __unicode__(self): if self.user.first_name or self.user.last_name: return "%s %s" % (self.user.first_name, self.user.last_name) else: return self.user.username </code></pre>
21,847,489
0
<p>Use SwingUtilities.invokeLater() without javax.swing.SwingUtilities.invokeAndWait(Unknown Source). It will solve this issue.</p>
20,239,740
0
<p>Had something similar before. In my case it was because of a missing dependency.</p> <p>Take a look at the eventviewer. Maybe you can also find some details there.</p>
6,087,593
0
(Adding and) Removing list items with JavaScript / jQuery <p>I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).</p> <p>Here is the thing. I have a list with lots of stuff in each list item:</p> <pre><code>&lt;ul id="fruit_list"&gt; &lt;li&gt; &lt;h4&gt; Fruit 1: &lt;a href="#" class="remove"&gt;remove&lt;/a&gt; &lt;/h4&gt; &lt;p&gt; blablabla &lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;h4&gt; Fruit 2: &lt;a href="#" class="remove"&gt;remove&lt;/a&gt; &lt;/h4&gt; &lt;p&gt; blablabla &lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;a href="#" class="add"&gt;add&lt;/a&gt; </code></pre> <p>What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.</p> <p>(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)</p> <p>So here is what I've written so far:</p> <pre><code>$(function(){ var i = $('#fruit_list li').size() + 1; $('a.add').click(function() { $('&lt;li&gt;&lt;h4&gt;Fruit '+i+':&lt;a href="#" class="remove"&gt; remove&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;Blabla&lt;/p&gt;&lt;/li&gt;') .appendTo('#fruit_list'); i++; }); $('a.remove').click(function(){ $(this).parentNode.parentNode.remove(); /* The above obviously does not work.. */ i--; }); }); </code></pre> <p>The 'add' anchor works as expected. The 'remove' drinks a lemonade..</p> <p>So, any ideas? Thanks </p> <p>EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:</p> <pre><code>$('a.remove').live('click', function(){ $(this).closest('li').remove(); i--; }); </code></pre> <p>Thank you for your rapid help!</p>
22,230,741
0
<p>simply upgrading to bootstrap v3.1.1 made the problem go away.</p>
11,327,735
0
<p>Assuming one has an extension method <code>IEnumerable.MinBy</code>:</p> <pre><code>var r = new Random(); return source.MinBy(x=&gt;r.Next()) </code></pre> <p>The method <code>MinBy</code> doesn't save the sequence to memory, it works like <code>IEnumerable.Min</code> making one iteration (see <a href="http://code.google.com/p/morelinq/source/browse/MoreLinq/MinBy.cs" rel="nofollow">MoreLinq</a> or <a href="http://stackoverflow.com/a/11326714/284795">elsewhere</a> )</p>
19,702,397
0
how to keep the last frame in opencv in c++ <p>I need to keep the information in the last frame in a video file and then calculate PSNR between the last and whole frames. the video is running! when I get to the last frame I would miss all the previous frames information. so I can not calculate a formula between the last and the first frame :(</p> <pre><code>float *frames; //this pointer points to the frames float *p; for(int i=0; i&lt;sizeof frames; i++){ ... ; } </code></pre> <p>I do not know how to fill the for-loop :(</p> <p>thanks in advance.. </p>
6,921,064
0
<p>Canonical (Ubuntu) tracks <a href="http://popcon.ubuntu.com/by_vote" rel="nofollow">software package usage</a> for their distro, so there's no need to rely on Stack Exchange issue counts to measure popularity. However, as others have pointed out, this only tracks Ubuntu users and Canonical (Ubuntu) uses and recommends bzr (sample bias). Nonetheless...</p> <pre><code> 2011 2011 2011 Package Aug 3 Sep 29 Dec 9 Change ------ ------ ------ ------ ------ git-core 3647 3402 3236 -11% bzr 4975 5286 6070 +22% mercurial 3411 3387 3461 +1% </code></pre> <p>The decline in votes for the git-core package makes me think I've done something wrong like <code>grep</code>ed the wrong package name from the ubuntu popularity table. Or maybe even this "vote" count is related to installations and not actual usage of the software.</p> <p>Here's some historical data for trending. I used the <code>&lt;install&gt;</code> rather than <code>&lt;vote&gt;</code> stats from Ubuntu in this table, but it shows a growth spurt in Bazaar and Mercurial starting in 2011. Nonetheless, <code>bzr</code> was behind <code>git</code> in 2011, but the recent stats for 2011 show that it passed <code>git</code> in total installed instances (on Ubuntu).</p> <pre><code> June Aug Dec Growth Oct Growth 2010 2011 2011 2013 ---- ----- ---- ---- ------ ---- ------ git 94k 159k 171k 80% 165k -3.5% bzr 52k 121k 135k 160% 170k 26.0% hg 36k 68k 75k 110% 95k 26.7% </code></pre> <p>Discalaimer: I used bzr on Ubuntu until 2012 when I worked on teams that used <code>git</code> exclusively. <code>Bzr</code> plays nice with all other VCSes, allowing you to use consistent, intuitive bzr command line syntax. My switch to <code>git</code> was for social rather than technical reasons.</p>
35,988,198
0
How to Mock Service Initialization Parameters in Service Fabric for Unit Testing similar to mocking the state using a mock class? <p>I am writing Unit tests for a Service Fabric Reliable Service. My application is an OWIN hosted Stateless service, I want to write Unit test for Communication listener, Which uses <strong><em>ServiceInitializationParameters</em></strong> class. I can't initialize a dummy object of this type since all the fields are read only and no public constructor is available. For State in service fabric, We can mock it by using a mock class which implements an interface for state. </p> <p>Is there any similar way to mock the Service Initialization Parameters ?</p>
19,449,746
0
<p>You should use next code:</p> <pre><code>try { $img = @getimagesize($image); echo "&lt;a href='$image'&gt;&lt;img src=\"$image\" width='300' height='150'/&gt;&lt;/a&gt;"; } catch(Exception $e) { echo "&lt;img src='".plugins_url()."/plugins/images/image_not_found.jpg' width='300' height='150'/&gt;"; } </code></pre>
39,220,851
0
<p>Hope This Helps</p> <p><strong>HTML Code</strong></p> <pre><code>&lt;table width="560"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;span&gt;5th Mar, 2016&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>CSS Code</strong></p> <pre><code>table { background-color: #fff; padding: 5px } table, th, td { color: #fff; border: 1px solid black; } table tr { background-color: #000; } </code></pre>
39,193,143
0
<p>The obvious solution, as Fyodor Soikin points out, is to simply make <code>Profile</code> a module.</p> <pre><code>module Profile = let someUserName = "some_user_name" let somePassword = "some_password" </code></pre> <p>Then you can just:</p> <pre><code>open Profile let credentials = { User = User someUserName; Password = Password somePassword } </code></pre> <p>Incidentally, while it may not be possible to open static classes in F# at the moment, this looks set to change in future versions - this feature has been "approved in principle". See the <a href="https://fslang.uservoice.com/forums/245727-f-language/suggestions/6958404-allow-opening-of-static-classes-matching-the-c-d">user voice item</a> for more.</p>
4,413,153
0
<p>The <code>drawString</code> method does not handle new-lines.</p> <p>You'll have to split the string on new-line characters yourself and draw the lines one by one with a proper vertical offset:</p> <pre><code>void drawString(Graphics g, String text, int x, int y) { for (String line : text.split("\n")) g.drawString(line, x, y += g.getFontMetrics().getHeight()); } </code></pre> <hr> <p>Here is a complete example to give you the idea:</p> <pre><code>import java.awt.*; public class TestComponent extends JPanel { private void drawString(Graphics g, String text, int x, int y) { for (String line : text.split("\n")) g.drawString(line, x, y += g.getFontMetrics().getHeight()); } public void paintComponent(Graphics g) { super.paintComponent(g); drawString(g, "hello\nworld", 20, 20); g.setFont(g.getFont().deriveFont(20f)); drawString(g, "part1\npart2", 120, 120); } public static void main(String s[]) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new TestComponent()); f.setSize(220, 220); f.setVisible(true); } } </code></pre> <p>which gives the following result:</p> <p><img src="https://i.stack.imgur.com/l8x9w.png" alt="enter image description here"></p>
12,299,724
0
List of Natural Language Processing Tools in Regards to Sentiment Analysis - Which one do you recommend <p>first up sorry for my not so perfect English... I am from Germany ;) </p> <p>So, for a research project of mine (Bachelor thesis) I need to analyze the sentiment of tweets about certain companies and brands. For this purpose I will need to script my own program / use some sort of modified open source code (no APIs' - I need to understand what is happening). </p> <p>Below you will find a list of some of the NLP Applications I found. My Question now is which one and which approach would you recommend? And which one does not require long nights adjusting the code?</p> <p>For example: When I screen twitter for the music player >iPod&lt; and someone writes: "It's a terrible day but at least my iPod makes me happy" or even harder: "It's a terrible day but at least my iPod makes up for it" </p> <p>Which software is smart enough to understand that the focused is on iPod and not the weather? </p> <p>Also which software is scalable / resource efficient (I want to analyze several tweets and don't want to spend thousands of dollars)? </p> <p><strong>Machine learning and data mining</strong></p> <p><em>Weka</em> - is a collection of machine learning algorithms for data mining. It is one of the most popular text classification frameworks. It contains implementations of a wide variety of algorithms including Naive Bayes and Support Vector Machines (SVM, listed under SMO) [Note: Other commonly used non-Java SVM implementations are SVM-Light, LibSVM, and SVMTorch]. A related project is Kea (Keyphrase Extraction Algorithm) an algorithm for extracting keyphrases from text documents.</p> <p><em>Apache Lucene Mahout</em> - An incubator project to created highly scalable distributed implementations of common machine learning algorithms on top of the Hadoop map-reduce framework.</p> <p><strong>NLP Tools</strong></p> <p><em>LingPipe</em> - (not technically 'open-source, see below) Alias-I's Lingpipe is a suite of java tools for linguistic processing of text including entity extraction, speech tagging (pos) , clustering, classification, etc... It is one of the most mature and widely used open source NLP toolkits in industry. It is known for it's speed, stability, and scalability. One of its best features is the extensive collection of well-written tutorials to help you get started. They have a list of links to competition, both academic and industrial tools. Be sure to check out their blog. LingPipe is released under a royalty-free commercial license that includes the source code, but it's not technically 'open-source'.</p> <p><em>OpenNLP</em> - hosts a variety of java-based NLP tools which perform sentence detection, tokenization, part-of-speech tagging, chunking and parsing, named-entity detection, and co-reference analysis using the Maxent machine learning package.</p> <p><em>Stanford Parser and Part-of-Speech (POS) Tagger</em> - Java packages for sentence parsing and part of speech tagging from the Stanford NLP group. It has implementations of probabilistic natural language parsers, both highly optimized PCFG and lexicalized dependency parsers, and a lexicalized PCFG parser. It's has a full GNU GPL license.</p> <p><em>OpenFST</em> - A package for manipulating weighted finite state automata. These are often used to represented a probablistic model. They are used to model text for speech recognition, OCR error correction, machine translation, and a variety of other tasks. The library was developed by contributors from Google Research and NYU. It is a C++ library that is meant to be fast and scalable.</p> <p><em>NTLK</em> - The natural language toolkit is a tool for teaching and researching classification, clustering, speech tagging and parsing, and more. It contains a set of tutorials and data sets for experimentation. It is written by Steven Bird, from the University of Melbourne.</p> <p><em>Opinion Finder</em> - A system that performs subjectivity analysis, automatically identifying when opinions, sentiments, speculations and other private states are present in text. Specifically, OpinionFinder aims to identify subjective sentences and to mark various aspects of the subjectivity in these sentences, including the source (holder) of the subjectivity and words that are included in phrases expressing positive or negative sentiments.</p> <p><em>Tawlk/osae</em> - A python library for sentiment classification on social text. The end-goal is to have a simple library that "just works". It should have an easy barrier to entry and be thoroughly documented. We have acheived best accuracy using stopwords filtering with tweets collected on negwords.txt and poswords.txt</p> <p><em>GATE</em> - GATE is over 15 years old and is in active use for all types of computational task involving human language. GATE excels at text analysis of all shapes and sizes. From large corporations to small startups, from €multi-million research consortia to undergraduate projects, our user community is the largest and most diverse of any system of this type, and is spread across all but one of the continents1.</p> <p><em>textir</em> - A suite of tools for text and sentiment mining. This includes the ‘mnlm’ function, for sparse multinomial logistic regression, ‘pls’, a concise partial least squares routine, and the ‘topics’ function, for efficient estimation and dimension selection in latent topic models.</p> <p>NLP Toolsuite - The JULIE Lab here offers a comprehensive NLP tool suite for the application purposes of semantic search, information extraction and text mining. Most of our continuously expanding tool suite is based on machine learning methods and thus is domain- and language independent.</p> <p>...</p> <p>On a side note: Would you recommend the twitter streaming or the get API? </p> <p>As to me, I am a fan of python and java ;)</p> <p>Thanks a lot for your help!!!</p>
10,875,635
0
<pre><code>from itertools import izip with open("myfile.csv") as inf, open("new.csv","w") as outf: header = [s.split('_to_') for s in inf.next().split(',')] for row in inf: nums = (int(s) for s in row.split(',')) for (_from, _to), num in izip(header, nums): outf.write("{},{},{}\n".format(_from, _to, _num)) </code></pre>
32,605,606
0
<pre><code>var background = $('body').css('background-image'); var start = background.substr(0, background.lastIndexOf('.')); var end = background.substr(background.lastIndexOf('.')); $('body').css('background-image', start + '_something_more' + end); </code></pre>
17,439,694
0
Self referencing schema for versioning <p>I need to version documents in a collection, such that any changes to a document make a copy, and save the edited copy as 'current' and the previous version is preserved, along with time stamps, person editing, etc. I have designed a schema like:</p> <pre><code>var doc = new Schema; doc.Add({ created: Date, created_by:{type: ObjectId, ref: 'User'}, doc_id: String, doc_data: String, prev_docs:[doc] }); </code></pre> <p>So editing a doc would take the current doc, make a copy, and update the document, sticking current_doc into prev_docs, etc.</p> <ol> <li>Can a schema reference itself, like <code>prev_docs</code> does?</li> <li>Is this design pattern scalable in MongoDB? <code>prev_docs</code> would only ever be used as an audit trail, users would not generally see previous versions, and the would be excluded completely from most queries.</li> </ol>
2,821,612
0
django+uploadify - don't working <p>I'm trying to use an example posted on the "github" the link is <a href="http://github.com/tstone/django-uploadify" rel="nofollow noreferrer">http://github.com/tstone/django-uploadify</a>. And I'm having trouble getting work. can you help me? I followed step by step, but does not work.</p> <p>Accessing the "URL" / upload / the only thing is that returns "True"</p> <p><strong>part of settings.py</strong></p> <pre><code>import os PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media') TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT_PATH, 'templates')) </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from teste.uploadify.views import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'upload/$', upload, name='uploadify_upload'), ) </code></pre> <p><strong>views.py</strong> </p> <pre><code>from django.http import HttpResponse import django.dispatch upload_received = django.dispatch.Signal(providing_args=['data']) def upload(request, *args, **kwargs): if request.method == 'POST': if request.FILES: upload_received.send(sender='uploadify', data=request.FILES['Filedata']) return HttpResponse('True') </code></pre> <p><strong>models.py</strong></p> <pre><code>from django.db import models def upload_received_handler(sender, data, **kwargs): if file: new_media = Media.objects.create( file = data, new_upload = True, ) new_media.save() upload_received.connect(upload_received_handler, dispatch_uid='uploadify.media.upload_received') class Media(models.Model): file = models.FileField(upload_to='images/upload/', null=True, blank=True) new_upload = models.BooleanField() </code></pre> <p><strong>uploadify_tags.py</strong></p> <pre><code>from django import template from teste import settings register = template.Library() @register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True) def multi_file_upload(context, upload_complete_url): """ * filesUploaded - The total number of files uploaded * errors - The total number of errors while uploading * allBytesLoaded - The total number of bytes uploaded * speed - The average speed of all uploaded files """ return { 'upload_complete_url' : upload_complete_url, 'uploadify_path' : settings.UPLOADIFY_PATH, # checar essa linha 'upload_path' : settings.UPLOADIFY_UPLOAD_PATH, } </code></pre> <p><strong>template - uploadify/multi_file_upload.html</strong></p> <pre><code>{% load uploadify_tags }{ multi_file_upload '/media/images/upload/' %} &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/swfobject.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.uploadify.js"&gt;&lt;/script&gt; &lt;div id="uploadify" class="multi-file-upload"&gt;&lt;input id="fileInput" name="fileInput" type="file" /&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt;// &lt;![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/media/swf/uploadify.swf', 'script' : '{% url uploadify_upload %}', 'cancelImg' : '/media/images/uploadify-remove.png/', 'auto' : true, 'folder' : '/media/images/upload/', 'multi' : true, 'onAllComplete' : allComplete }); }); function allComplete(event, data) { $('#uploadify').load('{{ upload_complete_url }}', { 'filesUploaded' : data.filesUploaded, 'errorCount' : data.errors, 'allBytesLoaded' : data.allBytesLoaded, 'speed' : data.speed }); // raise custom event $('#uploadify') .trigger('allUploadsComplete', data); } // ]]&lt;/script&gt; </code></pre>
16,195,555
0
<p>You can create a matrix directly and just multiply the data with it:</p> <pre><code>as.matrix(trans_temp) * col(trans_temp) </code></pre> <hr> <h3>Benchmarking with eddi's</h3> <pre><code>m &lt;- as.data.frame(matrix(runif(1e7), ncol=1000)) x &lt;- seq_len(1000) system.time(tt1 &lt;- as.matrix(m) * col(m)) # 0.335 seconds system.time(tt2 &lt;- t(x*t(m))) # 0.505 seconds identical(tt1, tt2) # TRUE </code></pre>
33,208,427
0
<p>I am using Windows with git bash/command promt</p> <p>zipalign.exe needed to be configured in environment variables.</p> <p>so include sdk folder 'build-tool' with android version folder you are using to build.</p> <pre><code>e.g. E:\android-sdk\build-tools\22.0.1 </code></pre> <p>it should contain 'zipalign.exe'. now you can user</p> <pre><code>zipalign -v 4 Project1.apk Project1-aligned.apk </code></pre> <p>from any location using command line tools.</p> <p>thumb up for me so i can help more developers.</p>
4,290,465
0
Field data type / validations questions <p>I have few questions on what data types to use and how to define some fields from my site. My current schema is in MySQL but in process of changing to PostregSQL.</p> <ol> <li><p>First &amp; Last name -> Since I have multi-lang, tables all support UTF-8, but do i need to declare them as nvarchar in-case a user enters a Chinese name? If so, how do i enforce field validation if it is set to accept alphabets only as i assume those are English alphabets and not validating for valid chinese or arabic alphabets? And i don't think PostregSQL supports nvarchar anyways?</p></li> <li><p>To store current time line - > Example I work in company A from Jan 2009 to Present. So i assume there will be 3 field for this: timeline_to, timeline_from, time_line present where to &amp; from are month/year varchars and present is just a flag to set the current date?</p></li> <li><p>User passwords. i am using SHA 256 + salting. so i have 2 fields declared as follows:<br> password_hash - varchar (64)<br> password_salt- varchar (64)<br> Does this work if the user password needs to be between 8 and 32 chars long?</p></li> <li><p>birth time -> I need to record birth time for the application to calculate some astrological values. so that means hour, minute and am/pm. So best to store these are 3 separate single select lists with varchar or use a time data type in the back end and allow users to use single select list in front end?</p></li> <li><p>Lastly for birth month and year only, are these int or varchar if i store them in separate rows? They all have primary keys of int for reporting purposes so int makes more sense? or should i store them in 1 field only as date type?</p></li> </ol>
40,221,455
0
How to build Angular2 app with external json file using angular-cli in prod mode? <p>My Angular2 app is using ng2-translate module and 'en.json' file contains translation. This is all working well in dev mode when built end deployed with angular-cli. But when built in prod mode, and deployed to WildFly, en.json is not found and translation is not loaded.</p> <p>How to build app in prod mode, so en.json is packed inside dist directory?</p>
6,543,061
0
<p>You can try something like this: </p> <p><a href="http://www.javascriptkit.com/javatutors/externalphp.shtml" rel="nofollow">http://www.javascriptkit.com/javatutors/externalphp.shtml</a></p> <p>The external file doesn't have to be a .js extension. Alternatively, you could associate .js files as PHP files in apache (or whatever webserver you are running). Saving your JS files as .php is probably easiest but keep in mind that it won't share the same variables as the script rendering the page. </p>
27,146,664
0
Does webRtc Hybrid app run on IOS <p>I want to develop IOS application using sdk like rtc.io I want to know whether javascript based hybrid application will run on IOS or not? Is there any available free SDK for IOS native webRTC Data channel app development? </p>
32,044,452
0
<p>I'm not entirely sure what you're trying to ask, but I'll give it a shot.</p> <p>You can use a ListView and then set its DataTemplate to effectively make it look exactly as u want. For example:</p> <pre><code> &lt;ListView ItemsSource="{Binding MyItems}" &gt; &lt;ListView.ItemTemplate&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;TextBlock Text="{Binding Property1}" /&gt; &lt;TextBlock Grid.Column="1" Text="{Binding Property2}" /&gt; &lt;/Grid&gt; &lt;/ListView.ItemTemplate&gt; &lt;/ListView&gt; </code></pre> <p>Where Property1 and Property2 are bindable properties of an item in your ItemsSource.</p>
24,832,024
0
CSS help for RadioButtonList <p>After spending a lot of time, I've come to realize that I need some external help related to a CSS problem. </p> <p>So, I've been using a free template for my website. In the contact form, I added RadioButtonList, and its rendering button over text, rather than button then text in the same line. I am trying to get the standard format, but unable to achieve it. </p> <p>The RadioButtonList is under a form, which references to CSS blocks via <code>&lt;div id="contact-form"&gt;</code>, when I remove the <code>id=contact-form</code>, it fixes the Radio button problem, but kills rest of the CSS. So, I don't want to touch it. I checked out the CSS stuff, and this is what it looks like: </p> <pre><code>/* contact form */ #contact-form form { margin-bottom: 30px; } #contact-form div { float: left; width: 100%; } #contact-form .half { width: 47%; } #contact-form label { display: inline-block; float: left; } #contact-form input, #contact-form textarea, #contact-form select { width: 100% !important; min-width: none; margin-bottom: 12px; } #contact-form button.submit { text-transform: uppercase; letter-spacing: 2px; margin-top: 24px; } #contact-form span.required { color: #11ABB0; } </code></pre> <p>On further trial and error, I found that on removing <code>width: 100%</code>the radio button and text come in same line, but radio button is to the right to the text. I was able to put buttons to the left of text by further deleting <code>float: left;</code> inside <code>#contact-form label</code>. This works! However, it ruins rest of the things, which is very upsetting. </p> <p>Also, when the radio button text is longer and comes to the next line, it screws up stuff again, and its weird. Would it possible to keep rest of the things unchanged, while I get to resolve the radio button problem? </p> <p>Can't I make some CSS change specific to radio button which does not effect rest of the things in CSS file or here in the RadioButtonList options/properties? Here's what it looks like: </p> <pre><code>&lt;asp:RadioButtonList ID="RadioButtonListMsgs" runat="server" RepeatLayout="Table" RepeatDirection="Vertical" TextAlign="Right"&gt; &lt;asp:ListItem&gt;A &lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;B&lt;/asp:ListItem&gt; &lt;/asp:RadioButtonList&gt; </code></pre> <p>Please, can someone help? Thanks a lot!</p>
40,660,301
0
Unexpected behavior with "set -o errexit" on AIX <p>This script shell works fine on GNU/Linux but not on AIX 5.3</p> <pre><code>#!/bin/sh echo $SHELL set -o nounset -o errexit [ 1 -eq 1 ] &amp;&amp; { echo "zzz" } &amp;&amp; echo "aaa" &amp;&amp; [ 1 -eq 0 ] &amp;&amp; echo "bbb" echo "ccc" </code></pre> <p>On GNU/Linux, I've got the expected output :</p> <pre><code>/bin/bash zzz aaa ccc </code></pre> <p>On AIX, I've got this one : </p> <pre><code>/bin/ksh zzz aaa </code></pre> <p>Without "set -o nounset -o errexit" it works fine... I don't understant why. Could you explain me what is wrong in my script shell.</p> <p>Thanks, </p> <p>Rémy</p> <hr> <p>Edit 18 nov. : Precision</p> <blockquote> <p>set -e When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit. <a href="http://explainshell.com/explain?cmd=set+-e" rel="nofollow noreferrer">http://explainshell.com/explain?cmd=set+-e</a></p> </blockquote> <p>In my example, the second test "[ 1 -eq 0 ]" is part of an AND, so I should see the output "ccc". This test returns 1, it traps the output "bbb", but should'nt exit the script.</p> <p>Rémy</p>
8,617,881
0
<p>This is because <code>NullPointerException</code> is a so-called "unchecked" exception. You don't need to declare them in the <code>throws</code> clause.</p> <p>However, a casual <code>Exception</code> is <em>not</em> unchecked, and you <em>do</em> need to declare in a <code>throws</code> declaration. You need to make <code>Method()</code> throw <code>Exception</code> in your second code snippet.</p> <p>Unchecked exceptions are <code>RuntimeException</code>, <code>Error</code> and derivate classes. <code>NullPointerException</code> derivates from <code>RuntimeException</code>.</p>
23,104,973
0
<p>I found this <a href="https://github.com/typesafehub/config" rel="nofollow">HOCON</a> example:</p> <pre><code>my.organization { project { name = "DeathStar" description = ${my.organization.project.name} "is a tool to take control over whole world. By world I mean couch, computer and fridge ;)" } team { members = [ "Aneta" "Kamil" "Lukasz" "Marcin" ] } } my.organization.team.avgAge = 26 </code></pre> <p>to read values:</p> <pre><code>val config = ConfigFactory.load() config.getString("my.organization.project.name") // =&gt; DeathStar config.getString("my.organization.project.description") // =&gt; DeathStar is a tool to take control over whole world. By world I mean couch, computer and fridge ;) config.getInt("my.organization.team.avgAge") // =&gt; 26 config.getStringList("my.organization.team.members") // =&gt; [Aneta, Kamil, Lukasz, Marcin] </code></pre> <p><em>Reference</em>: <a href="http://marcinkubala.wordpress.com/2013/10/09/typesace-config-hocon/" rel="nofollow">marcinkubala.wordpress.co</a>m</p>
27,455,169
0
<p>You should close the while() loop before the if/else.</p> <p>It is not the prettiest of code though.</p>
1,595,594
0
Getting GPS coordinates from Samsung Intrepid <p>I'm looking into purchasing the new Samsung Intrepid Windows Mobile 6.5 device. Before I plunk down the cash, I'm investigating the available APIs and support resources. I have one question I want answered. It's one question but it's a big one for me. Can I access the GPS coordinates of the device? Does this phone have a location API? I've been searching for code samples (C# or VB.NET) and found nothing. Not even a mention of this capability from a technical / developer perspective. Plenty of sales stuff that mention the phone has GPS but I need more info. I find that difficult to believe to so I'm willing to accept I must be missing something.</p>
20,810,996
1
how to limit possible input while using raw_input? (also using split) <p>i want to limit the users input in two cases:</p> <p>1.With a string and split, when asking the user to put in two, 2 digit numbers I wrote:</p> <pre><code>x=raw_input("words").split() </code></pre> <p>I want to only enable him to write an input that is two 2 digit numbers, and if he does something else I want to pop an error, and for him to be prompted again, until done right.</p> <p>2.This time an INT when asking the user for a random 4 digit number:</p> <pre><code>y=int(raw_input("words")) </code></pre> <p>I only want to allow (for example) 4 digit numbers, and again if he inputs <code>53934</code> for example I want to be able to write an error explaining he must only enter a 4 digit number, and loop it back until he gets it right.</p> <h1>Thank you, hopefully I explained myself properly.</h1> <p>update so - trying to start simple i decided that at first ill only try to ask the user to type in 8 letters. for example an <code>qwertyui</code> input is acceptable, but <code>sadiuso</code> (7 chars) is not.</p> <p>so i tried working with the syntax you gave me and wrote:</p> <pre><code>y=raw_input("words") if not (len(y) == 8): pop an error </code></pre> <p>but im getting a syntax error on the <code>:</code></p>
1,813,026
0
Is it any way to implement a linked list with indexed access too? <p>I'm in the need of sort of a linked list structure, but if it had indexed access too it would be great.</p> <p>Is it any way to accomplish that?</p> <p>EDIT: I'm writing in C, but it may be for any language.</p>
21,945,403
0
Widgets the Symfony way <p>What is "the Symfony way" of creating reusable widgets?</p> <p>By widget I mean an object with behavior defined in PHP and associated template that can be rendered on different pages (controller actions). </p> <p>E.g. tag cloud widget:</p> <pre><code>// TagCloudWidget.php class TagCloudWidget { /** @var PDO */ private $connection; public function __construct(PDO $connection) { $this-&gt;connection = $connection; } public function render() { $tags = $this-&gt;connection-&gt;query("SELECT * FROM tags ORDER BY name"); $tags-&gt;setFetchMode(PDO::FETCH_CLASS, "Tag"); include __DIR__ . "/TagCloudWidget.html.php"; } } // TagCloudWidget.html.php &lt;div class="tag-cloud"&gt; &lt;?php foreach ($tags as $tag) { ?&gt; &lt;span class="tag" style="font-size: &lt;?php echo $tag-&gt;importance; ?&gt;px;"&gt;&lt;?php echo $tag-&gt;name; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>What is the best way how to do it in Symfony? How to make the widget's dependecies to be managed by DI container?</p>
30,658,970
0
<p>You can add a click handler to each link in the <code>#ullist</code> element then set teh value of the text box</p> <pre><code>var text = document.getElementById('textbox'); var anchor = document.querySelector('#button'); var links = document.querySelectorAll('#ullist a'); for(var i = 0;i&lt; links.length;i++){ links[i].onclick = function(){ text.value = this.textContent || this.innerText } } </code></pre> <p>Demo: <a href="https://jsfiddle.net/arunpjohny/L2ogujk0/" rel="nofollow">Fiddle</a></p> <hr> <p>Using jQuery</p> <pre><code>jQuery(function($){ var $text = $('#textbox'); $('#ullist a').click(function () { $text.val($(this).text()); }); $('#button').click(function (e) { var textbox_text = $text.val(); var textbox_file = new Blob([textbox_text], { "type": "application/bat" }); this.href = URL.createObjectURL(textbox_file); this.download = "servicename.txt"; }); $('#list').click(function (e) { $('#ullist').toggle(); }); }) </code></pre> <p>Demo: <a href="https://jsfiddle.net/arunpjohny/L2ogujk0/2/" rel="nofollow">Fiddle</a></p>
5,146,684
0
ie6 and ie7 remove border around image sprites <p>Im using image sprites across my site.</p> <p>in IE6 and IE7 a gray border appears around the images.. works fine in the other browsers +IE8</p> <p>how can i remove it?<br> here it is the bottom one is a div:</p> <p><img src="https://i.stack.imgur.com/2uwyW.png" alt="enter image description here"></p>
28,855,168
0
<p>Change this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment"/&gt; </code></pre> <p>to</p> <pre><code>&lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.google.android.gms.maps.SupportMapFragment"/&gt; </code></pre>
1,460,101
0
Delphi 2009 - How to fix 'undeclared identifiers' that are identified <p>I have several custom components in my uses list of a unit. For some reason, D2009 is saying that it cannot resolve the unit name. But it seems as if it can find it - the code compiles fine. </p> <p>How can I have it resolve the unit names at design time though? My Structure window is showing all kinds of 'Undeclared Identifier' errors because the references in the Uses clause are not being found. This makes it difficult to code, and to debug legitimate errors in my code.</p>
24,227,485
0
LIBLINEAR with Weka <p>I'm using Weka 3.6.11 and I want to use its LibLinear wrapper. </p> <p>I get the message that "Liblinear classes not in CLASSPATH"</p> <p>I am on Windows. I create the CLASSPATH to the system variables, and wrote the path to the liblinear.jar file which happens to be </p> <p>C:\Program Files (x86)\Weka-3-6\LibLINEAR.jar</p> <p>So now, I'm not sure what the problem is. Any ideas?</p>
19,137,499
0
<h2>Short Answer</h2> <p>Yes, there are several ways how to do this. Which one is right for you depends on your personal needs and skill-set. Your options are to either edit the C source code and create your own Apache Module, or to add extra functionality by declaring either a Client Side or Server Side script to be used as (or included from) the header of the index file.</p> <h2>Long Answer</h2> <h3>Edit the Source Code</h3> <p>The only way to actually change the list, which is also the hardest option, would be to edit the source code and compile your own Apache Module. The HTML code for each file is put together on <a href="http://svn.apache.org/repos/asf/httpd/httpd/branches/2.2.x/modules/generators/mod_autoindex.c" rel="nofollow">line 1852 in the mod_autoindex.c file</a>. If you don't know C or if the code looks too daunting for you, there is no way to change the list <em>directly</em>.</p> <p>You can, however, change the list <em>indirectly</em> by adding (either server side or client side) functionality to the index header or footer file.</p> <p>Which brings us to easier options. </p> <h3>Add Server Side Functionality</h3> <p>Although you can't alter the list, you can make additions by having a server-side script that scans the directory you are browsing and adding thumbnails/previews for certain files. You could even hide the original list entirely with CSS and have the server side script build your own custom list. </p> <p>Of course, you would have to be able to program Python/Perl/Ruby/PHP/etc. to do this.</p> <p>I took a stab at this in PHP a while ago (mostly as an exercise) in my <a href="https://github.com/potherca/ApacheDirectoryListTheming" rel="nofollow">Apache Directory List Theming project</a>. It doesn't do anything other than show a list of thumbnails for all of the images and PDF files in a given directory. (It's also not very sophisticated).</p> <p>If you would also like to add previews for audio and/or video files, and you would like these previews to be present <em>in</em> the list generated by Apache, you're probably better of with a client side solution.</p> <h3>Add Client Side Functionality</h3> <p>By adding Javascript functionality, you could parse the list and for each file that is of interest to you insert a preview into the list. The <a href="https://github.com/jul/prettyAutoIndex" rel="nofollow">prettyAutoIndex</a> project does this. I haven't personally used it but it looks, well, pretty :-) It doesn't seem to be actively developed, but if it works it doesn't really have to be. </p> <p>If its not what you want and you can code in Javascript, it shouldn't be too difficult to create something by yourself.</p> <h3>Wrapping up</h3> <p>If you decide to create a server or client side solution, it shouldn't be much more complicated than creating a file with some functionality and calling it from your Apache Config with <code>headername</code>:</p> <pre><code>&lt;IfModule mod_autoindex.c&gt; HeaderName /path/to/header.file &lt;/IfModule&gt; </code></pre> <p>Unfortunately there are some gotchas, so I would suggest taking the time to read the relevant parts of <a href="http://httpd.apache.org/docs/2.2/mod/mod_autoindex.html" rel="nofollow">the mod_autoindex manual</a>.</p>
40,303,113
0
<p>You would be better using an if-elif-else structure in your code to deal with the 3 different expected conditions</p> <p>Also you need to change the <code>if item in item:</code> to <code>if item in shoppingListVar:</code></p> <pre><code>shoppingListVar = [] while True: item = input("Enter your Item to the List: ") if item in shoppingListVar: print("you already got this item in the list") elif item == "end": break else: shoppingListVar.append(item) print ("The following elements are in your shopping list:") print (shoppingListVar) </code></pre>
21,590
0
<p>If the objects aren't heavily keyed by other tables, and the lists are short, deleting everything in the domain and just re-inserting the correct list is the easiest. But that's not practical if the lists are large and you have lots of constraints to slow down the delete. I think your first method is really the cleanest. If you run it in a transaction you can be sure nothing odd happens while you're in the middle of the update to screw up the order.</p>
38,199,628
0
<p>from @mplungjan comments</p> <p>The difference is,</p> <p>1.meta tags are not reads after page load</p> <p>2.event handlers</p>
26,793,233
0
<p>The relevant section in the standard is 5.2.10 [expr.reinterpret.cast]. There are two relevant paragraphs:</p> <p>First, there is paragraph 1 which ends in:</p> <blockquote> <p>No other conversion can be performed explicitly using reinterpret_cast.</p> </blockquote> <p>... and paragraph 11 as none of the other apply:</p> <blockquote> <p>A glvalue expression of type <code>T1</code> can be cast to the type “reference to <code>T2</code>” if an expression of type “pointer to <code>T1</code>” can be explicitly converted to the type “pointer to <code>T2</code>” using a <code>reinterpret_cast</code>. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference cast <code>reinterpret_cast&lt;T&amp;&gt;(x)</code> has the same effect as the conversion <code>*reinterpret_cast&lt;T*&gt;(&amp;x)</code> with the built-in <code>&amp;</code> and <code>*</code> operators (and similarly for <code>reinterpret_cast&lt;T&amp;&amp;&gt;(x))</code>. —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.</p> </blockquote> <p>All the other clauses don't apply to objects but only to pointers, pointers to functions, etc. Since an rvalue is not a glvalue, the code is illegal.</p>
33,661,634
0
No $DISPLAY environment variable with matplotlib on remote server (no sudo) <p>I have been through many post talking about this issue but haven't find anything working on my server. So I am working on a server, on which I don't have a sudo access. I am simply trying to produce plots with matplotlib but I get the infamous </p> <blockquote> <p>TclError: no display name and no $DISPLAY environment variable</p> </blockquote> <p>I tried this ;</p> <pre><code>import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np # fake up some data spread = np.random.rand(50) * 100 center = np.ones(25) * 50 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 data = np.concatenate((spread, center, flier_high, flier_low), 0) # basic plot plt.boxplot(data) ##############Crash here plt.savefig( 'output_filename.png' ) </code></pre> <p>But I can't plot at all. Is there anyway to work around that,without involving installing system packages (I can pip install if needed). I am creating a command line tool for some other users so I need something without too much modification. I am using ipython for troubleshooting but get the same error when running with</p> <pre><code>python name_of_script.py </code></pre> <p>Thanks for looking into it.</p>
8,424,858
0
Can Nokogiri retain attribute quoting style? <p>Here is the contents of my file (note the nested quotes):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;property name="eventData" value='{"key":"value"}'/&gt; </code></pre> <p>in Ruby I have:</p> <pre><code>file = File.read(settings.test_file) @xml = Nokogiri::XML( file) puts "@xml " + @xml.to_s </code></pre> <p>and here is the output:</p> <pre><code>&lt;property name="eventData" value="{&amp;quot;key&amp;quot;:&amp;quot;value&amp;quot;}"/&gt; </code></pre> <p>Is there a way to convert it so the output would preserve the quotes exactly? i.e. single on the outside, double on the inside?</p>
25,416,175
0
<p>No matter where you put this code, you will need a reference to the view to get its bounds. You can either pass the view or bounds as a parameter or put it a UIView category or subclass.</p> <p>The UIColor class is just for creating colors, it has nothing to do with rendering or positioning them. That is a job for UIView. Therefore UIColor is not the place for this code imho.</p> <p>I suggest subclassing UIView and overriding drawRect to draw a gradient. Or create a UIView method like: <code>-(void)setBackgroundGradientWithStyle:(GradientStyle)gradientStyle colors:(NSArray *)colors</code> and put this code there.</p>
24,665,224
0
<p>Something like that should do the trick, even though your attempt seems correct in the first place :</p> <pre><code>typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::milliseconds Milliseconds; Clock::time_point t0 = Clock::now(); // DO A LOTS OF THINGS HERE..... Clock::time_point t1 = Clock::now(); auto elapsed_time = std::chrono::duration_cast&lt;Milliseconds&gt;(t1 - t0); auto duration = Milliseconds(2000); // Check if time left from initial 2 seconds wait the difference if (elapsed_time &lt; duration) { std::this_thread::sleep_for(duration - elapsed_time); } </code></pre>
28,638,691
0
<p>For us, the crux of this issue is that <code>DateTimeStyles.RoundtripKind</code> only works if your <code>DateTime</code> properties set the <code>DateTime.DateTimeKind</code> (<em>other than <code>DateTimeKind.Unspecified</code> - the default</em>) or better yet - using <code>DateTimeOffset</code> which <a href="https://msdn.microsoft.com/en-us/library/bb384267%28v=vs.110%29.aspx" rel="nofollow">enforces use of the <strong>TimeZone</strong> specificity</a>. </p> <p>Since we already had <code>DateTime</code> class properties, we worked around this for now by assigning the <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonSerializerSettings.cs" rel="nofollow"><code>JsonSerializerSettings.DateTimeZoneHandling</code></a> from <code>DateTimeZoneHandling.RoundtripKind</code> (<em>DateTime default</em>) to <code>DateTimeZoneHandling.Utc</code> in our <code>Global.asax.cs</code>. This change essentially appends the "Z" to the end of the <code>DateTime</code> - however there is one more step to convert the Local time to UTC. </p> <p>The second step is to provide the offset by assigning <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs" rel="nofollow"><code>IsoDateTimeConverter.DateTimeStyles</code></a> which JSON.NET <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonSerializer.cs" rel="nofollow"><code>JsonSerializer</code></a> will pickup from a <code>SerializerSettings.Converters</code> and automatically convert from Local time to UTC - much like the out-of-the-box ASP.NET MVC does. </p> <p>Obviously - there are other options, but this is solution worked for us.</p> <h3>Global.asax.cs</h3> <pre class="lang-cs prettyprint-override"><code>protected void Application_Start() { GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AdjustToUniversal }); } </code></pre> <p>The <a href="https://books.google.com/books?id=EvXX03I5iLYC&amp;pg=PA239&amp;lpg=PA239&amp;dq=AdjustToUniversal%20vs%20roundtripkind&amp;source=bl&amp;ots=jGdh-zuPs0&amp;sig=cfLgFIOjxlSYkFbTlQyMikhLzW4&amp;hl=en&amp;sa=X&amp;ei=13PnVMg8z5HIBJi8gcAK&amp;ved=0CEIQ6AEwBg#v=snippet&amp;q=roundtripkind&amp;f=false" rel="nofollow">reason this works is because <code>RoundtripKind</code> honors DateTime's <code>DateTimeKind</code></a> - which is <code>Unspecified</code> by default. We want to explicitly convert this to UTC - which <code>JavaScriptSerializer</code> used to do for us out of the box for ASP.NET MVC. The <a href="https://books.google.com/books?id=EvXX03I5iLYC&amp;pg=PA239&amp;lpg=PA239&amp;dq=AdjustToUniversal%20vs%20roundtripkind&amp;source=bl&amp;ots=jGdh-zuPs0&amp;sig=cfLgFIOjxlSYkFbTlQyMikhLzW4&amp;hl=en&amp;sa=X&amp;ei=13PnVMg8z5HIBJi8gcAK&amp;ved=0CEIQ6AEwBg#v=snippet&amp;q=adjusttouniversal&amp;f=false" rel="nofollow">regional offset is provided</a> by <code>DateTimeStyles.AdjustToUniversal</code> which converts your Local <code>DateTime</code> to UTC.</p>
20,437,777
0
cannot Imports System.Web.Script.Serializer <p>when I try to append this line to the code:</p> <pre><code>Imports System.Web.Script.Serializer </code></pre> <p>it showing me error like this:</p> <blockquote> <p>Namespace or type specified in the Imports 'System.Web.Script.Serializer' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</p> </blockquote> <p>then I searching references in google, say that should <code>Add References</code> then choose System.Net.Extension.dll in .NET tab, but it not found in the list</p> <p><img src="https://i.stack.imgur.com/HDT4K.png" alt="enter image description here"></p> <p>I try to import the System.Net.Extension.dll with manually. I open <code>Add Reference</code> dialog, in <code>Browse</code> tab, I select <code>System.Web.Extension.dll</code> in <code>C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0</code>, then klik Ok. but it still doesn't work instead show me error message agains like this:</p> <p><img src="https://i.stack.imgur.com/D09vt.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/cRVQW.png" alt="enter image description here"></p> <p>whats wrong with my VS2010 ??</p>
23,843,796
0
<pre><code>package com.example.WSTest; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; //import android.widget.SlidingDrawer;; public class WSTestActivity extends Activity { private static final String SOAP_ACTION = "http://MVIndia.com/AddActivity"; private static final String METHOD_NAME = "AddActivity"; private static final String NAMESPACE = "http://MVIndia.com/"; private static final String URL = "http://10.0.2.2/SAP/Service.asmx"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //final SlidingDrawer txt1 = (SlidingDrawer) findViewById(R.id.Spinner1); //final SlidingDrawer txt2 = (SlidingDrawer) findViewById(R.id.Spinner2); final EditText txt3 = (EditText) findViewById(R.id.editText3); final EditText txt4 = (EditText) findViewById(R.id.editText4); final EditText txt5 = (EditText) findViewById(R.id.editText5); final EditText txt6 = (EditText) findViewById(R.id.editText6); final EditText txt7 = (EditText) findViewById(R.id.editText7); final EditText txt8 = (EditText) findViewById(R.id.editText8); //final SlidingDrawer txt9 = (SlidingDrawer) findViewById(R.id.Spinner3); final EditText txt10 = (EditText) findViewById(R.id.editText10); Button button = (Button) findViewById(R.id.btnActivity); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapObject req_AddActivity = new SoapObject(NAMESPACE, METHOD_NAME); req_AddActivity.addProperty("strActivity", ""); req_AddActivity.addProperty("strActivityType", ""); req_AddActivity.addProperty("strAssignedTo", txt3.getText().toString()); req_AddActivity.addProperty("strBPCode", txt4.getText().toString()); req_AddActivity.addProperty("strBPName", txt5.getText().toString()); req_AddActivity.addProperty("strActivityDate", txt6.getText().toString()); req_AddActivity.addProperty("strContactPerson", txt7.getText().toString()); req_AddActivity.addProperty("strEndDate", txt8.getText().toString()); req_AddActivity.addProperty("strProgress", ""); req_AddActivity.addProperty("strRemarks", txt10.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(req_AddActivity); HttpTransportSE androidHttpTransport = new HttpTransportSE (URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //if (result.toString()=="True") //{ //Toast.makeText(WSTestActivity.this, "Activity added Successfully.", Toast.LENGTH_SHORT).show(); //} Toast.makeText(WSTestActivity.this, result.toString(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText(result.toString()); } catch(Exception E) { Toast.makeText(WSTestActivity.this, E.getClass().getName() + ": " + E.getMessage(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage()); } //Toast.makeText(WSTestActivity.this, "Caught", Toast.LENGTH_SHORT).show(); } }); } } </code></pre> <p>Try this It's working on my local machine. The Webservice returns true if the activity is added successfully. I hope it will help you.</p>
10,034,890
0
Synchronized block and monitor objects <p>Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used "this" as a monitor object instead of "msg".</p> <pre><code>public void display(String msg) { synchronized(msg) { for(int i=1;i&lt;=20;i++) { System.out.println("Name= "+msg); } } } </code></pre>
27,088,076
0
<p>Here is a <code>gnu awk</code> solution (due to multiple characters in <code>RS</code>):</p> <pre><code>awk -v RS=" |\n" '/([yeo])$/' file apple tomato empty </code></pre> <p>Here <code>RS</code> is set to space or newline, so it will run one and one word on each line.</p>
7,586,546
0
<p>You have to edit your .csproj file and in the Debug PropertyGroup you'll have to add the following: </p> <pre><code>&lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; </code></pre> <p>I have the following on <strong>Release</strong> and <strong>ReleaseCERT</strong> Configurations in my Project.csproj (I've only added the AutoParameterizationWebConfigConnectionStrings line):</p> <pre><code>&lt;PropertyGroup Condition=" '$(Configuration)|$(Platform)' == '**Release**|AnyCPU' "&gt; &lt;DebugType&gt;pdbonly&lt;/DebugType&gt; &lt;Optimize&gt;true&lt;/Optimize&gt; &lt;OutputPath&gt;bin\&lt;/OutputPath&gt; &lt;DefineConstants&gt;TRACE&lt;/DefineConstants&gt; &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt; &lt;WarningLevel&gt;4&lt;/WarningLevel&gt; &lt;!-- add the following line to avoid ConnectionString tokenization --&gt; &lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition="'$(Configuration)|$(Platform)' == '**ReleaseCERT**|AnyCPU'"&gt; &lt;OutputPath&gt;bin\&lt;/OutputPath&gt; &lt;DefineConstants&gt;TRACE&lt;/DefineConstants&gt; &lt;Optimize&gt;true&lt;/Optimize&gt; &lt;DebugType&gt;pdbonly&lt;/DebugType&gt; &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt; &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt; &lt;!-- add the following line to avoid ConnectionString tokenization --&gt; &lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; &lt;/PropertyGroup&gt; </code></pre>
30,321,752
0
How can I declare a global variable in ruby on rails? <p>How can I declare a global variable in "ruby on rails"?</p> <p>sample code:</p> <p>in my controller#application.rb:</p> <pre><code>def user_clicked() @current_userid = params[:user_id] end </code></pre> <p>in my layout#application.html.haml: I have sidebar with this link</p> <pre><code>= link_to "John", user_clicked_path(:user_id =&gt; 1) = link_to "Doe", user_clicked_path(:user_id =&gt; 2) = link_to "View clicked user", view_user_path </code></pre> <p>in my views#view_user.html.haml:</p> <pre><code>%h2 @current_userid </code></pre> <p>I hope you will understand the logic and what I am trying to say. I'm a noob in ruby on rails. Please help ^_^</p> <p>I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc.<br> The above is only a sample scenario. If I click the John or Doe link, it will send a user_id to the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1 or Doe=2.<br> Of course if I click the "View clicked user" link first, it will display nil.</p>
40,295,686
0
Nightwatch: Get text value of an element when hover over it <p>I have an element on a page that when I hover over it, a tooltip is displayed with text. How do I get the text value? I need to verify that correct text is displayed.</p> <p>We are using Nightwatch.js</p> <p>Many thanks!</p> <p><a href="https://i.stack.imgur.com/VaOBu.png" rel="nofollow">element with tooltip</a></p> <p><a href="https://i.stack.imgur.com/6dKek.png" rel="nofollow">element id</a></p>
30,715,405
0
<p>Simplest possible solution is to put user entered key in some global variable(or somewhere where you can access it later) and just call a method to instantiate your DbContext with correct connection string. Something like this:</p> <pre><code>public MyDbContext CreateContext() { if (user_entered_key == "one") { return new MyDbContext("Db1DbContext"); } else if (user_entered_key == "two") { return new MyDbContext("Db2DbContext"); } else { return new MyDbContext("Db3DbContext"); } } </code></pre>
7,164,217
0
<p>Try this instead (no loops):</p> <pre><code>A = (FA*KS2).'; %'# A is now 25-by-1 S2 = SS2(1,:)*sin(A) + SS2(2,:)*cos(A); </code></pre>
2,715,392
0
<pre><code>var addedStateEntries = Context .ObjectStateManager .GetObjectStateEntries(EntityState.Added); </code></pre>
11,402,420
0
<p>By "bias", I am assuming that you want to shift the result so that all pixel values are non-negative.</p> <p>In the notes for pixConvolve(), it says that the absolute value is taken to avoid negative output. It also says that if you wish to keep the negative values, use fpixConvolve() instead, which operates on an FPix and generates an FPix.</p> <p>If you want a biased result without clipping, it is in general necessary to do the following:</p> <ul> <li>(1) pixConvertToFpix() -- convert to an FPix</li> <li>(2) fpixConvolve() -- do the convolution on the FPix, producing an FPix</li> <li>(3) fpixGetMin() -- determine the bias required to make all values nonzero</li> <li>(4) fpixAddMultConstant() -- add the bias to the FPix</li> <li>(5) fpixGetMax() -- find the max value; if > 255, you need a 16 bpp Pix to represent it</li> <li>(6) fpixConvertToPix -- convert back to a pix</li> </ul> <p>Perhaps the leptonica maintainer (me) should bundle this up into a simple interface ;-)</p> <p>OK, here's a function, following the outline that I wrote above, that should give enough flexibility to do these convolutions.</p> <pre><code> /*! * pixConvolveWithBias() * Input: pixs (8 bpp; no colormap) * kel1 * kel2 (can be null; use if separable) * force8 (if 1, force output to 8 bpp; otherwise, determine * output depth by the dynamic range of pixel values) * &amp;bias (&lt;return&gt; applied bias) * Return: pixd (8 or 16 bpp) * * Notes: * (1) This does a convolution with either a single kernel or * a pair of separable kernels, and automatically applies whatever * bias (shift) is required so that the resulting pixel values * are non-negative. * (2) If there are no negative values in the kernel, a normalized * convolution is performed, with 8 bpp output. * (3) If there are negative values in the kernel, the pix is * converted to an fpix, the convolution is done on the fpix, and * a bias (shift) may need to be applied. * (4) If force8 == TRUE and the range of values after the convolution * is &gt; 255, the output values will be scaled to fit in * [0 ... 255]. * If force8 == FALSE, the output will be either 8 or 16 bpp, * to accommodate the dynamic range of output values without * scaling. */ PIX * pixConvolveWithBias(PIX *pixs, L_KERNEL *kel1, L_KERNEL *kel2, l_int32 force8, l_int32 *pbias) { l_int32 outdepth; l_float32 min1, min2, min, minval, maxval, range; FPIX *fpix1, *fpix2; PIX *pixd; PROCNAME("pixConvolveWithBias"); if (!pixs || pixGetDepth(pixs) != 8) return (PIX *)ERROR_PTR("pixs undefined or not 8 bpp", procName, NULL); if (pixGetColormap(pixs)) return (PIX *)ERROR_PTR("pixs has colormap", procName, NULL); if (!kel1) return (PIX *)ERROR_PTR("kel1 not defined", procName, NULL); /* Determine if negative values can be produced in convolution */ kernelGetMinMax(kel1, &amp;min1, NULL); min2 = 0.0; if (kel2) kernelGetMinMax(kel2, &amp;min2, NULL); min = L_MIN(min1, min2); if (min &gt;= 0.0) { if (!kel2) return pixConvolve(pixs, kel1, 8, 1); else return pixConvolveSep(pixs, kel1, kel2, 8, 1); } /* Bias may need to be applied; convert to fpix and convolve */ fpix1 = pixConvertToFPix(pixs, 1); if (!kel2) fpix2 = fpixConvolve(fpix1, kel1, 1); else fpix2 = fpixConvolveSep(fpix1, kel1, kel2, 1); fpixDestroy(&amp;fpix1); /* Determine the bias and the dynamic range. * If the dynamic range is &lt;= 255, just shift the values by the * bias, if any. * If the dynamic range is &gt; 255, there are two cases: * (1) the output depth is not forced to 8 bpp ==&gt; outdepth = 16 * (2) the output depth is forced to 8 ==&gt; linearly map the * pixel values to [0 ... 255]. */ fpixGetMin(fpix2, &amp;minval, NULL, NULL); fpixGetMax(fpix2, &amp;maxval, NULL, NULL); range = maxval - minval; *pbias = (minval &lt; 0.0) ? -minval : 0.0; fpixAddMultConstant(fpix2, *pbias, 1.0); /* shift: min val ==&gt; 0 */ if (range &lt;= 255 || !force8) { /* no scaling of output values */ outdepth = (range &gt; 255) ? 16 : 8; } else { /* scale output values to fit in 8 bpp */ fpixAddMultConstant(fpix2, 0.0, (255.0 / range)); outdepth = 8; } /* Convert back to pix; it won't do any clipping */ pixd = fpixConvertToPix(fpix2, outdepth, L_CLIP_TO_ZERO, 0); fpixDestroy(&amp;fpix2); return pixd; } </code></pre>
35,522,321
0
<p>If you rellay don't want to use the lenght.... use the maths!</p> <pre><code>my_str = Qstring::number(my_str.toInt()*pow(10,2-log10(my_str.toInt()))) </code></pre> <p>or:</p> <pre><code>my_str = my_str.append('0',2-log10(my_str.toInt())) </code></pre> <p>but it would be much simpler/quick to do this:</p> <pre><code>my_str = my_str.append('0',3-my_str.length()) </code></pre>
32,951,147
0
Output file in a certain way via Java <p>Having a little bit of an issue. I have successfully output a file based on the timestamp order, however, theres another condition i am trying to add also to alphabetically order if the time stamp is the same.</p> <p>for example:</p> <p>[TIMESTAMP = 12:30][EVENT=B]</p> <p>[TIMESTAMP = 12:30][EVENT=U]</p> <p>[TIMESTAMP = 12:30][EVENT=A]</p> <p>and i want it to output</p> <p>[TIMESTAMP = 12:30][EVENT=A]</p> <p>[TIMESTAMP = 12:30][EVENT=B]</p> <p>[TIMESTAMP = 12:30][EVENT=U]</p> <p>my current code at the moment stands:</p> <pre><code>package Organiser; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Organiser { public static void main(String[] args) throws FileNotFoundException { ArrayList&lt;String&gt; lines = new ArrayList&lt;&gt;(); String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1"; Scanner fileIn = new Scanner(new File(directory + ".txt")); PrintWriter out = new PrintWriter(directory + "_ordered.txt"); while (fileIn.hasNextLine() == true) { lines.add(fileIn.nextLine()); Collections.sort(lines); System.out.println("Reading..."); } for (String output : lines) { out.println(output + "\n"); } out.close(); System.out.println("Complete - See " + directory + "_ordered.txt"); } } </code></pre> <p>any ideas</p> <p>EDIT: this is only for sample data, i only want this to occur when the time stamps the same, otherwise, it will order accordingly as per the time stamp.</p> <p>Sample file:</p> <p><a href="https://www.dropbox.com/s/611psg6qw4nl9pw/ex1.txt?dl=0" rel="nofollow">https://www.dropbox.com/s/611psg6qw4nl9pw/ex1.txt?dl=0</a></p>
12,400,026
0
<p>Add a JoinColumn annotation to your ManyToOne field to specify a column name different than the one inferred by jpa </p> <p>Something like</p> <pre><code>@JoinColumn(name="clubadmin_id", referencedColumnName="clubadmin_id") </code></pre>
12,440,128
0
sd-toolkit sdk for barcode scanning on iPhone, does it work with the camera? <p>Like the question says, can you scan a barcode with the camera? or do you have to have the barcode on an image in the phone?</p>
11,069,563
0
<p>Probably you misspelled the class name or you didn't import the class name, check that and try again. And also what Andrew Said.</p> <p>In case you are using the IDE Eclipse if you press Ctrl+Shift+o (letter O) it imports everything automatically for you.</p> <p>Hope it helps.</p>
2,498,312
0
<p>I don't have the docs right in front of me, but I think if you mark the MouseButtonEventArgs object as Handled it stops the event from going up the chain.</p> <p>Should be as simple as </p> <pre><code>e.Handled = true; </code></pre> <p>Please somebody correct me if I am wrong about this.</p>
1,203,045
0
<p>I believe you can't add the ';' at the end. So try:</p> <pre><code>DbCommand command = new OracleCommand( "insert into hardware (HardwareID) VALUES (6)", myConnection); command.ExecuteNonQuery(); </code></pre>
27,776,172
0
<p>If you can access to your servlet from your browser, therefor you can access it programmatically. For example in <a href="http://theopentutorials.com/tutorials/android/http/android-how-to-send-http-get-request-to-servlet-using-apache-http-client/" rel="nofollow">this</a> link you can see how you can access to a servlet from android project. You just need to create an GET/POST HTTP request.</p>
25,234,753
0
<h2>Solution</h2> <h3>Here is the working solution I ended up with:</h3> <pre><code>@Nonnull protected Class&lt;T&gt; getEntityType() { (Class&lt;T&gt;) new TypeToken&lt;T&gt;(getClass()) {}.getRawType(); } /** * purge ObjectMetadata records that don't have matching Objects in the GCS anymore. */ public void purgeOrphans() { ofy().transact(new Work&lt;VoidWork&gt;() { @Override public VoidWork run() { try { for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable()) { final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename()); if (md == null) { ofy().delete().entity(bm); } } } catch (IOException e) { L.error(e.getMessage()); } return null; } }); } </code></pre>
37,738,247
0
Whats the proper tab order for invalid inputs? <p>For accessibility reasons, the first invalid input in a form ought to be focused upon form submission. This prevents the non-sighted user from being forced to hunt for the invalid inputs.</p> <p>My question pertains to tab order. After the first invalid input is focused, when the user clicks tab again, should the focus go to the next invalid input or just the next element in the normal tab order?</p> <p>Take this pseudo code for example. If input numbers 2 and 4 have errors, when the form is submitted then focus will be moved to input number 2. The next time the user presses the <code>tab</code> key does the focus go to input 3 or 4?</p> <pre><code>&lt;input id="1"&gt; &lt;input id="2"&gt; &lt;-- invalid &lt;input id="3"&gt; &lt;input id="4"&gt; &lt;-- invalid &lt;input id="5"&gt; &lt;button type="submit"&gt; </code></pre>