id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
2,340,355
What is the usage of global:: keyword in C#?
<p>What is the usage of <code>global::</code> keyword in C#? When must we use this keyword?</p>
2,340,364
1
0
null
2010-02-26 08:35:07.22 UTC
5
2010-02-26 11:48:10.007 UTC
2010-02-26 09:08:40.943 UTC
null
33
null
191,997
null
1
31
c#|syntax|keyword
3,037
<p>Technically, <code>global</code> is not a keyword: it's a so-called "contextual keyword". These have special meaning only in a limited program context and can be used as identifiers outside that context.</p> <p><code>global</code> can and should be used whenever there's ambiguity or whenever a member is hidden. From <a href="http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx" rel="noreferrer">here</a>:</p> <pre><code>class TestApp { // Define a new class called 'System' to cause problems. public class System { } // Define a constant called 'Console' to cause more problems. const int Console = 7; const int number = 66; static void Main() { // Error Accesses TestApp.Console Console.WriteLine(number); // Error either System.Console.WriteLine(number); // This, however, is fine global::System.Console.WriteLine(number); } } </code></pre> <p>Note, however, that <code>global</code> doesn't work when no namespace is specified for the type:</p> <pre><code>// See: no namespace here public static class System { public static void Main() { // "System" doesn't have a namespace, so this // will refer to this class! global::System.Console.WriteLine("Hello, world!"); } } </code></pre>
2,681,466
jsonp with jquery
<p>Can you give a very simple example of reading a jsonp request with jquery? I just can't get it to work.</p>
2,686,406
1
0
null
2010-04-21 08:54:31.27 UTC
41
2013-03-15 07:32:46.24 UTC
null
null
null
null
219,579
null
1
89
jquery|ajax|jsonp
80,243
<p>Here is working example:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Twitter 2.0&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt;&lt;body&gt; &lt;div id='tweet-list'&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var url = "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json"; $.getJSON(url + "?callback=?", null, function(tweets) { for(i in tweets) { tweet = tweets[i]; $("#tweet-list").append(tweet.text + "&lt;hr /&gt;"); } }); }); &lt;/script&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Notice the <code>?callback=?</code> at the end of the requested URL. That indicates to the <code>getJSON</code> function that we want to use JSONP. Remove it and a vanilla JSON request will be used. Which will fail due to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same origin policy</a>.</p> <p>You can find more information and examples on the JQuery site: <a href="http://api.jquery.com/jQuery.getJSON/" rel="noreferrer">http://api.jquery.com/jQuery.getJSON/</a></p>
38,593,371
How can I make a simple HTTP request in MainActivity.java? (Android Studio)
<p>I'm using Android Studio, and I've spent a few hours trying to do a simple HTTP request in my MainActivity.java file, and tried multiple ways, and seen many web pages on the subject, yet cannot figure it out.</p> <p>When I try OkHttp, I get a error about not being able to do it on the main thread. Now I'm trying to do it this way:</p> <pre><code>public static String getUrlContent(String sUrl) throws Exception { URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String content = "", line; while ((line = rd.readLine()) != null) { content += line + "\n"; } return content; } </code></pre> <p>I put that method directly in MainActivity.java, and my click event executes it from another method that is also in MainActivity.java:</p> <pre><code>try { String str = getUrlContent("https://example.com/WAN_IP.php"); displayMessage(str); } catch(Exception e){ displayMessage(e.getMessage()); } </code></pre> <p>But right now there is no crash, and I can tell there is an exception thrown on the line that starts "BufferedReader", but e.getMessage() is blank.</p> <p>I'm brand new to Android Studio and java, so please be kind and help me with this very basic problem. Eventually I will need to do post requests to the server, and it seems that OkHttp is the best way to go, but I'm not finding the "Hello World" of OkHttp in Android Studio documented anywhere online.</p>
38,593,586
3
3
null
2016-07-26 14:58:26.867 UTC
5
2020-05-18 01:01:25.92 UTC
null
null
null
null
667,090
null
1
6
java|http|android-studio|okhttp
38,925
<p>You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.</p> <p>Android force this behaviour by throwing an exception if you use the <code>HttpUrlConnection</code> object from the main thread.</p> <p>You should then make your network request in the background, and then update the UI on the main thread. The <a href="https://developer.android.com/reference/android/os/AsyncTask.html" rel="noreferrer"><code>AsyncTask</code></a> class can be very handy for this use case !</p> <pre><code>private class GetUrlContentTask extends AsyncTask&lt;String, Integer, String&gt; { protected String doInBackground(String... urls) { URL url = new URL(urls[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String content = "", line; while ((line = rd.readLine()) != null) { content += line + "\n"; } return content; } protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(String result) { // this is executed on the main thread after the process is over // update your UI here displayMessage(result); } } </code></pre> <p>And you start this process this way:</p> <pre><code>new GetUrlContentTask().execute(sUrl) </code></pre>
31,575,770
How can I fix Laravel 5.1 - 404 Not Found?
<p>I am trying to use Laravel 5.1 for the first time. I was able to install it and <code>https://sub.example.com/laravel/public/</code> is displaying what is should. However, views I create are giving me a 404 error Page not found.</p> <p>Here is what I have done so far:</p> <p>I created a controller in <code>laravel\app\Http\controllers\Authors.php</code></p> <p>Here is the code behind the <code>Authors.php</code> file</p> <pre><code>&lt;?php class Authors_Controller extends Base_Controller { public $restful = true; public function get_index() { return View::make('authors.index') -&gt;with('title', 'Authors and Books') -&gt;with('authors', Author::order_by('name')-&gt;get()); } } </code></pre> <p>Then I created a view in <code>laravel\resources\views\Authors\index.blade.php</code></p> <p>Here is the code behind the <code>index.blade.php</code> file</p> <pre><code>@layout('layouts.default') @section('content') Hello, this is a test @endsection </code></pre> <p>Then I created a layout in <code>laravel\resources\views\layouts\default.blade.php</code></p> <p>Here is the code behind the <code>default.blade.php</code> file</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;{{ $title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; @if(Session::has('message')) &lt;p style="color: green;"&gt;{{ Session::get('message') }}&lt;/p&gt; @endif @yield('content') Hello - My first test &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Finally I created a route in <code>laravel\app\Http\routes.php</code></p> <pre><code>&lt;?php Route::get('/', function () { return view('welcome'); }); Route::get('authors', array('as'=&gt;'authors', 'uses'=&gt;'authors@index')); </code></pre> <p>But for some reason I keep getting 404 error Page not found.</p> <p>I enabled the mod_rewrite on my Apache 2.4.9 by uncommenting out the line</p> <pre><code>LoadModule rewrite_module modules/mod_rewrite.so </code></pre> <p>Then restarted Apache.</p> <p>From what I can tell in the <code>php_info()</code> output the mod_rewrite is enabled</p> <pre><code>Loaded Modules core mod_win32 mpm_winnt http_core mod_so mod_php5 mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl </code></pre> <p>My current .htaccess file looks like this "which is the factory default"</p> <p> Options -MultiViews </p> <pre><code>RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </code></pre> <p></p> <p>I have also tried to change it to the code below as per the <a href="http://laravel.com/docs/5.1" rel="nofollow noreferrer">documentation</a>:</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </code></pre> <p>However, I am still getting the 404 page when I go to</p> <pre><code>https://sub.example.com/laravel/public/authors </code></pre> <p>What am I doing wrong? How can I fix this problem?</p>
31,627,316
6
0
null
2015-07-22 23:32:51.913 UTC
6
2020-07-09 22:09:04.2 UTC
2019-09-29 10:46:33.037 UTC
null
8,463,337
null
4,967,389
null
1
10
php|apache|.htaccess|laravel|mod-rewrite
79,749
<p>I see the same behaviour of being able to visit the / route but all other pages return a 404 when I first setup Laravel sites.</p> <p>In your apache config file httpd.conf or httpd-vhosts.conf you need to enable the directives that can be placed in the .htaccess file.</p> <p>Here is an example of my VirtualHost configuration:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin [email protected] DocumentRoot "C:/www/laravel_authority-controller_app/public" ServerName authoritycontroller.www ErrorLog "logs/AuthorityController.www-error.log" CustomLog "logs/AuthorityController.www-access.log" common &lt;Directory "C:/www/laravel_authority-controller_app/public"&gt; # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks Includes ExecCGI # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # AllowOverride FileInfo AuthConfig Limit # AllowOverride All # # Controls who can get stuff from this server. # Require all granted &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>The key entry for your issue is <code>AllowOverride All</code>. This should be enough to get the website working but you can also include <code>options</code> and <code>Require all granted</code> if they are consistent across the entire website.</p>
6,160,403
Can I add Task List items to csHTML in Visual Studio 2010?
<p><strong>Background:</strong></p> <p>I am fairly new to Visual Studio 2010 (worked on Lua, LIMSBasic (Labware) and a few others that didn't use decent IDEs and love the idea of task lists being pulled out of the comments I write right in the code.</p> <p>I have worked out how to use comments to generate all manner of "// TODO:" and other task list and found some good lists on stackoverflow for what type I can do but I can't establish <em>(no mater how hard I abuse google)</em> even if it's possible to add them to csHTML files <em>nevermind how</em>!</p> <p>I have tried using all of the following:</p> <pre><code>&lt;!--// TODO: Work out how to add todo stuff to the tasklist!--&gt; // TODO: Work out how to add todo stuff to the tasklist! &lt;!--TODO: Work out how to add todo stuff to the tasklist!--&gt; &lt;!-- TODO: Work out how to add todo stuff to the tasklist!--&gt; @// TODO: Work out how to add todo stuff to the tasklist! </code></pre> <p>...but nothing was added to the Task List.</p> <p><strong>Question:</strong></p> <p>So my question(s) is/are: Is it possible to add "TODO:" and other task list item to csHTML (MVC 3 using razor) and if so HOW?</p>
6,160,812
1
0
null
2011-05-28 07:52:40.317 UTC
2
2016-08-01 09:02:57.79 UTC
2016-01-22 10:14:08.25 UTC
null
769,294
null
769,294
null
1
33
asp.net|asp.net-mvc|visual-studio|asp.net-mvc-3|tasklist
6,870
<p>The following should work.</p> <pre><code>@{ //TODO: do stuff here } </code></pre> <p>or</p> <pre><code>@{/* TODO: do stuff here */} </code></pre> <p>As it first has to go into "code" mode, and then you can use a task comment.</p> <p>But apparently the following does not work (in my visual studio):</p> <pre><code>@*TODO: do stuff here *@ </code></pre>
24,728,394
Is there a way to create a function pointer to a method in Rust?
<p>For example,</p> <pre><code>struct Foo; impl Foo { fn bar(&amp;self) {} fn baz(&amp;self) {} } fn main() { let foo = Foo; let callback = foo.bar; } </code></pre> <pre class="lang-none prettyprint-override"><code>error[E0615]: attempted to take value of method `bar` on type `Foo` --&gt; src/main.rs:10:24 | 10 | let callback = foo.bar; | ^^^ help: use parentheses to call the method: `bar()` </code></pre>
24,728,592
1
0
null
2014-07-14 01:17:18.583 UTC
4
2019-06-03 15:04:16.137 UTC
2019-06-03 15:02:06.183 UTC
null
155,423
null
272,642
null
1
29
rust
11,610
<p>With <a href="https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name" rel="noreferrer">fully-qualified syntax</a>, <code>Foo::bar</code> will work, yielding a <code>fn(&amp;Foo) -&gt; ()</code> (similar to Python). </p> <pre><code>let callback = Foo::bar; // called like callback(&amp;foo); </code></pre> <p>However, if you want it with the <code>self</code> variable already bound (as in, calling <code>callback()</code> will be the same as calling <code>bar</code> on the <code>foo</code> object), then you need to use an explicit closure:</p> <pre><code>let callback = || foo.bar(); // called like callback(); </code></pre>
56,473,899
error TS2554: Expected 2 arguments, but got 1 with @ViewChild
<p>I was using ViewChild as follows:</p> <pre><code>@ViewChild("InternalMedia") localStream; @ViewChild("emoji") mEmoji; </code></pre> <p>Which was working fine till angular-7.x</p> <p>as soon as I upgraded it to angular-8.x it started giving following error</p> <pre><code>.../call_emoji/component.ts(41,4): error TS2554: Expected 2 arguments, but got 1. </code></pre> <p>I checked <a href="https://angular.io/api/core/ViewChild" rel="noreferrer">https://angular.io/api/core/ViewChild</a> and when I change it to </p> <pre><code>@ViewChild("InternalMedia",{static:false}) remoteStream; </code></pre> <p>It works. I'm not getting what static does and what should be it's value to work as previous?</p>
56,474,074
2
0
null
2019-06-06 08:43:26.597 UTC
2
2019-06-25 10:57:09.3 UTC
2019-06-06 08:49:38.093 UTC
null
4,655,241
null
4,655,241
null
1
51
angular|typescript|angular7|viewchild|angular8
63,043
<p>According to the Angular documentation static checks</p> <blockquote> <p>whether or not to resolve query results before change detection runs (i.e. return static results only). If this option is not provided, the compiler will fall back to its default behavior, which is to use query results to determine the timing of query resolution. If any query results are inside a nested view (e.g. *ngIf), the query will be resolved after change detection runs. Otherwise, it will be resolved before change detection runs.</p> </blockquote> <p>Effectively this determines when the query is run to retrieve the element. If set to false the query will be run after any change detections. If set to true it will be run immediately.</p> <p>For more information and why this option is included please see <a href="https://github.com/angular/angular/pull/28810" rel="noreferrer">this Github issue</a>.</p> <p>The behavior you are probably looking for is to set <code>static</code> to false. This will result in the old behavior. However if your component's view is not dynamic (for example you do not use *ngIf) you should be able to set it to true safely.</p>
23,744,612
Problems inherent to jQuery $.Deferred (jQuery 1.x/2.x)
<p>@Domenic has a very thorough article on the failings of jQuery deferred objects: <a href="http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/">You're missing the Point of Promises</a>. In it Domenic highlights a few failings of jQuery promises in comparison to others including <a href="https://github.com/kriskowal/q">Q</a>, when.js, RSVP.js and ES6 promises.</p> <p>I walk away from Domenic's article feeling that jQuery promises have an inherent failing, conceptually. I am trying to put examples to the concept.</p> <p>I gather there are two concerns with the jQuery implementation:</p> <h2>1. The <code>.then</code> method is not chainable</h2> <p>In other words</p> <pre><code>promise.then(a).then(b) </code></pre> <p>jQuery will call <code>a</code> then <code>b</code> when the <code>promise</code> is fulfilled.</p> <p>Since <code>.then</code> returns a new promise in the other promise libraries, their equivalent would be:</p> <pre><code>promise.then(a) promise.then(b) </code></pre> <h2>2. The exception handling is bubbled in jQuery.</h2> <p>The other issue would seem to be exception handling, namely:</p> <pre><code>try { promise.then(a) } catch (e) { } </code></pre> <p>The equivalent in Q would be:</p> <pre><code>try { promise.then(a).done() } catch (e) { // .done() re-throws any exceptions from a } </code></pre> <p>In jQuery the exception throws and bubbles when <code>a</code> fails to the catch block. In the other promises any exception in <code>a</code> would be carried through to the <code>.done</code> or <code>.catch</code> or other async catch. If none of the promise API calls catch the exception it disappears (hence the Q best-practice of e.g. using <code>.done</code> to release any unhandled exceptions).</p> <p>&nbsp;</p> <p>Do the problems above cover the concerns with the jQuery implementation of promises, or have I misunderstood or missed issues?</p> <hr> <p><strong><em>Edit</em></strong> This question relates to jQuery &lt; 3.0; as of <a href="http://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/">jQuery 3.0 alpha</a> jQuery is Promises/A+ compliant.</p>
23,744,774
1
0
null
2014-05-19 18:22:08.67 UTC
28
2016-04-12 10:28:47.463 UTC
2015-07-14 17:56:56.963 UTC
null
19,212
null
19,212
null
1
47
jquery|promise|jquery-deferred|q|es6-promise
15,387
<p>Update: jQuery 3.0 has fixed the problems outlined below. It is truly Promises/A+ compliant.</p> <h2>Yes, jQuery promises have serious and inherent problems.</h2> <p>That said, since the article was written jQuery made significant efforts to be more Promises/Aplus complaint and they now have a .then method that chains. </p> <p>So even in jQuery <code>returnsPromise().then(a).then(b)</code> for promise returning functions <code>a</code> and <code>b</code> will work as expected, unwrapping the return value before continuing forward. As illustrated in this <a href="http://jsfiddle.net/1njL4w1t/">fiddle</a>:</p> <pre><code>function timeout(){ var d = $.Deferred(); setTimeout(function(){ d.resolve(); },1000); return d.promise(); } timeout().then(function(){ document.body.innerHTML = "First"; return timeout(); }).then(function(){ document.body.innerHTML += "&lt;br /&gt;Second"; return timeout(); }).then(function(){ document.body.innerHTML += "&lt;br /&gt;Third"; return timeout(); }); </code></pre> <h2>However, the two <em>huge</em> problems with jQuery are error handling and unexpected execution order.</h2> <h3>Error handling</h3> <p>There is no way to mark a jQuery promise that rejected as "Handled", even if you resolve it, unlike catch. This makes rejections in jQuery inherently broken and very hard to use, nothing like synchronous <code>try/catch</code>.</p> <p>Can you guess what logs here? (<a href="http://jsfiddle.net/tY6ZV/">fiddle</a>)</p> <pre><code>timeout().then(function(){ throw new Error("Boo"); }).then(function(){ console.log("Hello World"); },function(){ console.log("In Error Handler"); }).then(function(){ console.log("This should have run"); }).fail(function(){ console.log("But this does instead"); }); </code></pre> <p>If you guessed <code>"uncaught Error: boo"</code> you were correct. jQuery promises are <strong>not throw safe</strong>. They will not let you handle any thrown errors unlike Promises/Aplus promises. What about reject safety? (<a href="http://jsfiddle.net/bcTYM/">fiddle</a>)</p> <pre><code>timeout().then(function(){ var d = $.Deferred(); d.reject(); return d; }).then(function(){ console.log("Hello World"); },function(){ console.log("In Error Handler"); }).then(function(){ console.log("This should have run"); }).fail(function(){ console.log("But this does instead"); }); </code></pre> <p>The following logs <code>"In Error Handler" "But this does instead"</code> - there is no way to handle a jQuery promise rejection at all. This is unlike the flow you'd expect:</p> <pre><code>try{ throw new Error("Hello World"); } catch(e){ console.log("In Error handler"); } console.log("This should have run"); </code></pre> <p>Which is the flow you get with Promises/A+ libraries like Bluebird and Q, and what you'd expect for usefulness. This is <em>huge</em> and throw safety is a big selling point for promises. Here is <a href="http://jsfiddle.net/PvJcX/15/">Bluebird acting correctly in this case</a>.</p> <h3>Execution order</h3> <p>jQuery will execute the passed function <em>immediately</em> rather than deferring it if the underlying promise already resolved, so code will behave differently depending on whether the promise we're attaching a handler to rejected already resolved. This is effectively <a href="http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony">releasing Zalgo</a> and can cause some of the most painful bugs. This creates some of the hardest to debug bugs.</p> <p>If we look at the following code: (<a href="http://jsfiddle.net/47tkdjLo/">fiddle</a>)</p> <pre><code>function timeout(){ var d = $.Deferred(); setTimeout(function(){ d.resolve(); },1000); return d.promise(); } console.log("This"); var p = timeout(); p.then(function(){ console.log("expected from an async api."); }); console.log("is"); setTimeout(function(){ console.log("He"); p.then(function(){ console.log("̟̺̜̙͉Z̤̲̙̙͎̥̝A͎̣͔̙͘L̥̻̗̳̻̳̳͢G͉̖̯͓̞̩̦O̹̹̺!̙͈͎̞̬ *"); }); console.log("Comes"); },2000); </code></pre> <p>We can observe that oh so dangerous behavior, the <code>setTimeout</code> waits for the original timeout to end, so jQuery switches its execution order because... who likes deterministic APIs that don't cause stack overflows? This is why the Promises/A+ specification requires that promises are always deferred to the next execution of the event loop. </p> <h3>Side note</h3> <p>Worth mentioning that newer and stronger promise libraries like Bluebird (and experimentally When) do not require <code>.done</code> at the end of the chain like Q does since they figure out unhandled rejections themselves, they're also much much faster than jQuery promises or Q promises.</p>
23,618,634
How do you catch CancellationToken.Register callback exceptions?
<p>I am using async I/O to communicate with an HID device, and I would like to throw a catchable exception when there is a timeout. I've got the following read method:</p> <pre><code>public async Task&lt;int&gt; Read( byte[] buffer, int? size=null ) { size = size ?? buffer.Length; using( var cts = new CancellationTokenSource() ) { cts.CancelAfter( 1000 ); cts.Token.Register( () =&gt; { throw new TimeoutException( "read timeout" ); }, true ); try { var t = stream.ReadAsync( buffer, 0, size.Value, cts.Token ); await t; return t.Result; } catch( Exception ex ) { Debug.WriteLine( "exception" ); return 0; } } } </code></pre> <p>The exception thrown from the Token's callback is not caught by any try/catch blocks and I'm not sure why. I assumed it would be thrown at the await, but it is not. Is there a way to catch this exception (or make it catchable by the caller of Read())?</p> <p><strong>EDIT:</strong> So I re-read the doc at <a href="http://msdn.microsoft.com/en-us/library/dd321635%28v=vs.110%29.aspx" rel="noreferrer">msdn</a>, and it says "Any exception the delegate generates will be propagated out of this method call."</p> <p>I'm not sure what it means by "propagated out of this method call", because even if I move the .Register() call into the try block the exception is still not caught.</p>
23,620,565
3
0
null
2014-05-12 20:51:50.243 UTC
8
2019-06-03 07:42:55.787 UTC
2014-05-12 23:02:12.333 UTC
null
618,895
null
618,895
null
1
10
c#|task-parallel-library|cancellationtokensource
11,582
<blockquote> <p>EDIT: So I re-read the doc at msdn, and it says "Any exception the delegate generates will be propagated out of this method call."</p> <p>I'm not sure what it means by "propagated out of this method call", because even if I move the .Register() call into the try block the exception is still not caught.</p> </blockquote> <p>What this means is that the caller of your cancellation callback (the code inside .NET Runtime) won't make an attempt to catch any exceptions you may throw there, so they will be propagated outside your callback, on whatever stack frame and synchronization context the callback was invoked on. This may crash the application, so you really should handle all non-fatal exceptions inside your callback. <em>Think of it as of an event handler.</em> After all, there may be multiple callbacks registered with <code>ct.Register()</code>, and each might throw. Which exception should have been propagated then?</p> <p>So, such exception will <em>not</em> be captured and propagated into the "client" side of the token (i.e., to the code which calls <code>CancellationToken.ThrowIfCancellationRequested</code>).</p> <p>Here's an alternative approach to throw <code>TimeoutException</code>, if you need to differentiate between user cancellation (e.g., a "Stop" button) and a timeout:</p> <pre><code>public async Task&lt;int&gt; Read( byte[] buffer, int? size=null, CancellationToken userToken) { size = size ?? buffer.Length; using( var cts = CancellationTokenSource.CreateLinkedTokenSource(userToken)) { cts.CancelAfter( 1000 ); try { var t = stream.ReadAsync( buffer, 0, size.Value, cts.Token ); try { await t; } catch (OperationCanceledException ex) { if (ex.CancellationToken == cts.Token) throw new TimeoutException("read timeout", ex); throw; } return t.Result; } catch( Exception ex ) { Debug.WriteLine( "exception" ); return 0; } } } </code></pre>
23,788,583
Search on descendants of an element
<p>With protractor whats the best way to select child elements? Say we have the layout below...</p> <pre class="lang-html prettyprint-override"><code>&lt;div id='parent_1'&gt; &lt;div class='red'&gt;Red&lt;/div&gt; &lt;div class='blue'&gt;Blue&lt;/div&gt; &lt;/div&gt; &lt;div id='parent_2'&gt; &lt;div class='red'&gt;Red&lt;/div&gt; &lt;div class='blue'&gt;Blue&lt;/div&gt; &lt;/div&gt; </code></pre> <p>With jQuery we'd do something like this.</p> <pre class="lang-js prettyprint-override"><code>var p1 = $('#parent_1'); var p1_red = $('.red', p1); //or p1.find('.red'); var p1_blue = $('.blue', p1); //or p1.find('.blue'); </code></pre> <p>But with Protractor does it make sense to first get the parent element? Since doing this <code>var p1 = element('#parent_1');</code> doesn't actually retrieve/search for the object until <code>getText()</code> or something is called. </p> <p>so doing this..</p> <p>Scenario 1 </p> <pre><code>expect(p1.element('.red')).toBe('red'); expect(p1.element('.blue')).toBe('blue'); </code></pre> <p>OR</p> <p>Scenario 2 </p> <pre><code>expect(element('#parent_1').element('.red')).toBe('red'); expect(element('#parent_1').element('.blue')).toBe('blue'); </code></pre> <p>OR</p> <p>Scenario 3 </p> <pre><code>expect(element('#parent_1 &gt; .red')).toBe('red'); expect(element('#parent_1 &gt; .blue')).toBe('blue'); </code></pre> <p><strong>Are there any benefits in one approach over the other?</strong></p> <p>This is what I'm doing but I don't know if there's any advantage of separating the parent from the cssSelector:</p> <pre class="lang-js prettyprint-override"><code>function getChild(cssSelector, parentElement){ return parentElement.$(cssSelector); } var parent = $('#parent_1'); var child_red = getChild('.red', parent); var child_blue = getChild('.blue', parent); </code></pre> <p>Looking at Protractor's <a href="https://github.com/angular/protractor/blob/master/docs/api.md#elementfinder">elementFinder</a> I could be doing this:</p> <pre class="lang-js prettyprint-override"><code>function getChild(cssSelector, parentCss){ return $(parentCss).$(cssSelector); } var child_red = getChild('.red', '#parent_1'); var child_blue = getChild('.blue', '#parent_1'); </code></pre>
24,895,439
1
0
null
2014-05-21 16:11:25.863 UTC
3
2019-04-30 12:40:41.943 UTC
2015-12-18 16:19:37.747 UTC
null
452,584
null
7,617
null
1
46
element|parent-child|protractor|chaining
46,700
<p>The advantage of separating the child from the child css selector would only be if you'd like to use the parent for something else. Otherwise, it's slightly faster to do it in one call, like <code>expect(element('#parent_1 &gt; .red')).toBe('red');</code> since Protractor doesn't need to make two calls to the browser in this case.</p> <p>Another reason to use the first approach would be if you were using a Locator strategy that cannot be expressed in CSS. For example:</p> <pre class="lang-js prettyprint-override"><code>var parent = element(by.css('.foo')); var child = parent.element(by.binding('childBinding')); expect(child.getText()).toEqual('whatever'); </code></pre>
52,741,533
How to Export CSV file from ASP.NET core
<p>I am trying to migrate code from ASP.net to ASP.net core.</p> <p>Where as in ASP.net code was like below,</p> <pre><code>var progresses = db.Progresses.Where(p =&gt; p.UserId == id).Include(p =&gt; p.User.UserMetaData).Include(p =&gt; p.Quiz).Include(p =&gt; p.User.Groups).OrderByDescending(p =&gt; p.UpdatedAt).ToList(); List&lt;ReportCSVModel&gt; reportCSVModels = new List&lt;ReportCSVModel&gt;(); const string downloadName = "Reports.csv"; var csv = new CsvWriter(Response.Output); csv.Configuration.RegisterClassMap&lt;ReportCSVMap&gt;(); Response.ClearContent(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName); csv.WriteHeader&lt;ReportCSVModel&gt;(); foreach (var progress in progresses) { var reportCSVModel = new ReportCSVModel(); reportCSVModel.Quiz = progress.Quiz.Title; reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString(); reportCSVModel.Status = progress.Status; reportCSVModel.CompletedDate = progress.UpdatedAt.ToString(); reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : ""; reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : ""; csv.WriteRecord&lt;ReportCSVModel&gt;(reportCSVModel); } Response.Flush(); Response.End(); return null; </code></pre> <p>But while using it in ASP.NET core, I Converted it like,</p> <pre><code>var progresses = _elearnContext.Progress.Where(p =&gt; p.UserId == id).Include(p =&gt; p.User.UserMetaData).Include(p =&gt; p.Quiz).Include(p =&gt; p.User.Groups).OrderByDescending(p =&gt; p.UpdatedAt).ToList(); // List&lt;ReportCSVModel&gt; reportCSVModels = new List&lt;ReportCSVModel&gt;(); List&lt;ReportCSVModel&gt; reportCSVModels = new List&lt;ReportCSVModel&gt;(); const string downloadName = "Reports.csv"; System.IO.TextWriter writeFile = new StreamWriter(Response.Body.ToString()); CsvWriter csv = new CsvWriter(writeFile); csv.Configuration.RegisterClassMap&lt;GroupReportCSVMap&gt;(); Response.Clear(); Response.ContentType = "application/octet-stream"; Response.Headers.Add("Content-Disposition", "attachment; filename=" + downloadName); csv.WriteHeader&lt;ReportCSVModel&gt;(); foreach (var progress in progresses) { var reportCSVModel = new ReportCSVModel(); reportCSVModel.Quiz = progress.Quiz.Title; reportCSVModel.Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString(); reportCSVModel.Status = progress.Status; reportCSVModel.CompletedDate = progress.UpdatedAt.ToString(); reportCSVModel.Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : ""; reportCSVModel.Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : ""; csv.WriteRecord&lt;ReportCSVModel&gt;(reportCSVModel); } Response.Clear(); return null; </code></pre> <p>In ASP.net where <code>Response.Output</code> is available but its not available in core. So I tried to use it like <code>Response.Body</code></p> <p>Can Anybody tell me, where I did wrong?</p>
52,742,357
3
0
null
2018-10-10 13:37:22.24 UTC
4
2020-07-15 06:35:46.937 UTC
2018-10-10 14:33:39.177 UTC
null
5,233,410
null
7,743,628
null
1
11
c#|asp.net-core-mvc|export-to-csv|csv-write-stream
40,911
<p>Consider changing approach to align more with current suggested syntax.</p> <p>Construct the CSV and return a FileResult, which allows the code to not have to directly manipulate the <code>Response</code> object.</p> <pre><code>[HttpGet] public IActionResult MyExportAction() { var progresses = _elearnContext.Progress.Where(p =&gt; p.UserId == id) .Include(p =&gt; p.User.UserMetaData) .Include(p =&gt; p.Quiz) .Include(p =&gt; p.User.Groups) .OrderByDescending(p =&gt; p.UpdatedAt) .ToList() .Select(progress =&gt; new ReportCSVModel() { Quiz = progress.Quiz.Title, Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString(), Status = progress.Status, CompletedDate = progress.UpdatedAt.ToString(), Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "", Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : "" } ); List&lt;ReportCSVModel&gt; reportCSVModels = progresses.ToList(); var stream = new MemoryStream(); using(var writeFile = new StreamWriter(stream, leaveOpen: true)) { var csv = new CsvWriter(writeFile, true); csv.Configuration.RegisterClassMap&lt;GroupReportCSVMap&gt;(); csv.WriteRecords(reportCSVModels); } stream.Position = 0; //reset stream return File(stream, "application/octet-stream", "Reports.csv"); } </code></pre>
3,053,726
Why might a System.String object not cache its hash code?
<p>A glance at the source code for <a href="http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx" rel="noreferrer"><code>string.GetHashCode</code></a> using <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a> reveals the following (for mscorlib.dll version 4.0):</p> <pre><code>public override unsafe int GetHashCode() { fixed (char* str = ((char*) this)) { char* chPtr = str; int num = 0x15051505; int num2 = num; int* numPtr = (int*) chPtr; for (int i = this.Length; i &gt; 0; i -= 4) { num = (((num &lt;&lt; 5) + num) + (num &gt;&gt; 0x1b)) ^ numPtr[0]; if (i &lt;= 2) { break; } num2 = (((num2 &lt;&lt; 5) + num2) + (num2 &gt;&gt; 0x1b)) ^ numPtr[1]; numPtr += 2; } return (num + (num2 * 0x5d588b65)); } } </code></pre> <p>Now, I realize that <a href="http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx#remarksToggle" rel="noreferrer">the implementation of <code>GetHashCode</code> is not specified and is implementation-dependent</a>, so the question "is <code>GetHashCode</code> implemented in the form of X or Y?" is not really answerable. I'm just curious about a few things:</p> <ol> <li>If Reflector has disassembled the DLL correctly and this <em>is</em> the implementation of <code>GetHashCode</code> (in my environment), am I correct in interpreting this code to indicate that a <code>string</code> object, based on this particular implementation, would not cache its hash code?</li> <li>Assuming the answer is yes, why would this be? It seems to me that the memory cost would be minimal (one more 32-bit integer, a drop in the pond compared to the size of the string itself) whereas the savings would be significant, especially in cases where, e.g., strings are used as keys in a hashtable-based collection like a <code>Dictionary&lt;string, [...]&gt;</code>. And since the <code>string</code> class is immutable, it isn't like the value returned by <code>GetHashCode</code> will ever even change.</li> </ol> <p>What could I be missing?</p> <hr> <p><strong>UPDATE</strong>: In response to Andras Zoltan's closing remark:</p> <blockquote> <p>There's also the point made in Tim's answer(+1 there). If he's right, and I think he is, then there's no guarantee that a string is actually immutable after construction, therefore to cache the result would be wrong.</p> </blockquote> <p>Whoa, <em>whoa</em> there! This is an interesting point to make (and <a href="http://philosopherdeveloper.wordpress.com/2010/05/28/are-strings-really-immutable-in-net/" rel="noreferrer">yes it's very true</a>), but I <strong>really doubt</strong> that this was taken into consideration in the implementation of <code>GetHashCode</code>. The statement "therefore to cache the result would be wrong" implies to me that the framework's attitude regarding strings is "Well, they're <em>supposed to be</em> immutable, but really if developers want to get sneaky they're mutable so we'll treat them as such." <strong>This is definitely not how the framework views strings</strong>. It fully relies on their immutability in so many ways (interning of string literals, assignment of all zero-length strings to <code>string.Empty</code>, etc.) that, basically, if you mutate a string, you're writing code whose behavior is entirely undefined and unpredictable.</p> <p>I guess my point is that for the author(s) of this implementation to worry, "What if this string instance is modified between calls, even though the class as it is publicly exposed is immutable?" would be like for someone planning a casual outdoor BBQ to think to him-/herself, "What if someone brings an atomic bomb to the party?" Look, if someone brings an atom bomb, party's over.</p>
3,053,829
6
7
null
2010-06-16 13:37:37.62 UTC
7
2019-10-26 17:48:53.987 UTC
2010-06-16 14:51:53.357 UTC
null
105,570
null
105,570
null
1
43
.net|string|immutability|hashcode|gethashcode
3,660
<p>Obvious potential answer: because that will cost memory.</p> <p>There's a cost/benefit analysis here:</p> <p><strong>Cost</strong>: 4 bytes for every string (and a quick test on each call to GetHashCode). Also make the string object mutable, which would obviously mean you'd need to be careful about the implementation - unless you <em>always</em> compute the hash code up-front, which is a cost of computing it once for <em>every</em> string, regardless of whether you ever hash it at all.</p> <p><strong>Benefit</strong>: Avoid recomputing the hash <em>for string values hashed more than once</em></p> <p>I would suggest that in many cases, there are many, many string objects and very few of them are hashed more than once - leading to a net cost. For some cases, obviously that won't be the case.</p> <p>I don't think I'm in a good position to judge which comes up more often... I would hope that MS has instrumented various real apps. (I'd also hope that Sun did the same for Java, which <em>does</em> cache the hash...)</p> <p>EDIT: I've just spoken to Eric Lippert about this (NDC is awesome :) and basically it <em>is</em> about the extra memory hit vs the limited benefits.</p>
2,676,436
Define an <img>'s src attribute in CSS
<p>I need to define an &lt;img>'s src attribute in CSS. Is there a way to specify this attribute?</p>
2,676,445
7
2
null
2010-04-20 15:33:18.073 UTC
23
2019-04-01 17:30:06.417 UTC
2010-04-20 15:55:42.757 UTC
Roger Pate
null
null
38,058
null
1
143
css|attributes|image
472,437
<pre><code>#divID { background-image: url("http://imageurlhere.com"); background-repeat: no-repeat; width: auto; /*or your image's width*/ height: auto; /*or your image's height*/ margin: 0; padding: 0; } </code></pre>
2,687,730
How can I make PHP display the error instead of giving me 500 Internal Server Error
<p>This has never happened before. Usually it displays the error, but now it just gives me a 500 internal server error. Of course before, when it displayed the error, it was different servers. Now I'm on a new server (I have full root, so if I need to configure it somewhere in the php.ini, I can.) Or perhaps its something with Apache?</p> <p>I've been putting up with it by just transferring the file to my other server and running it there to find the error, but that's become too tedious. Is there a way to fix this?</p>
2,687,747
7
1
null
2010-04-22 01:45:58.823 UTC
40
2021-08-17 09:52:37.867 UTC
null
null
null
null
266,542
null
1
168
apache|php
244,269
<p>Check the <code>error_reporting</code>, <code>display_errors</code> and <code>display_startup_errors</code> settings in your <code>php.ini</code> file. They should be set to <code>E_ALL</code> and <code>"On"</code> respectively (though you should not use <code>display_errors</code> on a production server, so disable this and use <code>log_errors</code> instead if/when you deploy it). You can also change these settings (except <code>display_startup_errors</code>) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):</p> <pre><code>error_reporting(E_ALL); ini_set('display_errors', 'On'); </code></pre> <p>After that, restart server.</p>
2,997,578
How do I comment on the Windows command line?
<p>In Bash, # is used to comment the following. How do I make a comment on the Windows command line?</p>
2,997,627
8
3
null
2010-06-08 13:14:36.32 UTC
17
2022-08-31 22:56:10.037 UTC
2017-12-06 14:07:53 UTC
null
63,550
null
156,458
null
1
185
windows|command-line|comments
226,034
<p>The command you're looking for is <code>rem</code>, short for &quot;remark&quot;.</p> <p>There is also a shorthand version <code>::</code> that some people use, and this <em>sort of</em> looks like <code>#</code> if you squint a bit and look at it sideways. I originally preferred that variant since I'm a <code>bash</code>-aholic and I'm still trying to forget the painful days of BASIC :-)</p> <p>Unfortunately, there are situations where <code>::</code> stuffs up the command line processor (such as within complex <code>if</code> or <code>for</code> statements) so I generally use <code>rem</code> nowadays. In any case, it's a hack, suborning the label infrastructure to make it <em>look</em> like a comment when it really isn't. For example, try replacing <code>rem</code> with <code>::</code> in the following example and see how it works out:</p> <pre class="lang-none prettyprint-override"><code>if 1==1 ( rem comment line 1 echo 1 equals 1 rem comment line 2 ) </code></pre> <p>You should also keep in mind that <code>rem</code> is a <em>command,</em> so you can't just bang it at the end of a line like the <code>#</code> in <code>bash</code>. It has to go where a command would go. For example, the first line below outputs all <code>hello rem a comment</code> but the second outputs the single word <code>hello</code>:</p> <pre class="lang-none prettyprint-override"><code>echo hello rem a comment. echo hello&amp; rem a comment. </code></pre> <p>The second is two <em>separate</em> commands separated by <code>&amp;</code>, and with no spaces before the <code>&amp;</code> because echo will output those as well. That's not necessarily important for screen output but, if you're redirecting to a file, it may:</p> <pre class="lang-none prettyprint-override"><code>echo hello &gt;file - includes the space. echo hello&gt;file - no space. </code></pre>
23,605,099
Should I use Browserify or Webpack for lazy loading of dependencies in angular 1.x
<p>I would like to have async loading of angular dependencies in a large application and I'm trying to decide between <a href="http://browserify.org/" rel="noreferrer">Browserify</a> or <a href="http://webpack.github.io/" rel="noreferrer">Webpack</a> for this. I know angular 2.0 will support this natively but for now I'm looking for a well supported and popular solution.</p> <p>Can anyone give advice on which ones works best in an angular team and the most optimal way to structure the project.</p>
24,876,326
2
0
null
2014-05-12 09:11:38.907 UTC
22
2019-06-29 15:56:00.667 UTC
2019-06-29 15:56:00.667 UTC
null
1,033,581
null
1,339,087
null
1
30
angularjs|browserify|webpack
14,773
<p>At my company, we've switched over from browserify to webpack for a multitude of reasons, lazy loading being one of them.</p> <p>Putting things in multiple bundles in browserify took some configuration changes as well as special code. Here is a great guide for that <a href="http://esa-matti.suuronen.org/blog/2013/04/15/asynchronous-module-loading-with-browserify/">http://esa-matti.suuronen.org/blog/2013/04/15/asynchronous-module-loading-with-browserify/</a> </p> <p>With webpack, adding a new bundle just means an extra entry file line in the configuration's entry file line. Here is a quick guide to that: <a href="https://github.com/petehunt/webpack-howto#7-multiple-entrypoints">https://github.com/petehunt/webpack-howto#7-multiple-entrypoints</a>. In the case of lazy-loading, you don't even need to change anything in the configuration file, which is awesome - just use the asynchronous <code>require</code> syntax detailed here: <a href="https://github.com/petehunt/webpack-howto#9-async-loading">https://github.com/petehunt/webpack-howto#9-async-loading</a></p> <p>Here is a template for a setup very similar to what we use at <a href="https://bench.co">https://bench.co</a> in production. <a href="https://github.com/jeffling/angular-webpack-example/">https://github.com/jeffling/angular-webpack-example/</a></p>
33,722,508
How can I create effect hide numbers the credit card except the last 3 numbers
<p>I have a problem, I need a editText with validation and a effect hide numbers the credit card except the last 3 numbers..</p> <p>I have the mask and work fine, but I need show the last 3 numbers.</p> <p>How can I create this effect?</p> <p><a href="https://i.stack.imgur.com/3SFtZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3SFtZ.png" alt="enter image description here"></a></p> <pre><code> &lt;EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/creditCard" android:layout_below="@+id/CVV" android:inputType="number" android:digits=" 1234567890" android:maxLength="16" android:layout_alignParentStart="true" /&gt; </code></pre> <p>class TarjetasBancarias</p> <pre><code>public class TarjetasBancarias extends AppCompatActivity { String a; int keyDel; private EditText creditCard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tarjetas_bancarias); creditCard = (EditText)findViewById(R.id.creditCard); creditCard.addTextChangedListener(new CreditCardNumberFormattingTextWatcher()); } </code></pre> <p>class CreditCardNumberFormattingTextWatcher</p> <pre><code>public static class CreditCardNumberFormattingTextWatcher implements TextWatcher { private boolean lock; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (lock || s.length() &gt; 16) { return; } lock = true; for (int i = 4; i &lt; s.length(); i += 5) { s.insert(i, "*"); if (s.toString().charAt(i) != ' ') { s.insert(i, " "); } } lock = false; } } </code></pre>
33,723,126
1
2
null
2015-11-15 17:17:16.46 UTC
9
2018-03-07 02:50:04.553 UTC
2018-03-07 02:50:04.553 UTC
null
1,033,581
null
3,741,698
null
1
4
android
8,304
<p>I solved my problem using <code>PasswordCharSequence</code> and aplicate a Mask</p> <pre><code>public class TarjetasBancarias extends AppCompatActivity { private EditText creditCard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tarjetas_bancarias); creditCard = (EditText)findViewById(R.id.creditCard); creditCard.setTransformationMethod(new MyPasswordTransformationMethod()); creditCard.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { boolean flag = true; String eachBlock[] = creditCard.getText().toString().split("-"); for (int i = 0; i &lt; eachBlock.length; i++) { if (eachBlock[i].length() &gt; 4) { flag = false; } } if (flag) { creditCard.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) keyDel = 1; return false; } }); if (keyDel == 0) { if (((creditCard.getText().length() + 1) % 5) == 0) { if (creditCard.getText().toString().split("-").length &lt;= 3) { creditCard.setText(creditCard.getText() + "-"); creditCard.setSelection(creditCard.getText().length()); } } a = creditCard.getText().toString(); } else { a = creditCard.getText().toString(); keyDel = 0; } } else { creditCard.setText(a); } } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } }); } public static class MyPasswordTransformationMethod extends PasswordTransformationMethod { @Override public CharSequence getTransformation(CharSequence source, View view) { return new PasswordCharSequence(source); } private class PasswordCharSequence implements CharSequence { private CharSequence mSource; public PasswordCharSequence(CharSequence source) { mSource = source; } public char charAt(int index) { char caracter; switch (index) { case 4: caracter = ' '; break; case 9: caracter = ' '; break; case 14: caracter = ' '; break; default: if(index &lt; 15) return '*'; else caracter = mSource.charAt(index); break; } return caracter; } public int length() { return mSource.length(); } public CharSequence subSequence(int start, int end) { return mSource.subSequence(start, end); } } };} </code></pre> <p><a href="https://i.stack.imgur.com/e60KV.png"><img src="https://i.stack.imgur.com/e60KV.png" alt="enter image description here"></a></p>
33,833,881
Is it possible to type hint a lambda function?
<p>Currently, in Python, a function's parameters and return types can be type hinted as follows:</p> <pre><code>def func(var1: str, var2: str) -&gt; int: return var1.index(var2) </code></pre> <p>Which indicates that the function takes two strings, and returns an integer.</p> <p>However, this syntax is highly confusing with lambdas, which look like:</p> <pre><code>func = lambda var1, var2: var1.index(var2) </code></pre> <p>I've tried putting in type hints on both parameters and return types, and I can't figure out a way that doesn't cause a syntax error.</p> <p>Is it possible to type hint a lambda function? If not, are there plans for type hinting lambdas, or any reason (besides the obvious syntax conflict) why not?</p>
33,833,896
5
2
null
2015-11-20 18:45:14.773 UTC
15
2022-07-08 13:24:17.047 UTC
2015-11-20 18:47:39.467 UTC
null
100,297
null
1,769,273
null
1
180
python|lambda
84,166
<p>You can, sort of, in Python 3.6 and up using <a href="https://www.python.org/dev/peps/pep-0526/" rel="noreferrer">PEP 526 variable annotations</a>. You can annotate the variable you assign the <code>lambda</code> result to with the <a href="https://docs.python.org/3/library/typing.html#typing.Callable" rel="noreferrer"><code>typing.Callable</code> generic</a>:</p> <pre><code>from typing import Callable func: Callable[[str, str], int] = lambda var1, var2: var1.index(var2) </code></pre> <p>This doesn't attach the type hinting information to the function object itself, only to the namespace you stored the object in, but this is usually all you need for type hinting purposes.</p> <p>However, you may as well just use a function statement instead; the only advantage that a <code>lambda</code> offers is that you can put a function definition for a simple expression <em>inside</em> a larger expression. But the above lambda is not part of a larger expression, it is only ever part of an assignment statement, binding it to a name. That's exactly what a <code>def func(var1: str, var2: str): return var1.index(var2)</code> statement would achieve.</p> <p>Note that you can't annotate <code>*args</code> or <code>**kwargs</code> arguments separately either, as the documentation for <code>Callable</code> states:</p> <blockquote> <p>There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types.</p> </blockquote> <p>That limitation does not apply to a <a href="https://www.python.org/dev/peps/pep-0544/#callback-protocols" rel="noreferrer">PEP 544 <em>protocol</em> with a <code>__call__</code> method</a>; use this if you need a expressive definition of what arguments should be accepted. You need Python 3.8 <em>or</em> install the <a href="https://pypi.org/project/typing-extensions/" rel="noreferrer"><code>typing-extensions</code> project</a> for a backport:</p> <pre class="lang-py prettyprint-override"><code>from typing_extensions import Protocol class SomeCallableConvention(Protocol): def __call__(self, var1: str, var2: str, spam: str = &quot;ham&quot;) -&gt; int: ... func: SomeCallableConvention = lambda var1, var2, spam=&quot;ham&quot;: var1.index(var2) * spam </code></pre> <p>For the <code>lambda</code> expression <em>itself</em>, you can't use any annotations (the syntax on which Python's type hinting is built). The syntax is only available for <code>def</code> function statements.</p> <p>From <a href="https://www.python.org/dev/peps/pep-3107/#lambda" rel="noreferrer">PEP 3107 - <em>Function Annotations</em></a>:</p> <blockquote> <p>lambda 's syntax does not support annotations. The syntax of lambda could be changed to support annotations, by requiring parentheses around the parameter list. However it <a href="http://web.archive.org/web/20150922163722/https://mail.python.org/pipermail/python-3000/2006-May/001613.html" rel="noreferrer">was decided</a> not to make this change because:</p> <ul> <li>It would be an incompatible change.</li> <li>Lambda's are neutered anyway.</li> <li>The lambda can always be changed to a function.</li> </ul> </blockquote> <p>You can still attach the annotations directly to the object, the <code>function.__annotations__</code> attribute is a writable dictionary:</p> <pre><code>&gt;&gt;&gt; def func(var1: str, var2: str) -&gt; int: ... return var1.index(var2) ... &gt;&gt;&gt; func.__annotations__ {'var1': &lt;class 'str'&gt;, 'return': &lt;class 'int'&gt;, 'var2': &lt;class 'str'&gt;} &gt;&gt;&gt; lfunc = lambda var1, var2: var1.index(var2) &gt;&gt;&gt; lfunc.__annotations__ {} &gt;&gt;&gt; lfunc.__annotations__['var1'] = str &gt;&gt;&gt; lfunc.__annotations__['var2'] = str &gt;&gt;&gt; lfunc.__annotations__['return'] = int &gt;&gt;&gt; lfunc.__annotations__ {'var1': &lt;class 'str'&gt;, 'return': &lt;class 'int'&gt;, 'var2': &lt;class 'str'&gt;} </code></pre> <p>Not that dynamic annotations like these are going to help you when you wanted to run a static analyser over your type hints, of course.</p>
51,043,439
Using latest JavaScript features in TypeScript, such as ES2018
<p>I have tried searching through TypeScripts documentation on their configurtion and can't seem to find the answer to what should be a simple question.</p> <p>Simply, how does one configure the typescript compiler so that it knows what JavaScript feature sets we are using?</p> <p>So for example, ES2019 lands and i think 'Ohh want to get me some of that'. In that situation what do i need to upgrade, to allow the compiler to transpile and pollyfill what it needs to? </p> <p>The lib option in the tsconfig confuses me and the docs don't explain much about the available libraries. I can't find anything on them directly either.</p> <p>So lets say ES2019 comes out and i add the lib option for it (Assuming there will be one). Does that mean i can now use ES2019 features? If i wish to support everything from ES2019 down do i need to add the libs for every other version below it? Or does adding the ES2019 lib provide all i need? </p> <p>Where do those libraries come from? Are they part of the core TypeScript libarary and so to get more i have to upgrade, or can i simply upgrade a seperate package and it will all work?</p> <p>Finally do those lib provide every needed to fully support that version of the spec. Or is it a subset of features?</p> <p>In our project we currently use TypeScript Version 2.5.3</p> <p>I realize thats a whole lot of questions so any information on anything, or links to documentation, would be greatly appreciated.</p>
51,044,240
1
1
null
2018-06-26 12:52:55.343 UTC
10
2018-06-26 16:05:48.81 UTC
null
null
null
null
3,212,848
null
1
24
typescript|compilation|ecmascript-next
7,465
<p>The story is a bit more complex, and we should begin by separating it in two: language features and runtime features.</p> <h2>ES Language Features</h2> <p>When we say language features we mean changes to the core JavaScript language syntax. For example <code>ES 2015</code> adds support for classes, arrow functions (<code>=&gt;</code>), and <code>for-of</code> iteration </p> <p>Typescript tries to implement all stable language features proposals as soon as possible and will down-compile them to the ES version specified as the <code>target</code> option to the compiler. So this means if you have the latest Typescript compiler, which adds support for a fresh new <code>ES 2019</code> language feature, you will be able to down-compile it all the way down to <code>ES3</code>. Typescript will emit the code necessary to make such features work in whatever version of ES you are targeting. </p> <p>And you can see this in action now. If you target <code>ES5</code>, arrow functions are compiled into regular <code>function</code>s and use a <code>_this</code> local variable to captures <code>this</code>. Classes are compiled to a function and the apropriate fields on the <code>prototype</code> set. </p> <h2>ES Runtime Features</h2> <p>In addition to the language features, we have certain runtime features that describe what built-in object types are available, and what methods and fields those runtime objects have. Examples of new object types in recent versions of <code>ES</code> would be <code>Promise</code> or <code>Proxy</code>. </p> <p>Typescript does not provide poly-fills for such features, if the runtime does not offer support for these you will need to come with your own poly-fill implementation if you want to use them.</p> <p>Typescript does however need to know what built-in objects exist at runtime and what their methods/fields are, this is where the <code>lib</code> option comes in. It allows you to specify what the runtime environment will look like. </p> <p>So you could for example target <code>es5</code>, but specify that the runtime will have all the build-in objects in conformance with the <code>es2015</code> standard (some might be implemented by the runtime itself, others may be added by you through poly-fills)</p> <h2>The intersection of the two</h2> <p>The division above is a simplification, in that some language features rely on the existence of certain built-in objects and methods. </p> <p>For example, the <code>async/await</code> language feature relies on the existence of promises. So if you use <code>async/await</code> and target <code>es5</code> you will get an error that the <code>Promise</code> constructor does not exist. If you target <code>es5</code> but you specify <code>lib: [ 'es2015', 'dom' ]</code> you will no longer get an error as you have told the compiler that even though you wish to down compile to <code>es5</code>, at runtime the <code>Promise</code> constructor will exist as per the <code>es2015</code> runtime specification represented in that particular lib(not the compiler's problem how this will happen, poly-fills or built-in runtime behavior).</p> <p>Generally if such a reliance exists, the typescript compiler will issue an error that certain types are missing and you can upgrade your lib, or change your target (which will change the default libs used), but you will have to ensure that the runtime has the necessary support.</p> <h2>The exceptions</h2> <p>It might not always be possible to down-compile language features all the way down to <code>es3</code> (either because of missing runtime features, or just because of the high cost of implementing the feature does not make it a priority for the compiler team). An example would be property accessors (<code>get</code>/<code>set</code>) when targeting <code>es3</code>, which is unsupported. The compiler should warn you however if you are using an unsupported language feature/ target combination.</p>
10,726,653
By default, JSF generates unusable IDs, which are incompatible with the CSS part of web standards
<p>Can someone who is an active JSF (or Primefaces) user explain why by default this happens why nobody is doing anything about it:</p> <pre><code>&lt;p:commandLink id="baz" update=":foo:boop" value="Example" /&gt; </code></pre> <p>Which generates markup that cannot be used in JavaScript or CSS without hacks and should generally be considered invalid:</p> <pre><code>&lt;a href="javascript:void(0);" id=":foo:bar:baz"&gt;Example&lt;/a&gt; </code></pre> <p>The <code>id=":bar:baz:foo"</code> attribute here contains colons, which aren't a valid character for this attribute, at least from CSS perspective.</p> <p>While the attribute may be valid according to spec, it fails to work with real-world JavaScript and CSS implementations.</p> <p>In short, default <code>id</code> attribute generation in JSF is unusable for front-end development.</p>
10,726,774
1
0
null
2012-05-23 19:35:14.727 UTC
13
2019-01-17 11:20:36.173 UTC
2019-01-17 11:20:36.173 UTC
null
452,775
null
163,643
null
1
10
java|html|jsf|web-standards
5,653
<p>The <code>:</code> is been chosen because that's the only sensible separator character for which can be guaranteed that the enduser won't accidently use it in JSF component IDs (which is been <a href="http://docs.oracle.com/javaee/6/api/javax/faces/component/UIComponent.html#setId%28java.lang.String%29" rel="noreferrer">validated</a>) <strong>and</strong> that it's possible to use it in CSS selectors by escaping it with <code>\</code>.</p> <p>Note that the <a href="http://www.w3.org/TR/html4/types.html#h-6.2" rel="noreferrer">HTML4 spec</a> says that the colon is a <strong>valid</strong> value in <code>id</code> and <code>name</code> attribute. So your complaint that it isn't compatible with &quot;web standards&quot; goes nowhere.</p> <blockquote> <p><strong>ID</strong> and <strong>NAME</strong> tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (&quot;-&quot;), underscores (&quot;_&quot;), colons (&quot;:&quot;), and periods (&quot;.&quot;).</p> </blockquote> <p>The only problem is thus that the <code>:</code> is a special character in CSS selectors which needs to be escaped. JS has at its own no problems with colons. The <code>document.getElementById(&quot;foo:bar&quot;)</code> works perfectly fine. The only possible problem is in jQuery because it uses CSS selector syntax.</p> <p>If you really need to, then you can always change the default separator character <code>:</code> by setting the <code>javax.faces.SEPARATOR_CHAR</code> context param to e.g. <code>-</code> or <code>_</code> as below. You only need to guarantee that you don't use that character anywhere in JSF component IDs <em>yourself</em> (it's not been validated!).</p> <pre class="lang-xml prettyprint-override"><code>&lt;context-param&gt; &lt;param-name&gt;javax.faces.SEPARATOR_CHAR&lt;/param-name&gt; &lt;param-value&gt;-&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>The <code>_</code> has by the way the additional disadvantage that it occurs in JSF autogenerated IDs like <code>j_id1</code>, thus you should also ensure that <em>all</em> <a href="http://docs.oracle.com/javaee/6/api/javax/faces/component/NamingContainer.html" rel="noreferrer"><code>NamingContainer</code></a> components throughout your JSF pages have a fixed ID instead of an autogenerated one. Otherwise JSF will have problems finding naming container children.</p> <p>I would only not recommend it. It's in long term confusing and brittle. To think about it again, unique elements in the average JSF webapp are by itself usually already not inside forms or tables. They generally just represent the main layout aspects. I'd say, it's otherwise a bad design in general HTML/CSS perspective. Just select them by reusable CSS class names instead of IDs. If you really need to, you can always wrap it in a plain HTML <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code> whose ID won't be prepended by JSF.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html">What are valid values for the id attribute in HTML?</a></li> <li><a href="https://stackoverflow.com/questions/2142929/is-it-possible-to-change-the-element-id-separator-in-jsf">Is it possible to change the element id separator in JSF?</a></li> <li><a href="https://stackoverflow.com/questions/7927716/how-to-select-primefaces-ui-or-jsf-components-using-jquery">How to select JSF components using jQuery?</a></li> <li><a href="https://stackoverflow.com/questions/5878692/how-to-use-jsf-generated-html-element-id-in-css-selectors">How to use JSF generated HTML element ID with colon &quot;:&quot; in CSS selectors?</a></li> <li><a href="https://stackoverflow.com/questions/12615556/integrate-javascript-in-jsf-composite-component-the-clean-way">Integrate JavaScript in JSF composite component, the clean way</a></li> </ul>
10,442,670
Why are my CSS properties being overridden/ignored?
<p>I'm having some issues with the CSS "hierarchy" (not sure if it's proper to call it a hierarchy). I'm trying to style the below bit of HTML.</p> <pre><code>&lt;body&gt; &lt;section id="content"&gt; &lt;article&gt; &lt;ul class="posts-list"&gt; &lt;li class="post-item"&gt; &lt;h2&gt;[post title]&lt;/h2&gt; &lt;p class="item-description"&gt;...&lt;/p&gt; &lt;p class="item-meta"&gt;...&lt;/p&gt; &lt;/li&gt; ... &lt;/ul&gt; &lt;/article&gt; &lt;/section&gt; &lt;/body&gt; </code></pre> <p>Since section#content changes on every page I have, I wanted to maintain consistent styles across all of them, so I wrote some "global" CSS rules.</p> <pre><code>#content { color: #000; margin-left: 300px; max-width: 620px; padding: 0px 10px; position: relative; } #content p, #content li { color: #111; font: 16px / 24px serif; } </code></pre> <p>I wanted to style HTML within a <code>ul.posts-list</code> differently, so I wrote these rules.</p> <pre><code>li.post-item &gt; * { margin: 0px; } .item-description { color: #FFF; } .item-meta { color: #666; } </code></pre> <p>However, I ran into some issues. Here is how Chrome is rendering the CSS:</p> <p><img src="https://i.stack.imgur.com/NSQzG.png" alt="Screenshot of how Chrome is rendering my CSS"></p> <p>For some reason, the rules <code>#content p, #content li</code> are overriding my rules for <code>.item-description</code> and <code>.item-meta</code>. My impression was that class/id names are considered specific and thus higher priority. However, it seems that I have a misunderstanding of how CSS works. What am I doing wrong here?</p> <p>Edit: Also, where can I read up more about how this hierarchy works?</p>
10,442,697
5
0
null
2012-05-04 04:20:15.087 UTC
1
2016-09-29 14:17:20.313 UTC
null
null
null
null
778,418
null
1
18
css|css-selectors
39,674
<p>Elements id have the priority in CSS since they are the most specific. You just have to use the id:</p> <pre><code>#content li.post-item &gt; * { margin: 0px; } #content .item-description { color: #FFF; } #content .item-meta { color: #666; } </code></pre> <p>Basically id have the priority on class which the priority on tags(p,li,ul, h1...). To override the rule, just make sure you have the priority ;)</p>
10,342,057
c# Threadpool - limit number of threads
<p>I am developing a console app.</p> <p>I want to use a Threadpool to perform web downloads. Here is some fake code. </p> <pre><code> for (int loop=0; loop&lt; 100; loop++) { ThreadPool.QueueUserWorkItem(new WaitCallback(GetPage), pageList[loop]); } snip private static void GetPage(object o) { //get the page } </code></pre> <p>How do I prevent my code from starting more than two (or ten, or whatever) simultaneous threads?</p> <p>I have tried </p> <pre><code> ThreadPool.SetMaxThreads(1, 0); ThreadPool.SetMinThreads(1, 0); </code></pre> <p>But they seem to have no impact.</p>
10,343,983
6
0
null
2012-04-26 22:01:33.67 UTC
11
2015-11-10 11:33:06.143 UTC
2012-04-26 22:08:21.39 UTC
null
313,072
null
313,072
null
1
26
c#|multithreading|threadpool
61,022
<p>I would use <code>Parallel.For</code> and set <code>MaxDegreeOfParallelism</code> accordingly.</p> <pre><code>Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 10 }, i =&gt; { GetPage(pageList[i]); }); </code></pre>
6,313,858
Importing multiple projects into eclipse
<p>I am just curious to know, whether there are possibilities to import more than one project at the same time into Eclipse. Because whenever I create my new workspace I had to import the needed projects from my old workspace to my newly created workspace. </p> <p>So it would be nice to know, if there are options to import multiple projects at the same time?</p> <p>Thanks.</p>
6,313,909
2
1
null
2011-06-11 03:22:51.327 UTC
1
2015-06-09 08:02:30.153 UTC
2012-06-27 04:20:37.71 UTC
null
603,744
null
603,744
null
1
33
java|android|eclipse
29,204
<p>If all of your old projects exist in a single directory or in a single parent directory, you can do <strong>File -> Import... -> Existing Projects into workspace</strong>. Choose a root directory that is a parent all of the projects you want to import. You will then be able to import all of the projects at once.</p>
5,759,232
std::vector, default construction, C++11 and breaking changes
<p>I ran today against a quite subtle issue I'd like to have your opinion on.</p> <p>Consider the following garden-variety shared-body-idiom class:</p> <pre><code>struct S { S() : p_impl(new impl) {} private: struct impl; boost::shared_ptr&lt;impl&gt; p_impl; }; </code></pre> <p>The fun appears when you try to put those into vectors in the following way:</p> <pre><code>std::vector&lt;S&gt; v(42); </code></pre> <p>Now, with MSVC 8 at least, all the elements in <code>v</code> share the same <code>impl</code> member. Actually, what causes this is the <code>vector</code> constructor:</p> <pre><code>template &lt;typename T, typename A = ...&gt; class vector { vector(size_t n, const T&amp; x = T(), const A&amp; a = A()); ... }; </code></pre> <p>Under the scenes, only one <code>S</code> object gets default constructed, the <code>n</code> elements of the <code>vector</code> are copied from it.</p> <p>Now, with C++11, there are rvalue references. So it cannot work like this. If a <code>vector</code> is constructed as</p> <pre><code>std::vector&lt;S&gt; v(42); </code></pre> <p>then most likely, implementations will chose to default construct the <code>n</code> objects inside the vector, since copy construction may not be available. This would be a breaking change in this case.</p> <p>My question is:</p> <ol> <li>Does the C++03 standard mandates that <code>std::vector</code> must have a constructor defined as above, ie. with a default argument ? In particular is there a guarantee that the entries of the vector object get copied instead of default constructed ?</li> <li>What does the C++11 standard say about this same point ?</li> <li>I see this as a possibility for a breaking change between C++03 and C+11. Has this issue been investigated ? Solved ?</li> </ol> <p><em>PS: Please no comments about the default constructor of the class <code>S</code> above. It was this or implementing some form of lazy construction.</em></p>
5,759,296
2
3
null
2011-04-22 19:28:30.207 UTC
12
2012-03-09 02:59:45.9 UTC
2012-03-01 23:07:04.447 UTC
null
500,104
null
373,025
null
1
54
c++|stl|vector|c++11|backwards-compatibility
3,285
<blockquote> <p>Does the C++03 standard mandate that <code>std::vector</code> must have a constructor defined as above, i.e. with a default argument? In particular is there a guarantee that the entries of the vector object get copied instead of default constructed? </p> </blockquote> <p>Yes, the specified behavior is that <code>x</code> is copied <code>n</code> times so that the container is initialized to contain with <code>n</code> elements that are all copies of <code>x</code>.</p> <hr> <blockquote> <p>What does the C++11 Standard say about this same point? </p> </blockquote> <p>In C++11 this constructor has been turned into two constructors.</p> <pre><code>vector(size_type n, const T&amp; x, const Allocator&amp; = Allocator()); // (1) explicit vector(size_type n); // (2) </code></pre> <p>Except for the fact that it no longer has a default argument for the second parameter, <strong>(1)</strong> works the same way as it does in C++03: <code>x</code> is copied <code>n</code> times.</p> <p>In lieu of the default argument for <code>x</code>, <strong>(2)</strong> has been added. This constructor value-initializes <code>n</code> elements in the container. No copies are made.</p> <p>If you require the old behavior, you can ensure that <strong>(1)</strong> is called by providing a second argument to the constructor invocation:</p> <pre><code>std::vector&lt;S&gt; v(42, S()); </code></pre> <hr> <blockquote> <p>I see this as a possibility for a breaking change between C++03 and C++11. I see this as a possibility for a breaking change between C++03 and C++11. Has this issue been investigated? Solved? </p> </blockquote> <p>Yes, as your example demonstrates, this is indeed a breaking change. </p> <p>As I am not a member of the C++ standardization committee (and I haven't paid particularly close attention to library-related papers in the mailings), I don't know to what degree this breaking change was discussed.</p>
33,225,183
How do I use AWS sdk definitions for TypeScript?
<p>I am trying to write an SES TypeScript client, using AWS definitions file downloaded from <a href="https://github.com/borisyankov/DefinitelyTyped/blob/master/aws-sdk/aws-sdk.d.ts">https://github.com/borisyankov/DefinitelyTyped/blob/master/aws-sdk/aws-sdk.d.ts</a></p> <p>Here is what I've tried:</p> <pre><code>/// &lt;reference path="../typings/aws-sdk.d.ts" /&gt; var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); </code></pre> <p>Here is the error that I get:</p> <pre><code>/usr/local/bin/tsc --sourcemap SesTest.ts SesTest.ts(3,9): error TS2304: Cannot find name 'SES'. Process finished with exit code 2 </code></pre> <p>I cannot find any documentation on how to make this work. Please help!</p>
44,526,081
2
0
null
2015-10-19 22:43:33.393 UTC
4
2019-06-06 20:57:56.96 UTC
null
null
null
null
260,516
null
1
30
javascript|amazon-web-services|typescript
36,492
<p>I think a more appropriate way to do this is </p> <p><code>import { &lt;ServiceName&gt; } from 'aws-sdk';</code></p> <p>for instance</p> <p><code>import { DynamoDB } from 'aws-sdk';</code></p> <p>followed by</p> <p><code>this.client = new DynamoDB();</code> in the class.</p> <p>I say it is more appropriate because it uses TypeScript's import syntax.</p> <p>Also, there's a clear explanation - by AWS - on how to use <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/#Usage_with_TypeScript" rel="noreferrer">TS with AWS SDK here</a>.</p>
31,612,598
Call a React component method from outside
<p>I want to call a method exposed by a React component from the instance of a React Element.</p> <p>For example, in this <a href="https://jsfiddle.net/r6r8cp3z/" rel="noreferrer">jsfiddle</a>. I want to call the <code>alertMessage</code> method from the <code>HelloElement</code> reference.</p> <p>Is there a way to achieve this without having to write additional wrappers?</p> <p><strong><em>Edit</em></strong> (copied code from JSFiddle)</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="container"&gt;&lt;/div&gt; &lt;button onclick="onButtonClick()"&gt;Click me!&lt;/button&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>var onButtonClick = function () { //call alertMessage method from the reference of a React Element! Something like HelloElement.alertMessage() console.log("clicked!"); } var Hello = React.createClass({displayName: 'Hello', alertMessage: function() { alert(this.props.name); }, render: function() { return React.createElement("div", null, "Hello ", this.props.name); } }); var HelloElement = React.createElement(Hello, {name: "World"}); React.render( HelloElement, document.getElementById('container') ); </code></pre>
31,615,047
14
2
null
2015-07-24 14:04:20.553 UTC
30
2022-06-19 03:29:57.297 UTC
2019-08-20 10:43:33.723 UTC
null
12,216,735
user1341217
null
null
1
121
reactjs
159,858
<p>There are two ways to access an inner function. One, instance-level, like you want, another, static level.</p> <h2>Instance</h2> <p>You need to call the function on the return from <code>React.render</code>. See below.</p> <h2>Static</h2> <p>Take a look at <a href="https://facebook.github.io/react/docs/component-specs.html#statics" rel="noreferrer">ReactJS Statics</a>. Note, however, that a static function cannot access instance-level data, so <code>this</code> would be <code>undefined</code>.</p> <pre class="lang-js prettyprint-override"><code>var onButtonClick = function () { //call alertMessage method from the reference of a React Element! HelloRendered.alertMessage(); //call static alertMessage method from the reference of a React Class! Hello.alertMessage(); console.log("clicked!"); } var Hello = React.createClass({ displayName: 'Hello', statics: { alertMessage: function () { alert('static message'); } }, alertMessage: function () { alert(this.props.name); }, render: function () { return React.createElement("div", null, "Hello ", this.props.name); } }); var HelloElement = React.createElement(Hello, { name: "World" }); var HelloRendered = React.render(HelloElement, document.getElementById('container')); </code></pre> <p>Then do <code>HelloRendered.alertMessage()</code>.</p>
19,441,521
Bash regex =~ operator
<p>What is the operator <code>=~</code> called? Is it only used to compare the right side against the left side?</p> <p>Why are double square brackets required when running a test?</p> <p>ie. <code>[[ $phrase =~ $keyword ]]</code></p> <p>Thank you</p>
19,441,575
3
0
null
2013-10-18 04:19:15.623 UTC
26
2021-07-24 21:23:49.11 UTC
null
null
null
null
339,946
null
1
95
bash|shell|unix
99,997
<ol> <li> <blockquote> <p>What is the operator <code>=~</code> called?</p> </blockquote> <p>I'm not sure it has a name. The <a href="http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs" rel="noreferrer">bash documentation</a> just calls it the <code>=~</code> operator.</p> </li> <li> <blockquote> <p>Is it only used to compare the right side against the left side?</p> </blockquote> <p>The right side is considered an extended regular expression. If the left side matches, the operator returns <code>0</code>, and <code>1</code> otherwise.</p> </li> <li> <blockquote> <p>Why are double square brackets required when running a test?</p> </blockquote> <p>Because <code>=~</code> is an operator of the <code>[[ expression ]]</code> compound command.</p> </li> </ol>
19,355,537
Wix - Setting Install Folder correctly
<p>I'm creating a program which is being installed by Wix, using VS 2010 and I've already got the product.wxs ready.</p> <p>In my wxs file, I've got directory definitions which looks like this:</p> <pre><code>&lt;SetDirectory Id="INSTALLFOLDER" Value="[WindowsVolume]Myapp" /&gt; &lt;Directory Id="TARGETDIR" Name="SourceDir"&gt; &lt;Directory Id="INSTALLFOLDER" Name="Myapp"&gt; &lt;Directory Id="Myapp_Installer_Dir" Name="Myapp"&gt; &lt;Directory Id="BIN" Name="Bin" /&gt; &lt;Directory Id="ICONS" Name="Icons" /&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;/Directory&gt; </code></pre> <p>And then I got these file installation definitions:</p> <pre><code>&lt;DirectoryRef Id="Myapp_Installer_Dir"&gt; &lt;Component Id="INSTALLER_Myapp" Guid="{94F18477-8562-4004-BC6F-5629CC19E4CB}" &gt; &lt;File Source="$(var.Myapp.TargetPath)" KeyPath="yes"/&gt; &lt;/Component&gt; &lt;/DirectoryRef&gt; &lt;DirectoryRef Id="BIN"&gt; &lt;Component Id="INSTALLER_Data" Guid="{545FB5DD-8A52-44D7-898E-7316E70A93F5}" &gt; &lt;File Source="$(var.Data.TargetPath)" KeyPath="yes"/&gt; &lt;/Component&gt; ... </code></pre> <p>And it continues in that manner. The files for the "ICONS" directory are defined as well.</p> <p>I am also using the WixUI_InstallDir dialog set and I got these lines present as well:</p> <pre><code>&lt;Property Id="WIXUI_INSTALLDIR" Value="Myapp_Installer_Dir" /&gt; &lt;UIRef Id="WixUI_InstallDir" /&gt; </code></pre> <p>The problem is when the user installs the program and changes the value of the installation folder, the files of the "Bin" and "Icons" are installed to their correct path, but the Myapp target is installed to a fix location which was defined at the start as the default installation path.</p> <p>Why do only the bin and icon files installed to the correct folder the user wanted, but the myapp target does not?</p>
19,382,499
3
0
null
2013-10-14 07:43:32.65 UTC
4
2021-04-07 11:11:04.767 UTC
2019-01-15 08:31:50.683 UTC
null
1,164,004
null
1,164,004
null
1
25
wix|installation
77,999
<p>I have finally figured out the problem. After searching for a while, I came across this document:</p> <p><a href="http://wixtoolset.org/documentation/manual/v3/wixui/dialog_reference/wixui_installdir.html"> WixUI_InstallDir Dialog Set </a></p> <p>The relevant part: "The directory ID must be all uppercase characters because it must be passed from the UI to the execute sequence to take effect."</p> <p>And as you can see in my code: "Myapp_Installer_Dir" does not meet this criteria.</p> <p>After changing it to "MYAPPINSTALLERDIR", everything worked.</p>
41,026,895
Checking version of angular-cli that's installed?
<p>Is there a way to check the specific version of <code>angular-cli</code> that's installed globally on my machine? I'm in a Windows environment. <code>*npm -v* and *node -v*</code> only gives me the version of npm and node respectively, and I can't seem to find any commands with <em>ng</em>.</p> <p>I'm trying to run a project that I'm working on, and it ran on an older version of angular-cli using npm. However, after installing other demo projects, my main project doesn't work anymore without uninstalling and reinstalling <code>angular-cli</code> at the specific version.</p>
41,027,175
16
0
null
2016-12-07 20:36:00.457 UTC
36
2022-09-01 12:24:20.693 UTC
2020-11-20 07:50:25.85 UTC
null
3,383,693
null
1,013,029
null
1
225
node.js|angular|npm|angular-cli
537,318
<p>angular cli can report its version when you run it with the version flag</p> <pre><code>ng --version </code></pre>
47,516,342
How to move to the next line in binding.pry ?
<p>In byebug we can move to next line by typing 'n', similarly is there anyway to move to the next line in 'pry' ?</p> <p>I have gone through there documentation but nothing's works out. </p>
47,516,471
3
0
null
2017-11-27 17:10:30.313 UTC
1
2020-11-27 13:40:44.43 UTC
null
null
null
null
9,015,957
null
1
32
ruby-on-rails|ruby|rubygems|pry|binding.pry
35,234
<p>Check out <a href="https://github.com/nixme/pry-nav" rel="noreferrer">pry-nav</a>, it gives you methods like <code>next</code> and <code>step</code>, which should be what you're looking for.</p> <p>If you're in regular old Pry you can use <code>exit</code> to go to the next <code>binding.pry</code> or <code>disable-pry</code> to exit Pry entirely.</p>
17,950,742
How can I add a new line in a Bash string?
<p>The new line <code>\n</code> is not taken account in the shell strings:</p> <pre><code>str=&quot;aaa\nbbbb&quot; echo $str </code></pre> <p>Output:</p> <pre><code>aaa\nbbbb </code></pre> <p>Expected result:</p> <pre><code>aaa bbbb </code></pre> <p>How can I add a new line in the string?</p>
17,950,785
1
1
null
2013-07-30 15:08:25.157 UTC
9
2022-03-27 15:23:11.227 UTC
2022-03-27 15:23:11.227 UTC
null
63,550
null
781,252
null
1
35
linux|bash|shell|sh|ash
85,146
<pre><code>$ echo "a\nb" a\nb $ echo -e "a\nb" a b </code></pre>
21,643,363
Error 0x84b10001 when installing SQL Server 2012 on a machine with VS2013
<p>I'm trying to install <a href="http://msdn.microsoft.com/en-us/evalcenter/hh230763.aspx" rel="nofollow noreferrer">SQL Server Express with Service Pack 1</a> on my Win8 Pro (x64) development machine and I'm consistently getting an error 0x84b10001 when trying to install it:</p> <p><img src="https://i.stack.imgur.com/7ijSO.png" alt="error message"></p> <p>Antivirus is disabled during the installation (done as Administrator) and I tried 2 versions of the SQL Server Express package and I'm getting the same issue with both.<br> I'm getting the same issue whether I'm trying the x86 or x64 packages.</p> <p>I suspect that the issue comes from the fact that Visual Studio 2013 has already installed some SQL Server packages but I do not see any way to update and modify these to add the Management Studio for istance.</p>
21,643,578
6
0
null
2014-02-08 07:37:15.853 UTC
null
2018-02-14 17:17:49.88 UTC
2014-02-08 07:55:03.957 UTC
null
3,811
null
3,811
null
1
4
sql-server-2012
42,371
<p>Well, turns out that this cryptic error is due to an <a href="http://connect.microsoft.com/SQLServer/feedback/details/747196/setup-fails-with-hexadecimal-value-0x00-is-an-invalid-character-line-1-position-367455">older instance of <em>SQL Server Desktop Engine</em> (MSDE) being present</a>.</p> <p>After uninstalling MSDE, the SQL Server 2012 setup worked without errors.</p>
18,876,440
How do I find out Groovy runtime version from a running app?
<p>I need to be able to find out the version of Groovy runtime via a groovy script. How do I do it? The examples I found on the net show a way, but apparently it has been deprecated and removed in the latest version.</p>
18,876,543
2
0
null
2013-09-18 15:30:14.143 UTC
7
2019-08-06 22:01:57.457 UTC
null
null
null
null
314,545
null
1
60
groovy
21,894
<p>This should work:</p> <pre><code>println GroovySystem.version </code></pre> <p>So long as you are on Groovy 1.6.6+</p> <p>Before that, it was:</p> <pre><code>println org.codehaus.groovy.runtime.InvokerHelper.version </code></pre> <p>But that's been removed from later versions of Groovy</p>
8,750,518
Difference between global maxconn and server maxconn haproxy
<p>I have a question about my haproxy config:</p> <pre><code>#--------------------------------------------------------------------- # Global settings #--------------------------------------------------------------------- global log 127.0.0.1 syslog emerg maxconn 4000 quiet user haproxy group haproxy daemon #--------------------------------------------------------------------- # common defaults that all the 'listen' and 'backend' sections will # use if not designated in their block #--------------------------------------------------------------------- defaults mode http log global option abortonclose option dontlognull option httpclose option httplog option forwardfor option redispatch timeout connect 10000 # default 10 second time out if a backend is not found timeout client 300000 # 5 min timeout for client timeout server 300000 # 5 min timeout for server stats enable listen http_proxy localhost:81 balance roundrobin option httpchk GET /empty.html server server1 myip:80 maxconn 15 check inter 10000 server server2 myip:80 maxconn 15 check inter 10000 </code></pre> <p>As you can see it is straight forward, but I am a bit confused about how the maxconn properties work. </p> <p>There is the global one and the maxconn on the server, in the listen block. My thinking is this: the global one manages the total number of connections that haproxy, as a service, will queue or process at one time. If the number gets above that, it either kills the connection, or pools in some linux socket? I have no idea what happens if the number gets higher than 4000.</p> <p>Then you have the server maxconn property set at 15. First off, I set that at 15 because my php-fpm, this is forwarding to on a separate server, only has so many child processes it can use, so I make sure I am pooling the requests here, instead of in php-fpm. Which I think is faster. </p> <p>But back on the subject, my theory about this number is each server in this block will only be sent 15 connections at a time. And then the connections will wait for an open server. If I had cookies on, the connections would wait for the CORRECT open server. But I don't.</p> <p>So questions are:</p> <ol> <li>What happens if the global connections get above 4000? Do they die? Or pool in Linux somehow?</li> <li>Are the global connection related to the server connections, other than the fact you can't have a total number of server connections greater than global?</li> <li>When figuring out the global connections, shouldn't it be the amount of connections added up in the server section, plus a certain percentage for pooling? And obviously you have other restrains on the connections, but really it is how many you want to send to the proxies?</li> </ol> <p>Thank you in advance.</p>
8,771,616
1
0
null
2012-01-05 22:06:05.143 UTC
67
2019-08-13 17:03:54.3 UTC
2019-08-13 17:03:54.3 UTC
null
497,356
null
667,608
null
1
99
haproxy
75,098
<p>Willy got me an answer by email. I thought I would share it. His answers are in bold.</p> <p>I have a question about my haproxy config:</p> <pre><code> #--------------------------------------------------------------------- # Global settings #--------------------------------------------------------------------- global log 127.0.0.1 syslog emerg maxconn 4000 quiet user haproxy group haproxy daemon #--------------------------------------------------------------------- # common defaults that all the 'listen' and 'backend' sections will # use if not designated in their block #--------------------------------------------------------------------- defaults mode http log global option abortonclose option dontlognull option httpclose option httplog option forwardfor option redispatch timeout connect 10000 # default 10 second time out if a backend is not found timeout client 300000 # 5 min timeout for client timeout server 300000 # 5 min timeout for server stats enable listen http_proxy localhost:81 balance roundrobin option httpchk GET /empty.html server server1 myip:80 maxconn 15 check inter 10000 server server2 myip:80 maxconn 15 check inter 10000 </code></pre> <p>As you can see it is straight forward, but I am a bit confused about how the maxconn properties work. </p> <p>There is the global one and the maxconn on the server, in the listen block.</p> <p><strong>And there is also another one in the listen block which defaults to something like 2000.</strong></p> <p>My thinking is this: the global one manages the total number of connections that haproxy, as a service, will que or process at one time.</p> <p><strong>Correct. It's the per-process max number of concurrent connections.</strong></p> <p>If the number gets above that, it either kills the connection, or pools in some linux socket?</p> <p><strong>The later, it simply stops accepting new connections and they remain in the socket queue in the kernel. The number of queuable sockets is determined by the min of (net.core.somaxconn, net.ipv4.tcp_max_syn_backlog, and the listen block's maxconn).</strong></p> <p>I have no idea what happens if the number gets higher than 4000.</p> <p><strong>The excess connections wait for another one to complete before being accepted. However, as long as the kernel's queue is not saturated, the client does not even notice this, as the connection is accepted at the TCP level but is not processed. So the client only notices some delay to process the request. But in practice, the listen block's maxconn is much more important, since by default it's smaller than the global one. The listen's maxconn limits the number of connections per listener. In general it's wise to configure it for the number of connections you want for the service, and to configure the global maxconn to the max number of connections you let the haproxy process handle. When you have only one service, both can be set to the same value. But when you have many services, you can easily understand it makes a huge difference, as you don't want a single service to take all the connections and prevent the other ones from working.</strong></p> <p>Then you have the server maxconn property set at 15. First off, I set that at 15 because my php-fpm, this is forwarding to on a separate server, only has so many child processes it can use, so I make sure I am pooling the requests here, instead of in php-fpm. Which I think is faster. </p> <p><strong>Yes, not only it should be faster, but it allows haproxy to find another available server whenever possible, and also it allows it to kill the request in the queue if the client hits "stop" before the connection is forwarded to the server.</strong></p> <p>But back on the subject, my theory about this number is each server in this block will only be sent 15 connections at a time. And then the connections will wait for an open server. If I had cookies on, the connections would wait for the CORRECT open server. But I don't.</p> <p><strong>That's exactly the principle. There is a per-proxy queue and a per-server queue. Connections with a persistence cookie go to the server queue and other connections go to the proxy queue. However since in your case no cookie is configured, all connections go to the proxy queue. You can look at the diagram doc/queuing.fig in haproxy sources if you want, it explains how/where decisions are taken.</strong></p> <p>So questions are:</p> <ol> <li><p>What happens if the global connections get above 4000? Do they die? Or pool in Linux somehow?</p> <p><strong>They're queued in linux. Once you overwhelm the kernel's queue, then they're dropped in the kernel.</strong></p></li> <li><p>Are the global connection related to the server connections, other than the fact you can't have a total number of server connections greater than global?</p> <p><strong>No, global and server connection settings are independant.</strong></p></li> <li><p>When figuring out the global connections, shouldn't it be the amount of connections added up in the server section, plus a certain percentage for pooling? And obviously you have other restrains on the connections, but really it is how many you want to send to the proxies?</p> <p><strong>You got it right. If your server's response time is short, there is nothing wrong with queueing thousands of connections to serve only a few at a time, because it substantially reduces the request processing time. Practically, establishing a connection nowadays takes about 5 microseconds on a gigabit LAN. So it makes a lot of sense to let haproxy distribute the connections as fast as possible from its queue to a server with a very small maxconn. I remember one gaming site queuing more than 30000 concurrent connections and running with a queue of 30 per server ! It was an apache server, and apache is much faster with small numbers of connections than with large numbers. But for this you really need a fast server, because you don't want to have all your clients queued waiting for a connection slot because the server is waiting for a database for instance. Also something which works very well is to dedicate servers. If your site has many statics, you can direct the static requests to a pool of servers (or caches) so that you don't queue static requests on them and that the static requests don't eat expensive connection slots. Hoping this helps, Willy</strong></p></li> </ol>
48,065,535
Should I keep gitconfig's "signingKey" private?
<p>I have recently set up GPG to sign my Git commits so now I have a <strong>signingKey</strong> field in my gitconfig. I'm not very familiar with details of GPG – is this signingKey a sensitive piece of information that I should keep private or does it fall into the public part of gpg? I have my gitconfig in a public repo where I keep my dotfiles and I was wondering if it's ok to have that field visible. </p>
48,067,999
2
0
null
2018-01-02 17:48:54.773 UTC
2
2021-04-29 00:35:06.41 UTC
null
null
null
null
298,209
null
1
32
git|gnupg|gpg-signature
3,498
<p>No, it isn't necessary to keep it private.</p> <p>The secret key is not in git's configs but in the GnuPG's &quot;keyring&quot;, which is usually some file in your HOME. In theory it can also be in more secure locations, like hardware token, but I don't know much about it.</p> <p>The value in git config only instructs gpg which secret key to select.</p>
1,253,122
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows?
<p>When using <code>subprocess.Popen(args, shell=True)</code> to run "<code>gcc --version</code>" (just as an example), on Windows we get this:</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen &gt;&gt;&gt; Popen(['gcc', '--version'], shell=True) gcc (GCC) 3.4.5 (mingw-vista special r3) ... </code></pre> <p>So it's nicely printing out the version as I expect. But on Linux we get this:</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen &gt;&gt;&gt; Popen(['gcc', '--version'], shell=True) gcc: no input files </code></pre> <p>Because gcc hasn't received the <code>--version</code> option.</p> <p>The docs don't specify exactly what should happen to the args under Windows, but it does say, on Unix, <em>"If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments."</em> IMHO the Windows way is better, because it allows you to treat <code>Popen(arglist)</code> calls the same as <code>Popen(arglist, shell=True)</code> ones.</p> <p><strong>Why the difference between Windows and Linux here?</strong></p>
1,254,322
3
1
null
2009-08-10 04:39:58.34 UTC
12
2014-12-10 15:11:01.41 UTC
null
null
null
null
68,707
null
1
24
python|shell|subprocess|popen
22,220
<p>Actually on Windows, it does use <code>cmd.exe</code> when <code>shell=True</code> - it prepends <code>cmd.exe /c</code> (it actually looks up the <code>COMSPEC</code> environment variable but defaults to <code>cmd.exe</code> if not present) to the shell arguments. (On Windows 95/98 it uses the intermediate <code>w9xpopen</code> program to actually launch the command).</p> <p>So the strange implementation is actually the <code>UNIX</code> one, which does the following (where each space separates a different argument):</p> <pre><code>/bin/sh -c gcc --version </code></pre> <p>It looks like the correct implementation (at least on Linux) would be:</p> <pre><code>/bin/sh -c "gcc --version" gcc --version </code></pre> <p>Since this would set the command string from the quoted parameters, and pass the other parameters successfully.</p> <p>From the <code>sh</code> man page section for <code>-c</code>:</p> <blockquote> <p><code>Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands.</code></p> </blockquote> <p>This patch seems to fairly simply do the trick:</p> <pre><code>--- subprocess.py.orig 2009-04-19 04:43:42.000000000 +0200 +++ subprocess.py 2009-08-10 13:08:48.000000000 +0200 @@ -990,7 +990,7 @@ args = list(args) if shell: - args = ["/bin/sh", "-c"] + args + args = ["/bin/sh", "-c"] + [" ".join(args)] + args if executable is None: executable = args[0] </code></pre>
532,754
Inheritance of static members in PHP
<p>In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I'm wondering if there's any way around this. </p> <p>I'm trying to write a wrapper for someone else's (somewhat clunky) function. The function in question can be applied to lots of different data types but requires different flags and options for each. But 99% of the time, a default for each type would suffice.</p> <p>It would be nice if this could be done with inheritance, without having to write new functions each time. For example:</p> <pre><code>class Foo { public static $default = 'DEFAULT'; public static function doSomething ($param = FALSE ) { $param = ($param === FALSE) ? self::$default : $param; return $param; } } class Bar extends Foo { public static $default = 'NEW DEFAULT FOR CHILD CLASS'; } echo Foo::doSomething() . "\n"; // echoes 'DEFAULT' echo Bar::doSomething() . "\n"; // echoes 'DEFAULT' not 'NEW DEFAULT FOR CHILD CLASS' // because it references $default in the parent class :( </code></pre>
532,803
3
0
null
2009-02-10 15:19:51.69 UTC
11
2013-02-17 09:58:30.753 UTC
2012-07-01 15:55:32.763 UTC
null
367,456
Clayton
49,529
null
1
38
php|inheritance
20,551
<p>Classic example of why using statics as globals (functions in this case) is a bad idea no matter the language.</p> <p>The most robust method is to create multiple implementation sub classes of an abstract base "Action" class.</p> <p>Then to try and remove some of the annoyance of instantiating an instance of the class just to call it's methods, you can wrap it in a factory of some sort.</p> <p>For example:</p> <pre><code>abstract class AbstractAction { public abstract function do(); } class FooAction extends AbstractAction { public function do() { echo "Do Foo Action"; } } class BarAction extends AbstractAction { public function do() { echo "Do Bar Action"; } } </code></pre> <p>Then create a factory to "aid" in instantiation of the function</p> <pre><code>class ActionFactory { public static function get($action_name) { //... return AbstractAction instance here } } </code></pre> <p>Then use it as:</p> <pre><code>ActionFactory::get('foo')-&gt;do(); </code></pre>
22,346,526
How to count the number of relationships in Neo4j
<p>I am using Neo4j 2.0 and using the following query to find out the count of number of a particular relationship from a particular node.</p> <p>I have to check the number of relationships named "LIVES" from a particular node PERSON.</p> <p>My query is:</p> <pre><code>match (p:PERSON)-[r:LIVES]-&gt;(u:CITY) where count(r)&gt;1 return count(p); </code></pre> <p>The error shown is:</p> <pre><code>SyntaxException: Invalid use of aggregating function count(...) </code></pre> <p>How should I correct it?</p>
22,347,608
1
0
null
2014-03-12 09:02:37.293 UTC
11
2016-04-21 03:52:06.517 UTC
2016-04-21 03:52:06.517 UTC
null
5,225,453
null
1,703,886
null
1
24
neo4j|cypher
32,975
<p>What you want is a version of having? People living in more than one city?</p> <pre><code>MATCH (p:PERSON)-[:LIVES]-&gt;(c:CITY) WITH p,count(c) as rels, collect(c) as cities WHERE rels &gt; 1 RETURN p,cities, rels </code></pre>
56,411,599
(Flutter) TextFormField Change labelColor on Focus
<p>I am trying to change my <code>labelText</code> color when focused. I can change the text color but not when focused.</p> <p>I have tried all the hint text colors and label text colors, but nothing helps.</p> <pre class="lang-dart prettyprint-override"><code>Container( padding: EdgeInsets.fromLTRB(15, 10, 15, 0), child: TextFormField( cursorColor: Colors.lightGreen, keyboardType: TextInputType.phone, decoration: InputDecoration( labelText: 'Phone Number', hintText: 'Enter a Phone Number', focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.lightGreen ) ), border: OutlineInputBorder( borderSide: BorderSide() ), ) ), ), </code></pre> <p>Here are images of what is happening:</p> <p><a href="https://i.stack.imgur.com/y2MRw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y2MRw.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/v4FtK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v4FtK.png" alt="enter image description here"></a></p>
56,411,859
16
2
null
2019-06-02 01:25:28.293 UTC
5
2022-07-12 07:37:01.207 UTC
2020-03-09 13:31:11.49 UTC
null
4,756,173
null
8,569,903
null
1
46
flutter|dart|form-fields
59,544
<p>You'd need to have a way determine its focus state and then create a conditional for its color based off of that. This is where a <code>focusNode</code> would be helpful. Construct a new <code>FocusNode</code> off the widget creation, use that as the <code>focusNode</code> property in the <code>TextFormField</code>. Then in color property of the <code>TextStyle</code> property of the <code>TextFormField</code> you could add something like:</p> <pre class="lang-dart prettyprint-override"><code>FocusNode myFocusNode = new FocusNode(); ... return TextFormField( focusNode: myFocusNode, decoration: InputDecoration( labelText: 'test', labelStyle: TextStyle( color: myFocusNode.hasFocus ? Colors.blue : Colors.black ) ), ); </code></pre> <p>EDIT : Just a quick note, you'll probably need to make sure this is in a <code>StatefulWidget</code> and then add a listener to the <code>focusNode</code> you created and call <code>setState</code> on any events on that <code>focusNode</code>. Otherwise you wont see any changes. </p>
24,244,519
Cannot define multiple 'included' blocks for a Concern (ActiveSupport::Concern::MultipleIncludedBlocks) with cache_classes = true
<p>I have a certain module which is used in a Rails 4.1.1 application </p> <pre><code>module A extend ActiveSupport::Concern included do #Some code end end </code></pre> <p>which is included in a class</p> <pre><code>class Some include A end </code></pre> <p>This works great with <code>cache_classes=true</code> in <code>application.rb</code>. Now, if I turn off the caching of classes, I get <code>Cannot define multiple 'included' blocks for a Concern (ActiveSupport::Concern::MultipleIncludedBlocks)</code> exception upson starting the server.</p> <p>How should one deal with such an issue since reloading the classes is done by Rails?</p>
24,486,561
3
0
null
2014-06-16 13:08:49.737 UTC
3
2021-11-04 22:16:51.753 UTC
null
null
null
null
1,563,325
null
1
34
ruby-on-rails|activesupport
14,800
<p>For anyone hitting the same wall to read, the solution to this is to strictly respect Rails autoloading rules. That is</p> <ol> <li>Removing all the require / require_relative</li> <li>Add needed paths to Rails autoload paths</li> <li>Put files at the right places with the right names so Rails can infer where to look for code to load.</li> </ol> <p>More info here: <a href="https://github.com/rails/rails/issues/15767">https://github.com/rails/rails/issues/15767</a></p>
5,702,028
Is it possible to run R from a tablet using Honeycomb (Android 3.0)?
<p>I have a Xoom tablet and it would be great if I could run statistical analysis using R on it. <a href="http://www.r-statistics.com/2010/06/could-we-run-a-statistical-analysis-on-iphoneipad-using-r/">As far as I know</a> it is not possible to use R on iPad due to license problems (GPl x iTunes etc.) and a lack of compiler for Fortran in the Apple tablet.</p> <p>But what about tablets using android? Arguably, the GPL issue is not a problem, so any help here on how to use R on my tablet?</p>
5,704,538
3
2
null
2011-04-18 11:15:46.137 UTC
11
2019-08-24 17:05:08.757 UTC
2011-05-29 07:22:15.817 UTC
null
750,987
null
242,673
null
1
17
android|r|android-3.0-honeycomb|tablet
19,085
<p>At some point, smartphones and tablets will have browsers capable enough to run <a href="http://rstudio.org" rel="noreferrer">RStudio</a> in its server mode via the browser. Currently, the latter demands too much in terms of newer GWT, Javascricpt, ... magic that it remains limited to (recent enough) desktop browsers; see <a href="http://www.rstudio.org/docs/advanced/optimizing_browser" rel="noreferrer">here</a> for a bit more on this.</p> <p>You can always ssh out though. <a href="http://code.google.com/p/connectbot/" rel="noreferrer">Connectbot</a> is a capable ssh client for Android, and of course free. No graphs though.</p>
6,051,237
How can I improve the performance of my custom OpenGL ES 2.0 depth texture generation?
<p>I have an open source iOS application that uses custom OpenGL ES 2.0 shaders to display 3-D representations of molecular structures. It does this by using procedurally generated sphere and cylinder impostors drawn over rectangles, instead of these same shapes built using lots of vertices. The downside to this approach is that the depth values for each fragment of these impostor objects needs to be calculated in a fragment shader, to be used when objects overlap.</p> <p>Unfortunately, OpenGL ES 2.0 <a href="https://stackoverflow.com/questions/4534467/writing-texture-data-onto-depth-buffer/4596314#4596314">does not let you write to gl_FragDepth</a>, so I've needed to output these values to a custom depth texture. I do a pass over my scene using a framebuffer object (FBO), only rendering out a color that corresponds to a depth value, with the results being stored into a texture. This texture is then loaded into the second half of my rendering process, where the actual screen image is generated. If a fragment at that stage is at the depth level stored in the depth texture for that point on the screen, it is displayed. If not, it is tossed. More about the process, including diagrams, can be found in my post <a href="http://www.sunsetlakesoftware.com/2011/05/08/enhancing-molecules-using-opengl-es-20" rel="nofollow noreferrer">here</a>.</p> <p>The generation of this depth texture is a bottleneck in my rendering process and I'm looking for a way to make it faster. It seems slower than it should be, but I can't figure out why. In order to achieve the proper generation of this depth texture, <code>GL_DEPTH_TEST</code> is disabled, <code>GL_BLEND</code> is enabled with <code>glBlendFunc(GL_ONE, GL_ONE)</code>, and <code>glBlendEquation()</code> is set to <code>GL_MIN_EXT</code>. I know that a scene output in this manner isn't the fastest on a tile-based deferred renderer like the PowerVR series in iOS devices, but I can't think of a better way to do this.</p> <p>My depth fragment shader for spheres (the most common display element) looks to be at the heart of this bottleneck (Renderer Utilization in Instruments is pegged at 99%, indicating that I'm limited by fragment processing). It currently looks like the following:</p> <pre><code>precision mediump float; varying mediump vec2 impostorSpaceCoordinate; varying mediump float normalizedDepth; varying mediump float adjustedSphereRadius; const vec3 stepValues = vec3(2.0, 1.0, 0.0); const float scaleDownFactor = 1.0 / 255.0; void main() { float distanceFromCenter = length(impostorSpaceCoordinate); if (distanceFromCenter &gt; 1.0) { gl_FragColor = vec4(1.0); } else { float calculatedDepth = sqrt(1.0 - distanceFromCenter * distanceFromCenter); mediump float currentDepthValue = normalizedDepth - adjustedSphereRadius * calculatedDepth; // Inlined color encoding for the depth values float ceiledValue = ceil(currentDepthValue * 765.0); vec3 intDepthValue = (vec3(ceiledValue) * scaleDownFactor) - stepValues; gl_FragColor = vec4(intDepthValue, 1.0); } } </code></pre> <p>On an iPad 1, this takes 35 - 68 ms to render a frame of a DNA spacefilling model using a passthrough shader for display (18 to 35 ms on iPhone 4). According to the PowerVR PVRUniSCo compiler (part of <a href="http://www.imgtec.com/powervr/insider/sdkdownloads/index.asp#GLES2" rel="nofollow noreferrer">their SDK</a>), this shader uses 11 GPU cycles at best, 16 cycles at worst. I'm aware that you're advised not to use branching in a shader, but in this case that led to better performance than otherwise.</p> <p>When I simplify it to </p> <pre><code>precision mediump float; varying mediump vec2 impostorSpaceCoordinate; varying mediump float normalizedDepth; varying mediump float adjustedSphereRadius; void main() { gl_FragColor = vec4(adjustedSphereRadius * normalizedDepth * (impostorSpaceCoordinate + 1.0) / 2.0, normalizedDepth, 1.0); } </code></pre> <p>it takes 18 - 35 ms on iPad 1, but only 1.7 - 2.4 ms on iPhone 4. The estimated GPU cycle count for this shader is 8 cycles. The change in render time based on cycle count doesn't seem linear.</p> <p>Finally, if I just output a constant color:</p> <pre><code>precision mediump float; void main() { gl_FragColor = vec4(0.5, 0.5, 0.5, 1.0); } </code></pre> <p>the rendering time drops to 1.1 - 2.3 ms on iPad 1 (1.3 ms on iPhone 4).</p> <p>The nonlinear scaling in rendering time and sudden change between iPad and iPhone 4 for the second shader makes me think that there's something I'm missing here. A full source project containing these three shader variants (look in the SphereDepth.fsh file and comment out the appropriate sections) and a test model can be downloaded from <a href="http://www.sunsetlakesoftware.com/sites/default/files/Molecules-DepthShaderProfiling.zip" rel="nofollow noreferrer">here</a>, if you wish to try this out yourself.</p> <p>If you've read this far, my question is: based on this profiling information, how can I improve the rendering performance of my custom depth shader on iOS devices?</p>
6,170,939
4
3
null
2011-05-18 21:29:04.02 UTC
30
2011-05-31 20:33:26.297 UTC
2017-05-23 12:01:28.62 UTC
null
-1
null
19,679
null
1
41
iphone|ios|ipad|opengl-es|glsl
11,137
<p>Based on the recommendations by Tommy, Pivot, and rotoglup, I've implemented some optimizations which have led to a doubling of the rendering speed for the both the depth texture generation and the overall rendering pipeline in the application.</p> <p>First, I re-enabled the precalculated sphere depth and lighting texture that I'd used before with little effect, only now I use proper <code>lowp</code> precision values when handling the colors and other values from that texture. This combination, along with proper mipmapping for the texture, seems to yield a ~10% performance boost.</p> <p>More importantly, I now do a pass before rendering both my depth texture and the final raytraced impostors where I lay down some opaque geometry to block pixels that would never be rendered. To do this, I enable depth testing and then draw out the squares that make up the objects in my scene, shrunken by sqrt(2) / 2, with a simple opaque shader. This will create inset squares covering area known to be opaque in a represented sphere.</p> <p>I then disable depth writes using <code>glDepthMask(GL_FALSE)</code> and render the square sphere impostor at a location closer to the user by one radius. This allows the tile-based deferred rendering hardware in the iOS devices to efficiently strip out fragments that would never appear onscreen under any conditions, yet still give smooth intersections between the visible sphere impostors based on per-pixel depth values. This is depicted in my crude illustration below:</p> <p><img src="https://i.stack.imgur.com/kd8NQ.jpg" alt="Layered spheres and opacity testing"></p> <p>In this example, the opaque blocking squares for the top two impostors do not prevent any of the fragments from those visible objects from being rendered, yet they block a chunk of the fragments from the lowest impostor. The frontmost impostors can then use per-pixel tests to generate a smooth intersection, while many of the pixels from the rear impostor don't waste GPU cycles by being rendered.</p> <p>I hadn't thought to disable depth writes, yet leave on depth testing when doing the last rendering stage. This is the key to preventing the impostors from simply stacking on one another, yet still using some of the hardware optimizations within the PowerVR GPUs.</p> <p>In my benchmarks, rendering the test model I used above yields times of 18 - 35 ms per frame, as compared to the 35 - 68 ms I was getting previously, a near doubling in rendering speed. Applying this same opaque geometry pre-rendering to the raytracing pass yields a doubling in overall rendering performance.</p> <p><strike> Oddly, when I tried to refine this further by using inset and circumscribed octagons, which should cover ~17% fewer pixels when drawn, and be more efficient with blocking fragments, performance was actually worse than when using simple squares for this. Tiler utilization was still less than 60% in the worst case, so maybe the larger geometry was resulting in more cache misses. </strike></p> <p>EDIT (5/31/2011):</p> <p>Based on Pivot's suggestion, I created inscribed and circumscribed octagons to use instead of my rectangles, only I followed the recommendations <a href="http://www.humus.name/index.php?page=News&amp;ID=228" rel="noreferrer">here</a> for optimizing triangles for rasterization. In previous testing, octagons yielded worse performance than squares, despite removing many unnecessary fragments and letting you block covered fragments more efficiently. By adjusting the triangle drawing as follows:</p> <p><img src="https://i.stack.imgur.com/LdeKx.jpg" alt="Rasterization optimizing octagons"></p> <p>I was able to reduce overall rendering time by an average of 14% on top of the above-described optimizations by switching to octagons from squares. The depth texture is now generated in 19 ms, with occasional dips to 2 ms and spikes to 35 ms.</p> <p>EDIT 2 (5/31/2011):</p> <p>I've revisited Tommy's idea of using the step function, now that I have fewer fragments to discard due to the octagons. This, combined with a depth lookup texture for the sphere, now leads to a 2 ms average rendering time on the iPad 1 for the depth texture generation for my test model. I consider that to be about as good as I could hope for in this rendering case, and a giant improvement from where I started. For posterity, here is the depth shader I'm now using:</p> <pre><code>precision mediump float; varying mediump vec2 impostorSpaceCoordinate; varying mediump float normalizedDepth; varying mediump float adjustedSphereRadius; varying mediump vec2 depthLookupCoordinate; uniform lowp sampler2D sphereDepthMap; const lowp vec3 stepValues = vec3(2.0, 1.0, 0.0); void main() { lowp vec2 precalculatedDepthAndAlpha = texture2D(sphereDepthMap, depthLookupCoordinate).ra; float inCircleMultiplier = step(0.5, precalculatedDepthAndAlpha.g); float currentDepthValue = normalizedDepth + adjustedSphereRadius - adjustedSphereRadius * precalculatedDepthAndAlpha.r; // Inlined color encoding for the depth values currentDepthValue = currentDepthValue * 3.0; lowp vec3 intDepthValue = vec3(currentDepthValue) - stepValues; gl_FragColor = vec4(1.0 - inCircleMultiplier) + vec4(intDepthValue, inCircleMultiplier); } </code></pre> <p>I've updated the testing sample <a href="http://www.sunsetlakesoftware.com/sites/default/files/Molecules-DepthShaderProfiling4.zip" rel="noreferrer">here</a>, if you wish to see this new approach in action as compared to what I was doing initially.</p> <p>I'm still open to other suggestions, but this is a huge step forward for this application.</p>
5,644,947
Simple PHP string replace?
<p>I have this code:</p> <pre><code>$abc = ' Hello "Guys" , Goodmorning'; </code></pre> <p>I want to replace every occurrence of <code>"</code> (double quotes) by <code>$^</code> so that string becomes</p> <pre><code>'Hello $^Guys$^ , Goodmorning' </code></pre> <p>I am new to PHP; in Java we can do this very easily by calling the string class <code>replaceAll</code> function, but how do I do it in PHP? I can't find the easy way on Google without using regular expressions.</p> <p>What is some syntax with or without the use of regular expressions?</p>
5,644,967
7
0
null
2011-04-13 05:50:08.467 UTC
null
2019-06-06 16:09:22.787 UTC
2016-02-09 15:12:31.103 UTC
null
63,550
null
395,661
null
1
16
php
61,211
<p>Have a look at <a href="http://au2.php.net/manual/en/function.str-replace.php" rel="nofollow noreferrer"><code>str_replace</code></a></p> <pre><code>$abc = ' Hello "Guys" , Goodmorning'; $abc = str_replace('"', '$^', $abc); </code></pre>
6,111,298
Best way to specify whitespace in a String.Split operation
<p>I am splitting a string based on whitespace as follows:</p> <pre><code>string myStr = "The quick brown fox jumps over the lazy dog"; char[] whitespace = new char[] { ' ', '\t' }; string[] ssizes = myStr.Split(whitespace); </code></pre> <p>It's irksome to define the char[] array everywhere in my code I want to do this. Is there more efficent way that doesn't require the creation of the character array (which is prone to error if copied in different places)?</p>
6,111,355
11
3
null
2011-05-24 13:39:04.323 UTC
41
2021-12-27 10:38:35.37 UTC
2011-05-24 13:40:30.893 UTC
null
76,337
user236520
null
null
1
279
c#|string
341,358
<p>If you just call:</p> <pre><code>string[] ssize = myStr.Split(null); //Or myStr.Split() </code></pre> <p>or:</p> <pre><code>string[] ssize = myStr.Split(new char[0]); </code></pre> <p>then white-space is assumed to be the splitting character. From the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.split" rel="noreferrer"><code>string.Split(char[])</code> method's documentation page</a>.</p> <blockquote> <p><em>If the separator parameter is <code>null</code> or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return <code>true</code> if they are passed to the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace" rel="noreferrer"><code>Char.IsWhiteSpace</code></a> method.</em></p> </blockquote> <p>Always, always, <strong>always</strong> read the documentation!</p>
6,077,899
Visual Studio. Code changes don't do anything
<p>Any changes I make to my code aren't doing anything. I've even tried putting lines in that I know will crash my program, and nothing. It just keep running the old version. It's even loading old versions of files I've edited and saved.</p> <p>There a 3 projects in my solution. 2 are pure C#. 1 is a WinForms application.</p>
6,078,114
14
5
null
2011-05-20 21:49:10.817 UTC
2
2021-07-16 11:33:06.487 UTC
2011-05-20 22:20:15.693 UTC
null
49,619
null
754,193
null
1
16
c#|visual-studio-2010|compilation
46,630
<p>It sometimes happens that some files "are being used by another process".</p> <p>Close your solution and delete all "bin" and "obj" subfolders of all your projects that are included in the solution.</p> <p>Then open your solution again, execute "Clean solution" and build it again.</p>
17,727,734
How to use chrome.alarms for Google Chrome extension
<p><strong>manifest.json</strong></p> <pre><code>{ &quot;manifest_version&quot;: 2, &quot;name&quot;: &quot;App name&quot;, &quot;description&quot;: &quot;Description goes here&quot;, &quot;version&quot;: &quot;1.0&quot;, &quot;background&quot;: { &quot;scripts&quot;: [&quot;background.js&quot;] }, &quot;permissions&quot;: [ &quot;tabs&quot;, &quot;alarms&quot; ], &quot;browser_action&quot;: { &quot;default_icon&quot;: &quot;icon.png&quot;, &quot;default_popup&quot;: &quot;popup.html&quot; } } </code></pre> <p>I trying to create a function to make a popup &quot;great&quot; every minute like this:</p> <pre><code>chrome.alarms.onAlarm.addListener(function(){ alert('great'); }); </code></pre> <p>Could someone please tell why is it not triggering that alert. I check the console, no error was displayed.</p>
21,644,841
2
0
null
2013-07-18 15:28:32.477 UTC
12
2022-02-26 22:40:55.49 UTC
2022-02-26 22:40:55.49 UTC
null
4,370,109
null
680,900
null
1
15
javascript|google-chrome-extension|dom-events
23,829
<p>Here is the simplest working example I can think of, warning it is very annoying as when the alarm is on it alerts "Beep" every 12 seconds. It uses a popup browser action to switch the alarm on and off.</p> <p>manifest.json</p> <pre><code>{ "manifest_version": 2, "name": "Alarm test", "description": "This extension alarms.", "version": "1.0", "permissions": [ "alarms" ], "background": { "scripts": ["eventPage.js"], "persistent": false }, "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" } } </code></pre> <p>popup.html</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Alarms Popup&lt;/title&gt; &lt;script src="popup.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="" id="alarmOn"&gt;ON&lt;/a&gt; &lt;a href="" id="alarmOff"&gt;OFF&lt;/a&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>popup.js</p> <pre><code>var alarmClock = { onHandler : function(e) { chrome.alarms.create("myAlarm", {delayInMinutes: 0.1, periodInMinutes: 0.2} ); window.close(); }, offHandler : function(e) { chrome.alarms.clear("myAlarm"); window.close(); }, setup: function() { var a = document.getElementById('alarmOn'); a.addEventListener('click', alarmClock.onHandler ); var a = document.getElementById('alarmOff'); a.addEventListener('click', alarmClock.offHandler ); } }; document.addEventListener('DOMContentLoaded', function () { alarmClock.setup(); }); </code></pre> <p>And the important bit in eventPage.js</p> <pre><code>chrome.alarms.onAlarm.addListener(function(alarm) { alert("Beep"); }); </code></pre>
44,043,906
"The headers or library files could not be found for jpeg" installing Pillow on Alpine Linux
<p>I'm trying to run Python's Scrapy in a Docker container based on <a href="https://hub.docker.com/_/python/" rel="noreferrer">python:alpine</a>. It was working before, but now I'd like to use Scrapy's <a href="https://doc.scrapy.org/en/latest/topics/media-pipeline.html#using-the-images-pipeline" rel="noreferrer">Image Pipeline</a> which requires me to install Pillow.</p> <p>As a simplified example, I tried the following <code>Dockerfile</code>:</p> <pre><code>FROM python:alpine RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add libjpeg zlib tiff freetype lcms libwebp tcl openjpeg RUN pip install Pillow </code></pre> <p>However, when I try to build this I get an error which contains the following:</p> <pre><code>Traceback (most recent call last): File "/tmp/pip-build-ft5yzzuv/Pillow/setup.py", line 744, in &lt;module&gt; zip_safe=not debug_build(), ) File "/usr/local/lib/python3.6/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/local/lib/python3.6/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/local/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run return orig.install.run(self) File "/usr/local/lib/python3.6/distutils/command/install.py", line 545, in run self.run_command('build') File "/usr/local/lib/python3.6/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/local/lib/python3.6/distutils/command/build.py", line 135, in run self.run_command(cmd_name) File "/usr/local/lib/python3.6/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/local/lib/python3.6/distutils/command/build_ext.py", line 339, in run self.build_extensions() File "/tmp/pip-build-ft5yzzuv/Pillow/setup.py", line 545, in build_extensions raise RequiredDependencyException(f) __main__.RequiredDependencyException: jpeg During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-ft5yzzuv/Pillow/setup.py", line 756, in &lt;module&gt; raise RequiredDependencyException(msg) __main__.RequiredDependencyException: The headers or library files could not be found for jpeg, a required dependency when compiling Pillow from source. Please see the install instructions at: https://pillow.readthedocs.io/en/latest/installation.html </code></pre> <p>I went through the requirements on <a href="https://pillow.readthedocs.io/en/latest/installation.html" rel="noreferrer">https://pillow.readthedocs.io/en/latest/installation.html</a> and tried to find the corresponding packages for Alpine, although one I couldn't find was <strong>libimagequant</strong>, so this might be the 'culprit'. Nonetheless, it the traceback and error message seem to be saying that <code>jpeg</code> is missing, whereas I have installed <code>openjpeg</code>. </p> <p>How can I modify the <code>Dockerfile</code> so that <code>pip install Pillow</code> runs?</p>
44,044,479
12
1
null
2017-05-18 09:31:37.977 UTC
18
2022-05-23 20:27:32.223 UTC
null
null
null
null
995,862
null
1
99
python|docker|dockerfile|pillow|alpine-linux
93,723
<p>In a comment that appears to have been deleted later, someone pointed me to <a href="https://github.com/python-pillow/Pillow/blob/c05099f45c0d94a2a98c3609a96bdb6cf7446627/depends/alpine_Dockerfile" rel="noreferrer">https://github.com/python-pillow/Pillow/blob/c05099f45c0d94a2a98c3609a96bdb6cf7446627/depends/alpine_Dockerfile</a>. Based on that Dockerfile I modified my own as follows:</p> <pre><code>FROM python:alpine RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN pip install Pillow </code></pre> <p>Now it builds successfully.</p>
5,543,280
How do I get the deleted-branch back in Git?
<p>I'm trying to use Git for our software development. I found that if I delete a branch in Git, I could lose my code forever. That surprised me. I thought as a version control system, it should be able to let me do anything (even stupid one) without worry about harming my work.</p> <p>The steps below are what I did:</p> <ol> <li>Initialize a Git repository.</li> <li>commit several changes to repository.</li> <li>switch/checkout current working directory to first commit.</li> <li>delete master branch.</li> <li>then I lost all of my work and I can't believe what I saw. Is it real? If I am drunk while coding. I could lose the code in Git.</li> </ol> <p>The question is how can I roll back the action of deleting a branch?</p> <p>Or, how can I get all history in Git, even something which has disappeared in log?</p>
5,543,479
1
5
null
2011-04-04 19:23:07.333 UTC
13
2021-04-10 20:18:44.317 UTC
2021-04-10 20:18:44.317 UTC
null
63,550
null
83,946
null
1
36
git
28,963
<p>To avoid the issue in the first place, <a href="https://stackoverflow.com/users/119963/jefromi">Jefromi</a> advices in the comments:</p> <blockquote> <p>Another tip: only use <strong><code>git branch -d</code></strong>, not <code>git branch -D</code>.<br> You'll be warned if you're about to delete something that might make you lose work, then you can take a second to think before using <code>-D</code>.<br> (Or, you can go delete from <code>gitk</code> so you really see what you're deleting.)</p> </blockquote> <pre><code>-d </code></pre> <blockquote> <p>Delete a branch.<br> The branch must be fully merged in its upstream branch, or in <code>HEAD</code> if no upstream was set with <code>--track</code> or <code>--set-upstream</code>.</p> </blockquote> <hr> <p>But if you did "lose" your work, see one of the <a href="http://blag.ahax.de/post/421939327/recovering-a-deleted-branch-using-git-reflog" rel="noreferrer">many blogs</a> <a href="http://effectif.com/git/recovering-lost-git-commits" rel="noreferrer">about reflog</a> (as <a href="https://stackoverflow.com/users/617364/james-kyburz">James Kyburz</a> suggests in the comments):</p> <p><a href="http://chrissloan.info/blog/git_reflog_to_the_rescue/" rel="noreferrer">Git reflog to the rescue</a>:</p> <p>back to list Git reflog to the rescue September 09, 2010 — written by Chris Sloan | 0 comments »</p> <blockquote> <p>The other day, I was working on a feature for Real Travel using our current branching strategy in that each release we do is a separate branch.<br> Not sure if it was a cause of lack of sleep from late hours pulled, but <strong>I accidentally deleted my local and remote copy of the branch before I merged it back into the master branch for release</strong>.<br> After a quick state of shock and thoughts running through my head of losing hours of work, I calmed down and relied on my Git knowledge.<br> Reading your full commit history:</p> <p>There are two ways to read the commit history in git. The first way shows a list of details commits while the other shows the log in reference to the current <code>HEAD</code>.</p> </blockquote> <pre><code>// log of detailed commits by users $&gt; git log // reference log compared to the current HEAD $&gt; git reflog </code></pre> <blockquote> <p>Using the <code>reflog</code> command, I was able to find out exactly where the last reference to my deleted branch was.<br> An example output of the <code>reflog</code> might look like this:</p> </blockquote> <pre><code>c7f3d98 HEAD@{0}: commit: Merged in some code f5716c8 HEAD@{1}: pull : Fast-forward d93c27b HEAD@{2}: commit: Added some items to project ... </code></pre> <blockquote> <p>Now the reflog will not show exactly where the branch was deleted, but if you remember your last commit to that branch and have a detailed enough message, it should be easy to find and restore.</p> <p>Restoring your branch is straight forward by checking out the HEAD you want to a new branch.</p> </blockquote> <pre><code>$&gt; git checkout -b my_new_branch HEAD@{5} </code></pre> <blockquote> <p>You can also use the hash too to checkout the new branch.</p> </blockquote> <pre><code>$&gt; git checkout -b my_new_branch d93c27b </code></pre> <blockquote> <p>Simple enough and now I can move on with actually merging the branch in before deletion.</p> </blockquote>
24,575,869
Read file and plot CDF in Python
<p>I need to read long file with timestamp in seconds, and plot of CDF using numpy or scipy. I did try with numpy but seems the output is NOT what it is supposed to be. The code below: Any suggestions appreciated. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Filename.txt') sorted_data = np.sort(data) cumulative = np.cumsum(sorted_data) plt.plot(cumulative) plt.show() </code></pre>
24,576,863
6
1
null
2014-07-04 13:52:00.563 UTC
7
2019-03-17 18:00:39.047 UTC
2014-07-26 23:48:52.307 UTC
null
973,680
null
3,277,160
null
1
9
python|numpy|matplotlib|scipy|cdf
52,778
<p>You have two options:</p> <p>1: you can bin the data first. This can be done easily with the <code>numpy.histogram</code> function:</p> <pre> import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Filename.txt') # Choose how many bins you want here num_bins = 20 # Use the histogram function to bin the data counts, bin_edges = np.histogram(data, bins=num_bins, normed=True) # Now find the cdf cdf = np.cumsum(counts) # And finally plot the cdf plt.plot(bin_edges[1:], cdf) plt.show() </pre> <p>2: rather than use <code>numpy.cumsum</code>, just plot the <code>sorted_data</code> array against the number of items smaller than each element in the array (see this answer for more details <a href="https://stackoverflow.com/a/11692365/588071">https://stackoverflow.com/a/11692365/588071</a>):</p> <pre> import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('Filename.txt') sorted_data = np.sort(data) yvals=np.arange(len(sorted_data))/float(len(sorted_data)-1) plt.plot(sorted_data,yvals) plt.show() </pre>
21,911,560
How can I set one NVIDIA graphics card for display and other for computing(in Linux)?
<p>I have install NVIDIA display driver and CUDA tookit on my machine with one NVIDIA GT520 card (used for both display and computation) but it is giving me error <b>"the launch timed out and was terminated"</b>, for some program. I searched for this error they are saying this error is due to OS watchdog(CentOS 6) and my kernel is taking too much of time. I find one solution that I can insert two cards and I can use one for display and other for computation on<a href="https://devtalk.nvidia.com/default/topic/521245/the-launch-timed-out-and-was-terminated-strange-error-on-cudamemcpy/"> this link</a>. How can I set particular one card for display and other for computation. I have CentOS 6.5 with kernel 2.6.32-431.3.1.el6.x86_64.</p>
21,913,494
1
1
null
2014-02-20 15:02:09.63 UTC
8
2014-02-20 16:17:05.02 UTC
null
null
null
null
2,182,934
null
1
6
linux|cuda
7,328
<p>A general description of how to do this is given <a href="http://nvidia.custhelp.com/app/answers/detail/a_id/3029/~/using-cuda-and-x">here</a>. You want to use the option 1 which is excerpted below:</p> <p>Option 1: Use Two GPUs (RECOMMENDED)</p> <p>If two GPUs can be made available in the system, then X processing can be handled on one GPU while CUDA tasks are executed on the other. This allows full interactivity and no disturbance of X while simultaneously allowing unhindered CUDA execution.</p> <p>In order to accomplish this:</p> <p>•The X display should be forced onto a single GPU using the BusID parameter in the relevant "Device" section of the xorg.conf file. In addition, any other "Device" sections should be deleted. For example:</p> <pre><code> BusID "PCI:34:0:0" </code></pre> <p>The PCI IDs of the GPUs may be determined from the lspci command or from the nvidia-smi -a command.</p> <p>•CUDA processing should be forced onto the other GPU, for example by using the CUDA_VISIBLE_DEVICES environment variable before any CUDA applications are launched. For example:</p> <pre><code> export CUDA_VISIBLE_DEVICES="1" </code></pre> <p>(Choose the numerical parameter to select the GPU that is not the X GPU)</p>
33,009,469
BaseActivity for Navigation
<p>I'm building a base activity for navigation and want something flexible so the Activity dictates to the Base Activity which layout to inflate.</p> <p>I have the following</p> <pre><code>public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private int mLayoutRes; protected void setLayout(int layoutRes) { mLayoutRes = layoutRes; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(mLayoutRes); // Layout implements toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null){ setSupportActionBar(toolbar); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // The layout implements the nav if (drawer != null){ ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } } // Other Nav code ommitted as its too verbose } </code></pre> <p>Then the Layout is passed from the activity as folows</p> <pre><code>public class Home extends BaseActivity { private final String TAG = "Home"; @Override protected void onCreate(Bundle savedInstanceState) { super.setLayout(R.layout.activity_home); super.onCreate(savedInstanceState); // Other Activity code } } </code></pre> <p>Is there a better way to achieve this? Maybe setting a base layout with a content frame and inflating into that?</p> <p>Any suggestions would be appreciated.</p>
33,010,518
6
1
null
2015-10-08 07:36:28.34 UTC
11
2018-03-19 04:43:09.18 UTC
null
null
null
null
3,392,017
null
1
9
android|navigation-drawer
15,469
<p>You can follow <a href="https://github.com/google/iosched/blob/2014/android/src/main/java/com/google/samples/apps/iosched/ui/BaseActivity.java" rel="nofollow noreferrer">BaseActivity</a> from Google IO application. Just override <code>setContentView</code> and you dont need <code>setLayout</code></p> <p>Here is my BaseActivity</p> <pre><code>package com.vtcmobile.kqviet.activity; public class BaseActivity extends AppCompatActivity { private Toolbar toolbar; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private NavigationView navigationView; protected Context mContext; public NavigationView getNavigationView() { return navigationView; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = BaseActivity.this; } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); initToolbar(); } private void initToolbar() { toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } private void setUpNav() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name); drawerLayout.setDrawerListener(drawerToggle); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); navigationView = (NavigationView) findViewById(R.id.navigation); // Setting Navigation View Item Selected Listener to handle the item // click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { public boolean onNavigationItemSelected(MenuItem menuItem) { // Checking if the item is in checked state or not, if not make // it in checked state if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); // Closing drawer on item click drawerLayout.closeDrawers(); // Check to see which item was being clicked and perform // appropriate action Intent intent; switch (menuItem.getItemId()) { case R.id.xxxx: return true; } return false; } }); // Setting the actionbarToggle to drawer layout // calling sync state is necessay or else your hamburger icon wont show // up drawerToggle.syncState(); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setUpNav(); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) return true; // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre>
32,791,995
error: cannot assign a value to final variable
<p>I am working on an assignment and I'm stuck on this error: cannot assign a value to final variable count</p> <p>Here is my code so far...</p> <pre><code>public class List { private final int Max = 25; private final int count; private Person list[]; public List() { count = 0; list = new Person[Max]; } public void addSomeone(Person p) { if (count &lt; Max){ count++; // THIS IS WHERE THE ERROR OCCURS list[count-1] = p; } } public String toString() { String report = ""; for (int x=0; x &lt; count; x++) report += list[x].toString() + "\n"; return report; } } </code></pre> <p>I'm very new to java and am obviously not a computer whiz so please explain the problem/solution in the simplest terms possible. Thank you so much.</p>
32,792,014
5
1
null
2015-09-25 23:25:50.853 UTC
1
2021-12-17 09:04:26.087 UTC
null
null
null
null
5,378,058
null
1
8
java|variables|variable-assignment
62,866
<p><code>count++;</code> will throw an error. Per Oracle,</p> <blockquote> <p>A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.</p> </blockquote> <p>You can follow along with that article <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4" rel="noreferrer">here</a>. Looking at your code, it seems that you really don't want <code>count</code> to be final. You want to be able to change its value throughout the program. The fix would be to remove the <code>final</code> modifier.</p>
9,567,682
How to set up Selenium with Chromedriver on Jenkins-hosted Grid
<p>I just make my frist steps with Selenium. I successfully set up a test (Firefox driver), running on Selenium grid on my Jenkins (using Jenkins-Selenium-Grid plugin). I also installed Chromdriver plugin and Chrome itself on the machine (Server2003 64bit) running Jenkins. Chrome is installed for all users (in C:\Program Files (x86)\Google\Chrome\Application\chrome.exe). The Problem is: as soon i try to use the Chromedriver i get</p> <pre><code>UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. </code></pre> <p>Since the Firefox test runs fine it must be a problem with "browser start"?! So the first question is: What is the default location for chrome binary that Chromdriver assumes? Second Question: How to fix this? Is there an Einvironment Property to set? Or could i simply set PATH to chrome.exe' location.</p> <p>UPDATE: i dug around a bit, ithink i ran into <a href="http://code.google.com/p/selenium/issues/detail?id=2362" rel="nofollow">this</a> or <a href="http://code.google.com/p/selenium/issues/detail?id=3366" rel="nofollow">that</a>. is the any workaround for this issues? </p>
28,510,818
4
0
null
2012-03-05 13:45:49.877 UTC
1
2016-06-27 12:29:34.023 UTC
2012-03-05 16:00:45.84 UTC
null
447,426
null
447,426
null
1
3
selenium|jenkins|jenkins-plugins|selenium-chromedriver
49,375
<p>Just went through the same process myself.</p> <p>Using <a href="https://wiki.jenkins-ci.org/display/JENKINS/Selenium+Plugin" rel="noreferrer">Selenium Plugin</a> you can set up the selenium grid.<br> Using <a href="https://wiki.jenkins-ci.org/display/JENKINS/ChromeDriver+plugin" rel="noreferrer">Chromedriver Plugin</a> you can have chrome driver automatically installed.<br> Using <a href="https://wiki.jenkins-ci.org/display/JENKINS/Selenium+Axis+Plugin" rel="noreferrer">Selenium Axis Plugin</a> you can create matrix jobs. </p> <p><strong>First time installation issue</strong> After installing the Chromedriver plugin it can take a few minutes to download and be ready after it is automatically installed. It can be that the slaves try and install the chromedriver before master is fully installed and so fail to lookup the download location. Restarting the slaves will cause it to try again and install the chromedriver on the slaves.</p> <p>On each slave and the master you should finally end up with a <code>$JENKINS_HOME\tools\chromedriver\chromedrive.exe</code> which you can refer to in the Jenkins Selenium plugin configuration for Chrome[driver] binary path as <code>tools\chromedrive\chromedriver.exe</code> and Jenkins will prepend the slave specific <code>$JENKINS_HOME</code> for you. <img src="https://i.stack.imgur.com/Itf2O.jpg" alt="Jenkins Selenium Config"></p> <p>Installed Chrome to the default location which turned out to be <code>C:\Program Files (x86)\Google\Chrome\Application\chrome.exe</code> same as described.</p> <p>At this point I could run a test job succesfully without the error you have shown. </p> <pre><code>DesiredCapabilities capability = DesiredCapabilities.chrome(); WebDriver driver = new RemoteWebDriver(new URL("http://Jenkins.ip.here:4444/wd/hub"), capability); driver.get(siteBase.toString()); String page = driver.getPageSource(); </code></pre> <p>So some other things to consider </p> <ul> <li>having changed jenkins selenium config, did you restart selenium service, after config change it appears to stop them. Does the config have instances specified.</li> <li><p>if it was an install location issue, you might be able to change the install location options in the test cases using</p> <pre><code>ChromeOptions options = new ChromeOptions(); options.setBinary("/path/to/other/chrome/binary"); </code></pre></li> </ul>
9,016,871
Android design - RelativeLayout (background color)
<p>I've the following RelativeLayout but i would like to improve it. (make a nice design)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout android:id="@+navigate/RLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ABABAB" xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textStyle="bold" android:id="@+id/hcorpo" android:layout_centerHorizontal="true" android:src="@drawable/hcorpo" android:layout_marginTop="15dp" /&gt;. &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textStyle="bold|italic" android:textColor="#000000" android:id="@+id/hotelinfos" android:layout_below="@+id/hcorpo" android:layout_alignLeft="@+id/hcorpo" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textStyle="bold" android:textColor="#000000" android:id="@+id/hotelname" android:layout_below="@+id/hotelinfos" android:layout_alignLeft="@+id/hotelinfos" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/hoteladdress" android:layout_below="@+id/hotelname" android:layout_alignLeft="@+id/hotelname" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:id="@+id/hotelphone" android:layout_below="@+id/hoteladdress" android:layout_alignLeft="@+id/hoteladdress" android:layout_marginTop="10dp" android:textColor="#12C" android:textStyle="bold|italic" android:onClick="onClick" android:clickable="true" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#12C" android:onClick="onClick" android:clickable="true" android:textStyle="bold|italic" android:id="@+id/hotelemail" android:layout_below="@+id/hotelphone" android:layout_alignLeft="@+id/hotelphone" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:textStyle="bold|italic" android:id="@+id/bookinginfos" android:layout_below="@+id/hotelemail" android:layout_alignLeft="@+id/hotelemail" android:layout_marginTop="20dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/pnr" android:layout_below="@+id/bookinginfos" android:layout_alignLeft="@+id/bookinginfos" android:layout_marginTop="10dp" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/segmentCode" android:layout_below="@+id/bookinginfos" android:layout_toRightOf="@+id/pnr" android:layout_marginTop="10dp" android:layout_marginRight="20dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/checkin" android:layout_below="@+id/pnr" android:layout_alignLeft="@+id/pnr" android:layout_marginTop="10dp" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/checkout" android:layout_below="@+id/pnr" android:layout_toRightOf="@+id/checkin" android:layout_marginTop="10dp" android:layout_marginRight="20dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/nights" android:layout_below="@+id/pnr" android:layout_toRightOf="@+id/checkout" android:layout_marginTop="10dp" android:layout_marginRight="20dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/roomType" android:layout_below="@+id/checkin" android:layout_alignLeft="@+id/checkin" android:layout_marginTop="10dp" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/boardBasis" android:layout_below="@+id/roomType" android:layout_alignLeft="@+id/roomType" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/paxNames" android:layout_below="@+id/boardBasis" android:layout_alignLeft="@+id/boardBasis" android:layout_marginTop="10dp" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:textStyle="bold|italic" android:id="@+id/forHotel" android:layout_below="@+id/paxNames" android:layout_alignLeft="@+id/paxNames" android:layout_marginTop="20dp" android:layout_marginRight="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/supplierCode" android:layout_below="@+id/forHotel" android:layout_alignLeft="@+id/forHotel" android:layout_marginTop="10dp" android:layout_marginRight="10dp" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/picture" android:layout_below="@+id/hcorpo" android:layout_alignRight="@+id/hcorpo" android:layout_marginTop="10dp"/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>I would like to do something like the tripadvisor app: <a href="http://hpics.li/d961aa3" rel="noreferrer">http://hpics.li/d961aa3</a> explanation:</p> <p>For example i would like to put the following part in a nice white rectangle:</p> <pre><code>&lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textStyle="bold|italic" android:textColor="#000000" android:id="@+id/hotelinfos" android:layout_below="@+id/hcorpo" android:layout_alignLeft="@+id/hcorpo" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textStyle="bold" android:textColor="#000000" android:id="@+id/hotelname" android:layout_below="@+id/hotelinfos" android:layout_alignLeft="@+id/hotelinfos" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textColor="#000000" android:id="@+id/hoteladdress" android:layout_below="@+id/hotelname" android:layout_alignLeft="@+id/hotelname" android:layout_marginTop="10dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:id="@+id/hotelphone" android:layout_below="@+id/hoteladdress" android:layout_alignLeft="@+id/hoteladdress" android:layout_marginTop="10dp" android:textColor="#12C" android:textStyle="bold|italic" android:onClick="onClick" android:clickable="true" /&gt; </code></pre> <p>Should i create a new RelativeLayout with another background color?</p> <p>Any help is appreciated !</p>
9,017,080
3
0
null
2012-01-26 10:36:38.13 UTC
1
2012-01-26 11:09:24 UTC
null
null
null
null
833,635
null
1
6
android|xml|android-relativelayout
38,322
<p>To get round rectangles as background in any layout, you can use 9 patch PNG images or use shape class to create custom drawables.</p> <p>Just check my sample code below, it may useful to you.</p> <p><strong>main.xml</strong> in layout folder</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="20dip" android:orientation="vertical" android:background="@drawable/bg"&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Testing white rectangle" android:textColor="#f00" android:padding="10dip" android:textSize="25dip" /&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Testing white rectangle" android:textColor="#0f0" android:padding="10dip" android:textSize="25dip" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>bg.xml</strong> in drawable folder</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"&gt; &lt;solid android:color="#fff"/&gt; &lt;corners android:bottomLeftRadius="7dip" android:topRightRadius="7dip" android:topLeftRadius="7dip" android:bottomRightRadius="7dip" /&gt; &lt;/shape&gt; </code></pre> <p><strong>Java file</strong></p> <pre><code>public class WhiteRectangle extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } </code></pre> <p><strong>The output is</strong> </p> <p><img src="https://i.stack.imgur.com/rx3lX.png" alt="White rectangle as background"></p>
9,406,475
Why is strtok changing its input like this?
<p>Ok, so I understand that strtok modifies its input argument, but in this case, it's collapsing down the input string into only the first token. Why is this happening, and what can I do to fix it? (Please note, I'm not talking about the variable "temp", which <em>should</em> be the first token, but rather the variable "input", which after one call to strtok becomes "this") </p> <pre><code>#include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main(int argc, char* argv[]) { char input[]="this is a test of the tokenizor seven"; char * temp; temp=strtok(input," "); printf("input: %s\n", input); //input is now just "this" } </code></pre>
9,406,528
3
0
null
2012-02-23 02:52:19.353 UTC
10
2012-02-23 03:01:14.59 UTC
null
null
null
null
1,209,326
null
1
20
c|strtok
15,646
<p>When <code>strtok()</code> finds a token, it changes the character immediately after the token into a <code>\0</code>, and then returns a pointer to the token. The next time you call it with a <code>NULL</code> argument, it starts looking after the separators that terminated the first token -- i.e., after the <code>\0</code>, and possibly further along.</p> <p>Now, the original pointer to the beginning of the string still points to the beginning of the string, but the first token is now <code>\0</code>-terminated -- i.e., <code>printf()</code> thinks the end of the token is the end of the string. The rest of the data is still there, but that <code>\0</code> stops <code>printf()</code> from showing it. If you used a <code>for</code>-loop to walk over the original input string up to the original number of characters, you'd find the data is all still there.</p>
9,379,043
Namespace aliasing in F#?
<p>I have a name clashing problem while opening some .Net assemblies in my F# code using</p> <pre><code>open System.IO </code></pre> <p>The only option I found and use now is to provide the full names of types for conflicting types, but this is a little bit boring.</p> <p>Is there any possibility to define an alias for .Net namespace in F# to prevent name clashing?</p>
9,379,274
1
0
null
2012-02-21 14:13:29.487 UTC
1
2012-02-21 14:29:26.563 UTC
null
null
null
null
376,692
null
1
29
f#|namespaces|alias
5,255
<p>F# does not support aliasing of namespaces - only modules and types. So, to resolve the conflicts between .NET assemblies, you will, unfortunatelly, need to define aliases for all the types you're using.</p> <p>This may be slightly easier thanks to the fact that F# type aliases are viewed as normal type declarations (by the F# compiler, not by the runtime). This means that, unlike with C# <code>using</code> keyword, you can define them in a spearate file:</p> <pre><code>// Aliases.fs namespace SysIO // Open the 'System' namespace to get a bit shorter syntax // ('type File = File' is interpreted as discriminated union) open System type File = IO.File type Directory = IO.Directory </code></pre> <p>In the rest of your application, you can now use <code>SysIO.File</code>. You still have to write the aliases, but at least you don't have to do that in every file...</p>
9,268,045
How can I detect that the Shift key has been pressed?
<p>I have a <code>NSView</code> subclass and I would like it to react when the user presses the <kbd>⇧ Shift</kbd> key. However, <code>-[NSView keyDown:]</code> (which I currently override) isn't called when modifier keys alone are pressed.</p> <p>How can I be notified when the Shift key has been pressed?</p>
9,268,267
7
0
null
2012-02-13 21:08:23.293 UTC
4
2020-05-20 17:54:36.53 UTC
2014-07-04 03:36:56.157 UTC
null
251,153
null
251,153
null
1
32
macos|cocoa
18,477
<p>From the Cocoa event handling guide:</p> <blockquote> <p>The flagsChanged: method can be useful for detecting the pressing of modifier keys without any other key being pressed simultaneously. For example, if the user presses the Option key by itself, your responder object can detect this in its implementation of flagsChanged:.</p> </blockquote> <p>More details can be found <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html">here</a>.</p> <p>The documentation for <em>NSResponder</em> also states the following:</p> <blockquote> <p>flagsChanged:</p> <p>Informs the receiver that the user has pressed or released a modifier key (Shift, Control, and so on).</p> <p>-- (void)flagsChanged:(NSEvent *)theEvent</p> </blockquote>
1,783,519
How to round *down* integers in Java?
<p>I'd like to round integers down to their nearest 1000 in Java.</p> <p>So for example:</p> <ul> <li>13,623 rounds to 13,000</li> <li>18,999 rounds to 18,000</li> <li>etc</li> </ul>
1,783,525
3
2
null
2009-11-23 14:38:16.573 UTC
3
2019-08-12 06:44:43.107 UTC
2009-11-23 14:41:03.747 UTC
null
573
null
216,104
null
1
22
java|numbers
38,871
<p>Simply divide by 1000 to lose the digits that are not interesting to you, and multiply by 1000:</p> <pre><code>i = i/1000 * 1000 </code></pre> <p>Or, you can also try:</p> <pre><code>i = i - (i % 1000) </code></pre>
1,964,969
Android: how to get the intent received by a service?
<p>I'm starting a service with an intent where I put extra information.</p> <p>How can I get the intent in the code of my service?</p> <p>There isn't a function like <code>getIntent().getExtras()</code> in service like in activity.</p>
1,964,974
3
0
null
2009-12-27 02:23:35.473 UTC
6
2016-12-25 13:49:21.617 UTC
2012-04-24 08:56:50.763 UTC
null
476,747
null
239,033
null
1
32
android|service|android-intent
34,480
<p>Override <code>onStart()</code> -- you receive the <code>Intent</code> as a parameter.</p>
1,648,172
Invoke EXE from batch file *without* waiting
<p>How do I invoke an EXE from a batch file without having the latter waiting for the EXE to finish? Something like the Cygwin 'cygstart'?</p>
1,648,175
3
0
null
2009-10-30 05:32:54.217 UTC
2
2016-03-11 20:45:01.087 UTC
null
null
null
null
129,543
null
1
34
batch-file
38,545
<p>Use "<code>start</code>". Type "<code>start /?</code>" at a command prompt.</p>
1,641,094
In WiX files, what does Name="SourceDir" refer to?
<p>WiX files always seem to include this line:</p> <pre><code>&lt;Directory Id="TARGETDIR" Name="SourceDir"&gt; </code></pre> <p>What is "SourceDir"? What is it used for? It's not a real directory name. Is it some kind of magical value?</p>
2,145,075
3
1
null
2009-10-29 01:09:26.807 UTC
17
2022-05-09 21:03:15.453 UTC
2016-09-09 15:30:53.323 UTC
null
129,130
null
60,620
null
1
67
wix|windows-installer|wix3
26,744
<p>From: <a href="https://robmensching.com/blog/posts/2010/1/26/stackoverflow-what-does-namesourcedir-refer-to/" rel="nofollow noreferrer">https://robmensching.com/blog/posts/2010/1/26/stackoverflow-what-does-namesourcedir-refer-to/</a></p> <p>Honestly, it's something that we should have hidden from the developer but didn't. Sorry. The truth of the matter is that the Windows Installer expects the Directory tree to always be rooted in a Directory row where the primary key (Directory/@Id) is &quot;TARGETDIR&quot; and the DefaultDir column (Directory/@Name) is &quot;SourceDir&quot;.</p> <p>During an install, TARGETDIR will default to the largest drive on the machine. <a href="https://docs.microsoft.com/en-us/windows/win32/msi/sourcedir" rel="nofollow noreferrer">SourceDir</a> will be set to the location where the MSI is being executed. Now, SourceDir is tricky after the initial install because it won't be set unless the ResolveSource action is called. However, you don't want to explicitly call the ResolveSource action because it is likely to prompt you to provide the original source media (aka: insert the CD, please).</p> <p>What we should have done in the WiX toolset is remove the need to specify the TARGETDIR/SourceDir pair and say &quot;Any Directory element that has no parent will automatically be parented to TARGETDIR because that's what the MSI SDK says to do.&quot; Instead, you have to do it yourself... and some devs wonder what it all means.</p>
8,480,341
set a boolean value
<p>Hi I'm working with boolean values and I'm a little bit confused. I have a boolean value:</p> <pre><code>boolean answer; </code></pre> <p>This can have two values : yes or not.</p> <p>If I insert from standard input the string "yes" it became true otherwise false. How can i do?</p>
8,480,356
7
1
null
2011-12-12 20:25:36.183 UTC
null
2011-12-14 00:20:11.003 UTC
null
null
null
null
1,055,637
null
1
2
java|boolean
52,728
<p>assuming input is your string:</p> <p><code>boolean answer = input.equalsIgnoreCase("yes");</code></p>
8,363,247
Python & XAMPP on Windows: how to?
<p>I have installed on my Win7x64 Xampp and Python 2.7.</p> <p>Now I'm trying to get the "power" of Python language... how can I do it?</p> <p>I've tried with mod_python and mod_wsgi but the first one does not exist for my version of Python, and when I try to start Apache after installing wsgi it gives me an error </p> <pre><code>&lt; Directory "\x93C:/wsgi_app\x94"&gt; path is invalid </code></pre> <p>I added a space between &lt; and 'directory' to make the string visible here.</p> <p>So... Anyone knows if there is a little tutorial to install these features?</p> <p>Or is anyone is kind enough to explain me step by step what shall I do?</p> <p>Thanks and sorry if i'm not so able to explain me.</p> <p>If you need something, please ask me.</p>
8,365,990
2
1
null
2011-12-02 22:01:05.267 UTC
13
2016-03-25 19:52:28.37 UTC
2014-08-26 06:56:50.933 UTC
null
1,078,216
null
1,078,216
null
1
10
python|windows|apache|xampp|mod-wsgi
49,986
<p>Yes you are right, mod_python won't work with Python 2.7. So mod_wsgi is the best option for you.</p> <p>I would recommend AMPPS as python environment is by default enabled with mod_python and python 2.5. <a href="http://www.ampps.com" rel="noreferrer">AMPPS Website</a></p> <p>if you still want to continue,</p> <p>Add this line in httpd.conf</p> <pre><code>LoadModule wsgi_module modules/mod_wsgi.so </code></pre> <p>Uncomment the line in httpd.conf</p> <pre><code>Include conf/extra/httpd-vhosts.conf </code></pre> <p>Open vhost file httpd-vhosts.conf and add</p> <pre><code>NameVirtualHost 127.0.0.1:80 &lt;VirtualHost 127.0.0.1:80&gt; &lt;Directory "path/to/directory/in/which/wsgi_test.wsgi/is/present"&gt; Options FollowSymLinks Indexes AllowOverride All Order deny,allow allow from All &lt;/Directory&gt; ServerName 127.0.0.1 ServerAlias 127.0.0.1 WSGIScriptAlias /wsgi "path/to/wsgi_test.wsgi" DocumentRoot "path/to/htdocs" ErrorLog "path/to/log.err" CustomLog "path/to/log.log" combined &lt;/VirtualHost&gt; </code></pre> <p>Add the following lines in wsgi_test.wsgi</p> <pre><code>def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] </code></pre> <p>Note : Don't make the test directory in htdocs. Because I haven't tried that yet. These steps worked for me in AMPPS. :)</p> <p>Then access 127.0.0.1/wsgi in your favorite browser. You will see Hello World!.</p> <p>If you don't see, follow <a href="http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide" rel="noreferrer">QuickConfigurationGuide</a></p> <p>OR</p> <p>You can add these lines in httpd.conf</p> <pre><code>&lt;IfModule wsgi_module&gt; &lt;Directory path/to/directory&gt; Options FollowSymLinks Indexes AllowOverride All Order deny,allow allow from All &lt;/Directory&gt; WSGIScriptAlias /wsgi path/to/wsgi_test.wsgi &lt;/IfModule&gt; </code></pre>
8,961,071
Android: Changing Background-Color of the Activity (Main View)
<p>I want to change the background color of my Main-View (not a Button or a Text-View) just the real background which is usually black... I got this code:</p> <pre><code>view.setBackgroundColor(0xfff00000); </code></pre> <p>This is inside an <code>OnClickListener</code>, but it just changes the background of the Button. </p>
8,961,125
10
1
null
2012-01-22 12:34:14.873 UTC
10
2021-08-09 12:46:52.523 UTC
2019-01-09 14:33:02.333 UTC
null
1,017,247
null
1,017,247
null
1
28
java|android|colors
134,089
<p>Try creating a method in your <code>Activity</code> something like...</p> <pre><code>public void setActivityBackgroundColor(int color) { View view = this.getWindow().getDecorView(); view.setBackgroundColor(color); } </code></pre> <p>Then call it from your OnClickListener passing in whatever colour you want.</p>
8,373,755
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity
<p>My app allows the user to press a button, it opens the camera, they can take a photo and it will show up in an <code>ImageView</code>. If the user presses back or cancel while the camera is open I get this force close - Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity... so i am guessing the result=0 is the issue what would I need to insert to make this stop force closing?</p> <p>Below is my code. I know I am forgetting something but just cant figure it out! (Admittedly I am about 2 weeks into learning android development). Thanks for any help!</p> <pre class="lang-java prettyprint-override"><code>private static final int CAMERA_REQUEST = 1888; private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.imageView = (ImageView)this.findViewById(R.id.photostrippic1); ImageView photoButton = (ImageView) this.findViewById(R.id.photostrippic1); photoButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } }); protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getExtras().get(&quot;data&quot;); imageView.setImageBitmap(photo); } </code></pre> <p>I guess I would need a &quot;else&quot; in there somewhere but I dont exactly know to do that.</p> <p>below is the logcat</p> <pre><code> java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity {photo.booth.app/photo.booth.app.PhotoboothActivity}: java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:2934) at android.app.ActivityThread.handleSendResult(ActivityThread.java:2986) at android.app.ActivityThread.access$2000(ActivityThread.java:132) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1068) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:150) at android.app.ActivityThread.main(ActivityThread.java:4293) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at photo.booth.app.PhotoboothActivity.onActivityResult(PhotoboothActivity.java:76) at android.app.Activity.dispatchActivityResult(Activity.java:4108) at android.app.ActivityThread.deliverResults(ActivityThread.java:2930) ... 11 more </code></pre>
10,357,574
11
1
null
2011-12-04 06:30:39.24 UTC
15
2022-02-21 13:44:22.027 UTC
2021-03-27 02:04:45.097 UTC
null
10,553,536
null
1,055,911
null
1
70
android|nullpointerexception|android-camera-intent
132,282
<p>Adding this first conditional should work:</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode != RESULT_CANCELED){ if (requestCode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(photo); } } } </code></pre>
341,080
ASP.NET DropDownList AutoPostback Not Working - What Am I Missing?
<p>I am attempting to get a DropDownList to AutoPostBack via an UpdatePanel when the selected item is changed. I'm going a little stir-crazy as to why this isn't working.</p> <p>Does anyone have any quick ideas?</p> <p>ASPX page:</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" &gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"&gt; &lt;asp:ListItem&gt;item 1&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;item 2&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>Code-behind (I put a breakpoint on the string assignment to capture the postback):</p> <pre><code>protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string s = ""; } </code></pre> <p><strong>Edit:</strong></p> <p><strong>OK, I have it working now. Very weird. All it took was a restart of Visual Studio. This is the kind of thing that frightens me as a developer ;) I think I've seen similar before, where VS gets "out of sync" wrt the assembly it's running.</strong></p> <p><strong>FYI I am running VS 2008 Web Developer Express.</strong></p> <p><strong>Thanks to those that answered.</strong></p>
341,147
4
0
null
2008-12-04 15:52:10.77 UTC
null
2013-11-30 21:50:17.823 UTC
2008-12-04 16:21:34.517 UTC
sasserstyl
38,522
sasserstyl
38,522
null
1
3
c#|asp.net|updatepanel|autopostback
44,756
<p>I was able to get it to work with what you posted. This is the code I used... Basically what you had but I am throwing an exception.</p> <pre><code> &lt;asp:ScriptManager ID="smMain" runat="server" /&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" &gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"&gt; &lt;asp:ListItem&gt;item 1&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;item 2&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { throw new NotImplementedException(); } </code></pre> <p>I tried a lot of variations to see if there was something off, but the exception was thrown every time. </p> <p>You might want to try the exception route to see if the postback is happening and this isn't a debugger issue. </p> <ul> <li><p>One issue might be with Vista and not running Visual Studios as administrator. I know that has a tendency to not allow debugging. </p></li> <li><p>Maybe the assembly you are running doesn't match the code? This might happen if you "View in Browswer" and then attach the debugger.</p></li> </ul>
1,029,185
Please share your experience with JavaScriptMVC, alternatives
<p>I have been reading through the documentation on the <a href="http://javascriptmvc.com/" rel="noreferrer">JavaScriptMVC</a> framework and it looks interesting. I am wondering if anybody here has used the framework, and with what success.</p> <p>So please share your experience with <a href="http://javascriptmvc.com/" rel="noreferrer">JavaScriptMVC</a>, if you have any. If you can suggest another MVC javascript framework that is fine to.</p> <p>Best regards, Egil.</p>
1,695,839
4
0
null
2009-06-22 20:15:34.43 UTC
9
2012-03-02 17:43:21.933 UTC
null
null
null
null
32,809
null
1
6
javascript|model-view-controller|javascriptmvc
1,597
<p>I have no experience with JavascriptMVC. However another really famous MVC framework for Javascript is ActiveJS <a href="http://www.activerecordjs.org/" rel="nofollow noreferrer">http://www.activerecordjs.org/</a> which came out about a year ago. It's by Aptana the people who make Aptana Studio and Jaxer (server side javascript). I do believe that would probably hold more merrit as Jaxer is amazing technology so I have no doubt Aptana have thought about this a lot.</p> <p>I also use a jQuery project called Ajaxy which offers Controllers to Ajax requests in my own projects. <a href="http://github.com/balupton/AJAXY/" rel="nofollow noreferrer">http://github.com/balupton/AJAXY/</a></p>
51,032
Is there a difference between foo(void) and foo() in C++ or C?
<p>Consider these two function definitions:</p> <pre><code>void foo() { } void foo(void) { } </code></pre> <p>Is there any difference between these two? If not, why is the <code>void</code> argument there? Aesthetic reasons?</p>
51,080
4
1
null
2008-09-09 00:48:23.63 UTC
73
2021-11-12 09:18:35.14 UTC
2017-01-13 23:12:13.047 UTC
null
1,459,996
Landon
1,597
null
1
275
c++|c|arguments
76,358
<p>In <strong>C</strong>: </p> <ul> <li><code>void foo()</code> means "a function <code>foo</code> taking an unspecified number of arguments of unspecified type" </li> <li><code>void foo(void)</code> means "a function <code>foo</code> taking no arguments"</li> </ul> <p>In <strong>C++</strong>: </p> <ul> <li><code>void foo()</code> means "a function <code>foo</code> taking no arguments" </li> <li><code>void foo(void)</code> means "a function <code>foo</code> taking no arguments"</li> </ul> <p>By writing <code>foo(void)</code>, therefore, we achieve the same interpretation across both languages and make our headers multilingual (though we usually need to do some more things to the headers to make them truly cross-language; namely, wrap them in an <code>extern "C"</code> if we're compiling C++).</p>
1,142,103
How do I load a shared object in C++?
<p>I have a shared object (a so - the Linux equivalent of a Windows dll) that I'd like to import and use with my test code. </p> <p>I'm sure it's not this simple ;) but this is the sort of thing I'd like to do..</p> <pre><code>#include "headerforClassFromBlah.h" int main() { load( "blah.so" ); ClassFromBlah a; a.DoSomething(); } </code></pre> <p>I assume that this is a really basic question but I can't find anything that jumps out at me searching the web.</p>
1,142,169
4
3
null
2009-07-17 08:50:46.88 UTC
14
2017-07-10 12:31:04.13 UTC
2009-07-17 09:10:06.077 UTC
null
22,185
null
22,185
null
1
30
c++|load|shared-objects
51,594
<p>There are two ways of loading shared objects in C++</p> <p>For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code.</p> <p>Statically:</p> <pre><code>#include "blah.h" int main() { ClassFromBlah a; a.DoSomething(); } gcc yourfile.cpp -lblah </code></pre> <p>Dynamically (In Linux):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;dlfcn.h&gt; int main(int argc, char **argv) { void *handle; double (*cosine)(double); char *error; handle = dlopen ("libm.so", RTLD_LAZY); if (!handle) { fprintf (stderr, "%s\n", dlerror()); exit(1); } dlerror(); /* Clear any existing error */ cosine = dlsym(handle, "cos"); if ((error = dlerror()) != NULL) { fprintf (stderr, "%s\n", error); exit(1); } printf ("%f\n", (*cosine)(2.0)); dlclose(handle); return 0; } </code></pre> <p>*Stolen from <a href="http://linux.die.net/man/3/dlopen" rel="noreferrer">dlopen Linux man page</a> The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching.</p> <p>For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage. </p> <p>There are some words <a href="http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.prftungd/doc/prftungd/when_dyn_linking_static_linking.htm" rel="noreferrer">Here</a> about when to use static and when to use dynamic linking.</p>
770,726
Moving multiple files in TFS Source Control
<p>I'm using Team Foundation Server 2008 (SP 1) and I need to move multiple files from one folder to another (to retain file history). In addition to Team Explorer (with SP 1) I've also got the latest TFS Power Tools (October 2008) installed (for Windows Shell integration).</p> <p>Now, the problem is that I can't seem to select and move multiple files via either the shell or the Source Control Explorer window. I can move individual files (by right clicking + "Move") and I can move whole folders (same operation) but when I select multiple files (in a folder) the "Move" context item is grayed/disabled.</p> <p>Does anyone know if this is possible.. and if not.. why not!?</p> <p>Can anyone suggest a workaround which isn't overly complicated?</p> <p><strong>Please vote up here:</strong> <a href="https://connect.microsoft.com/VisualStudio/feedback/details/715041/support-moving-multiple-files-in-tfs-source-control-explorer" rel="noreferrer">https://connect.microsoft.com/VisualStudio/feedback/details/715041/support-moving-multiple-files-in-tfs-source-control-explorer</a> <strong>and here</strong> <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2271540-allow-to-move-more-than-one-file-at-once-in-tfs-so" rel="noreferrer">http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2271540-allow-to-move-more-than-one-file-at-once-in-tfs-so</a></p> <p><img src="https://i.stack.imgur.com/QQWi4.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/8t53e.png" alt="enter image description here"></p>
772,728
4
0
null
2009-04-21 01:36:43.267 UTC
30
2022-05-03 11:24:45.76 UTC
2014-08-14 10:06:15.167 UTC
null
248,616
null
18,471
null
1
178
version-control|tfs
50,724
<p>Use the tf.exe tool from the Visual studio commandline - it can handle wildcards:</p> <pre><code>tf.exe move &lt;olditem&gt; &lt;newitem&gt; </code></pre> <p>Example:</p> <pre><code>tf.exe move "$/My Project/V*" "$/My Project/Archive" </code></pre> <p>[EDIT] As noted in the comments: move is an alias for rename. Both commands move history.</p>
25,698,072
SimpleClientHttpRequestFactory vs HttpComponentsClientHttpRequestFactory for Http Request timeout with RestTemplate?
<p>I am working on a project in which I need to make a HTTP URL call to my server which is running Restful Service which returns back the response as a <code>JSON String</code>.</p> <p>Below is my main code which is using the future and callables:</p> <pre><code>public class TimeoutThreadExample { private ExecutorService executor = Executors.newFixedThreadPool(10); private RestTemplate restTemplate = new RestTemplate(); public String getData() { Future&lt;String&gt; future = executor.submit(new Task(restTemplate)); String response = null; try { response = future.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return response; } } </code></pre> <p>Below is my <code>Task</code> class which implements the <code>Callable</code> interface and uses the <code>RestTemplate</code>:</p> <pre><code>class Task implements Callable&lt;String&gt; { private RestTemplate restTemplate; public Task(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String call() throws Exception { String url = "some_url"; String response = restTemplate.getForObject(url, String.class); return response; } } </code></pre> <p><strong>Problem Statement:</strong></p> <p>As you can see above, I am using default way of executing the URL using <code>RestTemplate</code> which doesn't use any Http Request timeout so that means internally it is using <code>-1</code> as the <code>read</code> and <code>connection</code> timeout. </p> <p>Now what I am looking to do is, I want to set up Http Request timeout using <code>RestTemplate</code> in my above code efficiently. And I am not sure which class I need to use for that, I can see <code>HttpComponentsClientHttpRequestFactory</code> and <code>SimpleClientHttpRequestFactory</code> so not sure which one I need to use?</p> <p>Any simple example basis on my above code will help me understand better on how to set the Http Request timeout using <code>RestTemplate</code>.</p> <p>And also does my Http Request timeout value should be less than future timeout value?</p> <ul> <li><code>HttpComponentsClientHttpRequestFactory</code> vs <code>SimpleClientHttpRequestFactory</code>. Which one to use?</li> <li>Does my Http Request timeout value should be less than future timeout value?</li> </ul>
25,706,265
2
0
null
2014-09-06 07:42:21.553 UTC
8
2021-02-12 08:43:52.027 UTC
2014-09-07 01:35:29.983 UTC
null
819,916
null
819,916
null
1
11
java|multithreading|spring|httprequest|resttemplate
26,460
<p>By default RestTemplate uses <code>SimpleClientHttpRequestFactory</code> which depends on default configuration of <code>HttpURLConnection</code>. </p> <p>You can configure them by using below attributes:</p> <pre><code>-Dsun.net.client.defaultConnectTimeout=TimeoutInMiliSec -Dsun.net.client.defaultReadTimeout=TimeoutInMiliSec </code></pre> <p>If you want to use <code>HttpComponentsClientHttpRequestFactory</code> - it has a connection pooling configuration which <code>SimpleClientHttpRequestFactory</code> does not have.</p> <p>A sample code for using <code>HttpComponentsClientHttpRequestFactory</code>:</p> <pre><code>public class TimeoutThreadExample { private ExecutorService executor = Executors.newFixedThreadPool(10); private static final RestTemplate restTemplate = createRestTemplate(); private static RestTemplate createRestTemplate(){ HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setReadTimeout(READ_TIME_OUT); requestFactory.setConnectTimeout(CONNECTION_TIME_OUT); return new RestTemplate(requestFactory); } public String getData() { Future&lt;String&gt; future = executor.submit(new Task(restTemplate)); String response = null; try { response = future.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return response; } } </code></pre>
51,738,158
Can I define the Negatable interface in Java?
<p>Asking this question to clarify my understanding of type classes and higher kinded types, I'm not looking for workarounds in Java.</p> <hr> <p>In Haskell, I could write something like</p> <pre class="lang-hs prettyprint-override"><code>class Negatable t where negate :: t -&gt; t normalize :: (Negatable t) =&gt; t -&gt; t normalize x = negate (negate x) </code></pre> <p>Then assuming <code>Bool</code> has an instance of <code>Negatable</code>, </p> <pre class="lang-hs prettyprint-override"><code>v :: Bool v = normalize True </code></pre> <p>And everything works fine.</p> <hr> <p>In Java, it does not seem possible to declare a proper <code>Negatable</code> interface. We could write:</p> <pre><code>interface Negatable { Negatable negate(); } Negatable normalize(Negatable a) { a.negate().negate(); } </code></pre> <p>But then, unlike in Haskell, the following would not compile without a cast (assume <code>MyBoolean</code> implements <code>Negatable</code>):</p> <pre><code>MyBoolean val = normalize(new MyBoolean()); // does not compile; val is a Negatable, not a MyBoolean </code></pre> <p><strong>Is there a way to refer to the implementing type in a Java interface, or is this a fundamental limitation of the Java type system?</strong> If it is a limitation, is it related to higher-kinded type support? I think not: it looks like this is another sort of limitation. If so, does it have a name?</p> <p>Thanks, and please let me know if the question is unclear!</p>
51,749,646
4
0
null
2018-08-08 03:17:15.28 UTC
7
2018-08-09 02:04:52.29 UTC
2018-08-08 21:38:26.843 UTC
null
2,707,792
null
5,259,805
null
1
51
java|haskell|typeclass
3,344
<p>In general, no.</p> <p>You <em>can</em> use tricks (as suggested in the other answers) that will make this work, but they do not provide all of the same guarantees that the Haskell typeclass does. Specifically, in Haskell, I could define a function like this:</p> <pre><code>doublyNegate :: Negatable t =&gt; t -&gt; t doublyNegate v = negate (negate v) </code></pre> <p>It is now known that the argument and return value of <code>doublyNegate</code> are both <code>t</code>. But the Java equivalent:</p> <pre><code>public &lt;T extends Negatable&lt;T&gt;&gt; T doublyNegate (Negatable&lt;T&gt; v) { return v.negate().negate(); } </code></pre> <p>doesn't, because <code>Negatable&lt;T&gt;</code> could be implemented by another type:</p> <pre><code>public class X implements Negatable&lt;SomeNegatableClass&gt; { public SomeNegatableClass negate () { return new SomeNegatableClass(); } public static void main (String[] args) { new X().negate().negate(); // results in a SomeNegatableClass, not an X } </code></pre> <p>This isn't particularly serious for this application, but does cause trouble for other Haskell typeclasses, e.g. <code>Equatable</code>. There is no way of implementing a Java <code>Equatable</code> typeclass without using an additional object and sending an instance of that object around wherever we send values that need comparing, (e.g: </p> <pre><code>public interface Equatable&lt;T&gt; { boolean equal (T a, T b); } public class MyClass { String str; public static class MyClassEquatable implements Equatable&lt;MyClass&gt; { public boolean equal (MyClass a, MyClass b) { return a.str.equals(b.str); } } } ... public &lt;T&gt; methodThatNeedsToEquateThings (T a, T b, Equatable&lt;T&gt; eq) { if (eq.equal (a, b)) { System.out.println ("they're equal!"); } } </code></pre> <p>(In fact, this is exactly how Haskell implements type classes, but it hides the parameter passing from you so you don't need to figure out which implementation to send where)</p> <p>Trying to do this with just plain Java interfaces leads to some counterintuitive results:</p> <pre><code>public interface Equatable&lt;T extends Equatable&lt;T&gt;&gt; { boolean equalTo (T other); } public MyClass implements Equatable&lt;MyClass&gt; { String str; public boolean equalTo (MyClass other) { return str.equals(other.str); } } public Another implements Equatable&lt;MyClass&gt; { public boolean equalTo (MyClass other) { return true; } } .... MyClass a = ....; Another b = ....; if (b.equalTo(a)) assertTrue (a.equalTo(b)); .... </code></pre> <p>You'd expect, due to the fact that <code>equalTo</code> really ought to be defined symmetrically, that if the <code>if</code> statement there compiles, the assertion would also compile, but it doesn't, because <code>MyClass</code> isn't equatable with <code>Another</code> even though the other way around is true. But with a Haskell <code>Equatable</code> type class, we know that if <code>areEqual a b</code> works, then <code>areEqual b a</code> is also valid. [1]</p> <p>Another limitation of interfaces versus type classes is that a type class can provide a means of creating a value which implements the type class without having an existing value (e.g. the <code>return</code> operator for <code>Monad</code>), whereas for an interface you must already have an object of the type in order to be able to invoke its methods.</p> <p>You ask whether there is a name for this limitation, but I'm not aware of one. It's simply because type classes are actually different to object-oriented interfaces, despite their similarities, because they are implemented in this fundamentally different way: an object is a subtype of its interface, thus carries around a copy of the interface's methods directly without modifying their definition, while a type class is a separate list of functions each of which is customised by substituting type variables. There is no subtype relationship between a type and a type class that has an instance for the type (a Haskell <code>Integer</code> isn't a subtype of <code>Comparable</code>, for example: there simply exists a <code>Comparable</code> instance that can be passed around whenever a function needs to be able to compare its parameters and those parameters happen to be Integers).</p> <p>[1]: The Haskell <code>==</code> operator is actually implemented using a type class, <code>Eq</code> ... I haven't used this because operator overloading in Haskell can be confusing to people not familiar with reading Haskell code.</p>
2,730,849
the easiest way to convert matrix to one row vector
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2724020/how-do-you-concatenate-the-rows-of-a-matrix-into-a-vector-in-matlab">How do you concatenate the rows of a matrix into a vector in MATLAB?</a> </p> </blockquote> <p>Hi,</p> <p>Does anyone know what is the best way to create one row matrix (vector) from M x N matrix by putting all rows, from 1 to M, of the original matrix into first row of new matrix the following way:</p> <pre><code>A = [row1; row2; ...; rowM] B = [row1, row2, ..., rowM] </code></pre> <p>Example:</p> <pre><code>A = [1 1 0 0; 0 1 0 1] B = [1 1 0 0 0 1 0 1] </code></pre> <p>Is there a simple method or perhaps a built-in function that could generate matrix B from A?</p>
2,730,889
2
1
null
2010-04-28 15:24:50.147 UTC
8
2014-01-20 18:36:51.417 UTC
2017-05-23 11:54:06.34 UTC
null
-1
null
22,996
null
1
20
matlab|matrix
129,200
<p>Try this: <code>B = A ( : )</code>, or try the <code>reshape</code> function. </p> <p><a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html" rel="noreferrer">http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html</a></p>
2,976,011
How to get fractions in an integer division?
<p>How do you divide two integers and get a double or float answer in C?</p>
2,976,020
2
2
null
2010-06-04 16:30:47.31 UTC
4
2020-08-23 18:55:16.463 UTC
2013-02-05 15:21:56.703 UTC
null
24,587
null
358,661
null
1
24
c|integer-division
94,223
<p>You need to cast one or the other to a <code>float</code> or <code>double</code>.</p> <pre><code>int x = 1; int y = 3; // Before x / y; // (0!) // After ((double)x) / y; // (0.33333...) x / ((double)y); // (0.33333...) </code></pre> <p>Of course, make sure that you are store the <em>result</em> of the division in a <code>double</code> or <code>float</code>! It doesn't do you any good if you store the result in another <code>int</code>.</p> <hr> <p>Regarding @Chad's comment ("<code>[tailsPerField setIntValue:tailsPer]</code>"):</p> <p>Don't pass a double or float to <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSControl/setIntValue:" rel="noreferrer"><code>setIntValue</code></a> when you have <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSControl/setDoubleValue:" rel="noreferrer"><code>setDoubleValue</code></a>, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.</p> <p>For example, on my system, the file:</p> <pre><code>#include &lt;stdio.h&gt; int main() { double x = 3.14; printf("%d", x); return 0; } </code></pre> <p>outputs:</p> <pre>1374389535</pre> <p>because the double was attempted to be read as an int.</p>
2,751,870
How, exactly, does the double-stringize trick work?
<p>At least some <strong>C</strong> preprocessors let you stringize the value of a macro, rather than its name, by passing it through one function-like macro to another that stringizes it:</p> <pre><code>#define STR1(x) #x #define STR2(x) STR1(x) #define THE_ANSWER 42 #define THE_ANSWER_STR STR2(THE_ANSWER) /* "42" */ </code></pre> <p>Example use cases <a href="http://everything2.com/title/stringize+macro+macro+hack" rel="noreferrer">here</a>.</p> <p>This does work, at least in GCC and Clang (both with <code>-std=c99</code>), but I'm not sure <em>how</em> it works in C-standard terms.</p> <p>Is this behavior guaranteed by C99?<br> If so, how does C99 guarantee it?<br> If not, at what point does the behavior go from C-defined to GCC-defined?</p>
2,751,891
2
2
null
2010-05-01 23:17:06.797 UTC
50
2016-02-15 21:44:21.58 UTC
2016-02-15 21:44:21.58 UTC
null
4,370,109
null
30,461
null
1
90
c|c-preprocessor|stringification
20,462
<p>Yes, it's guaranteed.</p> <p>It works because arguments to macros are themselves macro-expanded, <em>except</em> where the macro argument name appears in the macro body with the stringifier # or the token-paster ##.</p> <p>6.10.3.1/1:</p> <blockquote> <p>... After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded...</p> </blockquote> <p>So, if you do <code>STR1(THE_ANSWER)</code> then you get "THE_ANSWER", because the argument of STR1 is not macro-expanded. However, the argument of STR2 <em>is</em> macro-expanded when it's substituted into the definition of STR2, which therefore gives STR1 an argument of <code>42</code>, with the result of "42".</p>
41,122,028
Set default value to option select menu
<p>I want to bind a custom attribute to an option select menu. The <code>&lt;option&gt;</code> tag would simply have an attribute of <code>selected="selected"</code></p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;select&gt; &lt;option v-for="" v-bind:selected="[condition ? selected : notSelected]" value=""&gt;{{ resource.xprm_name }}&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/template&gt; data: { selected: "selected", notSelected: "" } </code></pre> <p>This does not work, but if I change <code>v-bind:selected</code> to <code>v-bind:class</code> then it receives the appropriate class, so the logic is working, but not with the <code>selected</code> attribute. </p> <p>Any way to make it work with such custom attributes?</p>
41,123,073
4
0
null
2016-12-13 13:11:53.477 UTC
9
2022-02-22 13:36:06.243 UTC
2016-12-13 13:27:15.303 UTC
null
1,072,354
null
1,072,354
null
1
54
vue-component|vue.js|vuejs2
146,780
<p>You can just use <code>v-model</code> for selecting a default value on a select box:</p> <p>Markup:</p> <pre><code>&lt;div id="app"&gt; &lt;select v-model="selected"&gt; &lt;option value="foo"&gt;foo&lt;/option&gt; &lt;option value="bar"&gt;Bar&lt;/option&gt; &lt;option value="baz"&gt;Baz&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>View Model:</p> <pre><code>new Vue({ el: "#app", data: { selected: 'bar' } }); </code></pre> <p>Here's the JSFiddle: <a href="https://jsfiddle.net/Lxfxyqmf/" rel="noreferrer">https://jsfiddle.net/Lxfxyqmf/</a></p>
1,980,689
C#: Code Contracts vs. normal parameter validation
<p>consider the following two pieces of code:</p> <pre><code> public static Time Parse(string value) { string regXExpres = "^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$"; Contract.Requires(value != null); Contract.Requires(new Regex(regXExpres).IsMatch(value)); string[] tokens = value.Split(':'); int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture); int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture); return new Time(hour, minute); } </code></pre> <p>and</p> <pre><code> public static Time Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] tokens = value.Split(':'); if (tokens.Length != 2) { throw new FormatException("value must be h:m"); } int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture); if (!(0 &lt;= hour &amp;&amp; hour &lt;= 24)) { throw new FormatException("hour must be between 0 and 24"); } int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture); if (!(0 &lt;= minute &amp;&amp; minute &lt;= 59)) { throw new FormatException("minute must be between 0 and 59"); } return new Time(hour, minute); } </code></pre> <p>I personally prefer the first version because the code is much clearer and smaller, and the Contracts can be easily turned off. But the disadvantage is that Visual Studio Code Analysis blames that I should check the parameter value for null and the Contracts of the constructor do not realize that the regex ensures that minute and hour are within the given boundarys.</p> <p>So i end up having a lot of wrong warnings and I see no way to validate string values with contracts without ending up throwing FormatExceptions other than a RegEx validation.</p> <p>Any suggestions how you would solve this and equivalent situations using Code contracts?</p>
1,980,767
1
1
null
2009-12-30 15:18:41.35 UTC
7
2010-02-24 12:25:38.737 UTC
2010-02-24 12:25:38.737 UTC
null
240,966
null
240,966
null
1
32
c#|.net|.net-4.0|code-contracts|microsoft-contracts
7,875
<p>In order to get rid of warnings you can use <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract.assume(VS.100).aspx" rel="noreferrer">Contract.Assume</a></p>
20,182,676
Unlock xcode files?
<p>A few days ago I had an issue with my mac so I took it to the Genius bar at a local Apple store. They said the partitions failed on the hard drive and that it had to be reformatted. I use a program to automatically back up the system to an external server, so I wasn't concerned about loosing anything. They reformatted and I've been putting things back in place.</p> <p>What I have not been able to figure out.. I have a number of Xcode projects that I need to work on but when I try to open them in Xcode I get this.</p> <blockquote> <p>The file "project.xcworkspace" could not be unlocked. Could not add write permission to the file because you do not own it. Try modifying the permissions of the file in the Finder or Terminal.</p> </blockquote> <p>I tried unlocking the project, the main folder, and the p.list file in finder and making sure that I had read/write access but I'm still getting the error. </p> <p>When they reformatted the computer it did erase all of the keys and certificates I've been looking but I don't think the software backs up the credentials on the computer so I don't think I can access the old certificates and keys. </p> <p>Has anyone run into this before? How do I unlock the file?</p>
20,182,779
3
0
null
2013-11-24 23:53:50.877 UTC
7
2020-07-02 08:16:43.607 UTC
null
null
null
null
1,349,533
null
1
29
xcode
48,397
<p>Remember the Project isn't just a standalone "<code>.xcodeproj</code>" file but it's actually a folder that contains a number of hidden items.</p> <p>So when applying permissions, make certain to apply permissions to <em>every</em> item in your project folder.</p> <p>You can do this via the "Apply Permissions to Enclosed Items" popdown menu (available in the "Get Info" window), which looks like this:</p> <p><img src="https://i.stack.imgur.com/eGEqB.jpg" alt="Apply Permissions to Enclosed Items"></p>
21,462,777
WebActivatorEx vs OwinStartup
<p>In a WebAPI application for example, what is the difference between</p> <pre><code>[assembly: OwinStartup(typeof(MyClass), "MyMethod")] </code></pre> <p>and </p> <pre><code>[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyClass), "MyMethod")] </code></pre> <p>?</p>
32,887,056
2
0
null
2014-01-30 17:01:08.407 UTC
10
2015-10-01 11:57:38.183 UTC
2014-01-30 17:02:44.037 UTC
null
76,337
null
360,245
null
1
20
asp.net|web|owin
8,998
<p>They both are similar at a high level in the sense that they allow you to carry out initialization of your web application, but they are different in some important ways as below:</p> <ol> <li>Methods targeted by <code>WebActivatorEx.PreApplicationStartMethodAttribute</code> will execute before the Application has started up. This allows you to do things like injecting an HttpModule etc.</li> <li>Methods targeted by <code>OwinStartupAttribute</code> will execute after Application has initialized. This is because this kind of startup is invoked by <code>OwinHttpModule</code> which in itself is injected in using <code>System.Web.PreApplicationStartMethodAttribute</code>.</li> <li>Owin startup can be disabled via configuration by using an appsetting within web.config of <code>owin:AutomaticAppStartup</code></li> <li>There is also <code>System.Web.PreApplicationStartMethodAttribute</code> which as of .NET 4.5 can be used multiple times within an assembly.</li> </ol> <p>So to summarise, this is the order of execution of methods depending on the attributes used.</p> <ol> <li><code>System.Web.PreApplicationStartMethodAttribute</code></li> <li><code>WebActivatorEx.PreApplicationStartMethodAttribute</code></li> <li>Global.asax (<code>Application_Start</code> method)</li> <li><code>OwinStartupAttribute</code></li> </ol>
29,978,413
Merge arrays in Ruby/Rails
<p>How can I merge two arrays? Something like this:</p> <pre><code>@movie = Movie.first() @options = Movie.order("RANDOM()").first(3).merge(@movie) </code></pre> <p>But it doesn't work.</p> <p>In <code>@options</code> I need an array with four elements includes <code>@movie</code>.</p>
29,978,458
5
0
null
2015-04-30 21:49:14.543 UTC
5
2020-04-08 13:44:58.55 UTC
2020-04-08 13:44:58.55 UTC
null
6,245,337
null
4,743,327
null
1
27
ruby-on-rails|ruby|ruby-on-rails-4|orm|rails-activerecord
61,629
<p>Like this?</p> <pre><code>⚡️ irb 2.2.2 :001 &gt; [1,2,3] + [4,5,6] =&gt; [1, 2, 3, 4, 5, 6] </code></pre> <p>But you don't have 2 arrays.</p> <p>You could do something like:</p> <pre><code>@movie = Movie.first() @options = Movie.order("RANDOM()").first(3).to_a &lt;&lt; @movie </code></pre>
20,429,246
How to write to .txt files in Python 3
<p>I have a <code>.txt</code> file in the same folder as this <code>.py</code> file and it has this in it:</p> <pre><code>cat\n dog\n rat\n cow\n </code></pre> <p>How can I save a var (var = 'ant') to the next line of the <code>.txt</code> file?</p>
20,429,275
2
0
null
2013-12-06 16:49:12.18 UTC
7
2020-02-21 14:20:14.58 UTC
2013-12-07 20:06:32.07 UTC
null
321,731
null
3,075,190
null
1
62
python|file|text|file-io
111,709
<p>Open the file in append mode and write a new line (including a <code>\n</code> line separator):</p> <pre><code>with open(filename, 'a') as out: out.write(var + '\n') </code></pre> <p>This adds the line at the end of the file after all the other contents.</p>
27,080,089
How to organize large Shiny apps?
<p>What are the best practices to organize larger Shiny applications?<br> I think best R practices are also applicable to Shiny.<br> Best R practices are discussed here: <a href="https://stackoverflow.com/questions/1266279/how-to-organize-large-r-programs?rq=1">How to organize large R programs</a><br> Link to Google's R Style Guide: <a href="https://google.github.io/styleguide/Rguide.xml" rel="noreferrer">Style Guide</a></p> <p>But what are the unique tips and tricks in Shiny context which I can adopt to make my Shiny code look better (and more readable)? I am thinking of things like:</p> <ul> <li>Exploiting object oriented programming in Shiny</li> <li>In <code>server.R</code> which parts should be sourced?</li> <li>File hierarchy of project containing markdown documents, pictures, xml and source files</li> </ul> <p>For example if I am using <code>navbarPage</code> and <code>tabsetPanel</code> in every <code>tabPanel</code> my code is starting to look quite messy after addition of several UI elements.</p> <p>Example code:</p> <pre><code>server &lt;- function(input, output) { #Here functions and outputs.. } ui &lt;- shinyUI(navbarPage("My Application", tabPanel("Component 1", sidebarLayout( sidebarPanel( # UI elements.. ), mainPanel( tabsetPanel( tabPanel("Plot", plotOutput("plot") # More UI elements.. ), tabPanel("Summary", verbatimTextOutput("summary") # And some more... ), tabPanel("Table", tableOutput("table") # And... ) ) ) ) ), tabPanel("Component 2"), tabPanel("Component 3") )) shinyApp(ui = ui, server = server) </code></pre> <p>For organizing <code>ui.R</code> code I found quite nice solution from GitHub: <a href="https://github.com/mostly-harmless/radiant/blob/master/dev/marketing/ui.R" rel="noreferrer">radiant code</a><br> Solution is to use <code>renderUI</code> to render every <code>tabPanel</code> and in <code>server.R</code> tabs are sourced to different files.</p> <pre><code>server &lt;- function(input, output) { # This part can be in different source file for example component1.R ################################### output$component1 &lt;- renderUI({ sidebarLayout( sidebarPanel( ), mainPanel( tabsetPanel( tabPanel("Plot", plotOutput("plot")), tabPanel("Summary", verbatimTextOutput("summary")), tabPanel("Table", tableOutput("table")) ) ) ) }) ##################################### } ui &lt;- shinyUI(navbarPage("My Application", tabPanel("Component 1", uiOutput("component1")), tabPanel("Component 2"), tabPanel("Component 3") )) shinyApp(ui = ui, server = server) </code></pre>
36,517,069
5
0
null
2014-11-22 17:06:29.987 UTC
54
2022-08-19 19:58:54.987 UTC
2018-01-31 11:53:17.76 UTC
null
6,656,269
null
4,222,792
null
1
72
r|shiny
19,320
<p>After addition of <strong>modules</strong> to R shiny. Managing of complex structures in shiny applications has become a lot easier.</p> <p>Detailed description of shiny modules:<a href="http://shiny.rstudio.com/articles/modules.html" rel="noreferrer">Here</a></p> <blockquote> <p>Advantages of using modules: </p> <ul> <li>Once created, they are easily reused</li> <li>ID collisions is easier to avoid</li> <li>Code organization based on inputs and output of modules</li> </ul> </blockquote> <p>In tab based shiny app, one tab can be considered as one module which has <strong>inputs</strong> and <strong>outputs</strong>. Outputs of tabs can be then passed to other tabs as inputs. </p> <p>Single-file app for tab-based structure which exploits modular thinking. App can be tested by using <a href="https://vincentarelbundock.github.io/Rdatasets/csv/datasets/cars.csv" rel="noreferrer">cars</a> dataset. Parts of the code where copied from the Joe Cheng(first link). All comments are welcome. </p> <pre><code># Tab module # This module creates new tab which renders dataTable dataTabUI &lt;- function(id, input, output) { # Create a namespace function using the provided id ns &lt;- NS(id) tagList(sidebarLayout(sidebarPanel(input), mainPanel(dataTableOutput(output)))) } # Tab module # This module creates new tab which renders plot plotTabUI &lt;- function(id, input, output) { # Create a namespace function using the provided id ns &lt;- NS(id) tagList(sidebarLayout(sidebarPanel(input), mainPanel(plotOutput(output)))) } dataTab &lt;- function(input, output, session) { # do nothing... # Should there be some logic? } # File input module # This module takes as input csv file and outputs dataframe # Module UI function csvFileInput &lt;- function(id, label = "CSV file") { # Create a namespace function using the provided id ns &lt;- NS(id) tagList( fileInput(ns("file"), label), checkboxInput(ns("heading"), "Has heading"), selectInput( ns("quote"), "Quote", c( "None" = "", "Double quote" = "\"", "Single quote" = "'" ) ) ) } # Module server function csvFile &lt;- function(input, output, session, stringsAsFactors) { # The selected file, if any userFile &lt;- reactive({ # If no file is selected, don't do anything validate(need(input$file, message = FALSE)) input$file }) # The user's data, parsed into a data frame dataframe &lt;- reactive({ read.csv( userFile()$datapath, header = input$heading, quote = input$quote, stringsAsFactors = stringsAsFactors ) }) # We can run observers in here if we want to observe({ msg &lt;- sprintf("File %s was uploaded", userFile()$name) cat(msg, "\n") }) # Return the reactive that yields the data frame return(dataframe) } basicPlotUI &lt;- function(id) { ns &lt;- NS(id) uiOutput(ns("controls")) } # Functionality for dataselection for plot # SelectInput is rendered dynamically based on data basicPlot &lt;- function(input, output, session, data) { output$controls &lt;- renderUI({ ns &lt;- session$ns selectInput(ns("col"), "Columns", names(data), multiple = TRUE) }) return(reactive({ validate(need(input$col, FALSE)) data[, input$col] })) } ################################################################################## # Here starts main program. Lines above can be sourced: source("path-to-module.R") ################################################################################## library(shiny) ui &lt;- shinyUI(navbarPage( "My Application", tabPanel("File upload", dataTabUI( "tab1", csvFileInput("datafile", "User data (.csv format)"), "table" )), tabPanel("Plot", plotTabUI( "tab2", basicPlotUI("plot1"), "plotOutput" )) )) server &lt;- function(input, output, session) { datafile &lt;- callModule(csvFile, "datafile", stringsAsFactors = FALSE) output$table &lt;- renderDataTable({ datafile() }) plotData &lt;- callModule(basicPlot, "plot1", datafile()) output$plotOutput &lt;- renderPlot({ plot(plotData()) }) } shinyApp(ui, server) </code></pre>
17,810,637
Mongoose versioning: when is it safe to disable it?
<p>From the <a href="http://mongoosejs.com/docs/guide.html#versionKey" rel="noreferrer">docs</a>:</p> <blockquote> <p>The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v. If this conflicts with your application you can configure as such:</p> <p>[...]</p> <p>Document versioning can also be disabled by setting the versionKey to false. DO NOT disable versioning unless you know what you are doing.</p> </blockquote> <p>But I'm curious, in which cases it should be safe to disable this feature?</p>
18,956,020
1
1
null
2013-07-23 12:48:50.973 UTC
8
2019-11-13 19:00:04.293 UTC
2013-09-23 09:11:38.15 UTC
null
369,001
null
1,565,597
null
1
22
mongodb|mongoose
16,152
<p>The version key purpose is optimistic locking.</p> <p>When enabled, the version value is atomically incremented whenever a document is updated.</p> <p>This allow your application code to test if changes have been made between a fetch (bringing in version key 42 for example) and a consequent update (ensuring version value still is 42). If version key has a different value (eg. 43 because an update has been made to the document), your application code can handle the concurrent modification.</p> <p>The very same concept is often used in relational databases instead of pessimistic locking that can bring horrible performance. All decent ORMs provide such a feature. For example it's nicely described <a href="http://www.objectdb.com/java/jpa/persistence/lock#Optimistic_Locking_" rel="noreferrer">in ObjectDB documentation</a>. It's an object database implemented in Java but the same concept applies.</p> <p>The <a href="http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning" rel="noreferrer">blog post</a> linked in Behlül's comment demonstrate the optimistic locking usefulness with a concrete example, but only for arrays changes, see below.</p> <p>On the opposite, here is a simple case where its useless: a user profile that can be edited by its owner ownly. Here you can get rid of optimistic locking and assume that the last edit always wins.</p> <p>So, only you know if your application need optimistic locking or not. Use case by use case.</p> <p>The Mongoose situation is somewhat special.</p> <p>Optimistic locking is enabled only for arrays because the internal storage format uses positional index. This is the issue described by the <a href="http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning" rel="noreferrer">blog post</a> linked in the question's comment. I found the <a href="http://grokbase.com/t/gg/mongoose-orm/137g5v9qs7/mongoose-confusion-about-versioning" rel="noreferrer">explanation</a> given in the <code>mongoose-orm</code> mailing list pretty clear: if you need optimistic locking for other fields, you need to handle it yourself.</p> <p>Here is a <a href="https://gist.github.com/bpceee/c6acb6c86f5674b91eba" rel="noreferrer">gist</a> showing how to implement a retry strategy for an <code>add</code> operation. Again, how you want to handle it depends on your use cases but it should be enough to get you started.</p> <p>I hope this clears things up.</p> <p>Cheers</p>
17,928,366
What is the recommended max value for join_buffer_size in mysql?
<p>I am traying to optimize my temporary data following the recommendation given in the answer to this question: <a href="https://stackoverflow.com/questions/13259275/mysql-tmp-table-size-max-heap-table-size">Mysql tmp_table_size max_heap_table_size</a></p> <p>What is the recommended value for <code>join_buffer_size</code> and <code>sort_buffer_size</code> in mysql?</p> <p>My actual values are:</p> <pre><code>join_buffer_size: 128 Kio; sort buffer size: 512 Kio; </code></pre>
17,936,079
1
0
null
2013-07-29 15:43:35.813 UTC
3
2015-04-07 12:43:02.51 UTC
2017-05-23 11:45:51.947 UTC
null
-1
null
2,456,038
null
1
10
mysql|sql
54,079
<p>It is impossible to answer your question in a general case. It really depends on the profile of your queries. Check the manual, learn their purpose, and as they put it nicely:</p> <p>(<a href="http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_sort_buffer_size">sort_buffer_size</a>)</p> <blockquote> <p>Setting it larger than required globally will slow down most queries that sort. It is best to increase it as a session setting, and only for the sessions that need a larger size. On Linux, there are thresholds of 256KB and 2MB where larger values may significantly slow down memory allocation (...). Experiment to find the best value for your workload.</p> </blockquote> <p>(<a href="http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_join_buffer_size">join_buffer_size</a>)</p> <blockquote> <p>There is no gain from setting the buffer larger than required to hold each matching row, and all joins allocate at least the minimum size, so use caution in setting this variable to a large value globally. It is better to keep the global setting small and change to a larger setting only in sessions that are doing large joins. Memory allocation time can cause substantial performance drops if the global size is larger than needed by most queries that use it.</p> </blockquote>
26,501,276
Converting Hex String to NSData in Swift
<p>I got the code to convert String to HEX-String in Objective-C:</p> <pre><code>- (NSString *) CreateDataWithHexString:(NSString*)inputString { NSUInteger inLength = [inputString length]; unichar *inCharacters = alloca(sizeof(unichar) * inLength); [inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)]; UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1)); NSInteger i, o = 0; UInt8 outByte = 0; for (i = 0; i &lt; inLength; i++) { UInt8 c = inCharacters[i]; SInt8 value = -1; if (c &gt;= '0' &amp;&amp; c &lt;= '9') value = (c - '0'); else if (c &gt;= 'A' &amp;&amp; c &lt;= 'F') value = 10 + (c - 'A'); else if (c &gt;= 'a' &amp;&amp; c &lt;= 'f') value = 10 + (c - 'a'); if (value &gt;= 0) { if (i % 2 == 1) { outBytes[o++] = (outByte &lt;&lt; 4) | value; outByte = 0; } else { outByte = value; } } else { if (o != 0) break; } } NSData *a = [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES]; NSString* newStr = [NSString stringWithUTF8String:[a bytes]]; return newStr; } </code></pre> <p>I want the same in Swift. Can anybody translate this code in Swift, or is there any easy way to do this in Swift?</p>
26,502,285
13
0
null
2014-10-22 06:11:15.167 UTC
10
2022-09-15 13:15:53.863 UTC
2021-03-09 20:31:47.267 UTC
null
1,265,393
null
1,717,036
null
1
49
ios|objective-c|swift
46,131
<p>This is my hex string to <code>Data</code> routine:</p> <pre><code>extension String { /// Create `Data` from hexadecimal string representation /// /// This creates a `Data` object from hex string. Note, if the string has any spaces or non-hex characters (e.g. starts with '&lt;' and with a '&gt;'), those are ignored and only hex characters are processed. /// /// - returns: Data represented by this hexadecimal string. var hexadecimal: Data? { var data = Data(capacity: count / 2) let regex = try! NSRegularExpression(pattern: &quot;[0-9a-f]{1,2}&quot;, options: .caseInsensitive) regex.enumerateMatches(in: self, range: NSRange(startIndex..., in: self)) { match, _, _ in let byteString = (self as NSString).substring(with: match!.range) let num = UInt8(byteString, radix: 16)! data.append(num) } guard data.count &gt; 0 else { return nil } return data } } </code></pre> <p>And for the sake of completeness, this is my <code>Data</code> to hex string routine:</p> <pre><code>extension Data { /// Hexadecimal string representation of `Data` object. var hexadecimal: String { return map { String(format: &quot;%02x&quot;, $0) } .joined() } } </code></pre> <hr /> <p>Note, as shown in the above, I generally only convert between hexadecimal representations and <code>NSData</code> instances (because if the information could have been represented as a string you probably wouldn't have created a hexadecimal representation in the first place). But your original question wanted to convert between hexadecimal representations and <code>String</code> objects, and that might look like so:</p> <pre><code>extension String { /// Create `String` representation of `Data` created from hexadecimal string representation /// /// This takes a hexadecimal representation and creates a String object from that. Note, if the string has any spaces, those are removed. Also if the string started with a `&lt;` or ended with a `&gt;`, those are removed, too. /// /// For example, /// /// String(hexadecimal: &quot;&lt;666f6f&gt;&quot;) /// /// is /// /// Optional(&quot;foo&quot;) /// /// - returns: `String` represented by this hexadecimal string. init?(hexadecimal string: String, encoding: String.Encoding = .utf8) { guard let data = string.hexadecimal() else { return nil } self.init(data: data, encoding: encoding) } /// Create hexadecimal string representation of `String` object. /// /// For example, /// /// &quot;foo&quot;.hexadecimalString() /// /// is /// /// Optional(&quot;666f6f&quot;) /// /// - parameter encoding: The `String.Encoding` that indicates how the string should be converted to `Data` before performing the hexadecimal conversion. /// /// - returns: `String` representation of this String object. func hexadecimalString(encoding: String.Encoding = .utf8) -&gt; String? { return data(using: encoding)? .hexadecimal } } </code></pre> <p>You could then use the above like so:</p> <pre><code>let hexString = &quot;68656c6c 6f2c2077 6f726c64&quot; print(String(hexadecimal: hexString)) </code></pre> <p>Or,</p> <pre><code>let originalString = &quot;hello, world&quot; print(originalString.hexadecimalString()) </code></pre> <p>For permutations of the above for earlier Swift versions, see the revision history of this question.</p>
43,804,032
Open Url in default web browser
<p>I am new in react-native and i want to open <strong>url</strong> in <strong>default browser like Chrome in Android and iPhone</strong> both.</p> <p>We open url via intent in Android same like functionality i want to achieve.</p> <p>I have search many times but it will give me the result of <em>Deepklinking</em>.</p>
43,804,295
4
0
null
2017-05-05 11:39:36.693 UTC
14
2022-07-20 13:26:07.82 UTC
2018-10-23 18:55:27.83 UTC
null
5,481,342
null
4,951,663
null
1
135
android|ios|react-native
184,644
<p>You should use <a href="https://reactnative.dev/docs/linking" rel="noreferrer"><code>Linking</code></a>.</p> <p>Example from the docs:</p> <pre><code>class OpenURLButton extends React.Component { static propTypes = { url: React.PropTypes.string }; handleClick = () =&gt; { Linking.canOpenURL(this.props.url).then(supported =&gt; { if (supported) { Linking.openURL(this.props.url); } else { console.log(&quot;Don't know how to open URI: &quot; + this.props.url); } }); }; render() { return ( &lt;TouchableOpacity onPress={this.handleClick}&gt; {&quot; &quot;} &lt;View style={styles.button}&gt; {&quot; &quot;}&lt;Text style={styles.text}&gt;Open {this.props.url}&lt;/Text&gt;{&quot; &quot;} &lt;/View&gt; {&quot; &quot;} &lt;/TouchableOpacity&gt; ); } } </code></pre> <p>Here's an example you can try on <a href="https://snack.expo.io/rJm_YkqyW" rel="noreferrer">Expo Snack</a>:</p> <pre><code>import React, { Component } from 'react'; import { View, StyleSheet, Button, Linking } from 'react-native'; import { Constants } from 'expo'; export default class App extends Component { render() { return ( &lt;View style={styles.container}&gt; &lt;Button title=&quot;Click me&quot; onPress={ ()=&gt;{ Linking.openURL('https://google.com')}} /&gt; &lt;/View&gt; ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', }, }); </code></pre>
49,535,920
Count and group by Power BI
<p>I am beginner at Power BI and I'm trying to group my data by "Opp title" and count the number of rows of dates: </p> <p><img src="https://i.stack.imgur.com/jHpfe.png" alt="Click here"></p> <p>The result will be :</p> <p><img src="https://i.stack.imgur.com/ML2dL.png" alt="Click here"></p>
49,537,042
2
0
null
2018-03-28 13:30:30.147 UTC
5
2019-11-28 11:10:52.78 UTC
2018-03-28 14:53:47.113 UTC
null
765,226
null
9,517,769
null
1
6
group-by|count|powerbi
64,223
<p>Step 1. Select the table visual where your data is located in the Report Pane.</p> <p>Step 2. In the Visualizations Pane, right click on the date Value in the Values area (not Filters area) and select <code>Date</code> instead of <code>Date Hierarchy</code>.</p> <p>Step 3. In the Visualization Pane, right click on the date Value (same place) and instead of <code>Don't Summarize</code> select <code>Count</code>.</p>
31,742,047
How to add a spinner while loading the content in AngularJS?
<p>I am using button spinner while loading the content, when the user clicks on the "Search" button content will load, at this time <code>buttonLabel</code> will be changed to "Searching" and spinner will be shown (Here button will be disabled). After loading the content (Promise resolved) <code>buttonLabel</code> will be reverted back to "Search" (button will be enable here).</p> <p>I have tried the below code, but it is always showing the spinner.</p> <p><strong>HTML :</strong></p> <pre><code>&lt;button class="btn btn-xs btn btn-blue" ng-click="show()"&gt; &lt;span&gt;&lt;i class="glyphicon glyphicon-off"&gt;&lt;/i&gt;&lt;/span&gt; {{buttonLabel}} &lt;/button&gt; </code></pre> <p><strong>Script :</strong></p> <pre><code>$scope.buttonLabel = "Search"; $scope.show = function() { $scope.buttonLabel = "Searching"; $scope.test = TestService.getList( $cookieStore.get('url'), $rootScope.resourceName+"/students" ); $scope.test.then( function( data ) { if( data.list ) { $scope.testData = data.list; $scope.buttonLabel = "Search"; } } } </code></pre> <p><strong>Updated Fiddle :</strong> <a href="http://jsfiddle.net/xc6nx235/18/" rel="nofollow noreferrer">http://jsfiddle.net/xc6nx235/18/</a></p>
31,742,426
7
0
null
2015-07-31 08:55:11.837 UTC
3
2018-10-08 04:35:22.84 UTC
2018-10-08 04:35:22.84 UTC
null
608,639
null
3,438,128
null
1
12
javascript|angularjs|twitter-bootstrap
64,664
<pre><code>&lt;div ng-app="formDemo" ng-controller="LocationFormCtrl"&gt; &lt;div&gt; &lt;button type="submit" class="btn btn-primary" ng-click="search()"&gt; &lt;span ng-show="searchButtonText == 'Searching'"&gt;&lt;i class="glyphicon glyphicon-refresh spinning"&gt;&lt;/i&gt;&lt;/span&gt; {{ searchButtonText }} &lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <p>All you need to do is use <code>ng-show</code> or <code>ng-hide</code> directives.</p> <p><strong>ng-show="expression"</strong></p> <pre><code>&lt;span ng-show="searchButtonText == 'Searching'"&gt; &lt;i class="glyphicon glyphicon-refresh spinning"&gt;&lt;/i&gt; &lt;/span&gt; </code></pre> <p>this span will only be visible when <code>searchButtonText</code> will be equal to a string 'Searching'.</p> <p>You should learn more about angular's directives. They'll be useful in future.</p> <p>Good luck.</p> <p>Demo <a href="http://jsfiddle.net/xc6nx235/16/" rel="noreferrer">http://jsfiddle.net/xc6nx235/16/</a></p>
32,046,550
NSDate set timezone in swift
<p>how can i return a NSDate in a predefined time zone from a string</p> <pre><code>let responseString = "2015-8-17 GMT+05:30" var dFormatter = NSDateFormatter() dFormatter.dateFormat = "yyyy-M-dd ZZZZ" var serverTime = dFormatter.dateFromString(responseString) println("NSDate : \(serverTime!)") </code></pre> <p>the above code returns the time as</p> <pre><code>2015-08-16 18:30:00 +0000 </code></pre>
32,047,102
5
0
null
2015-08-17 09:09:19.93 UTC
3
2020-09-27 18:58:57.07 UTC
null
null
null
null
5,042,696
null
1
13
swift|nsdate
59,292
<blockquote> <p>how can i return a NSDate in a predefined time zone?</p> </blockquote> <p>You can't.</p> <p>An instance of <code>NSDate</code> does not carry any information about timezone or calendar. It just simply identifies one point in universal time.</p> <p>You can interpret this <code>NSDate</code> object in whatever calendar you want. Swift's string interpolation (the last line of your example code) uses an <code>NSDateFormatter</code> that uses UTC (that's the "+0000" in the output).</p> <p>If you want the <code>NSDate</code>'s value as a string in the current user's calendar you have to explicitly set up a date formatter for that.</p>
51,192,925
Angular : how to call finally() with RXJS 6
<p>I was using RXJS 5, now as I upgraded it to 6, I am facing some problems.</p> <p>Previously I was able to use catch and finally but as per update catch is replaced with catchError (with in the pipe) now how to use finally?</p> <p>Also I have some questions :</p> <p>Do I need to change throw->throwError (in below code Observable.throw(err);)</p> <pre><code>import { Observable, Subject, EMPTY, throwError } from "rxjs"; import { catchError } from 'rxjs/operators'; return next.handle(clonedreq).pipe( catchError((err: HttpErrorResponse) =&gt; { if ((err.status == 400) || (err.status == 401)) { this.interceptorRedirectService.getInterceptedSource().next(err.status); return Observable.empty(); } else { return Observable.throw(err); } }) //, finally(() =&gt; { // this.globalEventsManager.showLoader.emit(false); //}); ); </code></pre> <p>Also how to use publish().refCount() now ?</p>
51,193,046
3
0
null
2018-07-05 13:43:58.253 UTC
6
2019-05-31 10:16:48.683 UTC
null
null
null
null
9,870,625
null
1
34
angular|rxjs|angular6|rxjs6
28,560
<ul> <li><p>use <code>throwError</code> instead of <code>Observable.throw</code>, see <a href="https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes" rel="noreferrer">https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes</a></p></li> <li><p><code>finally</code> was renamed to <code>finalize</code> and you'll use it inside <code>pipe()</code> among other operators.</p></li> <li><p>the same with <code>publish()</code> and <code>refCount()</code>. Both are operators you'll use inside <code>pipe()</code>.</p></li> </ul>
62,305,912
Shortcuts not working after updating to Android studio 4, in Mac?
<p>After updating to Android Studio 4 from AS 3.5, as a Mac user I found out none of the default shortcuts work properly, i.e <code>cmd+shift+F</code> does not open <code>search everywhere dialog</code> anymore? </p>
62,305,913
3
0
null
2020-06-10 14:21:04.66 UTC
2
2022-04-29 03:44:42.893 UTC
null
null
null
null
4,173,238
null
1
52
android|shortcut|android-studio-4.0|android-shortcut|keymaps
10,921
<p>To fix : in Android studio, from top menu tap on <code>Android studio</code> then <code>Preferences...</code> and type <code>keymap</code> then in the drop-down on the right screen select <code>Mac</code> and <code>apply</code>. </p> <p>all sorted now, all the shortcuts are aligned with the Mac keyboard. <a href="https://i.stack.imgur.com/ZPSya.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZPSya.png" alt="enter image description here"></a></p>
28,339,469
Which one should i use? docker kill or docker stop?
<p>Will <code>docker stop</code> fail if processes running inside the container fail to stop?? If i use <code>docker kill</code>, can unsaved data inside the container be preserved. Is <code>docker stop</code> time consuming compared to <code>docker kill</code>?? I want to do a shutdown of the container but without loosing any data(without high latency to complete kill or stop process).</p>
28,339,555
4
0
null
2015-02-05 08:37:47.75 UTC
6
2021-10-08 17:40:01.06 UTC
null
null
null
null
3,409,405
null
1
29
docker
20,617
<blockquote> <p>Line reference:</p> <p><code>docker stop</code>: Stop a running container (send SIGTERM, and then SIGKILL after grace period) [...] The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL. [emphasis mine]</p> <p><code>docker kill</code>: Kill a running container (send SIGKILL, or specified signal) [...] The main process inside the container will be sent SIGKILL, or any signal specified with option --signal. [emphasis mine]</p> </blockquote> <p>You can get more info from this post: <a href="https://superuser.com/questions/756999/whats-the-difference-between-docker-stop-and-docker-kill">https://superuser.com/questions/756999/whats-the-difference-between-docker-stop-and-docker-kill</a></p>
42,616,376
Install Pandas on Mac with pip
<p>I am trying to install <code>Pandas</code> with <code>pip</code>, but ran into to a problem. Here are the details:</p> <pre><code>Mac OS Sierra which python =&gt; /usr/bin/python python --version =&gt; Python 2.7.10 Inside "/System/Library/Frameworks/Python.framework/Versions" there is the following 2.3 2.5 2.6 2.7 Current </code></pre> <p><strong>I want pandas to be linked to <code>Python 2.7.10</code> in "/usr/bin/python"</strong> </p> <p>When I do <code>pip install pandas</code>, I get the following error message: </p> <pre><code>Collecting pandas Using cached pandas-0.19.2-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Requirement already satisfied: pytz&gt;=2011k in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas) Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas) Requirement already satisfied: numpy&gt;=1.7.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from pandas) Installing collected packages: pandas Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1- py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pandas' </code></pre> <p>Thanks for helping.</p>
42,616,942
6
4
null
2017-03-06 01:57:13.6 UTC
1
2021-12-25 17:26:00.723 UTC
2017-03-06 05:57:45.287 UTC
null
6,918,812
null
5,273,308
null
1
5
python|macos|pandas|pip
40,949
<p>Try running the pip install command as sudo. </p> <pre><code>sudo pip install pandas </code></pre> <p>Python packages are installed in the operating systems file system where not all users have permission to write files to. This is why you need to run the command as sudo, as sudo elevates your privileges to do this. </p> <p>Edit: This seems to be getting some upvotes so I've added some clarity to this question regarding user specific installation. You can also install this just for your user should this fit your use case with: <code>pip install --user pandas</code>.</p>
25,716,920
What does "CL" mean in a commit message? What does it stand for?
<p>From Angular.js change log:</p> <blockquote> <p>... After this CL, ng-trim no longer affects input[type=password], and will never trim the password value.</p> </blockquote> <p>This is from one of the commit messages, so presumably it means the patch. What does it stand for? Change log? </p>
27,520,705
3
0
null
2014-09-08 03:05:15.09 UTC
3
2020-03-11 11:43:51.203 UTC
2020-02-17 21:43:08.413 UTC
null
1,993,391
null
1,993,391
null
1
42
angularjs|terminology
26,879
<p>It means <em>Change List</em>.</p> <blockquote> <p>Create a change list (CL)</p> <p>Creating a change in git is really just creating a branch.</p> </blockquote> <p><a href="http://www.chromium.org/developers/contributing-code" rel="noreferrer">http://www.chromium.org/developers/contributing-code</a></p> <p>And the code review system there are using: <a href="https://code.google.com/p/rietveld/" rel="noreferrer">https://code.google.com/p/rietveld/</a></p>
30,345,446
how to trigger a function on window close using angularjs
<p>I need to execute a function when the user closes the application, but the following points need to be considered :</p> <ul> <li>I need to execute a function of one <code>service</code>, then...</li> <li>... an out-scoped pure-javascript based function is not likely to be useful here</li> <li>As I am using routes, a scoped <code>onLocationChangeSuccess</code> binding is useless as well</li> </ul> <p>therefore this solution is not going to work : <a href="https://stackoverflow.com/a/18355715/773595">https://stackoverflow.com/a/18355715/773595</a></p> <p>Because this will be triggered everytime the location change, but what I need is only one trigger when the tab/window is closed.</p>
30,345,961
3
1
null
2015-05-20 09:20:48.217 UTC
7
2016-01-25 12:16:01.383 UTC
2017-05-23 11:53:20.017 UTC
null
-1
null
773,595
null
1
12
javascript|angularjs|events
54,480
<p>You can register an onbeforeunload in your controller/directive then you'll have access to the scope. In case of a service i'd register it in the angular.run lifecycle.</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>angular.module('app', []) .controller('exitController', function($scope, $window) { $scope.onExit = function() { return ('bye bye'); }; $window.onbeforeunload = $scope.onExit; });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app" ng-controller="exitController"&gt; &lt;a href="http://www.disney.com"&gt;Leave page&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
20,618,570
Python logging.Formatter(): is there any way to fix the width of a field and justify it left/right?
<p>Here's a sample of log records from the logging tutorial:</p> <pre><code>2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message </code></pre> <p>This trailing jaggedness annoys me to no end.</p> <p>I really want to be able to format like this:</p> <pre><code>2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message 2005-03-19 15:38:55,979 - simpleExample - INFO - info message 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message </code></pre> <p>I've attempted the following for my logger, which doesn't work (abbreviated code):</p> <pre><code>fmt = "{0:&gt;8}" formatter = logging.Formatter("%(asctime)s %(filename)s: " + fmt.format("%(levelname)s") + " %(message)s", "%Y/%m/%d %H:%M:%S") </code></pre> <p>This executes fine and prints the level name as always, but it doesn't implement the width format.</p> <p>Ex.</p> <pre><code>logger.debug("testing debug message") logger.info("some random info") logger.critical("oh crap!") </code></pre> <p><strong>Actual result:</strong></p> <pre><code>2013/12/16 13:43:10 logtester: DEBUG testing debug message 2013/12/16 13:43:10 logtester: INFO some random info 2013/12/16 13:43:10 logtester: CRITICAL oh crap! </code></pre> <p><strong>Desired result:</strong></p> <pre><code>2013/12/16 13:43:10 logtester: DEBUG testing debug message 2013/12/16 13:43:10 logtester: INFO some random info 2013/12/16 13:43:10 logtester: CRITICAL oh crap! </code></pre> <p>Any hints to implement a fixed width of a field in a logging.Formatter()?</p> <p>Using Python 2.6.9.</p> <p><strong>EDIT</strong>: second attempt using another method:</p> <pre><code>formatter = logging.Formatter("%(asctime)s %(filename)s: " + "%(foo)5s" % {"foo" : "(%(levelname)s)"} + " %(message)s", "%Y/%m/%d %H:%M:%S") </code></pre> <p>Still results in:</p> <pre><code>2013/12/16 13:43:10 logtester: DEBUG testing debug message 2013/12/16 13:43:10 logtester: INFO some random info 2013/12/16 13:43:10 logtester: CRITICAL oh crap! </code></pre> <p>Maybe I'm just doing something boneheaded.</p>
20,618,659
2
1
null
2013-12-16 18:53:25.183 UTC
2
2021-10-19 12:30:22.46 UTC
2013-12-16 19:07:20.813 UTC
null
1,044,866
null
1,044,866
null
1
36
python|logging|formatting
12,476
<p>Field width can be specified by adding a number in front of the type specifier:</p> <pre><code>&gt;&gt;&gt; "%(foo)8s" % {'foo': 'bar'} ' bar' </code></pre> <p>You can use this in your format string passed to the formatter. For your example, that'd be:</p> <pre><code>"%(asctime)s %(filename)s: %(levelname)8s %(message)s" </code></pre>
29,685,705
Permanent and persistent Socket connection in java
<p>I've created a client-server connection, something like a chat system. Previously I was using a <code>while</code> loop on the client side, and it was waiting to read a message from the console every time (of course server has a <code>while</code> loop as well to serve forever). But now, I'm trying to first create a connection at the beginning of the session, and then occasionally send a message during the session, so to maintain a permanent and persistent connection.</p> <p>Currently, without the <code>while</code> loop, the client closes the connection and I don't know how to find a workaround. </p> <p>Here is the client code:</p> <pre><code>import java.net.*; import java.io.*; public class ControlClientTest { private Socket socket = null; // private BufferedReader console = null; private DataOutputStream streamOut = null; public static void main(String args[]) throws InterruptedException { ControlClientTest client = null; String IP="127.0.0.1"; client = new ControlClientTest(IP, 5555); } public ControlClientTest(String serverName, int serverPort) throws InterruptedException { System.out.println("Establishing connection. Please wait ..."); try { socket = new Socket(serverName, serverPort); System.out.println("Connected: " + socket); start(); } catch (UnknownHostException uhe) { System.out.println("Host unknown: " + uhe.getMessage()); } catch (IOException ioe) { System.out.println("Unexpected exception: " + ioe.getMessage()); } String line = ""; // while (!line.equals(".bye")) { try { Thread.sleep(1000); //TODO get data from input // line = console.readLine(); line="1"; if(line.equals("1")) line="1,123"; streamOut.writeUTF(line); streamOut.flush(); } catch (IOException ioe) { System.out.println("Sending error: " + ioe.getMessage()); } // } } public void start() throws IOException { // console = new BufferedReader(new InputStreamReader(System.in)); streamOut = new DataOutputStream(socket.getOutputStream()); } } </code></pre> <p>And here is the Server code:</p> <pre><code>import java.awt.*; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class ControlServer { private Socket socket = null; private ServerSocket server = null; private DataInputStream streamIn = null; public static void main(String args[]) { ControlServer server = null; server = new ControlServer(5555); } public ControlServer(int port) { try { System.out .println("Binding to port " + port + ", please wait ..."); server = new ServerSocket(port); System.out.println("Server started: " + server); System.out.println("Waiting for a client ..."); socket = server.accept(); System.out.println("Client accepted: " + socket); open(); boolean done = false; while (!done) { try { String line = streamIn.readUTF(); // TODO get the data and do something System.out.println(line); done = line.equals(".bye"); } catch (IOException ioe) { done = true; } } close(); } catch (IOException ioe) { System.out.println(ioe); } } public void open() throws IOException { streamIn = new DataInputStream(new BufferedInputStream( socket.getInputStream())); } public void close() throws IOException { if (socket != null) socket.close(); if (streamIn != null) streamIn.close(); } } </code></pre>
29,714,530
3
1
null
2015-04-16 20:51:57.147 UTC
10
2016-12-02 12:09:04.557 UTC
2015-11-11 19:45:57.753 UTC
null
1,015,495
user1196937
null
null
1
6
java|sockets
17,546
<p>I would like to summarize some good practices regarding the stability of TCP/IP connections which I apply on a daily basis.</p> <h1>Good practice 1 : Built-in Keep-Alive</h1> <pre><code>socket.setKeepAlive(true); </code></pre> <p>It automatically sends a signal after a period of inactivity and checks for a reply. The keep-alive interval is operating system dependent though, and has some shortcomings. But all by all, it could improve the stability of your connection.</p> <h1>Good practice 2 : SoTimeout</h1> <p>Whenver you perform a <code>read</code> (or <code>readUTF</code> in your case), your thread will actually block forever. In my experience this is bad practice for the following reasons: It's difficult to close your application. Just calling <code>socket.close()</code> is dirty. </p> <p>A clean solution, is a simple read time-out (e.g. 200ms). You can do this with the <code>setSoTimeout</code>method. When the <code>read()</code> method timeouts it will throw a <code>SocketTimeoutException</code>. (which is a subclass of <code>IOException</code>).</p> <pre><code>socket.setSoTimeout(timeoutInterval); </code></pre> <p>Here is an example to implement the loop. Please note the <code>shutdown</code> condition. Just set it to true, and your thread will die peacefully.</p> <pre><code>while (!shutdown) { try { // some method that calls your read and parses the message. code = readData(); if (code == null) continue; } catch (SocketTimeoutException ste) { // A SocketTimeoutExc. is a simple read timeout, just ignore it. // other IOExceptions will not be stopped here. } } </code></pre> <h1>Good practice 3 : Tcp No-Delay</h1> <p>Use the following setting when you are often interfacing small commands that need to be handled quickly.</p> <pre><code>try { socket.setTcpNoDelay(true); } catch (SocketException e) { } </code></pre> <h1>Good practice 4 : A heartbeat</h1> <p>Actually there are a lot of side scenario's that are not covered yet. </p> <p>One of them for example are server applications that are designed to only communicate with 1 client at a time. Sometimes they accept connections and even accept messages, but never reply to them.</p> <p>Another one: sometimes when you lose your connection it actually can take a long time before your OS notices this. Possibly due to the shortcomings described in <em>good practice 3</em>, but also in more complex network situations (e.g. using RS232-To-Ethernet converters, VMware servers, etc) this happens often.</p> <p>The solution here is to create a thread that sends a message every x seconds and then waits for a reply. (e.g. every 15 seconds). For this you need to create a second thread that just sends a message every 15 seconds. Secondly, you need to expand the code of <em>good practice 2</em> a little bit.</p> <pre><code> try { code = readData(); if (code == null) continue; lastRead = System.currentTimeMillis(); // whenever you receive the heart beat reply, just ignore it. if (MSG_HEARTBEAT.equals(code)) continue; // todo: handle other messages } catch (SocketTimeoutException ste) { // in a typical situation the soTimeout is about 200ms // the heartbeat interval is usually a couple of seconds. // and the heartbeat timeout interval a couple of seconds more. if ((heartbeatTimeoutInterval &gt; 0) &amp;&amp; ((System.currentTimeMillis() - lastRead) &gt; heartbeatTimeoutInterval)) { // no reply to heartbeat received. // end the loop and perform a reconnect. break; } } </code></pre> <p>You need to decide if your client or server should send the message. That decision is not so important. But e.g. if your client sends the message, then your client will need an additional thread to send the message. Your server should send a reply when it receives the message. When your client receives the answer, it should just <code>continue</code> (i.e. see code above). And both parties should check: "how long has it been?" in a very similar way.</p>
29,565,043
How to specify "own type" as return type in Kotlin
<p>Is there a way to specify the return type of a function to be the type of the called object?</p> <p>e.g.</p> <pre><code>trait Foo { fun bar(): &lt;??&gt; /* what to put here? */ { return this } } class FooClassA : Foo { fun a() {} } class FooClassB : Foo { fun b() {} } // this is the desired effect: val a = FooClassA().bar() // should be of type FooClassA a.a() // so this would work val b = FooClassB().bar() // should be of type FooClassB b.b() // so this would work </code></pre> <p>In effect, this would be roughly equivalent to <code>instancetype</code> in Objective-C or <code>Self</code> in Swift.</p>
29,566,159
6
1
null
2015-04-10 15:17:59.267 UTC
8
2021-07-22 00:40:52.017 UTC
null
null
null
null
188,461
null
1
34
kotlin
9,135
<p>There's no language feature supporting this, but you can always use recursive generics (which is the pattern many libraries use):</p> <pre><code>// Define a recursive generic parameter Me trait Foo&lt;Me: Foo&lt;Me&gt;&gt; { fun bar(): Me { // Here we have to cast, because the compiler does not know that Me is the same as this class return this as Me } } // In subclasses, pass itself to the superclass as an argument: class FooClassA : Foo&lt;FooClassA&gt; { fun a() {} } class FooClassB : Foo&lt;FooClassB&gt; { fun b() {} } </code></pre>
36,274,626
Javascript - Remove '\n' from string
<pre><code>var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n' </code></pre> <p>I am trying to sanitize a string by stripping out the <code>\n</code> but when I do <code>.replace(/\\\n/g, '')</code> it doesn't seem to catch it. I also Google searched and found:</p> <blockquote> <p>..in accordance with JavaScript regular expression syntax you need two backslash characters in your regular expression literals such as <code>/\\/</code> or <code>/\\/g</code>.</p> </blockquote> <p>But even when I test the expression just to catch backslash, it returns false: <code>(/\\\/g).test(strObj)</code></p> <p>RegEx tester captures <code>\n</code> correctly: <a href="http://regexr.com/3d3pe" rel="noreferrer">http://regexr.com/3d3pe</a></p>
36,274,681
3
2
null
2016-03-29 03:02:25.957 UTC
6
2016-03-29 06:16:34.337 UTC
2016-03-29 03:26:06.433 UTC
null
20,938
null
1,166,521
null
1
22
javascript|regex
65,016
<p>Should just be</p> <pre><code>.replace(/\n/g, '') </code></pre> <p>unless the string is actually </p> <pre><code>'\\n\\n\\n... </code></pre> <p>that it would be</p> <pre><code>.replace(/\\n/g, '') </code></pre>
13,860,490
Show data in ASP.NET html table
<p>I am writing an ASP.NET page which reads data from a database and needs to show it in a table. For some reason, I don't want to use the gridView. </p> <p><strong>How do I show the data in a table on the HTML page?</strong></p> <p>This is my C# code:</p> <pre><code> SqlConnection thisConnection = new SqlConnection(dbConnection); SqlCommand thisCommand = thisConnection.CreateCommand(); thisCommand.CommandText = "SELECT * from Test"; thisConnection.Open(); SqlDataReader reader = thisCommand.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string Name = reader.GetString(1); string Pass = reader.GetString(2); } thisConnection.Close(); </code></pre> <p>This is my ASPX page:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/test.master" CodeFile="test.aspx.cs" Inherits="test" %&gt; &lt;asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ContentPlaceHolder"&gt; &lt;table width="100%" align="center" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA" &gt; &lt;tr align="left" style="background-color:#004080;color:White;" &gt; &lt;td&gt; ID &lt;/td&gt; &lt;td&gt; Name &lt;/td&gt; &lt;td&gt;Pass&lt;/td&gt; &lt;/tr&gt; **&lt;%--Need the while output into here--%&gt;** &lt;/table&gt; &lt;/asp:Content&gt; </code></pre>
13,860,556
5
1
null
2012-12-13 13:06:15.82 UTC
3
2019-01-20 18:37:16.94 UTC
2012-12-13 14:42:53.183 UTC
null
87,238
null
87,238
null
1
6
c#|asp.net|html
48,028
<p>Basically use the classic ASP\PHP\Spaghetti code approach.</p> <p>First of all, place your code in one public method that returns a <code>string</code>. The method:</p> <pre><code>public string getWhileLoopData() { string htmlStr = ""; SqlConnection thisConnection = new SqlConnection(dbConnection); SqlCommand thisCommand = thisConnection.CreateCommand(); thisCommand.CommandText = "SELECT * from Test"; thisConnection.Open(); SqlDataReader reader = thisCommand.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string Name = reader.GetString(1); string Pass = reader.GetString(2); htmlStr +="&lt;tr&gt;&lt;td&gt;"+id+"&lt;/td&gt;&lt;td&gt;"+Name+"&lt;/td&gt;&lt;td&gt;"+Pass+"&lt;/td&gt;&lt;/tr&gt;" } thisConnection.Close(); return htmlStr; } </code></pre> <p>Then you can use the <code>&lt;%=getWhileLoopData()%&gt;</code> tag in ASP.NET that is equal to <code>&lt;%Response.Write(getWhileData())%&gt;</code></p> <p>It should look something like this:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/test.master" CodeFile="test.aspx.cs" Inherits="test" %&gt; &lt;asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ContentPlaceHolder"&gt; &lt;table width="100%" align="center" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA" &gt; &lt;tr align="left" style="background-color:#004080;color:White;" &gt; &lt;td&gt; ID &lt;/td&gt; &lt;td&gt; Name &lt;/td&gt; &lt;td&gt;Pass&lt;/td&gt; &lt;/tr&gt; &lt;%=getWhileLoopData()%&gt; &lt;/table&gt; &lt;/asp:Content&gt; </code></pre> <p>There is also the option to use an repeater control and bind the data from your DB to an Item Template of your liking.</p>