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
3,250,749
Using Windows Python from Cygwin
<p>I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using <code>/cygdrive/c/Python26/python.exe myfile.py</code> rather than <code>python myfile.exe</code>.</p> <p>This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't print until execution finishes. It works fine running in Windows Python from explorer.exe or cmd.exe, and it works in Cygwin using the Cygwin-installed Python (<code>/bin/python.exe</code>).</p> <p>Is there a workaround for this? The important thing is to be able to run the Windows version, but I'd like to do it all from with Bash.</p>
3,250,975
3
2
null
2010-07-14 21:38:54.853 UTC
28
2012-09-04 13:08:37.65 UTC
null
null
null
null
49,376
null
1
63
python|windows|cygwin
78,875
<p>Perhaps if you flush the output</p> <pre><code>import sys V = range(100000) for x in V: print x sys.stdout.flush() </code></pre>
20,470,874
How do you "rollback" last commit on Mercurial?
<p>I have a Mercurial repository that I use in local only... It's for my personal usage (so I don't "push" anywhere).</p> <p>I made a commit with 3 files, but after that I understood that I should do commit 4 files...</p> <p>Is there a way to "rollback" my <strong>last</strong> (latest, only one) commit, and "recommit" it with the correct files?</p> <p>(I don't know why, but my "<em>Amend current revision</em>" option is not active, so I can't use it...)</p>
20,471,145
3
4
null
2013-12-09 12:37:24.51 UTC
10
2018-05-08 22:41:09.81 UTC
2015-12-14 12:12:34.207 UTC
null
74,694
null
185,593
null
1
72
mercurial|commit|rollback
106,568
<p>You just need this command:</p> <pre><code>hg rollback </code></pre> <p>See: <a href="http://hgbook.red-bean.com/read/finding-and-fixing-mistakes.html" rel="noreferrer">http://hgbook.red-bean.com/read/finding-and-fixing-mistakes.html</a>.</p> <p>(Technically, this is deprecated as of version 2.7, August 2013, but I've yet to see an alternative that does exactly the same thing.)</p>
11,264,470
How to POST content with an HTTP Request (Perl)
<pre><code>use LWP::UserAgent; use Data::Dumper; my $ua = new LWP::UserAgent; $ua-&gt;agent("AgentName/0.1 " . $ua-&gt;agent); my $req = new HTTP::Request POST =&gt; 'http://example.com'; $req-&gt;content('port=8', 'target=64'); #problem my $res = $ua-&gt;request($req); print Dumper($res-&gt;content); </code></pre> <p>How can I send multiple pieces of content using $req->content? What kind of data does $req->content expect?</p> <p>It only sends the last one.</p> <p>Edit:</p> <p>Found out if i format it like 'port=8&amp;target=64' it works. Is there a better way?</p>
11,264,534
3
0
null
2012-06-29 15:19:45.373 UTC
5
2021-06-21 18:20:45.273 UTC
2018-05-21 17:12:55.88 UTC
null
622,310
null
937,922
null
1
12
perl|http|lwp
47,557
<pre><code>my $ua = LWP::UserAgent-&gt;new(); my $request = POST( $url, [ 'port' =&gt; 8, 'target' =&gt; 64 ] ); my $content = $ua-&gt;request($request)-&gt;as_string(); </code></pre>
10,903,100
Using the remote function of jquery validation
<p>I'm trying to figure out how I can turn this:</p> <pre><code>$('#username').blur(function(){ $.post('register/isUsernameAvailable', {"username":$('#username').val()}, function(data){ if(data.username == "found"){ alert('username already in use'); } }, 'json'); }); </code></pre> <p>into something close to this:</p> <pre><code>rules: { username: { minlength: 6, maxlength: 12, remote: { url: 'register/isUsernameAvailable', type: 'post', data: { 'username': $('#username').val() } } } </code></pre> <p>However I'm having a hard time finishing it off. What I want is instead of the alert to have it display the error message but I can set the message inside the actual jquery validation messages.</p> <p><a href="http://docs.jquery.com/Plugins/Validation/Methods/remote#options" rel="noreferrer">http://docs.jquery.com/Plugins/Validation/Methods/remote#options</a></p> <p><strong>UPDATE:</strong> </p> <p>For some reason its not doing it as a POST its doing it as a GET request and not sure why. Here's the updated code:</p> <pre><code>rules: { username: { minlength: 6, maxlength: 12, remote: { url: 'register/isUsernameAvailable', dataType: 'post', data: { 'username': $('#username').val() }, success: function(data) { if (data.username == 'found') { message: { username: 'The username is already in use!' } } } } }, </code></pre> <p><strong>UPDATE 2:</strong></p> <p>Now I'm getting somewhere I'm back to getting the POST request. I'm getting two more problems. One of which is the fact that for another POST request to be done the user has to refresh the form. And the last problem is that if the returned username is found it DOES NOT show the error message.</p> <pre><code>rules: { username: { minlength: 6, maxlength: 12, remote: { type: 'post', url: 'register/isUsernameAvailable', data: { 'username': $('#username').val() }, dataType: 'json', success: function(data) { if (data.username == 'found') { message: { username: 'The username is already in use!' } } } } }, </code></pre> <p><strong>UPDATE:</strong> </p> <pre><code>public function isUsernameAvailable() { if ($this-&gt;usersmodel-&gt;isUsernameAvailable($this-&gt;input-&gt;post('username'))) { return false; } else { return true; } } </code></pre> <p><strong>UPDATE 4:</strong></p> <p>Controller:</p> <pre><code>public function isUsernameAvailable() { if ($this-&gt;usersmodel-&gt;isUsernameAvailable($this-&gt;input-&gt;post('username'))) { return false; } else { return true; } } public function isEmailAvailable() { if ($this-&gt;usersmodel-&gt;isEmailAvailable($this-&gt;input-&gt;post('emailAddress'))) { return false; } else { return true; } } </code></pre> <p>MODEL:</p> <pre><code>/** * Check if username available for registering * * @param string * @return bool */ function isUsernameAvailable($username) { $this-&gt;db-&gt;select('username'); $this-&gt;db-&gt;where('LOWER(username)=', strtolower($username)); $query = $this-&gt;db-&gt;get($this-&gt;usersTable); if ($query-&gt;num_rows() == 0) { return true; } else { return false; } } /** * Check if email available for registering * * @param string * @return bool */ function isEmailAvailable($email) { $this-&gt;db-&gt;select('email'); $this-&gt;db-&gt;where('LOWER(email)=', strtolower($email)); $query = $this-&gt;db-&gt;get($this-&gt;usersTable); if($query-&gt;num_rows() == 0) { return true; } else { return false; } } </code></pre>
10,903,307
8
6
null
2012-06-05 18:49:26.447 UTC
5
2020-05-29 08:24:31.837 UTC
2012-06-05 23:42:03.053 UTC
null
1,244,239
null
1,244,239
null
1
12
jquery|jquery-validate
74,212
<p>Well I dunno bout your plugin concept specifically but I gather you want it to check to see with that plugin if the username is greater than 6 or less than 12. Which from your core example with jQuery without the plugin it would be as simple as adding one little if-else to the concept. </p> <pre><code>$('#username').blur(function(){ if($('#username').val().length &lt; 6 || $('#username').val().length &gt; 12) { alert('Username must be between 6 and 12 characters'); } else { $.post('register/isUsernameAvailable', {"username":$('#username').val()}, function(data){ if(data.username == "found"){ alert('username already in use'); } }, 'json'); } }); </code></pre>
10,904,476
JS Google Maps API v3 Animate Marker Between Coordinates
<p>I have a simple javascript maps application that I'm working on that requires me to animate the movement of multiple markers between different coords. Each marker is free to move on its own and all markers are stored in an array list. However, I have been having trouble getting them to smoothly transition locations.</p> <p>I've done a ton of research and trial/error but no luck, anyone have any luck with this?</p>
10,906,464
4
0
null
2012-06-05 20:30:53.773 UTC
13
2022-07-01 09:01:59.85 UTC
null
null
null
null
1,438,300
null
1
13
javascript|google-maps|animation|google-maps-api-3|google-maps-markers
47,461
<p>My quick-and-dirty approach does not involve a ton of research :(</p> <p>Here's the demo: <a href="https://web.archive.org/web/20130814022900/http://jsfiddle.net:80/yV6xv/4/" rel="noreferrer">http://jsfiddle.net/yV6xv/4/</a> Click on a marker to begin moving it, after it stops, you can click again to go back to its initial point. Clicking while in motion gives strange results.</p> <p>Start and endpoints are predefined in <code>initialize()</code>. The animation is defined by dividing the start and endpoints into 100 segments, and placing the marker at these points with a set interval. So the animation time is fixed: markers travel longer distances "faster" than shorter distances.</p> <p>I didn't do much testing, I know clicking on a moving marker will give unexpected results (start and endpoints get misplaced)</p> <p>This is the "interesting" part of the demo:</p> <pre><code> // store a LatLng for each step of the animation frames = []; for (var percent = 0; percent &lt; 1; percent += 0.01) { curLat = fromLat + percent * (toLat - fromLat); curLng = fromLng + percent * (toLng - fromLng); frames.push(new google.maps.LatLng(curLat, curLng)); } move = function(marker, latlngs, index, wait, newDestination) { marker.setPosition(latlngs[index]); if(index != latlngs.length-1) { // call the next "frame" of the animation setTimeout(function() { move(marker, latlngs, index+1, wait, newDestination); }, wait); } else { // assign new route marker.position = marker.destination; marker.destination = newDestination; } } // begin animation, send back to origin after completion move(marker, frames, 0, 20, marker.position); </code></pre>
11,065,252
What is the point of jQuery ajax accepts attrib? Does it actually do anything?
<p>Spent a solid hour trying to sort out why on earth this (coffeescript)</p> <pre><code>$.ajax accepts: "application/json; charset=utf-8" </code></pre> <p>did <em>absolutely nothing</em> to change the accepts header, while this</p> <pre><code>$.ajax dataType: "json" </code></pre> <p>properly sets the accepts header to <code>application/json; charset=utf-8</code></p> <p>Totally confused, am I missing something or is the accepts attrib a year-round April Fool's joke?</p>
11,065,286
1
0
null
2012-06-16 16:40:57.03 UTC
5
2016-07-07 15:15:56.99 UTC
null
null
null
null
185,840
null
1
30
jquery|types|header|set|response
24,827
<p>As always the <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">documentation</a> is your friend:</p> <blockquote> <p><strong>accepts</strong></p> <p>Default: depends on DataType </p> <p>The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.</p> <p><strong>dataType</strong></p> <p>Default: Intelligent Guess (xml, json, script, or html)</p> <p>The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:</p> <p>"<strong>xml</strong>": Returns a XML document that can be processed via jQuery.</p> <p>"<strong>html</strong>": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. </p> <p>"<strong>script</strong>": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, <code>_=[TIMESTAMP]</code>, to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. </p> <p>"<strong>json</strong>": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)</p> <p>"<strong>jsonp</strong>": Loads in a JSON block using JSONP. Adds an extra <code>?callback=?</code> to the end of your URL to specify the callback. Disables caching by appending a query string parameter,<br> <code>_=[TIMESTAMP]</code>, to the URL unless the cache option is set to true. </p> <p>"<strong>text</strong>": A plain text string. multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "<strong>text xml</strong>" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.</p> </blockquote> <p>Now back to your problem. I am not familiar with cofeescript but contrary to <code>dataType</code> which is a string, the <code>accepts</code> parameter is a map and should be used like this:</p> <pre><code>$.ajax({ url: ... dataType: 'json', accepts: { xml: 'text/xml', text: 'text/plain' } }); </code></pre>
11,052,744
How to efficiently remove a query string by Key from a Url?
<p>How to remove a query string by Key from a Url?</p> <p>I have the below method which works fine but just wondering is there any better/shorter way? or a built-in .NET method which can do it more efficiently?</p> <pre><code> public static string RemoveQueryStringByKey(string url, string key) { var indexOfQuestionMark = url.IndexOf("?"); if (indexOfQuestionMark == -1) { return url; } var result = url.Substring(0, indexOfQuestionMark); var queryStrings = url.Substring(indexOfQuestionMark + 1); var queryStringParts = queryStrings.Split(new [] {'&amp;'}); var isFirstAdded = false; for (int index = 0; index &lt;queryStringParts.Length; index++) { var keyValue = queryStringParts[index].Split(new char[] { '=' }); if (keyValue[0] == key) { continue; } if (!isFirstAdded) { result += "?"; isFirstAdded = true; } else { result += "&amp;"; } result += queryStringParts[index]; } return result; } </code></pre> <p>For example I can call it like:</p> <pre><code> Console.WriteLine(RemoveQueryStringByKey(@"http://www.domain.com/uk_pa/PostDetail.aspx?hello=hi&amp;xpid=4578", "xpid")); </code></pre> <p>Hope the question is clear.</p> <p>Thanks,</p>
11,080,157
16
4
null
2012-06-15 14:32:51.237 UTC
8
2022-09-21 12:34:22.763 UTC
null
null
null
null
133,212
null
1
43
c#|.net|regex|url|query-string
81,812
<p>This works well:</p> <pre><code>public static string RemoveQueryStringByKey(string url, string key) { var uri = new Uri(url); // this gets all the query string key value pairs as a collection var newQueryString = HttpUtility.ParseQueryString(uri.Query); // this removes the key if exists newQueryString.Remove(key); // this gets the page path from root without QueryString string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path); return newQueryString.Count &gt; 0 ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) : pagePathWithoutQueryString; } </code></pre> <p>an example:</p> <pre><code>RemoveQueryStringByKey("https://www.google.co.uk/search?#hl=en&amp;output=search&amp;sclient=psy-ab&amp;q=cookie", "q"); </code></pre> <p>and returns:</p> <pre><code>https://www.google.co.uk/search?#hl=en&amp;output=search&amp;sclient=psy-ab </code></pre>
11,353,679
What's the recommended way to connect to MySQL from Go?
<p>I am looking for a reliable solution to connect to a MySQL database from Go. I've seen some libraries around, but it is difficult to determine the different states of completeness and current maintenance. I don't have complex needs, but I'd like to know what people are relying on or the most standard solution to connect to MySQL.</p>
11,357,116
3
0
null
2012-07-05 23:00:36.03 UTC
78
2022-03-29 08:01:49.453 UTC
2022-03-29 08:00:24.633 UTC
null
8,712,494
null
78,640
null
1
169
mysql|database|go
72,130
<p>A few drivers are available but you should only consider those that implement the <a href="http://golang.org/pkg/database/sql/">database/sql</a> API as</p> <ul> <li>it provides a clean and efficient syntax,</li> <li>it ensures you can later change the driver without changing your code, apart the import and connection.</li> </ul> <p>Two fast and reliable drivers are available for MySQL :</p> <ul> <li><a href="http://github.com/ziutek/mymysql">MyMySQL</a></li> <li><a href="https://github.com/Go-SQL-Driver/MySQL/">Go-MySQL-Driver</a></li> </ul> <p>I've used both of them in production, programs are running for months with connection numbers in the millions without failure.</p> <p>Other SQL database drivers <a href="http://code.google.com/p/go-wiki/wiki/SQLDrivers">are listed on go-wiki</a>.</p> <p><strong>Import when using MyMySQL :</strong></p> <pre><code>import ( "database/sql" _ "github.com/ziutek/mymysql/godrv" ) </code></pre> <p><strong>Import when using Go-MySQL-Driver :</strong></p> <pre><code>import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) </code></pre> <p><strong>Connecting and closing using MyMySQL :</strong></p> <pre><code>con, err := sql.Open("mymysql", database+"/"+user+"/"+password) defer con.Close() // here you can use the connection, it will be closed when function returns </code></pre> <p><strong>Connecting and closing using Go-MySQL-Driver :</strong></p> <pre><code>con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database) defer con.Close() </code></pre> <p><strong>Select one row :</strong></p> <pre><code>row := con.QueryRow("select mdpr, x, y, z from sometable where id=?", id) cb := new(SomeThing) err := row.Scan(&amp;cb.Mdpr, &amp;cb.X, &amp;cb.Y, &amp;cb.Z) </code></pre> <p><strong>Select multiple rows and build an array with results :</strong></p> <pre><code>rows, err := con.Query("select a, b from item where p1=? and p2=?", p1, p2) if err != nil { /* error handling */} items := make([]*SomeStruct, 0, 10) var ida, idb uint for rows.Next() { err = rows.Scan(&amp;ida, &amp;idb) if err != nil { /* error handling */} items = append(items, &amp;SomeStruct{ida, idb}) } </code></pre> <p><strong>Insert :</strong> </p> <pre><code>_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr) </code></pre> <p>You'll see that working in Go with MySQL is a delightful experience : I <strong>never</strong> had a problem, my servers run for months without errors or leaks. The fact that most functions simply take a variable number of arguments lighten a task which is tedious in many languages.</p> <p>Note that if, in the future, you need to use another MySQL driver, you'll just have to change two lines in one go file : the line doing the import and the line opening the connection. </p>
12,749,622
Understanding how to create a heap in Python
<p>The <code>collections.Count.most_common</code> function in Python uses the <code>heapq</code> module to return the count of the most common word in a file, for instance.</p> <p>I have traced through the <code>heapq.py</code> file, but I'm having a bit of trouble understanding how a heap is created/updated with respect to words let's say.</p> <p>So, I think the best way for me to understand it, is to figure out how to create a heap from scratch.</p> <p>Can someone provide a pseudocode for creating a heap that would represent word count?</p>
12,749,951
4
1
null
2012-10-05 15:40:29.253 UTC
14
2020-04-29 06:42:06.623 UTC
2020-04-29 06:42:06.623 UTC
null
555,030
null
1,158,977
null
1
31
python|heap
56,981
<p>this is a slightly modified version of the code found here : <a href="http://code.activestate.com/recipes/577086-heap-sort/">http://code.activestate.com/recipes/577086-heap-sort/</a></p> <pre><code>def HeapSort(A,T): def heapify(A): start = (len(A) - 2) / 2 while start &gt;= 0: siftDown(A, start, len(A) - 1) start -= 1 def siftDown(A, start, end): root = start while root * 2 + 1 &lt;= end: child = root * 2 + 1 if child + 1 &lt;= end and T.count(A[child]) &lt; T.count(A[child + 1]): child += 1 if child &lt;= end and T.count(A[root]) &lt; T.count(A[child]): A[root], A[child] = A[child], A[root] root = child else: return heapify(A) end = len(A) - 1 while end &gt; 0: A[end], A[0] = A[0], A[end] siftDown(A, 0, end - 1) end -= 1 if __name__ == '__main__': text = "the quick brown fox jumped over the the quick brown quick log log" heap = list(set(text.split())) print heap HeapSort(heap,text) print heap </code></pre> <p>Output</p> <pre><code>['brown', 'log', 'jumped', 'over', 'fox', 'quick', 'the'] ['jumped', 'fox', 'over', 'brown', 'log', 'the', 'quick'] </code></pre> <p>you can visualize the program here <a href="http://goo.gl/2a9Bh">http://goo.gl/2a9Bh</a></p>
13,221,769
Node.JS: How to pass variables to asynchronous callbacks?
<p>I'm sure my problem is based on a lack of understanding of asynch programming in node.js but here goes.</p> <p>For example: I have a list of links I want to crawl. When each asynch request returns I want to know which URL it is for. But, presumably because of race conditions, each request returns with the URL set to the last value in the list.</p> <pre><code>var links = ['http://google.com', 'http://yahoo.com']; for (link in links) { var url = links[link]; require('request')(url, function() { console.log(url); }); } </code></pre> <p>Expected output:</p> <pre><code>http://google.com http://yahoo.com </code></pre> <p>Actual output:</p> <pre><code>http://yahoo.com http://yahoo.com </code></pre> <p>So my question is either:</p> <ol> <li>How do I pass url (by value) to the call back function? OR</li> <li>What is the proper way of chaining the HTTP requests so they run sequentially? OR</li> <li>Something else I'm missing?</li> </ol> <p>PS: For 1. I don't want a solution which examines the callback's parameters but a general way of a callback knowing about variables 'from above'.</p>
13,221,877
3
0
null
2012-11-04 18:59:48.757 UTC
18
2016-11-25 22:28:51.717 UTC
2016-11-25 22:28:51.717 UTC
null
3,853,934
null
279,255
null
1
46
javascript|node.js|asynchronous|web-crawler
48,790
<p>Your <code>url</code> variable is not scoped to the <code>for</code> loop as JavaScript only supports global and function scoping. So you need to create a function scope for your <code>request</code> call to capture the <code>url</code> value in each iteration of the loop by using an immediate function:</p> <pre><code>var links = ['http://google.com', 'http://yahoo.com']; for (link in links) { (function(url) { require('request')(url, function() { console.log(url); }); })(links[link]); } </code></pre> <p>BTW, embedding a <code>require</code> in the middle of loop isn't good practice. It should probably be re-written as:</p> <pre><code>var request = require('request'); var links = ['http://google.com', 'http://yahoo.com']; for (link in links) { (function(url) { request(url, function() { console.log(url); }); })(links[link]); } </code></pre>
22,298,005
How to find schema name in Oracle ? when you are connected in sql session using read only user
<p>I am connected to a oracle database with a read only user and i used service name while Setting up connection in sql developer hence i dont know SID ( schema ).</p> <p>How can i find out schema name which i am connected to ?</p> <p>I am looking for this because i want to <a href="https://stackoverflow.com/questions/6580529/how-to-generate-e-r-diagram-using-oracle-sql-developer">generate ER diagram</a> and in that process at one step it asks to select schema. When i tried to select my user name , i dint get any tables as i guess all tables are mapped with schema user.</p> <p>Edit: I got my answer partially by the below sql Frank provided in comment , it gave me owner name which is schema in my case. But I am not sure if it is generic solution applicable for all cases.</p> <pre><code>select owner, table_name from all_tables. </code></pre> <p><strong>Edit</strong>: I think above sql is correct solution in all cases because schema is owner of all db objects. So either i get schema or owner both are same. Earlier my understanding about schema was not correct and i gone through another <a href="https://stackoverflow.com/questions/880230/difference-between-a-user-and-a-schema-in-oracle">question</a> and found schema is also a user.</p> <p><a href="https://stackoverflow.com/users/610979/frank-schmitt">Frank</a>/<a href="https://stackoverflow.com/users/330315/a-horse-with-no-name">a_horse_with_no_name</a> Put this in answer so that i can accept it.</p>
22,351,196
3
13
null
2014-03-10 10:44:30.167 UTC
2
2020-09-26 13:52:38.723 UTC
2017-05-23 11:47:13.79 UTC
null
-1
null
2,922,515
null
1
25
sql|oracle11g
247,043
<p>To create a read-only user, you have to setup a different user than the one owning the tables you want to access.</p> <p>If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:</p> <ol> <li>Set the <em>current schema</em> in your session:</li> </ol> <pre class="lang-sql prettyprint-override"><code>ALTER SESSION SET CURRENT_SCHEMA=XYZ </code></pre> <ol start="2"> <li>Create synonyms for all tables:</li> </ol> <pre class="lang-sql prettyprint-override"><code>CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1 </code></pre> <p>So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:</p> <ol> <li>Query the current schema setting:</li> </ol> <pre class="lang-sql prettyprint-override"><code>SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL </code></pre> <ol start="2"> <li>List your synonyms:</li> </ol> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER </code></pre> <ol start="3"> <li>Investigate all tables (with the exception of the some well-known standard schemas):</li> </ol> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS'); </code></pre>
16,609,724
Using current time in UTC as default value in PostgreSQL
<p>I have a column of the <code>TIMESTAMP WITHOUT TIME ZONE</code> type and would like to have that default to the current time in UTC. Getting the current time in UTC is easy:</p> <pre><code>postgres=# select now() at time zone 'utc'; timezone ---------------------------- 2013-05-17 12:52:51.337466 (1 row) </code></pre> <p>As is using the current timestamp for a column:</p> <pre><code>postgres=# create temporary table test(id int, ts timestamp without time zone default current_timestamp); CREATE TABLE postgres=# insert into test values (1) returning ts; ts ---------------------------- 2013-05-17 14:54:33.072725 (1 row) </code></pre> <p>But that uses local time. Trying to force that to UTC results in a syntax error:</p> <pre><code>postgres=# create temporary table test(id int, ts timestamp without time zone default now() at time zone 'utc'); ERROR: syntax error at or near "at" LINE 1: ...int, ts timestamp without time zone default now() at time zo... </code></pre>
16,610,360
6
0
null
2013-05-17 13:00:50.147 UTC
39
2019-03-22 12:11:02.953 UTC
2018-10-22 13:55:10.607 UTC
null
1,828,296
null
211,490
null
1
237
postgresql|timezone|timestamp
253,051
<p>A function is not even needed. Just put parentheses around the default expression:</p> <pre><code>create temporary table test( id int, ts timestamp without time zone default (now() at time zone 'utc') ); </code></pre>
25,622,894
java.security.InvalidKeyException: invalid key format on generating RSA public key
<p>Background:</p> <p>I have created an applet to extract public key of a certificate extracted from a smart card. This public key is then stored in database. The private key of certificate is used to sign data and the public key is then used to verify the signature. Code for extracting public key from certificate:</p> <pre><code>private byte[] getPublicKey(KeyStore paramKeyStore) throws GeneralSecurityException { Enumeration localEnumeration = paramKeyStore.aliases(); if (localEnumeration.hasMoreElements()) { String element = (String) localEnumeration.nextElement(); Certificate[] arrayOfCertificate = paramKeyStore.getCertificateChain(element); byte[] publicKeyByteArray = arrayOfCertificate[0].getPublicKey().getEncoded(); return publicKeyByteArray; } throw new KeyStoreException("The keystore is empty!"); } </code></pre> <p>This publicKeyByteArray is then storeed in database as BLOB after converting to string using bytes2String method:</p> <pre><code>private static String bytes2String(byte[] bytes) { StringBuilder string = new StringBuilder(); for (byte b : bytes) { String hexString = Integer.toHexString(0x00FF &amp; b); string.append(hexString.length() == 1 ? "0" + hexString : hexString); } return string.toString(); } </code></pre> <p>The content of the BLOB(key) saved in database is:</p> <pre><code>30820122300d06092a864886f70d01010105000382010f003082010a02820101009bd307e4fc38adae43b93ba1152a4d6dbf82689336bb4e3af5160d16bf1599fe070f7acbfefd93e866e52043de1620bd57d9a3f244fb4e6ef758d70d19e0be86e1b12595af748fbc00aad9009bd61120d3348079b00af8462de46e254f6d2b092cbc85c7f6194c6c37f8955ef7b9b8937a7e9999541dbbea8c1b2349c712565482dbd573cd9b7ec56a59e7683b4c246620cf0d8148ed38da937f1e4e930eb05d5b4c6054712928fa59870763468c07e71265525e1e40839b51c833579f5742d3c8e0588766e3ed6deef1593b10baad0a2abea34734de1505d37710e1cfaa4225b562b96a6a4e87fecb1d627d4c61916e543eba87054ee9212e8183125cdb49750203010001 </code></pre> <p>After reading the stored public key byte[] from database, I try to convert it back to Public Key using following code: </p> <pre><code>Cipher rsa; rsa = Cipher.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pkey.getBytes()); PublicKey pk = keyFactory.generatePublic(publicKeySpec); rsa.init(Cipher.DECRYPT_MODE, pk); byte[] cipherDecrypt = rsa.doFinal(encryptedText.getBytes()); </code></pre> <p>but it gives following error:</p> <pre><code>Caused by: java.security.InvalidKeyException: invalid key format at sun.security.x509.X509Key.decode(X509Key.java:387) at sun.security.x509.X509Key.decode(X509Key.java:403) at sun.security.rsa.RSAPublicKeyImpl.&lt;init&gt;(RSAPublicKeyImpl.java:83) at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:298) at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:201) </code></pre> <p>Please suggest the reason and resolution for this issue.</p>
25,623,417
1
4
null
2014-09-02 11:59:33.723 UTC
5
2014-09-02 12:25:27.88 UTC
2014-09-02 12:22:58.513 UTC
null
474,189
null
3,619,997
null
1
6
java|rsa|public-key-encryption|x509|public-key
48,827
<p>You must have an error in the way you read the key back from the database. The following code works just fine for me:</p> <pre><code>String key = "3082012230..."; // full key omitted for brevity byte[] derPublicKey = DatatypeConverter.parseHexBinary(key); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(derPublicKey); keyFactory.generatePublic(publicKeySpec); </code></pre> <p>I would guess, based on the use of <code>pkey.getBytes()</code>, that you've simply tried to get the bytes from the string rather than hex-decoding it.</p>
4,705,564
Python script as linux service/daemon
<p>Hallo,</p> <p>I'm trying to let a python script run as service (daemon) on (ubuntu) linux.</p> <p>On the web there exist several solutions like:</p> <p><a href="http://pypi.python.org/pypi/python-daemon/" rel="noreferrer">http://pypi.python.org/pypi/python-daemon/</a></p> <blockquote> <p>A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonContext instance holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state.</p> </blockquote> <p><a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="noreferrer">http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/</a></p> <p>However as I want to integrate my python script specifically with ubuntu linux my solution is a combination with an init.d script</p> <pre><code>#!/bin/bash WORK_DIR="/var/lib/foo" DAEMON="/usr/bin/python" ARGS="/opt/foo/linux_service.py" PIDFILE="/var/run/foo.pid" USER="foo" case "$1" in start) echo "Starting server" mkdir -p "$WORK_DIR" /sbin/start-stop-daemon --start --pidfile $PIDFILE \ --user $USER --group $USER \ -b --make-pidfile \ --chuid $USER \ --exec $DAEMON $ARGS ;; stop) echo "Stopping server" /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose ;; *) echo "Usage: /etc/init.d/$USER {start|stop}" exit 1 ;; esac exit 0 </code></pre> <p>and in python:</p> <pre><code>import signal import time import multiprocessing stop_event = multiprocessing.Event() def stop(signum, frame): stop_event.set() signal.signal(signal.SIGTERM, stop) if __name__ == '__main__': while not stop_event.is_set(): time.sleep(3) </code></pre> <p>My question now is if this approach is correct. Do I have to handle any additional signals? Will it be a "well-behaved Unix daemon process"?</p>
4,706,394
2
0
null
2011-01-16 13:20:57.15 UTC
60
2014-02-14 00:34:56.437 UTC
null
null
null
null
405,559
null
1
72
python|linux|service|daemon
74,862
<p>Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use <code>upstart</code>.</p> <p>Here's an example upstart config for a hypothetical Python service:</p> <pre><code>description "My service" author "Some Dude &lt;blah@foo.com&gt;" start on runlevel [234] stop on runlevel [0156] chdir /some/dir exec /some/dir/script.py respawn </code></pre> <p>If you save this as script.conf to <code>/etc/init</code> you simple do a one-time</p> <pre><code>$ sudo initctl reload-configuration $ sudo start script </code></pre> <p>You can stop it with <code>stop script</code>. What the above upstart conf says is to start this service on reboots and also restart it if it dies.</p> <p>As for signal handling - your process should naturally respond to <code>SIGTERM</code>. By default this should be handled unless you've specifically installed your own signal handler.</p>
26,750,814
how to make synchronous http request in angular js
<p>How to make blocking http request in AngularJS so that i can use the $http response on very next line? </p> <p>In the following example, <code>$http</code> object doesn't return the result to the next line so that I can pass this result to <code>fullcalender()</code>, a JavaScript library, because <code>$scope.data</code> returns blank value.</p> <p>This is the sample code:</p> <pre><code>$http.get('URL').success(function(data){ $scope.data = data; }); $.fullCalender({ data: $scope.data }); </code></pre>
26,752,424
3
4
null
2014-11-05 06:14:02.233 UTC
4
2017-08-14 13:54:07.483 UTC
2017-08-14 13:54:07.483 UTC
null
2,275,011
null
3,631,271
null
1
20
angularjs
55,609
<p>You can use <a href="https://docs.angularjs.org/api/ng/service/$q" rel="nofollow">promises</a> for that.</p> <p>here is an example:</p> <pre><code>$scope.myXhr = function(){ var deferred = $q.defer(); $http({ url: 'ajax.php', method: 'POST', data:postData, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) //if request is successful .success(function(data,status,headers,config){ //resolve the promise deferred.resolve('request successful'); }) //if request is not successful .error(function(data,status,headers,config){ //reject the promise deferred.reject('ERROR'); }); //return the promise return deferred.promise; } $scope.callXhrAsynchronous = function(){ var myPromise = $scope.myXhr(); // wait until the promise return resolve or eject //"then" has 2 functions (resolveFunction, rejectFunction) myPromise.then(function(resolve){ alert(resolve); }, function(reject){ alert(reject) }); } </code></pre>
10,034,537
persistent vs immutable data structure
<p>Is there any difference in a persistent and immutable data structure? Wikipedia refers to immutable data structure when discussing persistence but I have a feeling there might be a subtle difference between the two.</p>
12,550,660
2
0
null
2012-04-05 19:09:10.563 UTC
10
2012-09-23 07:55:38.467 UTC
null
null
null
null
1,094,640
null
1
20
data-structures|immutability|object-persistence
10,132
<p><em>Immutability</em> is an implementation technique. Among other things, it provides <em>persistence</em>, which is an interface. The persistence API is something like:</p> <ul> <li><code>version update(operation o, version v)</code> performs operation <code>o</code> on version <code>v</code>, returning a new version. If the data structure is immutable, the new version is a new structure (that may share immutable parts of the old structure). If the data structure isn't immutable, the returned version might just be a version number. The version <code>v</code> remains a valid version, and it shouldn't change in any <code>observe</code>-able way because of this update - the update is only visible in the returned version, not in <code>v</code>.</li> <li><code>data observe(query q, version v)</code> observes a data structure at version <code>v</code> without changing it or creating a new version.</li> </ul> <p>For more about these differences, see:</p> <ul> <li><a href="http://www.math.tau.ac.il/~haimk/papers/persistent-survey.ps" rel="noreferrer">The chapter "Persistent data structures" by Haim Kaplan in <em>Handbook on Data Structures and Applications</em></a></li> <li><a href="http://www.cs.cmu.edu/~sleator/papers/Persistence.htm" rel="noreferrer">"Making Data Structures Persistent" by Driscoll et al.</a></li> <li><a href="http://courses.csail.mit.edu/6.851/spring12/lectures/L01.html" rel="noreferrer">The first lecture of the Spring 2012 incarnation of MIT's 6.851: Advanced Data Structures</a></li> </ul>
10,097,417
How do I create an Autoscrolling TextBox
<p>I have a WPF application that contains a multiline TextBox that is being used to display debugging text output. </p> <p>How can I set the TextBox so that as text is appended to the box, it will automatically scroll to the bottom of the textbox?</p> <ul> <li>I'm using the MVVM pattern.</li> <li>Ideally a pure XAML approach would be nice.</li> <li>The TextBox itself is not necessarily in focus.</li> </ul>
10,132,405
6
3
null
2012-04-10 22:33:17.343 UTC
13
2015-01-14 09:55:31.657 UTC
2012-04-13 04:33:48.323 UTC
null
546,730
null
5,007
null
1
27
wpf|xaml|mvvm
19,820
<p>The answer provided by @BojinLi works well. After reading through the answer linked to by @GazTheDestroyer however, I decided to implement my own version for the TextBox, because it looked cleaner.</p> <p>To summarize, you can extend the behavior of the TextBox control by using an attached property. (Called ScrollOnTextChanged)</p> <p>Using it is simple:</p> <pre><code>&lt;TextBox src:TextBoxBehaviour.ScrollOnTextChanged="True" VerticalScrollBarVisibility="Auto" /&gt; </code></pre> <p>Here is the TextBoxBehaviour class:</p> <pre><code>using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; namespace MyNamespace { public class TextBoxBehaviour { static readonly Dictionary&lt;TextBox, Capture&gt; _associations = new Dictionary&lt;TextBox, Capture&gt;(); public static bool GetScrollOnTextChanged(DependencyObject dependencyObject) { return (bool)dependencyObject.GetValue(ScrollOnTextChangedProperty); } public static void SetScrollOnTextChanged(DependencyObject dependencyObject, bool value) { dependencyObject.SetValue(ScrollOnTextChangedProperty, value); } public static readonly DependencyProperty ScrollOnTextChangedProperty = DependencyProperty.RegisterAttached("ScrollOnTextChanged", typeof (bool), typeof (TextBoxBehaviour), new UIPropertyMetadata(false, OnScrollOnTextChanged)); static void OnScrollOnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var textBox = dependencyObject as TextBox; if (textBox == null) { return; } bool oldValue = (bool) e.OldValue, newValue = (bool) e.NewValue; if (newValue == oldValue) { return; } if (newValue) { textBox.Loaded += TextBoxLoaded; textBox.Unloaded += TextBoxUnloaded; } else { textBox.Loaded -= TextBoxLoaded; textBox.Unloaded -= TextBoxUnloaded; if (_associations.ContainsKey(textBox)) { _associations[textBox].Dispose(); } } } static void TextBoxUnloaded(object sender, RoutedEventArgs routedEventArgs) { var textBox = (TextBox) sender; _associations[textBox].Dispose(); textBox.Unloaded -= TextBoxUnloaded; } static void TextBoxLoaded(object sender, RoutedEventArgs routedEventArgs) { var textBox = (TextBox) sender; textBox.Loaded -= TextBoxLoaded; _associations[textBox] = new Capture(textBox); } class Capture : IDisposable { private TextBox TextBox { get; set; } public Capture(TextBox textBox) { TextBox = textBox; TextBox.TextChanged += OnTextBoxOnTextChanged; } private void OnTextBoxOnTextChanged(object sender, TextChangedEventArgs args) { TextBox.ScrollToEnd(); } public void Dispose() { TextBox.TextChanged -= OnTextBoxOnTextChanged; } } } } </code></pre>
10,125,568
how to randomly choose multiple keys and its value in a dictionary python
<p>I have a dictionary like this:</p> <pre><code>user_dict = { user1: [(video1, 10),(video2,20),(video3,1)] user2: [(video1, 4),(video2,8),(video6,45)] ... user100: [(video1, 46),(video2,34),(video6,4)] } (video1,10) means (videoid, number of request) </code></pre> <p>Now I want to randomly choose 10 users and do some calculation like </p> <pre><code> 1. calculate number of videoid for each user. 2. sum up the number of requests for these 10 random users, etc </code></pre> <p>then I need to increase the random number to 20, 30, 40 respectively</p> <p>But "random.choice" can only choose one value at a time, right? how to choose multiple keys and the list following each key?</p>
10,125,602
4
0
null
2012-04-12 14:23:50.76 UTC
1
2021-04-06 09:43:04.56 UTC
null
null
null
null
504,283
null
1
28
python
40,298
<p>That's what <a href="http://docs.python.org//library/random.html?highlight=random.choice#random.sample" rel="noreferrer"><code>random.sample()</code></a> is for:</p> <blockquote> <p>Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.</p> </blockquote> <p>This can be used to choose the keys. The values can subsequently be retrieved by normal dictionary lookup:</p> <pre><code>&gt;&gt;&gt; d = dict.fromkeys(range(100)) &gt;&gt;&gt; keys = random.sample(list(d), 10) &gt;&gt;&gt; keys [52, 3, 10, 92, 86, 42, 99, 73, 56, 23] &gt;&gt;&gt; values = [d[k] for k in keys] </code></pre> <p>Alternatively, you can directly sample from <code>d.items()</code>.</p>
9,998,672
Winforms - how to show/hide elements in designer?
<p>I am trying to make a multiple page application using winforms. I decied to use multiple Panels - each panel represents different page, so I can switch between them when I need to display different content.</p> <p>My problem is about stacking panels in designer view. When I have 2+ full screen panels, they all stack on each other and I can't see the one that I created earlier. Is there any solution to this ? Changing visibility does not affect designers view. Think of it as a photoshop-like option to show/hide layers. I'm using Visual C# 2010 Express.</p>
9,998,893
7
1
null
2012-04-03 17:52:45.653 UTC
8
2020-11-02 21:30:14.793 UTC
2018-03-14 11:34:48.64 UTC
null
397,817
null
1,139,585
null
1
31
winforms|visual-studio|visual-studio-2010
34,013
<p>Several options here:</p> <ol> <li>Use the <code>Document Outline</code> view (<code>View --&gt; Other Windows --&gt; Document Outline</code>) to select the panel you care about. You can right-click on it and choose <code>Bring to Front</code> to put it in front of everything else.</li> <li>Though it's probably not relevant to what you're doing, you might consider using a <code>TabControl</code>, which you can mess with visually at design time. This is only a reasonable solution if you want your users to be able to manually change which panel they're viewing.</li> <li>Consider moving your panels into custom <code>UserControl</code> classes and work on them separately. If the content and logic of these panels is reasonably self-contained then you may want to do this anyway just to better restructure your code.</li> </ol> <hr> <p><strong>Addendum</strong>: You can also use a hack that makes a <code>TabControl</code>'s tabs invisible to the user. Put a <code>TabControl</code> on your form, and at run-time set the <code>ItemSize</code> height to 1. This makes it (almost) impossible for the user to change the tabs on their own, but still allows you to change the visible tab in the designer.</p> <pre><code>myTabControl.ItemSize = new Size(myTabControl.ItemSize.Width, 1); </code></pre> <p>Note that I called this a <em>hack</em> for a reason: <code>TabControl</code>s were not meant to be used this way. It's something that appears to work, but like all hacks it may break at any time so you should only do it as a last resort (and don't blame me if it causes headaches later on...). In short, I <strong>do not</strong> recommend this hack, I only offer it as a possibility.</p>
10,103,604
linux command line: du --- how to make it show only total for each directories
<p>I am doing it by (with coreutils_8.5-1ubuntu6_amd64):</p> <pre><code>du -sch `find ./ -maxdepth 1 -type d` </code></pre> <p>I am looking for a simple way (shorter cmd) to find <strong>size of subdirectories</strong>. Thank you.</p>
10,103,709
8
0
null
2012-04-11 09:51:53.803 UTC
22
2021-04-04 05:07:59.19 UTC
2012-04-11 09:59:43.973 UTC
null
451,718
null
451,718
null
1
91
linux|command-line
109,674
<p>This works with coreutils 5.97:</p> <p><code>du -cksh *</code></p>
7,935,292
android: camera onPause/onResume issue
<p>I have some troubles with the onPause() onResume() camera live cycle: Camera with preview, and taking photos works totally fine. With one exceptions:</p> <p>I start the app, click the home button, switch back to the app and take another shot.</p> <p>Result: shuttercallback is still executed (see code), but jpeg callback isn't anymore! Then my galaxy S vibrates, and the screen stays black, since startPreview() is not re-triggered after jpegCallback. The stack trace is far from usefull for me. Strange thing is that this only happens on my Galaxy S, not on the emulator. I have really no clue how to move on :/ Anyone has an idea what could be usefull?</p> <pre> 10-28 18:59:40.649: ERROR/SecCamera(4291): SetRotate(angle(0)) 10-28 18:59:40.649: ERROR/CameraHardwareSec(4291): ====setParameters processingmethod = (null) 10-28 18:59:40.649: ERROR/SecCamera(4291): setRecordingSize(width(800), height(480)) 10-28 18:59:40.673: ERROR/SecCamera(4291): SetRotate(angle(0)) 10-28 18:59:40.673: ERROR/CameraHardwareSec(4291): ====setParameters processingmethod = (null) 10-28 18:59:40.673: ERROR/SecCamera(4291): setRecordingSize(width(800), height(480)) 10-28 18:59:40.692: ERROR/SecCamera(4291): SetRotate(angle(0)) 10-28 18:59:40.692: ERROR/CameraHardwareSec(4291): ====setParameters processingmethod = (null) 10-28 18:59:40.692: ERROR/SecCamera(4291): setRecordingSize(width(800), height(480)) 10-28 18:59:40.712: ERROR/SecCamera(4291): SetRotate(angle(0)) 10-28 18:59:40.712: ERROR/CameraHardwareSec(4291): ====setParameters processingmethod = (null) 10-28 18:59:40.712: ERROR/SecCamera(4291): setRecordingSize(width(800), height(480)) 10-28 18:59:40.751: ERROR/CameraHardwareSec(4291): stopPreview() 10-28 18:59:40.751: ERROR/SecCamera(4291): cancelAutofocus() 10-28 18:59:40.751: ERROR/SecCamera(4291): cancelAutofocus() end, 0, 4 10-28 18:59:40.768: ERROR/SecCamera(4291): stopPreview() 10-28 18:59:40.768: ERROR/SecCamera(4291): fimc_v4l2_streamoff() 10-28 18:59:40.797: ERROR/CameraHardwareSec(4291): stopPreview() end 10-28 18:59:41.622: ERROR/SecCamera(4291): fimc_v4l2_streamoff() 10-28 18:59:46.536: ERROR/dalvikvm(2993): Failed to write stack traces to /data/anr/traces.txt (2775 of 2970): Unknown error: 0 10-28 18:59:46.540: ERROR/dalvikvm(2919): Failed to write stack traces to /data/anr/traces.txt (-1 of 3414): Math result not representable 10-28 18:59:46.610: ERROR/dalvikvm(3044): Failed to write stack traces to /data/anr/traces.txt (3354 of 7154): Math result not representable ... </pre> <p>Here is my (shortened) code:</p> <pre> public class CameraActivity extends Activity implements MenuViewCallback, CutoutPathManagerCallback { public static final String TAG = "CutoutCamera"; Preview preview; OverlayView overlay; static MenuView menuView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hide the window title. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); ... preview = (Preview) this.findViewById(R.id.preview); ... } ... @Override protected void onResume() { super.onResume(); this.log("onResume()"); preview.openCamera(); } @Override protected void onPause() { super.onPause(); this.log("onPause()"); if (preview.camera != null) { preview.camera.release(); preview.camera = null; } } // Called when shutter is opened ShutterCallback shutterCallback = new ShutterCallback() { // public void onShutter() { Log.d(TAG, "onShutter'd"); } }; // Handles data for raw picture PictureCallback rawCallback = new PictureCallback() { // public void onPictureTaken(byte[] data, Camera camera) { Log.d(TAG, "onPictureTaken - raw"); } }; // Handles data for jpeg picture PictureCallback jpegCallback = new PictureCallback() { // public void onPictureTaken(byte[] data, Camera camera) { Log.d(TAG, "onPictureTaken - jpeg"); ... } }; @Override public void shootButtonClicked() { preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback); } @Override public void focusButtonClicked() { preview.camera.autoFocus(new Camera.AutoFocusCallback() { public void onAutoFocus(boolean success, Camera camera) { } }); } } </pre> <pre> /** * order of execution: * openCamera() * onMeasure() * onLayout() * onMeasure() * onLayout() * surfaceCreated() * surfaceChanged() * onMeasure() * onLayout() * onMeasure() * @author stephan * */ class Preview extends ViewGroup implements SurfaceHolder.Callback { // private static final String TAG = "Preview"; SurfaceHolder mHolder; // public Camera camera; // private List supportedPreviewSizes; private Size previewSize; SurfaceView mSurfaceView; CameraActivity cameraActivity; int l2 = 0, t2 = 0, r2 = 0, b2 = 0; int padding = 20; Size optimalPreviewSize, optimalPictureSize; // the size of this view. gets set in onMeasure() int fullWidth, fullHeight; public Preview(Context context) { super(context); init(context); } public Preview(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public Preview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { setKeepScreenOn(true); cameraActivity = (CameraActivity) context; mSurfaceView = new SurfaceView(context); addView(mSurfaceView); mHolder = mSurfaceView.getHolder(); // mHolder.addCallback(this); // mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // } ... public void openCamera() { cameraActivity.log("openCamera()"); if (this.camera == null) { cameraActivity.log("Camera.open()"); this.camera = Camera.open(); //supportedPreviewSizes = camera.getParameters().getSupportedPreviewSizes(); requestLayout(); // -> onMeassure() -> onLayout() } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { cameraActivity.log("onMeasure()"); // We purposely disregard child measurements because act as a // wrapper to a SurfaceView that centers the camera preview instead // of stretching it. fullWidth = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); fullHeight = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(fullWidth, fullHeight); if(this.camera != null){ cameraActivity.log("fullSize:"+fullWidth+"x"+fullHeight); this.setCameraPreviewSize(); this.setCameraPictureSize(); } } private void calcScaledPreviewSize(){ ... } ... private void setCameraPreviewSize() { Camera.Parameters parameters = camera.getParameters(); if(parameters.getPreviewSize() != this.getOptimalPreviewSize()){ parameters.setPreviewSize(this.getOptimalPreviewSize().width, this.getOptimalPreviewSize().height); this.camera.setParameters(parameters); } } private void setCameraPictureSize() { Camera.Parameters parameters = this.camera.getParameters(); if(parameters.getPictureSize() != this.getOptimalCameraPictureSize()){ parameters.setPictureSize(getOptimalCameraPictureSize().width, getOptimalCameraPictureSize().height); this.camera.setParameters(parameters); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { cameraActivity.log("onLayout()"); if (changed && getChildCount() > 0 && this.camera != null) { final View child = getChildAt(0); cameraActivity.log("r:"+this.getPreviewRight()+" l:"+this.getPreviewLeft()+" b:"+this.getPreviewBottom()+" t:"+this.getPreviewTop()); child.layout(this.getPreviewLeft(), this.getPreviewTop(), this.getPreviewRight(), this.getPreviewBottom()); cameraActivity.initOverlay(this.getPreviewLeft(),this.getPreviewTop(),this.getPreviewRight(),this.getPreviewBottom()); } } private Size getOptimalPreviewSize() { if(optimalPreviewSize == null){ //calculate optimal preview size } return optimalPreviewSize; } private Size getOptimalCameraPictureSize() { if(optimalPictureSize == null){ //calculate optimal image size } return optimalPictureSize; } // Called once the holder is ready public void surfaceCreated(SurfaceHolder holder) { // // The Surface has been created, acquire the camera and tell it where // to draw. cameraActivity.log("surfaceCreated()"); try { if (this.camera != null) { this.camera.setPreviewDisplay(holder); } } catch (IOException exception) { Log.e(TAG, "IOException caused by setPreviewDisplay()", exception); } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { cameraActivity.log("surfaceChanged()"); if (camera != null) { Camera.Parameters parameters = camera.getParameters(); parameters.setPreviewSize(getOptimalPreviewSize().width, getOptimalPreviewSize().height); requestLayout(); camera.setParameters(parameters); camera.startPreview(); } } public void surfaceDestroyed(SurfaceHolder holder) { // cameraActivity.log("surfaceDestroyed()"); if(this.camera != null){ camera.stopPreview(); } } public void releaseCamera(){ cameraActivity.log("releaseCamera()"); if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); camera.release(); camera = null; } } } </pre>
8,805,285
3
0
null
2011-10-28 21:52:24.833 UTC
9
2018-01-27 17:05:56.553 UTC
null
null
null
null
457,059
null
1
12
android|camera|galaxy
22,244
<p>This is how I fixed it 100%, finally (working on every device I tried it on, including Galaxy S):</p> <p>I destroyed the camere preview object onResume and reinstantiated all together (like on startup). More details here:</p> <p><a href="https://stackoverflow.com/questions/8481402/android-i-get-no-stacktrace-phone-just-hangs">android: I get no stacktrace, phone just hangs</a></p>
7,709,030
Get GPS Location in a Broadcast Receiver/or Service to Broadcast Receiver data transfer
<p>I am new to android.<br> I want to get GPS Location in a broadcast receiver but it shows an error.</p> <p>My code is :</p> <pre><code>public void onReceive(Context context, Intent intent) { LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // errors in getSystemService method LocationListener locListener = new MyLocationListener(); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); Location loc = locManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.d(" **location**", " location" + loc.getLatitude()); } </code></pre> <p>Questions :</p> <ol> <li>Is it possible to get GPS Location data in Broadcast receiver? </li> <li>Another alternative way I tried so far was to use a service which is invoked by the Broadcast receiver. The service can get GPS data, but how can I get it in the Broadcast receiver?</li> </ol>
7,783,888
3
0
null
2011-10-10 05:58:44.833 UTC
14
2017-05-29 14:35:35.62 UTC
2013-05-09 22:18:09.213 UTC
null
281,545
null
371,720
null
1
18
android|service|broadcastreceiver
43,468
<p>From BroadcastReceiver I could not start Location Manager as well. So I started a service on BroadcastReceiver and in that service I manipulated Location Manager. I think I found this solution in Android development documentation. You also can start Activity instead of Service.</p> <p>Here is the code of switch to Service on BroadcastReceiver:</p> <p><strong>write this in <code>onReceive</code> method</strong></p> <pre><code> Intent serviceIntent = new Intent(context,MyService.class); serviceIntent.putExtra("locateRequest", "locateRequest"); // if you want pass parameter from here to service serviceIntent.putExtra("queryDeviceNumber", results[1]); context.startService(serviceIntent); //start service for get location </code></pre>
11,936,950
Inserting UTF-8 encoded string into UTF-8 encoded mysql table fails with "Incorrect string value"
<p>Inserting UTF-8 encoded string into UTF-8 encoded table gives incorrect string value.</p> <blockquote> <p>PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xF0\x9D\x84\x8E i...' for column 'body_value' at row 1: INSERT INTO</p> </blockquote> <p>I have a <code></code> character, in a string that <a href="http://php.net/manual/en/function.mb-detect-encoding.php" rel="noreferrer">mb_detect_encoding</a> claims is UTF-8 encoded. I try to insert this string into a MySQL table, which is defined as (among other things) <code>DEFAULT CHARSET=utf8</code></p> <p><strong>Edit:</strong> Drupal always does <code>SET NAMES utf8</code> with optional <code>COLLATE</code> (atleast when talking to MySQL).</p> <p><strong>Edit 2:</strong> Some more details that appear to be relevant. I grab some text from a PostgreSQL database. I stick it onto an object, use mb_detect_encoding to verify that it's UTF-8, and persist the object to the database, using <a href="http://api.drupal.org/api/drupal/modules!node!node.module/function/node_save/7" rel="noreferrer">node_save</a>. So while there is an HTTP request that triggers the import, the data does not come from the browser.</p> <p><strong>Edit 3:</strong> Data is denormalized over two tables:</p> <blockquote> <p>SELECT character_set_name FROM information_schema.<code>COLUMNS</code> C WHERE table_schema = "[database]" AND table_name IN ("field_data_body", "field_revision_body") AND column_name = "body_value";</p> </blockquote> <pre><code>&gt;+--------------------+ | character_set_name | +--------------------+ | utf8 | | utf8 | +--------------------+ </code></pre> <p><strong>Edit 4:</strong> Is it possible that the character is "to new"? I'm more than a little fuzzy on <a href="https://stackoverflow.com/questions/643694/utf-8-vs-unicode">the relationship between unicode and UTF-8</a>, but this <a href="http://en.wikipedia.org/wiki/List_of_Unicode_characters#Musical_symbols" rel="noreferrer">wikipedia article</a>, implies that the character was standardized very recently.</p> <p>I don't understand how that can fail with "Incorrect string value".</p>
11,948,519
4
5
null
2012-08-13 14:59:28.743 UTC
6
2020-07-15 00:04:20.097 UTC
2017-05-23 11:47:15.633 UTC
null
-1
null
1,147,744
null
1
14
php|mysql|drupal
39,086
<p> (U+1D10E) is a character Unicode found outside the BMP (Basic Multilingual Plane) (above U+FFFF) and thus can't be represented in UTF-8 in 3 bytes. MySQL charset utf8 only accepts UTF-8 characters if they can be represented in 3 bytes. If you need to store this in MySQL, you'll need to use MySQL charset utf8mb4. You'll need MySQL 5.5.3 or later. You can use ALTER TABLE to change the character set without much problem; since it needs more space to store the characters, a couple issues show up that may require you to reduce string size. See <a href="http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-upgrading.html">http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-upgrading.html</a> .</p>
11,467,746
"Return without GoSub" when using subforms in Access
<p>Why do I get a </p> <blockquote> <p>"Return without GoSub"</p> </blockquote> <p>error when using subforms in Access 2007?</p>
11,467,748
5
0
null
2012-07-13 09:29:18.69 UTC
1
2019-05-31 15:12:43.317 UTC
2018-05-31 13:02:40.82 UTC
null
709,443
null
709,443
null
1
16
ms-access|ms-access-2007|vba
50,589
<p>This can occur when there is a <code>Form_Load()</code> event in the subform, but not the main form. Try adding an <code>empty Form_Load()</code> event to the main form.</p>
11,457,328
What is _In_ in C++?
<p>I have searched this up rather a lot, but come up with no helpful results.</p> <p>I am currently trying to program simple DirextX game for Windows 8 Metro, and have come across <code>_In_</code> rather a lot. I'm just wondering what it is.</p> <p>Also, I have seen a lot of the use of <code>^</code> as the pointer <code>*</code> which I found odd. On top of this, some classes have an interface of <code>ref class MyClass</code>, which I believe is for C# legibility.</p> <p>Anyway, any help would be brilliant.</p>
11,457,407
4
5
null
2012-07-12 17:29:53.307 UTC
8
2021-05-09 13:55:49.183 UTC
2013-02-13 02:27:52.337 UTC
null
480,894
null
1,486,106
null
1
35
c++|c|microsoft-metro|c++-cx
27,631
<p>It is a <a href="http://msdn.microsoft.com/en-us/library/hh916383(v=vs.110).aspx" rel="noreferrer">SAL annotation</a>, used for code analysis. The annotations themselves are defined as macros that, in normal builds, expand to nothing.</p> <p>The <code>^</code> and <code>ref class</code> are features of <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh699871(v=vs.110).aspx" rel="noreferrer">C++/CX</a>, a set of language extensions developed to make it easier to build Metro style apps for Windows 8 in C++. Neither is a part of standard C++. The documentation (linked previously) has links to tutorials and references describing the language extensions.</p>
11,589,770
input type="text" vs input type="search" in HTML5
<p>I'm new to HTML5 as begun to work with HTML5's new form input fields. When I'm working with form input fields, especially <code>&lt;input type="text" /&gt;</code> and <code>&lt;input type="search" /&gt;</code> IMO there wasn't any difference in all major browser including Safari, Chrome, Firefox and Opera. And the search field also behaves like a regular text field.</p> <p>So, what is the difference between <code>input type="text"</code> and <code>input type="search"</code> in HTML5?</p> <p>What is the real purpose of <code>&lt;input type="search" /&gt;</code>?</p>
11,589,805
10
1
null
2012-07-21 05:33:48.01 UTC
15
2017-11-06 08:25:01.973 UTC
2014-01-04 11:16:35.82 UTC
null
562,769
null
972,501
null
1
155
forms|html|input
84,876
<p>Right now, there isn't a huge deal between them - maybe there never will be. However, the point is to give the browser-makers the ability to do something special with it, if they want.</p> <p>Think about <code>&lt;input type="number"&gt;</code> on cellphones, bringing up number pads, or <code>type="email"</code> bringing up a special version of the keyboard, with @ and .com and the rest available.</p> <p>On a cellphone, search could bring up an internal search applet, if they wanted.</p> <p>On the other side, it helps current devs with css.</p> <pre><code>input[type=search]:after { content : url("magnifying-glass.gif"); } </code></pre>
20,279,484
How to access the correct `this` inside a callback
<p>I have a constructor function which registers an event handler:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function MyConstructor(data, transport) { this.data = data; transport.on('data', function () { alert(this.data); }); } // Mock transport object var transport = { on: function(event, callback) { setTimeout(callback, 1000); } }; // called as var obj = new MyConstructor('foo', transport);</code></pre> </div> </div> </p> <p>However, I'm not able to access the <code>data</code> property of the created object inside the callback. It looks like <code>this</code> does not refer to the object that was created, but to another one.</p> <p>I also tried to use an object method instead of an anonymous function:</p> <pre><code>function MyConstructor(data, transport) { this.data = data; transport.on('data', this.alert); } MyConstructor.prototype.alert = function() { alert(this.name); }; </code></pre> <p>but it exhibits the same problems.</p> <p>How can I access the correct object?</p>
20,279,485
13
4
null
2013-11-29 06:13:11.43 UTC
837
2021-10-19 21:37:50.453 UTC
2021-07-25 20:19:56.12 UTC
null
63,550
null
218,196
null
1
1,789
javascript|callback|this
574,269
<h2>What you should know about <code>this</code></h2> <p><code>this</code> (aka &quot;the context&quot;) is a special keyword inside each function and its value only depends on <em>how</em> the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:</p> <pre><code>function foo() { console.log(this); } // normal function call foo(); // `this` will refer to `window` // as object method var obj = {bar: foo}; obj.bar(); // `this` will refer to `obj` // as constructor function new foo(); // `this` will refer to an object that inherits from `foo.prototype` </code></pre> <p>To learn more about <code>this</code>, have a look at the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" rel="noreferrer">MDN documentation</a>.</p> <hr /> <h2>How to refer to the correct <code>this</code></h2> <h3>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a></h3> <p>ECMAScript 6 introduced <em>arrow functions</em>, which can be thought of as lambda functions. They don't have their own <code>this</code> binding. Instead, <code>this</code> is looked up in scope just like a normal variable. That means you don't have to call <code>.bind</code>. That's not the only special behavior they have, please refer to the MDN documentation for more information.</p> <pre><code>function MyConstructor(data, transport) { this.data = data; transport.on('data', () =&gt; alert(this.data)); } </code></pre> <h3>Don't use <code>this</code></h3> <p>You actually don't want to access <code>this</code> in particular, but <em>the object it refers to</em>. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are <code>self</code> and <code>that</code>.</p> <pre><code>function MyConstructor(data, transport) { this.data = data; var self = this; transport.on('data', function() { alert(self.data); }); } </code></pre> <p>Since <code>self</code> is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the <code>this</code> value of the callback itself.</p> <h3>Explicitly set <code>this</code> of the callback - part 1</h3> <p>It might look like you have no control over the value of <code>this</code> because its value is set automatically, but that is actually not the case.</p> <p>Every function has the method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="noreferrer"><code>.bind</code> <em><sup>[docs]</sup></em></a>, which returns a new function with <code>this</code> bound to a value. The function has exactly the same behavior as the one you called <code>.bind</code> on, only that <code>this</code> was set by you. No matter how or when that function is called, <code>this</code> will always refer to the passed value.</p> <pre><code>function MyConstructor(data, transport) { this.data = data; var boundFunction = (function() { // parenthesis are not necessary alert(this.data); // but might improve readability }).bind(this); // &lt;- here we are calling `.bind()` transport.on('data', boundFunction); } </code></pre> <p>In this case, we are binding the callback's <code>this</code> to the value of <code>MyConstructor</code>'s <code>this</code>.</p> <p><strong>Note:</strong> When a binding context for jQuery, use <a href="http://api.jquery.com/jQuery.proxy/" rel="noreferrer"><code>jQuery.proxy</code> <em><sup>[docs]</sup></em></a> instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.</p> <h3>Set <code>this</code> of the callback - part 2</h3> <p>Some functions/methods which accept callbacks also accept a value to which the callback's <code>this</code> should refer to. This is basically the same as binding it yourself, but the function/method does it for you. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><code>Array#map</code> <em><sup>[docs]</sup></em></a> is such a method. Its signature is:</p> <pre><code>array.map(callback[, thisArg]) </code></pre> <p>The first argument is the callback and the second argument is the value <code>this</code> should refer to. Here is a contrived example:</p> <pre><code>var arr = [1, 2, 3]; var obj = {multiplier: 42}; var new_arr = arr.map(function(v) { return v * this.multiplier; }, obj); // &lt;- here we are passing `obj` as second argument </code></pre> <p><strong>Note:</strong> Whether or not you can pass a value for <code>this</code> is usually mentioned in the documentation of that function/method. For example, <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery's <code>$.ajax</code> method <em><sup>[docs]</sup></em></a> describes an option called <code>context</code>:</p> <blockquote> <p>This object will be made the context of all Ajax-related callbacks.</p> </blockquote> <hr /> <h2>Common problem: Using object methods as callbacks/event handlers</h2> <p>Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term &quot;method&quot; is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its &quot;containing&quot; object.</p> <p>Consider the following example:</p> <pre><code>function Foo() { this.data = 42, document.body.onclick = this.method; } Foo.prototype.method = function() { console.log(this.data); }; </code></pre> <p>The function <code>this.method</code> is assigned as click event handler, but if the <code>document.body</code> is clicked, the value logged will be <code>undefined</code>, because inside the event handler, <code>this</code> refers to the <code>document.body</code>, not the instance of <code>Foo</code>.<br /> As already mentioned at the beginning, what <code>this</code> refers to depends on how the function is <strong>called</strong>, not how it is <strong>defined</strong>.<br /> If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:</p> <pre><code>function method() { console.log(this.data); } function Foo() { this.data = 42, document.body.onclick = this.method; } Foo.prototype.method = method; </code></pre> <p><strong>The solution</strong> is the same as mentioned above: If available, use <code>.bind</code> to explicitly bind <code>this</code> to a specific value</p> <pre><code>document.body.onclick = this.method.bind(this); </code></pre> <p>or explicitly call the function as a &quot;method&quot; of the object, by using an anonymous function as callback / event handler and assign the object (<code>this</code>) to another variable:</p> <pre><code>var self = this; document.body.onclick = function() { self.method(); }; </code></pre> <p>or use an arrow function:</p> <pre><code>document.body.onclick = () =&gt; this.method(); </code></pre>
3,992,295
Unit-testing framework for MATLAB
<p>What are the unit-testing frameworks for MATLAB out there, and how do they compare? How should I choose one for our project? What are their pros and cons?</p>
3,992,858
4
1
null
2010-10-21 21:52:57.83 UTC
13
2014-12-29 07:57:28.357 UTC
null
null
null
null
1,428
null
1
23
unit-testing|matlab
7,769
<p>I think the most popular framework for MATLAB is <a href="http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework" rel="noreferrer">xUnit Test Framework</a> available on File Exchange. Very flexible and well documented.</p> <p>Some other unit-testing tools are listed <a href="http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#MATLAB" rel="noreferrer">here</a> and <a href="http://mlunit.dohmke.de/Unit_Testing_With_Matlab" rel="noreferrer">here</a>.</p> <p>Another very recent and interesting File Exchange submission is <a href="http://www.mathworks.com/matlabcentral/fileexchange/28862-doctest-embed-testable-examples-in-your-functions-help-comments" rel="noreferrer">Doctest</a>. Not exactly unit-testing framework though, it works like <em>doctest</em> in Python. I haven't tried it yet, but looks very promising for simple tests embedded into function's help. </p>
3,981,199
Adding "Open In..." option to iOS app
<p>On iOS devices, the Mail app offers "Open In..." option for attachments. The apps listed have registered their CFBundleDocumentTypes with the OS. What I am wondering is how my app might allow users to open files generated by my app in other apps. Is Mail the only app that provides this feature?</p>
3,981,774
4
2
null
2010-10-20 18:44:40.983 UTC
38
2016-02-24 01:58:12.157 UTC
null
null
null
null
203,220
null
1
48
iphone|ipad|ios
81,270
<p>Take a look at the <a href="https://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/RegisteringtheFileTypesYourAppSupports.html#//apple_ref/doc/uid/TP40010411-SW1" rel="noreferrer">Document Interaction Programming Topics for iOS: Registering the File Types Your App Supports</a>.</p> <p>As long as you provide your document types in your Info.plist, other apps that recognize that document type will list your app in their "open in" choices. Of course, that presumes that your app creates documents that other apps can open.</p>
4,000,877
How can I get the current instance's executable file name from native win32 C++ app?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/124886/how-to-get-the-application-executable-name-in-windows-c-win32-or-c-cli">How to get the application executable name in Windows (C++ Win32 or C++/CLI)?</a> </p> </blockquote> <p>How can I get the current instance's file name &amp; path from within my native win32 C++ application?</p> <p>For example; if my application was c:\projects\testapps\getapppath.exe it would be able to tell the path is c:\projects\testapps\getapppath.exe</p>
4,000,904
5
0
null
2010-10-22 20:52:46.39 UTC
5
2019-10-31 18:28:17.217 UTC
2017-05-23 12:32:02.037 UTC
null
-1
null
29,043
null
1
26
c++|winapi
47,825
<p>You can do this via the <a href="http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx" rel="noreferrer">GetModuleFileName</a> function.</p> <pre><code>TCHAR szFileName[MAX_PATH]; GetModuleFileName(NULL, szFileName, MAX_PATH) </code></pre>
3,727,439
How to enable horizontal scrolling with mouse?
<p>I cannot determine how to scroll horizontally using the mouse wheel. Vertical scrolling works well automatically, but I need to scroll my content horizontally. My code looks like this:</p> <pre><code>&lt;ListBox x:Name="receiptList" Margin="5,0" Grid.Row="1" ItemTemplate="{StaticResource receiptListItemDataTemplate}" ItemsSource="{Binding OpenReceipts}" ScrollViewer.VerticalScrollBarVisibility="Disabled"&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Horizontal" ScrollViewer.HorizontalScrollBarVisibility="Visible"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;/ListBox&gt; </code></pre> <p>My item template looks like this:</p> <pre><code>&lt;DataTemplate x:Key="receiptListItemDataTemplate"&gt; &lt;RadioButton GroupName="Numbers" Command="{Binding Path=DataContext.SelectReceiptCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type POS:PointOfSaleControl}}}" CommandParameter="{Binding }" Margin="2,0" IsChecked="{Binding IsSelected}"&gt; &lt;RadioButton.Template&gt; &lt;ControlTemplate TargetType="{x:Type RadioButton}" &gt; &lt;Grid x:Name="receiptGrid" &gt; &lt;Grid&gt; &lt;Border BorderThickness="2" BorderBrush="Green" Height="20" Width="20"&gt; &lt;Grid x:Name="radioButtonGrid" Background="DarkOrange"&gt; &lt;TextBlock x:Name="receiptLabel" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=NumberInQueue, Mode=OneWay}" FontWeight="Bold" FontSize="12" Foreground="White"&gt; &lt;/TextBlock&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsChecked" Value="True"&gt; &lt;Setter Property="Margin" TargetName="receiptGrid" Value="2,2,-1,-1"/&gt; &lt;Setter Property="Background" TargetName="radioButtonGrid" Value="Maroon"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/RadioButton.Template&gt; &lt;/RadioButton&gt; &lt;/DataTemplate&gt; </code></pre> <p>Is there another method or control that I need to add to get that functionality?</p>
42,047,117
6
1
null
2010-09-16 14:03:07.747 UTC
11
2021-06-07 09:08:22.367 UTC
2013-07-24 16:24:58.773 UTC
null
1,046,207
null
152,006
null
1
16
wpf|scrollviewer|horizontal-scrolling
17,433
<p>Here's a complete behaviour. Add the below class to your code, then in your XAML set the attached property to true on any <code>UIElement</code> that contains a <code>ScrollViewer</code> as a visual child.</p> <pre><code>&lt;MyVisual ScrollViewerHelper.ShiftWheelScrollsHorizontally=&quot;True&quot; /&gt; </code></pre> <p>The class:</p> <pre><code>public static class ScrollViewerHelper { public static readonly DependencyProperty ShiftWheelScrollsHorizontallyProperty = DependencyProperty.RegisterAttached(&quot;ShiftWheelScrollsHorizontally&quot;, typeof(bool), typeof(ScrollViewerHelper), new PropertyMetadata(false, UseHorizontalScrollingChangedCallback)); private static void UseHorizontalScrollingChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as UIElement; if (element == null) throw new Exception(&quot;Attached property must be used with UIElement.&quot;); if ((bool)e.NewValue) element.PreviewMouseWheel += OnPreviewMouseWheel; else element.PreviewMouseWheel -= OnPreviewMouseWheel; } private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs args) { var scrollViewer = ((UIElement)sender).FindDescendant&lt;ScrollViewer&gt;(); if (scrollViewer == null) return; if (Keyboard.Modifiers != ModifierKeys.Shift) return; if (args.Delta &lt; 0) scrollViewer.LineRight(); else scrollViewer.LineLeft(); args.Handled = true; } public static void SetShiftWheelScrollsHorizontally(UIElement element, bool value) =&gt; element.SetValue(ShiftWheelScrollsHorizontallyProperty, value); public static bool GetShiftWheelScrollsHorizontally(UIElement element) =&gt; (bool)element.GetValue(ShiftWheelScrollsHorizontallyProperty); [CanBeNull] private static T FindDescendant&lt;T&gt;([CanBeNull] this DependencyObject d) where T : DependencyObject { if (d == null) return null; var childCount = VisualTreeHelper.GetChildrenCount(d); for (var i = 0; i &lt; childCount; i++) { var child = VisualTreeHelper.GetChild(d, i); var result = child as T ?? FindDescendant&lt;T&gt;(child); if (result != null) return result; } return null; } } </code></pre> <p>This answer fixes a few bugs in <a href="https://stackoverflow.com/a/26143987/24874">Johannes' answer</a>, such as not filtering by Shift key, scrolling both horizontally and vertically at the same time (motion was diagonal) and the inability to disable the behaviour by setting the property to false.</p>
3,274,875
How to get cookie expiration date / creation date from javascript?
<p>Is it possible to retrieve the creation or expiration date of an existing cookie from javascript? If so how?</p>
3,274,924
7
2
null
2010-07-18 08:50:22.663 UTC
5
2021-03-13 11:06:54.85 UTC
2012-01-17 19:04:50.483 UTC
null
489,280
null
64,106
null
1
61
javascript|cookies
133,048
<p>The information is not available through document.cookie, but if you're really desperate for it, you could try performing a request through the XmlHttpRequest object to the current page and access the cookie header using getResponseHeader().</p>
3,913,241
How to insert null into database?
<p>Hi I am trying to insert null in a database column depending on a gridview datakeys value (if being "" insert null into database) However, I am getting a space ' ' inside the database column.</p> <pre><code>string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString(); insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value.ToString():sbcId))); </code></pre>
3,913,280
8
2
null
2010-10-12 09:32:56.313 UTC
3
2017-10-20 12:48:38.833 UTC
null
null
null
null
521,201
null
1
11
c#|asp.net|c#-2.0
56,436
<p>You have to rewrite your code:</p> <pre><code>if(string.IsNullOrEmpty(sbcId)) Parameters.Add(new OleDbParameter("EMPID", DBNull.Value)); else Parameters.Add(new OleDbParameter("EMPID", sbcId)); </code></pre> <p>The problem with the ternary if statement that you have is that its returntype must always be the same, which is why you cannot use it (string and DbNull.Value are not compatible)</p>
3,842,818
How to change Rails 3 server default port in develoment?
<p>On my development machine, I use port 10524. So I start my server this way :</p> <pre><code>rails s -p 10524 </code></pre> <p>Is there a way to change the default port to 10524 so I wouldn't have to append the port each time I start the server?</p>
3,843,133
9
1
null
2010-10-01 20:24:56.427 UTC
50
2021-02-05 20:40:55.187 UTC
null
null
null
null
94,348
null
1
168
ruby-on-rails
134,927
<p>First - do not edit anything in your gem path! It will influence all projects, and you will have a lot problems later...</p> <p>In your project edit <code>script/rails</code> this way:</p> <pre><code>#!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) # THIS IS NEW: require "rails/commands/server" module Rails class Server def default_options super.merge({ :Port =&gt; 10524, :environment =&gt; (ENV['RAILS_ENV'] || "development").dup, :daemonize =&gt; false, :debugger =&gt; false, :pid =&gt; File.expand_path("tmp/pids/server.pid"), :config =&gt; File.expand_path("config.ru") }) end end end # END OF CHANGE require 'rails/commands' </code></pre> <p>The principle is simple - you are monkey-patching the server runner - so it will influence just one project.</p> <p><strong>UPDATE</strong>: Yes, I know that the there is simpler solution with bash script containing:</p> <pre><code>#!/bin/bash rails server -p 10524 </code></pre> <p>but this solution has a serious drawback - it is boring as hell.</p>
3,706,819
What are the implications of using "!important" in CSS?
<p>I've been working on a website for a few months, and a lot of times when I've been trying to edit something, I have to use <code>!important</code>, <em>for example</em>:</p> <pre><code>div.myDiv { width: 400px !important; } </code></pre> <p>in order to make it display as expected. Is this bad practice? Or is the <code>!important</code> command okay to use? Can this cause anything undesired further down the line? </p>
3,706,876
9
2
null
2010-09-14 07:23:12.427 UTC
57
2019-06-15 07:37:59.353 UTC
2014-10-16 20:26:27.447 UTC
null
2,756,409
null
287,047
null
1
210
html|css|css-specificity
105,278
<p>Yes, I'd say your example of using <code>!important</code> is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.</p> <h3>What's wrong with <code>!important</code>:</h3> <p><a href="http://www.smashingmagazine.com/2010/04/css-specificity-and-inheritance/" rel="noreferrer">Specificity</a> is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:</p> <pre class="lang-css prettyprint-override"><code>button { color: black; } button.highlight { color: blue; font-size: 1.5em; } button#buyNow { color: green; font-size: 2em; } </code></pre> <p>On this page, all buttons are black. Except the buttons with the class &quot;highlight&quot;, which are blue. Except that one unique button with the ID &quot;buyNow&quot;, which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.</p> <p><strong><code>!important</code></strong>, however, is added at a property level, not a selector level. If, for instance, we used this rule:</p> <pre class="lang-css prettyprint-override"><code>button.highlight { color: blue !important; font-size: 1.5em; } </code></pre> <p>then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the <code>button#buyNow</code> selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).</p> <p>An element <code>&lt;button class=&quot;highlight&quot; id=&quot;buyNow&quot;&gt;</code> would have a font-size of <code>2em</code>, but a color <code>blue</code>.</p> <p>This means two things:</p> <ol> <li>The selector does not accurately convey the importance of all the rules inside it</li> <li>The <em>only</em> way to override the color blue is to use <em>another</em> <code>!important</code> declaration, for example in the <code>button#buyNow</code> selector.</li> </ol> <p>This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One <code>!important</code> leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one <code>!important</code> can be a useful short-term solution, it will come back to bite you in the ass in the long run.</p> <h3>When is it okay to use:</h3> <ul> <li>Overriding styles in a user stylesheet.</li> </ul> <p>This is what <code>!important</code> was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.</p> <ul> <li>Overriding 3rd party code &amp; inline styles.</li> </ul> <p>Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use <code>!important</code> sparingly.</p> <ul> <li>Utility classes</li> </ul> <p>Many libraries and frameworks come with utility classes like <code>.hidden</code>, <code>.error</code>, or <code>.clearfix</code>. They serve a single purpose, and often apply very few, but very important, rules. (<code>display: none</code> for a <code>.hidden</code> class, for example). These should override whatever other styles are currently on the element, and definitely warrant an <code>!important</code> if you ask me.</p> <h3>Conclusion</h3> <p>Using the <code>!important</code> declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.</p> <p>There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.</p>
3,779,763
Fast Algorithm for computing percentiles to remove outliers
<p>I have a program that needs to repeatedly compute the approximate percentile (order statistic) of a dataset in order to remove outliers before further processing. I'm currently doing so by sorting the array of values and picking the appropriate element; this is doable, but it's a noticable blip on the profiles despite being a fairly minor part of the program.</p> <p>More info:</p> <ul> <li>The data set contains on the order of up to 100000 floating point numbers, and assumed to be "reasonably" distributed - there are unlikely to be duplicates nor huge spikes in density near particular values; and if for some odd reason the distribution is odd, it's OK for an approximation to be less accurate since the data is probably messed up anyhow and further processing dubious. However, the data isn't necessarily uniformly or normally distributed; it's just very unlikely to be degenerate.</li> <li>An approximate solution would be fine, but I do need to understand <em>how</em> the approximation introduces error to ensure it's valid.</li> <li>Since the aim is to remove outliers, I'm computing two percentiles over the same data at all times: e.g. one at 95% and one at 5%.</li> <li>The app is in C# with bits of heavy lifting in C++; pseudocode or a preexisting library in either would be fine.</li> <li>An entirely different way of removing outliers would be fine too, as long as it's reasonable.</li> <li><strong><em>Update:</em></strong> It seems I'm looking for an approximate <a href="http://en.wikipedia.org/wiki/Selection_algorithm" rel="noreferrer">selection algorithm</a>.</li> </ul> <p>Although this is all done in a loop, the data is (slightly) different every time, so it's not easy to reuse a datastructure as was done <a href="https://stackoverflow.com/questions/3738349/fast-algorithm-for-repeated-calculation-of-percentile">for this question</a>.</p> <h1>Implemented Solution</h1> <p>Using the wikipedia selection algorithm as suggested by Gronim reduced this part of the run-time by about a factor 20.</p> <p>Since I couldn't find a C# implementation, here's what I came up with. It's faster even for small inputs than Array.Sort; and at 1000 elements it's 25 times faster.</p> <pre><code>public static double QuickSelect(double[] list, int k) { return QuickSelect(list, k, 0, list.Length); } public static double QuickSelect(double[] list, int k, int startI, int endI) { while (true) { // Assume startI &lt;= k &lt; endI int pivotI = (startI + endI) / 2; //arbitrary, but good if sorted int splitI = partition(list, startI, endI, pivotI); if (k &lt; splitI) endI = splitI; else if (k &gt; splitI) startI = splitI + 1; else //if (k == splitI) return list[k]; } //when this returns, all elements of list[i] &lt;= list[k] iif i &lt;= k } static int partition(double[] list, int startI, int endI, int pivotI) { double pivotValue = list[pivotI]; list[pivotI] = list[startI]; list[startI] = pivotValue; int storeI = startI + 1;//no need to store @ pivot item, it's good already. //Invariant: startI &lt; storeI &lt;= endI while (storeI &lt; endI &amp;&amp; list[storeI] &lt;= pivotValue) ++storeI; //fast if sorted //now storeI == endI || list[storeI] &gt; pivotValue //so elem @storeI is either irrelevant or too large. for (int i = storeI + 1; i &lt; endI; ++i) if (list[i] &lt;= pivotValue) { list.swap_elems(i, storeI); ++storeI; } int newPivotI = storeI - 1; list[startI] = list[newPivotI]; list[newPivotI] = pivotValue; //now [startI, newPivotI] are &lt;= to pivotValue &amp;&amp; list[newPivotI] == pivotValue. return newPivotI; } static void swap_elems(this double[] list, int i, int j) { double tmp = list[i]; list[i] = list[j]; list[j] = tmp; } </code></pre> <p><img src="https://lh5.ggpht.com/_ouyecKU9M6o/TJ4-46UveaI/AAAAAAABAl0/XtZjPbN1WWg/perf-Q9300.jpg" alt="Performance Graph"/></p> <p>Thanks, Gronim, for pointing me in the right direction!</p>
3,779,933
10
2
null
2010-09-23 15:08:19.17 UTC
10
2016-03-29 19:54:52.14 UTC
2017-05-23 11:45:25.62 UTC
null
-1
null
42,921
null
1
20
c#|c++|algorithm|percentile
17,797
<p>The histogram solution from Henrik will work. You can also use a selection algorithm to efficiently find the k largest or smallest elements in an array of n elements in O(n). To use this for the 95th percentile set k=0.05n and find the k largest elements.</p> <p>Reference:</p> <p><a href="http://en.wikipedia.org/wiki/Selection_algorithm#Selecting_k_smallest_or_largest_elements" rel="noreferrer">http://en.wikipedia.org/wiki/Selection_algorithm#Selecting_k_smallest_or_largest_elements</a></p>
4,020,131
Rails DB Migration - How To Drop a Table?
<p>I added a table that I thought I was going to need, but now no longer plan on using it. How should I remove that table?</p> <p>I've already run migrations, so the table is in my database. I figure <code>rails generate migration</code> should be able to handle this, but I haven't figured out how yet.</p> <p>I've tried: </p> <pre><code>rails generate migration drop_tablename </code></pre> <p>but that just generated an empty migration.</p> <p>What is the "official" way to drop a table in Rails?</p>
4,020,139
24
3
null
2010-10-26 01:52:32.497 UTC
116
2022-01-26 07:30:53.527 UTC
2022-01-26 07:30:53.527 UTC
null
967,621
null
27,860
null
1
565
ruby-on-rails|ruby-on-rails-3|migration|rollback|drop-table
446,788
<p>You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.</p> <p>You can find information about how to accomplish different tasks in a migration here:</p> <p><a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html" rel="noreferrer">http://api.rubyonrails.org/classes/ActiveRecord/Migration.html</a></p> <p>More specifically, you can see how to drop a table using the following approach:</p> <pre><code>drop_table :table_name </code></pre>
8,348,082
Where is data stored when using an HTML 5 Web SQL Database
<p>I just read something about HTML 5 Web SQL Databases. I did a little search on here and Google but couldn't find a simple to the point answer.</p> <p>Can someone tell me, where is the data stored when using this? In memory or a text file or something else?</p> <p>Also what browsers support this?</p>
8,348,152
4
0
null
2011-12-01 20:48:48.763 UTC
9
2016-03-31 18:58:15.707 UTC
null
null
null
null
143,030
null
1
10
html|web-sql
22,286
<p>It's stored in a SQLite database. <a href="http://caniuse.com/sql-storage" rel="noreferrer">Here</a> is a browser support chart I found: .</p> <p>That said, the W3C has officially dropped support for WebSQL in favor of IndexedDB. <a href="http://caniuse.com/indexeddb" rel="noreferrer">Here's</a> the equivalent chart for that: </p> <p>You may also want to look at <a href="http://datajs.codeplex.com/" rel="noreferrer">DataJS</a>, which is a library that abstracts some of the details of local storage and works across browsers: </p> <p>Hope that helps.</p>
8,279,981
How can I change Action Bar actions dynamically?
<p>I have an Activity with ActionBar and tab navigation. I am using the split mode, so the tabs are at the top and actions are in the bottom bar. How can I dynamically change the bottom actions? I need this because every tab has different actions.</p>
8,280,672
4
0
null
2011-11-26 16:49:53.597 UTC
16
2015-11-27 19:47:36.22 UTC
null
null
null
null
243,225
null
1
62
android|android-actionbar
53,657
<p>Since the actions are populated by the activity's options menu you can use <code>Activity#invalidateOptionsMenu()</code>. This will dump the current menu and call your activity's <code>onCreateOptionsMenu</code>/<code>onPrepareOptionsMenu</code> methods again to rebuild it.</p> <p>If you're using action bar tabs to change your fragment configuration there's a better way. Have each fragment manage its own portion of the menu. These fragments should call <a href="http://developer.android.com/reference/android/app/Fragment.html#setHasOptionsMenu%28boolean%29" rel="noreferrer"><code>setHasOptionsMenu(true)</code></a>. When fragments that have options menu items are added or removed the system will automatically invalidate the options menu and call to each fragment's <code>onCreateOptionsMenu</code>/<code>onPrepareOptionsMenu</code> methods in addition to the activity's. This way each fragment can manage its own items and you don't need to worry about performing menu switching by hand.</p>
7,734,077
MySQL - Replace Character in Columns
<p>Being a self-taught newbie, I created a large problem for myself. Before inserting data in to my database, I've been converting apostrophes (') in a string, to double quotes (""), instead of the required back-slash and apostrophe (\'), which MySQL actually requires.</p> <p>Before my table grows more than the 200,000 rows it already is, I thought it was best to rectify this issue immediately. So I did some research and found the SQL REPLACE function, which is great, but I'm now confused.</p> <p>In ASP, I was doing this:</p> <pre><code>str = Replace(str,"'","""") </code></pre> <p>If I look at my database in SQL Workbench, the symbol I converted is now a single quote ("), which has confused me a little. I understand why it changed from double to single, but I don't know which one I'm meant to be changing now. </p> <p>To go through and rectify my problem using SQL REPLACE, do I now convert single quotes (") to back-slash and apostrophes (\') or do I convert double quotes ("") to back-slash and apostrophes (\')?</p> <p>For example, this:</p> <pre><code>SQL = " SELECT REPLACE(myColumn,"""","\'") FROM myTable " </code></pre> <p>or this:</p> <pre><code>SQL = " SELECT REPLACE(myColumn,""","\'") FROM myTable " </code></pre> <p>I hope I explained myself well, any suggestions gratefully received as always. Any queries about my question, please comment.</p> <p>Many thanks</p> <p><strong>-- UPDATE --</strong></p> <p>I have tried the following queries but still fail to change the ( " ) in the data:</p> <pre><code>SELECT REPLACE(caption,'\"','\'') FROM photos WHERE photoID = 3371 SELECT REPLACE(caption,'"','\'') FROM photos WHERE photoID = 3371 SELECT REPLACE(caption,'""','\'') FROM photos WHERE photoID = 3371 </code></pre> <p>Yet if I search:</p> <pre><code>SELECT COUNT(*) FROM photos WHERE caption LIKE '%"%' </code></pre> <p>I get 16,150 rows.</p> <p><strong>-- UPDATE 2 --</strong></p> <p>Well, I have created a 'workaround'. I managed to convert an entire column pretty quickly writing an ASP script, using this SQL:</p> <pre><code>SELECT photoID, caption FROM photos WHERE caption LIKE '%""%'; </code></pre> <p>and then in ASP I did:</p> <pre><code>caption = Replace(caption,"""","\'") </code></pre> <p>But I would still like to know why I couldn't achieve that with SQL?</p>
7,734,956
4
4
null
2011-10-12 00:34:53.01 UTC
23
2015-02-11 11:01:29.493 UTC
2011-10-12 03:17:32.48 UTC
null
933,633
null
933,633
null
1
70
mysql|sql|database
149,109
<p>Just running the <code>SELECT</code> statement will have no effect on the data. You have to use an <code>UPDATE</code> statement with the <code>REPLACE</code> to make the change occur:</p> <pre><code>UPDATE photos SET caption = REPLACE(caption,'"','\'') </code></pre> <p>Here is a working sample: <a href="http://sqlize.com/7FjtEyeLAh" rel="noreferrer">http://sqlize.com/7FjtEyeLAh</a></p>
8,223,319
How to hide ajax requests from firebug console?
<p>How to hide ajax requests from firebug console or anything that shows ajax calls ? </p>
8,223,578
7
3
null
2011-11-22 07:22:34.933 UTC
14
2018-12-06 19:52:52.43 UTC
null
null
null
null
827,525
null
1
20
ajax|browser|firebug
36,879
<p>Make <a href="http://en.wikipedia.org/wiki/JSONP" rel="nofollow">JSONP</a> calls. JSONP calls are not real ajax requests (because they don't use <code>XMLHttpRequest</code> object, and they simply inject a script tag into the DOM). But they won't be shown in Firebug.</p>
7,863,285
What does y -= m < 3 mean?
<p>While looking through some example C code, I came across this: </p> <pre><code>y -= m &lt; 3; </code></pre> <p>What does this do? It it some kind of condensed for loop or something? It's impossible to google for as far as I know.</p>
7,863,291
8
7
null
2011-10-22 23:24:22.623 UTC
13
2019-11-30 08:59:19.523 UTC
2011-10-23 04:45:22.32 UTC
null
322,020
null
977,320
null
1
52
c
8,424
<p><code>m &lt; 3</code> is either <code>1</code> or <code>0</code>, depending on the truth value.</p> <p>So <code>y=y-1</code> when <code>m&lt;3</code> is <code>true</code>, or <code>y=y-0</code> when <code>m&gt;=3</code></p>
7,799,940
JFrame Exit on close Java
<p>I don't get how can I employ this code:</p> <pre><code>frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); </code></pre> <p>to close the program with the x button.</p>
7,800,013
8
4
null
2011-10-17 21:43:02.683 UTC
9
2019-05-21 10:31:08.78 UTC
2014-01-24 12:09:55.857 UTC
null
321,731
null
983,246
null
1
66
java|jframe
223,376
<p>You need the line</p> <pre><code>frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); </code></pre> <p>Because the default behaviour for the JFrame when you press the X button is the equivalent to</p> <pre><code>frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); </code></pre> <p>So almost all the times you'll need to add that line manually when creating your JFrame</p> <p>I am currently referring to constants in <code>WindowConstants</code> like <code>WindowConstants.EXIT_ON_CLOSE</code> instead of the same constants declared directly in <code>JFrame</code> as the prior reflect better the intent.</p>
4,147,952
Reading files with MIPS assembly
<p>I'm trying to write a program that reads in characters from a .dat file that correspond to different colors to be displayed in the LED simulator; x = off, R = red, etc. My problem is, I cannot figure out what I'm doing wrong with opening the .dat file. I've looked around and tried all I can think of, but each time I assemble and run, I get a -1 in $v0 signifying an error. Here's my code for opening/reading/closing the file: </p> <pre><code>.data fin: .asciiz "maze1.dat" # filename for input buffer: .asciiz "" .text #open a file for writing li $v0, 13 # system call for open file la $a0, fin # board file name li $a1, 0 # Open for reading li $a2, 0 syscall # open a file (file descriptor returned in $v0) move $s6, $v0 # save the file descriptor #read from file li $v0, 14 # system call for read from file move $a0, $s6 # file descriptor la $a1, buffer # address of buffer to which to read li $a2, 1024 # hardcoded buffer length syscall # read from file # Close the file li $v0, 16 # system call for close file move $a0, $s6 # file descriptor to close syscall # close file </code></pre> <p>The file maze1.dat is in the same directory as the MIPS program. Any help or suggestions are greatly appreciated.</p>
4,150,340
3
1
null
2010-11-10 18:54:05.977 UTC
2
2016-01-29 14:19:24.073 UTC
2013-03-04 22:13:35.503 UTC
null
717,732
null
503,585
null
1
7
file|io|mips|mars-simulator
39,696
<p>The only issue is your buffer is simply an empty string, which is only reserving one byte (null byte). You should instead use <code>buffer: .space 1024</code> or however many bytes you need. Everything else seems fine.</p> <p>If you are having trouble opening the file, make sure the extension is exactly correct. But my test just worked a .dat file and a few random text files.</p>
14,611,259
How to adjust the distance between the y-label and the y-axis in Matlab?
<p>In Matlab, if we do not rotate the y-label that contains several letters, the label may overlap with the tick numbers or even the y-axis. We can increase the distance between the y-label and the y-axis in the following way:</p> <pre><code>plot(A, B); y=ylabel('xxx', 'rot', 0); % do not rotate the y label set(y, 'position', get(y,'position')-[0.1,0,0]); % shift the y label to the left by 0.1 </code></pre> <p>However, a problem is that if we change <code>axis([0 1 0 25])</code> to <code>axis([0 10 0 25])</code>, the distance between the y-label and the y-axis will also change. Is there a convenient way to shift the y-label slightly to the left, but keep the distance between the y-label and the y-axis constant when we change the range of x?</p>
14,612,014
1
0
null
2013-01-30 18:35:47.733 UTC
3
2013-01-30 19:22:10.713 UTC
null
null
null
null
1,536,711
null
1
6
matlab|matlab-figure
46,142
<p>You can use normalized units for the y-label position. Try this:</p> <pre><code>set(y, 'Units', 'Normalized', 'Position', [-0.1, 0.5, 0]); </code></pre> <p>Normalized units are always relative to [0 1], so the range of your data doesn't matter.</p>
4,384,098
In Django models.py, what's the difference between default, null, and blank?
<ul> <li><code>null=True</code></li> <li><code>blank=True</code></li> <li><code>default = 0</code></li> </ul> <p>What's the difference? When do you use what?</p>
4,384,131
5
0
null
2010-12-08 04:12:45.22 UTC
22
2020-01-24 14:42:51.42 UTC
2019-01-22 22:30:04.06 UTC
null
6,813,490
null
179,736
null
1
74
python|database|django|string|integer
34,330
<p>Direct from <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/" rel="noreferrer">Django model field reference</a>:</p> <blockquote> <p><strong><code>Field.null</code></strong></p> <p>If <code>True</code>, Django will store empty values as <code>NULL</code> in the database. Default is <code>False</code>.</p> <p>Note that empty string values will always get stored as empty strings, not as <code>NULL</code>. Only use <code>null=True</code> for non-string fields such as integers, booleans and dates. For both types of fields, you will also need to set <code>blank=True</code> if you wish to permit empty values in forms, as the <code>null</code> parameter only affects database storage (see <code>blank</code>).</p> <p>Avoid using <code>null</code> on string-based fields such as <code>CharField</code> and <code>TextField</code> unless you have an excellent reason. If a string-based field has <code>null=True</code>, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” Django convention is to use the empty string, not <code>NULL</code>.</p> </blockquote> <p>&#32;</p> <blockquote> <p><strong><code>Field.blank</code></strong></p> <p>If <code>True</code>, the field is allowed to be blank. Default is <code>False</code>.</p> <p>Note that this is different than <code>null</code>. <code>null</code> is purely database-related, whereas <code>blank</code> is validation-related. If a field has <code>blank=True</code>, validation on Django’s admin site will allow entry of an empty value. If a field has <code>blank=False</code>, the field will be required.</p> </blockquote> <p>&#32;</p> <blockquote> <p><strong><code>Field.default</code></strong></p> <p>The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.</p> </blockquote>
4,489,012
Does C have a standard ABI?
<p>From a discussion <a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=590148" rel="noreferrer">somewhere else</a>:</p> <blockquote> <p>C++ has no standard ABI (Application Binary Interface)</p> <p>But neither does C, right?</p> <p>On any given platform it pretty much does. It wouldn't be useful as the lingua franca for inter-language communication if it lacked one.</p> </blockquote> <p>What's your take on this?</p>
4,490,480
9
9
null
2010-12-20 11:03:57.943 UTC
17
2021-07-21 17:18:36.143 UTC
2021-02-03 18:58:30.343 UTC
null
1,783,588
null
252,000
null
1
39
c|abi
26,767
<p>C defines no ABI. In fact, it bends over backwards to avoid defining an ABI. Those people, who like me, who have spent most of their programming lives programming in C on 16/32/64 bit architectures with 8 bit bytes, 2's complement arithmetic and flat address spaces, will usually be quite surprised on reading the convoluted language of the current C standard. </p> <p>For example, read the stuff about pointers. The standard doesn't say anything so simple as "a pointer is an address" for that would be making an assumption about the ABI. In particular, it allows for pointers being in different address spaces and having varying width.</p> <p>An ABI is a mapping from the execution model of the language to a particular machine/operating system/compiler combination. It makes no sense to define one in the language specification because that runs the risk of excluding C implementations on some architectures.</p>
14,518,195
How can I add new item to the String array?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2843366/how-to-add-new-elements-to-a-string-array">how to add new elements to a String[] array?</a> </p> </blockquote> <p>How can I add new item to the String array ? I am trying to add item to the initially empty String. Example :</p> <pre><code> String a []; a.add("kk" ); a.add("pp"); </code></pre>
14,518,450
5
1
null
2013-01-25 08:42:05.46 UTC
5
2018-08-09 03:59:44.933 UTC
2017-05-23 11:47:20.577 UTC
null
-1
null
2,007,418
null
1
25
java|arrays
257,702
<p>From <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html" rel="noreferrer">arrays</a> </p> <blockquote> <p>An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.</p> </blockquote> <p><img src="https://i.stack.imgur.com/opErm.gif" alt="enter image description here"></p> <p>So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.</p> <pre><code>String[] arr = new String[10]; // 10 is the length of the array. arr[0] = "kk"; arr[1] = "pp"; ... </code></pre> <p>So if your requirement is to add many objects, it's recommended that you use Lists like:</p> <pre><code>List&lt;String&gt; a = new ArrayList&lt;String&gt;(); a.add("kk"); a.add("pp"); </code></pre>
14,696,568
Avoid Unit of Work pattern in domain driven design
<p>I have read this and it makes me think twice...:</p> <p>"Avoid unit of work pattern. Aggregate roots should define transaction boundaries."</p> <p>Why should someone avoid the UOW pattern applying domain driven design?</p>
14,703,115
3
0
null
2013-02-04 22:07:33.997 UTC
9
2021-02-11 13:21:37.803 UTC
null
null
null
null
320,460
null
1
26
domain-driven-design|unit-of-work|aggregateroot
15,377
<p>(Before my post I recommend to read <a href="http://my.safaribooksonline.com/book/project-management/9780133039900/chapter-1dot-getting-started-with-ddd/ch01lev1sec2_html#X2ludGVybmFsX0h0bWxWaWV3P3htbGlkPTk3ODAxMzMwMzk5MDAlMkZjaDEwX2h0bWwmcXVlcnk9" rel="noreferrer">this chapter</a> of "Implementing Domain-Driven Design" book by V. Vernon. It can help to get close with aggregates and contain long answer on your question.)</p> <p>In a properly designed system one command changes one aggregate at a time, every aggregate has boundaries which defined by invariants in aggregate root. So when you do any changes on aggregate, invariants are checked and changes are applied (or not) in one transaction. It's <em>transaction consistency</em>. Do you need to use Unit of Work here? Don't think so.</p> <p>But quite often we are in situation when more then one aggregate need to be changed at one time. Transactions become larger, they touch more then one part of a system and we talk about <em>eventual consistency</em>. UoW is a good helper in this case.</p> <p>As it has been mentioned with no context it's hard to guess what author was thinking, but I suppose he told about transaction consistency case. In distributed system you will need to use something like UoW to provide eventual consistency to a system.</p>
14,378,437
Find component by ID in JSF
<p>I want to find some <code>UIComponent</code> from managed bean by the id that I have provided. </p> <p>I have written the following code:</p> <pre><code>private UIComponent getUIComponent(String id) { return FacesContext.getCurrentInstance().getViewRoot().findComponent(id) ; } </code></pre> <p>I have defined a <code>p:inputTextarea</code> as:</p> <pre><code>&lt;p:inputTextarea id="activityDescription" value="#{adminController.activityDTO.activityDescription}" required="true" maxlength="120" autoResize="true" counter="counter" counterTemplate="{0} characters remaining." cols="80" rows="2" /&gt; </code></pre> <p>Now if a call to the method as <code>getUIComponent("activityDescription")</code> it is returning <code>null</code>, but if I call it as <code>getUIComponent("adminTabView:activityForm:activityDescription")</code> then I can get the <code>org.primefaces.component.inputtextarea.InputTextarea</code> instance. </p> <p>Is there any way to get the component with only the id i.e., "activityDescription" not the absolute id i.e., "adminTabView:activityForm:activityDescription"?</p>
14,379,356
5
4
null
2013-01-17 11:49:54.093 UTC
17
2021-07-13 09:49:59.333 UTC
2021-07-13 09:49:59.333 UTC
null
157,882
null
576,758
null
1
52
jsf|uicomponents
105,542
<p>You can use the following code:</p> <pre><code>public UIComponent findComponent(final String id) { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); final UIComponent[] found = new UIComponent[1]; root.visitTree(new FullVisitContext(context), new VisitCallback() { @Override public VisitResult visit(VisitContext context, UIComponent component) { if (component != null &amp;&amp; id.equals(component.getId())) { found[0] = component; return VisitResult.COMPLETE; } return VisitResult.ACCEPT; } }); return found[0]; } </code></pre> <p>This code will find only the first component in the tree with the <code>id</code> you pass. You will have to do something custom if there are 2 components with the same name in the tree (this is possible if they are under 2 different naming containers).</p>
14,384,354
Force google account chooser
<p>Is there is a way I can force the <strong>google account chooser</strong> to appear even if the user is logged in just with one account.</p> <p>I have tried by redirecting to this URL:</p> <pre><code>https://accounts.google.com/AccountChooser?service=lso&amp;continue=[authorizeurl] </code></pre> <p>and it seems to work, but I don't know if there are any other conditions in which it might fail.</p> <p><img src="https://i.stack.imgur.com/GWLSa.png" alt="enter image description here"></p>
14,393,492
5
0
null
2013-01-17 17:08:52.06 UTC
21
2019-06-18 09:21:10.98 UTC
2013-01-17 17:17:08.1 UTC
null
1,760,291
null
234,047
null
1
63
google-oauth
34,351
<p>The following parameter is supported in OAuth2 authorization URLs:</p> <p><code>prompt</code></p> <p>Currently it can have values <code>none</code>, <code>select_account</code>, and <code>consent</code>.</p> <ul> <li><p>none: Will cause Google to not show any UI, and therefore fail if user needs to login, or select an account in case of multi-login, or consent if first approval. It can be run in an invisible i-frame to obtain a token from previously authorized users before you decide, for instance, to render an authorization button.</p></li> <li><p>consent: Will force the approval page to be displayed even if the user has previously authorized your application. May be useful in a few corner cases, for instance if you lost the refresh_token for the user, as Google only issues refresh_tokens on explicit consent action.</p></li> <li><p>select_account: Will cause the account selector to display, even if there's a single logged-in user, just as you asked.</p></li> </ul> <p><code>select_account</code> can be combined with <code>consent</code>, as in:</p> <p><code>prompt=select_account consent</code></p>
46,715,484
Correct async function export in node.js
<p>I had my custom module with following code:</p> <pre><code>module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) { ... } </code></pre> <p>It worked fine if call the function outside my module, however if I called inside I got error while running:</p> <blockquote> <p>(node:24372) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: PrintNearestStore is not defined</p> </blockquote> <p>When I changed syntax to:</p> <pre><code>module.exports.PrintNearestStore = PrintNearestStore; var PrintNearestStore = async function(session, lat, lon) { } </code></pre> <p>It started to work fine inside module, but fails outside the module - I got error:</p> <blockquote> <p>(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is not a function</p> </blockquote> <p>So I've changed code to:</p> <pre><code>module.exports.PrintNearestStore = async function(session, lat, lon) { await PrintNearestStore(session, lat, lon); } var PrintNearestStore = async function(session, lat, lon) { ... } </code></pre> <p>And now it works in all cases: inside and outside. However want to understand semantics and if there is more beautiful and shorter way to write it? How to correctly define and use <strong>async</strong> function both: inside and outside (exports) module?</p>
46,715,585
5
0
null
2017-10-12 17:21:58.097 UTC
15
2022-02-08 06:27:17.893 UTC
null
null
null
null
630,169
null
1
88
javascript|node.js|async-await
164,473
<p>This doesn't really have anything to with async functions specially. If you want to call a function internally <em>and</em> export it, define it <em>first</em> and then export it.</p> <pre><code>async function doStuff() { // ... } // doStuff is defined inside the module so we can call it wherever we want // Export it to make it available outside module.exports.doStuff = doStuff; </code></pre> <hr> <p>Explanation of the problems with your attempts:</p> <pre><code>module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) { ... } </code></pre> <p>This does not define a function in the module. The function definition is a function <em>expression</em>. The name of a function expression only creates a variable inside the function itself. Simpler example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var foo = function bar() { console.log(typeof bar); // 'function' - works }; foo(); console.log(typeof foo); // 'function' - works console.log(typeof bar); // 'undefined' - there is no such variable `bar`</code></pre> </div> </div> </p> <p>See also <a href="https://kangax.github.io/nfe/" rel="noreferrer">Named function expressions demystified</a>. You could of course refer to the function if you'd refer to <code>module.exports.PrintNearestStore</code> everywhere.</p> <hr> <pre><code>module.exports.PrintNearestStore = PrintNearestStore; var PrintNearestStore = async function(session, lat, lon) { } </code></pre> <p>This is <em>almost</em> OK. The problem is that the value of <code>PrintNearestStore</code> is <code>undefined</code> when you assign it to <code>module.exports.PrintNearestStore</code>. The order of execution is:</p> <pre><code>var PrintNearestStore; // `undefined` by default // still `undefined`, hence `module.exports.PrintNearestStore` is `undefined` module.exports.PrintNearestStore = PrintNearestStore; PrintNearestStore = async function(session, lat, lon) {} // now has a function as value, but it's too late </code></pre> <p>Simpler example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var foo = bar; console.log(foo, bar); // logs `undefined`, `undefined` because `bar` is `undefined` var bar = 21; console.log(foo, bar); // logs `undefined`, `21`</code></pre> </div> </div> </p> <p>If you changed the order it would work as expected.</p> <hr> <pre><code>module.exports.PrintNearestStore = async function(session, lat, lon) { await PrintNearestStore(session, lat, lon); } var PrintNearestStore = async function(session, lat, lon) { ... } </code></pre> <p>This works because <em>by the time</em> the function assigned to <code>module.exports.PrintNearestStore</code> <em>is executed</em>, <code>PrintNearestStore</code> has the function as its value.</p> <p>Simpler example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var foo = function() { console.log(bar); }; foo(); // logs `undefined` var bar = 21; foo(); // logs `21`</code></pre> </div> </div> </p>
55,322,434
How to clear CUDA memory in PyTorch
<p>I am trying to get the output of a neural network which I have already trained. The input is an image of the size 300x300. I am using a batch size of 1, but I still get a <code>CUDA error: out of memory</code> error after I have successfully got the output for 25 images.</p> <p>I tried <code>torch.cuda.empty_cache()</code>, but this still doesn't seem to solve the problem. Code:</p> <pre><code>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;) train_x = torch.tensor(train_x, dtype=torch.float32).view(-1, 1, 300, 300) train_x = train_x.to(device) dataloader = torch.utils.data.DataLoader(train_x, batch_size=1, shuffle=False) right = [] for i, left in enumerate(dataloader): print(i) temp = model(left).view(-1, 1, 300, 300) right.append(temp.to('cpu')) del temp torch.cuda.empty_cache() </code></pre> <p>This <code>for loop</code> runs for 25 times every time before giving the memory error.</p> <p>Every time, I am sending a new image in the network for computation. So, I don't really need to store the previous computation results in the GPU after every iteration in the loop. Is there any way to achieve this?</p>
55,340,037
1
0
null
2019-03-24 09:38:43.133 UTC
17
2022-03-29 07:32:31.303 UTC
2022-03-29 07:32:31.303 UTC
null
365,102
null
9,536,387
null
1
52
python|pytorch
91,264
<p>I figured out where I was going wrong. I am posting the solution as an answer for others who might be struggling with the same problem.</p> <p>Basically, what PyTorch does is that it creates a computational graph whenever I pass the data through my network and stores the computations on the GPU memory, in case I want to calculate the gradient during backpropagation. But since I only wanted to perform a forward propagation, I simply needed to specify <code>torch.no_grad()</code> for my model.</p> <p>Thus, the for loop in my code could be rewritten as:</p> <pre><code>for i, left in enumerate(dataloader): print(i) with torch.no_grad(): temp = model(left).view(-1, 1, 300, 300) right.append(temp.to('cpu')) del temp torch.cuda.empty_cache() </code></pre> <p>Specifying <code>no_grad()</code> to my model tells PyTorch that I don't want to store any previous computations, thus freeing my GPU space.</p>
57,410,051
Chrome not showing OPTIONS requests in Network tab
<p>My web client application is setting HTTP POST requests via fetch API. </p> <p>I see that OPTIONS preflight requests are sent via debugging proxy (Charles Proxy), but they are not displayed in Google Chrome Developer Tools\Network tab. </p> <p>I don't have any filters setup on the network tab. I remember OPTIONS requests being visible there, but not anymore. How do I bring them back?</p>
57,631,040
4
0
null
2019-08-08 10:03:49.453 UTC
29
2021-04-17 09:21:38.293 UTC
2019-08-08 10:10:48.34 UTC
null
1,384,013
null
1,384,013
null
1
117
google-chrome|cors|google-chrome-devtools|preflight
70,744
<p>You'll need to go to: <code>chrome://flags/#out-of-blink-cors</code>, <strong>disable</strong> the flag, and restart Chrome.</p> <p>This is an expected behavior change according to:<br> <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=995740#c1" rel="noreferrer">https://bugs.chromium.org/p/chromium/issues/detail?id=995740#c1</a></p> <p>I originally came across this via:<br> <a href="https://support.google.com/chrome/thread/11089651?hl=en" rel="noreferrer">https://support.google.com/chrome/thread/11089651?hl=en</a></p>
23,240,969
Python: count repeated elements in the list
<p>I am new to Python. I am trying to find a simple way of getting a count of the number of elements repeated in a list e.g.</p> <pre><code>MyList = ["a", "b", "a", "c", "c", "a", "c"] </code></pre> <p>Output:</p> <pre><code>a: 3 b: 1 c: 3 </code></pre>
23,240,989
5
0
null
2014-04-23 10:00:57.903 UTC
27
2022-07-27 17:47:54.337 UTC
2018-02-24 08:01:59.26 UTC
null
3,961,903
null
3,557,527
null
1
73
python|python-2.7
289,895
<p>You can do that using <strong><code>count</code></strong>:</p> <pre><code>my_dict = {i:MyList.count(i) for i in MyList} &gt;&gt;&gt; print my_dict #or print(my_dict) in python-3.x {'a': 3, 'c': 3, 'b': 1} </code></pre> <p><strong>Or</strong> using <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="noreferrer"><strong><code>collections.Counter</code></strong></a>:</p> <pre><code>from collections import Counter a = dict(Counter(MyList)) &gt;&gt;&gt; print a #or print(a) in python-3.x {'a': 3, 'c': 3, 'b': 1} </code></pre>
2,054,635
Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates
<p>I need a function to get an nearest address or city from coordinates(lat,long) using google map api reverse geocoding and php... Please give some sample code</p>
2,054,675
1
0
null
2010-01-13 05:24:10.397 UTC
10
2015-07-13 11:04:35.327 UTC
2010-01-13 11:41:01.633 UTC
null
73,488
null
1,486,512
null
1
15
php|google-maps|google-code|reverse-geocoding
43,535
<p>You need to use the <a href="http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder.getLocations" rel="nofollow noreferrer">getLocations</a> method on the <a href="http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder" rel="nofollow noreferrer">GClientGeocoder</a> object in the <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps API</a></p> <pre><code>var point = new GLatLng (43,-75); var geocoder = new GClientGeocoder(); geocoder.getLocations (point, function(result) { // access the address from the placemarks object alert (result.address); }); </code></pre> <p><strong>EDIT</strong>: Ok. You are doing this stuff server side. This means you need to use the <a href="http://code.google.com/apis/maps/documentation/geocoding/index.html#ReverseGeocoding" rel="nofollow noreferrer">HTTP Geocoding service</a>. To do this you will need to make an HTTP request using the URL format described in the linked article. You can parse the HTTP response and pull out the address:</p> <pre><code>// set your API key here $api_key = ""; // format this string with the appropriate latitude longitude $url = 'http://maps.google.com/maps/geo?q=40.714224,-73.961452&amp;output=json&amp;sensor=true_or_false&amp;key=' . $api_key; // make the HTTP request $data = @file_get_contents($url); // parse the json response $jsondata = json_decode($data,true); // if we get a placemark array and the status was good, get the addres if(is_array($jsondata )&amp;&amp; $jsondata ['Status']['code']==200) { $addr = $jsondata ['Placemark'][0]['address']; } </code></pre> <p><strong>N.B.</strong> The <a href="http://code.google.com/apis/maps/documentation/geocoding/index.html#Geocoding" rel="nofollow noreferrer">Google Maps terms of service</a> explicitly states that geocoding data without putting the results on a Google Map is prohibited.</p>
39,902,197
How can i pass webpack environment variables in html?
<p>How can i get / access webpack ENV variables during process time (not runtime in browser) ? the <code>webpack.DefinePlugin(...)</code> doesn't seem to work in html files, i don't have access to ENV variables in the main <code>index.html</code></p> <p>any solution ?</p>
42,239,310
2
0
null
2016-10-06 17:25:58.913 UTC
4
2018-08-26 19:11:00.457 UTC
null
null
null
null
807,503
null
1
36
webpack|environment-variables
25,956
<p>You can use <a href="https://www.npmjs.com/package/html-webpack-plugin" rel="noreferrer">html-webpack-plugin</a>. You will have to use .ejs or some other template language and then use like that </p> <pre><code>new HtmlWebpackPlugin({ template: './src/public/index.ejs', inject: 'body', environment: process.env.NODE_ENV }), </code></pre> <p>in index.ejs</p> <pre><code>&lt;body class="&lt;%= htmlWebpackPlugin.options.environment %&gt;"&gt; </code></pre>
27,144,702
How to reset 'display' property for flex-item
<p>I'm trying to convert old layout based on tables and JS to the new Flexbox with backward compatibility by keeping the tables for old browsers (specifically IE8, IE9 and Opera 10+).</p> <p>The problem is that there is no <code>display:flex-item</code> to override the old style of <code>display:table-cell</code>.</p> <p>I've tried various definitions like <code>display:inherit</code>, <code>display:initial</code> but none is able to reset the display definition to work correctly as flex-item.</p> <pre><code>&lt;!-- HTML user list --&gt; &lt;div class="userDetails layout"&gt; &lt;div class="picture"&gt;&lt;img src="..."&gt;&lt;/div&gt; &lt;div class="details"&gt;username, email, etc.&lt;/div&gt; &lt;/div&gt; /* CSS Table Layout */ .layout { display: table; width: 100%; } .layout &gt; .picture { display: table-cell; width: 30%; } .layout &gt; .details { display: table-cell; width: auto; } /* CSS Flexbox - ignored by browsers that does not support it */ /* just an example - should use all versions for best compatibility */ .layout { display: flex; } .layout &gt; .picture { display: ???; flex: 0 1 30%; } .layout &gt; .details { display: ???; flex: 1 1 auto; } </code></pre> <p>Whatever I set in display for the <code>.details</code> it does not work as flex-item and does not <em>grow</em> to fill the remaining space.</p> <p>Any idea how to override this without using JS to detect browser version and switch the styles?</p> <p><em>I've tried googling for solution but most of the results are just general articles about Flexbox; only similar is <a href="http://benfrain.com/css-performance-test-flexbox-v-css-table-fight/" rel="noreferrer">this test</a> which simply does not solve the backward compatility.</em></p> <p>UPDATE 1: This is a <a href="http://jsfiddle.net/nothrem/do525ff3/2/" rel="noreferrer">JSFiddle demo</a> of a pure Flexbox and Flexbox combined with table layout. If you resize the result window, the pure layout shrinks differently than the bottom one that combine table and Flexbox. Note: in Chrome this works correctly, try it in Firefox, IE, Safari, etc.</p> <p>UPDATE 2: Safari works correctly with prefixed definitions... <a href="http://jsfiddle.net/nothrem/do525ff3/2/" rel="noreferrer">updated JSFiddle demo</a></p>
27,146,937
3
0
null
2014-11-26 08:47:45.283 UTC
4
2017-11-19 06:31:17.947 UTC
2014-11-26 10:25:45.163 UTC
null
2,011,448
null
2,011,448
null
1
16
css|tablelayout|flexbox
103,831
<p>As Danield has mentioned, all children of a flex container (designated by <code>display: flex</code> or <code>display: inline-flex</code>) are automatically made flex items. There is no <code>display</code> property for a flex item; instead, you set it to some other value depending on how you want the children <em>of the flex item</em> to be laid out. If browsers are recognizing <code>display: flex-item</code>, then they probably have some weird non-standard implementation of "flexbox", because that value has never existed in any incarnation of the Flexbox spec (and I have no idea what exactly it would correspond to if it did).</p> <p>The initial value of <code>display</code> is <code>inline</code>, so <code>display: initial</code> is equivalent to <code>display: inline</code>. See <a href="https://stackoverflow.com/questions/8228980/reset-css-display-property-to-default-value/8229026#8229026">this answer</a>. What you're trying to do is reset the elements to whatever their default <code>display</code> is as given by browsers. You will need to know this value in advance; for <code>div</code> elements it's <code>display: block</code>.</p> <p>Unfortunately, this will override the existing <code>table-cell</code> declaration in all browsers, for obvious reasons. In that case, you might as well just stick with the table layout if it already works for you, if you need to support browsers that don't support flexbox.</p>
44,800,659
How define constructor implementation for an Abstract Class in Python?
<p>I am trying to declare an abstract class <code>A</code> with a constructor with a default behavior: all subclasses must initialize a member <code>self.n</code>:</p> <pre><code>from abc import ABCMeta class A(object): __metaclass__ = ABCMeta def __init__(self, n): self.n = n </code></pre> <p>However, I do not want to let the <code>A</code> class be instantiated because, well, it is an abstract class. The problem is, this is actually allowed:</p> <pre><code>a = A(3) </code></pre> <p>This produces no errors, when I would expect it should.</p> <p>So: how can I define an un-instantiable abstract class while defining a default behavior for the constructor?</p>
44,800,925
6
1
null
2017-06-28 11:02:34.737 UTC
7
2021-02-15 13:32:22.48 UTC
2020-08-07 19:29:15.197 UTC
null
5,780,109
null
3,120,489
null
1
67
python|python-2.7|oop|abstract-class
67,110
<p>Making the <code>__init__</code> an abstract method:</p> <pre><code>from abc import ABCMeta, abstractmethod class A(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self, n): self.n = n if __name__ == '__main__': a = A(3) </code></pre> <p>helps:</p> <pre><code>TypeError: Can't instantiate abstract class A with abstract methods __init__ </code></pre> <p>Python 3 version:</p> <pre><code>from abc import ABCMeta, abstractmethod class A(object, metaclass=ABCMeta): @abstractmethod def __init__(self, n): self.n = n if __name__ == '__main__': a = A(3) </code></pre> <p>Works as well:</p> <pre><code>TypeError: Can't instantiate abstract class A with abstract methods __init__ </code></pre>
54,031,546
How to create an empty list in Dart
<p>I want to create an empty list for a Flutter project.</p> <pre><code>final prefs = await SharedPreferences.getInstance(); final myStringList = prefs.getStringList('my_string_list_key') ?? &lt;empty list&gt;; </code></pre> <p>I seem to remember there are multiple ways but one recommended way. How do I do it?</p>
54,031,547
3
0
null
2019-01-04 00:11:03.81 UTC
1
2022-06-09 18:19:39.253 UTC
2019-11-22 01:00:47.607 UTC
null
3,681,880
null
3,681,880
null
1
64
list|dart|flutter
59,696
<p>There are a few ways to create an empty list in Dart. If you want a growable list then use an empty list literal like this:</p> <pre><code>[] </code></pre> <p>Or this if you need to specify the type:</p> <pre><code>&lt;String&gt;[] </code></pre> <p>Or this if you want a non-growable (fixed-length) list:</p> <pre><code>List.empty() </code></pre> <h3>Notes</h3> <ul> <li>In the past you could use <code>List()</code> but this is now deprecated. The reason is that <code>List()</code> did not initialize any members, and that isn't compatible with null safe code. Read <a href="https://dart.dev/null-safety/understanding-null-safety#no-unnamed-list-constructor" rel="noreferrer">Understanding null safety: No unnamed List constructor</a> for more.</li> <li><a href="https://www.dartlang.org/guides/language/effective-dart/usage#do-use-collection-literals-when-possible" rel="noreferrer">Effective Dart Usage Guide</a></li> </ul>
33,621,319
Spark / Scala: forward fill with last observation
<p>Using Spark 1.4.0, Scala 2.10</p> <p>I've been trying to figure out a way to forward fill null values with the last known observation, but I don't see an easy way. I would think this is a pretty common thing to do, but can't find an example showing how to do this.</p> <p>I see functions to forward fill NaN with a value, or lag / lead functions to fill or shift data by an offset, but nothing to pick up the last known value.</p> <p>Looking online, I see lots of Q/A about the same thing in R, but not in Spark / Scala.</p> <p>I was thinking about mapping over a date range, filter the NaNs out of the results and pick the last element but I guess I'm confused about the syntax.</p> <p>Using DataFrames I try something like</p> <pre><code>import org.apache.spark.sql.expressions.Window val sqlContext = new HiveContext(sc) var spec = Window.orderBy("Date") val df = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").load("test.csv") val df2 = df.withColumn("testForwardFill", (90 to 0).map(i=&gt;lag(df.col("myValue"),i,0).over(spec)).filter(p=&gt;p.getItem.isNotNull).last) </code></pre> <p>but that doesn't get me anywhere.</p> <p> The filter part doesn't work; the map function returns a Sequence of spark.sql.Columns, but the filter function expects to return a Boolean, so I need to get a value out of the Column to test on but there only seem to be Column methods that return a Column. </p> <p>Is there any way to do this more 'simply' on Spark?</p> <p>Thanks for your input</p> <p><strong>Edit</strong>:</p> <p>Simple example sample input:</p> <pre class="lang-none prettyprint-override"><code>2015-06-01,33 2015-06-02, 2015-06-03, 2015-06-04, 2015-06-05,22 2015-06-06, 2015-06-07, ... </code></pre> <p>Expected output:</p> <pre class="lang-none prettyprint-override"><code>2015-06-01,33 2015-06-02,33 2015-06-03,33 2015-06-04,33 2015-06-05,22 2015-06-06,22 2015-06-07,22 </code></pre> <p><strong>Note</strong>:</p> <ol> <li>I have many columns, many of which have this missing data pattern, but not at the same date/time. If I need to I will do the transform one column at a time.</li> </ol> <p><strong>EDIT</strong>:</p> <p>Following @zero323 's answer I tried this way:</p> <pre><code> import org.apache.spark.sql.Row import org.apache.spark.rdd.RDD val rows: RDD[Row] = df.orderBy($"Date").rdd def notMissing(row: Row): Boolean = { !row.isNullAt(1) } val toCarry: scala.collection.Map[Int,Option[org.apache.spark.sql.Row]] = rows.mapPartitionsWithIndex{ case (i, iter) =&gt; Iterator((i, iter.filter(notMissing(_)).toSeq.lastOption)) } .collectAsMap val toCarryBd = sc.broadcast(toCarry) def fill(i: Int, iter: Iterator[Row]): Iterator[Row] = { if (iter.contains(null)) iter.map(row =&gt; Row(toCarryBd.value(i).get(1))) else iter } val imputed: RDD[Row] = rows.mapPartitionsWithIndex{ case (i, iter) =&gt; fill(i, iter)} </code></pre> <p>the broadcast variable ends up as a list of values without nulls. That's progress but I still can't get the mapping to work. but i get nothing, because the index <code>i</code> in the doesn't map to the original data, it maps to the subset without null.</p> <p>What am I missing here?</p> <p><strong>EDIT and solution (as infered from @zero323 's answer):</strong></p> <pre><code>import org.apache.spark.sql.expressions.Window val sqlContext = new HiveContext(sc) var spec = Window.partitionBy("id").orderBy("Date") val df = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").load("test.csv") val df2 = df.withColumn("test", coalesce((0 to 90).map(i=&gt;lag(df.col("test"),i,0).over(spec)): _*)) </code></pre> <p>See zero323's answer below for more options if you're using RDDs instead of DataFrames. The solution above may not be the most efficient but works for me. If you're looking to optimize, check out the RDD solution.</p>
33,622,083
2
0
null
2015-11-10 01:24:21.417 UTC
18
2022-09-19 19:26:41.813 UTC
2019-01-11 12:31:05.173 UTC
null
1,560,062
null
2,494,262
null
1
31
scala|apache-spark|apache-spark-sql
13,900
<h2>Initial answer (a single time series assumption):</h2> <p>First of all try avoid window functions if you cannot provide <code>PARTITION BY</code> clause. It moves data to a single partition so most of the time it is simply not feasible.</p> <p>What you can do is to fill gaps on <code>RDD</code> using <code>mapPartitionsWithIndex</code>. Since you didn't provide an example data or expected output consider this to be pseudocode not a real Scala program:</p> <ul> <li><p>first lets order <code>DataFrame</code> by date and convert to <code>RDD</code></p> <pre><code>import org.apache.spark.sql.Row import org.apache.spark.rdd.RDD val rows: RDD[Row] = df.orderBy($"Date").rdd </code></pre></li> <li><p>next lets find the last not null observation per partition </p> <pre><code>def notMissing(row: Row): Boolean = ??? val toCarry: scala.collection.Map[Int,Option[org.apache.spark.sql.Row]] = rows .mapPartitionsWithIndex{ case (i, iter) =&gt; Iterator((i, iter.filter(notMissing(_)).toSeq.lastOption)) } .collectAsMap </code></pre></li> <li><p>and convert this <code>Map</code> to broadcast</p> <pre><code>val toCarryBd = sc.broadcast(toCarry) </code></pre></li> <li><p>finally map over partitions once again filling the gaps:</p> <pre><code>def fill(i: Int, iter: Iterator[Row]): Iterator[Row] = { // If it is the beginning of partition and value is missing // extract value to fill from toCarryBd.value // Remember to correct for empty / only missing partitions // otherwise take last not-null from the current partition } val imputed: RDD[Row] = rows .mapPartitionsWithIndex{ case (i, iter) =&gt; fill(i, iter) } </code></pre></li> <li><p>finally convert back to DataFrame</p></li> </ul> <h2>Edit (partitioned / time series per group data):</h2> <p>The devil is in the detail. If your data is partitioned after all then a whole problem can be solved using <code>groupBy</code>. Lets assume you simply partition by column "v" of type <code>T</code> and <code>Date</code> is an integer timestamp: </p> <pre><code>def fill(iter: List[Row]): List[Row] = { // Just go row by row and fill with last non-empty value ??? } val groupedAndSorted = df.rdd .groupBy(_.getAs[T]("k")) .mapValues(_.toList.sortBy(_.getAs[Int]("Date"))) val rows: RDD[Row] = groupedAndSorted.mapValues(fill).values.flatMap(identity) val dfFilled = sqlContext.createDataFrame(rows, df.schema) </code></pre> <p>This way you can fill all columns at the same time.</p> <blockquote> <p>Can this be done with DataFrames instead of converting back and forth to RDD?</p> </blockquote> <p>It depends, although it is unlikely to be efficient. If maximum gap is relatively small you can do something like this:</p> <pre><code>import org.apache.spark.sql.functions._ import org.apache.spark.sql.expressions.{WindowSpec, Window} import org.apache.spark.sql.Column val maxGap: Int = ??? // Maximum gap between observations val columnsToFill: List[String] = ??? // List of columns to fill val suffix: String = "_" // To disambiguate between original and imputed // Take lag 1 to maxGap and coalesce def makeCoalesce(w: WindowSpec)(magGap: Int)(suffix: String)(c: String) = { // Generate lag values between 1 and maxGap val lags = (1 to maxGap).map(lag(col(c), _)over(w)) // Add current, coalesce and set alias coalesce(col(c) +: lags: _*).alias(s"$c$suffix") } // For each column you want to fill nulls apply makeCoalesce val lags: List[Column] = columnsToFill.map(makeCoalesce(w)(maxGap)("_")) // Finally select val dfImputed = df.select($"*" :: lags: _*) </code></pre> <p>It can be easily adjusted to use different maximum gap per column.</p> <p>A simpler way to achieve a similar result in the latest Spark version is to use <code>last</code> with <code>ignoreNulls</code>:</p> <pre><code>import org.apache.spark.sql.functions._ import org.apache.spark.sql.expressions.Window val w = Window.partitionBy($"k").orderBy($"Date") .rowsBetween(Window.unboundedPreceding, -1) df.withColumn("value", coalesce($"value", last($"value", true).over(w))) </code></pre> <p>While it is possible to drop <code>partitionBy</code> clause and apply this method globally, it would prohibitively expensive with large datasets.</p>
30,001,051
:app:dexDebug ExecException finished with non-zero exit value 2
<p>Could anyone help me out with the following error. When i clean the project, it doesn't show any error but every time i try to run i get this message. </p> <p>Error:Execution failed for task ':app:dexDebug'.</p> <blockquote> <p>com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_45\bin\java.exe'' finished with non-zero exit value 2</p> </blockquote> <p>The application was running with no errors but as my system crashed and restarted android studio i had few updates for Android API 22. After the update the application keep giving me this error message. I downloaded JDK 8 and tried to run but didn't work. Later i downgraded to JDK 7 after this stack post but still has not fixed it. <a href="https://stackoverflow.com/questions/23318109/is-it-possible-to-use-java-8-for-android-development">Is it possible to use Java 8 for Android development?</a></p> <p>I have looked through numerous similar question but none works for me. Some similar issues found on stack were</p> <p><a href="https://stackoverflow.com/questions/28957412/why-java-exe-exit-with-value-1-in-android-studio/29236320#">why java.exe exit with value 1 in android studio</a></p> <p><a href="https://stackoverflow.com/questions/29747363/errorexecution-failed-for-task-appdexdebug-comcommand-finished-with-non">Error:Execution failed for task &#39;:app:dexDebug&#39;. &gt; comcommand finished with non-zero exit value 2</a></p> <p><a href="https://stackoverflow.com/questions/29756188/java-finished-with-non-zero-exit-value-2-android-gradle">Java finished with non-zero exit value 2 - Android Gradle</a></p> <p><a href="https://stackoverflow.com/questions/29998783/java-exe-finished-with-non-zero-exit-value-2-after-upgrading-play-service">java.exe finished with non-zero exit value 2</a></p> <p><a href="https://stackoverflow.com/questions/29837352/process-command-c-program-files-java-jdk1-8-0-31-bin-java-exe-fi">Process &#39;command&#39; C: \ Program Files \ Java \ jdk1.8.0_31 \ bin \ java.exe &#39;&#39; finished with a non -zero exit value 2</a></p> <p>I have looked through dependencies in gradle built to see if there were any conflict but found none.</p> <p>I even tried to copy the code into a new project and run it but still no success. Anyone who has faced the same issue and solved it please help me out.</p>
30,028,505
13
0
null
2015-05-02 10:15:15.703 UTC
4
2018-06-05 08:16:35.06 UTC
2018-06-05 08:16:35.06 UTC
null
8,187,464
null
796,320
null
1
25
java|android|android-studio|gradle|android-gradle-plugin
58,403
<p>After days of trying out finally could fix the issue. The problem with one of my .jar files. I had to remove each jar and check one by one until i found it. I removed the .jar file and cleaned my project and ran successfully. If any one should face similar issue check your jar file one by one.</p>
35,906,568
Wait until swift for loop with asynchronous network requests finishes executing
<p>I would like a for in loop to send off a bunch of network requests to firebase, then pass the data to a new view controller once the the method finishes executing. Here is my code:</p> <pre><code>var datesArray = [String: AnyObject]() for key in locationsArray { let ref = Firebase(url: "http://myfirebase.com/" + "\(key.0)") ref.observeSingleEventOfType(.Value, withBlock: { snapshot in datesArray["\(key.0)"] = snapshot.value }) } // Segue to new view controller here and pass datesArray once it is complete </code></pre> <p>I have a couple concerns. First, how do I wait until the for loop is finished and all the network requests are complete? I can't modify the observeSingleEventOfType function, it is part of the firebase SDK. Also, will I create some sort of race condition by trying to access the datesArray from different iterations of the for loop (hope that makes sense)? I've been reading about GCD and NSOperation but I'm a bit lost as this is the first app I've built. </p> <p>Note: Locations array is an array containing the keys I need to access in firebase. Also, it's important that the network requests are fired off asynchronously. I just want to wait until ALL the asynchronous requests complete before I pass the datesArray to the next view controller.</p>
35,906,703
10
0
null
2016-03-10 02:37:03.6 UTC
110
2022-07-28 14:21:08.857 UTC
2019-05-09 08:26:19.823 UTC
null
74,118
null
5,167,919
null
1
200
swift|asynchronous|grand-central-dispatch|nsoperation
111,893
<p>You can use <a href="http://commandshift.co.uk/blog/2014/03/19/using-dispatch-groups-to-wait-for-multiple-web-services/" rel="noreferrer">dispatch groups</a> to fire an asynchronous callback when all your requests finish.</p> <p>Here's an example using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished.</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() let myGroup = DispatchGroup() for i in 0 ..&lt; 5 { myGroup.enter() Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in print("Finished request \(i)") myGroup.leave() } } myGroup.notify(queue: .main) { print("Finished all requests.") } } </code></pre> <p><strong>Output</strong></p> <pre><code>Finished request 1 Finished request 0 Finished request 2 Finished request 3 Finished request 4 Finished all requests. </code></pre>
52,253,192
PySpark - to_date format from column
<p>I am currently trying to figure out, how to pass the String - format argument to the to_date pyspark function via a column parameter.</p> <p>Specifically, I have the following setup:</p> <pre class="lang-python prettyprint-override"><code>sc = SparkContext.getOrCreate() df = sc.parallelize([('a','2018-01-01','yyyy-MM-dd'), ('b','2018-02-02','yyyy-MM-dd'), ('c','02-02-2018','dd-MM-yyyy')]).toDF( ["col_name","value","format"]) </code></pre> <p>I am currently trying to add a new column, where each of the dates from the column F.col("value"), which is a string value, is parsed to a date.</p> <p>Separately for each format, this can be done with</p> <pre class="lang-python prettyprint-override"><code>df = df.withColumn("test1",F.to_date(F.col("value"),"yyyy-MM-dd")).\ withColumn("test2",F.to_date(F.col("value"),"dd-MM-yyyy")) </code></pre> <p>This however gives me 2 new columns - but I want to have 1 column containing both results - but calling the column does not seem to be possible with the to_date function:</p> <pre class="lang-python prettyprint-override"><code>df = df.withColumn("test3",F.to_date(F.col("value"),F.col("format"))) </code></pre> <p>Here an error "Column object not callable" is being thrown.</p> <p>Is is possible to have a generic approach for all possible formats (so that I do not have to manually add new columns for each format)?</p>
52,264,568
3
0
null
2018-09-10 07:44:25.137 UTC
1
2020-12-16 15:47:08.797 UTC
2018-09-10 19:55:25.363 UTC
null
5,858,851
null
6,333,935
null
1
8
apache-spark|pyspark|apache-spark-sql
46,195
<p>You can <a href="https://stackoverflow.com/questions/51140470/using-a-column-value-as-a-parameter-to-a-spark-dataframe-function">use a column value as a parameter</a> without a <code>udf</code> using the spark-sql syntax:</p> <p><strong>Spark version 2.2 and above</strong></p> <pre class="lang-python prettyprint-override"><code>from pyspark.sql.functions import expr df.withColumn("test3",expr("to_date(value, format)")).show() #+--------+----------+----------+----------+ #|col_name| value| format| test3| #+--------+----------+----------+----------+ #| a|2018-01-01|yyyy-MM-dd|2018-01-01| #| b|2018-02-02|yyyy-MM-dd|2018-02-02| #| c|02-02-2018|dd-MM-yyyy|2018-02-02| #+--------+----------+----------+----------+ </code></pre> <p>Or equivalently using pyspark-sql:</p> <pre class="lang-python prettyprint-override"><code>df.createOrReplaceTempView("df") spark.sql("select *, to_date(value, format) as test3 from df").show() </code></pre> <p><strong>Spark version 1.5 and above</strong></p> <p>Older versions of spark do not support having a <code>format</code> argument to the <code>to_date</code> function, so you'll have to use <code>unix_timestamp</code> and <code>from_unixtime</code>:</p> <pre class="lang-python prettyprint-override"><code>from pyspark.sql.functions import expr df.withColumn( "test3", expr("from_unixtime(unix_timestamp(value,format))").cast("date") ).show() </code></pre> <p>Or equivalently using pyspark-sql:</p> <pre class="lang-python prettyprint-override"><code>df.createOrReplaceTempView("df") spark.sql( "select *, cast(from_unixtime(unix_timestamp(value,format)) as date) as test3 from df" ).show() </code></pre>
39,393,926
Flask('application') versus Flask(__name__)
<p>In the official <a href="http://flask.pocoo.org/docs/0.11/quickstart/#a-minimal-application" rel="noreferrer">Quickstart</a>, it's recommended to use <code>__name__</code> when using a single <strong>module</strong>:</p> <blockquote> <ol start="2"> <li>... If you are using a single module (as in this example), you should use <code>__name__</code> because depending on if it’s started as application or imported as module the name will be different (<code>'__main__'</code> versus the actual import name). ...</li> </ol> </blockquote> <p>However, in their <a href="http://flask.pocoo.org/docs/0.11/api/#application-object" rel="noreferrer">API document</a>, hardcoding is recommended when my application is a <strong>package</strong>:</p> <blockquote> <p>So it’s important what you provide there. If you are using a single module, <code>__name__</code> is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.</p> </blockquote> <p>I can understand why it's better to hardcode the name of my package, but why not hardcoding the name of a single module? Or, in other words, what information can <code>Flask</code> get when it receives a <code>__main__</code> as its first parameter? I can't see how this can make it easier for Flask to find the resources...</p>
39,393,990
1
0
null
2016-09-08 14:43:11.533 UTC
6
2019-10-26 08:47:56.9 UTC
2016-09-08 14:49:18.78 UTC
null
5,399,734
null
5,399,734
null
1
36
python|flask|import|module|package
25,882
<p><code>__name__</code> is just a convenient way to get the import name of the place the app is defined. Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc. When using a package, if you define your app in <code>__init__.py</code> then the <code>__name__</code> will still point at the "correct" place relative to where the resources are. However, if you define it elsewhere, such as <code>mypackage/app.py</code>, then using <code>__name__</code> would tell Flask to look for resources relative to <code>mypackage.app</code> instead of <code>mypackage</code>.</p> <p>Using <code>__name__</code> isn't orthogonal to "hardcoding", it's just a shortcut to using the name of the package. And there's also no reason to say that the name <em>should</em> be the base package, it's entirely up to your project structure.</p>
34,188,461
Laravel 5.1 @can, how use OR clause
<p>I did not find how to use a clause (OR, AND) in view with @can, for checking multiple abilities ...</p> <p>I tried:</p> <pre><code>@can(['permission1', 'permission2']) @can('permission1' or 'permission2') @can('permission1' || 'permission2') </code></pre> <p>But dont work ;(</p>
34,189,000
8
0
null
2015-12-09 20:34:14.83 UTC
6
2022-03-25 11:42:47.03 UTC
2015-12-09 20:49:15.73 UTC
null
1,384,843
null
1,384,843
null
1
41
laravel|laravel-5.1|laravel-blade
41,036
<p>You can use the Gate facade:</p> <pre><code>@if(Gate::check('permission1') || Gate::check('permission2')) @endif </code></pre>
31,409,149
Jenkins Remote Trigger Not Working
<p>I am getting the following error when i try triggering a build using the following command:</p> <p>curl <a href="http://jenkins_server:port/jenkins/job/job_name/build?token=token_name">http://jenkins_server:port/jenkins/job/job_name/build?token=token_name</a></p> <p>Output:</p> <blockquote> <p>Authentication required</p> <p>&lt;-- You are authenticated as: anonymous<br/> Groups that you are in:</p> <p>Permission you need to have (but didn't): hudson.model.Hudson.Read<br/> ... which is implied by: hudson.security.Permission.GenericRead<br/> ... which is implied by: hudson.model.Hudson.Administer<br/> -></p> </blockquote> <p>I have admin rights and have also enabled 'Authentication Token'. I also have Build, Discover and Read rights on Job. I am using Jenkins 1.614.</p> <p>I did check several posts online but could not find anything that works for me.<br/><br/> Tried few options such as<br/> 1) curl -X POST <a href="http://jenkins_server:port/jenkins/job/job_name/build?token=token_name">http://jenkins_server:port/jenkins/job/job_name/build?token=token_name</a><br/> 2) curl -u user:API (Prints a long HTML page)<br/></p> <p>Any suggestions.</p>
31,411,425
9
0
null
2015-07-14 14:11:44.573 UTC
7
2021-04-14 04:00:27.913 UTC
null
null
null
null
361,089
null
1
28
curl|jenkins
29,572
<p>I install Build Token Root Plugin to solve this issue before</p> <p><a href="https://wiki.jenkins-ci.org/display/JENKINS/Build+Token+Root+Plugin" rel="noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/Build+Token+Root+Plugin</a></p> <p>Then as the same, setup Authentication Token</p> <p>Finally, either use curl to trigger remote build (Be careful the escape character "\")</p> <p><code>curl http://JENKINS_URL/buildByToken/build?job=JOB_NAME\&amp;token=TOKEN_NAME</code></p> <p>or paste the URL to your browser (No needs escape character "\")</p> <p><code>http://JENKINS_URL/buildByToken/build?job=JOB_NAME&amp;token=TOKEN_NAME</code></p> <p>If you see Succeed, it means that trigger remote Jenkins successfully.</p> <p>Note that, you don't have to setup build, discover, and read rights on Job</p> <p>For more information, you could reference to <a href="https://cloudbees.zendesk.com/hc/en-us/articles/204338790-Why-are-builds-not-being-triggered-with-Build-Token-Root-Plugin-" rel="noreferrer">https://cloudbees.zendesk.com/hc/en-us/articles/204338790-Why-are-builds-not-being-triggered-with-Build-Token-Root-Plugin-</a></p>
171,489
Explicit Type Conversion in Scala
<p>Lets say I have the following code:</p> <pre><code>abstract class Animal case class Dog(name:String) extends Animal var foo:Animal = Dog("rover") var bar:Dog = foo //ERROR! </code></pre> <p>How do I fix the last line of this code? Basically, I just want to do what, in a C-like language would be done:</p> <pre><code>var bar:Dog = (Dog) foo </code></pre>
171,531
1
0
null
2008-10-05 04:32:52.847 UTC
19
2011-05-02 21:28:28.11 UTC
2011-05-02 21:28:28.11 UTC
onlyafly
460,387
onlyafly
10,475
null
1
78
scala|type-conversion
69,811
<p>I figured this out myself. There are two solutions:</p> <p>1) Do the explicit cast:</p> <pre><code>var bar:Dog = foo.asInstanceOf[Dog] </code></pre> <p>2) Use pattern matching to cast it for you, this also catches errors:</p> <pre><code>var bar:Dog = foo match { case x:Dog =&gt; x case _ =&gt; { // Error handling code here } } </code></pre>
49,473,098
Call to undefined method Maatwebsite\Excel\Excel::load()
<p>I'm trying to import excel file (.xlsx) using maatwebsite 3.0. How to fix This error </p> <blockquote> <p>Call to undefined method Maatwebsite\Excel\Excel::load()</p> </blockquote> <p>My controller</p> <pre><code>public function importsave(Request $request) { if($request-&gt;hasFile('excel')) { $path = $request-&gt;file('excel')-&gt;getRealPath(); $data= Excel::load($path, function($reader) {})-&gt;get(); if(!empty($data) &amp;&amp; $data-&gt;count()) { foreach($data-&gt;toArray() as $key=&gt;$value) { if(!empty($value)) { Employee::insert($value); } } } } } </code></pre>
49,473,174
6
0
null
2018-03-25 06:20:21.24 UTC
2
2021-12-01 10:30:59.02 UTC
2018-03-26 07:37:24.067 UTC
null
1,594,915
null
9,080,111
null
1
18
php|excel|laravel|laravel-5|maatwebsite-excel
82,887
<p>Version <strong>3.0</strong> of that package <strong>doesn't handle imports yet</strong>. Release date for this feature is unknown. See this post for more details: <a href="https://medium.com/@maatwebsite/laravel-excel-lessons-learned-7fee2812551" rel="nofollow noreferrer">https://medium.com/@maatwebsite/laravel-excel-lessons-learned-7fee2812551</a></p> <p>I suggest you <strong>switch to version 2.</strong>*.</p> <p>Else you want to continue further ALL Laravel Excel 2.* methods are deprecated and will not be able to use in 3.0 .</p> <pre><code> Excel::load() is removed and replaced by Excel::import($yourImport) Excel::create() is removed and replaced by Excel::download/Excel::store($yourExport) Excel::create()-&gt;string('xlsx') is removed an replaced by Excel::raw($yourExport, Excel::XLSX) </code></pre> <p>3.0 provides no convenience methods for styling, you are encouraged to use PhpSpreadsheets native methods.</p>
43,943,384
Powershell to find Server Operating system
<p>I had a task to find Operating System of all the servers we had in AD for some Microsoft Licenses requirement. </p> <p>Has anyone done this?</p>
43,943,385
2
0
null
2017-05-12 17:28:20.953 UTC
null
2019-02-21 07:52:54.743 UTC
2018-01-23 17:58:08.417 UTC
null
2,212,710
null
2,212,710
null
1
3
powershell|operating-system|find|windows-server
46,147
<p>I figured it out. </p> <p>Please feel free to use it and modify it. If you have questions, let me know.</p> <p>It's a simple command. Hopefully, it helps someone. This gives you the type of operating systems you have. I am filtering based on Windows Server only and computer accounts that are active. Then sort by name and select unique OS.</p> <pre><code>Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} -Properties OperatingSystem | Sort Name | select -Unique OperatingSystem </code></pre> <p>Output:</p> <pre><code>OperatingSystem --------------- Windows Server 2012 R2 Standard Windows Server 2008 R2 Standard Windows Server 2012 R2 Standard Evaluation Windows Server 2008 R2 Enterprise </code></pre> <p>Next command is to get all the servers and show their Operating System. Again, I am filtering based on Windows server OS and Active computer accounts. I am sorting my list by Operating system:</p> <pre><code>Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} -Properties OperatingSystem | sort OperatingSystem | ft DNSHostName, OperatingSystem </code></pre> <p>You can also save the above in a variable and then get the count of Servers in each operating system category:</p> <pre><code>$Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} -Properties OperatingSystem | Sort Name $servers | group operatingsystem </code></pre>
39,081,945
How to specify spring.profiles.active when I run mvn install
<p>In this web application with Spring, I created several application-property files for different deploy environment. They specify different db connection configs. </p> <pre><code>application-dev.properties application-qa.properties application-stg.properties application-prod.properties </code></pre> <p>The recommended way according to <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html" rel="noreferrer">spring doc</a> is to set spring.profiles.active as JVM option at run time, for example:</p> <pre><code>-Dspring.profiles.active=prod </code></pre> <p>However what should I do for deploying the application as war using mvn install. How should I set the spring profile? I am using Eclipse.</p> <p><strong>EDIT</strong>: I set the JVM option under <a href="https://i.stack.imgur.com/uNqpj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uNqpj.png" alt="run configuration"></a>. It does not seem to get picked up by maven when I deploy it as a war though since I got the following error from tomcat:</p> <pre><code>Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception </code></pre>
39,082,932
2
0
null
2016-08-22 14:18:58.467 UTC
3
2018-05-26 10:35:31.99 UTC
2016-08-22 15:42:52.623 UTC
null
3,358,927
null
3,358,927
null
1
22
eclipse|spring|web-services|maven|jvm
62,679
<p>Under Run->run configurations, select your maven launch configuration, then select the JRE tab, and type your argument in the VM arguments text area. </p>
3,154,310
Search list of objects based on object variable
<p>I have a list of objects. These objects have three variables, ID, Name, &amp; value. There can be a lot of objects in this list, and I need to find one based on the ID or Name, and change the value. Example</p> <pre><code>class objec { public string Name; public int UID; public string value; } List&lt;objec&gt; TextPool = new List&lt;objec&gt;(); </code></pre> <p>How would I find the one entry in TextPool that had the Name of 'test' and change its value to 'Value'. The real program has many more search options, and values that need changing, so I couldn't just use a Dictionary (though Name and UID or unique identifiers). Any help would be great</p>
3,154,328
4
0
null
2010-07-01 00:07:21.757 UTC
3
2014-09-09 22:39:31.833 UTC
2014-09-09 22:39:31.833 UTC
null
267,631
null
267,631
null
1
15
c#|search|list
72,124
<p>You could use LINQ to find it, then change the element directly:</p> <pre><code>var item = TextPool.FirstOrDefault(o =&gt; o.Name == "test"); if (item != null) item.value = "Value"; </code></pre> <p>If you wanted to change all elements that match, you could, potentially, even do:</p> <pre><code>TextPool.Where(o =&gt; o.Name == "test").ToList().ForEach(o =&gt; o.value = "Value"); </code></pre> <p>However, I personally would rather split it up, as I feel the second option is less maintainable (doing operations which cause side effects directly on the query result "smells" to me)...</p>
3,151,779
Best way to invoke gdb from inside program to print its stacktrace?
<p>Using a function like this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/wait.h&gt; #include &lt;unistd.h&gt; void print_trace() { char pid_buf[30]; sprintf(pid_buf, "--pid=%d", getpid()); char name_buf[512]; name_buf[readlink("/proc/self/exe", name_buf, 511)]=0; int child_pid = fork(); if (!child_pid) { dup2(2,1); // redirect output to stderr fprintf(stdout,"stack trace for %s pid=%s\n",name_buf,pid_buf); execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL); abort(); /* If gdb failed to start */ } else { waitpid(child_pid,NULL,0); } } </code></pre> <p>I see the details of print_trace in the output.</p> <p>What are other ways to do it?</p>
4,611,112
4
17
2010-06-30 22:30:51.7 UTC
2010-06-30 17:27:58.493 UTC
67
2018-02-27 21:02:38.633 UTC
2018-02-27 21:02:38.633 UTC
null
266,720
null
266,720
null
1
62
c|linux|gdb|stack-trace
43,532
<p>You mentioned on my other answer (now deleted) that you also want to see line numbers. I'm not sure how to do that when invoking gdb from inside your application.</p> <p>But I'm going to share with you a couple of ways to print a simple stacktrace with function names and their respective line numbers <strong>without using gdb</strong>. Most of them came from a <em>very nice</em> article from <a href="http://www.linuxjournal.com/article/6391" rel="noreferrer">Linux Journal</a>:</p> <ul> <li><strong>Method #1:</strong></li> </ul> <blockquote> <p>The first method is to disseminate it with print and log messages in order to pinpoint the execution path. In a complex program, this option can become cumbersome and tedious even if, with the help of some GCC-specific macros, it can be simplified a bit. Consider, for example, a debug macro such as:</p> </blockquote> <pre><code> #define TRACE_MSG fprintf(stderr, __FUNCTION__ \ "() [%s:%d] here I am\n", \ __FILE__, __LINE__) </code></pre> <blockquote> <p>You can propagate this macro quickly throughout your program by cutting and pasting it. When you do not need it anymore, switch it off simply by defining it to no-op.</p> </blockquote> <ul> <li><strong>Method #2:</strong> (It doesn't say anything about line numbers, but I do on method 4)</li> </ul> <blockquote> <p>A nicer way to get a stack backtrace, however, is to use some of the specific support functions provided by glibc. The key one is backtrace(), which navigates the stack frames from the calling point to the beginning of the program and provides an array of return addresses. You then can map each address to the body of a particular function in your code by having a look at the object file with the nm command. Or, you can do it a simpler way--use backtrace_symbols(). This function transforms a list of return addresses, as returned by backtrace(), into a list of strings, each containing the function name offset within the function and the return address. The list of strings is allocated from your heap space (as if you called malloc()), so you should free() it as soon as you are done with it.</p> </blockquote> <p>I encourage you to read it since the page has <a href="http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/063/6391/6391l1.html" rel="noreferrer">source code</a> examples. In order to convert an address to a function name you must compile your application with the <strong>-rdynamic</strong> option.</p> <ul> <li><strong>Method #3:</strong> (A better way of doing method 2)</li> </ul> <blockquote> <p>An even more useful application for this technique is putting a stack backtrace inside a signal handler and having the latter catch all the "bad" signals your program can receive (SIGSEGV, SIGBUS, SIGILL, SIGFPE and the like). This way, if your program unfortunately crashes and you were not running it with a debugger, you can get a stack trace and know where the fault happened. This technique also can be used to understand where your program is looping in case it stops responding</p> </blockquote> <p>An implementation of this technique is available <a href="http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/063/6391/6391l2.html" rel="noreferrer">here</a>.</p> <ul> <li><strong>Method #4:</strong></li> </ul> <p>A small improvement I've done on method #3 to print line numbers. This could be copied to work on method #2 also.</p> <p>Basically, I <a href="http://tlug.up.ac.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV#addr2line" rel="noreferrer">followed a tip</a> that uses <strong>addr2line</strong> to </p> <blockquote> <p>convert addresses into file names and line numbers.</p> </blockquote> <p>The source code below prints line numbers for all local functions. If a function from another library is called, you might see a couple of <code>??:0</code> instead of file names.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;signal.h&gt; #include &lt;stdio.h&gt; #include &lt;signal.h&gt; #include &lt;execinfo.h&gt; void bt_sighandler(int sig, struct sigcontext ctx) { void *trace[16]; char **messages = (char **)NULL; int i, trace_size = 0; if (sig == SIGSEGV) printf("Got signal %d, faulty address is %p, " "from %p\n", sig, ctx.cr2, ctx.eip); else printf("Got signal %d\n", sig); trace_size = backtrace(trace, 16); /* overwrite sigaction with caller's address */ trace[1] = (void *)ctx.eip; messages = backtrace_symbols(trace, trace_size); /* skip first stack frame (points here) */ printf("[bt] Execution path:\n"); for (i=1; i&lt;trace_size; ++i) { printf("[bt] #%d %s\n", i, messages[i]); /* find first occurence of '(' or ' ' in message[i] and assume * everything before that is the file name. (Don't go beyond 0 though * (string terminator)*/ size_t p = 0; while(messages[i][p] != '(' &amp;&amp; messages[i][p] != ' ' &amp;&amp; messages[i][p] != 0) ++p; char syscom[256]; sprintf(syscom,"addr2line %p -e %.*s", trace[i], p, messages[i]); //last parameter is the file name of the symbol system(syscom); } exit(0); } int func_a(int a, char b) { char *p = (char *)0xdeadbeef; a = a + b; *p = 10; /* CRASH here!! */ return 2*a; } int func_b() { int res, a = 5; res = 5 + func_a(a, 't'); return res; } int main() { /* Install our signal handler */ struct sigaction sa; sa.sa_handler = (void *)bt_sighandler; sigemptyset(&amp;sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(SIGSEGV, &amp;sa, NULL); sigaction(SIGUSR1, &amp;sa, NULL); /* ... add any other signal here */ /* Do something */ printf("%d\n", func_b()); } </code></pre> <p>This code should be compiled as: <code>gcc sighandler.c -o sighandler -rdynamic</code></p> <p>The program outputs:</p> <pre><code>Got signal 11, faulty address is 0xdeadbeef, from 0x8048975 [bt] Execution path: [bt] #1 ./sighandler(func_a+0x1d) [0x8048975] /home/karl/workspace/stacktrace/sighandler.c:44 [bt] #2 ./sighandler(func_b+0x20) [0x804899f] /home/karl/workspace/stacktrace/sighandler.c:54 [bt] #3 ./sighandler(main+0x6c) [0x8048a16] /home/karl/workspace/stacktrace/sighandler.c:74 [bt] #4 /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x3fdbd6] ??:0 [bt] #5 ./sighandler() [0x8048781] ??:0 </code></pre> <hr> <p><strong>Update 2012/04/28</strong> for recent linux kernel versions, the above <code>sigaction</code> signature is obsolete. Also I improved it a bit by grabbing the executable name from <a href="https://stackoverflow.com/a/10365300/170521">this answer</a>. Here is an <a href="http://www.linuxjournal.com/files/linuxjournal.com/linuxjournal/articles/063/6391/6391l3.html" rel="noreferrer">up to date version</a>:</p> <pre><code>char* exe = 0; int initialiseExecutableName() { char link[1024]; exe = new char[1024]; snprintf(link,sizeof link,"/proc/%d/exe",getpid()); if(readlink(link,exe,sizeof link)==-1) { fprintf(stderr,"ERRORRRRR\n"); exit(1); } printf("Executable name initialised: %s\n",exe); } const char* getExecutableName() { if (exe == 0) initialiseExecutableName(); return exe; } /* get REG_EIP from ucontext.h */ #define __USE_GNU #include &lt;ucontext.h&gt; void bt_sighandler(int sig, siginfo_t *info, void *secret) { void *trace[16]; char **messages = (char **)NULL; int i, trace_size = 0; ucontext_t *uc = (ucontext_t *)secret; /* Do something useful with siginfo_t */ if (sig == SIGSEGV) printf("Got signal %d, faulty address is %p, " "from %p\n", sig, info-&gt;si_addr, uc-&gt;uc_mcontext.gregs[REG_EIP]); else printf("Got signal %d\n", sig); trace_size = backtrace(trace, 16); /* overwrite sigaction with caller's address */ trace[1] = (void *) uc-&gt;uc_mcontext.gregs[REG_EIP]; messages = backtrace_symbols(trace, trace_size); /* skip first stack frame (points here) */ printf("[bt] Execution path:\n"); for (i=1; i&lt;trace_size; ++i) { printf("[bt] %s\n", messages[i]); /* find first occurence of '(' or ' ' in message[i] and assume * everything before that is the file name. (Don't go beyond 0 though * (string terminator)*/ size_t p = 0; while(messages[i][p] != '(' &amp;&amp; messages[i][p] != ' ' &amp;&amp; messages[i][p] != 0) ++p; char syscom[256]; sprintf(syscom,"addr2line %p -e %.*s", trace[i] , p, messages[i] ); //last parameter is the filename of the symbol system(syscom); } exit(0); } </code></pre> <p>and initialise like this:</p> <pre><code>int main() { /* Install our signal handler */ struct sigaction sa; sa.sa_sigaction = (void *)bt_sighandler; sigemptyset (&amp;sa.sa_mask); sa.sa_flags = SA_RESTART | SA_SIGINFO; sigaction(SIGSEGV, &amp;sa, NULL); sigaction(SIGUSR1, &amp;sa, NULL); /* ... add any other signal here */ /* Do something */ printf("%d\n", func_b()); } </code></pre>
56,651,472
Does C# 8 support the .NET Framework?
<p>In Visual Studio 2019 Advanced Build settings, C# 8 does not appear to be available for a .NET Framework project, only (as in the picture below) for a .NET Core 3.0 project:</p> <p><a href="https://i.stack.imgur.com/3P2rH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3P2rH.png" alt="enter image description here"></a></p> <p>Does C# 8 support the .NET Framework?</p>
57,020,770
3
0
null
2019-06-18 14:31:05.273 UTC
67
2021-03-16 12:02:03.953 UTC
2020-03-12 02:08:32.587 UTC
null
397,817
null
1,461,680
null
1
225
c#|.net|visual-studio|.net-standard|c#-8.0
92,643
<p><strong>Yes, C# 8 can be used with the .NET Framework</strong> and other targets older than .NET Core 3.0/.NET Standard 2.1 in Visual Studio 2019 (or older versions of Visual Studio if you <a href="https://stackoverflow.com/a/58190585/397817">install a NuGet package</a>).</p> <p>The only thing required is to set language version to <code>8.0</code> in the csproj file. You can also do this in <a href="https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019#directorybuildprops-and-directorybuildtargets" rel="noreferrer">Directory.Build.props</a> to apply it to all projects in your solution. Read below for how to do this in Visual Studio 2019, version 16.3 and newer.</p> <p>Most - but not all - features are available whichever framework is targeted.</p> <hr /> <h2>Features that work</h2> <p>The following features are syntax changes only; they work regardless of framework:</p> <ul> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions" rel="noreferrer">Static local functions</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">Using declarations</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#null-coalescing-assignment" rel="noreferrer">Null-coalescing assignment</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members" rel="noreferrer">Readonly members</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#disposable-ref-structs" rel="noreferrer">Disposable ref structs</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#positional-patterns" rel="noreferrer">Positional patterns</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#tuple-patterns" rel="noreferrer">Tuple patterns</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions" rel="noreferrer">Switch expressions</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#nullable-reference-types" rel="noreferrer">Nullable reference types</a> are also supported, but the new <a href="http://docs.microsoft.com/en-us/dotnet/csharp/nullable-attributes" rel="noreferrer">nullable attributes</a> required to design the more complex nullable use cases are not. I cover this in more detail further down in the &quot;gory details&quot; section.</li> </ul> <h2>Features that can be made to work</h2> <p>These require new types which are not in the .NET Framework. They can only be used in conjunction with &quot;polyfill&quot; NuGet packages or code files:</p> <ul> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams" rel="noreferrer">Asynchronous streams</a> - <a href="https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/" rel="noreferrer">Microsoft.Bcl.AsyncInterfaces</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges" rel="noreferrer">Indices and ranges</a></li> </ul> <h2>Default interface members - do not, cannot, and never will work</h2> <p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods" rel="noreferrer">Default interface members</a> won't compile under .NET Framework and will never work because they require runtime changes in the CLR. The .NET CLR is now frozen as .NET Core is now the way forward.</p> <p><em>For more information on what does and doesn't work, and on possible polyfills, see Stuart Lang's article, <a href="https://stu.dev/csharp8-doing-unsupported-things/" rel="noreferrer">C# 8.0 and .NET Standard 2.0 - Doing Unsupported Things</a>.</em></p> <hr /> <h2>Code</h2> <p>The following C# project targetting .NET Framework 4.8 and using C# 8 nullable reference types compiles in Visual Studio 16.2.0. I created it by choosing the .NET Standard Class Library template and then editing it to target .NET Framework instead:</p> <p>.csproj:</p> <pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt; &lt;PropertyGroup&gt; &lt;TargetFrameworks&gt;net48&lt;/TargetFrameworks&gt; &lt;LangVersion&gt;8.0&lt;/LangVersion&gt; &lt;Nullable&gt;enable&lt;/Nullable&gt; &lt;/PropertyGroup&gt; &lt;/Project&gt; </code></pre> <p>.cs:</p> <pre><code>namespace ClassLibrary1 { public class Class1 { public string? NullableString { get; set; } } } </code></pre> <p>I then tried a .NET Framework 4.5.2 WinForms project, using a legacy <code>.csproj</code> format, and added the same nullable reference type property. I changed the language type in the Visual Studio Advanced Build settings dialog (disabled in 16.3) to <code>latest</code> and saved the project. Of course as this point it doesn't build. I opened the project file in a text editor and changed <code>latest</code> to <code>preview</code> in the build configuration <code>PropertyGroup</code>:</p> <pre><code>&lt;PropertyGroup Condition=&quot; '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' &quot;&gt; &lt;LangVersion&gt;preview&lt;/LangVersion&gt; </code></pre> <p>I then enabled support for nullable reference types by adding <code>&lt;Nullable&gt;enable&lt;/Nullable&gt;</code> to the main <code>PropertyGroup</code>:</p> <pre><code>&lt;PropertyGroup&gt; &lt;Nullable&gt;enable&lt;/Nullable&gt; </code></pre> <p>I reloaded the project, and it builds.</p> <hr /> <h2>Visual Studio 2019</h2> <p>There has been a major change in the RTM version of Visual Studio 2019 version 16.3, the launch version for C# 8.0: the language selection dropdown has been disabled:</p> <p><a href="https://i.stack.imgur.com/nAJfn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nAJfn.png" alt="enter image description here" /></a></p> <p>Microsoft's <a href="https://github.com/dotnet/project-system/pull/4923/commits/fc1f7f691851670909ed38fdfc3b4a4ac79c5e4b" rel="noreferrer">rationale</a> for this is:</p> <blockquote> <p>Moving forward, ... each version of each framework will have a single supported and default version, and we won't support arbitrary versions. To reflect this change in support, this commit permanently disables the language version combo box and adds a link to a document explaining the change.</p> </blockquote> <p>The document which opens is <a href="https://docs.microsoft.com/en-gb/dotnet/csharp/language-reference/configure-language-version" rel="noreferrer">C# language versioning</a>. This lists C# 8.0 as the default language for .NET Core 3.x ONLY. It also confirms that <strong>each version of each framework will, going forward, have a single supported and default version</strong> and that the framework-agnosticism of the language can no longer be relied on.</p> <p>The language version can still be forced to 8 for .NET Framework projects by editing the .csproj file.</p> <hr /> <h2>The gory details</h2> <p><em><strong>When this answer was first written, C# 8 was in preview and a lot of detective work was involved. I leave that information here for posterity. Feel free to skip it if you don't need to know all the gory details.</strong></em></p> <p>The C# language has historically been <a href="https://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c#comment54106872_247623">mostly framework neutral</a> - i.e. able to compile older versions of the Framework - although some features have required new types or CLR support.</p> <p>Most C# enthusiasts will have read the blog entry <a href="https://devblogs.microsoft.com/dotnet/building-c-8-0/" rel="noreferrer">Building C# 8.0</a> by Mads Torgersen, which explains that certain features of C# 8 have platform dependencies:</p> <blockquote> <p>Async streams, indexers and ranges all rely on new framework types that will be part of .NET Standard 2.1... .NET Core 3.0 as well as Xamarin, Unity and Mono will all implement .NET Standard 2.1, but .NET Framework 4.8 will not. This means that the types required to use these features won’t be available on .NET Framework 4.8.</p> </blockquote> <p>This looks a bit like <a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/" rel="noreferrer">Value Tuples</a> which were introduced in C# 7. That feature required new types - the <code>ValueTuple</code> structures - which were not available in NET Framework versions below 4.7 or .NET Standard older than 2.0. <strong>However</strong>, C# 7 could still be used in older versions of .NET, either without value tuples or with them by installing the <a href="https://www.nuget.org/packages/System.ValueTuple/" rel="noreferrer">System.ValueTuple Nuget package</a>. Visual Studio understood this, and all was fine with the world.</p> <p>However, Mads also wrote:</p> <blockquote> <p>For this reason, using C# 8.0 is only supported on platforms that implement .NET Standard 2.1.</p> </blockquote> <p>...which if true would have ruled out using C# 8 with <em>any</em> version of the .NET Framework, and indeed even in .NET Standard 2.0 libraries which only recently we were encouraged to use as a baseline target for library code. You wouldn't even be able to use it with .NET Core versions older than 3.0 as they too only support .NET Standard 2.0.</p> <p>The investigation was on! -</p> <ul> <li><p>Jon Skeet has an alpha version of Noda-Time using C# 8 <a href="https://github.com/nodatime/nodatime/blob/master/src/NodaTime/NodaTime.csproj" rel="noreferrer">ready to go</a> which targets .NET Standard 2.0 only. He is clearly expecting C# 8/.NET Standard 2.0 to support all frameworks in the .NET family. (See also Jon's blog post <a href="https://codeblog.jonskeet.uk/2018/04/21/first-steps-with-nullable-reference-types/" rel="noreferrer">&quot;First steps with nullable reference types&quot;</a>).</p> </li> <li><p>Microsoft employees have been discussing the Visual Studio UI for C# 8 nullable reference types <a href="https://github.com/dotnet/project-system/issues/4058" rel="noreferrer">on GitHub</a>, and it is stated that they intend to support the legacy <code>csproj</code> (pre-.NET Core SDK format <code>csproj</code>). This is a very strong indication that C# 8 will be usable with the .NET Framework. [I suspect they will backtrack on this now that the Visual Studio 2019 language version dropdown has been disabled and .NET has been tied to C# 7.3]</p> </li> <li><p>Shortly after the famous blog post, a <a href="https://github.com/dotnet/csharplang/issues/2002" rel="noreferrer">GitHub thread</a> discussed cross-platform support. An important point which emerged was that <a href="https://github.com/dotnet/standard/pull/1019" rel="noreferrer">.NET Standard 2.1 will include a marker that denotes that default implementations of interfaces is supported</a> - the feature requires a CLR change that will never be available to the .NET Framework. Here's the important bit, from Immo Landwerth, Program Manager on the .NET team at Microsoft:</p> </li> </ul> <blockquote> <p>Compilers (such as C#) are expected to use the presence of this field to decide whether or not to allow default interface implementations. If the field is present, the runtime is expected to be able to load &amp; execute the resulting code.</p> </blockquote> <ul> <li>This all pointed to &quot;C# 8.0 is only supported on platforms that implement .NET Standard 2.1&quot; being an oversimplification, and that C# 8 will support the .NET Framework but, as there is so much uncertainty, I <a href="https://github.com/dotnet/csharplang/issues/2651" rel="noreferrer">asked on GitHub</a> and HaloFour answered:</li> </ul> <blockquote> <p>IIRC, the only feature that definitely won't appear on .NET Framework is DIM (default interface methods) as that requires runtime changes. The other features are driven by the shape of classes that might never be added to the .NET Framework but can be polyfilled through your own code or NuGet (ranges, indexes, async iterators, async disposal).</p> </blockquote> <ul> <li><p><a href="https://stackoverflow.com/users/1949956/victor-derks">Victor Derks</a> commented that &quot;The <a href="http://docs.microsoft.com/en-us/dotnet/csharp/nullable-attributes" rel="noreferrer">new nullable attributes</a> required to design the more complex nullable use cases are only available in System.Runtime.dll that ships with .NET Core 3.0 and .NET Standard 2.1... [and] incompatible with .NET Framework 4.8&quot;</p> </li> <li><p>However, Immo Landwerth <a href="https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/#comments-2653" rel="noreferrer">commented</a> that &quot;The vast majority of our APIs didn't need any custom attributes as the types are either fully generic or not-null&quot; under the article <a href="https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/" rel="noreferrer">Try out Nullable Reference Types</a></p> </li> <li><p><a href="https://stackoverflow.com/users/6870582/ben-hall">Ben Hall</a> raised the issue <a href="https://github.com/dotnet/corefx/issues/40039" rel="noreferrer">Availability of nullable attributes outside of Core 3.0</a> on GitHub, with the following comments from Microsoft employees being of note:</p> </li> </ul> <blockquote> <p>C# 8 will be fully supported on .net core 3.0 and .net standard 2.1 only. If you manually edit the project file to use C# 8 with .net core 2.1, you are in unsupported territory. Some C# 8 features will happen to work well, some C# 8 features will work not too well (e.g. poor performance), some C# 8 features will work with extra hacks, and some C# 8 features will not work at all. Very complex to explain. We do not actively block it so the expert users who can navigate through it can do so. I would not recommend this unsupported mix&amp;match to be used broadly.</p> </blockquote> <p>(Jan Kotas)</p> <blockquote> <p>People like you who are willing understand -- and work around them -- are free to use C# 8. The point is, not all language features will work on down-level targets.</p> </blockquote> <p>(Immo Landwerth)</p> <hr /> <h2>Caveat emptor</h2> <p>The C# 8/.NET Framework combination is not officially supported by Microsoft. It is, they say, for experts only.</p>
28,837,633
pandas get position of a given index in DataFrame
<p>Let's say I have a DataFrame like this:</p> <pre><code>df A B 5 0 1 18 2 3 125 4 5 </code></pre> <p>where <code>5, 18, 125</code> are the index</p> <p>I'd like to get the line before (or after) a certain index. For instance, I have index <code>18</code> (eg. by doing <code>df[df.A==2].index</code>), and I want to get the line before, and I don't know that this line has <code>5</code> as an index.</p> <p>2 sub-questions:</p> <ul> <li>How can I get the position of index <code>18</code>? Something like <code>df.loc[18].get_position()</code> which would return <code>1</code> so I could reach the line before with <code>df.iloc[df.loc[18].get_position()-1]</code></li> <li>Is there another solution, a bit like options <code>-C</code>, <code>-A</code> or <code>-B</code> with grep ?</li> </ul>
28,837,788
2
0
null
2015-03-03 17:02:00.873 UTC
9
2022-09-21 14:01:46.977 UTC
2015-03-03 17:24:06.36 UTC
null
3,297,428
null
3,297,428
null
1
21
python|pandas
23,265
<p>For your first question:</p> <pre><code>base = df.index.get_indexer_for((df[df.A == 2].index)) </code></pre> <p>or alternatively</p> <pre><code>base = df.index.get_loc(18) </code></pre> <p>To get the surrounding ones: </p> <pre><code>mask = pd.Index(base).union(pd.Index(base - 1)).union(pd.Index(base + 1)) </code></pre> <p>I used Indexes and unions to remove duplicates. You may want to keep them, in which case you can use <code>np.concatenate</code></p> <p>Be careful with matches on the very first or last rows :)</p>
40,497,399
HTTP request from Angular sent as OPTIONS instead of POST
<p>I'm trying to send some HTTP requests from my angular.js application to my server, but I need to solve some CORS errors.</p> <p>The HTTP request is made using the following code:</p> <pre><code>functions.test = function(foo, bar) { return $http({ method: 'POST', url: api_endpoint + 'test', headers: { 'foo': 'value', 'content-type': 'application/json' }, data: { bar:'value' } }); }; </code></pre> <p>The first try ended up with some CORS errors. So I've added the following lines to my PHP script:</p> <pre><code>header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT'); header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type'); </code></pre> <p>The first error is now eliminated.</p> <p>Now the Chrome's developer console shows me the following errors:</p> <blockquote> <p>angular.js:12011 OPTIONS <a href="http://localhost:8000/test" rel="noreferrer">http://localhost:8000/test</a> (anonymous function)</p> <p>423ef03a:1 XMLHttpRequest cannot load <a href="http://localhost:8000/test" rel="noreferrer">http://localhost:8000/test</a>. Response for preflight has invalid HTTP status code 400</p> </blockquote> <p>and the network request looks like I expected (HTTP status <code>400</code> is also expected):</p> <p><a href="https://i.stack.imgur.com/FmAW9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FmAW9.png" alt="network request"></a></p> <p>I can't imagine how to solve the thing (and how to understand) why the request will send on localhost as <code>OPTIONS</code> and to remote servers as <code>POST</code>. Is there a solution how to fix this strange issue?</p>
40,497,696
6
6
null
2016-11-08 22:18:14.143 UTC
9
2022-01-16 17:58:57.057 UTC
2019-11-20 15:57:52.467 UTC
null
971,141
null
1,115,471
null
1
31
javascript|php|angularjs|http|cors
64,897
<h2>TL;DR answer</h2> <h3>Explanation</h3> <p>The <code>OPTIONS</code> request is so called <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests" rel="noreferrer"><strong>pre-flight request</strong></a>, which is part of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer"><em>Cross-origin resource sharing</em> (CORS)</a>. Browsers use it to <strong>check if a request is allowed from a particular domain</strong> as follows:</p> <ol> <li>The browser wants to send a request to a particular URL, let's say a <code>POST</code> request with the <code>application/json</code> content type</li> <li>First, it sends the <em>pre-flight</em> <code>OPTIONS</code> request to the same URL</li> <li>What follows depends on the <em>pre-flight</em> request's response HTTP status code: <ul> <li>If the server replies with a non-<code>2XX</code> status response, the browser won't send the actual request (because he knows now that it would be refused anyway)</li> <li>If the server replies with a <code>HTTP 200 OK</code> (or any other <code>2XX</code>) response, the browser will send the actual request, <code>POST</code> in your case</li> </ul> </li> </ol> <h3>Solution</h3> <p>So, in your case, the proper header is present, you just have to <strong>make sure the <em>pre-flight</em> request's response HTTP status code is <code>200 OK</code> or some other successful one (<code>2XX</code>)</strong>.</p> <hr /> <h2>Detailed Explanation</h2> <h3><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests" rel="noreferrer">Simple requests</a></h3> <p>Browsers <strong>are not</strong> sending the <em>pre-flight</em> requests in some cases, those are so-called <em>simple requests</em> and are used in the following conditions:</p> <blockquote> <ul> <li>One of the allowed methods: - <code>GET</code> - <code>HEAD</code> - <code>POST</code></li> </ul> </blockquote> <ul> <li>Apart from the headers automatically set by the user agent (for example, Connection, User-Agent, etc.), the only headers which are allowed to be manually set are the following: <ul> <li><code>Accept</code></li> <li><code>Accept-Language</code></li> <li><code>Content-Language</code></li> <li><code>Content-Type</code> (but note the additional requirements below)</li> <li><code>DPR</code></li> <li><code>Downlink</code></li> <li><code>Save-Data</code></li> <li><code>Viewport-Width</code></li> <li><code>Width</code></li> </ul> </li> <li>The only allowed values for the Content-Type header are: <ul> <li><code>application/x-www-form-urlencoded</code></li> <li><code>multipart/form-data</code></li> <li><code>text/plain</code></li> </ul> </li> <li>No event listeners are registered on any <code>XMLHttpRequestUpload</code> object used in the request; these are accessed using the <code>XMLHttpRequest.upload</code> property.</li> <li>No <code>ReadableStream</code> object is used in the request.</li> </ul> <p>Such requests are sent directly and the server simply successfully processes the request or replies with an error in case it didn't match the CORS rules. In any case, the response will contain the CORS headers <code>Access-Control-Allow-*</code>.</p> <h3><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests" rel="noreferrer">Pre-flighted requests</a></h3> <p>Browsers <strong>are</strong> sending the <em>pre-flight</em> requests if the actual request doesn't meet the <em>simple request</em> conditions, the most usually:</p> <ul> <li>custom content types like <code>application/xml</code> or <code>application/json</code>, etc., are used</li> <li>the request method is other than <code>GET</code>, <code>HEAD</code> or <code>POST</code></li> <li>the <code>POST</code> method is of an another content type than <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code> or <code>text/plain</code></li> </ul> <p>You need to <strong>make sure that the response to the <em>pre-flight</em> request has the following attributes</strong>:</p> <ul> <li>successful HTTP status code, i.e. <code>200 OK</code></li> <li>header <code>Access-Control-Allow-Origin: *</code> (a wildcard <code>*</code> allows a request from any domain, you can use any specific domain to restrict the access here of course)</li> </ul> <p>From the other side, the server may <strong>refuse the CORS request</strong> simply by sending a response to the <em>pre-flight</em> request with the following attributes:</p> <ul> <li>non-success HTTP code (i.e. other than <code>2XX</code>)</li> <li>success HTTP code (e.g. <code>200 OK</code>), but without any CORS header (i.e. <code>Access-Control-Allow-*</code>)</li> </ul> <p>See the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">documentation on Mozilla Developer Network</a> or for example <a href="https://www.html5rocks.com/en/tutorials/cors/" rel="noreferrer">HTML5Rocks' CORS tutorial</a> for details.</p>
95,890
What is a variable's linkage and storage specifier?
<p>When someone talks about a variables storage class specifier, what are they talking about?<br> They also often talk about variable linkage in the same context, what is that?</p>
95,927
2
0
null
2008-09-18 19:15:06.453 UTC
15
2008-09-18 19:42:52.75 UTC
null
null
null
Benoit Lavigne
10,703
null
1
11
c++|c
4,965
<p>The storage class specifier controls the <em>storage</em> and the <em>linkage</em> of your variables. These are two concepts that are different. C specifies the following specifiers for variables: auto, extern, register, static.</p> <p><strong>Storage</strong><br> The storage duration determines how long your variable will live in ram.<br> There are three types of storage duration: static, automatic and dynamic.</p> <p><em>static</em><br> If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.</p> <p><em>automatic</em><br> If the variable is declared in a function, but <strong>without</strong> the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size).</p> <p><em>dynamic</em><br> If you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.</p> <p><strong>Linkage</strong><br> Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.</p> <p><em>no linkage</em><br> This variable is only visible where it was declared. Typically applies to variables declared in a function.</p> <p><em>internal linkage</em><br> This variable will be visible to all the functions within the file (called a <a href="https://stackoverflow.com/questions/28160/multiple-classes-in-a-header-file-vs-a-single-header-file-per-class">translation unit</a>), but other files will not know it exists.</p> <p><em>external linkage</em><br> The variable will be visible to other translation units. These are often thought of as "global variables".</p> <p>Here is a table describing the storage and linkage characteristics based on the specifiers</p> <pre> Storage Class Function File Specifier Scope Scope ----------------------------------------------------- none automatic static no linkage external linkage extern static static external linkage external linkage static static static no linkage internal linkage auto automatic invalid no linkage register automatic invalid no linkage </pre>
2,575,116
fopen / fopen_s and writing to files
<p>I'm using fopen in C to write the output to a text file. The function declaration is (where <code>ARRAY_SIZE</code> has been defined earlier):</p> <pre><code>void create_out_file(char file_name[],long double *z1){ FILE *out; int i; if((out = fopen(file_name, "w+")) == NULL){ fprintf(stderr, "***&gt; Open error on output file %s", file_name); exit(-1); } for(i = 0; i &lt; ARRAY_SIZE; i++) fprintf(out, "%.16Le\n", z1[i]); fclose(out); } </code></pre> <p>My questions: </p> <ol> <li><p>On compilation with MVS2008 I get the warning: warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. I haven't see much information on <code>fopen_s</code> so that I can change my code. Any suggestions? </p></li> <li><p>Can one instruct <code>fprintf</code> to write numbers at a desired numerical precision <strong>to a file</strong>? If I'm using <code>long double</code> then I assume that my answers are good till 15 digits after the decimal point. Am I right? </p></li> </ol>
2,575,187
6
2
null
2010-04-04 16:48:49.073 UTC
3
2015-10-15 14:36:58.137 UTC
2015-10-15 14:36:58.137 UTC
null
119,775
null
308,316
null
1
24
c|file-io|precision|fopen
95,286
<p><code>fopen_s</code> is a variant of <code>fopen</code> which contains parameter validation and hands back an error code instead of a pointer in case something goes wrong during the open process. It's more secure than the base variant because it accounts for more edge conditions. The compiler is warning you to use it because <code>fopen</code> represents a potential exploitation vector in your application.</p> <p>You can specify digits of precision to the <code>printf</code> family of functions by using the specifier <code>%.xg</code>, where <strong>x</strong> is the digits of precision you want in the output. A <code>long double</code> varies in precision from platform to platform, but you can generally bet on it being at least 16 digits of decimal precision.</p> <p>Edit: While I'm not entirely on board with the others who are suggesting that <code>fopen_s</code> is a <em>complete</em> waste of time, it does represent a pretty low chance of exploitation and it isn't widely supported. Some of the other functions warned about under C4996 are much more serious vulnerabilities, however, and using <code>_CRT_SECURE_NO_WARNINGS</code> is the equivalent of turning off the alarm for both "you left your bedroom door unlocked" and "you left a nuclear bomb in the kitchen". </p> <p>As long as you aren't restricted to using "pure C" for your project (e.g. for a school assignment or an embedded microcontroller), you would do well to exploit the fact that almost all modern C compilers are also C++ compilers and use the C++ <code>iostream</code> variants of all of these I/O functions in order to get both improved security <em>and</em> compatibility at the same time.</p>
3,086,418
Svn revert all properties changes
<p>I have a svn working copy which I attempted to reverse merge a couple of recent revisions into. I cancelled the merge before it completed as I changed my mind. Now my working copy has a couple of thousand "changes" from updates to the ancestry related properties on most of the files. I have about 10 files with real code changes mixed in which I don't want to have to seperate out by hand. </p> <p>Is there a way for me to revert all of the property changes without affecting the content changes?</p>
3,091,639
6
0
null
2010-06-21 16:21:59.077 UTC
6
2021-01-21 16:58:03.947 UTC
null
null
null
null
325,129
null
1
31
svn
14,627
<p>Turns out that Tortoise SVN can do this really nicely. In the commit dialog you can sort the "modified" files by "text status" or "properties status". I simply sorted by text status and then reverted all the "modified" files which had "normal" "text status".</p>
2,582,877
Find issues that were ever assigned to me
<p>I am trying to create a filter to search for all issues that were ever assigned to me, even after the assignee is changed. I cant find the appropriate search parameters for this. Is it even possible in jira?</p>
2,583,353
7
2
null
2010-04-06 05:43:18.817 UTC
13
2022-05-03 08:07:52.83 UTC
null
null
null
null
9,425
null
1
94
jira
41,426
<p>Check out the toolkit plugin <a href="https://studio.plugins.atlassian.com/wiki/display/JTOOL/JIRA+Toolkit+Plugin" rel="noreferrer">https://studio.plugins.atlassian.com/wiki/display/JTOOL/JIRA+Toolkit+Plugin</a></p> <p>It has a custom field 'Participant' which allows you to find all issues that you raised, were assigned to or commented on.</p> <p>Francis</p>
2,336,785
set language within a django view
<p><strong>background:</strong> The view is called when a payment service pings back a payment outcome behind the scenes - afterwhich I need to send an email in the right language to confirm payment and so on. I can get the language code back in the request from the payment server and would like to use that along with Django's i18n systems to determine which language to send my email out in.</p> <p>So I need to set the language of my django app from within a view. And then do my template rendering and emailing all in one go.</p> <p>setting <code>request.session['django_language'] = lang</code> only effects the next view when I'm testing.</p> <p>Is there any other way to do it?</p> <p>Cheers,</p> <p>Guy</p>
2,336,889
8
0
null
2010-02-25 19:03:21.913 UTC
25
2021-11-12 10:31:57.883 UTC
null
null
null
null
214,841
null
1
57
django|internationalization
56,163
<p>To quote parts from Django's Locale Middleware (<code>django.middleware.locale.LocaleMiddleware</code>):</p> <pre><code>from django.utils import translation class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). """ def process_request(self, request): language = translation.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() </code></pre> <p>The <code>translation.activate(language)</code> is the important bit.</p>
2,785,093
Facebook 'Friends.getAppUsers' using Graph API
<p>I have an application that uses the old REST API call <code>Friends.getAppUsers</code> to get the list of friends for the current user that have authorized my application.</p> <p>I have read the documentation, how do I do this with the Graph API? What would an example of this be?</p>
3,066,091
8
0
null
2010-05-06 23:02:16.307 UTC
59
2014-04-12 09:41:44.197 UTC
2014-04-12 09:41:44.197 UTC
null
1,045,444
null
233,202
null
1
87
facebook|facebook-graph-api|facebook-friends
66,017
<p>I've done a lot of investigations on this issue. From what I can tell, there is no way to do <code>Friends.getAppUsers</code> using Graph API. The latest SDKs provided by Facebook all use the old REST API to get friends using the application.</p>
2,721,455
Implementing few methods of a interface class-C#
<p>Is it possible in C# to have a class that implement an interface that has 10 methods declared but implementing only 5 methods i.e defining only 5 methods of that interface??? Actually I have an interface that is implemented by 3 class and not all the methods are used by all the class so if I could exclude any method??? </p> <p>I have a need for this. It might sound as a bad design but it's not hopefully. The thing is I have a collection of User Controls that needs to have common property and based on that only I am displaying them at run time. As it's dynamic I need to manage them for that I'm having Properties. Some Properties are needed by few class and not by all. And as the control increases this Properties might be increasing so as needed by one control I need to have in all without any use. just the dummy methods. For the same I thought if there is a way to avoid those methods in rest of the class it would be great. It sounds that there is no way other than having either the abstract class or dummy functions :-(</p>
2,721,470
11
3
null
2010-04-27 13:13:51.01 UTC
4
2017-06-27 06:53:30.737 UTC
2010-04-27 13:30:11.547 UTC
null
85,019
null
85,019
null
1
26
c#|interface
48,073
<p>You can make it an abstract class and add the methods you don't want to implement as abstract methods.</p> <p>In other words:</p> <pre><code>public interface IMyInterface { void SomeMethod(); void SomeOtherMethod(); } public abstract class MyClass : IMyInterface { // Really implementing this public void SomeMethod() { // ... } // Derived class must implement this public abstract void SomeOtherMethod(); } </code></pre> <p>If these classes all need to be concrete, not abstract, then you'll have to throw a <code>NotImplementedException</code>/<code>NotSupportedException</code> from inside the methods. But a much better idea would be to split up the interface so that implementing classes don't have to do this.</p> <p>Keep in mind that classes can implement multiple interfaces, so if some classes have some of the functionality but not all, then you want to have more granular interfaces:</p> <pre><code>public interface IFoo { void FooMethod(); } public interface IBar() { void BarMethod(); } public class SmallClass : IFoo { public void FooMethod() { ... } } public class BigClass : IFoo, IBar { public void FooMethod() { ... } public void BarMethod() { ... } } </code></pre> <p>This is probably the design you really should have.</p>
3,031,887
How to catch a "Done" key press from the soft keyboard
<p>how do I catch specific key events from the soft keyboard? specifically I'm interested in the "Done" key.</p>
3,032,071
11
0
null
2010-06-13 10:33:50.207 UTC
8
2021-02-04 15:34:58.48 UTC
2016-05-23 11:10:52.44 UTC
null
3,193,867
null
258,429
null
1
63
android
57,607
<p><strong>Note:</strong> This answer is old and no longer works. See the answers below.</p> <p>You catch the KeyEvent and then check its keycode. FLAG_EDITOR_ACTION is used to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done"</p> <pre><code>if (event.getKeyCode() == KeyEvent.FLAG_EDITOR_ACTION) //your code here </code></pre> <p>Find the docs <a href="http://developer.android.com/reference/android/view/KeyEvent.html" rel="nofollow noreferrer">here</a>. </p>
2,648,802
At what point is it worth using a database?
<p>I have a question relating to databases and at what point is worth diving into one. I am primarily an embedded engineer, but I am writing an application using Qt to interface with our controller. </p> <p>We are at an odd point where we have enough data that it would be feasible to implement a database (around 700+ items and growing) to manage everything, but I am not sure it is worth the time right now to deal with. I have no problems implementing the GUI with files generated from excel and parsed in, but it gets tedious and hard to track even with VBA scripts. I have been playing around with converting our data into something more manageable for the application side with Microsoft Access and that seems to be working well. If that works out I am only a step (or several) away from using an SQL database and using the Qt library to access and modify it.</p> <p>I don't have much experience managing data at this level and am curious what may be the best way to approach this. So what are some of the real benefits of using a database if any in this case? I realize much of this can be very application specific, but some general ideas and suggestions on how to straddle the embedded/application programming line would be helpful.</p> <p>This is not about putting a database in an embedded project. It is also not a business type application where larger databases are commonly used. I am designing a GUI for a single user on a desktop to interface with a micro-controller for monitoring and configuration purposes.</p> <hr> <p>I decided to go with SQLite. You can do some very interesting things with data that I didn't really consider an option when first starting this project.</p>
2,649,916
13
7
null
2010-04-15 20:38:18.09 UTC
26
2019-02-26 09:16:49.917 UTC
2013-11-01 20:16:54.67 UTC
null
102,937
null
317,948
null
1
56
c++|sql|database|qt|user-interface
3,974
<p>A database is worthwhile when: </p> <ol> <li>Your application evolves to some form of data driven execution.</li> <li>You're spending time designing and developing external data storage structures.</li> <li>Sharing data between applications or organizations (including individual people)</li> <li>The data is no longer short and simple.</li> <li>Data Duplication</li> </ol> <p><strong>Evolution to Data Driven Execution</strong><br> When the data is changing but the execution is not, this is a sign of a data driven program or parts of the program are data driven. A set of configuration options is a sign of a data driven function, but the whole application may not be data driven. In any case, a database can help manage the data. (The database library or application does not have to be huge like Oracle, but can be lean and mean like SQLite). </p> <p><strong>Design &amp; Development of External Data Structures</strong><br> Posting questions to <strong>Stack Overflow</strong> about serialization or converting trees and lists to use files is a good indication your program has graduated to using a database. Also, if you are spending any amount of time designing algorithms to store data in a file or designing the data in a file is a good time to research the usage of a database. </p> <p><strong>Sharing Data</strong><br> Whether your application is sharing data with another application, another organization or another person, a database can assist. By using a database, data consistency is easier to achieve. One of the big issues in problem investigation is that teams are not using the same data. The customer may use one set of data; the validation team another and development using a different set of data. A database makes versioning the data easier and allows entities to use the same data.</p> <p><strong>Complex Data</strong><br> Programs start out using small tables of hard coded data. This evolves into using dynamic data with maps, trees and lists. Sometimes the data expands from simple two columns to 8 or more. Database theory and databases can ease the complexity of organizing data. Let the database worry about managing the data and free up your application and your development time. After all, how the data is managed is not as important as to the quality of the data and it's accessibility. </p> <p><strong>Data Duplication</strong><br> Often times, when data grows, there is an ever growing attraction for duplicate data. Databases and database theory can minimize the duplication of data. Databases can be configured to warn against duplications.</p> <p>Moving to using a database has many factors to be considered. Some include but are not limited to: data complexity, data duplication (including parts of the data), project deadlines, development costs and licensing issues. If your program can run more efficiently with a database, then do so. A database may also save development time (and money). There are other tasks that you and your application can be performing than managing data. Leave data management up to the experts.</p>
2,973,270
Using a custom typeface in Android
<p>I want to use a custom font for my android application which I am creating.<br> I can individually change the typeface of each object from Code, but I have hundreds of them.</p> <p>So,</p> <ul> <li>Is there a way to do this from the XML? [Setting a custom typeface]</li> <li>Is there a way to do it from code in one place, to say that the whole application and all the components should use the custom typeface instead of the default one?</li> </ul>
2,973,931
21
4
null
2010-06-04 10:28:23.22 UTC
57
2021-02-09 18:27:45.08 UTC
2017-03-31 04:57:27.937 UTC
null
3,681,880
null
177,890
null
1
111
xml|android|layout|fonts
129,015
<blockquote> <p>Is there a way to do this from the XML?</p> </blockquote> <p><strike>No, sorry. You can only specify the built-in typefaces through XML.</strike></p> <blockquote> <p>Is there a way to do it from code in one place, to say that the whole application and all the components should use the custom typeface instead of the default one?</p> </blockquote> <p><strike>Not that I am aware of.</strike></p> <p>There are a variety of options for these nowadays:</p> <ul> <li><p>Font resources and backports in the Android SDK, if you are using <code>appcompat</code></p></li> <li><p><a href="https://android-arsenal.com/tag/37?sort=created" rel="nofollow noreferrer">Third-party libraries</a> for those not using <code>appcompat</code>, though not all will support defining the font in layout resources</p></li> </ul>
23,709,739
Why does node.js need python
<p>I am starting up with node This is from node.js README.md</p> <p>Prerequisites (Unix only):</p> <pre><code>* GCC 4.2 or newer * Python 2.6 or 2.7 * GNU Make 3.81 or newer * libexecinfo (FreeBSD and OpenBSD only) </code></pre> <p>Curious to know why does node.js need Python ? Does it use Python underneath its API</p>
23,710,101
2
1
null
2014-05-17 09:30:02.537 UTC
11
2014-05-17 10:50:28.75 UTC
null
null
null
null
1,371,989
null
1
36
python|node.js
23,298
<p>Node.js is built with <a href="https://code.google.com/p/gyp/">GYP</a> — cross-platform built tool written in Python. Also some other build steps are implemented in Python. So Python is required for building node from source.</p> <p>But you also need Python for building native addons.</p>
10,403,794
VBA Range from String
<p>This is kind of silly, but I've been stuck for a while in this simple statement:</p> <pre><code> Dim range1 as Range Dim mysheet as String Dim myrange as String mysheet = "Sheet1" range = "A1:A10" range1 = Worksheets(mysheet).Range(myrange) </code></pre> <p>I've testing all the solutions that I've found on the internet as for example <a href="http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx" rel="noreferrer">this</a>, <a href="https://stackoverflow.com/questions/2911577/how-to-convert-a-string-to-a-range-object">this</a> and <a href="http://anthony-vba.kefra.com/forum/viewtopic.php?t=1917&amp;sid=efca1b5454c7f98554a3ed908b7b3bda" rel="noreferrer">this</a>, but nothing. </p> <p>All the time it gives me errors: 1004 "Error defined by the application" or "object variable or with not set".</p> <p>I have tried the following:</p> <pre><code>range1 = ThisWorkbook.Worksheets(mysheet).Range(myrange) range1 = ActiveWorkbook.Worksheets(mysheet).Range(myrange) range1 = Sheets(mysheet).Range(myrange) (and the combinations above) range1 = Worksheets(mysheet).Range(Cells(1,1), Cells(1,10)) (and the combinations with This/Active workbook) </code></pre> <p>and </p> <pre><code>with This/ActiveWorkbook range1 = .Worksheets(mysheet).Range(myrange) end with </code></pre> <p>None have worked.</p> <p>This is a REALLY silly thing, but I've been stuck for a while now :s</p> <p>Can anyone help me?</p> <p>Really thanks in advance.</p> <p>Best regards,</p>
10,403,853
1
0
null
2012-05-01 20:20:44.01 UTC
2
2012-05-02 09:04:20.033 UTC
2017-05-23 12:34:04.65 UTC
null
-1
null
1,238,957
null
1
17
vba|excel
68,865
<p>You need to use Set to assign objects:</p> <pre><code>Set range1 = Worksheets(mysheet).Range(myrange) </code></pre>
10,841,060
Regex to replace values that include part of match in replacement in sublime?
<p>I've come up with this regex that finds all words that start with <code>$</code> and contain <code>_</code> underscores:</p> <p><code>\$(\w+)_(\w+)</code></p> <p>I'm basically searching for variables, like <code>$var_foo</code> etc.</p> <p>How do I replace stuff using the regex groups?</p> <p>For example, how can I remove the underscore and make the next letter uppercase, like <code>$varFoo</code> ?</p>
10,841,126
1
0
null
2012-05-31 20:49:00.107 UTC
10
2014-10-22 08:24:30.46 UTC
2014-10-22 08:24:30.46 UTC
null
1,922,144
null
376,947
null
1
44
regex|sublimetext|textmate|oniguruma
27,627
<p>The replacement expression is:</p> <pre><code>\$\1\u\2 </code></pre> <ul> <li><code>\1</code>, <code>\2</code> are the captures (or <code>$1</code>, <code>$2</code>)</li> <li><code>\u</code> up-cases (see the <a href="http://manual.macromates.com/en/regular_expressions#replacement_string_syntax_format_strings">Replacement String Syntax section</a>).</li> </ul> <p>See the <a href="http://manual.macromates.com/en/regular_expressions#regular_expressions">Regular Expressions chapter</a> <sup>(in the <a href="http://manual.macromates.com/en/">TextMate docs</a>)</sup> for more information. </p> <p>There's already a package that does this, and more:</p> <ul> <li><a href="http://thecrumb.com/2011/10/27/sublime-text-package-of-the-day-case-conversion/">Brief blog about CaseConversion</a></li> <li><a href="https://bitbucket.org/scottbessler/sublimetextcaseconversion/src">CaseConversion package</a></li> </ul>
5,743,390
Creating ARPA language model file with 50,000 words
<p>I want to create an ARPA language model file with nearly 50,000 words. I can't generate the language model by passing my text file to the CMU Language Tool. Is any other link available where I can get a language model for these many words?</p>
6,356,792
2
1
null
2011-04-21 11:24:07.877 UTC
11
2016-07-16 15:14:17.097 UTC
2016-07-16 15:14:17.097 UTC
null
2,950,946
null
686,849
null
1
14
speech-recognition|cmusphinx|n-gram|language-model
7,390
<p>I thought I'd answer this one since it has a few votes, although based on Christina's other questions I don't think this will be a usable answer for her since a 50,000-word language model almost certainly won't have an acceptable word error rate or recognition speed (or most likely even function for long) with in-app recognition systems for iOS that use this format of language model currently, due to hardware constraints. I figured it was worth documenting it because I think it may be helpful to others who are using a platform where keeping a vocabulary this size in memory is more of a viable thing, and maybe it will be a possibility for future device models as well.</p> <p>There is no web-based tool I'm aware of like the Sphinx Knowledge Base Tool that will munge a 50,000-word plaintext corpus and return an ARPA language model. But, you can obtain an already-complete 64,000-word DMP language model (which can be used with Sphinx at the command line or in other platform implementations in the same way as an ARPA .lm file) with the following steps:</p> <ol> <li>Download this language model from the CMU speech site:</li> </ol> <p><a href="http://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/US%20English%20HUB4%20Language%20Model/HUB4_trigram_lm.zip" rel="noreferrer">http://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/US%20English%20HUB4%20Language%20Model/HUB4_trigram_lm.zip</a></p> <p>In that folder is a file called language_model.arpaformat.DMP which will be your language model.</p> <ol start="2"> <li>Download this file from the CMU speech site, which will become your pronunciation dictionary:</li> </ol> <p><a href="https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic" rel="noreferrer">https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic</a></p> <p>Convert the contents of cmu07a.dic to all uppercase letters. </p> <p>If you want, you could also trim down the pronunciation dictionary by removing any words from it which aren't found in the corpus language_model.vocabulary (this would be a regex problem). These files are intended for use with one of the Sphinx English-language acoustic models.</p> <p>If the desire to use a 50,000-word English language model is driven by the idea of doing some kind of generalized large vocabulary speech recognition and not by the need to use a very specific 50,000 words (for instance, something specialized like a medical dictionary or 50,000-entry contact list), this approach should give those results if the hardware can handle it. There are probably going to be some Sphinx or Pocketsphinx settings that will need to be changed which will optimize searches through this size of model.</p>
23,259,586
Bcrypt password hashing in Golang (compatible with Node.js)?
<p>I set up a site with Node.js+passport for user authentication. </p> <p>Now I need to migrate to Golang, and need to do authentication with the user passwords saved in db. </p> <p>The Node.js encryption code is:</p> <pre><code> var bcrypt = require('bcrypt'); bcrypt.genSalt(10, function(err, salt) { if(err) return next(err); bcrypt.hash(user.password, salt, function(err, hash) { if(err) return next(err); user.password = hash; next(); }); }); </code></pre> <p>How to make the same hashed string as Node.js bcrypt with Golang?</p>
23,259,804
3
0
null
2014-04-24 04:03:58.5 UTC
28
2020-08-24 15:25:23.323 UTC
2016-08-02 18:54:50.403 UTC
user6169399
null
null
2,036,213
null
1
80
node.js|go|bcrypt
56,193
<p>Using the <a href="http://godoc.org/golang.org/x/crypto/bcrypt" rel="noreferrer">golang.org/x/crypto/bcrypt</a> package, I believe the equivalent would be:</p> <pre><code>hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) </code></pre> <p><strong>Working example:</strong></p> <pre><code>package main import ( "golang.org/x/crypto/bcrypt" "fmt" ) func main() { password := []byte("MyDarkSecret") // Hashing the password with the default cost of 10 hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { panic(err) } fmt.Println(string(hashedPassword)) // Comparing the password with the hash err = bcrypt.CompareHashAndPassword(hashedPassword, password) fmt.Println(err) // nil means it is a match } </code></pre>
23,073,799
Make span element hidden when javascript validation succeeds
<p>I am stuck on how to make a span element become hidden again when the JavaScript validation succeeds. Currently <code>onchange</code> and <code>onblur</code> a red span appears showing an error if there is no text or if there are numbers in a name field. This does not disappear when the correct text is put in. I was just wondering how to make this message disappear when the correct text is put in? Code is below.</p> <p>JavaScript:</p> <pre><code>function validateName() { var name = form.firstname.value; if (form.firstname.value == "") { document.getElementById("firstnameInvalid").style.visibility = "visible"; return false; } if (/[0-9]/.test(name)) { document.getElementById("firstnameInvalid").style.visibility = "visible"; return false; } return true; } </code></pre> <p>Form HTML:</p> <pre><code>&lt;form name="form" method="post" action= "userdetails.html" onsubmit="return validate(this)"&gt; &lt;p&gt;First Name:&lt;input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name"&gt; &lt;span id="firstnameInvalid" style="color:red; visibility:hidden"&gt; First Name is Invalid &lt;/span&gt; &lt;/p&gt; </code></pre>
23,073,914
2
0
null
2014-04-15 02:44:05.237 UTC
null
2020-02-19 15:07:06.087 UTC
2016-08-31 13:51:32.257 UTC
null
3,885,376
null
3,534,211
null
1
7
javascript|html
49,133
<p>You're on the right track. </p> <p><a href="http://jsfiddle.net/isherwood/BHe5Z/" rel="nofollow noreferrer">Fiddle demo</a></p> <pre><code>function validateName() { var name = form.firstname.value; if (form.firstname.value == "") { document.getElementById("firstnameInvalid").style.visibility = "visible"; return false; } else if (/[0-9]/.test(name)) { document.getElementById("firstnameInvalid").style.visibility = "visible"; return false; } else { document.getElementById("firstnameInvalid").style.visibility = "hidden"; } } </code></pre> <p>You can simplify this a bit by using your variable and removing the returns, which don't seem to be necessary: </p> <p><a href="http://jsfiddle.net/isherwood/BHe5Z/1/" rel="nofollow noreferrer">Fiddle demo</a></p> <pre><code>function validateName() { var name = form.firstname.value; if (name == "") { document.getElementById("firstnameInvalid").style.visibility = "visible"; } else if (/[0-9]/.test(name)) { document.getElementById("firstnameInvalid").style.visibility = "visible"; } else { document.getElementById("firstnameInvalid").style.visibility = "hidden"; } } </code></pre>
41,146,373
Access function location programmatically
<p>Is it possible in code to access <code>["[[FunctionLocation]]"]</code> property that google chrome developer tools show when using console log on a function ?</p>
41,666,584
3
0
null
2016-12-14 15:32:38.353 UTC
5
2021-10-14 17:14:08.717 UTC
2021-10-14 17:14:08.717 UTC
null
1,048,572
null
1,256,902
null
1
31
javascript|google-chrome-devtools|v8|console.log
8,628
<p>The answer, for now, is <strong>no</strong>.</p> <p>The <code>[[FunctionLocation]]</code> property you see in Inspector is added in <a href="https://github.com/v8/v8/blob/f9fbaec39a201812c5e45c9b632f012ab3c531b7/src/inspector/v8-debugger.cc#L719-L721" rel="noreferrer"><code>V8Debugger::internalProperties()</code></a> in the debugger's C++ code, which uses another C++ function <a href="https://github.com/v8/v8/blob/f9fbaec39a201812c5e45c9b632f012ab3c531b7/src/inspector/v8-debugger.cc#L831-L861" rel="noreferrer"><code>V8Debugger::functionLocation()</code></a> to gather information about the function. <code>functionLocation()</code> then uses a number of V8-specific C++ APIs such as <a href="https://github.com/v8/v8/blob/f9fbaec39a201812c5e45c9b632f012ab3c531b7/include/v8.h#L3685-L3694" rel="noreferrer"><code>v8::Function::GetScriptLineNumber()</code> and <code>GetScriptColumnNumber()</code></a> to find out the exact information.</p> <p>All APIs described above are exclusively available to C++ code, not JavaScript code. In other words, JavaScript code on the webpage does not have direct access to this information.</p> <hr> <p>However, you may be able to get access to the properties using a Chrome extension. More recently, the V8 JavaScript engine used by Chrome has added support to access these properties through the <a href="https://chromedevtools.github.io/devtools-protocol/" rel="noreferrer">Chrome DevTools Protocol</a>. In particular, you can get the internal properties through the <a href="https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties" rel="noreferrer"><code>Runtime.getProperties</code></a> call. Additionally, it <a href="https://chromedevtools.github.io/devtools-protocol/#extension" rel="noreferrer">seems like</a> Chrome extensions may be able to interact with the DevTools protocol through <a href="https://developer.chrome.com/extensions/debugger.html" rel="noreferrer"><code>chrome.debugger</code></a>.</p> <p>A proof of concept for using the DevTools protocol in Node.js, which has direct access to the protocol using the <a href="https://nodejs.org/api/inspector.html" rel="noreferrer">Inspector</a> built-in module (helpfully mentioned by Mohamed in their answer):</p> <pre class="lang-js prettyprint-override"><code>global.a = () =&gt; { /* test function */ }; const s = new (require('inspector').Session)(); s.connect(); let objectId; s.post('Runtime.evaluate', { expression: 'a' }, (err, { result }) =&gt; { objectId = result.objectId; }); s.post('Runtime.getProperties', { objectId }, (err, { internalProperties }) =&gt; { console.log(internalProperties); }); </code></pre> <p>yields</p> <pre class="lang-js prettyprint-override"><code>[ { name: '[[FunctionLocation]]', value: { type: 'object', subtype: 'internal#location', value: [Object], description: 'Object' } }, { name: '[[Scopes]]', value: { type: 'object', subtype: 'internal#scopeList', className: 'Array', description: 'Scopes[2]', objectId: '{"injectedScriptId":1,"id":24}' } } ] </code></pre> <p>with Node.js v12.3.1.</p>
47,255,455
babel-polyfill vs babel-plugins
<p>I am a bit lost in the Babel options / config. I want to use recent js features and compile (with webpack) to browser code. </p> <p>What is the difference between <a href="https://babeljs.io/docs/usage/polyfill/" rel="noreferrer">babel-polyfill</a> and <a href="https://babeljs.io/docs/plugins/" rel="noreferrer">babel plugins</a> with <code>babel-preset-env</code>? </p> <p>Are they intended to work together?</p>
47,326,735
2
0
null
2017-11-13 00:13:11.007 UTC
8
2018-01-28 20:58:08.827 UTC
2017-11-16 00:49:10.99 UTC
null
2,112,538
null
2,112,538
null
1
15
babeljs|babel-polyfill
7,637
<p>Answer from <a href="https://medium.com/@jcse/clearing-up-the-babel-6-ecosystem-c7678a314bf3" rel="noreferrer">this article</a>: </p> <blockquote> <p>The distinction between a <code>babel transform plugin</code> versus <code>babel-polyfill / babel-runtime</code> <strong>is whether or not you can reimplement the feature today, in ES5</strong>. For example, <code>Array.from</code> can be rewritten in ES5 but there is nothing I can write in ES5 to add arrow function syntax to JavaScript. Therefore, there is a transform for arrow functions but none for <code>Array.from</code>. It will have to be provided by a separate polyfill like <code>babel-polyfill</code>, or <code>babel-runtime</code>.</p> </blockquote> <hr> <p>As a side note, here is my current understanding of the babel eco-system.</p> <p><code>Babel</code> is a javascript compiler: it <strong>parses</strong>, <strong>transforms</strong> and <strong>outputs transformed code</strong>.</p> <h3>babel-core</h3> <ul> <li>This is the <strong>parse</strong> and <strong>output</strong> parts.</li> <li>It does not do any transformation.</li> <li>It can be used from the command line or from a bundler (webpack, rollup and co.)</li> </ul> <h3>babel-polyfill / babel-runtime</h3> <ul> <li>Acts on the <strong>transform</strong> part by prepending es5 javascript to your code to emulate <strong>es2015+ functions</strong> (like Object.assign). </li> <li>Relies on <a href="https://medium.com/@jcse/clearing-up-the-babel-6-ecosystem-c7678a314bf3" rel="noreferrer">Regenerator</a> (to polyfill <a href="https://github.com/facebook/regenerator" rel="noreferrer">generators</a>) and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A" rel="noreferrer">core-js</a> (to polyfill all the rest).</li> <li>Difference between <code>babel-polyfill</code> and <code>babel-runtime</code>: the former defines global methods (and pollutes the global scope) whereas the latter transforms your code to make the same functionnality available as <a href="https://stackoverflow.com/a/31790138/2112538">explained in this answer</a>.</li> </ul> <h3>babel plugins</h3> <ul> <li><strong>Transform</strong> the code you wrote. </li> <li><code>babel syntax / transform plugins</code>: parse and transform <strong>es2015+ syntax</strong> (like arrow functions) to convert it to es5.</li> <li><code>babel-plugins-stage-x</code> (from stage-0 to stage-4): transform future javascript syntax which is not in the JS specs yet, starting at stage-0 (just an idea) down to stage-4 (will land in the <code>babel-plugins</code> soon).</li> </ul> <h3>babel-preset-env</h3> <ul> <li><code>babel-preset-env</code> determines the Babel plugins and polyfills needed for a specific environment.</li> <li>With no configuration, it will load all the plugins (including es2015, es2016 and es2017) required to transpile es2015+ to es5.</li> <li>With a <code>target</code> option, it loads only the plugins required to run on a specific target.</li> <li>With the <code>builtIn</code> option, it uses only the <code>babel-polyfill</code> which are not <em>built-in</em> the target.</li> <li>Does not work with <code>babel-transform-runtime</code> yet (as of nov. 2017). (see <a href="https://github.com/babel/babel-preset-env/issues/246" rel="noreferrer">this issue</a>)</li> </ul>
17,981,673
Execute LambdaExpression and get returned value as object
<p>Is there a clean way to do this?</p> <pre><code>Expression&lt;Func&lt;int, string&gt;&gt; exTyped = i =&gt; "My int = " + i; LambdaExpression lambda = exTyped; //later on: object input = 4; object result = ExecuteLambdaSomeHow(lambda, input); //result should be "My int = 4" </code></pre> <p>This should work for different types.</p>
17,981,732
1
5
null
2013-07-31 21:56:06.177 UTC
4
2013-07-31 22:24:17.39 UTC
null
null
null
null
320,623
null
1
35
c#|lambda|expression
13,951
<p>Sure... you just need to compile your lambda and then invoke it...</p> <pre><code>object input = 4; var compiledLambda = lambda.Compile(); var result = compiledLambda.DynamicInvoke(input); </code></pre> <p>Styxxy brings up an excellent point... You would be better served by letting the compiler help you out. Note with a compiled expression as in the code below input and result are both strongly typed.</p> <pre><code>var input = 4; var compiledExpression = exTyped.Compile(); var result = compiledExpression(input); </code></pre>
53,309,622
What is the difference between AssetImage and Image.asset - Flutter
<p>In my application, I use these 2 classes but I don't know which one I should prioritize.</p> <pre><code>Image.asset('icons/heart.png') AssetImage('icons/hear.png') </code></pre> <p>Maybe there is one who fetches the image faster.</p>
53,309,748
2
0
null
2018-11-14 22:22:52.66 UTC
3
2022-01-24 10:15:49.737 UTC
null
null
null
null
2,679,301
null
1
48
dart|flutter
25,521
<p><code>Image</code> is a <code>StatefulWidget</code> and <code>Image.asset</code> is just a named constructor, you can use it directly on your widget tree.</p> <p><code>AssetImage</code> is an <code>ImageProvider</code> which is responsible for obtaining the image of the specified path.</p> <p>If you check the source code of the <code>Image.asset</code> you will find that it's using AssetImage to get the image.</p> <pre><code> Image.asset(String name, { Key key, AssetBundle bundle, this.semanticLabel, this.excludeFromSemantics = false, double scale, this.width, this.height, this.color, this.colorBlendMode, this.fit, this.alignment = Alignment.center, this.repeat = ImageRepeat.noRepeat, this.centerSlice, this.matchTextDirection = false, this.gaplessPlayback = false, String package, this.filterQuality = FilterQuality.low, }) : image = scale != null ? ExactAssetImage(name, bundle: bundle, scale: scale, package: package) : AssetImage(name, bundle: bundle, package: package), assert(alignment != null), assert(repeat != null), assert(matchTextDirection != null), super(key: key); </code></pre>
36,915,823
Spring RestTemplate and generic types ParameterizedTypeReference collections like List<T>
<p>An Abstract controller class requires List of objects from REST. While using Spring RestTemplate its not mapping it to required class instead it returns Linked HashMAp</p> <pre><code> public List&lt;T&gt; restFindAll() { RestTemplate restTemplate = RestClient.build().restTemplate(); ParameterizedTypeReference&lt;List&lt;T&gt;&gt; parameterizedTypeReference = new ParameterizedTypeReference&lt;List&lt;T&gt;&gt;(){}; String uri= BASE_URI +"/"+ getPath(); ResponseEntity&lt;List&lt;T&gt;&gt; exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference); List&lt;T&gt; entities = exchange.getBody(); // here entities are List&lt;LinkedHashMap&gt; return entities; } </code></pre> <p>If I use,</p> <pre><code>ParameterizedTypeReference&lt;List&lt;AttributeInfo&gt;&gt; parameterizedTypeReference = new ParameterizedTypeReference&lt;List&lt;AttributeInfo&gt;&gt;(){}; ResponseEntity&lt;List&lt;AttributeInfo&gt;&gt; exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference); </code></pre> <p>It works fine. But can not put in all subclasses, any other solution.</p>
41,182,994
7
0
null
2016-04-28 13:15:17.43 UTC
9
2022-04-24 04:05:10.47 UTC
null
null
null
null
1,346,369
null
1
51
java|resttemplate|spring-rest|spring-web
79,256
<p>I worked around this using the following generic method:</p> <pre><code>public &lt;T&gt; List&lt;T&gt; exchangeAsList(String uri, ParameterizedTypeReference&lt;List&lt;T&gt;&gt; responseType) { return restTemplate.exchange(uri, HttpMethod.GET, null, responseType).getBody(); } </code></pre> <p>Then I could call:</p> <pre><code>List&lt;MyDto&gt; dtoList = this.exchangeAsList("http://my/url", new ParameterizedTypeReference&lt;List&lt;MyDto&gt;&gt;() {}); </code></pre> <p>This did burden my callers with having to specify the <code>ParameterizedTypeReference</code> when calling, but meant that I did not have to keep a static mapping of types like in vels4j's answer&nbsp;</p>
30,019,323
How do I enable the preview panel for TypeScript files in Visual Studio 2015?
<p>I miss the feature that would show you the results of your TypeScript compile in a separate panel. I haven't found a way to turn that back on in Visual Studio 2015 with TypeScript 1.5 beta.</p> <p>I have WebEssentials for 2015 installed as well as ReSharper 9.1.</p> <p>Anyone have any luck with this?</p>
31,368,251
3
1
null
2015-05-03 20:59:18.507 UTC
4
2017-09-28 08:07:09.66 UTC
null
null
null
null
7,756
null
1
36
visual-studio|typescript|visual-studio-2015
11,495
<p>This has been removed from Web Essentials 2015 in VS 2015RC.</p> <p>See: <a href="https://github.com/madskristensen/WebEssentials2015/issues/53" rel="noreferrer">https://github.com/madskristensen/WebEssentials2015/issues/53</a></p> <blockquote> <p>madskristensen commented on Jun 8</p> <p>The TS preview pane has been removed from Web Essentials 2015 due to continuously running into conflicts with the TS compiler when new versions come out. The TS team are aware of it and I hope they will add the feature into the TS tooling in the future. It is possible that this feature will be included in the brand new Web Compiler extensions (<a href="https://visualstudiogallery.msdn.microsoft.com/3b329021-cd7a-4a01-86fc-714c2d05bb6c" rel="noreferrer">https://visualstudiogallery.msdn.microsoft.com/3b329021-cd7a-4a01-86fc-714c2d05bb6c</a>) when preview panes have been implemented.</p> </blockquote>
29,954,037
Why is an OPTIONS request sent and can I disable it?
<p>I am building a web API. I found whenever I use Chrome to POST, GET to my API, there is always an OPTIONS request sent before the real request, which is quite annoying. Currently, I get the server to ignore any OPTIONS requests. Now my question is what's good to send an OPTIONS request to double the server's load? Is there any way to completely stop the browser from sending OPTIONS requests?</p>
29,954,326
15
1
null
2015-04-29 20:37:22.013 UTC
217
2021-06-18 05:36:38.15 UTC
2021-03-21 19:49:28.713 UTC
null
9,918,730
null
1,663,023
null
1
554
http|cors|preflight
584,438
<p><strong>edit 2018-09-13</strong>: added some precisions about this pre-flight request and how to avoid it at the end of this reponse.</p> <p><code>OPTIONS</code> requests are what we call <code>pre-flight</code> requests in <code>Cross-origin resource sharing (CORS)</code>.</p> <p>They are necessary when you're making requests across different origins in specific situations. </p> <p>This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon. </p> <p>Your server should not ignore but handle these requests whenever you're attempting to do cross origin requests.</p> <p>A good resource can be found here <a href="http://enable-cors.org/" rel="noreferrer">http://enable-cors.org/</a></p> <p>A way to handle these to get comfortable is to ensure that for any path with <code>OPTIONS</code> method the server sends a response with this header </p> <p><code>Access-Control-Allow-Origin: *</code></p> <p>This will tell the browser that the server is willing to answer requests from any origin. </p> <p>For more information on how to add CORS support to your server see the following flowchart</p> <p><a href="http://www.html5rocks.com/static/images/cors_server_flowchart.png" rel="noreferrer">http://www.html5rocks.com/static/images/cors_server_flowchart.png</a></p> <p><img src="https://i.stack.imgur.com/6jsKY.png" alt="CORS Flowchart"></p> <hr> <p><strong>edit 2018-09-13</strong></p> <p>CORS <code>OPTIONS</code> request is triggered only in somes cases, as explained in <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" rel="noreferrer">MDN docs</a>:</p> <blockquote> <p>Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:</p> <p>The only allowed methods are:</p> <ul> <li>GET</li> <li>HEAD</li> <li>POST</li> </ul> <p>Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:</p> <ul> <li>Accept</li> <li>Accept-Language</li> <li>Content-Language</li> <li>Content-Type (but note the additional requirements below)</li> <li>DPR</li> <li>Downlink</li> <li>Save-Data</li> <li>Viewport-Width</li> <li>Width</li> </ul> <p>The only allowed values for the Content-Type header are:</p> <ul> <li>application/x-www-form-urlencoded</li> <li>multipart/form-data</li> <li>text/plain</li> </ul> <p>No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.</p> <p>No ReadableStream object is used in the request.</p> </blockquote>
25,750,253
bootstrap multiselect(refresh) is not working properly
<p>I am using bootstrap multiselect list box. When user selects options on the multiselect it shows correctly. But there is a option to reset the previously selected options. When user click on reset button, automatically <code>style=display:none</code> is adding to the dropdown button and the dropdown list is becomes invisible.</p> <p><strong>This is my code</strong></p> <pre><code>$("#button").click(function () { $('option', $('.multiselect')).each(function (element) { $(this).removeAttr('selected').prop('selected', false); }); $('.multiselect').multiselect('refresh'); }); </code></pre>
31,607,099
6
0
null
2014-09-09 17:04:26.267 UTC
9
2021-12-28 16:17:17.623 UTC
2014-09-09 17:12:17.167 UTC
null
3,408,779
null
3,408,779
null
1
12
jquery|twitter-bootstrap|bootstrap-multiselect
61,333
<p>Other helpful options are:</p> <ol> <li><p><code>$('Id').multiselect('refresh');</code> - Refreshs the multiselect based on the selected options of the select.</p></li> <li><p><code>$('Id').multiselect('destroy');</code> - Unbinds the whole plugin.</p></li> <li><p><code>buildFilter</code> :Builds the filter.</p></li> <li><p><code>buildSelectAll</code> : Build the selct all.Checks if a select all has already been created.</p></li> <li><p><code>$('Id').multiselect('select', ['1', '2', '4']);</code> - Select all options of the given values.</p></li> <li><p><code>clearSelection</code> : Clears all selected items.</p></li> <li><p><code>$('Id').multiselect('deselect', ['1', '2', '4']);</code> - Deselects all options of the given values.</p></li> <li><p><code>$('Id').multiselect('selectAll', true);</code> - Selects all enabled &amp; visible options.</p></li> <li><p><code>$('Id').multiselect('deselectAll', true);</code> - Deselects all options.</p></li> <li><p><code>$('Id').multiselect('rebuild');</code> - Rebuild the plugin.</p></li> <li><p><code>$('Id').multiselect('enable');</code> - Enable the multiselect.</p></li> <li><p><code>$('Id').multiselect('disable');</code> - Disable the multiselect.</p></li> <li><p><code>hasSelectAll</code> : Checks whether a select all checkbox is present.</p></li> <li><p><code>updateSelectAll</code> : Updates the select all checkbox based on the currently displayed and selected checkboxes.</p></li> <li><p><code>$('Id').multiselect('updateButtonText');</code> - Update the button text and its title based on the currently selected options.</p></li> <li><p><code>getSelected()</code> : Get all selected options.</p></li> <li><p><code>getOptionByValue()</code> : Gets a select option by its value.</p></li> <li><p><code>$('Id').multiselect('dataprovider', options);</code> - The provided data will be used to build the dropdown.</p></li> </ol> <p>for more detail visit <a href="http://davidstutz.github.io/bootstrap-multiselect/" rel="noreferrer">bootstrap-multiselect</a></p>