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
18,453,948
Android drawText including text wrapping
<p>I am currently creating an image editor and am attempting to draw text on top of on image using canvas.drawText(). So far I have been successful in doing this but when the user enters text that is too long, the text just continues on one line out of the page and doesn't wrap itself to the width of the screen. How would I go about doing this? I have tried using a static layout but cannot seem to get it to work, has anyone got a tutorial to do this?</p> <p>My function for drawing on a canvas using static layout:</p> <pre><code> public Bitmap createImage(float scr_x,float scr_y,String user_text){ Canvas canvas = new Canvas(image); scr_x = 100; scr_y = 100; final TextPaint tp = new TextPaint(Color.WHITE); canvas.save(); StaticLayout sl = new StaticLayout("" + user_text, tp, originalBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); sl.draw(canvas); return image; } </code></pre> <p>Okay, I've updated my code, but when I try to draw on the image nothing happens at all, I have no idea why either:</p> <pre><code> public Bitmap createImage(String user_text) { // canvas object with bitmap image as constructor Canvas canvas = new Canvas(image); TextPaint tp = new TextPaint(); tp.setColor(Color.RED); tp.setTextSize(50); tp.setTextAlign(Align.CENTER); tp.setAntiAlias(true); StaticLayout sl = new StaticLayout("" + user_text, tp, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1, 0, false); canvas.translate(100, 100); sl.draw(canvas); return image; } </code></pre> <p>Is staticlayout not meant to be used to draw on canvas?</p>
18,520,131
3
2
null
2013-08-26 22:17:01.97 UTC
10
2019-06-27 09:38:54.883 UTC
2013-08-26 23:20:42.187 UTC
null
2,113,326
null
2,113,326
null
1
19
android|canvas|word-wrap|drawtext
16,810
<p>Yes, <code>StaticLayout</code> <em>is</em> what you're meant to use to draw multi-line text on a <code>Canvas</code>. Save yourself a world of pain and don't think about breaking text yourself -- you're on the right path. </p> <p>I'm not sure about the bitmap problem, but your second code above worked just fine to draw text on a canvas for me. </p> <p><a href="https://stackoverflow.com/a/41779935/1323398">Learn to use <code>StaticLayout</code></a> , then <a href="http://developer.android.com/reference/android/text/Layout.html#draw(android.graphics.Canvas)" rel="nofollow noreferrer">draw the Layout object onto a canvas</a> using the <code>Layout.draw()</code> method.</p> <h3>References</h3>
5,162,960
Should PUT and DELETE be used in forms?
<p>Assuming my web application has full support of PUT and DELETE on the server side, should I make use of them? </p> <p>Basically my question is how many browsers support this:</p> <pre><code>&lt;form method="PUT"&gt; </code></pre> <p>or</p> <pre><code>&lt;form method="DELETE"&gt; </code></pre> <p>Is there any benefits to using these two HTTP Methods other than being REST-compliant? (assuming the replacement for these two methods is the commonly used POST)</p>
5,163,030
3
0
null
2011-03-02 03:03:47.9 UTC
13
2019-07-09 02:26:53.627 UTC
2011-03-02 03:29:33.677 UTC
null
172,322
null
69,742
null
1
92
html|http|rest|cross-browser
114,066
<p>Your question involves two closely related but separate standards, HTTP and HTML. The PUT and DELETE methods are part of HTTP. In HTTP they have obvious use in RESTful interfaces, and other services which build on HTTP such as Webdav.</p> <p>HTML up to version 4 only defines the use of POST and GET for forms. HTML5 at this time appears as though it may support the further methods. [note, support is not included in the current w3 draft]</p> <p>Any current browser support (I'm not directly aware of any) will be very limited and only really useful as an experiment at the bleeding edge.</p>
25,827,924
Function cannot be referenced as it is a deleted function
<p>Hello I am learning C++ from a book and am on a exercise question below</p> <p>Write a function that takes and returns an istream&amp;. The function should read the stream until it hits end-of-file. The function should print what it reads to the standard output. Reset the stream so that it is valid before returning the stream.</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;istream&gt; #include &lt;string&gt; #include &lt;string.h&gt; #include &lt;list&gt; #include &lt;vector&gt; #include &lt;fstream&gt; std::istream ReadFile(std::istream &amp;iStream) { std::string word; while (iStream &gt;&gt; word) {} std::cout &lt;&lt; "I read value " &lt;&lt; word &lt;&lt; std::endl; iStream.setstate(std::ios::goodbit); return iStream; } int _tmain(int argc, _TCHAR* argv[]) { ReadFile(std::cin); system("pause"); return 0; } </code></pre> <p>The above is my attempt, however I am getting errors at the "return iStream" line.</p> <pre><code>Error1 error C2280: 'std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::basic_istream(const std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;)' : attempting to reference a deleted function 2 IntelliSense: function "std::basic_istream&lt;_Elem, _Traits&gt;::basic_istream(const std::basic_istream&lt;_Elem, _Traits&gt;::_Myt &amp;) [with _Elem=char, _Traits=std::char_traits&lt;char&gt;]" (declared at line 77 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\istream") cannot be referenced -- it is a deleted function </code></pre> <p>I don't really know what these errors are, I am aware you can delete stuff but I am not onto that topic in the book yet. As far as I know I have not at all touched the istream file... Can someone help me please?</p> <p>Thanks!</p>
25,827,939
2
3
null
2014-09-13 21:34:33.963 UTC
8
2014-09-13 21:54:03.95 UTC
null
null
null
null
3,216,729
null
1
36
c++
87,755
<p>You can&rsquo;t return an <code>istream</code> by value because it&rsquo;s not copyable.</p> <p>Since it&rsquo;s not copyable the copy constructor has been deleted (to enforce the non-copyability), and that&rsquo;s the direct technical cause of the diagnostic.</p> <p>So, instead of</p> <pre><code>std::istream ReadFile(std::istream &amp;iStream) </code></pre> <p>&hellip; do</p> <pre><code>std::istream&amp; ReadFile(std::istream&amp; iStream) </code></pre> <p>In other news, &hellip;</p> <hr> <p>Instead of</p> <pre><code>#include "stdafx.h" </code></pre> <p>just turn off precompiled headers in the Visual Studio project settings.</p> <p>This also gives you more standard-conforming behavior for header inclusions.</p> <p>If you don&rsquo;t do that, then configure the project so that any warning about skipping an include, yields a hard compilation error.</p> <hr> <p>Instead of</p> <pre><code>iStream.setstate(std::ios::goodbit); </code></pre> <p>&hellip; do</p> <pre><code>istream.clear(); </code></pre> <hr> <p>Instead of the non-portable Microsoft monstrosity</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) </code></pre> <p>just use standard</p> <pre><code>int main() </code></pre> <p>or in C++11 trailing return type syntax,</p> <pre><code>auto main() -&gt; int </code></pre> <hr> <p>Instead of</p> <pre><code>system("pause"); </code></pre> <p>simply run your program via <kbd>Ctrl</kbd>+<kbd>F5</kbd> in Visual Studio. Or, place a breakpoint on the last right brace of <code>main</code> and run in the debugger. Or, run the program from the command line.</p> <hr> <p>The exercise formulation</p> <blockquote> <p><strong>&rdquo;</strong> should read the stream until it hits end-of-file</p> </blockquote> <p>is ambiguous, but anyway reading <em>words</em>, as you&rsquo;re doing, does not faithfully reproduce whitespace in the stream. For a more accurate reproduction of the stream contents you can either read <em>character</em> by character, or (via <code>getline</code>) <em>line</em> by line. Or, you can use a special mechanism for this task, namely outputting the <em>read buffer</em>, which does everything in one little statement.</p> <hr> <p>Finally, you don&rsquo;t need all those headers. You only need <code>&lt;iostream&gt;</code>, and if you choose to read lines, also <code>&lt;string&gt;</code>. Also, you don&rsquo;t need the <code>return 0;</code> at the end of <code>main</code>, because that&rsquo;s the default.</p>
9,531,214
Access individual bits in a char c++
<p>How would i go about accessing the individual bits inside a c++ type, <code>char</code> or any c++ other type for example.</p>
9,531,250
4
3
null
2012-03-02 09:56:44.077 UTC
16
2020-06-20 07:48:49.507 UTC
null
null
null
null
1,240,563
null
1
21
c++|bit
39,663
<p>If you want access bit <code>N</code>:</p> <p>Get: <code>(INPUT &gt;&gt; N) &amp; 1;</code></p> <p>Set: <code>INPUT |= 1 &lt;&lt; N;</code></p> <p>Unset: <code>INPUT &amp;= ~(1 &lt;&lt; N);</code></p> <p>Toggle: <code>INPUT ^= 1 &lt;&lt; N;</code></p>
9,630,430
Upload large file in Android without outofmemory error
<p>My upload code as below:</p> <pre><code>String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; try { URL url = new URL(ActionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Accept", "text/*"); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data;" + "name=\"folder\"" + end + end); ds.write(SavePath.getBytes("UTF-8")); ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data;" + "name=\"Filedata\"; filename=\""); ds.write(FileName.getBytes("UTF-8")); ds.writeBytes("\"" + end); ds.writeBytes(end); FileInputStream fStream = new FileInputStream(uploadFilepath+""+FileName); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; int pro = 0; while((length = fStream.read(buffer)) != -1) { ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); fStream.close(); ds.flush(); InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while((ch = is.read()) != -1) { b.append((char)ch); } ds.close(); } catch(Exception e) { e.printStackTrace(); } </code></pre> <p>While smaller than 16 mb, it upload success. But while it more than 16 mb, the "OutOfMemory" error show. How to avoid the outofmemory error?</p>
9,630,475
3
3
null
2012-03-09 07:27:21.187 UTC
28
2018-12-13 17:44:46.12 UTC
2018-04-26 08:50:15.273 UTC
null
1,276,636
null
1,070,896
null
1
27
android|upload|out-of-memory|httpurlconnection
35,938
<p>Did you try using </p> <pre><code>con.setChunkedStreamingMode(1024); </code></pre> <p>This will help you to chunk your data into specific size, so that you need not keep your entire file in the memory.</p> <p><strong>UPDATE:</strong></p> <p>Try using the below method. I use this method to upload a 80 mb file without Exception. </p> <pre><code>public String sendFileToServer(String filename, String targetUrl) { String response = "error"; Log.e("Image filename", filename); Log.e("url", targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; // DataInputStream inputStream = null; String pathToOurFile = filename; String urlServer = targetUrl; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss"); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { FileInputStream fileInputStream = new FileInputStream(new File( pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs &amp; Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); String connstr = null; connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; Log.i("Connstr", connstr); outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Log.e("Image length", bytesAvailable + ""); try { while (bytesRead &gt; 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); response = "outofmemoryerror"; return response; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { e.printStackTrace(); response = "error"; return response; } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Log.i("Server Response Code ", "" + serverResponseCode); Log.i("Server Response Message", serverResponseMessage); if (serverResponseCode == 200) { response = "true"; } String CDate = null; Date serverTime = new Date(connection.getDate()); try { CDate = df.format(serverTime); } catch (Exception e) { e.printStackTrace(); Log.e("Date Exception", e.getMessage() + " Parse Exception"); } Log.i("Server Response Time", CDate + ""); filename = CDate + filename.substring(filename.lastIndexOf("."), filename.length()); Log.i("File Name in Server : ", filename); fileInputStream.close(); outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling response = "error"; Log.e("Send file Exception", ex.getMessage() + ""); ex.printStackTrace(); } return response; } </code></pre>
18,569,815
What's the point of "javascript:" in code (not URLs)?
<p>I stumbled upon something strange that I never really seen before:</p> <pre><code>javascript:a=a+10; </code></pre> <p>The line above seems to be correct and evaluates happily (at least in Firefox) just like if the <code>javascript:</code> part never existed.</p> <p>While I do understand the purpose of the old <code>javascript:void(...)</code> style <code>&lt;a href=".."/&gt;</code> used during the dark ages of <a href="https://en.wikipedia.org/wiki/Dynamic_HTML" rel="noreferrer">DHTML</a>, I just can't figure out any useful usage of this prefix in plain JavaScript code.</p> <p>Does it have some special meaning?</p>
18,569,870
4
8
null
2013-09-02 09:28:53.783 UTC
5
2013-09-12 05:55:43.457 UTC
2013-09-08 08:48:41.45 UTC
null
63,550
null
752,872
null
1
83
javascript
3,807
<p>The "<code>javascript:</code>" is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label" rel="noreferrer">label</a>. It's supposed to be used to identify a loop so that you could then use "<code>break javascript;</code>" to break out of it, but is being misused here. It's harmless, but probably not a good idea to add a label to a statement that isn't a loop.</p>
18,236,599
Visits counter without database with PHP
<p>I have a single webpage and i would like to track how many times it's visited without using a database.</p> <p>I thought about XML, updating a file every time a user visits the page:</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;counter&gt;8&lt;/counter&gt; </code></pre> <p>Then i thought it could have been a better idea to declare a PHP counter in a separate file and then update it everytime a user visits the page.</p> <p>counter.php</p> <pre><code>&lt;?php $counter = 0; ?&gt; </code></pre> <p>update_counter.php:</p> <pre><code>&lt;?php include "counter.php"; $counter += 1; $var = "&lt;?php\n\t\$counter = $counter;\n?&gt;"; file_put_contents('counter.php', $var); ?&gt; </code></pre> <p>With this, everytime <code>update_counter.php</code> is visited, the variable in the <code>counter.php</code> file is incremented.</p> <p>Anyway, i noticed that if the <code>counter.php</code> file has <code>$counter = 5</code> and the <code>update_counter.php</code> file is visited by i.e. 1000 users at the exact same time, the file gets read 1000 times at the same time (so the the value <code>5</code> gets read in all requests) the <code>counter.php</code> file will be updated with value <code>5+1 (=6)</code> instead of <code>1005</code>.</p> <p>Is there a way to make it work without using database?</p>
18,237,034
5
5
null
2013-08-14 15:56:31.737 UTC
8
2020-06-19 04:41:48.957 UTC
null
null
null
null
1,759,845
null
1
8
php|counter
20,772
<p>You can use <code>flock()</code> which will lock the file so that other processes are not writing to the file. </p> <p>Edit: updated to use <code>fread()</code> instead of <code>include()</code></p> <pre><code>$fp = fopen("counter.txt", "r+"); while(!flock($fp, LOCK_EX)) { // acquire an exclusive lock // waiting to lock the file } $counter = intval(fread($fp, filesize("counter.txt"))); $counter++; ftruncate($fp, 0); // truncate file fwrite($fp, $counter); // set your data fflush($fp); // flush output before releasing the lock flock($fp, LOCK_UN); // release the lock fclose($fp); </code></pre>
18,296,850
Click table rows to select checkbox using jQuery
<p>As I didn't find any question asked before, on how to toggle checkbox on click of a table row, so I would like to share my approach to this...</p>
18,296,851
5
0
null
2013-08-18 07:46:01.093 UTC
14
2019-11-04 18:29:59.303 UTC
null
null
null
null
1,542,290
null
1
28
jquery|checkbox|html-table
72,038
<p>In order to select the checkbox of a row inside the table, we will first check whether the <code>type</code> <code>attribute</code> of the element we are targetting is not a checkbox if it's not a checkbox than we will check all the checkboxes nested inside that table row.</p> <pre><code>$(document).ready(function() { $('.record_table tr').click(function(event) { if (event.target.type !== 'checkbox') { $(':checkbox', this).trigger('click'); } }); }); </code></pre> <p><a href="http://jsfiddle.net/FbHAV/" rel="noreferrer"><strong>Demo</strong></a></p> <hr> <p>If you want to highlight the table row on <code>checkbox</code> <code>checked</code> than we can use an <code>if</code> condition with <code>is(":checked")</code>, if yes than we find the closest <code>tr</code> element using <code>.closest()</code> and than we add class to it using <code>addClass()</code></p> <pre><code>$("input[type='checkbox']").change(function (e) { if ($(this).is(":checked")) { //If the checkbox is checked $(this).closest('tr').addClass("highlight_row"); //Add class on checkbox checked } else { $(this).closest('tr').removeClass("highlight_row"); //Remove class on checkbox uncheck } }); </code></pre> <p><a href="http://jsfiddle.net/FbHAV/2/" rel="noreferrer"><strong>Demo</strong></a></p>
18,747,500
How to set a default attribute value for a Laravel / Eloquent model?
<p>If I try declaring a property, like this:</p> <pre><code>public $quantity = 9; </code></pre> <p>...it doesn't work, because it is not considered an "attribute", but merely a property of the model class. Not only this, but also I am blocking access to the actually real and existent "quantity" attribute.</p> <p>What should I do, then?</p>
18,748,106
5
0
null
2013-09-11 17:22:11.917 UTC
6
2022-06-10 12:47:48.557 UTC
null
null
null
null
370,290
null
1
56
php|model|laravel|laravel-4|eloquent
82,057
<p>This is what I'm doing now:</p> <pre><code>protected $defaults = array( 'quantity' =&gt; 9, ); public function __construct(array $attributes = array()) { $this-&gt;setRawAttributes($this-&gt;defaults, true); parent::__construct($attributes); } </code></pre> <p>I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the <code>$defaults</code> array in our models...</p> <hr> <p><strong>UPDATE</strong>:</p> <p>As pointed by cmfolio, <strong>the actual ANSWER is quite simple</strong>: </p> <p>Just override the <code>$attributes</code> property! Like this:</p> <pre><code>protected $attributes = array( 'quantity' =&gt; 9, ); </code></pre> <p>The issue was discussed <a href="https://github.com/laravel/framework/issues/2265" rel="noreferrer">here</a>.</p>
18,534,343
Why SimpleDateFormat("MM/dd/yyyy") parses date to 10/20/20128?
<p>I have this code:</p> <pre><code> DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); dateFormat.setLenient(false); Date date = dateFormat.parse("10/20/20128"); </code></pre> <p>and I would expect the dateFormat.parse call to throw ParseException since the year I'm providing is 5 characters long instead of 4 like in the format I defined. But for some reason even with the lenient set to false this call returns a Date object of 10/20/20128.</p> <p>Why is that? It doesn't make much sense to me. Is there another setting to make it even more strict?</p>
18,534,451
5
5
null
2013-08-30 13:40:20.76 UTC
2
2021-12-05 12:02:24.327 UTC
null
null
null
null
2,266,509
null
1
23
java|date|simpledateformat|date-parsing
52,902
<p>20128 is a valid year and Java hopes the world to live that long I guess.</p> <blockquote> <p>if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.</p> </blockquote> <p><a href="http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year"><strong>Reference.</strong></a></p> <p>If you want to validate if a date is in limit, you can define one and check-</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date maxDate = sdf.parse("01/01/2099"); // This is the limit if(someDate.after(maxDate)){ System.out.println("Invalid date"); } </code></pre>
18,700,219
Rails 4: assets not loading in production
<p>I'm trying to put my app into production and image and css asset paths aren't working.</p> <p>Here's what I'm currently doing:</p> <ul> <li>Image assets live in /app/assets/images/image.jpg </li> <li>Stylesheets live in /app/assets/stylesheets/style.css</li> <li>In my layout, I reference the css file like this: <code>&lt;%= stylesheet_link_tag "styles", media: "all", "data-turbolinks-track" =&gt; true %&gt;</code></li> <li>Before restarting unicorn, I run <code>RAILS_ENV=production bundle exec rake assets:precompile</code> and it succeeds and I see the fingerprinted files in the <code>public/assets</code> directory.</li> </ul> <p>When I browse to my site, I get a 404 not found error for <code>mysite.com/stylesheets/styles.css</code>. </p> <p>What am I doing wrong?</p> <p><strong>Update:</strong> In my layout, it looks like this:</p> <pre><code>&lt;%= stylesheet_link_tag "bootstrap.min", media: "all", "data-turbolinks-track" =&gt; true %&gt; &lt;%= stylesheet_link_tag "styles", media: "all", "data-turbolinks-track" =&gt; true %&gt; &lt;%= javascript_include_tag "application", "data-turbolinks-track" =&gt; true %&gt; </code></pre> <p>The generate source is this:</p> <pre><code>&lt;link data-turbolinks-track="true" href="/stylesheets/bootstrap.min.css" media="all" rel="stylesheet" /&gt; &lt;link data-turbolinks-track="true" href="/stylesheets/styles.css" media="all" rel="stylesheet" /&gt; &lt;script data-turbolinks-track="true" src="/assets/application-0c647c942c6eff10ad92f1f2b0c64efe.js"&gt;&lt;/script&gt; </code></pre> <p>Looks like Rails is not properly looking for the compiled css files. But it's very confusing <em>why</em> it's working correctly for javascripts (notice the <code>/assets/****.js</code> path).</p>
18,702,000
18
15
null
2013-09-09 14:09:53.597 UTC
53
2019-08-17 07:42:26.297 UTC
2013-09-10 14:26:53.86 UTC
null
263,858
null
1,141,918
null
1
123
ruby-on-rails|ruby|asset-pipeline|ruby-on-rails-4
120,321
<p>In <code>/config/environments/production.rb</code> I had to add this:</p> <pre><code>Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb ) </code></pre> <p>The .js was getting precompiled already, but I added it anyway. The .css and .css.erb apparently don't happen automatically. The <code>^[^_]</code> excludes partials from being compiled -- it's a regexp.</p> <p>It's a little frustrating that the docs clearly state that asset pipeline IS enabled by default but doesn't clarify the fact that only applies to javascripts.</p>
27,603,782
Java Spring resttemplate character encoding
<p>I'm using the Java Spring Resttemplate for getting a json via a get request. The JSON I'm getting has instead of special character slike ü ö ä or ß some weird stuff. So I guess somethings wrong with the character encoding. I can't find any help on the internet. The code I'm using for now is:</p> <pre><code>String json = restTemplate.getForObject( overPassStatementPostCode, String.class, params); </code></pre>
28,742,831
6
5
null
2014-12-22 13:35:52.597 UTC
8
2022-07-05 07:05:05.34 UTC
2016-02-19 14:01:51.14 UTC
null
2,886,891
null
3,978,036
null
1
30
java|json|utf-8|character-encoding|resttemplate
66,675
<p>You just need to add the <code>StringHttpMessageConverter</code> to the template's message converters:</p> <pre><code>RestTemplate template = new RestTemplate(); template.getMessageConverters() .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); ResponseEntity&lt;Object&gt; response = template.exchange(endpoint, method, entity, Object.class); </code></pre>
14,929,819
Why is there no forEach method on Object in ECMAScript 5?
<p>ECMAScript 5's <code>array.forEach(callback[, thisArg])</code> is very convenient to iterate on an array and has many advantage over the syntax with a for:</p> <ul> <li>It's more concise. </li> <li>It doesn't create variables that we need only for the purpose of iterating. </li> <li>It's creates a visibility scope for the local variables of the loop.</li> <li>It boosts the performance.</li> </ul> <p><strong>Is there a reason why there is no <code>object.forEach</code> to replace <code>for(var key in object)</code> ?</strong></p> <p>Of course, we could use a JavaScript implementation, like _.each or $.each but those are performance killers.</p>
14,929,940
3
2
null
2013-02-18 05:05:22.587 UTC
11
2016-05-19 03:00:30.493 UTC
2013-02-18 05:08:19.45 UTC
user1645055
null
null
1,060,205
null
1
40
javascript|foreach|ecmascript-5
43,778
<p>Well, it's pretty easy to rig up yourself. Why further pollute the prototypes?</p> <pre><code>Object.keys(obj).forEach(function(key) { var value = obj[key]; }); </code></pre> <p>I think a big reason is that the powers that be want to avoid adding built in properties to <code>Object</code>. <code>Object</code>s are the building blocks of everything in Javascript, but are also the generic key/value store in the language. Adding new properties to <code>Object</code> would conflict with property names that your Javascript program might want to use. So adding built in names to <code>Object</code> is done with extreme caution.</p> <p>Array is indexed by integers, so it doesn't have this issue.</p> <p>This is also why we have <code>Object.keys(obj)</code> instead of simply <code>obj.keys</code>. Pollute the <code>Object</code> constructor as that it typically not a big deal, but leave instances alone.</p>
15,180,008
How to calculate the 95% confidence interval for the slope in a linear regression model in R
<p>Here is an exercise from Introductory Statistics with R:</p> <p>With the rmr data set, plot metabolic rate versus body weight. Fit a linear regression model to the relation. According to the fitted model, what is the predicted metabolic rate for a body weight of 70 kg? Give a 95% confidence interval for the slope of the line.</p> <p>rmr data set is in the 'ISwR' package. It looks like this:</p> <pre><code>&gt; rmr body.weight metabolic.rate 1 49.9 1079 2 50.8 1146 3 51.8 1115 4 52.6 1161 5 57.6 1325 6 61.4 1351 7 62.3 1402 8 64.9 1365 9 43.1 870 10 48.1 1372 11 52.2 1132 12 53.5 1172 13 55.0 1034 14 55.0 1155 15 56.0 1392 16 57.8 1090 17 59.0 982 18 59.0 1178 19 59.2 1342 20 59.5 1027 21 60.0 1316 22 62.1 1574 23 64.9 1526 24 66.0 1268 25 66.4 1205 26 72.8 1382 27 74.8 1273 28 77.1 1439 29 82.0 1536 30 82.0 1151 31 83.4 1248 32 86.2 1466 33 88.6 1323 34 89.3 1300 35 91.6 1519 36 99.8 1639 37 103.0 1382 38 104.5 1414 39 107.7 1473 40 110.2 2074 41 122.0 1777 42 123.1 1640 43 125.2 1630 44 143.3 1708 </code></pre> <p>I know how to calculate the predicted y at a given x but how can I calculate the confidence interval for the slope?</p>
15,180,053
1
1
null
2013-03-02 22:09:50.243 UTC
23
2013-03-03 08:40:59.287 UTC
2013-03-02 22:19:15.113 UTC
null
367,273
null
1,337,629
null
1
56
r|statistics|linear-regression|confidence-interval
218,704
<p>Let's fit the model:</p> <pre><code>&gt; library(ISwR) &gt; fit &lt;- lm(metabolic.rate ~ body.weight, rmr) &gt; summary(fit) Call: lm(formula = metabolic.rate ~ body.weight, data = rmr) Residuals: Min 1Q Median 3Q Max -245.74 -113.99 -32.05 104.96 484.81 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) (Intercept) 811.2267 76.9755 10.539 2.29e-13 *** body.weight 7.0595 0.9776 7.221 7.03e-09 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 157.9 on 42 degrees of freedom Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09 </code></pre> <p>The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).</p> <p>This can be computed using <a href="http://stat.ethz.ch/R-manual/R-patched/library/stats/html/confint.html"><code>confint</code></a>:</p> <pre><code>&gt; confint(fit, 'body.weight', level=0.95) 2.5 % 97.5 % body.weight 5.086656 9.0324 </code></pre>
28,211,418
Python: OSError: cannot load library libcairo.so.2
<p>I'm having some trouble running a python script on my Windows 7 platform. I've installed Python and also cairo, last one using "pip". I'm running the script using this command:</p> <pre><code>C:\Python34&gt;python.exe label/make_label.py </code></pre> <p>and I get the following error message:</p> <pre><code>Traceback (most recent call last): File "label/make_label.py", line 6, in &lt;module&gt; import cairocffi as cairo File "C:\Python34\lib\site-packages\cairocffi\__init__.py", line 41, in &lt;modul e&gt; cairo = dlopen(ffi, *CAIRO_NAMES) File "C:\Python34\lib\site-packages\cairocffi\__init__.py", line 34, in dlopen return ffi.dlopen(names[0]) # pragma: no cover File "C:\Python34\lib\site-packages\cffi\api.py", line 118, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "C:\Python34\lib\site-packages\cffi\api.py", line 411, in _make_ffi_libra ry backendlib = _load_backend_lib(backend, libname, flags) File "C:\Python34\lib\site-packages\cffi\api.py", line 400, in _load_backend_l ib return backend.load_library(name, flags) OSError: cannot load library libcairo.so.2: error 0x7e </code></pre> <p>What I've already done is the following:</p> <ul> <li>Added the PATH to GTK/bin in the environmental variable</li> <li>I check the folder GTK/bin and found "libcairo-2.dll" so I renamed it to libcairo.so</li> </ul> <p>I don't know what other information could be useful in solving this but please let me know and I'll try to add it.</p>
28,211,757
5
2
null
2015-01-29 09:44:19.193 UTC
4
2020-09-17 22:05:40.357 UTC
2020-03-30 19:12:33.977 UTC
null
6,573,902
null
2,180,252
null
1
27
python|windows|cairo
43,667
<p>It seems cairo depends a shared library which is not in standard search library, however, the python is calling dlopen to dynamic load the library, so you could try to put the libcairo.so.2(if it's a link, then make sure the reference locates at the same folder) in the working directory. You can also try pkg-config to set the environment. see here <a href="http://people.freedesktop.org/~dbn/pkg-config-guide.html" rel="noreferrer">http://people.freedesktop.org/~dbn/pkg-config-guide.html</a></p>
8,252,558
Is there a way to perform a mouseover (hover over an element) using Selenium and Python bindings?
<p>Reading <a href="http://groups.google.com/group/selenium-developers/browse_thread/thread/eebb4269d53b4a01" rel="noreferrer">here</a>, there apparently used to be a <code>RenderedWebElement</code> class with a <code>hover</code> method. It, however, was exclusively made for Java (I have searched the Python bindings documentation to no avail) and has since been deprecated for Java.</p> <p>A <code>hover</code> can't be performed using <a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.action_chains.html" rel="noreferrer"><code>action_chains</code></a> nor by using a <a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html" rel="noreferrer"><code>WebElement</code></a> object either. </p> <p>Any ideas as to how to do this for Python? I have been <a href="https://stackoverflow.com/questions/6232390/is-there-a-proved-mouseover-workaround-for-firefoxdriver-in-selenium2">here</a> but it uses <code>RenderedWebElement</code> and hence doesn't help too much.</p> <p><em>I am using: Python 2.7, Windows Vista, Selenium 2, Python Bindings</em> </p> <p><strong>EDIT:</strong> There is a method <code>mouse_over</code> for a <code>selenium.selenium.selenium</code> object but I cannot figure a way to create an instance without having the stand-alone server running already.</p> <p><strong>EDIT</strong> Please go through the comments of the reply marked as answer just in-case you have misconceptions like I did !</p>
8,261,754
2
0
null
2011-11-24 05:23:07.853 UTC
29
2020-06-08 13:33:45.073 UTC
2019-06-15 00:43:23.02 UTC
null
919,093
null
919,093
null
1
64
python|selenium|selenium-webdriver|python-bindings
100,252
<p>To do a hover you need to use the <code>move_to_element</code> method.</p> <p>Here is an example</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains firefox = webdriver.Firefox() firefox.get('http://foo.bar') element_to_hover_over = firefox.find_element_by_id("baz") hover = ActionChains(firefox).move_to_element(element_to_hover_over) hover.perform() </code></pre>
23,942,356
AngularJS Error: $injector:unpr Unknown Provider
<p>I'm trying to build my own service by following the example in the documentation for the factory methodology. I think I've done something wrong however because I continue to get the unknown provider error. This is my code for my app including the declaration, configuration and factory definition.</p> <p><strong>EDIT I've now added all of the files to help troubleshoot</strong></p> <p><strong>EDIT The full details of the error are below the issues appears to be with getSettings, as it's looking for getSettingsProvider and cannot find it</strong></p> <pre><code>Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr? p0=getSettingsProvider%20%3C-%20getSettings at Error (native) at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:6:450 at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:35:431 at Object.c [as get] (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:13) at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:35:499 at c (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:13) at d (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:230) at Object.instantiate (http://localhost/sw/selfservice/bower_components/angular/angular.min.js:34:394) at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:66:112 at http://localhost/sw/selfservice/bower_components/angular/angular.min.js:53:14 angular.js:9778 (anonymous function) angular.js:9778 (anonymous function) angular.js:7216 h.$apply angular.js:12512 (anonymous function) angular.js:1382 d angular.js:3869 $b.c angular.js:1380 $b angular.js:1394 Wc angular.js:1307 (anonymous function) angular.js:21459 a angular.js:2509 (anonymous function) angular.js:2780 q angular.js:330 c </code></pre> <p><br><br></p> <p>These are all of the files I have in my app currently</p> <p>app.JS</p> <pre><code>//Initialize angular module include route dependencies var app = angular.module("selfservice", ['ngRoute']); app.config(function ($routeProvider) { $routeProvider .when('/', { templateUrl:"partials/login.html", controller:"login" }); }); app.factory('getSettings', ['$http', '$q', function($http, $q) { return function (type) { var q = $q.defer(); $http.get('models/settings.json').success(function (data) { q.resolve(function() { var settings = jQuery.parseJSON(data); return settings[type]; }); }); return q.promise; }; }]); </code></pre> <p>And here is how I am using this service in my controller</p> <p>controller.JS</p> <pre><code>app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) { var loadSettings = getSettings('global'); loadSettings.then(function(val) { $scope.settings = val; }); }]); app.controller("login", ['$scope', function ($scope) { return "" }]); </code></pre> <p>directives.js</p> <pre><code>app.directive('watchResize', function(){ return { restrict: 'M', link: function(scope, elem, attr) { scope.spacer = (window.innerWidth &lt; 1025) ? '' : 'large-3'; scope.button = (window.innerWidth &lt; 1025) ? '' : 'large-6'; angular.element(window).on('resize', function(){ scope.$apply(function(){ scope.spacer = (window.innerWidth &lt; 1025) ? '' : 'large-3'; scope.button = (window.innerWidth &lt; 1025) ? '' : 'large-6'; }); }); } }; }); </code></pre> <p>And if it's pertinent here's the HTML</p> <pre><code>&lt;html class="no-js" lang="en" ng-app="selfservice" ng-controller="globalControl"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;title&gt;{{settings.title}}&lt;/title&gt; &lt;link rel="stylesheet" href="css/app.css" /&gt; &lt;script src="bower_components/modernizr/modernizr.js"&gt;&lt;/script&gt; &lt;script src="bower_components/angular/angular.min.js"&gt;&lt;/script&gt; &lt;script src="bower_components/angular-route/angular-route.min.js"&gt;&lt;/script&gt; &lt;script src="bower_components/jquery/dist/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="js/app.js"&gt;&lt;/script&gt; &lt;script src="js/controllers.js"&gt;&lt;/script&gt; &lt;script src="js/directives.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="template"&gt; &lt;header id="header"&gt; &lt;img src="{{settings.logo}}" alt="{{settings.logoDescription}}"/&gt; &lt;/header&gt; &lt;div id="view"&gt; &lt;ng-view&gt;&lt;/ng-view&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="bower_components/foundation/js/foundation.min.js"&gt;&lt;/script&gt; &lt;script&gt; //initialize foundation $(document).foundation(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can someone point me in the right direction? I have done my best to follow the documentation, and looking through SO most of the related issues are much more in depth, and more difficult for me to understand. This is my first time creating a service.</p>
23,942,850
13
5
null
2014-05-29 20:27:47.293 UTC
10
2020-07-24 06:10:13.273 UTC
2014-05-29 21:01:09.96 UTC
null
2,115,971
null
2,115,971
null
1
62
javascript|angularjs|angularjs-service
232,888
<p>Your angular module needs to be initialized properly. The global object <code>app</code> needs to be defined and initialized correctly to inject the service.</p> <p>Please see below sample code for reference:</p> <p>app.js</p> <pre><code>var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl:"partials/login.html", controller:"login" }); $locationProvider .html5Mode(true); }]); app.factory('getSettings', ['$http', '$q', function($http, $q) { return { //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand... getSetting: function (type) { var q = $q.defer(); $http.get('models/settings.json').success(function (data) { q.resolve(function() { var settings = jQuery.parseJSON(data); return settings[type]; }); }); return q.promise; } } }]); app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) { //Modified the function call for updated service var loadSettings = getSettings.getSetting('global'); loadSettings.then(function(val) { $scope.settings = val; }); }]); </code></pre> <p>Sample HTML code should be like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head lang="en"&gt; &lt;title&gt;Sample Application&lt;/title&gt; &lt;/head&gt; &lt;body ng-app="SampleApp" ng-controller="globalControl"&gt; &lt;div&gt; Your UI elements go here &lt;/div&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.</p> <p>I hope this will solve your basic injection issue.</p>
23,838,661
Why is Clang optimizing this code out?
<p>The purpose of the code is to find the total number of 32-bit floating point bit patterns which represent values between 0 and 1. It seems to me this should work, but for some reason the assembly output from Clang is basically the equivalent of <code>return 0;</code>.</p> <p>I compiled this with Clang 3.3 and Clang 3.4.1, using <code>-std=c++1y -Wall -Wextra -pedantic -O2</code> and <code>-std=c++1y -Wall -Wextra -pedantic -O3</code></p> <p>Clang 3.4 optimizes everything away with -O2 and -O3.</p> <p>Clang 3.3 only optimizes everything away with -O3.</p> <p>By "optimizes everything away" I mean that this is the assembly output of the program:</p> <pre><code>main: # @main xorl %eax, %eax ret </code></pre> <pre class="lang-c++ prettyprint-override"><code>#include &lt;limits&gt; #include &lt;cstring&gt; #include &lt;cstdint&gt; template &lt;class TO, class FROM&gt; inline TO punning_cast(const FROM &amp;input) { TO out; std::memcpy(&amp;out, &amp;input, sizeof(TO)); return out; } int main() { uint32_t i = std::numeric_limits&lt;uint32_t&gt;::min(); uint32_t count = 0; while (1) { float n = punning_cast&lt;float&gt;(i); if(n &gt;= 0.0f &amp;&amp; n &lt;= 1.0f) count++; if (i == std::numeric_limits&lt;uint32_t&gt;::max()) break; i++; } return count; } </code></pre>
23,839,549
3
54
null
2014-05-23 21:36:37.4 UTC
2
2015-11-26 15:09:20.923 UTC
2014-05-27 20:46:05.167 UTC
null
922,184
null
897,778
null
1
51
c++|clang|compiler-optimization
3,874
<p>Here's a simpler test case which points out that it's a compiler bug:</p> <p><a href="http://coliru.stacked-crooked.com/a/58b3f9b4edd8e373" rel="nofollow noreferrer">http://coliru.stacked-crooked.com/a/58b3f9b4edd8e373</a></p> <pre><code>#include &lt;cstdint&gt; int main() { uint32_t i = 0; uint32_t count = 1; while (1) { if( i &lt; 5 ) count+=1; if (i == 0xFFFFFFFF) break; i++; } return count; // should return 6 } </code></pre> <p>The assembly shows that it outputs 1, instead of 6. It doesn't think it's an infinite loop either, in which case the assembly doesn't return from main.</p>
5,051,135
Rails 3 check if attribute changed
<p>Need to check if a block of attributes has changed before update in Rails 3.</p> <p>street1, street2, city, state, zipcode</p> <p>I know I could use something like</p> <pre><code>if @user.street1 != params[:user][:street1] then do something.... end </code></pre> <p>But that piece of code will be REALLY long. Is there a cleaner way?</p>
5,051,147
5
0
null
2011-02-19 13:54:57.27 UTC
29
2020-02-09 22:25:50.18 UTC
null
null
null
null
216,135
null
1
160
ruby-on-rails|ruby-on-rails-3
125,805
<p>Check out <a href="http://api.rubyonrails.org/classes/ActiveModel/Dirty.html" rel="noreferrer">ActiveModel::Dirty</a> (available on all models by default). The documentation is really good, but it lets you do things such as:</p> <pre><code>@user.street1_changed? # =&gt; true/false </code></pre>
4,908,114
How to use onPause with Android?
<p>using <code>onSaveInstanceState(Bundle ..) and onRestoreInstanceState(Bundle ..)</code><br> was really good and work, but it is working when click Turn off button on Emulator.<br> Now, i want to save state and restore the saved data when below button used:<br> <img src="https://i.stack.imgur.com/wEWUY.jpg" alt="Emulator"></p> <p>I think it is possible to use OnPause() OR oOnStop(), if i am right, How to use it,<br> it will be enough to show me Java source of saving one boolean variable, and restore it,<br> Thanks.</p>
4,908,227
6
0
null
2011-02-05 16:43:04.097 UTC
8
2014-08-24 21:48:19.057 UTC
null
null
null
null
315,264
null
1
7
android
58,080
<p>I would use <code>onPause()</code>, as <code>onStop()</code> is not guaranteed to be called. See the <a href="http://developer.android.com/guide/topics/fundamentals.html" rel="noreferrer">application fundamentals</a> for details on the lifecycle.</p> <p>To save and restore a boolean, I would use <code>SharedPreferences</code>. There is a code example on the <a href="http://developer.android.com/guide/topics/data/data-storage.html#pref" rel="noreferrer">data storage page</a> that shows how to save and restore a boolean. They use <code>onCreate()</code> and <code>onStop()</code>, but I would use <code>onResume()</code> and <code>onPause()</code>, for the reasons I have already mentioned.</p>
4,850,702
Is CORS a secure way to do cross-domain AJAX requests?
<p>After reading about CORS (Cross-Origin Resource Sharing), I don't understand how it improves security. Cross-Domain AJAX communication is allowed if the correct ORIGIN header is sent. As an example, if I send</p> <p>ORIGIN: <a href="http://example.com" rel="noreferrer">http://example.com</a></p> <p>The server checks if this domain is in the white list and, if it is, header: </p> <p>Access-Control-Allow-Origin: [received url here] </p> <p>is sent back, together with the response (This is the simple case, there are also prefighted requests, but the question is the same).</p> <p>Is this really secure? If someone wants to receive the information, faking an ORIGIN headers seems like a really trivial task. Also the standard says that the policy is enforced in the browser, blocking the response if Access-Control-Allow-Origin is not correct. Obviously if anyone is trying to get that info, he will not use a standard browser to block it.</p>
4,850,752
6
1
null
2011-01-31 12:12:44.703 UTC
34
2021-05-28 12:21:58.357 UTC
2016-12-29 17:10:45.807 UTC
null
1,033,581
null
596,076
null
1
87
javascript|ajax|cross-domain|cors
28,703
<p>You can't fake an Origin header with JavaScript in a web browser. CORS is designed to prevent that.</p> <p>Outside of a web browser, it doesn't matter. It isn't designed to stop people from getting data that is available to the public. You can't expose it to the public without members of the public getting it.</p> <p>It is designed so that given:</p> <ul> <li>Alice, a person providing an API designed to be accessed via Ajax</li> <li>Bob, a person with a web browser</li> <li>Charlie, a third party running their own website</li> </ul> <p>If Bob visits Charlie's website, then Charlie cannot send JS to Bob's browser so that it fetches data from Alice's website and sends it to Charlie.</p> <p>The above situation becomes more important if Bob has a user account on Alice's website which allows him to do things like post comments, delete data, or see data that is <strong>not</strong> available to the general public — since without protection, Charlie's JS could tell Bob's browser to do that behind Bob's back (and then send the results to Charlie).</p> <p>If you want to stop unauthorized people from seeing the data, then you need to protect it with passwords, SSL client certs or some other means of identity-based authentication/authorization. </p>
5,593,686
Make DateTimePicker work as TimePicker only in WinForms
<p>How to restrict <code>DateTimePicker</code> to select the time only? I don't know how to disable calendar control which drops when you press the button at the right of <code>DateTimePicker</code>.</p>
5,593,716
6
0
null
2011-04-08 10:18:32.453 UTC
10
2022-05-09 06:57:10.583 UTC
2016-04-08 15:43:54.693 UTC
null
971,141
null
371,967
null
1
90
c#|winforms
118,517
<p>A snippet out of the <a href="http://msdn.microsoft.com/en-us/library/ms229631.aspx" rel="noreferrer">MSDN</a>:</p> <blockquote> <p>'The following code sample shows how to create a DateTimePicker that enables users to choose a time only.'</p> </blockquote> <pre><code>timePicker = new DateTimePicker(); timePicker.Format = DateTimePickerFormat.Time; timePicker.ShowUpDown = true; </code></pre> <p>And for anyone who wants to know what it looks like:</p> <p><a href="https://i.stack.imgur.com/I1FTr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/I1FTr.png" alt="enter image description here" /></a></p>
5,316,572
How to print 5 consecutive lines after a pattern in file using awk
<p>I would like to search for a pattern in a file and prints 5 lines after finding that pattern.</p> <p>I need to use <code>awk</code> in order to do this.</p> <p>Example: </p> <p>File Contents:</p> <pre class="lang-none prettyprint-override"><code>. . . . ####PATTERN####### #Line1 #Line2 #Line3 #Line4 #Line5 . . . </code></pre> <p>How do I parse through a file and print only the above mentioned lines? Do I use the NR of the line which contains "PATTERN" and keep incrementing upto 5 and print each line in the process. Kindly do let me know if there is any other efficient wat to do it in Awk.</p>
5,317,829
7
1
null
2011-03-15 18:56:27.913 UTC
14
2019-06-24 22:15:36.407 UTC
2018-11-17 21:07:05.29 UTC
null
5,848,185
null
224,640
null
1
44
shell|unix|awk
91,583
<p>Another way to do it in AWK:</p> <pre><code>awk '/PATTERN/ {for(i=1; i&lt;=5; i++) {getline; print}}' inputfile </code></pre> <p>in <code>sed</code>:</p> <pre><code>sed -n '/PATTERN/{n;p;n;p;n;p;n;p;n;p}' inputfile </code></pre> <p>in GNU <code>sed</code>:</p> <pre><code>sed -n '/PATTERN/,+7p' inputfile </code></pre> <p>or</p> <pre><code>sed -n '1{x;s/.*/####/;x};/PATTERN/{:a;n;p;x;s/.//;ta;q}' inputfile </code></pre> <p>The <code>#</code> characters represent a counter. Use one fewer than the number of lines you want to output.</p>
5,083,224
git pull while not in a git directory
<p>Let's say I have a directory, <code>/X/Y</code>, which is a git repository. Is it possible to somehow call a command like <code>git pull</code> from inside <code>/X</code>, but targeting the <code>/X/Y</code> directory?</p> <p><strong>EDIT:</strong> I guess I was wondering specifically: is it possible to do this using the a git command, but without having to change directories?</p> <p><strong>NOTE:</strong> I've accepted <a href="https://stackoverflow.com/questions/5083224/git-pull-while-not-in-a-git-directory/20115526#20115526">VonC's answer</a> as it's much more elegant than previous options. For people running Git older than 1.8.5, please see <a href="https://stackoverflow.com/questions/5083224/git-pull-while-not-in-a-git-directory/5083437#5083437">bstpierre's answer below</a>.</p>
20,115,526
9
3
null
2011-02-22 19:58:57.2 UTC
72
2020-02-06 10:18:23.683 UTC
2017-05-23 12:18:15.39 UTC
null
-1
null
528,317
null
1
343
git
156,406
<p>Starting <a href="https://github.com/git/git/blob/5fd09df3937f54c5cfda4f1087f5d99433cce527/Documentation/RelNotes/1.8.5.txt#L115-L116" rel="noreferrer">git 1.8.5 (Q4 2013)</a>, you will be able to "use a Git command, but without having to change directories".</p> <blockquote> <p>Just like "<code>make -C &lt;directory&gt;</code>", <strong>"<code>git -C &lt;directory&gt; ...</code>" tells Git to go there before doing anything else</strong>.</p> </blockquote> <p>See <a href="https://github.com/git/git/commit/44e1e4d67d5148c245db362cc48c3cc6c2ec82ca" rel="noreferrer">commit 44e1e4</a> by <strong><a href="http://perlresume.org/NAZRI" rel="noreferrer">Nazri Ramliy</a></strong>:</p> <blockquote> <p>It takes more keypresses to invoke Git command in a different directory without leaving the current directory:</p> <ol> <li><code>(cd ~/foo &amp;&amp; git status)<br> git --git-dir=~/foo/.git --work-tree=~/foo status<br> GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status</code> </li> <li><code>(cd ../..; git grep foo)</code></li> <li><code>for d in d1 d2 d3; do (cd $d &amp;&amp; git svn rebase); done</code></li> </ol> <p>The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.</p> <p>With this new option, the above can be done with fewer keystrokes:</p> <ol> <li><code>git -C ~/foo status</code></li> <li><code>git -C ../.. grep foo</code></li> <li><code>for d in d1 d2 d3; do git -C $d svn rebase; done</code></li> </ol> </blockquote> <hr> <p>Since Git 2.3.4 (March 2015), and <a href="https://github.com/git/git/commit/6a536e2076f02a98e0d6403ff68f3acf717fa1c4" rel="noreferrer">commit 6a536e2</a> by <a href="https://github.com/KarthikNayak" rel="noreferrer">Karthik Nayak (<code>KarthikNayak</code>)</a>, <code>git</code> will treat "<code>git -C '&lt;path&gt;'</code>" as a <strong>no-op when <code>&lt;path&gt;</code> is empty.</strong> </p> <blockquote> <p>'<code>git -C ""</code>' unhelpfully dies with error "<code>Cannot change to ''</code>", whereas the shell treats cd ""' as a no-op.<br> Taking the shell's behavior as a precedent, teach <code>git</code> to treat -C ""' as a no-op, as well.</p> </blockquote> <hr> <p>4 years later, Git 2.23 (Q3 2019) documents that '<code>git -C ""</code>' works and doesn't change directory</p> <blockquote> <p>It's been behaving so since 6a536e2 (<code>git</code>: treat "<code>git -C '&lt;path&gt;'</code>" as a no-op when <code>&lt;path&gt;</code> is empty, 2015-03-06, Git v2.3.4). </p> </blockquote> <p>That means <a href="https://github.com/git/git/blob/1a64e07d235579ae0b3bc6d1f081a51a6e48a4d1/Documentation/git.txt#L59-L60" rel="noreferrer">the documentation</a> now (finally) includes:</p> <blockquote> <p>If '<code>&lt;path&gt;</code>' is present but empty, e.g. <code>-C ""</code>, then the current working directory is left unchanged.</p> </blockquote> <hr> <p>You can see <code>git -C</code> used with Git 2.26 (Q1 2020), as an example.</p> <p>See <a href="https://github.com/git/git/commit/b44171725646880db07cbee6446e15b4afaa1930" rel="noreferrer">commit b441717</a>, <a href="https://github.com/git/git/commit/9291e6329ef3333f9447b0b4cdec0607e00c39cf" rel="noreferrer">commit 9291e63</a>, <a href="https://github.com/git/git/commit/5236fce6b4b597588f5e3955b309195f376a858f" rel="noreferrer">commit 5236fce</a>, <a href="https://github.com/git/git/commit/10812c2337eb04f2857000fd644efdc02247ca92" rel="noreferrer">commit 10812c2</a>, <a href="https://github.com/git/git/commit/62d58cda69621eb2f70517c87f1baeeb7b2f398c" rel="noreferrer">commit 62d58cd</a>, <a href="https://github.com/git/git/commit/b87b02cfe6973ac8cc778e0463bc3ad6accb96a6" rel="noreferrer">commit b87b02c</a>, <a href="https://github.com/git/git/commit/9b92070e5231773f564c1fe631cddd6d436963a5" rel="noreferrer">commit 9b92070</a>, <a href="https://github.com/git/git/commit/3595d10c26db483239d97ca8fc435c1c9dabcfb1" rel="noreferrer">commit 3595d10</a>, <a href="https://github.com/git/git/commit/f511bc02edc8e2729e7babb1b4caa98684d941bc" rel="noreferrer">commit f511bc0</a>, <a href="https://github.com/git/git/commit/f6041abdcd7bfefed1cbe14cbe221f0e848cbec4" rel="noreferrer">commit f6041ab</a>, <a href="https://github.com/git/git/commit/f46c243e669f5f1e6ef2f25000d5a5f593d2e1f3" rel="noreferrer">commit f46c243</a>, <a href="https://github.com/git/git/commit/99c049bc4c029471af5efcbd1a4ca1fd4a45b923" rel="noreferrer">commit 99c049b</a>, <a href="https://github.com/git/git/commit/3738439c7779acf2dafadbbc488bb222c94a2b12" rel="noreferrer">commit 3738439</a>, <a href="https://github.com/git/git/commit/7717242014dc59f58db7e56c2b8f9fc79e04fa0b" rel="noreferrer">commit 7717242</a>, <a href="https://github.com/git/git/commit/b8afb908c261752310d4792f901c68fe27b77b40" rel="noreferrer">commit b8afb90</a> (20 Dec 2019) by <a href="https://github.com/Denton-L" rel="noreferrer">Denton Liu (<code>Denton-L</code>)</a>.<br> <sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/381e8e9de142b636e4a25b6df113d70168e21a34" rel="noreferrer">commit 381e8e9</a>, 05 Feb 2020)</sup> </p> <blockquote> <h2><a href="https://github.com/git/git/commit/b44171725646880db07cbee6446e15b4afaa1930" rel="noreferrer"><code>t1507</code></a>: inline <code>full_name()</code></h2> <p><sup>Signed-off-by: Denton Liu</sup></p> <p>Before, we were running <code>test_must_fail full_name</code>. However, <code>test_must_fail</code> should only be used on git commands.<br> Inline <code>full_name()</code> so that we can use <code>test_must_fail</code> on the <code>git</code> command directly.</p> <p>When <code>full_name()</code> was introduced in <a href="https://github.com/git/git/commit/28fb84382b0eb728534dbe2972bbfec3f3d83dd9" rel="noreferrer">28fb84382b</a> ("Introduce <code>&lt;branch&gt;@{upstream}</code> notation", 2009-09-10, Git v1.7.0-rc0 -- <a href="https://github.com/git/git/commit/4ca1b623865a9dc100f95a7867e35a9f73d7507a" rel="noreferrer">merge</a>), the <code>git -C</code> option wasn't available yet (since it was introduced in <a href="https://github.com/git/git/commit/44e1e4d67d5148c245db362cc48c3cc6c2ec82ca" rel="noreferrer">44e1e4d67d</a> ("<code>git</code>: run in a directory given with -C option", 2013-09-09, Git v1.8.5-rc0 -- <a href="https://github.com/git/git/commit/087350398e8b2c5d4b39f051b23a2e533f4d830b" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/128a96c98442524c7f2eeef4757b1e48445f24ce" rel="noreferrer">batch #5</a>)).<br> As a result, the helper function removed the need to manually <code>cd</code> each time. However, since <code>git -C</code> is available now, we can just use that instead and inline <code>full_name()</code>.</p> </blockquote>
5,195,321
Remove an onclick listener
<p>I have an object where the text cycles and displays status messages. When the messages change, I want the click event of the object to change to take you to the activity that the message is relating to.</p> <p>So, I have a <code>TextView mTitleView</code> and I'm assigning the event like this.</p> <pre><code>public void setOnTitleClickListener(OnClickListener listener) { mTitleView.setOnClickListener(listener); } </code></pre> <p>How do I remove that click event? There are some status messages that do not have an actionable area so I'd like to turn off the click event. I'd also like to be able to cycle through these click events and dispose of them properly, but I'm unsure of the best practice.</p>
5,195,379
9
0
null
2011-03-04 14:57:05.917 UTC
24
2020-07-23 17:32:59.493 UTC
null
null
null
null
107,455
null
1
229
android|onclick|textview|listener
158,088
<p><code>mTitleView.setOnClickListener(null)</code> should do the trick.</p> <p>A better design might be to do a check of the status in the OnClickListener and then determine whether or not the click should do something vs adding and clearing click listeners.</p>
5,185,864
JavaScript quicksort
<p>I have been looking around the web for a while and I am wondering if there is a 'stable' defacto implementation of quicksort that is generally used? I can write my own but why reinvent the wheel...</p>
5,186,021
19
7
null
2011-03-03 19:59:55.27 UTC
18
2022-08-15 04:42:43.423 UTC
2012-04-16 12:56:02.253 UTC
null
31,671
null
109,614
null
1
28
javascript|quicksort
56,829
<p>You can easily "stabilize" an unstable sort using a decorate-sort-undecorate pattern</p> <pre><code>function stableSort(v, f) { if (f === undefined) { f = function(a, b) { a = ""+a; b = ""+b; return a &lt; b ? -1 : (a &gt; b ? 1 : 0); } } var dv = []; for (var i=0; i&lt;v.length; i++) { dv[i] = [v[i], i]; } dv.sort(function(a, b){ return f(a[0], b[0]) || (a[1] - b[1]); }); for (var i=0; i&lt;v.length; i++) { v[i] = dv[i][0]; } } </code></pre> <p>the idea is to add the index as last sorting term so that no two elements are now "the same" and if everything else is the same the original index will be the discriminating factor.</p>
12,496,838
How to add onChange attribute for select box from Javascript / jQuery
<p>I have select box with out <code>onChange</code> attribute. Now after loading the total page, based on some conditions I have to add <code>onChange</code> for the select box from Javascript. I am trying with the following code, but its not working:</p> <pre><code>$(&quot;#depositForm&quot;).attr((&quot;onChange&quot;, &quot;selectedMainDepositType('this');&quot; )); </code></pre> <p>Its is not adding the <code>onChange</code> event.</p> <pre><code>&lt;select id=&quot;depositForm_depositSubType&quot; class=&quot;depositSubType&quot; style=&quot;width:160px;&quot; name=&quot;depositSubType&quot;&gt; </code></pre> <p>has to be changed as</p> <pre><code>&lt;select id=&quot;depositForm_depositSubType&quot; onchange=&quot;selectedMainDepositType(this);&quot; class=&quot;depositSubType&quot; style=&quot;width:160px;&quot; name=&quot;depositSubType&quot;&gt; </code></pre> <p>Please suggest how to add the <code>onChange</code> attribute.</p>
12,496,854
5
2
null
2012-09-19 14:27:15.353 UTC
1
2020-07-03 17:36:11.337 UTC
2020-07-03 17:36:11.337 UTC
null
4,370,109
null
1,225,623
null
1
7
javascript|html|jquery|jquery-events
55,948
<p>Did you try...</p> <pre><code>$("#depositForm").on("change", function(event) { selectedMainDepositType(this); } ); </code></pre> <p><a href="http://api.jquery.com/on/" rel="noreferrer">jQuery .on()</a></p>
12,351,107
Request Attributes not available in jsp page when using sendRedirect from a servlet
<p>I am new to jsp and servlet. My scenario is as follows</p> <p>I have a jsp page which have a form in it. with two fields. The code snipet of the jsp page is as follows.</p> <p>MyFirstJSP.jsp file </p> <pre><code>&lt;body&gt; &lt;h1&gt; This is my first jsp and servlet project&lt;/h1&gt; &lt;% //System.out.println(request.getAttribute("fname")); if(request.getAttribute("fname")!=null){ System.out.println(request.getAttribute("fname")); }else{ System.out.println("No request "); } %&gt; &lt;form action="MyFirstServlet" method="get"&gt; First Name&lt;input type="text" name="fname" value= ${fname}&gt;&lt;br&gt; Last Name&lt;input type="text" name="lname" value= ${lname}&gt; &lt;input type="submit" value="Send"&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>When I submit this form the MyFirstServlet is called which checks the first name entered by user. If the first name is equals to "abc" then servlet sets the attribute to request object and send redirect it to the callsing jsp page i.e. above page. Which will get the value from request object and fill it in to respective field of form. I have Java Expression language too for same effect.</p> <p>Here is my code snipet of the MyFirstServlet.java servlet file</p> <pre><code>/** * Servlet implementation class MyFirstServlet */ public class MyFirstServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyFirstServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String firstname=request.getParameter("fname"); if(firstname.equalsIgnoreCase("abc")){ System.out.println("Setting attributes"); request.setAttribute("fname",firstname); request.setAttribute("lname",request.getParameter("lname")); response.sendRedirect("MyFirstJSP.jsp"); }else{ System.out.Println("No problem"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter p=response.getWriter(); p.println("Success!"); doGet(request,response); } } </code></pre> <p>But when I execute the code the servlet redirects to the jsp page but not fills the form fields with the respective values. As to find the cause I have added the if-else-block to know the cause and I get to know that the request objects attribute is not available here. </p> <p>If I use the request dispatcher in this case then the values are gets available and the form is gets filled with the values but the url in the address bar does not chage and always shows the url to the servlet.</p> <p>So My query is </p> <p>**1)Why the request object is not available to jsp page using sendRedirect.</p> <p>2)Is thre any other way to show my form in jsp page prefilled with the values entered by user if the servlet sendredirects to the calling jsp so that user need not to reenter the data in to form.** </p> <p>Please guide me friends in this problem Thank You!</p>
12,351,632
2
1
null
2012-09-10 11:51:20.273 UTC
3
2015-11-25 13:08:42.383 UTC
2012-09-10 12:25:09.9 UTC
null
559,026
null
266,074
null
1
7
jsp|servlets|response.redirect|requestdispatcher
48,833
<p>You need to <strong>forward</strong> to the jsp page on server side, as a <strong>redirect</strong> is a client side action (check out the location header <a href="http://en.wikipedia.org/wiki/HTTP_location" rel="noreferrer">1</a>) the request attributes get lost.</p> <p>replace</p> <pre><code>response.sendRedirect("MyFirstJSP.jsp"); </code></pre> <p>with</p> <pre><code>request.getRequestDispatcher("MyFirstJSP.jsp").forward(request, response); </code></pre> <p>Edit: sorry, I skipped this part </p> <blockquote> <p>If I use the request dispatcher in this case then the values are gets available and the form is gets filled with the values but the url in the address bar does not chage and always shows the url to the servlet.</p> </blockquote> <p>nevertheless, you cannot pass request attributes to your jsp when redirecting (as i've already mentioned above it's a clientside action)</p> <p>I'd suggest doing the following:</p> <ul> <li>Implement doGet for only rendering the page that contains the form</li> <li>Implement doPost for handling the submitted form data</li> <li>use POST instead of GET in the HTML-Form to submit the form</li> </ul> <p>In both, doGet and doPost, use <strong>forward</strong> to render the *.jsp page.</p> <p>GET /MyFirstServlet -> forward to MyFirstJSP.jsp</p> <p>POST /MyFirstServlet -> forward to MyFirstJSP.jsp</p> <p>this is the most commonly used and clean approach.</p> <p>EDIT 2: Simple Example</p> <p>SimpleFormServlet.java</p> <pre><code>public class SimpleFormServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String VIEW_NAME = "/WEB-INF/jsp/simpleForm.jsp"; private static final String MODEL_NAME = "form"; public SimpleFormServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(MODEL_NAME, new SimpleForm()); request.getRequestDispatcher(VIEW_NAME).forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final SimpleForm form = map(request); if(form.getfName().equalsIgnoreCase("abc")){ request.setAttribute(MODEL_NAME, form); // put additional attributes on the request // e.g. validation errors,... request.getRequestDispatcher(VIEW_NAME).forward(request, response); }else{ System.out.println("No problem"); response.sendRedirect("/SuccessServlet"); } } private SimpleForm map(final HttpServletRequest request) { SimpleForm form = new SimpleForm(); form.setfName(request.getParameter("fName")); form.setlName(request.getParameter("lName")); return form; } public static class SimpleForm implements Serializable { private static final long serialVersionUID = -2756917543012439177L; private String fName; private String lName; public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } } } </code></pre> <p>/WEB-INF/jsp/simpleForm.jsp</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="POST"&gt; First Name&lt;input type="text" name="fName" value="${form.fName}"&gt;&lt;br&gt; Last Name&lt;input type="text" name="lName" value="${form.lName}"&gt; &lt;input type="submit" value="Send"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ol> <li>GET /SimpleFormServlet</li> <li>doGet() prepares the form model (SimpleForm) and adds it as a request attribute named 'form'</li> <li>forward to the simpleForm.jsp</li> <li>access the model values and prefill the form: ${form.fName} and ${form.lName}</li> <li>the browser still shows /SimpleFormServlet (and we like it ;-))</li> <li><strong>POST</strong> the form relatively to /SimpleFormSerlvet (you don't have to set the action attribute of the form element explicitly)</li> <li>doPost() maps the request parameters to the SimpleForm.</li> <li>process the request and do whatever you want to do (validation)</li> <li>then you can either forward to the simpleForm.jsp (like when validation fails) or <strong>redirect</strong> to another servlet (/SuccessServlet for example)</li> </ol>
12,295,604
PHP - simple download script
<p>I'm making a simple download script, where my users can download their own images etc.</p> <p>But I'm having some weird problem.</p> <p>When I've downloaded the file, it's having the contents from my index.php file no matter what filetype I've downloaded.. My code is like so:</p> <pre><code>$fullPath = $r['snptFilepath'] . $r['snptFilename']; if (file_exists($fullPath)) { #echo $fullPath; // setting headers header('Content-Description: File Transfer'); header('Cache-Control: public'); # needed for IE header('Content-Type: '.$r['snptFiletype'].''); header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']); header('Content-Length: '.$r['snptSize'].''); readfile($fullPath)or die('error!'); } else { die('File does not exist'); } </code></pre> <p>$r is the result from my database, where I've stored size, type, path etc. when the file is uploaded.</p> <p><strong>UPDATE</strong></p> <p>When I'm uploading and downloading *.pdf files it's working with success. But when I'm trying to download *.zip and text/rtf, text/plain it's acting weird.</p> <p>By weird I mean: It downloads the full index.php file, with the downloaded file contents inside of it.</p> <p><strong>ANSWER</strong></p> <p>I copied this from <a href="http://php.net/manual/en/function.readfile.php" rel="noreferrer">http://php.net/manual/en/function.readfile.php</a> and it's working now. It seems that : ob_clean(); did the trick! Thanks for the help everyone.</p> <pre><code>#setting headers header('Content-Description: File Transfer'); header('Content-Type: '.$type); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; </code></pre>
12,296,811
2
12
null
2012-09-06 08:06:32.833 UTC
1
2014-07-25 11:13:20.523 UTC
2012-09-06 09:15:49.887 UTC
null
804,506
null
804,506
null
1
8
php
49,798
<p>I copied this from <a href="http://php.net/manual/en/function.readfile.php" rel="noreferrer">http://php.net/manual/en/function.readfile.php</a> and it works now. ob_clean(); did the trick..</p> <pre><code> #setting headers header('Content-Description: File Transfer'); header('Cache-Control: public'); header('Content-Type: '.$type); header("Content-Transfer-Encoding: binary"); header('Content-Disposition: attachment; filename='. basename($file)); header('Content-Length: '.filesize($file)); ob_clean(); #THIS! flush(); readfile($file); </code></pre>
12,567,956
Error when starting Tomcat, unsupported major/minor version, environment variables seem correct though
<p>I'm having a problem starting Tomcat 7 from the command line on Linux, and the log shows this:</p> <pre><code>Sep 24, 2012 8:54:10 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the jav a.library.path: /usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/lib/amd64/server:/usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/lib/amd64:/u sr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/../lib/amd64:/usr/lib64/mpi/gcc/openmpi/lib64:/usr/java/packages/lib/amd64:/usr/lib64:/lib6 4:/lib:/usr/lib Sep 24, 2012 8:54:10 AM org.apache.tomcat.util.digester.Digester startElement SEVERE: Begin event threw error java.lang.UnsupportedClassVersionError: pms/security/BCryptRealm : Unsupported major.minor version 51.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at java.net.URLClassLoader.access$000(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:212) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:144) at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1276) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:504) at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.jav a:1320) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScann erImpl.java:2732) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:625) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:48 8) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:819) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:748) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1208) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:525) at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1537) at org.apache.catalina.startup.Catalina.load(Catalina.java:610) at org.apache.catalina.startup.Catalina.load(Catalina.java:658) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:450)</code></pre> <p>From googling I understand the first bit I can just ignore, but I was wondering if that's indicative of the version of Java it's trying to use, since it keeps saying Java 6. The "Unsupported major.minor version 51.0" I understand means I have a problem with Java versions somehow. </p> <p>I built the class it's having problems with (a custom realm to use BCrypt) using ant, and running ant -v shows it's compiling with Java 7, which is what I want. I've set JAVA_HOME and JDK_HOME to use Java 7 as well (they're all pointing to the same place as far as I can tell). </p> <p>What else am I missing? If more info is needed let me know. I'd really appreciate any pointers on where I should look for whatever is going wrong. Thanks.</p> <p>ETA a little more info per questions in comments: I'm starting tomcat via the command line. I just do ./bin/startup.sh from the tomcat base directory. I downloaded tomcat from the <a href="http://tomcat.apache.org/download-70.cgi" rel="noreferrer">Apache website</a>. I got the core tar.gz version and unpacked it just last night (I only had version 6 before and wanted to upgrade). Also this isn't my personal machine; I only have user rights, if that matters.</p>
12,568,053
4
3
null
2012-09-24 15:16:19.923 UTC
1
2018-02-04 07:21:28.37 UTC
2012-09-24 15:29:17.463 UTC
null
630,868
null
630,868
null
1
11
java|linux|ant|tomcat7
41,140
<p>Open <code>tomcat/bin</code> directory and change <code>JAVA_HOME</code> parmater in <code>catalina.sh</code></p>
12,510,849
Automatic @property synthesize not working on NSManagedObject subclass
<p>After updating to the newest Version of Xcode 4.5 for iOS6 last night, i get Warnings and Errors like this</p> <blockquote> <p>Property 'mapAnnotation' requires method 'mapAnnotation' to be defined - use @synthesize, @dynamic or provide a method implementation in this class implementation</p> </blockquote> <p>because of missing @synthesize Statements, and even Errors about unknown iVars if i use them. </p> <p>The thing is, i thought it was not necessary to write these @synthesize statements since the last Xcode Update to 4.5 that came out with Mountain Lion, AND all my projects worked without them before i've updated Xcode last night (i've deleted a whole bunch of @synthesize statements from my files back then) It's even still in the Release-Notes:</p> <blockquote> <p>• Objective-C @synthesize command is generated by default when using properties.</p> </blockquote> <p>So i'm confused, am i missing a new Project-Setting that turns automatic @synthesize generation on? </p> <p>But it's not even working when i create a new Project and try it</p>
12,544,653
1
5
null
2012-09-20 10:34:56.743 UTC
13
2014-07-20 07:44:24.68 UTC
2014-07-20 07:44:24.68 UTC
null
1,265,393
null
1,066,219
null
1
25
xcode|properties|ios6|synthesize
9,611
<p>I faced the same problem and found the reason and the solution.</p> <p>If you look at the header file of NSManagedObject in iOS 6 SDK, you'll see "NS_REQUIRES_PROPERTY_DEFINITIONS" which forces classes to specify @dynamic or @synthesize for properties.</p> <p>(You can see the NS_REQUIRES_PROPERTY_DEFINITIONS in the API diff between iOS 5.1 and iOS 6.0.)</p> <p>This is because the compiler has to know if you want a property to be dynamic or synthesized especially in the implementation of a subclass of NSManagedObject class.</p> <p>I could solve this problem simply by adding the @synthesize lines explicitly for the properties other than @dynamic in NSManagedObject subclasses.</p>
12,190,103
Checkstyle : always receive File contains tab characters (this is the first instance)
<p>I'm using Checkstyle for Java in Eclipse IDE. I don't know in every java file, at second line, I always receive warning in Checkstyle : (although I'm pretty sure that I don't press tab key)</p> <blockquote> <p>File contains tab characters (this is the first instance).</p> </blockquote> <pre><code>public class Percolation { private boolean[][] grid; ... } </code></pre> <p>When I have typed : <code>public class Percolation {</code>, press enter, Eclipse will make an indent for me, after that, I type <code>private boolean[][] grid;</code>. But, I still receive this warning.</p> <p>Please tell me how to fix this. (I don't want to turn off this warning, because this is a must. Another people will check again my file).</p> <p>Thanks :)</p>
12,190,210
8
0
null
2012-08-30 04:52:30.467 UTC
6
2019-06-03 00:32:50.333 UTC
null
null
null
null
1,192,728
null
1
29
java|eclipse|checkstyle
67,101
<p>In eclipse, go to Preferences > General > Editors > Text Editors and check the box for "Insert spaces for tabs". Then it will indent with spaces instead of tabs.</p>
12,134,605
Concatenate in jQuery Selector
<p>Simple problem. I have a js variable I want to be concatenated too within a jQuery selector. However it is not working. No errors are popping up either. What is wrong? How do I correctly concatenate a variable to some text in a jQuery selector.</p> <pre><code>&lt;div id="part2"&gt;&lt;/div&gt; &lt;script type="text/javascript" &gt; $('#button').click(function () { var text = $('#text').val(); var number = 2; $.post('ajaxskeleton.php', { red: text }, function(){ $('#part' + number).html(text); }); }); &lt;/script&gt; </code></pre>
12,134,652
2
8
null
2012-08-26 23:00:19.2 UTC
5
2016-04-23 16:54:36.607 UTC
null
null
null
null
1,509,401
null
1
31
jquery|concatenation
154,157
<p>There is nothing wrong with syntax of</p> <pre><code>$('#part' + number).html(text); </code></pre> <p>jQuery accepts a String (<em>usually a CSS Selector</em>) or a <a href="http://javascript.info/tutorial/dom-nodes" rel="noreferrer">DOM Node</a> as parameter to create a <a href="https://stackoverflow.com/questions/6445180/what-is-a-jquery-object">jQuery Object</a>. </p> <p>In your case you should pass a String to <code>$()</code> that is </p> <pre><code>$(&lt;a string&gt;) </code></pre> <p>Make sure you have access to the variables <code>number</code> and <code>text</code>. </p> <p>To test do:</p> <pre><code>function(){ alert(number + ":" + text);//or use console.log(number + ":" + text) $('#part' + number).html(text); }); </code></pre> <p>If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.</p>
44,142,450
apt-get installing oracle java 7 stopped working
<p>Recently <code>apt-get install -y oracle-java7-installer</code> stopped working.</p> <p>I know in their roadmap, I think the public version is no longer supported, but it's been working all the way until recently. <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html" rel="noreferrer">http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html</a></p> <p>Anyone have a work around for this?</p> <pre><code>http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz?AuthParam=1495560077_4041e14adcb5fd7e68827ab0e15dc3b1 Connecting to download.oracle.com (download.oracle.com)|96.6.45.99|:80... connected. HTTP request sent, awaiting response... 404 Not Found 2017-05-23 10:19:17 ERROR 404: Not Found. </code></pre>
44,151,028
5
3
null
2017-05-23 18:29:20.667 UTC
9
2017-12-04 18:10:53.697 UTC
null
null
null
null
2,088,345
null
1
16
java|oracle|java-7|apt-get
13,395
<p>It appears Oracle has moved the download link, you can still fetch the tar ball from the oracle website after jumping through some hoops. The WebUpd8 installer is currently broken. The official explanation can be found at <a href="http://www.webupd8.org/2017/06/why-oracle-java-7-and-6-installers-no.html" rel="noreferrer">http://www.webupd8.org/2017/06/why-oracle-java-7-and-6-installers-no.html</a></p> <hr> <h1>Download Method 1: Login into to Oracle site</h1> <p>The link now seems to be: <a href="http://download.oracle.com/otn/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz" rel="noreferrer">http://download.oracle.com/otn/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz</a> notice "otn" and not "otn-pub", but at least from the website you seem to need to be signed in and not only accept the license agreement. </p> <p>It may be possible with debconf to change the url from otn-pub to otn and get the installer to work but I haven't tried. You can fetch the binary yourself and either install manually or with the installer pointing it to wherever you put the downloaded tar ball. </p> <p>Edit: It seems there isn't a way to configure download URL (though you can hijack it with hosts as in another answer).</p> <h1>Download Method 2: Use a trusted mirror</h1> <p>If you want to download jdk-7u80-linux-x64.tar.gz from a script without logging into to oracle it hosted locations include:</p> <ul> <li><a href="http://ftp.osuosl.org/pub/funtoo/distfiles/oracle-java/" rel="noreferrer">http://ftp.osuosl.org/pub/funtoo/distfiles/oracle-java/</a></li> <li><a href="http://ftp.heanet.ie/mirrors/funtoo/distfiles/oracle-java/" rel="noreferrer">http://ftp.heanet.ie/mirrors/funtoo/distfiles/oracle-java/</a></li> </ul> <p>EDIT: The sha256 has been removed from this answer because (as this edit demonstrates) anyone can edit said hash. Get your hashes from a trusted source. Suggestions include:</p> <ul> <li><a href="https://www.oracle.com/webfolder/s/digest/7u80checksum.html" rel="noreferrer">https://www.oracle.com/webfolder/s/digest/7u80checksum.html</a></li> </ul> <hr> <h1>Install Method 1: Prepopulate cache</h1> <pre><code>#put the file in the default cache location: sudo mv jdk-7u80-linux-x64.tar.gz /var/cache/oracle-jdk7-installer/ #then install normally: sudo apt-get install oracle-java7-installer </code></pre> <h1>Install Method 2: (more elegant IMHO) put tar ball anywhere and tell the installer where to look</h1> <pre><code>#setup ppa (you probably came here after already doing this) sudo add-apt-repository ppa:webupd8team/java sudo apt-get update #put the file in a temporary location: sudo mv jdk-7u80-linux-x64.tar.gz /tmp/ #set local path to /tmp (or any other path) echo oracle-java7-installer oracle-java7-installer/local select /tmp | \ sudo /usr/bin/debconf-set-selections #While your at it you may want tp approve license (or skip this and approve when prompted) echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | \ sudo /usr/bin/debconf-set-selections #then install normally: sudo apt-get install oracle-java7-installer </code></pre>
3,660,798
What happens on the wire when a TLS / LDAP or TLS / HTTP connection is set up?
<p>I'm rewording my question so hopefully I can get a better response. I asked a similar question on <a href="https://serverfault.com/questions/178561/what-are-the-exact-protocol-level-differences-between-ssl-and-tls">serverfault here</a>, and <em>think</em> that a proper and valid TLS server is one that expects the &quot;STARTTLS&quot; command.</p> <p>Is it true that STARTTLS can be issued to a properly configured LDAP or HTTP TLS server without needing an extra port? I know that this is true from an SMTP perspective, but aren't sure how broadly I can apply those experiences to other protocols.</p> <p>I've spent time reading (but not fully grasping)</p> <ul> <li>The <a href="https://www.rfc-editor.org/rfc/rfc2246" rel="nofollow noreferrer">TLS Spec</a></li> <li>Differences between <a href="http://novosial.org/openssl/tls-name/" rel="nofollow noreferrer">TLS and SSL</a></li> <li>The <a href="http://www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt" rel="nofollow noreferrer">SSL Spec</a></li> </ul> <p><strong>Q:</strong> What happens on the wire right before the TLS over LDAP or HTTP session is set up? Since this is TCP based can I simply telnet to that port and issue some command to verify it's working (up to that point)?</p>
3,661,416
3
0
null
2010-09-07 16:53:00.79 UTC
9
2012-02-11 03:20:41.973 UTC
2021-10-07 05:49:19.053 UTC
null
-1
null
328,397
null
1
16
https|ldap|certificate|ssl
10,475
<p>There are very few differences between SSL and TLS in the way they are used. There is, however, a fundamental difference between up-front establishment of SSL/TLS and the use of a command such as <code>STARTTLS</code>. Sometimes, &quot;TLS&quot; is used in contrast to &quot;SSL&quot;, to mean &quot;using a STARTTLS mode&quot; but this is incorrect.</p> <h2>Up-front TLS/SSL</h2> <p>In this case, the client initiates the TLS/SSL connection before anything else, so SSL/TLS handshake happens first. Once the secure socket is up, the application using it can start sending the various commands for the protocol above TLS (e.g. HTTP, LDAP in this mode, SMTP).</p> <p>In this mode, the SSL/TLS versions have to run on a different port from their plain counterparts, for example: HTTPS on port 443, LDAPS on port 636, IMAPS on port 993, instead of 80, 389, 143 respectively.</p> <p>The layers implementing these application protocols barely need to know they're running on top of TLS/SSL. Sometimes, they're simply tunneled in tools such as <em>sslwrap</em>.</p> <h2>TLS after STARTTLS (or equivalent)</h2> <p>The TLS specification allows for the handshake to happen at any time, including after having exchanged some data in plain TCP over the same TCP connection.</p> <p>Some protocols, including LDAP, incorporate a command to tell the application protocol there will be an upgrade. Essentially, the first part of the LDAP communication happens in plain text, then a <code>STARTTLS</code> message is sent (still in plain text), which indicates that the current TCP connection will be reused but that the next commands will be wrapped within a TLS/SSL layer. At this stage, the TLS/SSL handshake happens and the communication is &quot;upgraded&quot; to TLS/SSL. Only after this the communication is secured via TLS/SSL, and both the client and servers know that they have to wrap/unwrap their commands from the TLS layer (typically adding a TLS library between the TCP layer and the application layer).</p> <p>The details of how <code>STARTTLS</code> is implemented within each protocol vary depending on the protocol (because this has to be compatible with the protocol using it to some extent).</p> <p>Even HTTP has a variant using this mechanism, although it's mostly never supported: <a href="https://www.rfc-editor.org/rfc/rfc2817" rel="nofollow noreferrer">RFC 2817 Upgrading to TLS Within HTTP/1.1</a>. This is completely different from the way HTTPS works (<a href="https://www.rfc-editor.org/rfc/rfc2818" rel="nofollow noreferrer">RFC 2818</a>), which initiates TLS/SSL first.</p> <p>The advantages of the <code>STARTTLS</code> approach is that you can run both secured and plain variants on the same port, the disadvantages are the consequences of that, in particular potential downgrade attacks or possible mistakes in the configuration.</p> <p>(<strong>EDIT</strong>: I've removed an incorrect sentence, as @GregS pointed out, thanks.)</p> <p>(<strong>EDIT</strong>: I've also put more on SSL vs. TLS in <a href="https://serverfault.com/questions/178561/what-are-the-exact-protocol-level-differences-between-ssl-and-tls/179139#179139">this answer on ServerFault</a>.)</p>
26,228,385
Time-complexity of recursive algorithm for calculating binomial coefficient
<p>I'm studying about algorithm complexity analysis. I have problem with unconformity or <code>C(n, k)</code>.</p> <pre><code>int C(int n, int k){ if(n==k || k==0) return 1; return C(n-1, k) + C(n-1, k-1); } </code></pre> <p>How can I determine its execution complexity or <code>T(n)</code>?</p>
26,229,383
1
7
null
2014-10-07 04:05:38.69 UTC
8
2015-09-30 15:33:57.213 UTC
2014-10-08 02:46:54.437 UTC
null
3,440,545
null
2,874,409
null
1
7
c++|recursion|complexity-theory|time-complexity
12,170
<p>The recurrence you are looking for is </p> <blockquote> <p>T(n,k) = T(n-1,k) + T(n-1,k-1) + O(1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;with &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; T(n,n) = T(n,0) = O(1)</p> </blockquote> <p>Obviously n is decreased by one every step. If we ignore (just for the moment) that there is a parameter k, basically the number of calls doubles every step. This happens n times, until n = 1. Now C(1,k) returns 1. So you call C(n,k) at most 2<sup>n</sup> times. So C(n,k) is in O(2<sup>n</sup>).</p> <p>Now we remember the k. What would be a worst case for k? maybe k = n/2 (for an even n). You can see that you need at least n/2 steps until k reaches 1 or n reaches n/2 in any recursive call. So the number of calls doubles at least 2<sup>n/2</sup> times. But there are many more calls. Writing it down is quite a bit of work.</p> <p><strong>Edit 1</strong> So lets take a look at this picture</p> <p><img src="https://i.stack.imgur.com/UyzkD.png" alt="pascal&#39;s triangle with number of calls and arrows"></p> <p>You start calling C(n,n/2) (with n=6). The grey triangle is the part that is contained in the n/2 "steps" until you reach the corner (C(n,0) or C(n,n)) <em>first</em>. But as you can see, there are more calls. I marked the calls, where the recursion stops with a blue box and wrote the number a special C(n,k) is called, with a green number.</p> <p><strong>Edit 2</strong> The value of C(n,k) and the number of calls of C(n,k), that return the value 1, are the same, since the function return only the value 1 (or a result of a recursive call). In the example you see that the sum of the green numbers written at the blue boxes, which are the number of calls, sums up to 20 which is also the value of C(6,3). </p> <p><strong>Edit 3</strong> Since all operations in one C(n,k) call run in O(1) (constant time), we only have to count the calls to get the complexity. Notice: If C(n,k) would contain an operation that runs in O(n), we would have to multiply the number of call by O(n) to get the complexity.</p> <p>You will also notice the connection to <a href="http://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="noreferrer">Pascal's triangle</a>.</p> <h3>A little trick</h3> <p>The algorithm C(n,k) computes the <a href="http://en.wikipedia.org/wiki/Binomial_coefficient" rel="noreferrer">Binomial coefficient</a> by adding 1's. By using <a href="http://en.wikipedia.org/wiki/Stirling%27s_approximation" rel="noreferrer">Stirling's approximation</a> you can see, that C(n,n/2) &approx; 2<sup>n</sup>/sqrt(n) (left out some constants for simplification). So the algorithm has to add that many 1's and so it has a complexity of O(2<sup>n</sup>/sqrt(n)).</p>
21,991,044
How to get high resolution website logo (favicon) for a given URL
<p>I'm developing a web browser on Android and want to show the URL logo for the most visited sites like in Chrome (4 X 2). But the problem is that most favicons (eg: <a href="http://www.bbc.co.uk/favicon.ico">http://www.bbc.co.uk/favicon.ico</a>) are of size either 16X16 or 32X32 and they don't look good when scaled up. </p> <p>Is there a way I can download a high resolution icon/bitmap for an URL in a standard way? How about opening the home page and then extracting all the image links and then choose an image with the name logo in it? Would this method work for all the URLs? I want to know if there is a standard way to obtain a high resolution icon for a given URL or favicon is the only standard way to get the website logo?</p>
22,007,642
7
5
null
2014-02-24 14:47:23 UTC
13
2022-05-18 07:31:59.683 UTC
2014-06-09 23:04:27.17 UTC
null
1,214,743
null
391,401
null
1
28
image|url|browser|favicon|graphical-logo
32,635
<p>You can code it yourself or use an existing solution.</p> <p><strong>Do-it-yourself algorithm</strong></p> <ol> <li>Look for Apple touch icon declarations in the code, such as <code>&lt;link rel="apple-touch-icon" href="/apple-touch-icon.png"&gt;</code>. Theses pictures range from 57x57 to 152x152. See <a href="https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" rel="noreferrer">Apple specs</a> for full reference.</li> <li>Even if you find no Apple touch icon declaration, try to load them anyway, based on Apple naming convention. For example, you might find something at <code>/apple-touch-icon.png</code>. Again, see <a href="https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" rel="noreferrer">Apple specs</a> for reference.</li> <li>Look for high definition PNG favicon in the code, such as <code>&lt;link rel="icon" type="image/png" href="/favicon-196x196.png" sizes="196x196"&gt;</code>. In this example, you have a 196x196 picture.</li> <li>Look for Windows 8 / IE10 and Windows 8.1 / IE11 tile pictures, such as <code>&lt;meta name="msapplication-TileImage" content="/mstile-144x144.png"&gt;</code>. These pictures range from 70x70 to 310x310, or even more. See these <a href="http://blogs.msdn.com/b/ie/archive/2012/06/08/high-quality-visuals-for-pinned-sites-in-windows-8.aspx" rel="noreferrer">Windows 8</a> and <a href="http://msdn.microsoft.com/en-us/library/ie/dn255024%28v=vs.85%29.aspx" rel="noreferrer">Windows 8.1</a> references.</li> <li>Look for <code>/browserconfig.xml</code>, dedicated to Windows 8.1 / IE11. This is the other place where you can find tile pictures. See <a href="http://msdn.microsoft.com/en-us/library/ie/dn455106%28v=vs.85%29.aspx" rel="noreferrer">Microsoft specs</a>.</li> <li>Look for the <code>og:image</code> declaration such as <code>&lt;meta property="og:image" content="http://somesite.com/somepic.png"/&gt;</code>. This is how a web site indicates to FB/Pinterest/whatever the preferred picture to represent it. See <a href="http://ogp.me/" rel="noreferrer">Open Graph Protocol</a> for reference.</li> <li>At this point, you found no suitable logo... damned! You can still load all pictures in the page and make a guess to pick the best one.</li> </ol> <p>Note: Steps 1, 2 and 3 are basically what Chrome does to get suitable icons for bookmark and home screen links. Coast by Opera even use the MS tile pictures to get the job done. Read this list to figure out <a href="http://realfavicongenerator.net/favicon_compatibility" rel="noreferrer">which browser uses which picture</a> (full disclosure: I am the author of this page).</p> <p><strong>APIs and open source projects</strong></p> <p><em>RealFaviconGenerator</em>: You can get any web site favicon or related icon (such as the Touch Icon) with this <a href="http://realfavicongenerator.net/api/download_website_favicon" rel="noreferrer">favicon retrieval API</a>. Full disclosure: I'm the author of this service.</p> <p><em>BestIcon</em>: Although less comprehensive, <a href="https://github.com/mat/besticon" rel="noreferrer">Besticon</a> offers a good alternative, especially if you want to host the code yourself. There is also a <a href="http://icons.better-idea.org/" rel="noreferrer">hosted version</a> you can use right away.</p>
11,258,888
ReferenceError: "alert" is not defined
<p>I am trying to call a java script function from java code.</p> <p>Here is my Java code</p> <pre><code> public static void main(String[] args) throws FileNotFoundException { try { /** * To call a anonymous function from java script file */ ScriptEngine engine = new ScriptEngineManager() .getEngineByName("javascript"); FileReader fr = new FileReader("src/js/MySpec.js"); engine.eval(fr); } catch (ScriptException scrEx) { scrEx.printStackTrace(); } } </code></pre> <p>Here is my java script file:</p> <pre><code>(function() { alert("Hello World !!!"); })(); </code></pre> <p>But when I run main method of driver class it is giving me error as below:</p> <pre><code>Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "alert" is not defined. (&lt;Unknown source&gt;#2) in &lt;Unknown source&gt; at line number 2 at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:110) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:232) at Java6RhinoRunner.load(Java6RhinoRunner.java:42) at Java6RhinoRunner.main(Java6RhinoRunner.java:12) </code></pre> <p>What I know is that it need some script engine to execute it.</p> <p>For that I added rhino.jar file in to my class path.But this is not working.</p> <p>I an not getting how to solve this error. Please help.Thanks in advance.</p>
11,258,916
1
0
null
2012-06-29 09:00:24.58 UTC
3
2012-06-29 11:10:26.987 UTC
2012-06-29 11:10:26.987 UTC
null
559,026
null
489,718
null
1
20
java|javascript|rhino
61,745
<p><code>alert</code> is not part of JavaScript, it's part of the <code>window</code> object provided by web browsers. So it doesn't exist in the context you're trying to use it in. (This is also true of <code>setInterval</code>, <code>setTimeout</code>, and other timer-related stuff, FYI.)</p> <p>If you just want to do simple console output, Rhino provides a <code>print</code> function to your script, so you could replace <code>alert</code> with <code>print</code>. Your script also has access to all of the Java classes and such, so for instance <code>java.lang.System.out.println('Hello');</code> would work from your JavaScript script (although it's a bit redundant with the provided <code>print</code> function). You can also make Java variables available to your script easily via <code>ScriptEngine.put</code>, e.g:</p> <pre><code>engine.put("out", System.out); </code></pre> <p>...and then in your script:</p> <pre><code>out.println('Hello from JavaScript'); </code></pre> <p>...so that's a third way to do output from the script. :-)</p> <p>See the discussion in <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/package-summary.html" rel="noreferrer">the <code>javax.script</code> package documentation</a>, in particular <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html#put%28java.lang.String,%20java.lang.Object%29" rel="noreferrer"><code>ScriptEngine#put</code></a>, or for more complex cases, <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/Bindings.html" rel="noreferrer"><code>Bindings</code></a> (and <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/SimpleBindings.html" rel="noreferrer"><code>SimpleBindings</code></a>) and <a href="http://docs.oracle.com/javase/7/docs/api/javax/script/ScriptContext.html" rel="noreferrer"><code>ScriptContext</code></a>.</p>
12,846,351
UIScrollView contentSize not working
<p>I put a <code>UIScrollView</code> in my nib's <code>view</code>, and linked it to a an <code>IBOutlet</code> property.</p> <p>Now, when I do this in my <code>viewDidLoad</code> method, it seems to have no effect on the <code>contentSize</code>:</p> <pre><code>self.sv.backgroundColor = [UIColor yellowColor]; // this works CGSize size = CGSizeMake(1000.0, 1000.0); [self.sv setContentSize:size]; // this does not </code></pre> <p>It behaves as if the <code>contentSize</code> was the same as the frame. What's going on? This started working when I turned off AutoLayout. Why?</p>
12,846,417
15
2
null
2012-10-11 18:39:41.773 UTC
15
2019-09-21 15:40:45.937 UTC
2015-05-16 18:05:39.513 UTC
null
1,135,714
null
121,646
null
1
62
objective-c|ios|uiscrollview
97,533
<p>I had the same problem. Auto Layout for <code>UIScrollView</code> is messed up.</p> <p>Work around: Put everything in the <code>UIScrollView</code> into another <code>UIView</code>, and put that <code>UIView</code> as the only child of the <code>UIScrollView</code>. Then you can use Auto Layout.</p> <p>If things near the end is messed up (the end of whichever direction your <code>UIScrollView</code> scrolls), change the constraint at the end to have the lowest possible priority. </p>
22,083,689
Is it possible to extend enum in Java 8?
<p>Just playing and came up with a sweet way to add functionality to <code>enum</code>s in <a href="https://stackoverflow.com/q/22074497/823393">Java Enum toString() method</a> with <a href="https://stackoverflow.com/a/22075272/823393">this</a>.</p> <p>Some further tinkering allowed me to <em>nearly</em> also add a tidy (i.e. not throwing an exception) reverse look-up but there's a problem. It's reporting:</p> <pre><code>error: valueOf(String) in X cannot implement valueOf(String) in HasValue public enum X implements PoliteEnum, ReverseLookup { overriding method is static </code></pre> <p>Is there a way?</p> <p>The aim here is to silently add (via an interface implementation with a <code>default</code> method like I added <code>politeName</code> in the linked answer) a <code>lookup</code> method that does the <code>valueOf</code> function without throwing an exception. Is it possible? It is clearly now possible to extend <code>enum</code> - one of my major problems with Java until now.</p> <p>Here's my failed attempt:</p> <pre><code>public interface HasName { public String name(); } public interface PoliteEnum extends HasName { default String politeName() { return name().replace("_", " "); } } public interface Lookup&lt;P, Q&gt; { public Q lookup(P p); } public interface HasValue { HasValue valueOf(String name); } public interface ReverseLookup extends HasValue, Lookup&lt;String, HasValue&gt; { @Override default HasValue lookup(String from) { try { return valueOf(from); } catch (IllegalArgumentException e) { return null; } } } public enum X implements PoliteEnum/* NOT ALLOWED :( , ReverseLookup*/ { A_For_Ism, B_For_Mutton, C_Forth_Highlanders; } public void test() { // Test the politeName for (X x : X.values()) { System.out.println(x.politeName()); } // ToDo: Test lookup } </code></pre>
22,102,121
4
11
null
2014-02-28 00:22:18.963 UTC
10
2015-11-09 15:54:22.087 UTC
2017-05-23 12:00:03.463 UTC
null
-1
null
823,393
null
1
15
java|enums|extend|java-8
18,721
<p>You are over-complicating your design. If you are willing to accept that you can invoke a <code>default</code> method on an instance only, there entire code may look like this:</p> <pre><code>interface ReverseLookupSupport&lt;E extends Enum&lt;E&gt;&gt; { Class&lt;E&gt; getDeclaringClass(); default E lookup(String name) { try { return Enum.valueOf(getDeclaringClass(), name); } catch(IllegalArgumentException ex) { return null; } } } enum Test implements ReverseLookupSupport&lt;Test&gt; { FOO, BAR } </code></pre> <p>You can test it with:</p> <pre><code>Test foo=Test.FOO; Test bar=foo.lookup("BAR"), baz=foo.lookup("BAZ"); System.out.println(bar+" "+baz); </code></pre> <p>An non-throwing/catching alternative would be:</p> <pre><code>interface ReverseLookupSupport&lt;E extends Enum&lt;E&gt;&gt; { Class&lt;E&gt; getDeclaringClass(); default Optional&lt;E&gt; lookup(String name) { return Stream.of(getDeclaringClass().getEnumConstants()) .filter(e-&gt;e.name().equals(name)).findFirst(); } </code></pre> <p>to use like:</p> <pre><code>Test foo=Test.FOO; Test bar=foo.lookup("BAR").orElse(null), baz=foo.lookup("BAZ").orElse(null); System.out.println(bar+" "+baz); </code></pre>
16,739,084
AngularJS using $rootScope as a data store
<p>I have an idea for my AngularJS app and I'm curious if the AngularJS community would consider it okay to do it this way. In short, I am connecting to a data API and displaying my results on the page.</p> <p>I have created an AngularJS service that creates a data store on <code>$rootScope.DataStore</code>. I also have a service method that updates the DataStore with the data returned from an API endpoint. If I request the "products" API endpoint from inside my controller with <code>DataStore.update('products')</code>, this would update <code>$rootScope.DataStore.products</code> with my product data.</p> <p>Now, in the view/partial, all I need to do is say <code>ng-repeat="product in DataStore.products"</code> to show my data, and it doesn't matter what controller scope I am in. So, in essence my DataStore is my single source of truth.</p> <p>What I feel like I gain from this method is easy to follow semantics and minimal controller coding. So, anytime the DataStore is updated, anything that's bound to DataStore also gets updated.</p> <p>Would this put too much load on the <code>$rootScope</code> digest cycle, or is this just an odd way to do it? Or is it a totally awesome way? :) Any comments are welcome.</p>
16,739,309
5
0
null
2013-05-24 15:58:23.633 UTC
23
2020-04-05 02:56:34.907 UTC
2020-04-05 02:56:34.907 UTC
null
2,185,093
null
1,229,564
null
1
58
javascript|html|angularjs|angularjs-scope
50,634
<p>This question is addressed in the <a href="http://docs.angularjs.org/misc/faq" rel="nofollow noreferrer">AngularJS FAQ</a> quoted here:</p> <blockquote> <p>Occasionally there are pieces of data that you want to make global to the whole app. For these, you <strong>can inject $rootScope</strong> and set values on it like any other scope. Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope.</p> </blockquote> <p>It seems that the team does encourage using <code>$rootScope</code> this way, with this caveat:</p> <blockquote> <p>Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.</p> <p>Conversely, don't create a service whose only purpose in life is to store and return bits of data.</p> </blockquote> <p>This does not put too much load on the <code>$digest</code> cycle (which implements basic dirty checking to test for data mutation) and this is not an odd way to do things.</p> <p><strong>EDIT:</strong> For more details on performance, see this answer from Misko (AngularJS dev) here on SO: <a href="https://stackoverflow.com/questions/9682092/angularjs-how-does-databinding-work/9693933#9693933">How does data binding work in AngularJS?</a> Specifically note the section on performance. </p>
50,893,657
Failed to resolve: androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1
<p>I am trying to understand ViewModel and LiveData concepts in android. I am making a practice project but when i added <code>implementation 'androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1'</code> line in my app level gradle file it shows me </p> <blockquote> <p>Failed to resolve: androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1.</p> </blockquote> <p>I have searched on google for solution and i found <a href="https://stackoverflow.com/a/50781666/7804719">this</a> answer, it works when i compile only viewmodel library but if i compile extensions library using same method as <code>implementation group: 'androidx.lifecycle', name:'lifecycle-extensions-ktx', version: '2.0.0-alpha1'</code>, it shows the same error as above. I have also tried to find it on Maven repositories site <a href="https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-extensions" rel="noreferrer">here</a> but i didn't have any information for how to compile it.</p> <h1>UPDATE</h1> <h3>App Level Build.gradle</h3> <pre><code>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 defaultConfig { applicationId "***************" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:28.0.0-alpha3' implementation 'com.android.support.constraint:constraint-layout:1.1.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation group: 'androidx.lifecycle', name:'lifecycle-extensions-ktx', version: '2.0.0-alpha1' implementation group: 'androidx.lifecycle', name:'lifecycle-viewmodel-ktx', version: '2.0.0-alpha1' } </code></pre>
50,902,132
6
5
null
2018-06-17 04:21:48.13 UTC
3
2021-07-06 16:52:28.87 UTC
2018-06-17 06:07:26.107 UTC
null
7,804,719
null
7,804,719
null
1
17
android|kotlin|android-architecture-components|android-viewmodel|android-livedata
41,449
<h2><strong>UPDATE</strong></h2> <p>As per <a href="https://stackoverflow.com/users/421467/dr-jacky">@Dr.jacky</a>'s comment and Android Developers Documentation,</p> <blockquote> <p>The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.</p> </blockquote> <p>More Info at <a href="https://developer.android.com/jetpack/androidx/releases/lifecycle" rel="noreferrer">https://developer.android.com/jetpack/androidx/releases/lifecycle</a></p> <hr /> <p>I have found the answer. As <code>Thunder Knight</code> said <a href="https://stackoverflow.com/a/50781666/7804719">here</a> <code>it seems to be that the repository was emptied somehow. Hence, you can not download it from the repository.</code>. I agree with this and so i was looking for answer on <a href="http://mvnrepository.com" rel="noreferrer">mvnrepository.com</a> and i found it <a href="https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-extensions/2.0.0-alpha1" rel="noreferrer">here</a>. I have to add</p> <blockquote> <p>implementation group: 'androidx.lifecycle', name: 'lifecycle-extensions', version: '2.0.0-alpha1'</p> </blockquote> <p>line for adding lifecycle-extensions and also i was adding <code>-ktx</code> in name of library but it was the mistake. In <a href="https://developer.android.com/topic/libraries/architecture/adding-components" rel="noreferrer">documentation</a> they have not commented to add <code>-ktx</code> in line of <code>lifecycle-extensions</code>.</p> <p>Credits:- <a href="https://stackoverflow.com/a/50781666/7804719">@Thunder Knight</a></p>
4,233,185
Connection must be valid and open error
<p>I'm getting error: Connection must be valid and open when I start this program. I searched on google and only found 2 people that have the same error. Is it possible to fix this ?? Thx</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Data.Odbc; using System.Data.Sql; namespace WindowsFormsApplication1 { static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { string connectionString = "Server=localhost;Uid=root;Pwd=******;Database=testing;"; MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString); connection.Open(); string insertQuery = "ALTER TABLE `user` ADD lol INT"; MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery); myCommand.ExecuteNonQuery(); connection.Close(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } </code></pre>
4,233,208
2
2
null
2010-11-20 14:28:10.987 UTC
null
2013-02-28 08:08:53.56 UTC
2013-02-28 08:08:53.56 UTC
null
921,684
null
512,205
null
1
7
c#|mysql
51,253
<p>You need to tell your command about your connection object. Add the connection parameter to this line:</p> <pre><code>MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection); </code></pre>
4,636,679
ListView adapter data change without ListView being notified
<p>I've written a ListActivity that has a custom list adapter. The list is being updated from a ContentProvider when onCreate is run. I also have a service that gets started when I run the app and it first updates the ContentProvider, then sends a Broadcast that the content has been updated.<br> My ListActivity receives the broadcast and tries to update my ListView. My problem is, I'm getting intermittent errors about the ListView adapter data changing without the ListView being notified. I call the <code>notifyDataSetChanged()</code> method on my list adapter right after I update it. What it seems like is happening is the list is still in the process of being updated after first call in onCreate when it receives the broadcast from the service to update, so it tries to update my ListView before it's finished updating from it's first run. Does this make sense? Here is some of my code.</p> <p>NOTE: The service is working properly, it gets new data and updates my ContentProvider, and I do get the broadcast in my activity when it is updated.</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = this; getPrefs(); setContentView(R.layout.main); // Setup preference listener preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.registerOnSharedPreferenceChangeListener(listener); // Setup report list adapter ListView nzbLv = (ListView) findViewById(R.id.report_list); nzbla = new NZBReportListAdaptor(ctx); getReports(); nzbla.setListItems(report_list); nzbLv.setAdapter(nzbla); // Broadcast receiver to get notification from NZBService to update ReportList registerReceiver(receiver, new IntentFilter(NZBService.BROADCAST_ACTION)); startService(new Intent(ctx, NZBService.class)); } @Override public void onResume() { super.onResume(); timerHandler.resume(); new updateSabQueue().execute(); //updateList(); } @Override public void onPause() { super.onPause(); timerHandler.pause(); unregisterReceiver(receiver); } private BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { Toast.makeText(ctx, "NZBService broadcast recieved", Toast.LENGTH_SHORT).show(); updateReportList(); } }; private void updateReportList() { new updateReportList().execute(); } private class updateReportList extends AsyncTask&lt;Void, Void, Boolean&gt; { /* (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() * Show progress dialog */ protected void onPreExecute() { } /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) * Get new articles from the internet */ protected Boolean doInBackground(Void...unused) { getReports(); return true; } /** * On post execute. * Close the progress dialog */ @Override protected void onPostExecute(Boolean updated) { if (updated) { Log.d(TAG, "NZB report list adapter updated"); synchronized(this) { nzbla.setListItems(report_list); } Log.d(TAG, "NZB report list notified of change"); nzbla.notifyDataSetChanged(); } } } </code></pre> <p>Now that this question is answered, I will post my updated code in an effort to help others who might come across it.</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ctx = this; getPrefs(); setContentView(R.layout.main); // Setup preference listener preferences = PreferenceManager.getDefaultSharedPreferences(this); preferences.registerOnSharedPreferenceChangeListener(listener); // Setup report list adapter ListView nzbLv = (ListView) findViewById(R.id.report_list); nzbla = new NZBReportListAdaptor(ctx); report_list.addAll(getReports()); nzbla.setListItems(report_list); nzbLv.setAdapter(nzbla); // Broadcast receiver to get notification from NZBService to update ReportList registerReceiver(receiver, new IntentFilter(NZBService.BROADCAST_ACTION)); startService(new Intent(ctx, NZBService.class)); } private class updateReportList extends AsyncTask&lt;Void, Void, ArrayList&lt;Report&gt;&gt; { /* (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() * Show progress dialog */ protected void onPreExecute() { } /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) * Get new articles from the internet */ protected ArrayList&lt;Report&gt; doInBackground(Void...unused) { return getReports(); } /** * On post execute. * Close the progress dialog */ @Override protected void onPostExecute(ArrayList&lt;Report&gt; updated) { nzbla.setListItems(updated); nzbla.notifyDataSetChanged(); } } private ArrayList&lt;Report&gt; getReports() { ArrayList&lt;Report&gt; reports = new ArrayList&lt;Report&gt;(); ContentResolver r = getContentResolver(); Cursor c = r.query(NZBReportProvider.CONTENT_URI, null, null, null, NZBReportProvider.ARTICLE_KEY_ROWID + " DESC"); startManagingCursor(c); Log.d(TAG, "NZBReport cursor.getCount=" + c.getCount()); int title = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_TITLE); int desc = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_DESCRIPTION); int cat = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_CAT); int size = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_SIZE); int link = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_LINK); int catid = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_CATID); int date = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_DATE_ADDED); int group = c.getColumnIndex(NZBReportProvider.ARTICLE_KEY_GROUP); if (c.getCount() &gt; 0) { c.moveToFirst(); do { URL url = null; try { url = new URL(c.getString(link)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } reports.add(new Report(c.getString(title), url, c.getString(desc), c.getString(cat), c.getString(date), c.getString(size), c.getInt(catid), c.getString(group))); } while (c.moveToNext()); } return reports; } </code></pre>
4,636,870
2
0
null
2011-01-08 23:05:26.937 UTC
4
2015-12-12 16:11:00.34 UTC
2015-12-12 16:11:00.34 UTC
null
4,370,109
null
326,430
null
1
7
android|android-listview|adapter|notify
40,580
<p>You have to do all your updating of Adapter data on the UI thread so the synchronized block isn't necessary. It's also useless since your synchronizing on the <code>AsyncTask</code> which is created new each time it's executed.</p> <p>Another problem is that you are calling <code>notifyDataSetChanged</code> external to the <code>Adapter</code>. You should call it at the end of your <code>setListItems</code> method. That shouldn't be causing errors though since it's being executed on the UI thread but it should not be called in that way.</p> <p>You should make sure that your <code>getReports</code> method is not modifying the backing store of the <code>Adapter</code> in any way. Since it is running on a separate thread it cannot modify anything the <code>Adapter</code> has access too. Even if it's protected by locks. What you need to do is in your <code>doInBackground</code> method is generate the list of updates or a new list, etc., and pass that into <code>onPostExecute</code> which then commits the new data to the <code>Adapter</code> on the UI thread. So, if your <code>getReports</code> function is changing <code>report_list</code> and your <code>Adapter</code> has a reference to <code>report_list</code> you are doing it wrong. <code>getReports</code> must create a new <code>report_list</code> and then pass that back to your <code>Adapter</code> when it's finished creating it on the UI thread.</p> <p>To reiterate, you can only modify data the <code>Adapter</code> and subsequently the <code>ListView</code> has access too on the UI thread. Using synchronization/locks does not change this requirement.</p>
4,667,979
What's standard behavior when <button> element is clicked? Will it submit the form?
<p>What is the standard behavior for when a <code>&lt;button&gt;</code> element is clicked in a form? Will it submit the form?</p> <p>Question is about tag/element <code>&lt;button&gt;</code>, not <code>&lt;input type=button&gt;</code>.</p>
4,667,996
2
0
null
2011-01-12 10:58:35.39 UTC
9
2021-08-10 12:47:07.787 UTC
2021-08-10 12:47:07.787 UTC
null
1,253,298
null
84,325
null
1
51
javascript|html|dom
22,897
<p>If the button is within a form, the default behavior is submit.</p> <p>If the button is not within a form, it will do nothing.</p> <p>BUT BE AWARE!</p> <blockquote> <p>Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".</p> </blockquote> <p>Taken from <a href="http://www.w3schools.com/tags/tag_button.asp" rel="noreferrer">http://www.w3schools.com/tags/tag_button.asp</a></p>
4,052,770
Deciphering the .NET clr20r3 exception parameters P1..P10
<p>I'm trying to decipher the meaning on the P1...P10 parameters associated with a <code>clr20r3</code> that is written to the event log when my application experiences an exception.</p> <p>The best I've <a href="http://www.dimensionsusers.com/forum/viewtopic.php?f=29&amp;t=148" rel="noreferrer">been able to find</a> is:</p> <ul> <li><strong>P1</strong>: the hosting process (<em>e.g.</em> <code>w3wp.exe</code>)</li> <li><strong>P2</strong>: the hosting process version (<em>e.g.</em> <code>6.0.3790.1830</code>)</li> <li><strong>P3</strong>: ??? (<em>e.g.</em> <code>42435be1</code>)</li> <li><strong>P4</strong>: the assembly from which the exception was raised (<em>e.g.</em> <code>mrtables.webservice</code>)</li> <li><strong>P5</strong>: the assembly version (<em>e.g.</em> <code>2.1.2.0</code>)</li> <li><strong>P6</strong>: ??? (<em>e.g.</em> <code>4682617f</code>)</li> <li><strong>P7</strong>: ??? (<em>e.g.</em> <code>129</code>)</li> <li><strong>P8</strong>: ??? (<em>e.g.</em> <code>50</code>)</li> <li><strong>P9</strong>: the exception type raised (<em>e.g.</em> <code>system.argumentexception</code>)</li> <li><strong>P10</strong>: ??? (<em>e.g.</em> <code>NIL</code>)</li> </ul> <p><a href="http://google.com/?q=clr20r3+" rel="noreferrer">Googling for clr20r3</a> provides thousands of sample parameter values, from which someone can try to derive a pattern.</p> <p>But I'm hoping for documentation on the parameter meanings, as opposed to educated guesses.</p> <hr> <p><strong>Edit:</strong> While I can hope for canonical documentation, really I'd be happy to see the exception being thrown, at what line, complete with a stack trace.</p> <h2>Bonus Reading</h2> <ul> <li><a href="https://stackoverflow.com/questions/1937931/unhandled-exception-that-caused-the-application-to-crash-with-eventtype-clr20r3">Unhandled exception that caused the application to crash with &quot;EventType clr20r3, P1 w3wp.exe&quot; in the log, but no details there</a> <em>(asking for help with a problem, while we're asking for a canonical explanation of what the parameters mean)</em></li> </ul>
4,053,016
2
1
null
2010-10-29 14:27:45.303 UTC
51
2018-08-19 13:59:36.157 UTC
2018-08-19 13:59:36.157 UTC
null
12,597
null
12,597
null
1
82
.net|exception|clr
34,262
<p>Here is the information on Watson Buckets</p> <ol> <li>Exe File Name</li> <li>Exe File assembly version number</li> <li>Exe File Stamp</li> <li>Exe file full assembly name</li> <li>Faulting assembly version</li> <li>Faulting assembly timestamp</li> <li>Faulting assembly method def </li> <li>Faulting method IL Offset within the faulting method</li> <li>Exception type</li> </ol> <p>And also here is a <a href="http://web.archive.org/web/20140901101840/http://msdn.microsoft.com/en-us/magazine/cc793966.aspx" rel="noreferrer">MSDN</a> article on the same.</p> <p>Sample:</p> <pre><code> Problem Signature 01: devenv.exe Problem Signature 02: 11.0.50727.1 Problem Signature 03: 5011ecaa Problem Signature 04: Microsoft.VisualStudio.SharePoint.Project Problem Signature 05: 11.0.60226.0 Problem Signature 06: 512c2dba Problem Signature 07: 18a8 Problem Signature 08: 1d Problem Signature 09: System.NullReferenceException </code></pre>
26,616,861
Memory leak when executing Doctrine query in loop
<p>I'm having trouble in locating the cause for a memory leak in my script. I have a simple repository method which increments a 'count' column in my entity by X amount:</p> <pre><code>public function incrementCount($id, $amount) { $query = $this -&gt;createQueryBuilder('e') -&gt;update('MyEntity', 'e') -&gt;set('e.count', 'e.count + :amount') -&gt;where('e.id = :id') -&gt;setParameter('id', $id) -&gt;setParameter('amount', $amount) -&gt;getQuery(); $query-&gt;execute(); } </code></pre> <p>Problem is, if I call this in a loop the memory usage balloons on every iteration:</p> <pre><code>$entityManager = $this-&gt;getContainer()-&gt;get('doctrine')-&gt;getManager(); $myRepository = $entityManager-&gt;getRepository(MyEntity::class); while (true) { $myRepository-&gt;incrementCount("123", 5); $doctrineManager-&gt;clear(); gc_collect_cycles(); } </code></pre> <p>What am I missing here? I've tried <code>-&gt;clear()</code>, as per Doctrine's <a href="http://doctrine-orm.readthedocs.org/en/latest/reference/batch-processing.html" rel="noreferrer">advice on batch processing</a>. I even tried <code>gc_collect_cycles()</code>, but still the issue remains.</p> <p>I'm running Doctrine 2.4.6 on PHP 5.5.</p>
26,769,322
7
6
null
2014-10-28 19:27:01.16 UTC
8
2022-08-04 17:58:57.857 UTC
2019-12-11 16:47:31.093 UTC
null
526,495
null
526,495
null
1
24
php|symfony|memory-leaks|doctrine-orm|doctrine
18,937
<p>I resolved this by adding <code>--no-debug</code> to my command. It turns out that in debug mode, the profiler was storing information about every single query in memory.</p>
9,962,568
Fast solution to Subset sum algorithm by Pisinger
<p>This is a follow-up to my previous <a href="https://stackoverflow.com/questions/9809436/fast-solution-to-subset-sum">question</a>. I still find it very interesting problem and as there is one algorithm which deserves more attention I'm posting it here.</p> <p>From <a href="https://en.wikipedia.org/wiki/Subset_sum_problem#cite_ref-Pisinger09_2-0" rel="nofollow noreferrer">Wikipedia</a>: <em>For the case that each xi is positive and bounded by the same constant, Pisinger found a linear time algorithm.</em></p> <p>There is a different paper which seems to describe the same algorithm but it is a bit difficult to read for me so please - does anyone know how to translate the pseudo-code from page 4 (<code>balsub</code>) into working implementation?</p> <p>Here are couple of pointers I collected so far:</p> <p><a href="http://www.diku.dk/~pisinger/95-6.ps" rel="nofollow noreferrer">http://www.diku.dk/~pisinger/95-6.ps</a> (the paper)<br> <a href="https://stackoverflow.com/a/9952759/1037407">https://stackoverflow.com/a/9952759/1037407</a><br> <a href="http://www.diku.dk/hjemmesider/ansatte/pisinger/codes.html" rel="nofollow noreferrer">http://www.diku.dk/hjemmesider/ansatte/pisinger/codes.html</a> </p> <p>PS: I don't really insist on precisely this algorithm so if you know of any other similarly performant algorithm please feel free to suggest it bellow.</p> <p><strong>Edit</strong></p> <p>This is a Python version of the code posted bellow by oldboy:</p> <pre><code>class view(object): def __init__(self, sequence, start): self.sequence, self.start = sequence, start def __getitem__(self, index): return self.sequence[index + self.start] def __setitem__(self, index, value): self.sequence[index + self.start] = value def balsub(w, c): '''A balanced algorithm for Subset-sum problem by David Pisinger w = weights, c = capacity of the knapsack''' n = len(w) assert n &gt; 0 sum_w = 0 r = 0 for wj in w: assert wj &gt; 0 sum_w += wj assert wj &lt;= c r = max(r, wj) assert sum_w &gt; c b = 0 w_bar = 0 while w_bar + w[b] &lt;= c: w_bar += w[b] b += 1 s = [[0] * 2 * r for i in range(n - b + 1)] s_b_1 = view(s[0], r - 1) for mu in range(-r + 1, 1): s_b_1[mu] = -1 for mu in range(1, r + 1): s_b_1[mu] = 0 s_b_1[w_bar - c] = b for t in range(b, n): s_t_1 = view(s[t - b], r - 1) s_t = view(s[t - b + 1], r - 1) for mu in range(-r + 1, r + 1): s_t[mu] = s_t_1[mu] for mu in range(-r + 1, 1): mu_prime = mu + w[t] s_t[mu_prime] = max(s_t[mu_prime], s_t_1[mu]) for mu in range(w[t], 0, -1): for j in range(s_t[mu] - 1, s_t_1[mu] - 1, -1): mu_prime = mu - w[j] s_t[mu_prime] = max(s_t[mu_prime], j) solved = False z = 0 s_n_1 = view(s[n - b], r - 1) while z &gt;= -r + 1: if s_n_1[z] &gt;= 0: solved = True break z -= 1 if solved: print c + z print n x = [False] * n for j in range(0, b): x[j] = True for t in range(n - 1, b - 1, -1): s_t = view(s[t - b + 1], r - 1) s_t_1 = view(s[t - b], r - 1) while True: j = s_t[z] assert j &gt;= 0 z_unprime = z + w[j] if z_unprime &gt; r or j &gt;= s_t[z_unprime]: break z = z_unprime x[j] = False z_unprime = z - w[t] if z_unprime &gt;= -r + 1 and s_t_1[z_unprime] &gt;= s_t[z]: z = z_unprime x[t] = True for j in range(n): print x[j], w[j] </code></pre>
9,997,386
2
1
null
2012-04-01 07:04:38.827 UTC
11
2020-10-01 14:50:22.83 UTC
2017-05-23 12:19:19.203 UTC
null
-1
null
1,037,407
null
1
9
algorithm|subset-sum
5,932
<pre><code>// Input: // c (capacity of the knapsack) // n (number of items) // w_1 (weight of item 1) // ... // w_n (weight of item n) // // Output: // z (optimal solution) // n // x_1 (indicator for item 1) // ... // x_n (indicator for item n) #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { int c = 0; cin &gt;&gt; c; int n = 0; cin &gt;&gt; n; assert(n &gt; 0); vector&lt;int&gt; w(n); int sum_w = 0; int r = 0; for (int j = 0; j &lt; n; ++j) { cin &gt;&gt; w[j]; assert(w[j] &gt; 0); sum_w += w[j]; assert(w[j] &lt;= c); r = max(r, w[j]); } assert(sum_w &gt; c); int b; int w_bar = 0; for (b = 0; w_bar + w[b] &lt;= c; ++b) { w_bar += w[b]; } vector&lt;vector&lt;int&gt; &gt; s(n - b + 1, vector&lt;int&gt;(2 * r)); vector&lt;int&gt;::iterator s_b_1 = s[0].begin() + (r - 1); for (int mu = -r + 1; mu &lt;= 0; ++mu) { s_b_1[mu] = -1; } for (int mu = 1; mu &lt;= r; ++mu) { s_b_1[mu] = 0; } s_b_1[w_bar - c] = b; for (int t = b; t &lt; n; ++t) { vector&lt;int&gt;::const_iterator s_t_1 = s[t - b].begin() + (r - 1); vector&lt;int&gt;::iterator s_t = s[t - b + 1].begin() + (r - 1); for (int mu = -r + 1; mu &lt;= r; ++mu) { s_t[mu] = s_t_1[mu]; } for (int mu = -r + 1; mu &lt;= 0; ++mu) { int mu_prime = mu + w[t]; s_t[mu_prime] = max(s_t[mu_prime], s_t_1[mu]); } for (int mu = w[t]; mu &gt;= 1; --mu) { for (int j = s_t[mu] - 1; j &gt;= s_t_1[mu]; --j) { int mu_prime = mu - w[j]; s_t[mu_prime] = max(s_t[mu_prime], j); } } } bool solved = false; int z; vector&lt;int&gt;::const_iterator s_n_1 = s[n - b].begin() + (r - 1); for (z = 0; z &gt;= -r + 1; --z) { if (s_n_1[z] &gt;= 0) { solved = true; break; } } if (solved) { cout &lt;&lt; c + z &lt;&lt; '\n' &lt;&lt; n &lt;&lt; '\n'; vector&lt;bool&gt; x(n, false); for (int j = 0; j &lt; b; ++j) x[j] = true; for (int t = n - 1; t &gt;= b; --t) { vector&lt;int&gt;::const_iterator s_t = s[t - b + 1].begin() + (r - 1); vector&lt;int&gt;::const_iterator s_t_1 = s[t - b].begin() + (r - 1); while (true) { int j = s_t[z]; assert(j &gt;= 0); int z_unprime = z + w[j]; if (z_unprime &gt; r || j &gt;= s_t[z_unprime]) break; z = z_unprime; x[j] = false; } int z_unprime = z - w[t]; if (z_unprime &gt;= -r + 1 &amp;&amp; s_t_1[z_unprime] &gt;= s_t[z]) { z = z_unprime; x[t] = true; } } for (int j = 0; j &lt; n; ++j) { cout &lt;&lt; x[j] &lt;&lt; '\n'; } } } </code></pre>
9,964,496
Alpha-beta move ordering
<p>I have a basic implementation of alpha-beta pruning but I have no idea how to improve the move ordering. I have read that it can be done with a shallow search, iterative deepening or storing the bestMoves to transition table.</p> <p>Any suggestions how to implement one of these improvements in this algorithm?</p> <pre><code> public double alphaBetaPruning(Board board, int depth, double alpha, double beta, int player) { if (depth == 0) { return board.evaluateBoard(); } Collection&lt;Move&gt; children = board.generatePossibleMoves(player); if (player == 0) { for (Move move : children) { Board tempBoard = new Board(board); tempBoard.makeMove(move); int nextPlayer = next(player); double result = alphaBetaPruning(tempBoard, depth - 1, alpha,beta,nextPlayer); if ((result &gt; alpha)) { alpha = result; if (depth == this.origDepth) { this.bestMove = move; } } if (alpha &gt;= beta) { break; } } return alpha; } else { for (Move move : children) { Board tempBoard = new Board(board); tempBoard.makeMove(move); int nextPlayer = next(player); double result = alphaBetaPruning(tempBoard, depth - 1, alpha,beta,nextPlayer); if ((result &lt; beta)) { beta = result; if (depth == this.origDepth) { this.bestMove = move; } } if (beta &lt;= alpha) { break; } } return beta; } } public int next(int player) { if (player == 0) { return 4; } else { return 0; } } </code></pre>
9,964,572
2
0
null
2012-04-01 12:46:22.313 UTC
8
2015-10-16 03:04:38.783 UTC
2015-10-16 02:41:40.99 UTC
null
1,090,562
user1306283
null
null
1
18
java|algorithm|artificial-intelligence|minimax|alpha-beta-pruning
17,537
<ul> <li><p>Node reordering with shallow search is trivial: calculate the heuristic value for each child of the state <strong>before recursively checking them</strong>. Then, sort the values of these states [descending for max vertex, and ascending for min vertex], and recursively invoke the algorithm on the sorted list. The idea is - if a state is good at shallow depth, it is more likely to be good at deep state as well, and if it is true - you will get more prunnings. </p> <p>The sorting should be done <strong>before</strong> this [in both <code>if</code> and <code>else</code> clauses]</p> <p><code>for (Move move : children) {</code></p></li> <li><p>storing moves is also trivial - many states are calculated twice, when you finish calculating any state, store it [with the depth of the calculation! it is improtant!] in a <code>HashMap</code>. First thing you do when you start calculation on a vertex - is check if it is already calculated - and if it is, returned the cached value. The idea behind it is that many states are reachable from different paths, so this way - you can eliminate redundant calculations.</p> <p>The changes should be done both in the first line of the method [something like <code>if (cache.contains((new State(board,depth,player)) return cache.get(new State(board,depth,player))</code>] [excuse me for lack of elegance and efficiency - just explaining an idea here]. <br> You should also add <code>cache.put(...)</code> before each <code>return</code> statement.</p></li> </ul>
9,751,554
List as a member of a python class, why is its contents being shared across all instances of the class?
<p>I have defined a class <code>Listener</code> and created a dictionary of <code>Listener</code> objects. Each listener has an <code>id</code> to identify them, and a list of <code>artists</code> they listen to, <code>artists = []</code>. Adding something to the <code>artists</code> list adds it for all instances of the <code>Listener</code> class, rather than the referred instance. This is my problem.</p> <p>The Listener class is defined as follows:</p> <pre><code>class Listener: id = "" artists = [] def __init__(self, id): self.id = id def addArtist(self, artist, plays): print self.id # debugging... print "pre: ", self.artists self.artists.append(artist) print "post: ", self.artists </code></pre> <p>Here is my debugging test code:</p> <pre><code>def debug(): listeners = {} listeners["0"] = Listener("0") listeners["1"] = Listener("1") listeners["0"].addArtist("The Beatles", 10) listeners["0"].addArtist("Lady Gaga", 4) listeners["1"].addArtist("Ace of Base", 5) </code></pre> <p>And the output:</p> <pre><code>0 pre: [] post: ['The Beatles'] 0 pre: ['The Beatles'] post: ['The Beatles', 'Lady Gaga'] 1 pre: ['The Beatles', 'Lady Gaga'] post: ['The Beatles', 'Lady Gaga', 'Ace of Base'] </code></pre> <p>My expected output is that the final <code>addArtist("Ace of Base", 5)</code> call would result in the output </p> <pre><code>1 pre: [] post: ['Ace of Base'] </code></pre> <p>Is this a subtlety of Python I'm not understanding? Why is this the output and how can I get the desired output instead? Thanks!</p>
9,751,566
2
1
null
2012-03-17 16:13:18.643 UTC
12
2020-08-19 16:45:34.113 UTC
2019-08-29 22:27:13.14 UTC
null
3,082,718
null
1,084,573
null
1
34
python|list|class
62,424
<p>You don't want the members declared inside the class, but just set in the <code>__init__</code> method:</p> <pre><code>class Listener: def __init__(self, id): self.id = id self.artists = [] def addArtist(self, artist, plays): print self.id # debugging... print "pre: ", self.artists self.artists.append(artist) print "post: ", self.artists </code></pre> <p>If you have a class like</p> <pre><code>class A: x=5 </code></pre> <p>Then x is a member of the class and not a member of instances of that class. This can be confusing, since python lets you access class members through the instance:</p> <pre><code>&gt;&gt;&gt; a=A() &gt;&gt;&gt; print a.x 5 </code></pre> <p>But you can also access it through the class itself:</p> <pre><code>&gt;&gt;&gt; print A.x 5 </code></pre> <p>It would even appear that this works properly:</p> <pre><code>&gt;&gt;&gt; a1=A() &gt;&gt;&gt; a2=A() &gt;&gt;&gt; a1.x=6 &gt;&gt;&gt; print a1.x 6 &gt;&gt;&gt; print a2.x 5 </code></pre> <p>but what has actually happened is that you've put a new x into the a1 instance, which will be printed instead of the class member, which still has its original value:</p> <pre><code>&gt;&gt;&gt; print A.x 5 </code></pre> <p>You only start to see a difference when you have something that can be changed, like a list:</p> <pre><code>class A: l=[] &gt;&gt;&gt; a1=A() &gt;&gt;&gt; print a1.l [] &gt;&gt;&gt; a2=A() &gt;&gt;&gt; print a2.l [] &gt;&gt;&gt; a1.l.append(5) &gt;&gt;&gt; print a1.l [5] &gt;&gt;&gt; print a2.l [5] &gt;&gt;&gt; print A.l [5] </code></pre>
9,832,660
Why don't most vim color schemes look as nice as the screenshot when I use them?
<p>I have downloaded many vim color schemas and tried them out, but many of them don't look like the official screenshot.</p> <p>For example, vim's own color schema - <code>desert</code> should look like this: <img src="https://i.stack.imgur.com/1fFmd.png" alt="desert color schema"> </p> <p>But in my vim, many colors won't display, for example the background. <img src="https://i.stack.imgur.com/TVBIg.png" alt="my vim color display"></p> <p>But some color schemas work correctly.</p> <p>Why is that?</p> <p>In the: Edit-> Profile Preferences -> Colors, I select the "use colors from system theme"</p>
9,833,425
4
4
null
2012-03-23 00:43:35.947 UTC
22
2012-07-21 20:21:04.43 UTC
2012-07-19 20:19:57.05 UTC
null
541,091
null
1,276,501
null
1
47
vim|colors|terminal|schema
48,857
<p>Many colorschemes are designed for 256 colors, which is significantly better than a standard 8 color terminal. To make that work, you need <code>$TERM</code> set to a 256 color terminal like <code>xterm-256color</code>.</p> <p>If you have a 256 color capable terminal (looks like you do from your screenshot if that is Gnome Terminal), set the <code>$TERM</code> to <code>xterm-256color</code> and enable 256 colors in your vimrc with something like:</p> <pre><code>if $TERM == "xterm-256color" set t_Co=256 endif </code></pre> <p>The <a href="http://vim.wikia.com/wiki/256_colors_in_vim">Vim wiki has some tips</a> on setting the correct <code>$TERM</code> for different terminal emulators. The easiest way to test this out quickly is to do</p> <pre><code>TERM=xterm-256color vim </code></pre> <p>This will not make colorschemes designed for GUI vim fully compatible with terminal Vim, but will make 256-color colorschemes work, and those are a giant improvement over the standard 8 color colorschemes.</p>
10,252,448
How to check whether a sentence is correct (simple grammar check in Python)?
<p>How to check whether a sentence is valid in Python?</p> <p>Examples:</p> <pre><code>I love Stackoverflow - Correct I Stackoverflow love - Incorrect </code></pre>
10,252,472
5
0
null
2012-04-20 19:33:13.96 UTC
25
2022-09-04 04:36:10.143 UTC
2013-03-12 04:41:23.22 UTC
null
610,569
null
1,110,394
null
1
61
python|nlp|grammar
86,552
<p>Check out <a href="http://www.nltk.org" rel="noreferrer">NLTK</a>. They have support for grammars that you can use to parse your sentence. You can define a grammar, or use one that is provided, along with a context-free parser. If the sentence parses, then it has valid grammar; if not, then it doesn't. These grammars may not have the widest coverage (eg, it might not know how to handle a word like StackOverflow), but this approach will allow you to say specifically what is valid or invalid in the grammar. <a href="http://www.nltk.org/book/ch08.html" rel="noreferrer">Chapter 8</a> of the NLTK book covers parsing and should explain what you need to know.</p> <p>An alternative would be to write a python interface to a wide-coverage parser (like the <a href="http://nlp.stanford.edu/software/lex-parser.shtml" rel="noreferrer">Stanford parser</a> or <a href="http://svn.ask.it.usyd.edu.au/trac/candc" rel="noreferrer">C&amp;C</a>). These are statistical parsers that will be able to understand sentences even if they haven't seen all the words or all the grammatical constructions before. The downside is that sometimes the parser will still return a parse for a sentence with bad grammar because it will use the statistics to make the best guess possible.</p> <p>So, it really depends on exactly what your goal is. If you want very precise control over what is considered grammatical, use a context-free parser with NLTK. If you want robustness and wide-coverage, use a statistical parser.</p>
9,953,448
Bash - How to remove all white spaces from a given text file?
<p>I want to remove all the white spaces from a given text file.</p> <p>Is there any shell command available for this ?</p> <p>Or, how to use <code>sed</code> for this purpose?</p> <p>I want something like below:</p> <blockquote> <p>$ cat hello.txt | sed ....</p> </blockquote> <p>I tried this : <code>cat hello.txt | sed 's/ //g'</code> .</p> <p>But it removes only spaces, not tabs.</p> <p>Thanks.</p>
9,953,487
11
1
null
2012-03-31 06:03:00.893 UTC
17
2022-08-29 14:51:14.997 UTC
2022-08-29 14:51:14.997 UTC
null
5,918,539
null
986,020
null
1
97
linux|bash|sed
363,591
<pre><code>$ man tr NAME tr - translate or delete characters SYNOPSIS tr [OPTION]... SET1 [SET2] DESCRIPTION Translate, squeeze, and/or delete characters from standard input, writing to standard output. </code></pre> <p>In order to wipe all whitespace including newlines you can try:</p> <pre><code>cat file.txt | tr -d " \t\n\r" </code></pre> <p>You can also use the character classes defined by tr (credits to <a href="https://stackoverflow.com/users/315868/htompkins">htompkins</a> comment):</p> <pre><code>cat file.txt | tr -d "[:space:]" </code></pre> <p>For example, in order to wipe just horizontal white space:</p> <pre><code>cat file.txt | tr -d "[:blank:]" </code></pre>
7,748,392
Is there any reason not to call setIntent when overriding onNewIntent?
<p>While experiencing a problem similar to <a href="https://stackoverflow.com/questions/4787249/how-to-capture-the-new-intent-in-onnewintent">this question</a>, I began to wonder why we explicitly have to call <code>setIntent</code> when overriding <code>onNewIntent</code>, and why this code isn't performed already by <code>super.onNewIntent</code>.</p> <pre><code>@Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); // Why isn't this performed by the framework in the line above? setIntent(intent); } </code></pre>
7,749,347
3
0
null
2011-10-13 01:18:49.447 UTC
10
2014-01-21 14:49:26.16 UTC
2017-05-23 12:18:14.06 UTC
null
-1
null
81,717
null
1
29
android|android-intent|android-activity
14,013
<p><code>Intent</code> objects are persistently attached to the <code>Activity</code>, <code>Service</code> and other components for as long as those components are running. They don't simply go away because you moved off to another application. The reason for this is because Android may kill the process at any time, but the user may still want to go back and continue what they were doing. This makes Intents ideal for storing or transmitting small (and sometimes large) bits of information, via the Extras.</p> <p>The <code>onNewIntent()</code> method is specifically for handling application components that are more persistent and hence may be called more than once during its LifeCycle but needs to keep track of the reasons why it was called (and hence the data it was called with). Whether you call <code>setIntent()</code> or not depends on what you need to do.</p> <p>If you don't care why it was subsequently called, you may keep the original <code>Intent</code> by not calling <code>setIntent()</code>. This is particularly useful when your <code>Activity</code> (or some other component) does the same thing no matter who called it and what data it provides.</p> <p>If you have a need to respond to each event individually, then you must at least store the new <code>Intent</code>'s information. This means you may avoid <code>setIntent()</code>, however, then none of the components it links to will have any of the <code>Intent</code> information unless you send it to them directly. This may be the desired behavior for an application that cannot insure the original <code>Intent</code> was completely handled.</p> <p>If you need to respond to each Intent individually and the original <code>Intent</code> does not matter, then you use <code>setIntent()</code>. This discards the original <code>Intent</code>, which is still in there... and places the new <code>Intent</code> so that if the user moves away (yet again), they will come back to the same place.</p> <p>The reason why <code>super.onNewIntent()</code> does not handle this is because the core component classes cannot determine whether or not the new <code>Intent</code> is more important than the old one. All it cares is that it <em>has</em> an <code>Intent</code>, not what it is. This is why we override methods like these, so that <em>we</em> determine what is important and what is not. The general feeling is that base classes like <code>Activity</code> can use whatever data we have, in whatever ways it wants to (unless we override and tell it otherwise). However, they should not (and often cannot) get rid of our data unless we tell them to specifically. <strong>This is an argument you really don't want to have with some programmers. hehe</strong></p> <p>Hope this helps.</p>
7,767,218
Why does the binding update without implementing INotifyPropertyChanged?
<p>I created a ViewModel and bound its property to two textboxes on UI. The value of the other textbox changes when I change the value of first and <em>focus out of the textbox</em> but I'm not implementing INotifyPropertyChanged. How is this working?</p> <p>Following is XAML</p> <pre><code>&lt;Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"&gt; &lt;Window.DataContext&gt; &lt;local:ViewModel /&gt; &lt;/Window.DataContext&gt; &lt;StackPanel&gt; &lt;TextBox Text="{Binding Name}" /&gt; &lt;TextBox Text="{Binding Name}" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>And following is my ViewModel</p> <pre class="lang-cs prettyprint-override"><code>class ViewModel { public string Name { get; set; } } </code></pre>
7,767,274
3
0
null
2011-10-14 11:54:43.79 UTC
18
2020-06-08 12:07:46.79 UTC
2011-10-24 14:04:18.13 UTC
null
41,071
null
36,464
null
1
47
wpf|xaml|data-binding
10,798
<p>I tested it, you are right. Now i searched for it on the web, and found <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9365bb6a-b411-4967-9a03-ae2a810fb215/" rel="noreferrer">this</a>.</p> <blockquote> <p>Sorry to take so long to reply, actually you are encountering a another <strong>hidden aspect of WPF</strong>, that's it WPF's data binding engine <strong>will data bind to PropertyDescriptor instance</strong> which wraps the source property if the source object is a plain CLR object <strong>and doesn't implement INotifyPropertyChanged</strong> interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox.</p> <p>And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect.</p> <p>Hope this clears things up a little bit.</p> </blockquote> <p>So basically you can do this, as long as its a plain CLR object. Pretty neat but totally unexpected - and i have done a bit of WPF work the past years. You never stop learning new things, right?</p> <p>As suggested by Hasan Khan, here is <a href="http://10rem.net/blog/2010/12/17/puff-the-magic-poco-binding-and-inotifypropertychanged-in-wpf" rel="noreferrer">another link</a> to a pretty interesting article on this subject.</p> <blockquote> <p>Note <strong>this only works when using binding</strong>. If you update the values <strong>from code</strong>, the change <strong>won't be notified</strong>. [...]</p> <p>WPF uses the much lighter weight PropertyInfo class when binding. If you explicitly implement INotifyPropertyChanged, all WPF needs to do is call the PropertyInfo.GetValue method to get the latest value. That's quite a bit less work than getting all the descriptors. Descriptors end up costing in the order of 4x the memory of the property info classes. [...]</p> <p>Implementing INotifyPropertyChanged can be a fair bit of tedious development work. However, you'll need to weigh that work against the runtime footprint (memory and CPU) of your WPF application. <strong>Implementing INPC yourself will save runtime CPU and memory</strong>.</p> </blockquote> <p><strong>Edit:</strong></p> <p>Updating this, since i still get comments and upvotes now and then from here, so it clearly is still relevant, even thouh i myself have not worked with WPF for quite some time now. However, as mentioned in the comments, be aware that this may cause <a href="http://www.cplotts.com/2009/04/14/wpf-memory-leaks/" rel="noreferrer">memory leaks</a>. Its also supposedly heavy on the Reflection usage, which has been mentioned as well.</p>
11,558,929
In App purchase in iOS suddenly stop working ( Error code=5002 occurred )
<p>I have integrated in-App purchase in my application successfully. I tested it properly by making test user account in itunes. My in-app purchase worked fine. But suddenly my IAP stopped working.</p> <p>App can load all of the products but after entering my account credentials then transection queue undergoes state <code>SKPaymentTransactionStateFailed</code> and gives an error </p> <blockquote> <p>Error Domain=SSServerErrorDomain Code=5002 "An unknown error has occurred"</p> </blockquote>
21,064,083
6
5
null
2012-07-19 10:31:54.057 UTC
6
2014-01-11 15:25:50.37 UTC
2012-07-19 15:50:48.87 UTC
user577537
null
user1228103
null
null
1
28
ios|in-app-purchase
10,582
<p>It has been stopped working on simulator. try to use it on real device. It will work fine.</p>
11,845,412
Text floating in block next to image
<p>I would like to achieve the following placement:</p> <p>Two different texts (in block) floating / inline next to image. (Everything inside div).</p> <p>I have been trying with different display settings (block + inline for text etc.) but it is still not working.</p> <p><img src="https://i.stack.imgur.com/Z0Efj.png" alt="enter image description here"> </p> <p><strong>HTML:</strong></p> <pre><code>&lt;div class="res"&gt; &lt;img src="&lt;?php echo 'img/'.$row["sType"].'.png';?&gt;"/&gt; &lt;span&gt;TITLEe&lt;/span&gt; &lt;span&gt;Description&lt;/span&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>.res { height:60px; background-color:yellow; border-bottom:1px solid black; text-align:left; } .res img { margin-top:8.5px; margin-left:5px; display:inline } .res span { display:block; } </code></pre>
11,845,560
6
1
null
2012-08-07 11:55:07.18 UTC
7
2022-04-03 15:15:57.223 UTC
2012-08-07 12:00:45.01 UTC
null
1,318,239
null
1,318,239
null
1
35
html|css
111,731
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { width: 400px; border: 4px solid red; padding: 20px; overflow: hidden; } .content img { margin-right: 15px; float: left; } .content h3, .content p{ margin-left: 15px; display: block; margin: 2px 0 0 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="content"&gt; &lt;img src="http://cdn4.iconfinder.com/data/icons/socialmediaicons_v120/48/google.png"/ alt="" &gt; &lt;h3&gt;Title&lt;/h3&gt; &lt;p&gt;Some Description&lt;/p&gt; &lt;/div&gt;​</code></pre> </div> </div> </p>
11,465,258
Xlib.h not found when building graphviz on Mac OS X 10.8 (Mountain Lion)
<p>When using homebrew to install graphviz, the script gets to the point of "Making install in tkstubs" and then throws the following fatal error:</p> <pre><code>In file included from tkStubLib.c:15: /usr/include/tk.h:78:11: fatal error: 'X11/Xlib.h' file not found #include &lt;X11/Xlib.h&gt; </code></pre> <p>I have installed XQuartz as X11 has been dropped in Mountain Lion, but I'm unsure if it is installed correctly. The location of Xlib.h is:</p> <pre><code>/opt/X11/include/X11/Xlib.h </code></pre> <p>There are also two symlinks to /opt/X11, they are:</p> <pre><code>/usr/X11 /usr/X11R6 </code></pre> <p>Does this look like the correct setup to you? I've never dealt with X11 or XQuartz until yesterday.</p> <p>Cheers.</p>
11,465,328
8
0
null
2012-07-13 06:29:41.677 UTC
17
2019-05-26 01:37:07.977 UTC
2012-08-22 17:51:15.603 UTC
null
456,584
null
709,016
null
1
45
x11|graphviz|homebrew|osx-mountain-lion
78,692
<p>You need to tell the <code>tkstubs</code> build (and possibly other bits in the package as well) to look for headers in <code>/opt/X11/include</code>; this is not on the standard include path.</p> <p>Usually this is achieved by passing <code>-I/opt/X11/include</code> as an additional compiler flag, the method to do so is however dependent on the build system.</p> <p>For reasonably modern <code>configure</code> scripts, the best approach is to pass it in the environment variable <code>CPPFLAGS</code>; if the package uses another build system or this doesn't work for another reason, then you need to look at the <code>Makefile</code> in the build directory.</p>
11,516,747
Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception
<p><strong>Why does it say <em>null</em> URL and gives a empty ' ' class in the exception when I have provided the database URL?</strong></p> <p>I am trying to connect to a derby database via a servlet while using Tomcat. When the servlet gets run, I get the following exceptions:</p> <pre><code>org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at servlets.servlet_1.doGet(servlet_1.java:23) // ---&gt; Marked the statement in servlet at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307) at java.sql.DriverManager.getDriver(DriverManager.java:253) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437) ... 24 more </code></pre> <p><em>Servlet :</em></p> <pre><code>package servlets; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.http.*; import javax.servlet.*; import javax.sql.DataSource; public class servlet_1 extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // String queryString = request.getQueryString(); System.out.println(&quot;!!!!!!!!!!!!!!!!!!!&quot;); Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup(&quot;java:comp/env&quot;); DataSource ds = (DataSource)envContext.lookup(&quot;jdbc/PollDatasource&quot;); Connection connection = ds.getConnection(); // --&gt;LINE 23 String sqlQuery = &quot;select * from PollResult&quot;; PreparedStatement statement = connection.prepareStatement(sqlQuery); ResultSet set = statement.executeQuery(); System.out.println(&quot;after the final statement&quot;); } catch (Exception exc) { exc.printStackTrace(); } } } </code></pre> <p>What exception is this? Why do I get this exception?</p> <p>I have added the following tag in <code>context.xml</code> of Tomcat :</p> <pre><code>&lt;Resource name=&quot;jdbc/PollDatasource&quot; auth=&quot;Container&quot; type=&quot;javax.sql.DataSource&quot; driverClassName=&quot;org.apache.derby.jdbc.EmbeddedDriver&quot; url=&quot;jdbc:derby://localhost:1527/poll_database;create=true&quot; username=&quot;suhail&quot; password=&quot;suhail&quot; maxActive=&quot;20&quot; maxIdle=&quot;10&quot; maxWait=&quot;-1&quot; /&gt; </code></pre> <p>and this in <code>web.xml</code> :</p> <pre><code>&lt;resource-ref&gt; &lt;description&gt;my connection&lt;/description&gt; &lt;res-ref-name&gt;jdbc/PollDatasource&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;/resource-ref&gt; </code></pre> <p>Where am I making a mistake?</p> <p><em>Image that shows the database URL..</em></p> <p><img src="https://i.stack.imgur.com/8oTLF.jpg" alt="enter image description here" /></p> <p><strong><em>NOTE : After the answer by @Bryan Pendleton I changed the driver to <code>org.apache.derby.jdbc.ClientDriver</code> but I get the same exception.</em></strong></p>
11,588,580
12
7
null
2012-07-17 05:54:47.36 UTC
9
2022-07-13 11:04:59.297 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
648,138
null
1
56
java|jakarta-ee|tomcat|jndi|derby
164,544
<p>I can't see anything obviously wrong, but perhaps a different approach might help you debug it?</p> <p>You could try specify your datasource in the per-application-context instead of the global tomcat one.</p> <p>You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Context [optional other attributes as required]&gt; &lt;Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver" url="jdbc:derby://localhost:1527/poll_database;create=true" username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/&gt; &lt;/Context&gt; </code></pre> <p>Obviously the path and docBase would need to match your application's specific details.</p> <p>Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.</p> <p>At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.</p>
11,991,194
Can I set null as the default value for a @Value in Spring?
<p>I'm currently using the @Value Spring 3.1.x annotation like this:</p> <pre><code>@Value("${stuff.value:}") private String value; </code></pre> <p>This puts an empty String into the variable if the attribute is not present. I would like to have null as the default instead of an empty String. Of course I also want to avoid an error when the property stuff.value is not set.</p>
11,993,545
5
0
null
2012-08-16 16:00:40.25 UTC
23
2020-06-16 12:32:38.633 UTC
null
null
null
null
1,159,684
null
1
145
java|spring|spring-annotations
121,562
<p>You must set the nullValue of the <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html#setNullValue%28java.lang.String%29">PropertyPlaceholderConfigurer</a>. For the example I'm using the string <code>@null</code> but you can also use the empty string as nullValue.</p> <pre><code>&lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;!-- config the location(s) of the properties file(s) here --&gt; &lt;property name="nullValue" value="@null" /&gt; &lt;/bean&gt; </code></pre> <p>Now you can use the string <code>@null</code> to represent the <code>null</code> value</p> <pre><code>@Value("${stuff.value:@null}") private String value; </code></pre> <p>Please note: The context name space doesn't support the null value at the moment. You can't use</p> <pre><code>&lt;context:property-placeholder null-value="@null" ... /&gt; </code></pre> <p>Tested with Spring 3.1.1</p>
3,357,712
How can I call a static method in a Ruby module from a class that includes the module?
<p>Is it possible to declare static methods in a module in ruby?</p> <pre><code>module Software def self.exit puts "exited" end end class Windows include Software def self.start puts "started" self.exit end end Windows.start </code></pre> <p>The example above will not print out "exited".</p> <p>Is it only possible to have instance methods in a module?</p>
3,357,865
4
0
null
2010-07-28 21:38:33.313 UTC
5
2018-05-16 20:17:18.89 UTC
2018-05-16 20:17:18.89 UTC
null
27,358
null
224,922
null
1
28
ruby
22,450
<p>Define your module like this (i.e. make <code>exit</code> an instance method in the module):</p> <pre><code>module Software def exit puts "exited" end end </code></pre> <p>and then use <code>extend</code> rather than <code>include</code></p> <pre><code>class Windows extend Software # your self.start method as in the question end </code></pre> <p>In use:</p> <pre><code>irb(main):016:0&gt; Windows.start started exited =&gt; nil </code></pre> <p><strong>Explanation</strong></p> <blockquote> <p><a href="http://ruby-doc.org/core/classes/Object.html#M000335" rel="noreferrer"><em>obj</em>.extend(module, ...)</a> adds to <em>obj</em> the instance methods from each module given as a parameter</p> </blockquote> <p>...so when used within the context of a class definition (with the class itself as the receiver) the methods become class methods.</p>
3,807,662
EJB's - when to use Remote and/or local interfaces?
<p>I'm very new to Java EE and I'm trying to understand the concept of Local interfaces and Remote interfaces. I've been told that one of the big advantages of Java EE is that it is easy to scale (which I believe means you can deploy different components on different servers). Is that where Remote and Local interfaces come in? Are you supposed to use Remote interfaces if you expect your application to have different components on different servers? And use Local interfaces if your application is only going to reside on one server?</p> <p>If my assumptions above are correct, how would you go about choosing whether to use Local or Remote interfaces for a new application, where your unsure of what the volume of traffic would be? Start off by using Local interfaces, and gradually upgrade to Remote interfaces where applicable?</p> <p>Thanks for any clarification and suggestions.</p>
3,809,779
4
0
null
2010-09-27 20:39:05.463 UTC
76
2019-12-13 17:14:40.633 UTC
2017-02-20 17:38:46.183 UTC
null
1,475,228
null
221,564
null
1
189
java|jakarta-ee|ejb
87,204
<blockquote> <p>I'm very new to Java EE and I'm trying to understand the concept of Local interfaces and Remote interfaces.</p> </blockquote> <p>In the initial versions of the EJB specification, EJBs were "assumed" to be remote components and the only way to invoke them was to make a remote call, using RMI semantics and all the overhead it implies (a network call and object serialization for every method call). EJB clients had to pay this performance penalty even when collocated in the same virtual machine with the EJB container. </p> <p>Later, Sun realized most business applications were actually not distributing EJBs on a different tier and they fixed the spec (in EJB 2.0) by introducing the concept of Local interfaces so that clients collocated in the same virtual machine with the EJB container can call EJBs using direct method invocation, totally bypassing RMI semantics (and the associated overhead).</p> <blockquote> <p>I've been told that one of the big advantages of Java EE is that it is easy to scale (which I believe means you can deploy different components on different servers)</p> </blockquote> <p>Java EE can scale, but this doesn't necessarily means <em>distributing</em> components. You can run a Web+EJB application on a cluster without separating the Web tier and the EJB tier. </p> <blockquote> <p>Are you supposed to use Remote interfaces if you expect your application to have different components on different servers? And use Local interfaces if your application is only going to reside on one server?</p> </blockquote> <p>I would phrase it like this: use remote interfaces if the client are not in the same JVM (this doesn't mean using only one server/JVM).</p> <blockquote> <p>(...) Start off by using Local interfaces, and gradually upgrade to Remote interfaces where applicable?</p> </blockquote> <p>I would probably start by using Local interfaces. And as already hinted, switching to remote interfaces is not always mandatory (you can cluster a <em>collocated</em> structure). </p> <p>I suggest to check the resources mentioned below (the 2 first ones are quite old but still relevant, the 2 others are more recent). </p> <h3>Resources</h3> <ul> <li><a href="http://www.theserverside.com/news/1364410/Under-the-Hood-of-J2EE-Clustering" rel="noreferrer">Under the Hood of J2EE Clustering</a> by Wang Yu</li> <li><a href="http://www.theserverside.com/news/1363681/Scaling-Your-Java-EE-Applications" rel="noreferrer">Scaling Your Java EE Applications</a> by Wang Yu</li> <li><a href="http://www.theserverside.com/news/1320914/Scaling-Your-Java-EE-Applications-Part-2" rel="noreferrer">Scaling Your Java EE Applications -- Part 2</a> by Wang Yu</li> </ul>
3,949,762
How to wrap text using CSS?
<pre><code>&lt;td&gt;gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg&lt;/td&gt; </code></pre> <p>How do I get text like this to wrap in CSS?</p>
3,950,240
5
2
null
2010-10-16 16:37:22.683 UTC
25
2019-05-29 15:36:17.12 UTC
null
null
null
null
251,257
null
1
107
css|word-wrap
309,689
<p>Try doing this. Works for IE8, FF3.6, Chrome</p> <pre><code>&lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div style="word-wrap: break-word; width: 100px"&gt;gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; </code></pre>
3,580,557
Rails 3 using Devise: How to allow someone to log in using their Facebook account?
<p>I have a Rails 3 application using <a href="http://github.com/plataformatec/devise" rel="noreferrer">Devise</a> for authentication. Now I need to allow someone to log in using their Facebook account. I think this is called Facebook Connect, but I've also heard the term Facebook Graph API, so I'm not sure which one I'm asking for.</p> <p>What do I need to do in order to integrate Facebook Connect with Devise?</p> <h2>Solution:</h2> <p>This question is pretty old now. A year ago, Devise v1.2 introduced <a href="https://github.com/intridea/omniauth" rel="noreferrer">OmniAuth</a> support. Now Devise is at v2.1 (as of this writing) and using OmniAuth is even easier. Here is a great tutorial from the Devise wiki on <a href="https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview" rel="noreferrer">using the <code>omniauth-facebook</code> gem with Devise to allow sign-in using Facebook</a>.</p> <p>Also check out this great tutorial on <a href="http://devcenter.heroku.com/articles/facebook" rel="noreferrer">registering your application and working with the Facebook Graph API</a>.</p>
5,321,309
7
1
null
2010-08-27 00:32:49.677 UTC
58
2013-10-27 14:57:24.203 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
48,523
null
1
65
ruby-on-rails|facebook|devise
39,125
<p>Devise 1.2 now comes with facebook login support using omniauth and works with Rails 3.0. Check out the <a href="https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview" rel="noreferrer">wiki entry</a>.</p>
3,258,634
PHP: How to send HTTP response code?
<p>I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.</p> <p>How can I do this in PHP?</p>
12,018,482
8
1
null
2010-07-15 18:23:56.84 UTC
91
2022-08-12 16:09:47 UTC
2013-12-25 12:53:19.92 UTC
null
367,456
null
279,712
null
1
312
php|http-response-codes
507,758
<p>I just found this question and thought it needs a more comprehensive answer:</p> <p>As of <strong>PHP 5.4</strong> there are three methods to accomplish this:</p> <h2>Assembling the response code on your own (PHP >= 4.0)</h2> <p>The <a href="http://php.net/header" rel="noreferrer"><code>header()</code></a> function has a special use-case that detects a HTTP response line and lets you replace that with a custom one</p> <pre><code>header("HTTP/1.1 200 OK"); </code></pre> <p>However, this requires special treatment for (Fast)CGI PHP:</p> <pre><code>$sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') header("Status: 404 Not Found"); else header("HTTP/1.1 404 Not Found"); </code></pre> <p><strong>Note:</strong> According to the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6" rel="noreferrer">HTTP RFC</a>, the <em>reason phrase</em> can be any custom string (that conforms to the standard), but for the sake of client compatibility I <em>do not</em> recommend putting a random string there.</p> <p><strong>Note:</strong> <a href="http://php.net/php-sapi-name" rel="noreferrer"><code>php_sapi_name()</code></a> requires <strong>PHP 4.0.1</strong></p> <h2>3rd argument to header function (PHP >= 4.3)</h2> <p>There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.</p> <p>Since 4.3, the <code>header</code> function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:</p> <pre><code>header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404); </code></pre> <p><strong>I recommend the 2nd one</strong>. The first <em>does</em> work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.</p> <h2>http_response_code function (PHP >= 5.4)</h2> <p>The <a href="http://php.net/http-response-code" rel="noreferrer"><code>http_response_code()</code></a> function was introduced in PHP 5.4, and it made things <strong>a lot</strong> easier.</p> <pre><code>http_response_code(404); </code></pre> <p>That's all.</p> <h2>Compatibility</h2> <p>Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" <code>http_response_code</code> function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...</p> <pre><code>// For 4.3.0 &lt;= PHP &lt;= 5.4.0 if (!function_exists('http_response_code')) { function http_response_code($newcode = NULL) { static $code = 200; if($newcode !== NULL) { header('X-PHP-Response-Code: '.$newcode, true, $newcode); if(!headers_sent()) $code = $newcode; } return $code; } } </code></pre>
3,286,448
Calling a python method from C/C++, and extracting its return value
<p>I'd like to call a custom function that is defined in a Python module from C. I have some preliminary code to do that, but it just prints the output to stdout.</p> <p><strong>mytest.py</strong></p> <pre class="lang-py prettyprint-override"><code>import math def myabs(x): return math.fabs(x) </code></pre> <p><strong>test.cpp</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;Python.h&gt; int main() { Py_Initialize(); PyRun_SimpleString(&quot;import sys; sys.path.append('.')&quot;); PyRun_SimpleString(&quot;import mytest;&quot;); PyRun_SimpleString(&quot;print mytest.myabs(2.0)&quot;); Py_Finalize(); return 0; } </code></pre> <p>How can I extract the return value into a C <code>double</code> and use it in C?</p>
3,310,608
10
3
null
2010-07-20 01:54:41.243 UTC
42
2022-01-20 16:50:21.953 UTC
2021-11-02 23:27:37.65 UTC
null
1,358,308
null
134,397
null
1
87
c++|python|c|python-c-api|python-embedding
101,795
<p>As explained before, using PyRun_SimpleString seems to be a bad idea.</p> <p>You should definitely use the methods provided by the C-API (<a href="http://docs.python.org/c-api/" rel="noreferrer">http://docs.python.org/c-api/</a>).</p> <p>Reading the introduction is the first thing to do to understand the way it works.</p> <p>First, you have to learn about PyObject that is the basic object for the C API. It can represent any kind of python basic types (string, float, int,...).</p> <p>Many functions exist to convert for example python string to char* or PyFloat to double.</p> <p>First, import your module :</p> <pre><code>PyObject* myModuleString = PyString_FromString((char*)"mytest"); PyObject* myModule = PyImport_Import(myModuleString); </code></pre> <p>Then getting a reference to your function :</p> <pre><code>PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"myabs"); PyObject* args = PyTuple_Pack(1,PyFloat_FromDouble(2.0)); </code></pre> <p>Then getting your result :</p> <pre><code>PyObject* myResult = PyObject_CallObject(myFunction, args) </code></pre> <p>And getting back to a double :</p> <pre><code>double result = PyFloat_AsDouble(myResult); </code></pre> <p>You should obviously check the errors (cf. link given by Mark Tolonen).</p> <p>If you have any question, don't hesitate. Good luck.</p>
3,640,544
Visual Studio keyboard shortcut to display IntelliSense
<p>What's the keyboard shortcut for Visual Studio to display the IntelliSense box if one accidentally hits <kbd>ESC</kbd> and wants the box come back again?</p>
3,640,565
10
2
null
2010-09-04 01:24:48.957 UTC
54
2021-07-07 20:08:33.323 UTC
2021-07-07 20:08:33.323 UTC
null
285,795
null
248,430
null
1
160
visual-studio|keyboard-shortcuts
118,759
<p><kbd>Ctrl</kbd> + <kbd>Space</kbd></p> <p>or</p> <p><kbd>Ctrl</kbd> + <kbd>J</kbd></p> <p>You can also go to menu <em>Tools</em> → <em>Options</em> → <em>Environment</em> → <em>Keyboard</em> and check what is assigned to these shortcuts. The command name should be <code>Edit.CompleteWord</code>.</p>
3,634,915
What does "data abstraction" exactly mean?
<p>What does data abstraction refer to? Please provide real life examples alongwith.</p>
3,635,024
16
2
null
2010-09-03 10:36:10.99 UTC
7
2018-06-22 12:17:09.203 UTC
2014-01-27 06:29:32.817 UTC
null
2,723,067
null
164,683
null
1
15
c++|abstraction|database-abstraction
43,683
<p>Abstraction has two parts:</p> <ul> <li><strong>Hide</strong> details that don't matter from a certain point of view</li> <li>Identify details that do matter from a certain point of view and consider items to be of the <strong>the same</strong> class if they possess those details.</li> </ul> <p>For example, if I am designing a program to deal with inventory, I would like to be able to find out how many items of a certain type the system has in stock. From the perspective of the interface system, I don't care if I am getting this information from a database, a csv file, a remote repository via a SOAP interface or punch cards. I just care that I can can say <code>widget.get_items_in_stock()</code> and know that it will return an integer. </p> <p>If I later decide that I want to record that number in some other way, the person designing the interface doesn't need to know, care or worry about it as long as <code>widget</code> still has the <code>get_items_in_stock()</code> method. Like wise, the interface doesn't need to care if I subclass the widget class and add a <code>get_square_root_of_items_in_stock()</code> method. I can pass an instance of the new class to it just as well.</p> <p>So in this example, we've <strong>hidden</strong> the details of how the data is acquired and decided that anything with a <code>get_items_in_stock()</code> method is an instance of <strong>the same</strong> class (or a subclass thereof) for certain purposes.</p>
7,749,530
What is the difference between = and := in Scala?
<p>What is the difference between <code>=</code> and <code>:=</code> in Scala?</p> <p>I have googled extensively for "scala colon-equals", but was unable to find anything definitive.</p>
7,749,559
4
2
null
2011-10-13 04:39:01.78 UTC
11
2019-05-14 15:09:28.833 UTC
2019-05-14 15:09:28.833 UTC
null
2,270,475
null
293,064
null
1
55
scala|syntax|colon-equals
13,648
<p><code>=</code> in scala is the actual assignment operator -- it does a handful of specific things that for the most part you don't have control over, such as</p> <ul> <li>Giving a <code>val</code> or <code>var</code> a value when it's created</li> <li>Changing the value of a <code>var</code></li> <li>Changing the value of a field on a class</li> <li>Making a type alias</li> <li>Probably others</li> </ul> <p><code>:=</code> is not a built-in operator -- anyone can overload it and define it to mean whatever they like. The reason people like to use <code>:=</code> is because it looks very assignmenty and is used as an assignment operator in other languages.</p> <p>So, if you're trying to find out what <code>:=</code> means in the particular library you're using... my advice is look through the Scaladocs (if they exist) for a method named <code>:=</code>.</p>
8,287,628
Proxies with Python 'Requests' module
<p>Just a short, simple one about the excellent <a href="https://requests.readthedocs.io/en/latest/" rel="noreferrer">Requests</a> module for Python.</p> <p>I can't seem to find in the documentation what the variable 'proxies' should contain. When I send it a dict with a standard &quot;IP:PORT&quot; value it rejected it asking for 2 values. So, I guess (because this doesn't seem to be covered in the docs) that the first value is the ip and the second the port?</p> <p>The docs mention this only:</p> <blockquote> <p>proxies – (optional) Dictionary mapping protocol to the URL of the proxy.</p> </blockquote> <p>So I tried this... what should I be doing?</p> <pre><code>proxy = { ip: port} </code></pre> <p>and should I convert these to some type before putting them in the dict?</p> <pre><code>r = requests.get(url,headers=headers,proxies=proxy) </code></pre>
8,287,752
12
0
null
2011-11-27 17:50:23.487 UTC
81
2022-05-31 15:11:45.363 UTC
2022-05-31 15:11:45.363 UTC
null
9,445,557
user1064306
null
null
1
240
python|python-requests|httprequest|http-proxy
528,304
<p>The <code>proxies</code>' dict syntax is <code>{&quot;protocol&quot;: &quot;scheme://ip:port&quot;, ...}</code>. With it you can specify different (or the same) proxie(s) for requests using <em>http</em>, <em>https</em>, and <em>ftp</em> protocols:</p> <pre><code>http_proxy = &quot;http://10.10.1.10:3128&quot; https_proxy = &quot;https://10.10.1.11:1080&quot; ftp_proxy = &quot;ftp://10.10.1.10:3128&quot; proxies = { &quot;http&quot; : http_proxy, &quot;https&quot; : https_proxy, &quot;ftp&quot; : ftp_proxy } r = requests.get(url, headers=headers, proxies=proxies) </code></pre> <p>Deduced from the <a href="https://requests.readthedocs.io/en/latest/api/#requests.request" rel="noreferrer"><code>requests</code> documentation</a>:</p> <blockquote> <p><strong>Parameters:</strong><br /> <code>method</code> – method for the new Request object.<br /> <code>url</code> – URL for the new Request object.<br /> ...<br /> <code>proxies</code> – (optional) Dictionary <em>mapping</em> <strong>protocol</strong> to the <strong>URL of the proxy</strong>.<br /> ...</p> </blockquote> <hr /> <p>On linux you can also do this via the <code>HTTP_PROXY</code>, <code>HTTPS_PROXY</code>, and <code>FTP_PROXY</code> environment variables:</p> <pre><code>export HTTP_PROXY=10.10.1.10:3128 export HTTPS_PROXY=10.10.1.11:1080 export FTP_PROXY=10.10.1.10:3128 </code></pre> <p>On Windows:</p> <pre><code>set http_proxy=10.10.1.10:3128 set https_proxy=10.10.1.11:1080 set ftp_proxy=10.10.1.10:3128 </code></pre>
7,839,907
No more data to read from socket error
<p>We are using Oracle as the database for our Web application. The application runs well most of the time, but we get this "No more data to read from socket" error.</p> <pre><code>Caused by: java.sql.SQLRecoverableException: No more data to read from socket at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1142) at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1099) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:288) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:863) at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576) at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3620) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1869) at org.hibernate.loader.Loader.doQuery(Loader.java:718) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270) at org.hibernate.loader.Loader.doList(Loader.java:2449) ... 63 more </code></pre> <p>We use spring, hibernate and i have the following for the datasource in my applciation context file.</p> <pre><code>&lt;bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource"&gt; &lt;property name="driverClassName" value="${database.driverClassName}" /&gt; &lt;property name="url" value="${database.url}" /&gt; &lt;property name="username" value="${database.username}" /&gt; &lt;property name="password" value="${database.password}" /&gt; &lt;property name="defaultAutoCommit" value="false" /&gt; &lt;property name="initialSize" value="10" /&gt; &lt;property name="maxActive" value="30" /&gt; &lt;property name="validationQuery" value="select 1 from dual" /&gt; &lt;property name="testOnBorrow" value="true" /&gt; &lt;property name="testOnReturn" value="true" /&gt; &lt;property name="poolPreparedStatements" value="true" /&gt; &lt;property name="removeAbandoned" value="true" /&gt; &lt;property name="logAbandoned" value="true" /&gt; &lt;/bean&gt; </code></pre> <p>I am not sure whether this is because of application errors, database errors or network errors. </p> <p>We see the following on the oracle logs</p> <pre><code>Thu Oct 20 10:29:44 2011 Errors in file d:\oracle\diag\rdbms\ads\ads\trace\ads_ora_3836.trc (incident=31653): ORA-03137: TTC protocol internal error : [12333] [4] [195] [3] [] [] [] [] Incident details in: d:\oracle\diag\rdbms\ads\ads\incident\incdir_31653\ads_ora_3836_i31653.trc Thu Oct 20 10:29:45 2011 Trace dumping is performing id=[cdmp_20111020102945] Thu Oct 20 10:29:49 2011 Sweep [inc][31653]: completed Sweep [inc2][31653]: completed Thu Oct 20 10:34:20 2011 Errors in file d:\oracle\diag\rdbms\ads\ads\trace\ads_ora_860.trc (incident=31645): ORA-03137: TTC protocol internal error : [12333] [4] [195] [3] [] [] [] [] Incident details in: d:\oracle\diag\rdbms\ads\ads\incident\incdir_31645\ads_ora_860_i31645.trc Thu Oct 20 10:34:21 2011 </code></pre> <p><strong>Oracle Version : 11.2.0.1.0</strong></p>
7,844,985
13
7
null
2011-10-20 17:38:45.44 UTC
21
2022-04-11 17:38:55.327 UTC
2016-07-27 12:32:24.553 UTC
null
810,720
null
634,664
null
1
70
oracle|hibernate|spring|jdbc
406,389
<p>For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.</p> <p>You have two ways to address this:</p> <ul> <li>upgrade to <strong>11.2</strong></li> <li>set oracle parameter <code>_optim_peek_user_binds = false</code></li> </ul> <p>Of course underscore parameters should only be set if advised by oracle support</p>
4,749,650
Function that would return the data retrieved from a select query - Oracle
<p>I am trying to write a function that would return the result of a select query. I have worked with very basic functions that would return a number and a varchar2(string). But now I want to return the result of a select, which would be like 10 rows and their corresponding columns.</p> <p>How would I write the function and what would the return type be?</p> <p>An example function that I have written is:</p> <blockquote> <p>create or replace function func1 return varchar2 as begin return('hello from func1'); end func1;</p> </blockquote> <p>I am still at a basic level, so can anybody help me out with returning the result of a select query? I believe cursors are to be used, as there would be more than one row.</p>
4,749,847
3
0
null
2011-01-20 16:20:58.937 UTC
2
2016-12-28 11:22:42.233 UTC
2016-12-28 11:22:42.233 UTC
null
63,550
null
431,918
null
1
16
oracle|function|stored-procedures|plsql|return
64,556
<p>Normally, a function returns a single "thing". Normally, that is a scalar (a number, a varchar2, a record, etc) though you can return a collection. So, for example, you could return a collection (in this case a nested table) with all the EMPNO values from the EMP table</p> <pre><code>CREATE TYPE empno_tbl IS TABLE OF NUMBER; CREATE OR REPLACE FUNCTION get_empnos RETURN empno_tbl IS l_empnos empno_tbl; BEGIN SELECT empno BULK COLLECT INTO l_empnos FROM emp; RETURN l_empnos; END; </code></pre> <p>But this isn't a particularly common thing to do in a function. It would be a bit more common to have the function return a cursor rather than returning values and to let the caller handle fetching the data, i.e.</p> <pre><code>CREATE OR REPLACE FUNCTION get_empnos2 RETURN SYS_REFCURSOR IS l_rc SYS_REFCURSOR; BEGIN OPEN l_rc FOR SELECT empno FROM emp; RETURN l_rc; END; </code></pre> <p>But even that isn't particularly common in Oracle. Depending on what you're trying to accomplish, it would generally be more common to simply create a view that selected the data you were interested in and to query that view rather than calling a function or procedure.</p>
4,323,737
How to connect Django to a MySQL database over an SSL connection?
<p>I'm trying to connect Django to a MySQL database which is accessible through an SSL connection. How do I configure this?</p> <p>My first guess would be setting the 'OPTIONS' property of the database definition. However, I can't find info on what possible options to use. The option <code>'ssl': '/map/to/ca-cert.pem'</code> does not work.</p> <p>The following command seems to work:</p> <pre><code>mysql -h url.to.host -u lizard -p --ssl-ca=./ca-cert.pem </code></pre> <p>Edit: Ok I'm looking at the python-mysqldb documentation... maybe I can find the answer there.</p>
4,323,785
4
0
null
2010-12-01 11:14:27.46 UTC
10
2021-05-04 19:09:18.567 UTC
2021-05-04 19:04:47.45 UTC
null
7,487,335
null
80,500
null
1
9
mysql|django|ssl
18,926
<p>Django uses the Python <code>MySQLdb</code> library to interface with MySQL. Looking at <a href="http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects" rel="noreferrer">the MySQLdb connection documentation</a>, it looks like the <code>ssl</code> option requires a dictionary argument. So this might work:</p> <pre><code>'OPTIONS': {'ssl': {'key': '/map/to/ca-cert.pem'}} </code></pre>
14,392,146
Batch file to create Folder based on Date and Copy Files from One Location to Another Location?
<p>I want to Copy/Move files in Windows XP from Desktop(a Folder) to My Document(another Folder), which was created by same Batch File on Current Date in Format DD/MM/YYYY.</p> <p>This is working fine when .BAT File is in Desktop Folder.</p> <pre><code>@echo off set date="%date:~7,2%-%date:~4,2%-%date:~10,4%" mkdir %date% copy *.txt \%date% pause </code></pre> <p>Now what this .BAT is doing is, creating Folder 18-01-2013 on Desktop and coping all .TXT files in this Folder.</p> <p>But this is not working,</p> <pre><code>@echo off set date="%date:~7,2%-%date:~4,2%-%date:~10,4%" mkdir %USERPROFILE%\My Documents\%date% copy %USERPROFILE%\desktop\*.txt %USERPROFILE%\My Documents\%date% pause </code></pre> <p>This .BAT File is creating these folders; 1. In C Drive>Documents 2. On Desktop (and, Chandel>My, Documents>18-01-2013, Settings>Anshuman)</p> <p>Any help in this regard is highly appreciated!</p>
14,392,286
1
0
null
2013-01-18 03:58:32.57 UTC
1
2015-06-25 12:24:12.7 UTC
2013-03-19 12:53:45.537 UTC
null
1,348,709
null
692,269
null
1
4
batch-file
59,535
<p>Try putting lines that has file/folder names with spaces in quotes e.g. update this line</p> <pre><code>mkdir %USERPROFILE%\My Documents\%date% </code></pre> <p>to</p> <pre><code>mkdir "%USERPROFILE%\My Documents\%date%" </code></pre>
4,362,569
What are useful ranking algorithms for documents without links?
<p>I've looked at <a href="https://rads.stackoverflow.com/amzn/click/com/1933988665" rel="nofollow noreferrer" rel="nofollow noreferrer">Algorithms of the Intelligent Web</a> that describes (page 55) an interesting algorithm - called DocRank - for creating a <a href="http://en.wikipedia.org/wiki/PageRank" rel="nofollow noreferrer">PageRank</a> like score for business documents (i.e. documents without links like PDF, MS Word documents, etc...). In short it analyzes term frequency intersection between each document in a collection. </p> <p>Can anyone else identify interesting algorithms described elsewhere, or wants to share something novel here, to apply against these types of documents to improve search results? </p> <p>Please forgo answers involving things like click tracking or other actions <strong>NOT</strong> about analyzing the actual documents. </p>
4,364,300
4
2
null
2010-12-06 01:54:04.687 UTC
10
2012-10-18 13:49:20.9 UTC
2012-10-18 13:49:20.9 UTC
null
249,690
null
470,838
null
1
15
algorithm|search|machine-learning
4,064
<p><strong>First Technique: <em>step-wise similarity</em></strong></p> <p>I can offer one example--that i've actually tested/validated against real data. If you were to gather a number of techniques and rank them along two axes--inherent complexity or ease of implementation AND performance (resolution, or predictive accuracy), this technique would be high on the first axis, and somewhere near the middle on the second; a simple and effective technique, but which might <em>underperform</em> against state-of-the-art techniques.</p> <p>We found that <em>the combination of <strong>low-frequency keyword</strong> intersection combined with <strong>similarity among readers/viewers</strong> of a document</em>, is a fairly strong predictor of the document's content. Put another way: if two documents have the a similar set of very low-frequency terms (e.g., domain-specific terms, like 'decision manifold', etc.) and they have similar inbound traffic profiles, that combination is strongly probative of similarity of the documents.</p> <p>The relevant details: </p> <p><em>first filter</em>: <em>low-frequency terms</em>. We parsed a large set of documents to get the term frequency for each. We used this word frequency spectrum as a 'fingerprint', which is common, but we applied an inverse weighting, so that the common terms ('a', 'of', 'the') counted very little in the similarity measure, whereas the rare terms counted a lot (this is quite common, as you probably know).</p> <p>Trying to determine whether two documents were similar based on this along was problematic; for instance, two documents might share a list of rare terms relating to MMOs, and still the documents weren't similar because one is directed to playing MMOs and the other to designing them. </p> <p><em>second filter</em>: <em>readers</em>. Obviously we don't know who had read these documents, so we inferred readership from traffic sources. You can see how that helped in the example above. The inbound traffic for the MMO player site/document reflected the content, likewise for the document directed to MMO design.<br> <br/></p> <hr> <p><strong>Second Technique: <em>kernel Principal Component Analysis (kPCA)</em></strong></p> <p>kPCA is <em>unsupervised</em> technique (the class labels are removed from the data before the data is passed in). At the heart of the technique is just an eigenvector-based decomposition of a matrix (in this case a covariance matrix). This technique handles non-linearity via the kernel trick, which just maps the data to a higher dimensional features space then performs the PCA in that space. In Python/NumPy/SciPy it is about 25 lines of code.</p> <p>The data is collected from very simple text parsing of literary works--in particular, most of the published works of these four authors: Shakespeare, Jane Austen, Jack London, Milton. (I believe, though i'm not certain, that normal college students take course in which they are assigned to read novels by these authors.) </p> <p>This dataset is widely used in ML and is available from a number of places on the Web.</p> <p>So these works were divided into 872 pieces (corresponding roughly to chapters in novels); in other words, about 220 different substantial pieces of text for each of the four authors. </p> <p>Next a word-frequency scan was performed on the combined corpus text, and the <em>70 most common</em> words were selected for the study, the remainder of the results of the frequency scan were discarded. </p> <p>Those 70 words were:</p> <pre><code>[ 'a', 'all', 'also', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'been', 'but', 'by', 'can', 'do', 'down', 'even', 'every', 'for', 'from', 'had', 'has', 'have', 'her', 'his', 'if', 'in', 'into', 'is', 'it', 'its', 'may', 'more', 'must', 'my', 'no', 'not', 'now', 'of', 'on', 'one', 'only', 'or', 'our', 'should', 'so', 'some', 'such', 'than', 'that', 'the', 'their', 'then', 'there', 'things', 'this', 'to', 'up', 'upon', 'was', 'were', 'what', 'when', 'which', 'who', 'will', 'with', 'would', 'your', 'BookID', 'Author' ] </code></pre> <p>These became the field (column) names. Finally, one data row corresponding to the 872 texts was prepared (from the truncated word frequency scan). Here's one of those data points:</p> <pre><code>[ 46, 12, 0, 3, 66, 9, 4, 16, 13, 13, 4, 8, 8, 1, 0, 1, 5, 0, 21, 12, 16, 3, 6, 62, 3, 3, 30, 3, 9, 14, 1, 2, 6, 5, 0, 10, 16, 2, 54, 7, 8, 1, 7, 0, 4, 7, 1, 3, 3, 17, 67, 6, 2, 5, 1, 4, 47, 2, 3, 40, 11, 7, 5, 6, 8, 4, 9, 1, 0, 1 ] </code></pre> <p>In sum, the data is comprised of 70 dimensions (each dimension is the frequency or total count of a particular word, in a given text of one of these four authors. </p> <p>Again, although this data is primarily used for supervised classification (the class labels are there for a reason), the technique i used was <strong><em>unsupervised</em></strong>--put another way, i never showed the class labels to the algorithm. The kPCA algorithm has absolutely no idea what those four different clusters (shown in the plot below) correspond to nor how each differs from the other--the algorithm did not even know how many groups (classes) that data was comprised of. I just gave it the data, and it partitioned it very neatly into four distinct groups based on an inherent ordering.</p> <p>The results:<img src="https://i.stack.imgur.com/ru3PE.png" alt="alt text"></p> <p>Again, the algorithm i used here is kPCA. Using Python, NumPy, and Matplotlib, the script that produced these results is about 80 lines of code--for the IO, data processing, applying kPCA, and plotting the result. </p> <p>Not much, but too much for an SO post. In any event, anyone who wants this code can get it from my repo. At the same time, there is also a complete, well-documented kPCA algorithm coded in python + numpy in each of these python packages (all available from <a href="http://mloss.org/software/" rel="noreferrer">mloss.org</a>): <strong><em>shogun</em></strong> ('A Large Scale Machine Learning Toolbox'), '<strong><em>sdpy</em></strong> (a set of modules directed to computer vision and machine learning), and <strong><em>mlpy</em></strong> ('Machine Learning in PYthon').</p>
4,646,779
Embedding googleVis charts into a web site
<p>Reading from the <a href="http://code.google.com/p/google-motion-charts-with-r/" rel="noreferrer">googleVis</a> package <a href="http://google-motion-charts-with-r.googlecode.com/svn/trunk/inst/doc/googleVis.pdf" rel="noreferrer">vignette</a>: <em>"With the googleVis package users can create easily web pages with interactive charts based on R data frames and display them either via the R.rsp package <strong>or within their own sites</strong>"</em>. Following the instructions I was able to see the sample charts, using the <a href="http://finzi.psych.upenn.edu/R/library/googleVis/html/gvisMethods.html" rel="noreferrer">plot</a> method for gvis objects. This method by default creates a rsp-file in the rsp/myAnalysis folder of the googleVis package, using the type and chart id information of the object and displays the output using the local web server of the R.rsp package (port 8074 by default).</p> <p>Could anybody help me (or provide some link) on the procedure someone has to follow in order to embed such charts into an existing web site (e.g. a joomla site)?</p>
4,649,753
5
5
null
2011-01-10 12:24:45.623 UTC
21
2016-02-23 22:16:21.817 UTC
null
null
null
null
170,792
null
1
24
r|google-visualization
12,080
<p>Obviously I think that this is too verbose for @gd047, but I put a kind of tutorial since it maybe helpful for other readers who want to use googleVis on their own website.</p> <p>install googleVis from CRAN</p> <pre><code>install.packages('googleVis') </code></pre> <p>pay attention to the messages.</p> <p>then, create gvis object:</p> <pre><code>library(googleVis) M &lt;- gvisMotionChart(Fruits, "Fruit", "Year") </code></pre> <p>you can find the contents of M by:</p> <pre><code>&gt; M </code></pre> <p>and you can find the plot on your browser:</p> <pre><code>&gt; plot(M) </code></pre> <p>then, what is necessary to generate the chart is M$html$chart:</p> <pre><code>&gt; M$html$chart [1] "&lt;!-- MotionChart ... omitted... \"&gt;\n&lt;/div&gt;\n" </code></pre> <p>save it to a file:</p> <pre><code>&gt; cat(M$html$chart, file="tmp.html") </code></pre> <p>if you open the "tmp.html" as a file (i.e, address says files:///***/tmp.html), then security warning may occur. What you need is to access the html via http://.</p> <p>So if you can edit any web page where &lt;script&gt; tag is available (e.g., blogger), you can use it by simply copy and paste the contents of tmp.html, like this:</p> <p><a href="http://takahashik.blogspot.com/2011/01/googlevis-example.html" rel="noreferrer">http://takahashik.blogspot.com/2011/01/googlevis-example.html</a></p> <p>here is the famous "iris" version of example:</p> <p><a href="http://takahashik.blogspot.com/2011/01/googlevis-example-for-data-iris_10.html" rel="noreferrer">http://takahashik.blogspot.com/2011/01/googlevis-example-for-data-iris_10.html</a></p> <p>Otherwise, if you have a web server, you can use it by uploading the tmp.html on the server.</p>
4,474,086
Display QImage with QtGui
<p>I am new to Qt, and I am trying to create a simple GUI Application that displays an image once a button has been clicked on.</p> <p>I can read the image in a <code>QImage</code> object, but is there any simple way to call a Qt function that takes the <code>QImage</code> as an input, and displays it?</p>
4,474,570
5
0
null
2010-12-17 19:31:36.023 UTC
21
2018-02-26 14:19:56.797 UTC
2013-12-18 17:47:09.593 UTC
null
2,682,142
null
546,444
null
1
50
c++|qt|qimage|qtgui
133,607
<p>Thanks All, I found how to do it, which is the same as Dave and Sergey:</p> <p>I am using QT Creator:</p> <p>In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")</p> <p>In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:</p> <pre><code>void MainWindow::on_pushButton_clicked() { QImage imageObject; imageObject.load(imagePath); ui-&gt;myLabel-&gt;setPixmap(QPixmap::fromImage(imageObject)); //OR use the other way by setting the Pixmap directly QPixmap pixmapObject(imagePath"); ui-&gt;myLabel2-&gt;setPixmap(pixmapObject); } </code></pre>
4,408,937
Font size auto adjust to fit
<p>I'm trying to do what the title says. I've seen that <code>font-size</code> can be a percentage. So my guess was that <code>font-size: 100%;</code> would do it, but no.</p> <p>Here is an example: <a href="http://jsfiddle.net/xVB3t/">http://jsfiddle.net/xVB3t/</a></p> <p>Can I get some help please?</p> <p>(If is necesary to do it programatically with js there is no problem)</p>
4,409,008
7
6
null
2010-12-10 12:46:34.787 UTC
5
2018-06-22 07:19:29.127 UTC
2010-12-10 12:59:27.89 UTC
null
128,165
null
310,276
null
1
22
javascript|html|css|fonts|font-size
88,136
<p>This question might help you out but I warn you though this solves it through jQuery:</p> <p><a href="https://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container">Auto-size dynamic text to fill fixed size container</a></p> <p>Good luck.</p> <p>The OP of that question made a plugin, <a href="http://plugins.jquery.com/project/TextFill" rel="nofollow noreferrer">here is the link to it</a> (&amp; <a href="http://plugins.jquery.com/files/jQuery-TextFill-0.1.zip" rel="nofollow noreferrer">download</a>)</p> <p>BTW I'm suggesting jQuery because as <a href="https://stackoverflow.com/questions/4408937/font-size-auto-adjust-to-fit/4408978#4408978">Gaby pointed out</a> this can't be done though CSS only and you said you were willing to use js...</p>
14,578,530
How to open/display documents(.pdf, .doc) without external app?
<p>I want to create a program, that open documents without external app. I need this, because i want to scroll the document with the phones orientation(Pitch and Roll). I create a button on the bottom of the screen, and when i hold down the button, i can scroll the document too. If i release the button, i can't scroll it. So, if i open the document with external app, my button disappears, and the sensorManager works neither.</p> <p>Have someone any idea to solve this problem. Or have someone any idea, how to scroll the document, opened in an external app, with my phones orientation?</p> <p>(Sorry for my English)</p> <p>This is my manifest:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.orientationscrolling" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.example.orientationscrolling.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>This is my Layout:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="bottom" android:orientation="vertical" &gt; &lt;Button android:id="@+id/mybutt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:text="Scroll!!" android:layout_gravity="right"/&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>This is my Code:</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); button = (Button) findViewById( R.id.mybutt ); String pdf = "http://www.pc-hardware.hu/PDF/konfig.pdf"; String doc="&lt;iframe src='http://docs.google.com/gview?embedded=true&amp;url=http://www.pc-hardware.hu/PDF/konfig.pdf' width='100%' height='100%' style='border: none;'&gt;&lt;/iframe&gt;"; webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setPluginsEnabled(true); webView.getSettings().setAllowFileAccess(true); webView.loadData( doc , "text/html", "UTF-8"); } </code></pre>
14,578,661
4
3
null
2013-01-29 08:29:01.833 UTC
22
2018-11-25 02:34:31.79 UTC
2013-01-29 10:01:38.543 UTC
null
1,638,031
null
1,638,031
null
1
23
android|pdf|external
103,946
<p>I think you should use custom library for getting that done .See <a href="https://stackoverflow.com/a/11153195/1450401">this</a> and <a href="http://www.androidpdf.mobi/download" rel="noreferrer">this</a></p> <p>But there is a way for displaying PDF with out calling another application</p> <p>This is a way for showing PDF in android app that is embedding the PDF document to <strong>android webview</strong> using support from <code>http://docs.google.com/viewer</code></p> <p>pseudo</p> <pre><code>String doc="&lt;iframe src='http://docs.google.com/viewer?url=+location to your PDF File+' width='100%' height='100%' style='border: none;'&gt;&lt;/iframe&gt;"; </code></pre> <p>a sample is is shown below</p> <pre><code> String doc="&lt;iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&amp;embedded=true' width='100%' height='100%' style='border: none;'&gt;&lt;/iframe&gt;"; </code></pre> <p>Code</p> <pre><code> WebView wv = (WebView)findViewById(R.id.webView); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setPluginsEnabled(true); wv.getSettings().setAllowFileAccess(true); wv.loadUrl(doc); //wv.loadData( doc, "text/html", "UTF-8"); </code></pre> <p>and in manifest provide</p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET"/&gt; </code></pre> <p>See <a href="https://stackoverflow.com/a/11718742/1450401"><strong>this</strong></a></p> <p>Caution : I am not aware of compatibility issues with various android versions </p> <p>In this approach the drawback is you need internet connectivity . But i think it satisfy your need</p> <p>EDIT Try this as src for iframe</p> <pre><code>src="http://docs.google.com/gview?embedded=true&amp;url=http://www.pc-hardware.hu/PDF/konfig.pdf" </code></pre> <p>try <code>wv.loadData( doc , "text/html", "UTF-8");</code> . Both works for me</p> <p><img src="https://i.stack.imgur.com/KHvGO.png" alt="enter image description here"><img src="https://i.stack.imgur.com/HrQh6.png" alt="enter image description here"></p>
14,791,444
Adding list items with SharePoint 2013 REST API
<p>I'm trying to add a new item in a existing list using SharePoint 2013 with the REST API.</p> <p>There is pretty good documentation for this here: <a href="http://msdn.microsoft.com/en-us/library/jj164022%28office.15%29.aspx#ListItems" rel="noreferrer">http://msdn.microsoft.com/en-us/library/jj164022(office.15).aspx#ListItems</a></p> <p>The list I am trying to add items to is called "Resources", so I do the following http POST operation to add the new item:</p> <pre><code>POST https://&lt;site&gt;/apps/reserve/_api/lists/getbytitle('Resources')/items X-RequestDigest: &lt;digest_key&gt; Content-Type: application/json;odata=verbose { "__metadata": {"type": "SP.Data.ResourcesListItem"}, "Title": "New Title", "Description": "New Description", "Location": "Sunnyvale" } </code></pre> <p>But I get back the following error:</p> <pre><code>A type named 'SP.Data.ResourcesListItem' could not be resolved by the model. When a model is available, each type name must resolve to a valid type. </code></pre> <p>So I presume I don't have the correct name for the name for the resource. In the documentation, it says:</p> <pre><code>To do this operation, you must know the ListItemEntityTypeFullName property of the list and pass that as the value of type in the HTTP request body. </code></pre> <p>But I don't know how to get the ListItemEntityTypeFullName for my list, and the documentation does not seem explain how-- I copied the pattern from the doc (SP.Data.&lt; LIST_NAME >ListItem") but I guess that is not right.</p> <p>How can I find the name for my list?</p>
14,791,940
1
0
null
2013-02-09 20:49:40.517 UTC
8
2015-07-02 17:46:29.203 UTC
null
null
null
null
1,195,996
null
1
24
rest|sharepoint|sharepoint-api|sharepoint-2013
30,648
<p>You can get the name as follows:</p> <pre><code>GET https://&lt;site&gt;/apps/reserve/_api/lists/getbytitle('Resources')?$select=ListItemEntityTypeFullName </code></pre> <p>The list name will be under: content -> m:properties -> d:ListItemEntityTypeFullName</p>
14,427,596
Convert an int to bool with Json.Net
<p>I am calling a webservice and the returned data for a bool field is either 0 or 1 however with my model I am using a System.Bool</p> <p>With Json.Net is it possible to cast the 0/1 into a bool for my model?</p> <p>Currently I am getting an error</p> <blockquote> <p>Newtonsoft.Json.JsonSerializationException: Error converting value "0" to type 'System.Boolean'</p> </blockquote> <p>Any help would be awesome!!</p>
14,428,145
1
0
null
2013-01-20 18:13:18.85 UTC
11
2013-01-20 19:07:33.7 UTC
null
null
null
null
293,545
null
1
50
c#-4.0|json.net|deserialization
20,460
<p>Ended up creating a converter</p> <pre><code> public class BoolConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((bool)value) ? 1 : 0); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value.ToString() == "1"; } public override bool CanConvert(Type objectType) { return objectType == typeof(bool); } } </code></pre> <p>Then within my model</p> <pre><code> [JsonConverter(typeof(BoolConverter))] public bool active { get; set; } </code></pre> <p>hope this helps someone else</p>
14,709,802
Exit after res.send() in Express.js
<p>I have a fairly simple Express.js app with a login component that I'd like to exit early if login fails. I'm seeing indications that the app isn't doing that and I haven't found a definitive answer that indicates whether calling <code>res.send()</code> halts any further processing. Here's my code as it stands now:</p> <pre><code>client.login( username, password, function( auth, client ) { if( !auth ) { res.send( 401 ); } // DO OTHER STUFF IF AUTH IS SUCCESSFUL } </code></pre> <p>If I read the source code correctly, it <em>should</em> end the request (aborting further processing), but I'm new to node, so I'm not quite ready to trust what I think I'm reading. To boil it down, I guess I'm mostly looking for a definitive answer from a more trustworthy source that my own interpretation of unfamiliar source code. If <code>send()</code> doesn't abort processing, what's the right way to do that?</p>
14,711,160
7
2
null
2013-02-05 14:26:22.837 UTC
14
2021-05-08 23:11:20.737 UTC
null
null
null
null
1,665
null
1
61
node.js|express
57,118
<p>If you are using express as your framework, you should call next() instead.</p> <p>Each handler in express receives 3 parameters (unlinke 2 for basic http) which are <code>req</code>, <code>res</code> and <code>next</code></p> <p><code>next</code> is a function that when called with no arguments will trigger the next handler in the middleware chain.</p> <p>If <code>next</code> is called with an arguments, this argument will be interpreter as an error, regardless of the type of that argument.</p> <p>Its signature is <code>next([error])</code>. When next is called with an error, then instead of calling the next handler in the middleware chain, it calls the error handler. You should handle the 401 response code in that error handler. See <a href="http://expressjs.com/guide/error-handling.html" rel="noreferrer">this</a> for more info on error handling in Express</p> <p>EDIT: As <strong>@Baptiste Costa</strong> commented, simply calling <code>next()</code> will <strong>not</strong> cease the current execution but it will call on the next middleware. It is good practice to use <code>return next()</code> instead to prevent Node from throwing errors further on (such as the <code>can't set headers after they are sent</code> - error). This includes the above suggestion of error throwing which is common:</p> <pre><code>return next(new Error([error])); </code></pre>
38,764,435
Difference between func() and (*this).func() in C++
<p>I am working on someone else code in C++, and I found a weird call to a certain function <code>func()</code>. Here is an example:</p> <pre><code>if(condition) func(); else (*this).func(); </code></pre> <p>What is the difference between <code>func()</code> and <code>(*this).func()</code>?</p> <p>What are the cases where the call to <code>func()</code> and <code>(*this).func()</code> will execute different code?</p> <p>In my case, <code>func()</code> is not a macro. It is a virtual function in the base class, with an implementation in both base and derived class, and no free <code>func()</code>. The <code>if</code> is located in a method in the base class.</p>
38,764,576
4
11
null
2016-08-04 10:09:47.887 UTC
6
2016-08-04 16:13:48.73 UTC
2016-08-04 14:19:43.823 UTC
null
2,682,991
null
2,682,991
null
1
59
c++|dispatch
8,012
<p>There actually is a difference, but in a very non-trivial context. Consider this code:</p> <pre><code>void func ( ) { std::cout &lt;&lt; "Free function" &lt;&lt; std::endl; } template &lt;typename Derived&gt; struct test : Derived { void f ( ) { func(); // 1 this-&gt;func(); // 2 } }; struct derived { void func ( ) { std::cout &lt;&lt; "Method" &lt;&lt; std::endl; } }; test&lt;derived&gt; t; </code></pre> <p>Now, if we call <code>t.f()</code>, the first line of <code>test::f</code> will invoke the free function <code>func</code>, while the second line will call <code>derived::func</code>.</p>
2,824,088
Passing constructor arguments when using StructureMap
<p>I'm using StructureMap for my DI. Imagine I have a class that takes 1 argument like:</p> <pre><code>public class ProductProvider : IProductProvider { public ProductProvider(string connectionString) { .... } } </code></pre> <p>I need to specify the "connectionString <strong>at run-time</strong> when I get an instance of IProductProvider.</p> <p>I have configured StructureMap as follows: </p> <pre><code>ForRequestedType&lt;IProductProvider&gt;.TheDefault.Is.OfConcreteType&lt;ProductProvider&gt;(). WithCtorArgument("connectionString"); </code></pre> <p>However, I don't want to call EqualTo("something...") method here as I need some facility to dynamically specify this value at run-time.</p> <p>My question is: how can I get an instance of IProductProvider by using ObjectFactory? </p> <p>Currently, I have something like:</p> <pre><code>ObjectFactory.GetInstance&lt;IProductProvider&gt;(); </code></pre> <p>But as you know, this doesn't work... </p> <p>Any advice would be greatly appreciated. </p>
2,824,144
3
0
null
2010-05-13 02:17:16.497 UTC
4
2019-12-19 13:16:20.403 UTC
null
null
null
null
292,120
null
1
48
dependency-injection|constructor|structuremap
21,406
<p>I found the answer myself! Here is the solution:</p> <pre><code>ObjectFactory.With("connectionString").EqualTo(someValueAtRunTime).GetInstance&lt;IProductProvider&gt;(); </code></pre> <p>Hope this helps others who have come across the same issue. </p>
2,715,164
How can I decode the boost library naming?
<p>I tried to find out that <code>gd</code> means in boost library name and I only found two other people looking for the same thing.</p> <p>I suppose it should be a place where this is clearly documented and I would like to find it.</p> <ul> <li><code>mt</code> - multitheaded, get it with <code>bjam threading=multi</code></li> <li><code>s</code> - <code>bjam runtime-link=static</code></li> <li><code>g</code> - using debug versions of the standard and runtime support libraries. <strong>what bjam switch???</strong></li> <li><code>d</code> - debug <code>bjam variant=debug</code></li> </ul> <h1>Update</h1> <p>How do I control what <code>bjam</code> switches controls the above variants? In fact the only one that I wasn't able to identify is the <code>g</code>.</p>
2,715,214
3
2
null
2010-04-26 16:40:12.763 UTC
22
2016-11-28 13:44:26.363 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
99,834
null
1
58
c++|boost|boost-build|bjam
26,033
<p>See <a href="http://www.boost.org/doc/libs/1_42_0/more/getting_started/windows.html#library-naming" rel="noreferrer">Boost getting started windows</a> section 6.3 naming and <a href="http://www.boost.org/doc/libs/1_42_0/more/getting_started/unix-variants.html#library-naming" rel="noreferrer">section 6.1 on Unix naming</a></p> <p>The ones that deal with -mt and d are</p> <pre><code>-mt Threading tag: indicates that the library was built with multithreading support enabled. Libraries built without multithreading support can be identified by the absence of `-mt`. -d ABI tag: encodes details that affect the library's interoperability with other compiled code. For each such feature, a single letter is added to the tag as listed in this table: Key Use this library when (Boost.Build option) s linking statically to the C++ standard library and compiler runtime support libraries. (runtime-link=static) g using debug versions of the standard and runtime support libraries. (runtime-debugging=on) y using a special debug build of Python. (python-debugging=on) d building a debug version of your code. (variant=debug) p using the STLPort standard library rather than the default one supplied with your compiler. (stdlib=stlport) </code></pre>
3,012,822
What's the difference between Console.WriteLine() vs Debug.WriteLine()?
<p>What's the difference between <strong><code>Console</code></strong><code>.WriteLine()</code> vs <strong><code>Debug</code></strong><code>.WriteLine()</code>?</p>
3,012,838
3
0
null
2010-06-10 08:34:22.457 UTC
17
2020-10-09 12:01:26.24 UTC
2016-05-09 11:40:49.687 UTC
null
33,311
null
182,153
null
1
104
.net|vb.net
55,251
<p><a href="http://msdn.microsoft.com/en-us/library/system.console.writeline(VS.71).aspx" rel="noreferrer">Console.WriteLine</a> writes to the standard output stream, either in debug or release. <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.writeline.aspx" rel="noreferrer">Debug.WriteLine</a> writes to the trace listeners in the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.listeners.aspx" rel="noreferrer">Listeners</a> collection, but only when running in debug. When the application is compiled in the release configuration, the Debug elements will not be compiled into the code.</p> <p>As <code>Debug.WriteLine</code> writes to all the trace listeners in the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.listeners.aspx" rel="noreferrer">Listeners</a> collection, it is possible that this could be output in more than one place (Visual Studio output window, Console, Log file, third-party application which registers a listener (I believe <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="noreferrer">DebugView</a> does this), etc.).</p>
2,923,139
Prompt User before browser close?
<p>We have an administrative portal that our teachers constantly forget to download their latest PDF instructions before logging out and/or closing the browser window. I have looked around but can't find what I'm looking for. </p> <p>I want to accomplish the following goals:</p> <h2>Goal 1</h2> <p>Before a user can close the browser window, they are prompted "Did you remember to download your form?" with two options, yes/no. If yes, close, if no, return to page.</p> <h2>Goal 2</h2> <p>Before a user can click the 'logout' button, they are prompted with the same as above.</p> <p>My first pass at the very basic code (which does not work for browser close) is:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;script type="text/javascript"&gt; function init() { if (window.addEventListener) { window.addEventListener("beforeunload", unloadMess, false); } else if (window.onbeforeunload) { window.onbeforeunload = unloadMess; }; } function unloadMess() { var User_Message = "[Your user message here]" return User_Message; } &lt;/script&gt; &lt;/head&gt; &lt;body onload="init();"&gt; hello this is my site &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>EDIT - NEW ISSUES</h2> <p>The solution provided below works but also has its own issues:</p> <p>When user clicks the link to actually download the forms, the page thinks they are trying to leave and in turn present an error message to them! Also - I would like for one event or another to occur but not necessarily both. I.e. they hit 'logout' button and they are presented with the OnClick event, THEN the browser prompt. Any ideas?</p>
2,923,258
4
3
null
2010-05-27 16:55:29.053 UTC
8
2018-12-04 14:50:00.937 UTC
2015-12-10 13:59:48.577 UTC
null
3,885,376
null
337,690
null
1
19
javascript|popup|browser-close
41,910
<p><strong>Update 2017</strong></p> <p>All modern browsers do not support custom messages any longer.</p> <pre><code>window.onbeforeunload = function(evt) { return true; } </code></pre> <p>This one for closing the tab:</p> <pre><code>window.onbeforeunload = function(evt) { var message = 'Did you remember to download your form?'; if (typeof evt == 'undefined') { evt = window.event; } if (evt) { evt.returnValue = message; } return message; } </code></pre> <p>and use <code>onClick</code> event for logout button:</p> <pre><code>onClick="return confirm('Did you remember to download your form?');" </code></pre>
3,030,099
Pragma in define macro
<p>Is there some way to embed pragma statement in macro with other statements?</p> <p>I am trying to achieve something like:</p> <pre><code>#define DEFINE_DELETE_OBJECT(type) \ void delete_ ## type_(int handle); \ void delete_ ## type(int handle); \ #pragma weak delete_ ## type_ = delete_ ## type </code></pre> <p>I am okay with boost solutions (save for wave) if one exists.</p>
3,030,312
4
4
null
2010-06-12 21:09:18.783 UTC
30
2016-02-25 10:36:45.993 UTC
2016-02-25 10:36:45.993 UTC
null
4,370,109
null
206,328
null
1
117
c-preprocessor|pragma|stringification
49,276
<p>If you're using c99 or c++0x there is the pragma operator, used as</p> <pre><code>_Pragma("argument") </code></pre> <p>which is equivalent to</p> <pre><code>#pragma argument </code></pre> <p>except it can be used in macros (see section 6.10.9 of the c99 standard, or 16.9 of the c++0x final committee draft)</p> <p>For example,</p> <pre><code>#define STRINGIFY(a) #a #define DEFINE_DELETE_OBJECT(type) \ void delete_ ## type ## _(int handle); \ void delete_ ## type(int handle); \ _Pragma( STRINGIFY( weak delete_ ## type ## _ = delete_ ## type) ) DEFINE_DELETE_OBJECT(foo); </code></pre> <p>when put into <code>gcc -E</code> gives</p> <pre><code>void delete_foo_(int handle); void delete_foo(int handle); #pragma weak delete_foo_ = delete_foo ; </code></pre>
40,579,330
Minify CSS with Node-sass
<p>I'm using SCSS in my NodeJS project and have my script working to turn all my seperate SCSS files into a single CSS file using the following command</p> <pre><code>node-sass -w public/css/scss/style.scss public/css/style.css </code></pre> <p>My only issue is that I also want the CSS file to be minified. Is this possible with Node-sass? The docs say there is an option for 'compact' but it doesn't seem to work when I try</p> <pre><code>node-sass -w compact public/css/scss/style.scss public/css/style.css </code></pre> <p>Thank you in advance for any help.</p>
40,592,964
4
0
null
2016-11-13 22:06:41.517 UTC
7
2021-11-29 20:02:59.513 UTC
null
null
null
null
5,422,775
null
1
60
css|node.js|minify|node-sass
39,117
<p>In the <a href="https://github.com/sass/node-sass" rel="noreferrer">node-sass documentation</a> says you have to use <code>--output-style</code>, and it could be <code>nested | expanded | compact | compressed</code>. To minify use <code>compressed</code></p> <p>For example:</p> <pre><code>node-sass -w public/css/scss/style.scss public/css/style.css --output-style compressed </code></pre> <p>will minify the CSS.</p>
40,711,101
Max JSON column length in MySQL
<p>What's the max number of characters I can store in a JSON column in MySQL? I don't see this mentioned in the MySQL manual.</p>
40,711,346
2
1
null
2016-11-21 00:28:25.887 UTC
5
2021-12-24 17:48:40.413 UTC
2017-11-03 03:06:13.557 UTC
null
3,791,314
null
3,791,314
null
1
43
mysql|json
42,878
<p>Here's a demo of what @JorgeLondoño is talking about.</p> <p>Set the server's max allowed packet size:</p> <pre><code>mysql&gt; set global max_allowed_packet=1024*1024*1024; </code></pre> <p>Exit and open the mysql client again, this time setting the client max packet size to match:</p> <pre><code>$ mysql --max-allowed-packet=$((1024*1024*1024)) </code></pre> <p>Create a test table with a JSON column and fill it with the longest JSON document you can:</p> <pre><code>mysql&gt; create table test.jtest ( j json ); mysql&gt; insert into test.jtest set j = concat('[', repeat('&quot;word&quot;,', 100000000), '&quot;word&quot;]'); Query OK, 1 row affected (1 min 49.67 sec) mysql&gt; select length(j) from test.jtest; +-----------+ | length(j) | +-----------+ | 800000008 | +-----------+ </code></pre> <p>This shows that I was able to create a single JSON document with 100 million elements, and MySQL stores this in approximately 800MB.</p> <p>I didn't try a longer document. I assume it maxes out at 1 GB, which is the largest value you can set for max_allowed_packet.</p>
50,044,618
How to increment counter for a specific list item in Flutter?
<p>Like in my sample image, below, I want to increment or decrement quantity upon button click for single list item. If I increase the counter in setState(), its incrementing in every list item. I need help with this, especially in handling specific list item in Flutter.</p> <p>![Sample Image][2]<br> Any help is appreciated.<br> Thanks in advance. </p> <p><a href="https://i.stack.imgur.com/QV1Jp.png" rel="noreferrer">Got the List Item</a> Thanks for the help,</p> <p><img src="https://i.stack.imgur.com/QV1Jp.png" alt="Sample Image"> </p>
50,046,789
5
1
null
2018-04-26 13:44:27.607 UTC
2
2022-08-27 21:03:50.497 UTC
2018-04-27 10:09:46.033 UTC
null
6,130,226
null
6,130,226
null
1
10
dart|flutter
42,187
<p>All you need to do is to refactor your widgets the proper way. You can refactor your <code>Card</code>s / items into their separate <code>StatefulWdiget</code> such that each increment/decrement affect only a specific item and not the whole list.</p> <p>Check this example : </p> <p><a href="https://i.stack.imgur.com/nfa3I.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/nfa3I.gif" alt="enter image description here"></a></p> <pre><code>class FlutterExample extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( body: new ListView( children: new List.generate(5, (i)=&gt;new ListTileItem( title: "Item#$i", )), ), ); } } class ListTileItem extends StatefulWidget { String title; ListTileItem({this.title}); @override _ListTileItemState createState() =&gt; new _ListTileItemState(); } class _ListTileItemState extends State&lt;ListTileItem&gt; { int _itemCount = 0; @override Widget build(BuildContext context) { return new ListTile( title: new Text(widget.title), trailing: new Row( children: &lt;Widget&gt;[ _itemCount!=0? new IconButton(icon: new Icon(Icons.remove),onPressed: ()=&gt;setState(()=&gt;_itemCount--),):new Container(), new Text(_itemCount.toString()), new IconButton(icon: new Icon(Icons.add),onPressed: ()=&gt;setState(()=&gt;_itemCount++)) ], ), ); } } </code></pre>
52,310,599
What does minikube docker-env mean?
<p>In the Kubernetes <a href="https://kubernetes.io/docs/tutorials/hello-minikube/#create-your-node-js-application" rel="noreferrer">minikube tutorial</a> there is this command to use Minikube Docker daemon :</p> <pre><code>$ eval $(minikube docker-env) </code></pre> <p>What exactly does this command do, that is, what exactly does <code>minikube docker-env</code> mean? </p>
52,310,892
4
0
null
2018-09-13 09:22:48.113 UTC
9
2022-01-03 22:33:47.76 UTC
2018-09-13 09:42:37.75 UTC
null
396,567
null
6,205,738
null
1
84
docker|kubernetes|dockerfile|minikube
43,307
<p>The command <code>minikube docker-env</code> returns a set of Bash environment variable exports to configure your local environment to re-use the Docker daemon inside the Minikube instance.</p> <p>Passing this output through <code>eval</code> causes bash to evaluate these exports and put them into effect.</p> <p>You can review the specific commands which will be executed in your shell by omitting the evaluation step and running <code>minikube docker-env</code> directly. However, <em>this will not perform the configuration</em> – the output needs to be evaluated for that.</p> <hr /> <p>This is a workflow optimization intended to improve your experience with building and running Docker images which you can run inside the minikube environment. It is not mandatory that you re-use minikube's Docker daemon to use minikube effectively, but doing so will significantly improve the speed of your code-build-test cycle.</p> <p>In a normal workflow, you would have a separate Docker registry on your host machine to that in minikube, which necessitates the following process to build and run a Docker image inside minikube:</p> <ol> <li>Build the Docker image on the host machine.</li> <li>Re-tag the built image in your local machine's image registry with a remote registry or that of the minikube instance.</li> <li>Push the image to the remote registry or minikube.</li> <li>(If using a remote registry) Configure minikube with the appropriate permissions to pull images from the registry.</li> <li>Set up your deployment in minikube to use the image.</li> </ol> <p>By re-using the Docker registry inside Minikube, this becomes:</p> <ol> <li>Build the Docker image using Minikube's Docker instance. This pushes the image to Minikube's Docker registry.</li> <li>Set up your deployment in minikube to use the image.</li> </ol> <hr /> <p>More details of the purpose can be found in the <a href="https://minikube.sigs.k8s.io/docs/handbook/pushing/#1-pushing-directly-to-the-in-cluster-docker-daemon-docker-env" rel="noreferrer">minikube docs</a>.</p>
52,169,219
Get Branch name in gitlab ci
<p>In my Gitlab CI, I have a stage that triggers another stage by api call trigger and I want to pass the current branch name as parameter to the other project holding the trigger. I used the <code>CI_COMMIT_REF_NAME</code> for this, it seemed to work, but now that I call the stage only when merging the branch to master, the <code>CI_COMMIT_REF_NAME</code> always says &quot;master&quot;.</p> <p>In the <a href="https://docs.gitlab.com/ee/ci/variables/#variables" rel="noreferrer">documentation</a> it says &quot;The branch or tag name for which project is built&quot;, do I understand it correctly that it kind of holds the target branch of my working branch?</p> <p>I tried to get the current branch in gitlab ci with <code>git symbolic-ref HEAD | sed 's!refs\/heads\/!!'</code> as well but it was empty.</p> <p>Is <code>CI_COMMIT_REF_NAME</code> the variable I am looking for and something is going wrong or do I need something else?</p> <p>Thanks in advance.</p>
52,176,899
2
0
null
2018-09-04 15:04:21.75 UTC
6
2022-03-09 14:20:45.257 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
6,834,956
null
1
39
gitlab|gitlab-ci
53,076
<p>I'm not sure what you mean by “a stage that triggers another stage by api call trigger”. But, generally speaking, GitLab CI jobs are part of a CI pipeline, and CI pipelines are created for a branch or tag.</p> <p>The <code>CI_COMMIT_REF_NAME</code> variable contains the name of the branch or tag that the pipeline was created for.</p> <p>The <code>CI_MERGE_REQUEST_TARGET_BRANCH_NAME</code> is &quot;The target branch name of the merge request.&quot;</p> <p>from <a href="https://docs.gitlab.com/ee/ci/variables/predefined_variables.html" rel="noreferrer">GitLab Predefined Variables reference</a></p>
22,607,755
What does "open!" mean?
<p>I'm looking at an OCaml source file that begins with the following instruction:</p> <pre><code>open! MiscParser </code></pre> <p>I understand that <code>open MiscParser</code> means "open the <code>MiscParser</code> module", but I don't know what the exclamation mark means.</p>
22,608,364
2
0
null
2014-03-24 11:11:53.733 UTC
5
2021-07-28 04:11:03.79 UTC
2021-07-28 04:11:03.79 UTC
null
7,943,564
null
1,308,444
null
1
35
syntax|module|ocaml
3,917
<p>It's to avoid triggering warnings if the <code>open</code> shadows an exisiting identifier. See the <a href="https://ocaml.org/manual/overridingopen.html" rel="nofollow noreferrer">manual</a>.</p>
40,503,107
Put a button inside the text box
<p>I'm trying to design a form, with a button inside a text-box. I want that button to be inside the text-box. This is how I tried:</p> <pre><code>&lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-sm-6&quot;&gt; &lt;div class=&quot;form-group required&quot;&gt; &lt;label for=&quot;PickList_Options&quot; class=&quot;col-sm-4 control-label&quot;&gt;Options&lt;/label&gt; &lt;div class=&quot;col-sm-4 buttonwrapper&quot;&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;PickList_Options&quot; name=&quot;PickList_Options&quot; value='' /&gt; &lt;button&gt;GO&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-sm-6&quot;&gt; &lt;div class=&quot;result&quot; id=&quot;mydiv&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>my css:</p> <pre><code>.buttonwrapper { display:inline-block; } input, button { background-color:transparent; border:0; } </code></pre> <p>But, the problem is, the Go button is placed below the text-box. What should I do to place it inside the text-box?</p> <p><a href="https://i.stack.imgur.com/xFeCu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xFeCu.png" alt="Simple Image" /></a></p> <p>I want that &quot;Go&quot; button to be inside the text-box.</p>
40,503,280
9
2
null
2016-11-09 09:02:58.63 UTC
4
2022-02-08 12:52:53.293 UTC
2020-08-17 13:55:04.507 UTC
null
10,859,114
null
6,269,804
null
1
13
html|css
45,146
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.buttonwrapper { display: inline-block; } input{ background-color: transparent; border: 2px solid black; } button { margin-left: -50%; border: none; background-color: transparent; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="row"&gt; &lt;div class="col-sm-6"&gt; &lt;div class="form-group required"&gt; &lt;label for="PickList_Options" class="col-sm-4 control-label"&gt;Options&lt;/label&gt; &lt;div class="col-sm-4 buttonwrapper"&gt; &lt;input type="text" class="form-control" id="PickList_Options" name="PickList_Options" value='' /&gt; &lt;button&gt;GO&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-6"&gt; &lt;div class="result" id="mydiv"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3,168,401
JSON formatting (Sending JSON via jQuery AJAX post to Java/Wicket server)
<p>I'm using jQuery to post JSON to a Java server, but I think my JSON must be wrong. Here's an example of my data and how I'm sending it:</p> <pre><code>var lookup = { 'name': name, 'description': description, 'items': [{ 'name': itemName, 'value': itemValue }] } $.ajax({ type: 'post', data: lookup, dataType: 'json' }); </code></pre> <p>I'm using Wicket's AbstractAjaxBehavior to receive the data and would like to get a single JSON string that I can parse. When I get a Map of the parameters passed, the keyset looks like this:</p> <pre><code>items[0][name], description, name, items[0][value], </code></pre> <p>Obviously I can easily get the values for name and description, but the key for my array of items is messed up. I'm sure it's something simple, but I seem to keep running around the solution. Any suggestions? Thanks!</p>
3,168,431
1
1
null
2010-07-02 18:56:36.033 UTC
9
2010-07-12 17:49:07.697 UTC
2010-07-12 17:49:07.697 UTC
null
197,560
null
197,560
null
1
15
java|jquery|ajax|json|wicket
45,704
<p>You have to use JSON.stringify:</p> <pre><code>$.ajax({ type: 'post', data: JSON.stringify(lookup), contentType: 'application/json', dataType: 'json' }); </code></pre> <p>You should also specify 'application/json' as the contentType. By default jQuery will serialize objects with application/x-www-form-urlencoded (even if the contentType is application/json'). So you have to do it manually.</p> <p>EDIT: Key for 'post' should be type, not method.</p>
21,305,865
Golang separating items with comma in template
<p>I am trying to display a list of comma separated values, and don't want to display a comma after the last item (or the only item if there is only one).</p> <p>My code so far:</p> <pre><code>Equipment: {{$equipment := .Equipment}} {{ range $index, $element := .Equipment}} {{$element.Name}} {{if lt $index ((len $equipment) -1)}} , {{end}} {{end}} </code></pre> <p>The current output: <code>Equipment: Mat , Dumbbell ,</code> How do I get rid of the trailing comma</p>
21,305,933
5
0
null
2014-01-23 10:45:25.447 UTC
7
2022-05-20 08:49:29.35 UTC
null
null
null
null
818,951
null
1
49
go
25,967
<p>A nice trick you can use is:</p> <pre><code>Equipment: {{$equipment := .Equipment}} {{ range $index, $element := .Equipment}} {{if $index}},{{end}} {{$element.Name}} {{end}} </code></pre> <p>This works because the first index is <code>0</code>, which returns <code>false</code> in the <code>if</code> statement. So this code returns <code>false</code> for the first index, and then places a comma in front of each following iteration. This results in a comma separated list without a leading or trailing comma.</p>
37,228,851
Delete certificate from Computer Store
<p>I am having difficulty getting powershell to delete a certificate that was accidentally installed to all our Windows 7 machines to the Computer Store.</p> <p>As an example I have included a screen shot of where the certificate is installed (this is not the actual certificate). We have a few hundred machines so we would like to do this as automatic as possible.</p> <p>If someone could provide a way to delete the certificate by Serial Number or Thumbprint that would be great.</p> <p><a href="https://i.stack.imgur.com/hBwM6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hBwM6.png" alt="enter image description here"></a></p>
37,229,338
1
0
null
2016-05-14 16:01:32.85 UTC
2
2020-08-10 15:06:41.223 UTC
2019-06-19 22:51:47.903 UTC
null
41,956
null
911,148
null
1
42
powershell|certificate
70,754
<p>You can use the <code>Cert:</code>-PSDrive with <code>Get-ChildItem</code> and <code>Remove-Item</code>. Ex:</p> <pre><code>#Delete by thumbprint Get-ChildItem Cert:\LocalMachine\My\D20159B7772E33A6A33E436C938C6FE764367396 | Remove-Item #Delete by subject/serialnumber/issuer/whatever Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -match 'Frode F' } | Remove-Item </code></pre>
58,976,251
Checking text appears inside an element using react testing library
<p>I'm writing some tests for a React app using <a href="https://testing-library.com/" rel="noreferrer">Testing Library</a>. I want to check that some text appears, but I need to check it appears in a particular place because I know it already appears somewhere else.</p> <p>The <a href="https://testing-library.com/docs/dom-testing-library/api-queries#bytext" rel="noreferrer">Testing Library documentation for queries</a> says that the <code>getByText</code> query takes a <code>container</code> parameter, which I guessed lets you search within that container. I tried doing this, with the <code>container</code> and <code>text</code> parameters in the order specified in the docs:</p> <pre><code>const container = getByTestId('my-test-id'); expect(getByText(container, 'some text')).toBeTruthy(); </code></pre> <p>and I get an error: <code>matcher.test is not a function</code>.</p> <p>If I put the params the other way round:</p> <pre><code>const container = getByTestId('my-test-id'); expect(getByText('some text', container)).toBeTruthy(); </code></pre> <p>I get a different error: <code>Found multiple elements with the text: some text</code></p> <p>Which means it's not searching inside the specified container.</p> <p>I think I'm not understanding how <code>getByText</code> works. What am I doing wrong?</p>
59,027,935
3
0
null
2019-11-21 13:32:00.003 UTC
7
2022-09-19 17:37:19.08 UTC
2021-02-18 22:08:14.433 UTC
null
2,418,295
null
1,107,844
null
1
53
javascript|reactjs|react-testing-library
73,300
<p>Better to use <a href="https://testing-library.com/docs/dom-testing-library/api-within/" rel="noreferrer"><code>within</code></a> for this sort of things:</p> <pre><code>render(&lt;MyComponent /&gt;) const { getByText } = within(screen.getByTestId('my-test-id')) expect(getByText('some text')).toBeInTheDocument() </code></pre>
24,503,494
Run cURL command every 5 seconds
<p>This is the command that I want to run -</p> <pre><code>curl --request POST --data-binary @payload.txt --header "carriots.apiKey:XXXXXXXXXXXXXXXXXXXX" --verbose http://api.carriots.com/streams </code></pre> <p>This basically sends a data stream to a server.</p> <p>I want to run this command every 5 seconds. How do I achieve this?</p>
24,503,528
2
0
null
2014-07-01 06:10:55.437 UTC
4
2022-05-10 21:25:52.8 UTC
2014-07-01 06:22:55.68 UTC
null
1,495,539
null
2,492,264
null
1
39
linux|curl|libcurl
56,636
<p>You can run in while loop. </p> <pre><code>while sleep 5; do cmd; done </code></pre> <p><strong>Edit:</strong></p> <p>If you don't want to use <code>while..loop</code>. you can use <a href="http://linux.die.net/man/1/watch">watch</a> command.</p> <pre><code>watch -n 5 cmd </code></pre>