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
27,756,510
How to set the color of matching braces in VS 2015?
<p>I wish to have a more emphasis on the brackets match, so I set it to yellow and bold in the options. However, when I place my cursor next to a curly brace (also parenthesis, brackets etc.) it still only flags with washed-out gray...</p> <p>How do I set the color to my liking?</p> <p>The setting I've made was: </p> <p>Tools → Options → Environment → Font and Colors<br> - Brace Matching (Highlight)<br> - Brace Matching (Rectangle)</p>
29,988,532
4
3
null
2015-01-03 15:40:42.267 UTC
5
2019-10-13 10:15:47.667 UTC
2016-10-10 06:12:16.393 UTC
null
107,625
null
1,525,840
null
1
38
visual-studio-2015
16,669
<p>I just tried it with the RC release we shipped this week and also seeing the problem. Will follow up with the team and get this fixed. I'll post updates here. Thanks for sharing the problem!</p> <p>Update: I confirmed with the team that this is a known issue and is on the list to get fixed. </p>
538,643
How good is Subversion at storing lots of binary files?
<p>I'm looking for a place to put a few GB of documents (mostly <code>.doc</code> and <code>.xls</code>). My team already has a Subversion server set up for managing the documents we create, so I'd prefer to use that if possible. How well will Subversion handle all this extra stuff? Most of it is legacy information and will only ever have one version, but it is possible that a few documents could be updated.</p> <p>I've been warned that SVN isn't particularly lots-of-big-binary-files-friendly. I'm wary of trying it to see whether it works since they'll always be in the repository history even if I later delete them.</p> <p>Any alternatives? We'll need the ability to comment on and/or tag documents, but we can use a Delicious-like service combined with the URLs for the documents in SVN (or similar).</p> <p><strong>Later</strong> I'm not so worried about diffs on the binaries since, as stated above, they won't change much. I'm OK with a slight hassle if they do -- it's no worse than SharePoint.</p>
538,658
7
0
2009-02-11 20:34:41.297 UTC
2009-02-11 20:34:41.313 UTC
9
2014-11-19 15:31:49.157 UTC
2009-02-20 19:00:05.153 UTC
Paul
23,356
Gaius
1,190
null
1
39
svn|documentation|content-management-system
50,373
<p>There's a difference between lots of big binary files, and a big number of binary files. </p> <p>In my experience SVN is fine with individual binary files of several hundred megabytes. The only problems I've seen begin to occur with individual files of around a gigabyte or so. Operations fail for mysterious and unknown reasons, possibly SVN failing to handle network related problems.</p> <p>I am not aware of any SVN problems related to the number of binary files, beyond their lack of merge-ability and the fact that binary files often can't be efficiently stored as deltas (SVN can use deltas).</p> <p>So;</p> <ul> <li>1000 1MB files = fine.</li> <li>100 10MB files = fine</li> <li>10 100MB files = fine</li> <li>1 >1000MB file = not a good idea.</li> </ul> <p>I would hope the size of your documents fits into one of the fine categories :)</p>
711,672
C# HTMLDecode without System.Web possible?
<p>I know there are different methods in the System.Web namespace for decoding html entities (such as "%20" for space). I'm building a Winforms application however, but needs to deal with html encoded strings. Basically I have the iTunes Library XML file and need to decode the URLs in there to check the files.</p> <p>Is this possible without the System.Web namespace?</p>
8,714,006
7
4
null
2009-04-02 21:20:13.627 UTC
10
2016-08-29 14:51:15.313 UTC
2012-09-06 21:34:40.947 UTC
null
246,246
null
66,841
null
1
47
c#|html-encode
32,245
<blockquote> <p>Developers who need to use System.Web.HttpUtility in their client apps and had to reference System.Web.dll and therefore target NET4 full (System.Web.dll is in Full) , can now target the NET4 Client Profile by using the new System.Net.WebUtility class which is in System.dll (System.dll is in NET4 Client Profile). System.Net.WebUtility includes HtmlEncode and HtmlDecode. Url encoding can be accomplished using the System.Uri class (also in System.dll).</p> </blockquote> <p>From <a href="http://blogs.msdn.com/b/jgoldb/archive/2010/04/12/what-s-new-in-net-framework-4-client-profile-rtm.aspx">http://blogs.msdn.com/b/jgoldb/archive/2010/04/12/what-s-new-in-net-framework-4-client-profile-rtm.aspx</a></p>
329,628
How does "Find Nearest Locations" work?
<p>Nowadays most of the Restaurants and other businesses have a "<a href="http://www.fedex.com//Dropoff/start" rel="nofollow noreferrer">Find Locations</a>" functionality on their websites which lists nearest locations for a given address/Zip. How is this implemented? Matching the zipcode against the DB is a simple no-brainer way to do but may not always work, for example there may be a branch closer to the given location but could be in a different zip. One approach that comes to my mind is to convert the given zip-code/address into map co-ordinates and list any branches falling into a pre-defined radius. I welcome your thoughts on how this would've been implemented.If possible provide more detailed implementation details like any web-services used etc.,</p>
329,665
8
0
null
2008-11-30 23:51:37.853 UTC
9
2014-04-24 08:10:49.403 UTC
2014-04-24 08:10:49.403 UTC
null
404,335
bluegene
15,474
null
1
9
algorithm|mapping
9,463
<p>A lot of geospatial frameworks will help you out with this. In the geospatial world, a zip code is just a "polygon", which is just an area on a map which defines clear boundaries (not a polygon in the math sense). In SQL 2008 spatial, for example, you can create a new polygon based on your original polygon. So you can dynamically create a polygon that is your zip code extended by a certain distance at every point. It takes the funky shape of the zip code into account. With an address, It’s easy, because you just create a polygon, which is a circle around the one point. You can then do queries give you all points within the new polygon that you created in either method.</p> <p>A lot of these sites are basically just doing this. They give you all points within a 5 mile extended polygon, and then maybe a 10 mile extended polygon, and so on and so forth. They are not actually calculating distance. Most ma stuff on the web is not sophisticated at all.</p> <p>You can see some basic examples <a href="http://johanneskebeck.spaces.live.com/blog/cns!42E1F70205EC8A96!3541.entry" rel="noreferrer">here</a> to get the general idea of what I'm talking about.</p>
880,524
Why is it not good to have a primary key on a join table?
<p>I was watching a screencast where the author said it is not good to have a primary key on a join table but didn't explain why. </p> <p>The join table in the example had two columns defined in a Rails migration and the author added an index to each of the columns but no primary key. </p> <p>Why is it not good to have a primary key in this example?</p> <pre><code>create_table :categories_posts, :id =&gt; false do |t| t.column :category_id, :integer, :null =&gt; false t.column :post_id, :integer, :null =&gt; false end add_index :categories_posts, :category_id add_index :categories_posts, :post_id </code></pre> <p>EDIT: As I mentioned to Cletus, I can understand the potential usefulness of an auto number field as a primary key even for a join table. However in the example I listed above, the author explicitly avoids creating an auto number field with the syntax ":id => false" in the "create table" statement. Normally Rails would automatically add an auto-number id field to a table created in a migration like this and this would become the primary key. But for this join table, the author specifically prevented it. I wasn't sure why he decided to follow this approach.</p>
880,648
8
3
null
2009-05-19 01:02:26.437 UTC
13
2013-01-24 13:05:51.86 UTC
2009-05-19 01:24:09.593 UTC
null
101,050
null
101,050
null
1
27
ruby-on-rails|database|migration|primary-key|junction-table
13,019
<p>Some notes:</p> <ol> <li>The combination of category_id and post_id is unique in of itself, so an additional ID column is redundant and wasteful</li> <li>The phrase "not good to have a primary key" is incorrect in the screencast. You still have a Primary Key -- it is just made up of the two columns (e.g. CREATE TABLE foo( cid, pid, PRIMARY KEY( cid, pid ) ). For people who are used to tacking on ID values everywhere this may seem odd but in relational theory it is quite correct and natural; the screencast author would better have said it is "not good to have an implicit integer attribute called 'ID' as the primary key".</li> <li>It is redundant to have the extra column because you will place a unique index on the combination of category_id and post_id anyway to ensure no duplicate rows are inserted</li> <li>Finally, although common nomenclature is to call it a "composite key" this is also redundant. The term "key" in relational theory is actually the set of zero or more attributes that uniquely identify the row, so it is fine to say that the primary key is category_id, post_id</li> <li>Place the MOST SELECTIVE column FIRST in the primary key declaration. A discussion of the construction of b(+/*) trees is out of the scope of this answer ( for some lower-level discussion see: <a href="http://www.akadia.com/services/ora_index_selectivity.html" rel="noreferrer">http://www.akadia.com/services/ora_index_selectivity.html</a> ) but in your case, you'd probably want it on post_id, category_id since post_id will show up less often in the table and thus make the index more useful. Of course, since the table is so small and the index will be, essentially, the data rows, this is not very important. It would be in broader cases where the table is wider.</li> </ol>
34,065
How to read a value from the Windows registry
<p>Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:</p> <ol> <li>Safely determine that such a key exists.</li> <li>Programmatically (i.e. with code) get its value.</li> </ol> <p>I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. </p> <p>Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.</p>
35,717
8
0
null
2008-08-29 06:40:21.333 UTC
33
2020-03-04 13:56:31.637 UTC
2009-06-21 22:05:37.593 UTC
Rob Cooper
811
nolandda
3,551
null
1
101
c++|windows|winapi|registry
169,224
<p><strong>Here is some pseudo-code to retrieve the following:</strong></p> <ol> <li>If a registry key exists</li> <li>What the default value is for that registry key</li> <li>What a string value is</li> <li>What a DWORD value is</li> </ol> <p><strong>Example code:</strong></p> <p>Include the library dependency: Advapi32.lib</p> <pre><code>HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &amp;hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); LONG GetDWORDRegKey(HKEY hKey, const std::wstring &amp;strValueName, DWORD &amp;nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast&lt;LPBYTE&gt;(&amp;nResult), &amp;dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &amp;strValueName, bool &amp;bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &amp;strValueName, std::wstring &amp;strValue, const std::wstring &amp;strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &amp;dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; } </code></pre>
965,150
Jquery: ajax post and encoding
<p>I am unable to understand why I can't get a correct ISO-8859-1 charstet from the server answer. Being this a work on legacy code, i hardly could change charset encoding on the pages.</p> <p>I make use of the JQuery call</p> <pre><code>$.post("server-side-code", {t:ctext, i:ioff, sid:sessionid}, function(data, status) { $('#chk').append(data); }); </code></pre> <p>posting a textarea value created using javascript:</p> <pre><code>&lt;form accept-charset='ISO-8859-1' method='post'&gt; &lt;textarea cols='40' rows='8' id='commento'&gt;&lt;/textarea&gt;&lt;br&gt; &lt;input type='button' value='invia' id='submit'&gt;&lt;/form&gt; </code></pre> <p>The server side script processing the request declares at its very top:</p> <pre><code>text/html; charset=ISO-8859-1 </code></pre> <p>so, honestly, I can't figure out what else I should declare, in terms of encoding. This notwithstanding, the accented characters "àèéìòù" bounce back as: "à èéìòù" when placing the server answer in an HTML element</p> <p>The source is saved as ascii. Tryng to do this to have rudimentary Html encoding on the variable to be posted does not solve:</p> <pre><code>ctext = escapeHTML(ctext); function escapeHTML (str) { var div = document.createElement('div'); var text = document.createTextNode(str); div.appendChild(text); return div.innerHTML; }; </code></pre> <p>Some idea?</p> <p>Thanks!</p>
1,229,012
9
1
null
2009-06-08 14:24:14.387 UTC
2
2013-07-25 05:12:57.53 UTC
2012-11-19 14:48:06.62 UTC
null
431,359
null
47,506
null
1
9
jquery
62,140
<p>I have a better solution now. Both post and get works PERFECTLY. I'm working over tomcat who by default handle ISO 8859 stuff.</p> <p>Web page properties:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; </code></pre> <p>charset of the webpage inside the head.</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&gt; </code></pre> <p>Now, all my parameteres are escaped with escape function, I provided this solution before.</p> <pre><code>(function($) {$.fn.escape = function() { return escape(this.val());};})(jQuery); </code></pre> <p>Now, when sending the ajax request I set the contentType to this:</p> <pre><code>contentType : "application/x-www-form-urlencoded; charset=iso-8859-1" </code></pre> <p>And finally , when receiving the parameters at the servlet or any receiver I get a decoded parameter using this.</p> <pre><code> public String getHttpParameter(String name) throws Exception { String value = this.getHttpRequest().getParameter(name); return value == null || value.isEmpty() ? value : URLDecoder.decode(value,"ISO-8859-1"); } </code></pre> <p>POST and GET works perfectly in IE 7 and 8 , SAFARI, CHROME and FIREFOX.</p>
1,236,053
Why do Google and Twitter use table layout?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/796504/does-it-make-sense-to-use-the-table-tag-on-a-modern-website">Does it make sense to use the &lt;table&gt; tag on a &ldquo;modern&rdquo; website?</a> </p> </blockquote> <p>Everywhere I go I see <strong>don't use table layout, it's evil</strong>, even Google says that, so why one of the most visited websites, Google and Twitter, use it for their homepage?</p> <p>I don't think it is any kind of mistake, or any other stupid problem. </p> <p>The only reason I can think of is, that they want the page to look similar even if client doesn't support CSS, like with Lynx.</p> <p>So why everyone say it is so bad, if the biggest websites on the internet use it.</p> <p>In my opinion, there are some cases, like those mentioned above, where it is vitaly important to have the same look everywhere, than it is OK to use tables.</p> <p><strong>edit</strong>: The same question goes about html elements like <code>&lt;center&gt;</code>, or formatting text with attribute <strong>align</strong> and other "html attributes and elements used to substitute CSS functionality"</p>
1,236,066
9
7
null
2009-08-05 22:14:24.737 UTC
12
2016-10-05 18:47:41.027 UTC
2017-05-23 11:45:49.073 UTC
null
-1
null
72,583
null
1
40
html|css|layout|xhtml|html-table
6,714
<p>Page load time is king for these guys, and bandwidth usage is extreme.</p> <p>I'd have to say they use tables for raw data speed, since they are serving up so much bandwidth every day.</p> <p>Also, notice that they use inline styles in the page header to reduce the number of HTTP requests to help speed up page load time.</p>
24,515
"bad words" filter
<p>Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="noreferrer">found this</a> one, and it's a start, but nothing more.</p> <p>Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) </p> <p>The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. </p> <p>Thanks for any help.</p>
24,615
9
8
null
2008-08-23 19:17:34.353 UTC
42
2018-04-05 20:30:44.263 UTC
2010-10-22 15:38:03.223 UTC
null
730
ila
1,178
null
1
52
list|dictionary|profanity
102,192
<p>I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught.</p> <pre><code>&lt;?php /** * @author [email protected] **/ if($_GET['act'] == 'do') { $pattern['a'] = '/[a]/'; $replace['a'] = '[a A @]'; $pattern['b'] = '/[b]/'; $replace['b'] = '[b B I3 l3 i3]'; $pattern['c'] = '/[c]/'; $replace['c'] = '(?:[c C (]|[k K])'; $pattern['d'] = '/[d]/'; $replace['d'] = '[d D]'; $pattern['e'] = '/[e]/'; $replace['e'] = '[e E 3]'; $pattern['f'] = '/[f]/'; $replace['f'] = '(?:[f F]|[ph pH Ph PH])'; $pattern['g'] = '/[g]/'; $replace['g'] = '[g G 6]'; $pattern['h'] = '/[h]/'; $replace['h'] = '[h H]'; $pattern['i'] = '/[i]/'; $replace['i'] = '[i I l ! 1]'; $pattern['j'] = '/[j]/'; $replace['j'] = '[j J]'; $pattern['k'] = '/[k]/'; $replace['k'] = '(?:[c C (]|[k K])'; $pattern['l'] = '/[l]/'; $replace['l'] = '[l L 1 ! i]'; $pattern['m'] = '/[m]/'; $replace['m'] = '[m M]'; $pattern['n'] = '/[n]/'; $replace['n'] = '[n N]'; $pattern['o'] = '/[o]/'; $replace['o'] = '[o O 0]'; $pattern['p'] = '/[p]/'; $replace['p'] = '[p P]'; $pattern['q'] = '/[q]/'; $replace['q'] = '[q Q 9]'; $pattern['r'] = '/[r]/'; $replace['r'] = '[r R]'; $pattern['s'] = '/[s]/'; $replace['s'] = '[s S $ 5]'; $pattern['t'] = '/[t]/'; $replace['t'] = '[t T 7]'; $pattern['u'] = '/[u]/'; $replace['u'] = '[u U v V]'; $pattern['v'] = '/[v]/'; $replace['v'] = '[v V u U]'; $pattern['w'] = '/[w]/'; $replace['w'] = '[w W vv VV]'; $pattern['x'] = '/[x]/'; $replace['x'] = '[x X]'; $pattern['y'] = '/[y]/'; $replace['y'] = '[y Y]'; $pattern['z'] = '/[z]/'; $replace['z'] = '[z Z 2]'; $word = str_split(strtolower($_POST['word'])); $i=0; while($i &lt; count($word)) { if(!is_numeric($word[$i])) { if($word[$i] != ' ' || count($word[$i]) &lt; '1') { $word[$i] = preg_replace($pattern[$word[$i]], $replace[$word[$i]], $word[$i]); } } $i++; } //$word = "/" . implode('', $word) . "/"; echo implode('', $word); } if($_GET['act'] == 'list') { $link = mysql_connect('localhost', 'username', 'password', '1'); mysql_select_db('peoples'); $sql = "SELECT word FROM filters"; $result = mysql_query($sql, $link); $i=0; while($i &lt; mysql_num_rows($result)) { echo mysql_result($result, $i, 'word') . "&lt;br /&gt;"; $i++; } echo '&lt;hr&gt;'; } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;RegEx Generator&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action='badword.php?act=do' method='post'&gt; Word: &lt;input type='text' name='word' /&gt;&lt;br /&gt; &lt;input type='submit' value='Generate' /&gt; &lt;/form&gt; &lt;a href="badword.php?act=list"&gt;List Words&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
794,198
How do I check if a given value is a generic list?
<pre><code>public bool IsList(object value) { Type type = value.GetType(); // Check if type is a generic list of any type } </code></pre> <p>What's the best way to check if the given object is a list, or can be cast to a list?</p>
794,219
9
1
null
2009-04-27 16:07:09.557 UTC
13
2022-01-17 12:18:53.973 UTC
null
null
null
Jason
null
null
1
106
c#|reflection|list|generics
94,343
<pre><code>using System.Collections; if(value is IList &amp;&amp; value.GetType().IsGenericType) { } </code></pre>
308,213
Explaining computational complexity theory
<p>Assuming some background in mathematics, how would you give a general overview of computational complexity theory to the naive?</p> <p>I am looking for an explanation of the P = NP question. What is P? What is NP? What is a NP-Hard?</p> <p>Sometimes Wikipedia is written as if the reader already understands all concepts involved.</p>
309,507
10
1
null
2008-11-21 08:46:45.887 UTC
28
2017-12-10 00:14:18.297 UTC
2017-12-10 00:14:18.297 UTC
Mario Orteg&#243;n
1,711,796
Mario Orteg&#243;n
2,309
null
1
23
algorithm|theory|complexity-theory
6,195
<p>Hoooo, doctoral comp flashback. Okay, here goes.</p> <p>We start with the idea of a decision problem, a problem for which an algorithm can always answer "yes" or "no." We also need the idea of two models of computer (Turing machine, really): deterministic and non-deterministic. A deterministic computer is the regular computer we always thinking of; a non-deterministic computer is one that is just like we're used to except that is has unlimited parallelism, so that any time you come to a branch, you spawn a new "process" and examine both sides. Like Yogi Berra said, when you come to a fork in the road, you should take it.</p> <p>A decision problem is in P if there is a known polynomial-time algorithm to get that answer. A decision problem is in NP if there is a known polynomial-time algorithm for a non-deterministic machine to get the answer.</p> <p>Problems known to be in P are trivially in NP --- the nondeterministic machine just never troubles itself to fork another process, and acts just like a deterministic one. There are problems that are known to be neither in P nor NP; a simple example is to enumerate all the bit vectors of length n. No matter what, that takes 2<sup>n</sup> steps. </p> <p>(Strictly, a decision problem is in NP if a nodeterministic machine can arrive at an answer in poly-time, and a deterministic machine can <em>verify</em> that the solution is correct in poly time.)</p> <p>But there are some problems which are known to be in NP for which no poly-time deterministic algorithm is known; in other words, we know they're in NP, but don't know if they're in P. The traditional example is the decision-problem version of the Traveling Salesman Problem (decision-TSP): given the cities and distances, is there a route that covers all the cities, returning to the starting point, in less than <em>x</em> distance? It's easy in a nondeterministic machine, because every time the nondeterministic traveling salesman comes to a fork in the road, he takes it: his clones head on to the next city they haven't visited, and at the end they compare notes and see if any of the clones took less than <em>x</em> distance. </p> <p>(Then, the exponentially many clones get to fight it out for which ones must be killed.)</p> <p>It's not known whether decision-TSP is in P: there's no known poly-time solution, but there's no proof such a solution doesn't exist.</p> <p>Now, one more concept: given decision problems P and Q, if an algorithm can transform a solution for P into a solution for Q in polynomial time, it's said that Q is <em>poly-time reducible</em> (or just reducible) to P.</p> <p>A problem is NP-complete if you can prove that (1) it's in NP, and (2) show that it's poly-time reducible to a problem already known to be NP-complete. (The hard part of that was provie the <em>first</em> example of an NP-complete problem: that was done by Steve Cook in <a href="http://en.wikipedia.org/wiki/Cook%27s_theorem" rel="noreferrer">Cook's Theorem</a>.)</p> <p>So really, what it says is that if anyone ever finds a poly-time solution to one NP-complete problem, they've automatically got one for <em>all</em> the NP-complete problems; that will also mean that P=NP.</p> <p>A problem is NP-hard if and only if it's "at least as" hard as an NP-complete problem. The more conventional Traveling Salesman Problem of finding the shortest route is NP-hard, not strictly NP-complete.</p>
1,280,369
jQuery Set Selected Option Using Next
<p>How can I, using jQuery, set the "next" item of an already selected item as "selected."</p> <p>For example, if I have:</p> <pre><code>&lt;select&gt; &lt;option value="1" &gt;Number 1&lt;/option&gt; &lt;option value="2" selected="selected"&gt;Number 2&lt;/option&gt; &lt;option value="3" &gt;Number 3&lt;/option&gt; &lt;option value="4" &gt;Number 4&lt;/option&gt; &lt;/select&gt; </code></pre> <p>We can see that "Number 2" is selected, and using jQuery, I'd like to set "Number 3" as selected, and remove the selected "attribute" from "Number 2". I'm assuming I need to use the <em>next</em> selector, but I'm not quite sure how to implement.</p>
1,280,383
11
1
null
2009-08-14 21:42:20.117 UTC
9
2015-09-07 05:01:18.227 UTC
2015-05-04 13:56:21.563 UTC
null
2,040,375
Dodinas
null
null
1
42
jquery|html-select
155,523
<pre><code>$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected'); </code></pre> <p>Check out working code here <a href="http://jsbin.com/ipewe/edit" rel="noreferrer">http://jsbin.com/ipewe/edit</a></p>
955,030
Remove CSS from a Div using JQuery
<p>I'm new to JQuery. In my App I have the following:</p> <pre><code>$("#displayPanel div").live("click", function(){ $(this).css({'background-color' : 'pink', 'font-weight' : 'bolder'}); }); </code></pre> <p>When I click on a Div, the color of that Div is changed. Within that Click function I have some functionalities to do. After all that I want to remove the applied Css from the Div. How could I do it in JQuery?</p>
955,044
13
1
null
2009-06-05 09:34:07.313 UTC
30
2014-07-22 10:47:43.567 UTC
2009-06-05 09:50:36 UTC
null
83,667
null
79,980
null
1
170
jquery|css
443,221
<p>Put your CSS properties into a class, then do something like this:</p> <pre><code>$("#displayPanel div").live("click", function(){ $(this).addClass('someClass'); }); </code></pre> <p>Then where your 'other functionalities' are do something like:</p> <pre><code>$("#myButton").click(function(){ $("#displayPanel div").removeClass('someClass'); }); </code></pre>
1,221,833
Pipe output and capture exit status in Bash
<p>I want to execute a long running command in Bash, and both capture its exit status, and <a href="http://en.wikipedia.org/wiki/Tee_(command)" rel="noreferrer">tee</a> its output.</p> <p>So I do this:</p> <pre><code>command | tee out.txt ST=$? </code></pre> <p>The problem is that the variable ST captures the exit status of <code>tee</code> and not of command. How can I solve this?</p> <p>Note that command is long running and redirecting the output to a file to view it later is not a good solution for me.</p>
1,221,870
15
2
null
2009-08-03 11:31:52.45 UTC
112
2019-03-01 11:19:12 UTC
2018-08-27 04:09:51.37 UTC
null
6,862,601
null
63,051
null
1
492
bash|shell|error-handling|pipe
194,147
<p>There is an internal Bash variable called <code>$PIPESTATUS</code>; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.</p> <pre><code>&lt;command&gt; | tee out.txt ; test ${PIPESTATUS[0]} -eq 0 </code></pre> <p>Or another alternative which also works with other shells (like zsh) would be to enable pipefail:</p> <pre><code>set -o pipefail ... </code></pre> <p>The first option does <em>not</em> work with <code>zsh</code> due to a little bit different syntax.</p>
121,631
Inner join vs Where
<p>Is there a difference in performance (in oracle) between</p> <pre><code>Select * from Table1 T1 Inner Join Table2 T2 On T1.ID = T2.ID </code></pre> <p>And</p> <pre><code>Select * from Table1 T1, Table2 T2 Where T1.ID = T2.ID </code></pre> <p>?</p>
354,834
19
6
null
2008-09-23 15:13:28.04 UTC
64
2020-05-14 22:28:35.75 UTC
2009-06-03 22:00:11.817 UTC
mwigdahl
16,587
Juan Manuel
1,782
null
1
289
sql|performance|oracle
134,848
<p>No! The same execution plan, look at these two tables:</p> <pre><code>CREATE TABLE table1 ( id INT, name VARCHAR(20) ); CREATE TABLE table2 ( id INT, name VARCHAR(20) ); </code></pre> <p>The execution plan for the query using the inner join:</p> <pre><code>-- with inner join EXPLAIN PLAN FOR SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id; SELECT * FROM TABLE (DBMS_XPLAN.DISPLAY); -- 0 select statement -- 1 hash join (access("T1"."ID"="T2"."ID")) -- 2 table access full table1 -- 3 table access full table2 </code></pre> <p>And the execution plan for the query using a WHERE clause.</p> <pre><code>-- with where clause EXPLAIN PLAN FOR SELECT * FROM table1 t1, table2 t2 WHERE t1.id = t2.id; SELECT * FROM TABLE (DBMS_XPLAN.DISPLAY); -- 0 select statement -- 1 hash join (access("T1"."ID"="T2"."ID")) -- 2 table access full table1 -- 3 table access full table2 </code></pre>
6,515,018
Error with Compass polling on windows 7
<p>I am attempting to work locally on a PHP application which I cloned from the Git repository my partner and I use.</p> <p>He uses a Mac, and until now I have been working on the app in a virtual Ubuntu Linux environment. Both environments have been able to use Compass polling with the same file structure and files.</p> <p>On Windows 7, I run Compass commands from Cygwin, and this is the command I use to have Compass poll from the root directory of the app (C:/wamp/www/application):</p> <p><code>compass watch --trace src/Application/ApplicationBundle/Resources/compass/</code></p> <p>When I then make a change to a .scss file, I receive the following error:</p> <p><code>ArgumentError on line 716 of /usr/lib/ruby/1.8/pathname.rb: different prefix: "/ /cygdrivecwampwwwlimelightsrclimelightlimelightbundleresourcescompasssrcpartials _object.scss" and "/cygdrive/c/wamp/www/limelight/src/limelight/limelightbundle/ resources/compass/src" /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/path.rb:81:in 'split_path' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/path.rb:69:in 'run_callback' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/path.rb:55:in 'callback_action' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/path.rb:35:in 'update' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/state/directory.rb:39:in 'modified' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/state/directory.rb:37:in 'each' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/state/directory.rb:37:in 'modified' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/state/directory.rb:18:in 'refresh' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/backends/polling.rb:17:in 'run' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/backends/polling.rb:17:in 'each' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/backends/polling.rb:17:in 'run' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/backends/polling.rb:15:in 'loop' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/backends/polling.rb:15:in 'run' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm/monitor.rb:26:in 'run' /usr/lib/ruby/gems/1.8/gems/fssm-0.2.7/lib/fssm.rb:20:in 'monitor' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/lib/compass/commands/watch_project.rb:86:in 'perform' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/lib/compass/commands/base.rb:18:in 'execute' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/lib/compass/commands/project_base.rb:19:in 'execute' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/lib/compass/exec/sub_command_ui.rb:43:in 'perform!' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/lib/compass/exec/sub_command_ui.rb:15:in 'run!' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/bin/compass:25 /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/bin/compass:39:in 'call' /usr/lib/ruby/gems/1.8/gems/compass-0.11.1/bin/compass:39 /usr/bin/compass:19:in 'load' /usr/bin/compass:19</code></p> <p>All I've been able to find through searching is that it may have something to do with the fact that Windows capitalizes its drive names, although the lack of slashes in the returned path makes me think the problem may be elsewhere.</p> <p>Does anyone know why I might receive this error in Windows, but not other platforms?</p> <p>NOTE: I have found a <a href="http://robhoward.id.au/2011/01/compass-sass-on-windows/" rel="noreferrer">work-around</a> involving installing ruby (and compass) through Windows' command prompt rather than Cygwin, and that should work fine for now. Still, if anyone has ideas, I'm still curious as to what the problem could be.</p>
6,552,159
5
1
null
2011-06-29 02:01:34.817 UTC
9
2014-04-02 23:19:13.677 UTC
2011-07-26 15:18:32.567 UTC
null
93,848
null
820,218
null
1
9
ruby|windows-7|cygwin|compass-sass
3,942
<p>According to <a href="https://github.com/ttilley/fssm/commit/a394304b66008872f7fcacfffcd2cdad0e6a2f9e#lib/fssm/pathname.rb-P20">this commit</a>, this is a problem caused by a compass dependency called FSSM. It is used to monitor file changes in compass. A workaround is described in <a href="https://github.com/ttilley/fssm/commit/a394304b66008872f7fcacfffcd2cdad0e6a2f9e#commitcomment-357393">this comment</a>. </p> <p>It seems that FSSM detects that ruby is running inside a Windows box, and treats paths in the Windows' way <code>(C:\blabla)</code>. Commenting out the line 26 of the file <code>&lt;fssm_gem_path&gt;/lib/fssm/pathname.rb</code> makes <code>compass watch</code> work as expected. You can also add</p> <pre><code>unless path[0, 1] == File::SEPARATOR </code></pre> <p>to the end of line 26 to make it work.</p>
6,718,256
How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?
<p>The code is meant to output the current tab object for the page the user is viewing to the console but it just outputs undefined. It's run from within a browser action page.</p> <pre><code>chrome.tabs.getCurrent( function(tab){ console.log(tab); } ); </code></pre> <p>I've looked at the <a href="http://code.google.com/chrome/extensions/tabs.html#method-getCurrent" rel="noreferrer">documentation</a> and as far as I can tell the code seems to match what it says.</p>
6,718,277
5
1
null
2011-07-16 15:13:10.09 UTC
9
2021-06-27 06:35:12.407 UTC
2012-12-26 08:52:37.4 UTC
null
1,793,477
null
838,009
null
1
45
javascript|html|google-chrome-extension|google-chrome-devtools
45,639
<p>Try:</p> <pre><code>chrome.tabs.getSelected(null, function(tab){ console.log(tab); }); </code></pre>
6,895,457
How to define relative paths in Visual Studio Project?
<p>I have a library and a console application that uses a library. The library has a folder with source and header files.</p> <p>My project is in a child/inner directory but that library directory that I want to include is in a parent/upper directory.</p> <p>My project directory:</p> <pre><code>H:\Gmail_04\gsasl-1.0\lib\libgsaslMain </code></pre> <p>Includes files are here:</p> <pre><code>H:\Gmail_04\gsasl-1.0\src </code></pre> <p>How can I use paths relative to the project directory, to include folders that are in a parent/upper directory?</p>
6,895,484
5
0
null
2011-08-01 07:38:16.92 UTC
22
2021-07-20 22:03:52.3 UTC
2015-04-17 02:21:13.073 UTC
null
796,832
null
709,187
null
1
70
c|visual-studio|visual-studio-2008|visual-c++
211,467
<p>If I get you right, you need <code>..\..\src</code></p>
6,351,609
CMake - linking to library downloaded from ExternalProject_add()
<p>I am trying to use ExternalProject_add() to download/install dependencies. It installs fine, but I can't figure out how to actually link the libraries after they are downloaded. </p> <p>I want to call target_link_libraries() on the library that was just downloaded, but the path to the library will vary by system. </p> <p>If this were a system dependency, I could just call find_package() - but the packages weren't installed on the default search path. I don't think you can specify a search path for find_package in module mode. </p> <p>Here's a snippet of my CMakeLists.txt that doesn't work: </p> <pre><code>ExternalProject_Add( protobuf URL http://protobuf.googlecode.com/files/protobuf-2.4.1.tar.gz CONFIGURE_COMMAND &lt;SOURCE_DIR&gt;/configure --prefix=&lt;INSTALL_DIR&gt; PREFIX ${MYPROJ_SOURCE_DIR}/dependencies ) find_package(protobuf REQUIRED) set(LIBS ${LIBS} ${PROTOBUF_LIBRARIES}) target_link_libraries (mybinary ${LIBS}) </code></pre>
6,355,851
6
1
null
2011-06-15 00:06:37.843 UTC
28
2020-07-05 18:16:10.797 UTC
2018-08-12 13:02:34.66 UTC
null
8,815,948
null
409,210
null
1
65
cmake|external-project
36,868
<p>When you're using ExternalProject_Add, you can't use find_package, since there's nothing to find when CMake runs to configure the outer project.</p> <p>So, if library locations vary by platform you will need conditional logic based on your platform. (I don't know protobuf's libraries or structure here, so this is just an example, but it should get you headed in the right direction...) Something like this:</p> <pre><code>if(WIN32) set(PROTOBUF_LIB_DIR "${MYPROJ_SOURCE_DIR}/dependencies/win" set(prefix "") set(suffix ".lib") elseif(APPLE) set(PROTOBUF_LIB_DIR "${MYPROJ_SOURCE_DIR}/dependencies/mac" set(prefix "lib") set(suffix ".a") else() set(PROTOBUF_LIB_DIR "${MYPROJ_SOURCE_DIR}/dependencies/linux" set(prefix "lib") set(suffix ".a") endif() set(PROTOBUF_LIBRARIES "${PROTOBUF_LIB_DIR}/${prefix}protobufLib1${suffix}" "${PROTOBUF_LIB_DIR}/${prefix}protobufLib2${suffix}") </code></pre> <p>Granted, this is less convenient than using find_package. If you can use a pre-built/pre-installed package, you should, so that you can use find_package. If you must build the other package from source code as part of your project, though, ExternalProject_Add is useful, even though it is unable to abstract away all the details for you.</p>
6,530,573
How to crop UIImage on oval shape or circle shape?
<p>Please give ideas for how to crop <code>UIImage</code> on oval shape or circle shape. Please share your ideas.</p>
6,531,539
11
0
null
2011-06-30 06:05:32.08 UTC
33
2021-02-11 10:47:32.533 UTC
2019-01-31 04:40:28.12 UTC
null
822,420
null
822,420
null
1
41
ios|objective-c|swift|iphone|ios4
50,718
<pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; CALayer *imageLayer = YourImageview.layer; [imageLayer setCornerRadius:5]; [imageLayer setBorderWidth:1]; [imageLayer setMasksToBounds:YES]; </code></pre> <p>by increasing radius it will become more round-able.</p> <p>As long as the image is a square, you can get a perfect circle by taking half the width as the corner radius: </p> <pre><code>[imageView.layer setCornerRadius:imageView.frame.size.width/2]; </code></pre> <p>You also need to add</p> <pre><code>[imageView.layer setMasksToBounds:YES]; </code></pre> <p><strong>Swift 4.2</strong></p> <pre><code>import QuartzCore var imageLayer: CALayer? = YourImageview.layer imageLayer?.cornerRadius = 5 imageLayer?.borderWidth = 1 imageLayer?.masksToBounds = true </code></pre>
38,299,930
How to add a simple text label to an image in Go?
<p>Given <code>image.RGBA</code>, coordinates, and a line of text, how do I add a simple label with any plain fixed font? E.g. <code>Face7x13</code> from <a href="https://godoc.org/golang.org/x/image/font/basicfont" rel="noreferrer"><code>font/basicfont</code></a>.</p> <pre><code>package main import ( "image" "image/color" "image/png" "os" ) func main() { img := image.NewRGBA(image.Rect(0, 0, 320, 240)) x, y := 100, 100 addLabel(img, x, y, "Test123") png.Encode(os.Stdout, img) } func addLabel(img *image.RGBA, x, y int, label string) { col := color.Black // now what? } </code></pre> <p>Alignment doesn't really matter, but best if I could write the label above a line which starts at the coordinates.</p> <p>And I would like to avoid external loadable dependencies like fonts.</p>
38,300,583
2
1
null
2016-07-11 05:49:19.85 UTC
21
2022-02-25 20:29:31.91 UTC
2016-07-11 11:13:31.367 UTC
null
1,705,598
null
93,540
null
1
51
image|go|fonts|draw
29,035
<p>The <a href="https://godoc.org/golang.org/x/image/font" rel="noreferrer"><code>golang.org/x/image/font</code></a> package just defines interfaces for font faces and drawing text on images.</p> <p>You may use the Go implementation of Freetype font rasterizer: <a href="https://github.com/golang/freetype" rel="noreferrer"><code>github.com/golang/freetype</code></a>.</p> <p>The key type is <a href="http://godoc.org/github.com/golang/freetype#Context" rel="noreferrer"><code>freetype.Context</code></a>, it has all the methods you need.</p> <p>For a complete example, check out this file: <a href="https://github.com/golang/freetype/blob/master/example/freetype/main.go" rel="noreferrer"><code>example/freetype/main.go</code></a>. This example loads a font file, creates and configures <code>freetype.Context</code>, draws text on image and saves the result image to file.</p> <p>Let's assume you already have the font file loaded, and a <code>c</code> context configured (see the example how to do that). Then your <code>addLabel()</code> function could look like this:</p> <pre><code>func addLabel(img *image.RGBA, x, y int, label string) { c.SetDst(img) size := 12.0 // font size in pixels pt := freetype.Pt(x, y+int(c.PointToFixed(size)&gt;&gt;6)) if _, err := c.DrawString(label, pt); err != nil { // handle error } } </code></pre> <p>If you don't want to hassle with the <code>freetype</code> package and external font files, the <a href="https://godoc.org/golang.org/x/image/font/basicfont" rel="noreferrer"><code>font/basicfont</code></a> package contains a basic font named <code>Face7x13</code> whose graphical data is entirely self-contained. This is how you could use that:</p> <pre><code>import ( &quot;golang.org/x/image/font&quot; &quot;golang.org/x/image/font/basicfont&quot; &quot;golang.org/x/image/math/fixed&quot; &quot;image&quot; &quot;image/color&quot; ) func addLabel(img *image.RGBA, x, y int, label string) { col := color.RGBA{200, 100, 0, 255} point := fixed.Point26_6{fixed.I(x), fixed.I(y)} d := &amp;font.Drawer{ Dst: img, Src: image.NewUniform(col), Face: basicfont.Face7x13, Dot: point, } d.DrawString(label) } </code></pre> <p>This is how this <code>addLabel()</code> function can be used: the code below creates a new image, draws the <code>&quot;Hello Go&quot;</code> text on it and saves it in a file named <code>hello-go.png</code>:</p> <pre><code>func main() { img := image.NewRGBA(image.Rect(0, 0, 300, 100)) addLabel(img, 20, 30, &quot;Hello Go&quot;) f, err := os.Create(&quot;hello-go.png&quot;) if err != nil { panic(err) } defer f.Close() if err := png.Encode(f, img); err != nil { panic(err) } } </code></pre> <p>Note the above code also requires the <a href="https://golang.org/pkg/image/png/" rel="noreferrer"><code>&quot;image/png&quot;</code></a> package import.</p> <p>Also note that the <code>y</code> coordinate given will be the bottom line of the text. So if you want to draw a line to the top left corner, you have to use <code>x = 0</code> and <code>y = 13</code> (13 is the height of this <code>Face7x13</code> font). If you wish, you could build this into the <code>addLabel()</code> function by subtracting <code>13</code> from the <code>y</code> coordinate, so that the passed <code>y</code> coordinate would be the top coordinate at which the text will be drawn.</p> <p>There is also an additional self-contained font in the <a href="https://godoc.org/golang.org/x/image/font/inconsolata" rel="noreferrer"><code>golang.org/x/image/font/inconsolata</code></a> package with regular and bold style, to use them, you only need to specify a different <a href="https://godoc.org/golang.org/x/image/font#Face" rel="noreferrer"><code>Face</code></a> in <code>addLabel()</code>:</p> <pre><code>import &quot;golang.org/x/image/font/inconsolata&quot; // To use regular Inconsolata font family: Face: inconsolata.Regular8x16, // To use bold Inconsolata font family: Face: inconsolata.Bold8x16, </code></pre>
38,160,412
MongoDB: How to find the exact version of installed MongoDB
<p>I have mongoDB 3.2 installed locally for Windows 7. I would like to find out its specific version (like is it 3.2.1, or 3.2.3 or...). How could I find it? If I open the database shell (mongo.exe), I can see it outputs:</p> <blockquote> <p>MongoDB shell version: 3.2.0</p> </blockquote> <p>But that's just the shell version, and I'm not sure whether it's the same as my real database version.</p>
38,160,452
7
1
null
2016-07-02 12:58:06.633 UTC
17
2022-01-03 00:01:42.237 UTC
2021-02-03 13:17:29.433 UTC
null
10,907,864
null
4,662,347
null
1
202
mongodb
288,634
<p>Just run your console and type:</p> <pre><code>db.version() </code></pre> <p><a href="https://docs.mongodb.com/manual/reference/method/db.version/" rel="noreferrer">https://docs.mongodb.com/manual/reference/method/db.version/</a></p>
38,203,839
fsockopen(): unable to connect to ssl://smtp.gmail.com:465
<pre><code>$config = array( 'protocol' =&gt; 'smtp', 'smtp_host' =&gt; 'ssl://smtp.gmail.com', 'smtp_port' =&gt; '465', 'smtp_user' =&gt; "[email protected]", 'smtp_pass' =&gt; "xxxxxxx", // change it to yours 'mailtype' =&gt; 'html', 'charset' =&gt; 'utf8' ); $this-&gt;load-&gt;library('email',$config); $this-&gt;email-&gt;set_newline("\r\n"); $this-&gt;email-&gt;set_crlf( "\r\n" ); $this-&gt;email-&gt;from($config['smtp_user']); $this-&gt;email-&gt;to($email['user_email']); $this-&gt;email-&gt;subject($row['tplsubject']); $this-&gt;email-&gt;message(html_entity_decode($email_subject)); $this-&gt;email-&gt;send(); </code></pre> <p>This code not working its showing error </p> <blockquote> <p>A PHP Error was encountered</p> <p>Severity: Warning</p> <p>Message: fsockopen(): unable to connect to ssl://smtp.gmail.com:465 (Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?)</p> <p>Filename: libraries/Email.php</p> <p>Line Number: 1689</p> </blockquote>
38,227,466
3
2
null
2016-07-05 12:45:28.967 UTC
3
2022-02-09 11:02:00.163 UTC
2016-07-06 15:37:38.68 UTC
null
206,403
null
5,299,384
null
1
11
codeigniter
49,692
<p>This is not a codeigniter problem, but a php settings related problem. The answer to this question can be found here: <a href="https://stackoverflow.com/questions/21962849/unable-to-find-the-socket-transport-ssl-did-you-forget-to-enable-it-when-you">Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?</a></p> <p>One thing to note is that in codeigniter you can use an e-mail config file, to hold all your config settings. (so you don't have to define them each time in a controller). You can do this by creating the file: <code>application/config/email.php</code> you can then fill this file with your settings, like this:</p> <pre><code>&lt;?php defined('BASEPATH') OR exit('No direct script access allowed'); $config = array( 'protocol' =&gt; 'smtp', // 'mail', 'sendmail', or 'smtp' 'smtp_host' =&gt; 'your_host', 'smtp_port' =&gt; your_port, 'smtp_user' =&gt; 'your_email', 'smtp_pass' =&gt; 'your_password', 'smtp_crypto' =&gt; 'security', //can be 'ssl' or 'tls' for example 'mailtype' =&gt; 'html', //plaintext 'text' mails or 'html' 'smtp_timeout' =&gt; '4', //in seconds 'charset' =&gt; 'iso-8859-1', 'wordwrap' =&gt; TRUE ); </code></pre> <p>each time you load the library (<code>$this-&gt;load-&gt;library('email');</code>) these settings will be automatically loaded.</p> <p>Also I recommend that you change your e-mail password <strong>immediately</strong> because you wrote your credentials in your question.</p>
15,707,431
HTTP POST using Angular.js
<p>I'm new to the scene and I want to use Angular.js to make an HTTP POST request. I'm accessing PHP scripts which have parameters that are just POST variables. What gets returned from each script is a JSON string. Normally in an HTML form you can make such a request like:</p> <pre><code>&lt;form method="post" action="url.php"&gt; &lt;input name="this"&gt; &lt;input name="that"&gt; &lt;input value="Submit"&gt; &lt;/form&gt; </code></pre> <p>Depending on your input and after you click submit, JSON data1 will return something like this: <code>{ "code" : 1 }</code></p> <p>I have no access to the scripts or to the servers that hosts them.</p> <p>I was wondering if it's possible for Angular.js to read the JSON data1, match that data1 to what they're defined in my JSON data2, and then output them to my view (<code>&lt;pre&gt;data2&lt;/pre&gt;</code>). </p> <p>For example, if <code>{ "code" : 1 }</code> is retrieved, I want my JSON to output the value for code #1:</p> <pre><code>{ "code" : [ { 1: "User already logged in." }, { 2: "Wrong parameters, try again."}, { 3: "etc., etc." } ] }; </code></pre> <p>Here's my attempt:</p> <pre><code>&lt;form ng-controller="PhpCtrl" name="f1"&gt; &lt;input type="text" name="name"&gt; &lt;input type="text" name="password"&gt; &lt;pre ng-model="codeStatus"&gt;{{codeStatus}}&lt;/pre&gt; &lt;input type="submit" ng-click="add()" value="Submit"&gt; &lt;/form&gt; function PhpCtrl($scope, $http, $templateCache) { $scope.method = 'POST'; $scope.url = 'url.php'; $scope.codeStatus = ""; $scope.add = function() { $http({ method: $scope.method, url: $scope.url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, cache: $templateCache }). success(function(response) { $scope.codeStatus = response.data; }). error(function(response) { $scope.codeStatus = response || "Request failed"; }); return false; }; } </code></pre> <p>All it's posting so far to the view is "Request failed" lol, although it's processing HTTP/1.1 200. I know I still have a ways to go but I would appreciate any help. Once I figure out how to post the proper JSON data1 to the view, the next step is matching and outputting the appropriate data2. Thank you in advance!</p>
15,711,147
3
4
null
2013-03-29 16:36:33.98 UTC
8
2015-02-12 01:04:20.647 UTC
2013-03-29 19:46:53.45 UTC
null
2,137,538
null
2,137,538
null
1
20
php|javascript|json|angularjs|http-post
59,842
<p>Acctually the problem is in the backend with PHP you don't retrieve the posted data like usual, this worked for me:</p> <pre><code>function PhpCtrl($scope, $http, $templateCache) { var method = 'POST'; var url = 'url.php'; $scope.codeStatus = ""; $scope.add = function() { var FormData = { 'name' : document.f1.name.value, 'password' : document.f1.password.value }; $http({ method: method, url: url, data: FormData, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, cache: $templateCache }). success(function(response) { $scope.codeStatus = response.data; }). error(function(response) { $scope.codeStatus = response || "Request failed"; }); return false; }; } </code></pre> <p>in the PHP file:</p> <pre><code>$data = json_decode(file_get_contents("php://input")); echo $data-&gt;name; </code></pre> <p>Hope this help.</p>
15,680,259
Parse XML in SQL Server
<p>The XML looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;GespeicherteDaten&gt; &lt;strategieWuerfelFelder Type="strategieWuerfelFelder"&gt; &lt;Felder X="3" Y="3" Z="3"&gt; &lt;Feld X="1" Y="1" Z="1"&gt; &lt;strategieWuerfelFeld Type="strategieWuerfelFeld"&gt; &lt;Name&gt;Name&lt;/Name&gt; &lt;Beschreibung&gt;Test&lt;/Beschreibung&gt; &lt;/strategieWuerfelFeld&gt; &lt;/Feld&gt; &lt;Feld X="1" Y="1" Z="2"&gt; &lt;strategieWuerfelFeld Type="strategieWuerfelFeld"&gt; &lt;Name&gt;Name2&lt;/Name&gt; &lt;Beschreibung&gt;Test2&lt;/Beschreibung&gt; &lt;/strategieWuerfelFeld&gt; &lt;/Feld&gt; &lt;/Felder&gt; &lt;/strategieWuerfelFelder&gt; &lt;/GespeicherteDaten&gt;' </code></pre> <p>My result table should contain the attributes Felder->X, Y, Z, Feld->X,Y,Z and Name.</p> <p>Like: </p> <pre class="lang-none prettyprint-override"><code>Felder_X | Felder_Y | Felder_Z | Feld_X | Feld_Y | Feld_Z | Name </code></pre> <p>Is it possible to get this values directly from a query or stored procedure?</p>
15,681,388
2
0
null
2013-03-28 11:10:21.713 UTC
10
2013-03-28 12:14:08.803 UTC
2013-03-28 12:13:21.52 UTC
null
569,436
null
2,219,153
null
1
23
sql-server|xml|sql-server-2005
86,819
<pre><code>DECLARE @xml xml SET @xml = '&lt;GespeicherteDaten&gt; &lt;strategieWuerfelFelder Type="strategieWuerfelFelder"&gt; &lt;Felder X="3" Y="3" Z="3"&gt; &lt;Feld X="1" Y="1" Z="1"&gt; &lt;strategieWuerfelFeld Type="strategieWuerfelFeld"&gt; &lt;Name&gt;Name&lt;/Name&gt; &lt;Beschreibung&gt;Test&lt;/Beschreibung&gt; &lt;/strategieWuerfelFeld&gt; &lt;/Feld&gt; &lt;Feld X="1" Y="1" Z="2"&gt; &lt;strategieWuerfelFeld Type="strategieWuerfelFeld"&gt; &lt;Name&gt;Name2&lt;/Name&gt; &lt;Beschreibung&gt;Test2&lt;/Beschreibung&gt; &lt;/strategieWuerfelFeld&gt; &lt;/Feld&gt; &lt;/Felder&gt; &lt;/strategieWuerfelFelder&gt;&lt;/GespeicherteDaten&gt;' SELECT b.value('@X', 'int') as X , b.value('@Y', 'int') as Y , b.value('@Z', 'int') as Z , b.value('(./strategieWuerfelFeld/Name/text())[1]','Varchar(50)') as [Name] , b.value('../@X','int') as Felder_X , b.value('../@Y','int') as Felder_Y , b.value('../@Z','int') as Felder_Z FROM @xml.nodes('/GespeicherteDaten/strategieWuerfelFelder/Felder/Feld') as a(b) </code></pre>
15,664,318
Are there named groups in Groovy regex pattern matches?
<p>Something like:</p> <pre><code>def match = "John 19" =~ /(&amp;name&amp;)\w+ (&amp;age&amp;\d+)/ def name = match.name def age = match.age </code></pre> <p>Is there a groovy syntax that allows for something like this (instead of of the fictional <code>&amp;</code> operator I made up? </p>
15,664,805
3
3
null
2013-03-27 16:38:19.93 UTC
8
2019-12-04 11:37:36.863 UTC
null
null
null
null
11,236
null
1
25
regex|groovy
16,104
<p>Assuming you are using on Java 7+, you can do:</p> <pre><code>def matcher = 'John 19' =~ /(?&lt;name&gt;\w+) (?&lt;age&gt;\d+)/ if( matcher.matches() ) { println "Matches" assert matcher.group( 'name' ) == 'John' assert matcher.group( 'age' ) == '19' } else { println "No Match" } </code></pre> <p>If you are not on java 7 yet, you'd need a <a href="https://code.google.com/p/named-regexp/">third party regex library</a></p>
10,302,261
Forecasting time series data
<p>I've done some research and I am stuck in finding the solution. I have a time series data, very basic data frame, let's call it <code>x</code>:</p> <pre><code>Date Used 11/1/2011 587 11/2/2011 578 11/3/2011 600 11/4/2011 599 11/5/2011 678 11/6/2011 555 11/7/2011 650 11/8/2011 700 11/9/2011 600 11/10/2011 550 11/11/2011 600 11/12/2011 610 11/13/2011 590 11/14/2011 595 11/15/2011 601 11/16/2011 700 11/17/2011 650 11/18/2011 620 11/19/2011 645 11/20/2011 650 11/21/2011 639 11/22/2011 620 11/23/2011 600 11/24/2011 550 11/25/2011 600 11/26/2011 610 11/27/2011 590 11/28/2011 595 11/29/2011 601 11/30/2011 700 12/1/2011 650 12/2/2011 620 12/3/2011 645 12/4/2011 650 12/5/2011 639 12/6/2011 620 12/7/2011 600 12/8/2011 550 12/9/2011 600 12/10/2011 610 12/11/2011 590 12/12/2011 595 12/13/2011 601 12/14/2011 700 12/15/2011 650 12/16/2011 620 12/17/2011 645 12/18/2011 650 12/19/2011 639 12/20/2011 620 12/21/2011 600 12/22/2011 550 12/23/2011 600 12/24/2011 610 12/25/2011 590 12/26/2011 750 12/27/2011 750 12/28/2011 666 12/29/2011 678 12/30/2011 800 12/31/2011 750 </code></pre> <p>I really appreciate any help with this. I am working with time series data and need to be able to create forecast based on historical data.</p> <ol> <li><p>First I tried to convert it to <code>xts</code>: </p> <pre><code>x.xts &lt;- xts(x$Used, x$Date) </code></pre></li> <li><p>Then, I converted <code>x.xts</code> to regular time series:</p> <pre><code>x.ts &lt;- as.ts(x.xts) </code></pre></li> <li><p>Put the values in <code>ets</code>:</p> <pre><code>x.ets &lt;- ets(x.ts) </code></pre></li> <li><p>Performed forecasting for 10 periods:</p> <pre><code>x.fore &lt;- forecast(x.ets, h=10) </code></pre></li> <li><p><code>x.fore</code> is this:</p> <pre><code> Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 87 932.9199 831.7766 1034.063 778.2346 1087.605 88 932.9199 818.1745 1047.665 757.4319 1108.408 89 932.9199 805.9985 1059.841 738.8103 1127.029 90 932.9199 794.8706 1070.969 721.7918 1144.048 91 932.9199 784.5550 1081.285 706.0153 1159.824 92 932.9199 774.8922 1090.948 691.2375 1174.602 93 932.9199 765.7692 1100.071 677.2849 1188.555 94 932.9199 757.1017 1108.738 664.0292 1201.811 95 932.9199 748.8254 1117.014 651.3717 1214.468 96 932.9199 740.8897 1124.950 639.2351 1226.605 </code></pre></li> <li><p>When I try to plot the <code>x.fore</code>, I get a graph but the x-axis is showing numbers rather than dates:</p></li> </ol> <p><img src="https://i.stack.imgur.com/nCbwj.png" alt="enter image description here"></p> <p>Are the steps I am doing correct? How can I change the x-axis to read show dates? </p> <p>I thank you so much for any input.</p>
10,347,205
3
3
null
2012-04-24 16:43:06.993 UTC
21
2017-04-27 07:38:57.96 UTC
2013-03-16 15:27:17.183 UTC
null
271,616
null
1,148,098
null
1
26
r|time-series|xts
39,783
<p>Here's what I did:</p> <pre><code>x$Date = as.Date(x$Date,format="%m/%d/%Y") x = xts(x=x$Used, order.by=x$Date) # To get the start date (305) # &gt; as.POSIXlt(x = "2011-11-01", origin="2011-11-01")$yday ## [1] 304 # Add one since that starts at "0" x.ts = ts(x, freq=365, start=c(2011, 305)) plot(forecast(ets(x.ts), 10)) </code></pre> <p>Resulting in:</p> <p><img src="https://i.stack.imgur.com/yQMS1.png" alt="Example output"></p> <p>What can we learn from this:</p> <ul> <li>Many of your steps can be combined reducing the number of intermediate objects you create</li> <li>The output is still not as pretty as @joran, but it is still easily readable. <code>2011.85</code> means "day number <code>365*.85</code>" (day 310 in the year).</li> <li>Figuring out the day in a year can be done by using <code>as.POSIXlt(x = "2011-11-01", origin="2011-11-01")$yday</code> and figuring out the date from a day number can be done by using something like <code>as.Date(310, origin="2011-01-01")</code></li> </ul> <h2>Update</h2> <p>You can drop even more intermediate steps, since there's no reason to first convert your data into an xts.</p> <pre><code>x = ts(x$Used, start=c(2011, as.POSIXlt("2011-11-01")$yday+1), frequency=365) # NOTE: We have only selected the "Used" variable # since ts will take care of dates plot(forecast(ets(x), 10)) </code></pre> <p>This gives exactly the same result as the image above.</p> <h2>Update 2</h2> <p>Building on the solution provided by @joran, you can try:</p> <pre><code># 'start' calculation = `as.Date("2011-11-01")-as.Date("2011-01-01")+1` # No need to convert anything to dates at this point using xts x = ts(x$Used, start=c(2011, 305), frequency=365) # Directly plot your forecast without your axes plot(forecast(ets(x), 10), axes = FALSE) # Generate labels for your x-axis a = seq(as.Date("2011-11-01"), by="weeks", length=11) # Plot your axes. # `at` is an approximation--there's probably a better way to do this, # but the logic is approximately 365.25 days in a year, and an origin # date in R of `January 1, 1970` axis(1, at = as.numeric(a)/365.25+1970, labels = a, cex.axis=0.6) axis(2, cex.axis=0.6) </code></pre> <p>Which will yield:</p> <p><img src="https://i.stack.imgur.com/ttoXl.png" alt="Second attempt"></p> <p>Part of the problem in your original code is that after you have converted your data to an <code>xts</code> object, and converted that to a <code>ts</code> object, you lose the dates in your <code>forecast</code> points. </p> <p>Compare the first column (<code>Point</code>) of your <code>x.fore</code> output to the following:</p> <pre><code>&gt; forecast(ets(x), 10) Point Forecast Lo 80 Hi 80 Lo 95 Hi 95 2012.000 741.6437 681.7991 801.4884 650.1192 833.1682 2012.003 741.6437 676.1250 807.1624 641.4415 841.8459 2012.005 741.6437 670.9047 812.3828 633.4577 849.8298 2012.008 741.6437 666.0439 817.2435 626.0238 857.2637 2012.011 741.6437 661.4774 821.8101 619.0398 864.2476 2012.014 741.6437 657.1573 826.1302 612.4328 870.8547 2012.016 741.6437 653.0476 830.2399 606.1476 877.1399 2012.019 741.6437 649.1202 834.1672 600.1413 883.1462 2012.022 741.6437 645.3530 837.9345 594.3797 888.9078 2012.025 741.6437 641.7276 841.5599 588.8352 894.4523 </code></pre> <p>Hopefully this helps you understand the problem with your original approach and improves your capacity with dealing with time series in R.</p> <h2>Update 3</h2> <p><strong><em>Final, and more accurate solution--because I'm avoiding other work that I should actually be doing right now...</em></strong></p> <p>Use the <code>lubridate</code> package for better date handling:</p> <pre><code>require(lubridate) y = ts(x$Used, start=c(2011, yday("2011-11-01")), frequency=365) plot(forecast(ets(y), 10), xaxt="n") a = seq(as.Date("2011-11-01"), by="weeks", length=11) axis(1, at = decimal_date(a), labels = format(a, "%Y %b %d"), cex.axis=0.6) abline(v = decimal_date(a), col='grey', lwd=0.5) </code></pre> <p>Resulting in:</p> <p><img src="https://i.stack.imgur.com/yYCbX.png" alt="Final plot"></p> <p>Note the alternative method of identifying the start date for your <code>ts</code> object.</p>
10,289,017
How to format date and time string in C++
<p>Let's say I have time_t and tm structure. I can't use Boost but MFC. How can I make it a string like following?</p> <pre><code>Mon Apr 23 17:48:14 2012 </code></pre> <p>Is using sprintf the only way?</p>
10,289,094
6
3
null
2012-04-23 22:09:34.703 UTC
6
2016-01-07 01:57:41.84 UTC
null
null
null
null
749,973
null
1
29
c++|datetime|mfc
101,942
<p>The C library includes <a href="http://en.cppreference.com/w/c/chrono/strftime" rel="noreferrer"><code>strftime</code></a> specifically for formatting dates/times. The format you're asking for seems to correspond to something like this:</p> <pre><code>char buffer[256]; strftime(buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y", &amp;your_tm); </code></pre> <p>I believe <a href="http://en.cppreference.com/w/cpp/io/manip/put_time" rel="noreferrer"><code>std::put_time</code></a> uses a similar format string, though it does relieve you of having to explicitly deal with a buffer. If you want to write the output to a stream, it's quite convenient, but to get it into a string it's not a lot of help -- you'd have to do something like:</p> <pre><code>std::stringstream buffer; buffer &lt;&lt; std::put_time(&amp;your_tm, "%a %b %d %H:%M:%S %Y"); // now the result is in `buffer.str()`. </code></pre> <p><code>std::put_time</code> is new with C++11, but C++03 has a <code>time_put</code> facet in a locale that <em>can</em> do the same thing. If memory serves, I did manage to make it work once, but after that decided it wasn't worth the trouble, and I haven't done it since.</p>
25,068,032
Empty loop is slower than a non-empty one in C
<p>While trying to know how long a line of C code used to execute, I noticed this weird thing :</p> <pre><code>int main (char argc, char * argv[]) { time_t begin, end; uint64_t i; double total_time, free_time; int A = 1; int B = 1; begin = clock(); for (i = 0; i&lt;(1&lt;&lt;31)-1; i++); end = clock(); free_time = (double)(end-begin)/CLOCKS_PER_SEC; printf("%f\n", free_time); begin = clock(); for (i = 0; i&lt;(1&lt;&lt;31)-1; i++) { A += B%2; } end = clock(); free_time = (double)(end-begin)/CLOCKS_PER_SEC; printf("%f\n", free_time); return(0); } </code></pre> <p>Which when executed displays :</p> <pre><code>5.873425 4.826874 </code></pre> <p>Why does the empty loop use more time than the second which has an instruction within ? Of course I've tried many variants but everytime, an empty loop takes more time than one with one single instruction within.</p> <p>Note that I have tried swapping loops order and adding some warmup code and it didn't change my problem at all.</p> <p>I'm using codeblocks as IDE with GNU gcc compiler, linux ubuntu 14.04 and have a quadcore intel i5 at 2.3GHz (I've tried running the programm on a single core, this doesn't change the result).</p>
25,077,620
4
18
null
2014-07-31 20:07:28.833 UTC
12
2014-08-02 11:39:23.077 UTC
2014-08-02 04:07:38.963 UTC
null
4,279
null
3,882,647
null
1
65
c|performance|loops
6,760
<p>The fact is that modern processors are complicated. All the instructions executed will interact with each other in complicated and interesting ways. Thanks for <a href="https://stackoverflow.com/a/25069078">"that other guy" for posting the code.</a> </p> <p>Both OP and "that other guy" apparently found that the short loop takes 11 cycles, while the long one takes 9 cycles. For the long loop, 9 cycles is plenty of time even though there are lot of operations. For the short loop, there must be some stall caused by it being so short, and just adding a <code>nop</code> makes the loop long enough to avoid the stall. </p> <p>One thing that happens if we look at the code: </p> <pre><code>0x00000000004005af &lt;+50&gt;: addq $0x1,-0x20(%rbp) 0x00000000004005b4 &lt;+55&gt;: cmpq $0x7fffffff,-0x20(%rbp) 0x00000000004005bc &lt;+63&gt;: jb 0x4005af &lt;main+50&gt; </code></pre> <p>We read <code>i</code> and write it back (<code>addq</code>). We read it immediately again, and compare it (<code>cmpq</code>). And then we loop. But the loop uses branch prediction. So at the time when the <code>addq</code> is executed, the processor isn't really sure it is allowed to write to <code>i</code> (because branch prediction could be wrong). </p> <p>Then we compare to <code>i</code>. The processor will try to avoid reading <code>i</code> from memory, because reading it takes a long time. Instead some bit of hardware will remember that we just wrote to <code>i</code> by adding to it, and instead of reading <code>i</code>, the <code>cmpq</code> instruction gets the data from the store instruction. Unfortunately, we are not sure at this point if the write to <code>i</code> actually happened or not! So that could introduce a stall here. </p> <p>The problem here is that the conditional jump, the <code>addq</code> which leads to a conditional store, and the <code>cmpq</code> which isn't sure where to get the data from, are all very very close together. They are unusually close together. It could be that they are so close together, the processor cannot figure out at this time whether to take <code>i</code> from the store instruction or to read it from memory. And reads it from memory, which is slower because it has to wait for the store to finish. And adding just one <code>nop</code> gives the processor enough time. </p> <p>Usually you think that there is RAM, and there is cache. On a modern Intel processor, reading memory can read from (slowest to fastest): </p> <ol> <li>Memory (RAM)</li> <li>L3 cache (optional)</li> <li>L2 cache</li> <li>L1 cache</li> <li>Previous store instruction that hasn't written to L1 cache yet. </li> </ol> <p>So what the processor does internally in the short, slow loop: </p> <ol> <li>Read <code>i</code> from L1 cache</li> <li>Add 1 to <code>i</code></li> <li>Write <code>i</code> to L1 cache</li> <li>Wait until <code>i</code> is written to L1 cache</li> <li>Read <code>i</code> from L1 cache</li> <li>Compare <code>i</code> with INT_MAX</li> <li>Branch to (1) if it is less. </li> </ol> <p>In the long, fast, loop the processor does: </p> <ol> <li>Lots of stuff</li> <li>Read <code>i</code> from L1 cache</li> <li>Add 1 to <code>i</code></li> <li>Do a "store" instruction that will write <code>i</code> to L1 cache</li> <li>Read <code>i</code> directly from the "store" instruction without touching L1 cache</li> <li>Compare <code>i</code> with INT_MAX</li> <li>Branch to (1) if it is less. </li> </ol>
13,402,809
insert a line in csv file
<p>I have a huge csv file (on order of terabytes).</p> <p>Now, I want to insert one row which is a header to the the top.</p> <p>For example if input.csv looks like this:</p> <pre><code> 1,2,3,4 22,3,23,1 </code></pre> <p>I want it to look like</p> <pre><code>id1,id2,id3,id4 1,2,3,4 and so on </code></pre> <p>How do i do this from shell, terminal, awk, bash?/</p>
13,403,045
5
0
null
2012-11-15 17:18:54.6 UTC
5
2021-03-03 06:13:10.85 UTC
2012-11-15 17:40:19.333 UTC
null
341,459
null
902,885
null
1
23
bash|shell|sed|awk|terminal
44,960
<p>In place, using sed:</p> <pre><code>sed -i 1i"id1,id2,id3,id4" file.csv </code></pre> <p>edit:</p> <p>As @Ed Morton points out, using sed with the <code>-i</code> switch sed edits the file in place, and can therefore be dangerous when editing large files. If you supply a prefix after the <code>-i</code> option then sed creates a backup. So something like this would be safer:</p> <pre><code>sed -i.bak 1i"id1,id2,id3,id4" file.csv </code></pre> <p>The original file will then be located in <code>file.csv.bak</code></p>
13,388,104
Remove Auto-Layout Constraints for Specific Object
<p>I have a <code>UIImageView</code> embedded in a <code>UIView</code>. My entire app uses <code>AutoLayout</code>, but I want to remove <code>constraints</code> for the <code>UIImageView</code>. <code>Xcode</code> will not allow me to delete the <code>constraints</code>, is there a way to disable them for a specific object, set them to zero, something?</p>
17,232,369
6
3
null
2012-11-14 21:59:30.423 UTC
10
2016-12-29 09:17:23.8 UTC
2016-12-29 09:17:23.8 UTC
null
1,342,402
null
688,953
null
1
51
iphone|uiview|uiimageview|autolayout
72,420
<p>I agree Xcode auto-layout is horrible to use if you want something particular...</p> <p>What I use to remove constraints programatically: </p> <pre><code>[detailsPhotoView removeConstraints:detailsPhotoView.constraints]; </code></pre>
13,579,982
How to create a custom exception and handle it in dart
<p>I have written this code to test how custom exceptions are working in the dart.</p> <p>I'm not getting the desired output could someone explain to me how to handle it??</p> <pre class="lang-dart prettyprint-override"><code>void main() { try { throwException(); } on customException { print(&quot;custom exception is been obtained&quot;); } } throwException() { throw new customException('This is my first custom exception'); } </code></pre>
13,580,222
4
2
null
2012-11-27 08:21:36.137 UTC
6
2022-03-15 18:41:45.37 UTC
2021-01-23 03:04:34.427 UTC
user10563627
null
null
1,767,502
null
1
84
flutter|dart|exception|try-catch
57,108
<p>You can look at the <a href="http://www.dartlang.org/docs/dart-up-and-running/ch02.html#exceptions" rel="noreferrer">Exception part of <em>A Tour of the Dart Language</em></a>.</p> <p>The following code works as expected (<code>custom exception has been obtained</code> is displayed in console) :</p> <pre class="lang-dart prettyprint-override"><code>class CustomException implements Exception { String cause; CustomException(this.cause); } void main() { try { throwException(); } on CustomException { print(&quot;custom exception has been obtained&quot;); } } throwException() { throw new CustomException('This is my first custom exception'); } </code></pre>
24,049,673
Swift class introspection & generics
<p>I am trying to dynamically create a <code>class</code> instance based type using generics, however I am encountering difficulty with class introspection.</p> <p>Here are the questions:</p> <ul> <li>Is there a Swift-equivalent to Obj-C's <code>self.class</code>?</li> <li>Is there a way to instantiate a class using the <code>AnyClass</code> result from <code>NSClassFromString</code>?</li> <li>Is there a way to get <code>AnyClass</code> or otherwise type information strictly from a generic parameter <code>T</code>? (Similar to C#'s <code>typeof(T)</code> syntax)</li> </ul>
24,050,187
7
3
null
2014-06-05 00:15:24.15 UTC
41
2020-06-01 23:34:15.497 UTC
null
null
null
null
1,970,765
null
1
125
introspection|swift
64,547
<p>Well, for one, the Swift equivalent of <code>[NSString class]</code> is <code>.self</code> (see <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/doc/uid/TP40014097-CH31-XID_1022">Metatype docs</a>, though they're pretty thin).</p> <p>In fact, <code>NSString.class</code> doesn't even work! You have to use <code>NSString.self</code>.</p> <pre><code>let s = NSString.self var str = s() str = "asdf" </code></pre> <p>Similarly, with a swift class I tried...</p> <pre><code>class MyClass { } let MyClassRef = MyClass.self // ERROR :( let my_obj = MyClassRef() </code></pre> <p>Hmm… the error says:</p> <blockquote> <p>Playground execution failed: error: :16:1: error: constructing an object of class type 'X' with a metatype value requires an '@required' initializer</p> <pre><code> Y().me() ^ &lt;REPL&gt;:3:7: note: selected implicit initializer with type '()' class X { ^ </code></pre> </blockquote> <p>It took me a while to figure out what this means… turns out it wants the class to have a <code>@required init()</code></p> <pre><code>class X { func me() { println("asdf") } required init () { } } let Y = X.self // prints "asdf" Y().me() </code></pre> <p>Some of the docs refer to this as <code>.Type</code>, but <code>MyClass.Type</code> gives me an error in the playground.</p>
24,338,678
Clear form fields after a successful submit
<p>well im working on a small html form.</p> <pre><code> &lt;form class="contact" action="" method="POST"&gt; &lt;label&gt;Name : &lt;/label&gt;&lt;input type="text" name="name" value="&lt;? echo $name; ?&gt;"/&gt; &lt;p class="middle"&gt;&lt;label&gt;Comment : &lt;/label&gt;&lt;textarea name="message"&gt;&lt;/textarea&gt;&lt;? echo $message; ?&gt;&lt;/p&gt; &lt;label class="captcha"&gt;&lt;img src="captcha.php" style="line-height: 30px;"&gt;&lt;/label&gt;&lt;input type="text" name="code"/&gt; &lt;input type="submit" class="csubmit" value="Now !" name="get"/&gt; &lt;/form&gt; </code></pre> <p>and this is the php code:</p> <pre><code>&lt;?php if (isset($_POST['get'])) { $error = ""; if (!empty($_POST['name'])) { $name = $_POST['name']; } else { $error .= "no name. &lt;br /&gt;"; } if (!empty($_POST['message'])) { $message = $_POST['message']; } else { $error .= "no message &lt;br /&gt;"; } if(($_POST['code']) == $_SESSION['code']) { $code = $_POST['code']; } else { $error .= "wrong captcha &lt;br /&gt;"; } if (!empty($error)) { echo '&lt;p class="error"&gt;Error :&lt;br/&gt;' . $error . '&lt;/p&gt;'; } elseif (!empty($success)) { echo $success; } if (empty($error)) { $message = mysql_real_escape_string($message); $name = mysql_real_escape_string($name); $id = mysql_real_escape_string($_GET['id']); $date = date("Y-m-d H:i:s"); mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')"); echo "thank you"; } } ?&gt; </code></pre> <p>As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?</p>
24,338,725
1
3
null
2014-06-21 05:44:14.533 UTC
1
2017-04-22 15:46:56.037 UTC
null
null
null
null
3,756,377
null
1
2
php|html|forms
39,503
<p>You can use .reset() on your form.</p> <pre><code>$("#form")[0].reset(); </code></pre> <p>You could follow that with Javascript too</p> <pre><code>document.getElementById('form').reset(); </code></pre> <p>Or, if successful, redirect the user back to your contact page:</p> <pre><code>header("Location: contact.php"); // redirect back to your contact form exit; </code></pre> <p><strong>EDIT</strong></p> <pre><code>&lt;input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" /&gt; function clearform() { document.getElementById("name").value=""; //don't forget to set the textbox ID document.getElementById("message").value=""; //don't forget to set the textbox ID document.getElementById("code").value=""; //don't forget to set the textbox ID } </code></pre> <p>Also use:</p> <pre><code>required="required" </code></pre> <p>so people will be required to fill out the input fields :)</p> <p>Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.</p>
3,544,322
How to use an auto incremented primary key as a foreign key as well?
<p>This is what I'm trying to do:</p> <p>I have 2 tables...</p> <pre><code>CREATE TABLE `parent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `data` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; CREATE TABLE `child` ( `parent_id` int(11) DEFAULT NULL, `related_ids` int(11) DEFAULT NULL, KEY `parent_id` (`parent_id`), KEY `related_ids` (`related_ids`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>And then a constraint:</p> <pre><code>ALTER TABLE `parent` ADD FOREIGN KEY (`id`) REFERENCES `child` (`parent_id`); </code></pre> <p>As you can see the table parent has an auto-incremented primary key "id", which is also being used as a foreign key for the child table.</p> <p>Now I want to insert a record in the parent table, like this:</p> <pre><code>INSERT INTO parent SET DATA="abc"; </code></pre> <p>And it fails with error: </p> <blockquote> <p>Cannot add or update a child row: a foreign key constraint fails (<code>myschema</code>.<code>parent</code>, CONSTRAINT <code>parent_ibfk_1</code> FOREIGN KEY (<code>id</code>) REFERENCES <code>child</code> (<code>parent_id</code>))</p> </blockquote> <p>I understand that it fails because it doesn't find a referred record in the child table. If I start by creating a record in the child table, set it's parent_id to 1, then reset the auto-increment counter of the parent table (so that the next insert will have id = 1), it works! But that's not a solution.</p> <p>I don't see the utility of the insert blocking if there is no related row in the child table...</p> <p>I'm just trying to do a one-to-many relationship...</p> <p>(I know I can use JOIN, but I'm trying to use table relations, for data integrity and also as metadata for PHP)</p>
3,544,338
2
0
null
2010-08-23 02:13:30.797 UTC
4
2019-03-29 15:10:24.543 UTC
2019-03-29 15:10:24.543 UTC
null
370,786
null
370,786
null
1
7
mysql|foreign-keys|constraints|auto-increment|database-relations
57,709
<p>It looks like you have the referencing and referenced tables in reverse. You may want to do:</p> <pre><code>ALTER TABLE `child ` ADD FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`); </code></pre> <p>You can also define the foreign key in the <code>CREATE TABLE</code> statement, as follows:</p> <pre><code>CREATE TABLE `parent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `data` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; CREATE TABLE `child` ( `parent_id` int(11) DEFAULT NULL, `related_ids` int(11) DEFAULT NULL, KEY `parent_id` (`parent_id`), KEY `related_ids` (`related_ids`), FOREIGN KEY (`parent_id`) REFERENCES `parent`(`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>Test case:</p> <pre><code>INSERT INTO parent (`data`) VALUES ('test data 1'); Query OK, 1 row affected (0.01 sec) INSERT INTO parent (`data`) VALUES ('test data 2'); Query OK, 1 row affected (0.01 sec) INSERT INTO child (`parent_id`, `related_ids`) VALUES (1, 100); Query OK, 1 row affected (0.01 sec) INSERT INTO child (`parent_id`, `related_ids`) VALUES (2, 100); Query OK, 1 row affected (0.01 sec) INSERT INTO child (`parent_id`, `related_ids`) VALUES (3, 100); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails </code></pre>
3,258,044
c# - WebRequest HTTP POST with Cookie (port from curl script)
<p>The IBM RTC RESTful api gives an example of a shell script for authenticating with the server:</p> <pre><code>COOKIES=./cookies.txt USER=my_user PASSWORD=my_password HOST="https://myJazzServer:9092/jazz" curl -k -c $COOKIES "$HOST/authenticated/identity" curl -k -L -b $COOKIES -c $COOKIES -d j_username=$USER -d j_password=$PASSWORD "$HOST/authenticated/j_security_check" </code></pre> <p>This works perfectly, however i need to authenticate with the server using c#.</p> <p>So far i have the following, but it isn't working (returns the authorization failed page):</p> <pre><code> CookieContainer _cookie; public string _RTC() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myJazzServer.com:9092/jazz/authenticated/identity"); if (_cookie == null) { _cookie = new CookieContainer(); } string a; request.CookieContainer = _cookie; using (var response = request.GetResponse()) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { a = sr.ReadToEnd(); } } byte[] data = (new ASCIIEncoding()).GetBytes("j_username=myUser&amp;j_password=MyPass"); request = (HttpWebRequest)WebRequest.Create("https://myJazzServer.com:9092/jazz/authenticated/j_security_check"); request.Method = "POST"; request.ContentType = "text/html"; request.ContentLength = data.Length; request.CookieContainer = _cookie; Stream reqStream = request.GetRequestStream(); reqStream.Write(data,0,data.Length); string b; using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { b = reader.ReadToEnd(); } } } </code></pre>
3,272,574
2
2
null
2010-07-15 17:04:08.423 UTC
13
2013-06-13 05:26:25.773 UTC
2010-07-17 17:24:45.883 UTC
null
220,299
null
220,299
null
1
13
c#|post|curl|httpwebrequest|jazz
37,922
<p>I would suggest you try the following:</p> <pre><code>public class WebClientEx : WebClient { private CookieContainer _cookieContainer = new CookieContainer(); protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = _cookieContainer; } return request; } } class Program { static void Main() { using (var client = new WebClientEx()) { var response1 = client.DownloadString("https://myJazzServer.com:9092/jazz/authenticated/identity"); var data = new NameValueCollection { { "j_username", "myUser" }, { "j_password", "MyPass" }, }; var response2 = client.UploadValues("https://myJazzServer.com:9092/jazz/authenticated/j_security_check", data); Console.WriteLine(Encoding.Default.GetString(response2)); } } } </code></pre> <p>Also to simplify debugging you could activate tracing by putting this in your app.config:</p> <pre><code>&lt;configuration&gt; &lt;system.diagnostics&gt; &lt;sources&gt; &lt;source name="System.Net.Sockets" tracemode="protocolonly"&gt; &lt;listeners&gt; &lt;add name="System.Net.Sockets" type="System.Diagnostics.TextWriterTraceListener" initializeData="network.log" /&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;/sources&gt; &lt;switches&gt; &lt;add name="System.Net.Sockets" value="Verbose"/&gt; &lt;/switches&gt; &lt;trace autoflush="true" /&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>This will create a detailed log file of the network activity which might simplify debugging.</p>
3,423,620
How do I add and remove Polygons on Google Maps v3?
<p>I'm trying to show and remove polygons onto a Google Map, using v3 of the API. In my JavaScript, I've already got an MVCArray of some custom Lat-Longs.</p> <p>I'm trying to figure out how to add these polygons and then, based upon some other JavaScript event or user action, such as a click on a polygon (that has been rendered), that polygon will be removed.</p> <p>Are any code examples available? I'm struggling to find some; most of them usually go to some v2 code.</p>
3,427,650
2
0
null
2010-08-06 12:12:55.157 UTC
5
2021-12-10 20:40:07.283 UTC
2021-12-10 20:40:07.283 UTC
null
472,495
null
30,674
null
1
17
javascript|google-maps|google-maps-api-3|polygon
42,099
<p>In the API docs, there are a couple of simple examples of <a href="http://code.google.com/apis/maps/documentation/javascript/overlays.html#Polygons" rel="noreferrer">adding a polygon to a map</a>. Here's the initialize() function from the simple <a href="http://code.google.com/apis/maps/documentation/javascript/examples/polygon-simple.html" rel="noreferrer">Bermuda Triangle</a> example with the addition of adding an event listener to remove the polygon when clicked.</p> <pre><code>function initialize() { var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875); var myOptions = { zoom: 5, center: myLatLng, mapTypeId: google.maps.MapTypeId.TERRAIN }; var bermudaTriangle; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var triangleCoords = [ new google.maps.LatLng(25.774252, -80.190262), new google.maps.LatLng(18.466465, -66.118292), new google.maps.LatLng(32.321384, -64.75737), new google.maps.LatLng(25.774252, -80.190262) ]; // Construct the polygon bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35 }); bermudaTriangle.setMap(map); // add an event listener google.maps.event.addListener(bermudaTriangle, 'click', function() { this.setMap(null); }); } </code></pre>
9,460,140
gpg encrypt file without keyboard interaction
<p>I am running next command within a crontab to encrypt a file and I don't want a keyboard interaction</p> <pre><code>echo "PASSPHRASE" | gpg --passphrase-fd 0 -r USER --encrypt FILENAME.TXT </code></pre> <p>but I have this answer:</p> <pre><code>gpg: C042XXXX: There is no assurance this key belongs to the named user pub 40XXX/C042XXXX 2012-01-11 Name LastName. (comment) &lt;[email protected]&gt; Primary key fingerprint: XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX Subkey fingerprint: XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX It is NOT certain that the key belongs to the person named in the user ID. If you *really* know what you are doing, you may answer the next question with yes. Use this key anyway? (y/N) </code></pre>
9,466,566
9
2
null
2012-02-27 04:39:03.303 UTC
14
2021-01-22 21:08:13.257 UTC
2013-12-23 03:40:46.677 UTC
null
351,122
null
351,122
null
1
88
bash|crontab|gnupg
84,993
<p>As David intimated, the problem here is that gpg doesn't trust the public key you're using to encrypt. You could sign the key as he explained.</p> <p>An alternative--especially if the key might be changing occasionally--would be to tack on <code>--trust-model always</code> to your gpg command.</p> <p>Here's the relevant bit from the man page:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>--trust-model pgp|classic|direct|always|auto Set what trust model GnuPG should follow. The models are: pgp This is the Web of Trust combined with trust signatures as used in PGP 5.x and later. This is the default trust model when creating a new trust database. classic This is the standard Web of Trust as used in PGP 2.x and earlier. direct Key validity is set directly by the user and not calculated via the Web of Trust. always Skip key validation and assume that used keys are always fully trusted. You generally won't use this unless you are using some external validation scheme. This option also suppresses the "[uncertain]" tag printed with signature checks when there is no evidence that the user ID is bound to the key. auto Select the trust model depending on whatever the internal trust database says. This is the default model if such a database already exists. </code></pre> </blockquote>
16,173,469
What is server side rendering of javascript?
<p>Some javascript frameworks like Dust.js claim that they ALSO support server-side rendering (in addition to client side rendering) as well. Can someone explain how does this work? My understanding is that the JS is always executed in the browser runtime.</p>
16,173,594
4
4
null
2013-04-23 15:33:30.967 UTC
7
2021-12-18 20:11:25.033 UTC
2013-04-23 15:39:09.823 UTC
null
127,320
null
127,320
null
1
28
javascript|rendering|client-side|dust.js
13,088
<p>JavaScript can be run on servers using systems like <a href="http://nodejs.org/" rel="noreferrer">Node.js</a>.</p> <p>With regard to <a href="http://akdubya.github.io/dustjs/#guide" rel="noreferrer">Dust.js</a>, a templating engine, it can generate hypertext and HTML on the server and send that content directly to the client's browser. This is typically used to avoid a flash of temporarily empty templates, caused by the browser requiring a split second to populate a view's templates via a framework like Dust.js. The downside is that the page will take slightly longer to load because more work has to be done on the server before sending data to the client.</p> <p>Check out <a href="https://stackoverflow.com/questions/8372099/should-i-render-this-template-using-javascript-or-the-server">this question</a> for the pros and cons of server-side rending. One must choose between slow post-processing (requiring the user's browser to do the work) or slow pre-processing (making the server do the work before the user sees anything).</p>
11,044,423
Writing a javascript variable from user input to the document
<p>This seems like it should be relatively straightforward, I cannot figure out what I'm doing wrong. I need to take input (user's name) from the user via textbox, set it as a variable, and display it on the page. I keep getting "undefined" instead of the user's name.</p> <p>Here's a condensed version. This will display a Div that covers the entire page which contains an input for the user to type their name. when the user hits submit the div disappears and the name is set to a variable. I left the form handling functions in case they are relevant to the problem.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;HOME&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;CENTER&gt; &lt;BR /&gt; &lt;FONT COLOR="RED" FACE="ARIAL BOLD" SIZE="5"&gt;test&lt;/FONT&gt; &lt;BR /&gt; &lt;script language="javascript"&gt; var currentTime = new Date(); var month = currentTime.getMonth() + 1; var day = currentTime.getDate(); var year = currentTime.getFullYear(); var name = uservariable; function setName(){ uservariable = document.forms["username"]["user"].value; var ele = document.getElementById("nameInput"); if(ele.style.display == "none") { ele.style.display = "block"; } else { ele.style.display = "none"; } document.getElementById('element_7').value = uservariable; } function validateForm() { var x=document.forms["username"]["user"].value; if (x==null || x=="") { alert("Rembrandt's first name was Beauregard, what is yours?"); } else { setName() } } &lt;/script&gt; &lt;DIV id="nameInput" STYLE="background-color:#ccc;position:fixed;width:100%;height:100%;top:0px;left:0px;z-index:1000;display:block;"&gt; &lt;br /&gt;&lt;br /&gt;&lt;FONT FACE="ARIAL BOLD" SIZE="3"&gt;First Name:&lt;/font&gt;&lt;br /&gt; &lt;form name="username" action="javascript:validateForm()"&gt; &lt;input type="text" name="user" value="" size="20"&gt;&lt;br&gt; &lt;input type="submit" value="Start Shift"&gt; &lt;/form&gt; &lt;/div&gt; &lt;script language="javascript"&gt; document.write(name + "s LEADS SUBMITTED FOR " + month + "/" + day + "/" + year + ":&lt;/B&gt;"); &lt;/script&gt; &lt;/center&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/div&gt; &lt;/CENTER&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
11,044,588
1
2
null
2012-06-15 04:04:54.18 UTC
2
2012-06-15 04:26:42.923 UTC
null
null
null
null
1,444,609
null
1
4
javascript|variables|input
41,354
<pre><code>&lt;head&gt; &lt;script&gt; function doStuff() { var nameElement = document.getElementById("someInput"); var theName = nameElement.value; document.getElementById("someDiv").innerHTML += theName; } &lt;/script&gt; &lt;/head&gt; &lt;html&gt; &lt;div id="someDiv"&gt; Hello &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;input id="someInput" type="text"&gt; &lt;input type="button" value="Say Hello" onClick="doStuff()"&gt; &lt;br&gt; &lt;/html&gt; </code></pre>
28,919,285
Identify slow-to-compile function
<p>I have some cpp files that take a lot to compile. They contain some basic classes/code, with some templates, but nothing to justify compile time on the order of dozens of seconds. </p> <p>I do use a couple of external libs (boost/opencv)</p> <p>This is what gcc says about the compilation time. How can I find the library/include/function call that's to blame for the horrendous compilation time?</p> <pre><code>Execution times (seconds) phase setup : 0.00 ( 0%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 1445 kB ( 0%) ggc phase parsing : 6.69 (46%) usr 1.61 (60%) sys 12.14 (47%) wall 488430 kB (66%) ggc phase lang. deferred : 1.59 (11%) usr 0.36 (13%) sys 3.83 (15%) wall 92964 kB (13%) ggc phase opt and generate : 6.25 (43%) usr 0.72 (27%) sys 10.09 (39%) wall 152799 kB (21%) ggc |name lookup : 1.05 ( 7%) usr 0.28 (10%) sys 2.01 ( 8%) wall 52063 kB ( 7%) ggc |overload resolution : 0.83 ( 6%) usr 0.18 ( 7%) sys 1.48 ( 6%) wall 42377 kB ( 6%) ggc ... </code></pre> <p><a href="https://stackoverflow.com/questions/13559818/profiling-the-c-compilation-process">Profiling the C++ compilation process</a> deals with identifying the slow file, but I'd need more fine-grained information to find the culprit</p> <p>(Other files/projects compile in milliseconds/seconds, so it's not a matter of computer resources. I use gcc 4.9.1)</p>
28,920,293
2
7
null
2015-03-07 19:56:44.42 UTC
10
2015-03-07 22:04:57.793 UTC
2017-05-23 12:32:21.533 UTC
null
-1
null
981,773
null
1
12
c++|performance|gcc|boost|compilation
5,068
<p>There are basically two things that cause long compilation times: too many includes and too many templates.</p> <p>When you are including too many headers and that these headers are including too many headers of their own, it just means that the compiler has a lot of work to do to load all these files and it will spend an inordinate amount of time on the processing passes that it has to do on all code, regardless of whether its actually used or not, like pre-processing, lexical analysis, AST building, etc.. This can be especially problematic when code is spread over a large number of small headers, because the performance is very much I/O bound (lots of time wasted just fetching and reading files from the hard-disk). Unfortunately, Boost libraries tend to be very much structured this way.</p> <p>Here are a couple of ways or tools to solve this problem:</p> <ul> <li>You can use the "<a href="https://code.google.com/p/include-what-you-use/">include-what-you-use</a>" tool. This is a Clang-based analysis tool that basically looks at what you are actually using in your code, and which headers those things come from, and then reports on any potential optimizations you could make by removing certain unnecessary includes, using forward-declarations instead, or maybe replace the broader "all-in-one" headers with the more fine-grained headers.</li> <li>Most compilers have options to dump the preprocessed sources (on GCC / Clang, it's <code>-E</code> or <code>-E -P</code> options, or simply used GCC's C preprocessor program <code>cpp</code> directly). You can take your source file and comment out different include statements or groups of include statements, and dump the preprocessed source to see the total amount of code that these different headers pull in (and maybe use a line count command, like <code>$ g++ -E -P my_source.cpp | wc -l</code>). This could help you identify, in sheer number of lines of code to process, which headers are the worst offenders. Then, you can see what you can do to avoid them or mitigate the issue somehow.</li> <li>You can also use pre-compiled headers. This is a feature supported by most compilers with which you can specify certain headers (especially oft-included "all-in-one" headers) to be pre-compiled to avoid re-parsing them for every source file that includes them.</li> <li>If your OS supports it, you can use a <a href="http://www.jamescoyle.net/how-to/943-create-a-ram-disk-in-linux">ram-disk</a> for your code and the headers of your external libraries. This essentially takes up part of your RAM memory and makes it look like a normal hard-disk / file-system. This can significantly reduce compilation times by reducing the I/O latency, since all the headers and source files are read from RAM memory instead of the actual hard-disk.</li> </ul> <p>The second problem is that of template instantiations. In your time report from GCC, there should be a time value reported somewhere for template instantiation phase. If that number is high, which it will be as soon as there is any significant amount of templates meta-programming involved in the code, then you will need to work on that problem. There are lots of reasons why some template-heavy code can be painfully slow to compile, including deeply recursive instantiation patterns, overly fancy Sfinae tricks, abuse of type-traits and concepts checking, and good old fashion over-engineered generic code. But there are also simple tricks that can fix a lot of issues, like using unnamed namespaces (to avoid all the time wasted generating symbols for instantiations that don't really need to be visible outside the translation unit) and specializing type-traits or concept checks templates (to basically "short-circuit" much of the fancy meta-programming that goes into them). Another potential solution for template instantiations is to use "<a href="http://en.wikipedia.org/wiki/C%2B%2B11#Extern_template">extern templates</a>" (from C++11) to control where specific template instantiations should be instantiated (e.g., in a separate cpp file) and avoid re-instantiating it everywhere it's used.</p> <p>Here are a couple of ways or tools to help you identify the bottlenecks:</p> <ul> <li>You can use the "<a href="https://github.com/mikael-s-persson/templight">Templight</a>" profiling tool (and its auxiliary "<a href="https://github.com/mikael-s-persson/templight-tools">Templight-tools</a>" for dealing with the traces). This is again a Clang-based tool that can be used as a drop-in replacement for the Clang compiler (the tool is actually an instrumented full-blown compiler) and it will generate a complete profile of all the template instantiations that occur during compilation, including the time spent on each (and optionally, memory consumption estimates, although this will affect the timing values). The traces can later be converted to a Callgrind format and be visualized in KCacheGrind, just read the description on that on the <a href="https://github.com/mikael-s-persson/templight-tools#inspecting-the-profiles">templight-tools page</a>. This can basically be used like a typical run-time profiler, but for profiling the time and memory consumption when compiling template-heavy code.</li> <li>A more rudimentary way of going about finding the worst offenders is to create test source files that instantiate particular templates that you suspect are responsible for the long compilation times. Then, you compile those files, time it, and try to work your way (maybe in a "binary search" fashion) towards the worst offenders.</li> </ul> <p>But even with these tricks, identifying template instantiation bottlenecks is easier than actually solving them. So, good luck with that.</p>
17,585,632
how to convert date and time to timestamp in php?
<p>i have a date <code>'07/23/2009'</code> and a time <code>'18:11'</code> and i want to get a timestamp out of it : here is my example:</p> <pre><code>date_default_timezone_set('UTC'); $d = str_replace('/', ', ', '07/23/2009'); $t = str_replace(':', ', ', '18:11'); $date = $t.', 0, '.$d; echo $date; echo '&lt;br&gt;'; echo $x = mktime("$date"); </code></pre> <p>the issue is that <code>$x</code> gives me the current timestamp.</p> <p>any ideas?</p>
17,586,057
5
0
null
2013-07-11 05:25:02.937 UTC
1
2018-09-23 17:21:19.2 UTC
null
null
null
null
642,022
null
1
4
php|date|datetime|timestamp|mktime
46,336
<p>it gives error because mktime function require all values of numbers only and this function gives only date . if you try like</p> <pre><code>$h = 18; $i = 11; $s = 00; $m = 07; $d =23; $y = 2009; echo date("h-i-s-M-d-Y",mktime($h,$i,$s,$m,$d,$y)); </code></pre> <p>then it will work.</p> <p>so your complete code will be</p> <pre><code>date_default_timezone_set('UTC'); $d = str_replace('/', ',', '07/23/2009'); $t = str_replace(':', ',', '18:11'); $date = $t.',0,'.$d; $fulldate = explode(',',$date); echo '&lt;br&gt;'; $h = $fulldate[0]; $i = $fulldate[1]; $s = $fulldate[2]; $m = $fulldate[3]; $d =$fulldate[4]; $y = $fulldate[5]; echo date("h-i-s-M-d-Y",mktime($h,$i,$s,$m,$d,$y)) . "&lt;br&gt;"; </code></pre> <p>//if you want timestamp then use </p> <pre><code>echo strtotime("07/23/2009 18:11"); </code></pre> <p>Thanks</p>
17,358,088
Finding cause of deadlock error from oracle trace file
<p>I have been getting this "ora-00060 deadlock detected while waiting for resource" error often now in my application when multiple users are using the application. I have got the trace file from the oracle Admin, but need help in reading it. Below is bits of data from the trace file, which i hope would help in locating the cause.</p> <pre><code>*** 2013-06-25 09:37:35.324 DEADLOCK DETECTED ( ORA-00060 ) [Transaction Deadlock] The following deadlock is not an ORACLE error. It is a deadlock due to user error in the design of an application or from issuing incorrect ad-hoc SQL. The following information may aid in determining the deadlock: Deadlock graph: ---------Blocker(s)-------- ---------Waiter(s)--------- Resource Name process session holds waits process session holds waits TM-000151a2-00000000 210 72 SX SSX 208 24 SX SSX TM-000151a2-00000000 208 24 SX SSX 210 72 SX SSX session 72: DID 0001-00D2-000000C6 session 24: DID 0001-00D0-00000043 session 24: DID 0001-00D0-00000043 session 72: DID 0001-00D2-000000C6 Rows waited on: Session 72: no row Session 24: no row ----- Information for the OTHER waiting sessions ----- Session 24: sid: 24 ser: 45245 audsid: 31660323 user: 90/USER flags: (0x45) USR/- flags_idl: (0x1) BSY/-/-/-/-/- flags2: (0x40009) -/-/INC pid: 208 O/S info: user: zgrid, term: UNKNOWN, ospid: 2439 image: [email protected] client details: O/S info: user: , term: , ospid: 1234 machine: xyz.local program: current SQL: delete from EMPLOYEE where EMP_ID=:1 ----- End of information for the OTHER waiting sessions ----- Information for THIS session: ----- Current SQL Statement for this session (sql_id=dyfg1wd8xa9qt) ----- delete from EMPLOYEE where EMP_ID=:1 =================================================== </code></pre> <p>I would appreciate if some one can tell me what the "Deadlock graph::" is saying. Also the rows waited on section says no rows. </p> <p>I also read in some blogs that "sqltxt" section from the trace file can suggest the cause. Below is the query i see in that section.</p> <pre><code> select /*+ all_rows */ count(1) from "USERS"."EMPLOYEE_SALARY" where EMPSAL_EMP_ID=:1 </code></pre> <p>The employee_salary table has foreignkey constraint on EMPSAL_EMP_ID column. </p> <p>The sql hint says "all_rows", so does it mean that this table gets table level lock when deleting records from employee table? i dont have an index on the foreign key column currently. Would adding an index on this column help?</p> <p>Kindly post, in case any more information is need.</p> <p>Thanks</p>
17,364,252
1
2
null
2013-06-28 05:54:28.073 UTC
11
2017-11-29 18:05:28.053 UTC
null
null
null
null
829,594
null
1
16
oracle|deadlock|trace
45,302
<p>First of all, <code>select</code> statement never lock anything in Oracle, just uses last available consistent version of data. It's not a case for <code>select ... for update</code> which locks data like <code>update</code> since Oracle 9i, but there are no <code>for update</code> clause in the query from question. </p> <pre><code>Resource Name process session holds waits process session holds waits TM-000151a2-00000000 210 72 SX SSX 208 24 SX SSX </code></pre> <p>Session #72 holds table-level lock (TM) with "Row Exclusive" type (SX) and want to acquire "Share Row Exclusive" (SSX) lock on same table. This session blocked by Session #24 which already holds table-level lock of a same type (SX) and waits while SSX lock would be available.</p> <pre><code>Resource Name process session holds waits process session holds waits TM-000151a2-00000000 208 24 SX SSX 210 72 SX SSX </code></pre> <p>This (second row) demonstrates exactly same situation, but in opposite direction: Session #24 waits for SSX lock become available, but blocked by Session #72 which already holds SX lock on same table.</p> <p>So, Sessions #24 and Session #72 blocks each other: deadlock happens.</p> <p>Both lock types (SX and SSX) are table-level locks.<br> To understand the situation I recommend to read <a href="http://www.soug.ch/fileadmin/user_upload/Newsletter/NL_public/NL_2013_1_Award_Article.pdf">this article</a> by Franck Pachot.</p> <p>Below is citation from this article, which directly relevant to your situation(note that SSX and SRX abbreviations are equivalent):</p> <blockquote> <p>Referential integrity also acquires TM locks. For example, the common issue with unindexed foreign keys leads to S locks on child table when you issue a delete, or update on the key, on the parent table. This is because without an index, Oracle has no single lower level resource to lock in order to prevent a concurrent insert that can violate the referential integrity.<br> When the foreign key columns are the leading columns in a regular index, then the first index entry with the parent value can be used as a single resource and locked with a row level TX lock.<br> And what if referential integrity has an on delete cascade? In addition to the S mode, there is the intention to update rows in the child table, as with Row X (RX) mode. This is where the share row exclusive (SRX) occurs: S+RX=SRX.</p> </blockquote> <p>So, most probable variant is that Session #72 and Session #24 deletes some rows in <code>EMPLOYEE</code> table at same time, and there are <code>on delete cascade</code> constraint for <code>EMPSAL_EMP_ID</code> in conjunction with absence of index on <code>EMPLOYEE_SALARY</code> table in which <code>EMPSAL_EMP_ID</code> column listed first.</p>
24,543,291
Why would scenebuilder 2.0 fail to open my fxml file?
<p>I have an fxml file that I created using SceneBuilder 2.0. This file is used in my JavaFx project that I am developing using Netbeans 8. Today, SceneBuilder stopped working with my file. When I tried to open it, SceneBuilder would minimize and would not open the file. I don't have any custom components in my scene graph. </p> <p>I copied the contents of the file into a new fxml file and gave it a new name. SceneBuilder was then able to open this file even though the contents are identical to the file that it is unable to open. </p> <p>What is going on here? </p> <p>my apologies, but I am unable to post the contents of the fxml file. </p>
26,185,879
7
5
null
2014-07-03 00:42:20.327 UTC
10
2020-08-29 20:06:56.983 UTC
null
null
null
null
1,255,725
null
1
34
javafx|fxml|scenebuilder
35,926
<p>Okay.. so here I am searching for the solution for this weird problem! Seeing none of the other answers working for me, I did the random most thing I could think of and it worked.</p> <p><code>Open SceneBuilder (a brand new one). Go to File &gt; Open Recent &gt; Clear Menu. Close Scene Builder.</code> </p> <p>Now the bug should be fixed (it did for me)</p> <p>PS: I am ashamed of posting this answer. But since this is a nasty bug which wasted time, I don't want anyone else to waste theirs'.</p> <p>PPS: Also, I can't double-check this solution, since it worked for me and I can't recreate the buggy scenario anymore.</p>
24,744,375
Regex for only allowing letters, numbers, space, commas, periods?
<p>I am clueless with regex as it is complicated for me. I am working with a program that limits input from users based on a regex. I am currently after a regex that will only let the user input:</p> <pre><code>A-Z and a-z 0-9 . , ! ? </code></pre> <p>So basically anything in a typical paragraph or web article.</p> <p>The program states "Enter a regular expression which entered text must match (evaluated with preg_match, using s and i flags) for it to be valid."</p> <p>I have tried this regex with no success and I am currently searching for others to try.</p> <pre><code> '/^[a-zA-Z0-9,.!? ]*$/' </code></pre> <p>It should allow a simple sentence such as</p> <blockquote> <p>"HI my name is John! I like to eat apples, oranges, and grapes. Will you eat with me?</p> </blockquote>
24,744,717
3
10
null
2014-07-14 19:31:25.28 UTC
4
2021-04-28 05:40:26.777 UTC
2014-07-14 19:47:52.057 UTC
null
541,091
null
3,838,246
null
1
17
php|regex
45,398
<p><code>^[\.a-zA-Z0-9,!? ]*$</code></p> <p>is what the regex is, it works, see example website to test regex.</p>
27,341,064
How do I fix 'ImportError: cannot import name IncompleteRead'?
<p>When I try to install anything with <code>pip</code> or <code>pip3</code>, I get:</p> <pre class="lang-none prettyprint-override"><code>$ sudo pip3 install python3-tk Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')() File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2476, in load_entry_point return ep.load() File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2190, in load ['__name__']) File "/usr/lib/python3/dist-packages/pip/__init__.py", line 61, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python3/dist-packages/pip/vcs/mercurial.py", line 9, in &lt;module&gt; from pip.download import path_to_url File "/usr/lib/python3/dist-packages/pip/download.py", line 25, in &lt;module&gt; from requests.compat import IncompleteRead ImportError: cannot import name 'IncompleteRead' </code></pre> <p>I have a Ubuntu 14.10 system.</p> <p>How can I fix this problem?</p>
27,425,458
16
7
null
2014-12-07 08:44:01.713 UTC
44
2020-05-01 05:30:40.997 UTC
2019-03-20 05:33:19.433 UTC
null
2,747,593
null
562,769
null
1
287
python|pip
334,068
<p>While <a href="https://stackoverflow.com/a/27341847/2854723">this previous answer</a> might be the reason, this snipped worked for me as a solution (in <code>Ubuntu 14.04</code>):</p> <p>First remove the package from the package manager:</p> <pre class="lang-none prettyprint-override"><code># apt-get remove python-pip </code></pre> <p>And then install the latest version by side:</p> <pre class="lang-none prettyprint-override"><code># easy_install pip </code></pre> <p>(thanks to @Aufziehvogel, @JunchaoGu)</p>
26,694,359
Differences between OT and CRDT
<p>Can someone explain me simply the main differences between Operational Transform and CRDT?</p> <p>As far as I understand, both are algorithms that permits data to converge without conflict on different nodes of a distributed system.</p> <p>In which usecase would you use which algorithm? As far as I understand, OT is mostly used for text and CRDT is more general and can handle more advanced structures right?</p> <p>Is CRDT more powerful than OT? </p> <hr> <p>I ask this question because I am trying to see how to implement a collaborative editor for HTML documents, and not sure in which direction to look first. I saw the ShareJS project, and their attempts to support rich text collaboration on the browser on <code>contenteditables</code> elements. Nowhere in ShareJS I see any attempt to use CRDT for that. </p> <p>We also know that Google Docs is using OT and it's working pretty well for real-time edition of rich documents. Is Google's choice of using OT because CRDT was not very known at that time? Or would it be a good choice today too?</p> <p>I'm also interested to hear about other use cases too, like using these algorithms on databases. Riak seems to use CRDT. Can OT be used to sync nodes of a database too and be an alternative to Paxos/Zab/Raft?</p>
27,494,397
1
2
null
2014-11-01 23:28:46.117 UTC
40
2018-10-12 03:24:48.597 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
82,609
null
1
95
algorithm|paxos|operational-transform|crdt|nosql
16,787
<p>Both approaches are similar in that they provide eventual consistency. The difference is in how they do it. One way of looking at it is:</p> <ul> <li>OT does it by changing <strong>operations</strong>. Operations are sent over the wire and concurrent operations are transformed once they are received. </li> <li>CRDTs do it by changing <strong>state</strong>. Operations are made on the local CRDT. Its state is sent over the wire and is merged with the state of a copy. It doesn't matter how many times or in what order merges are made - all copies converge.</li> </ul> <p>You're right, OT is mostly used for text and does predate CRDTs but <a href="http://www-sop.inria.fr/orion/COGC/teams/ECOOjournal.pdf" rel="noreferrer">research</a> shows that:</p> <blockquote> <p>many OT algorithms in the literature do not satisfy convergence properties unlike what was stated by their authors</p> </blockquote> <p>In other words CRDT merging is commutative while OT transformation functions sometimes are not.</p> <p>From the <a href="http://en.wikipedia.org/wiki/Conflict-free_replicated_data_type" rel="noreferrer">Wikipedia article on CRDT</a>:</p> <blockquote> <p>OTs are generally complex and non-scalable</p> </blockquote> <p>There are different kinds of CRDTs (sets, counters, ...) suited for different kinds of problems. There are some that are designed for text editing. For example, Treedoc - <a href="https://hal.inria.fr/file/index/docid/445975/filename/icdcs09-treedoc.pdf" rel="noreferrer">A commutative replicated data type for cooperative editing</a>. </p>
17,473,398
Java SFTP upload using JSch, but how to overwrite the current file?
<p>I am trying to upload two files to a server with SFTP using JSch. It works fine to upload the files if the directory is empty but I want to upload the same file over and over (just changing an id inside) but I can't figure out how to do this. There is some static parameter in JSch called OVERWRITE but I can't find out how to use it.</p> <p>Anyone care to show me how I should add this setting?</p> <p>This is my current code:</p> <pre><code>public void upload() { try { JSch jsch = new JSch(); session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT); session.setPassword(SFTPPASS); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel; channelSftp.cd(SFTPWORKINGDIR); File f1 = new File("ext_files/" + FILETOTRANSFER1); channelSftp.put(new FileInputStream(f1), f1.getName()); File f2 = new File("ext_files/" + FILETOTRANSFER2); channelSftp.put(new FileInputStream(f2), f2.getName()); channelSftp.exit(); session.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } </code></pre>
17,476,038
1
0
null
2013-07-04 14:59:29.967 UTC
4
2013-07-04 18:01:07.5 UTC
null
null
null
null
928,408
null
1
19
java|upload|sftp|jsch
46,039
<p>I've never used JSch but from the looks of it there are a number of overloaded put methods where one matches your current signature with the addition of a "mode" parameter and there seems to be three static mode parameters in the ChannelSftp class (OVERWRITE = 0, RESUME = 1, APPEND = 2) so you should be able to use:</p> <p><code>channelSftp.put(new FileInputStream(f1), f1.getName(), ChannelSftp.OVERWRITE);</code></p>
17,156,445
Why I get this error writing data to a file
<p>I have this code</p> <pre><code>myvector &lt;- c(3.45235, 1.32525, ... , 2.41351) # some numbers write(myvector, "C:/mypath/myfile.txt") # I use "/" instead of "\" </code></pre> <p>and I get the following error:</p> <blockquote> <p>Error in file(file, ifelse(append, "a", "w")) : cannot open the connection In addition: warning message: In file(file, ifelse(append, "a", "w")) : cannot open file 'C:/mypath/myfile.txt' : No such file or directory</p> </blockquote> <p>I read <a href="http://stat.ethz.ch/R-manual/R-patched/library/base/html/write.html" rel="noreferrer">this tutorial</a>, but I can't understant what's wrong with my code. Any idea?</p> <p><strong>edit</strong>:</p> <p>As @dickoa pointed out, I need an existing path to write a file, so I tried to simplify in the following way:</p> <pre><code>file.exists("C:/") write(myvector, "C:/myfile.txt") </code></pre> <p><em>Surprisingly</em> :P the path "C:/" exists (the result is TRUE) but I get a similar error:</p> <blockquote> <p>Error in file(file, ifelse(append, "a", "w")) : cannot open the connection In addition: warning message: In file(file, ifelse(append, "a", "w")) : cannot open file 'C:/mypath/myfile.txt' : Permission denied</p> </blockquote>
17,159,269
5
12
null
2013-06-17 20:40:37.183 UTC
2
2020-09-24 07:17:45.587 UTC
2015-12-06 10:22:30.22 UTC
null
4,370,109
null
1,749,584
null
1
21
r|file
133,334
<p>I know @dickoa answered the question in the comments, but in order to provide at least one answer here, I wanted to go through a few simple gotchas with R on Windows.</p> <ol> <li>When you are using Windows, you still have to use forward slashes for paths. In R, backslashes are reserved for escaping values. So a path in R looks like: <code>C:/path/to/my/directory</code></li> <li>In newer variants of Windows, the C:\ is protected from writes by user accounts. If you want to write to the C:\, you must be an administrator. You can accomplish this by right-clicking on the R icon in Windows and choosing "Run as an administrator." This should also be done when you're installing packages. You may not have rights to install packages on certain Windows versions if you don't run it as an administrator. </li> <li>If you don't want to run R as an administrator, and you want to write to files, you will by default have rights to the <code>C:/Users/username/</code> directory.</li> </ol> <p>All credit to @dickoa again for his answer in first.</p> <p>Best of luck!</p>
17,281,556
What's the conceptual difference between Machines and Conduits (or other similar libraries)?
<p>I'd like to learn the concept, so that I'd be able to understand and use libraries such as <a href="http://hackage.haskell.org/package/machines">machines</a>.</p> <p>I tried to follow <a href="https://dl.dropbox.com/u/4588997/Machines.pdf">Rúnar Bjarnason's talk on machines</a>, but there is too little information, basically just a bunch of data types. I can't even understand what <code>k</code> is in</p> <pre><code>newtype Machine k o = Step k o (Machine k o) data Step k o r = Stop | Yield o r | forall t . Await (t -&gt; r) (k t) r </code></pre> <p>or what's <code>t</code> is and why it's quantified. Or, what's the conceptual difference between <em>conduit</em>-like libraries and <em>machines</em>?</p>
17,282,019
1
0
null
2013-06-24 17:36:42.53 UTC
13
2013-08-04 11:29:12.487 UTC
2013-08-04 11:29:12.487 UTC
null
387,076
null
1,333,025
null
1
29
haskell|conduit|transducer-machines
2,848
<p><code>conduit</code> and <code>pipes</code> are both far more mature than <code>machines</code>, but -- that said -- <code>machines</code> is trying to take a different path than <code>conduit</code> and <code>pipes</code>.</p> <p>With <code>machines</code>, I'm trying for a relatively simple API in terms of type arguments. Both <code>conduit</code> and <code>pipes</code> have chosen to unify all of their concepts by using 5-6 different type variable arguments.</p> <p>Machines takes a different approach of parameterizing a machine (or <code>Plan</code>) on its "input language", which puts all the onus on a single extra argument (or two in the case of a <code>Plan</code>). Also by choosing to parameterize the input language in this way it opens up possibilities of using machines that can accept input (non-)deterministically from multiple input sources. The result is basically just a free monad with an extra 'emit' instruction!</p> <p>In exchange for a slightly more rigorous policy about how you build and use machines, it can eventually offer better safety about asymptotics of the resulting code.</p> <p>That said, <code>pipes</code> and <code>conduit</code> have had a lot of real world use and <code>machines</code> is more or less a playground for me, Rúnar Bjarnason and Paul Chiusano.</p> <p>It is currently suitable for working on input that you intend to consume entirely, but less so for working with complicated resources or for parsing than what you get with those other two APIs.</p> <p><em>Now, about that quantifier!</em></p> <p><code>t</code> there is actually existentially quantified. By doing so we can make the <code>Monad</code> for machines not care about the functoriality of the <code>k</code> parameter. This is important because of the way <code>Source</code> is implemented. If I didn't need <code>Source</code> to work, then we could use the simpler</p> <pre><code>data Step k o r = Stop | Yield o r | Await (k r) r </code></pre> <p>This would have the unfortunate side-effect that when you went to compose a Machine with a <code>Source</code>, that the compiler wouldn't know what <code>Functor</code> instance to pick and you'd be swimming in unnecessary type annotations.</p> <p>The existential quantification there is a trick I picked up when working on the <code>kan-extensions</code> package. It is a generalization of one of the <code>Yoneda</code> types from there.</p>
17,490,286
Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?
<p>I have a scenario in my app, where I want to do some time consuming task which consists of some data processing as well as UI update, in a method. My method looks like this,</p> <pre><code>- (void)doCalculationsAndUpdateUIs { // DATA PROCESSING 1 // UI UPDATE 1 // DATA PROCESSING 2 // UI UPDATE 2 // DATA PROCESSING 3 // UI UPDATE 3 } </code></pre> <p>As it is time consuming I wanted to do the data processing on the background thread, using,</p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{ </code></pre> <p>But as both data processing and UI updates are in the same method, I wanted to move only the UI updates in main thread using,</p> <pre><code>dispatch_async(dispatch_get_main_queue(), ^{ </code></pre> <p>Finally my method looks like this,</p> <pre><code>- (void)doCalculationsAndUpdateUIs { // DATA PROCESSING 1 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 1 }); /* I expect the control to come here after UI UPDATE 1 */ // DATA PROCESSING 2 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 2 }); /* I expect the control to come here after UI UPDATE 2 */ // DATA PROCESSING 3 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 3 }); } </code></pre> <p>Does this really work? Is this really a good practice? What is the best way to achieve this?</p> <p>P.S. All these three operations are interrelated to each other.</p> <hr> <p><strong>EDIT:</strong> Sorry guys. I have <strong>missed a line in the above code</strong>. My actual code looks like this.</p> <pre><code>- (void)doCalculationsAndUpdateUIs { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // DATA PROCESSING 1 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 1 }); /* I expect the control to come here after UI UPDATE 1 */ // DATA PROCESSING 2 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 2 }); /* I expect the control to come here after UI UPDATE 2 */ // DATA PROCESSING 3 dispatch_async(dispatch_get_main_queue(), ^{ // UI UPDATE 3 }); }); } </code></pre> <p>Once again, I really apologize for the confusion.</p>
17,490,329
8
4
null
2013-07-05 13:39:59.727 UTC
30
2018-12-12 18:34:50.46 UTC
2016-09-02 23:55:22.607 UTC
null
483,046
null
491,980
null
1
49
ios|objective-c|multithreading|grand-central-dispatch|dispatch-async
114,188
<p>No it doesn't wait and the way you are doing it in that sample is not good practice.</p> <p><code>dispatch_async</code> is always <strong>asynchronous</strong>. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code. </p> <p>If you want the update to wait you can use <code>dispatch_sync</code> instead.</p> <pre><code>// This will wait to finish dispatch_sync(dispatch_get_main_queue(), ^{ // Update the UI on the main thread. }); </code></pre> <p>Another approach would be to nest enqueueing the block. I <em>wouldn't</em> recommend it for multiple levels though. </p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Background work dispatch_async(dispatch_get_main_queue(), ^{ // Update UI dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Background work dispatch_async(dispatch_get_main_queue(), ^{ // Update UI }); }); }); }); </code></pre> <p>If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.</p>
17,613,726
netbeans shows "Waiting For Connection (netbeans-xdebug)"
<p>need help to configure xdebug, for debugging projects from IDE netbeans.</p> <p>These are the features of my components:</p> <p>XAMPP 1.8.2 </p> <p>PHP: 5.4.16</p> <p>netbeans: 7.3.1</p> <p>Apache: 2.4.4 (Win32) </p> <p>this is the final part of my php.ini file:</p> <pre><code> [XDebug] zend_extension = "C:\xampp\php\ext\php_xdebug-2.2.3-5.4-vc9-nts.dll" ;xdebug.profiler_append = 0 ;xdebug.profiler_enable = 1 ;xdebug.profiler_enable_trigger = 0 xdebug.profiler_output_dir = "C:\xampp\tmp" ;xdebug.profiler_output_name = "cachegrind.out.%t-%s" xdebug.remote_enable = 1 xdebug.remote_handler = "dbgp" xdebug.remote_host = "127.0.0.1" ;xdebug.trace_output_dir = "C:\xampp\tmp" </code></pre> <p>when I run phpinfo(), there is no xdebug installed, and when I debug a project from netbeans, it says "Waiting For Connection (netbeans-xdebug)".</p> <p>can someone help me to configure it? would be very appreciated.</p> <p>thanks in advance.</p>
18,418,779
23
6
null
2013-07-12 11:16:28.403 UTC
32
2021-05-27 09:26:05.403 UTC
2018-02-21 23:34:04.507 UTC
null
2,005,680
null
1,816,322
null
1
73
php|windows|apache|netbeans|xdebug
86,084
<p>Have you rectified the issue ? If not then please try this. </p> <p>1.) <code>php.ini</code> file content</p> <pre><code>[xDebug] zend_extension = "c:\xampp\php\ext\php_xdebug-2.2.3-5.4-vc9.dll" xdebug.remote_autostart=on xdebug.remote_enable=on xdebug.remote_enable=1 xdebug.remote_handler="dbgp" ;xdebug.remote_host="localhost:81" xdebug.remote_host=192.168.1.5 ;xdebug.remote_connect_back=1 xdebug.remote_port=9000 xdebug.remote_mode=req xdebug.idekey="netbeans-xdebug" </code></pre> <p><code>xdebug.remote_host=192.168.1.5</code> - This is the IPv4 address of my system, I changed to this because I couldn't debug with <code>localhost</code> and <code>127.0.0.1</code>.</p> <p>in NetBeans IDE, open <code>Tools-&gt; Options -&gt; PHP -&gt; Debugging</code>. The values of debugger port and Session Id should match with the port and idekey specified in <code>php.ini</code>.</p> <p>Now save php.ini, restart Apache and try to debug.</p> <p>Thanks Johnson</p>
17,578,115
Pass percentiles to pandas agg function
<p>I want to pass the numpy <code>percentile()</code> function through pandas' <code>agg()</code> function as I do below with various other numpy statistics functions.</p> <p>Right now I have a dataframe that looks like this:</p> <pre><code>AGGREGATE MY_COLUMN A 10 A 12 B 5 B 9 A 84 B 22 </code></pre> <p>And my code looks like this:</p> <pre><code>grouped = dataframe.groupby('AGGREGATE') column = grouped['MY_COLUMN'] column.agg([np.sum, np.mean, np.std, np.median, np.var, np.min, np.max]) </code></pre> <p>The above code works, but I want to do something like</p> <pre><code>column.agg([np.sum, np.mean, np.percentile(50), np.percentile(95)]) </code></pre> <p>I.e., specify various percentiles to return from <code>agg()</code>.</p> <p>How should this be done?</p>
17,578,653
14
1
null
2013-07-10 18:22:46.707 UTC
26
2022-07-29 10:37:33.88 UTC
2021-10-02 14:07:09.273 UTC
null
13,990,016
null
1,700,913
null
1
94
python|pandas|numpy|aggregate
92,653
<p>Perhaps not super efficient, but one way would be to create a function yourself:</p> <pre><code>def percentile(n): def percentile_(x): return np.percentile(x, n) percentile_.__name__ = 'percentile_%s' % n return percentile_ </code></pre> <p>Then include this in your <code>agg</code>:</p> <pre><code>In [11]: column.agg([np.sum, np.mean, np.std, np.median, np.var, np.min, np.max, percentile(50), percentile(95)]) Out[11]: sum mean std median var amin amax percentile_50 percentile_95 AGGREGATE A 106 35.333333 42.158431 12 1777.333333 10 84 12 76.8 B 36 12.000000 8.888194 9 79.000000 5 22 12 76.8 </code></pre> <p>Note sure this is how it <em>should</em> be done though...</p>
26,145,917
Observable which does not pass anything in onNext()
<p>I would need an Observable, for example to provide a system clock, which does not need to pass anything in onNext(). I couldn't find a signature that would allow me to do that.</p> <p>Sure, I could use any object and then pass null, but that doesn't make much sense. So my question is if there is a better way to do that.</p> <pre><code>Observable.create(new Observable.OnSubscribe&lt;Anyobject&gt;() { // use any object in the signature @Override public void call(Subscriber&lt;? super Anyobject&gt; subscriber) { subscriber.onNext(null); // then pass null subscriber.onCompleted(); } }) </code></pre>
26,147,278
6
2
null
2014-10-01 16:19:35.623 UTC
7
2019-04-08 09:57:50.287 UTC
2014-10-03 17:37:06.743 UTC
null
48,136
null
3,642,107
null
1
46
java|rx-java
46,438
<p>You don't need to call <code>onNext</code> if your <code>Observable</code> doesn't emit anything. You could use <code>Void</code> in your signature and do something like</p> <pre><code>Observable&lt;Void&gt; o = Observable.create(new Observable.OnSubscribe&lt;Void&gt;() { @Override public void call(Subscriber&lt;? super Void&gt; subscriber) { // Do the work and call onCompleted when you done, // no need to call onNext if you have nothing to emit subscriber.onCompleted(); } }); o.subscribe(new OnCompletedObserver&lt;Void&gt;() { @Override public void onCompleted() { System.out.println("onCompleted"); } @Override public void onError(Throwable e) { System.out.println("onError " + e.getMessage()); } }); </code></pre> <p>You can define an OnCompletedObserver to simplify your Observer callback so that you don't have to override the onNext since you don't need it.</p> <pre><code>public abstract class OnCompletedObserver&lt;T&gt; implements Observer&lt;T&gt; { @Override public void onNext(T o) { } } </code></pre> <p>If I've understood what you're asking then this should do the trick.</p>
25,977,803
Steam web API getting CS:GO inventory
<p>Alright, so I have been looking for this all over the internet, and what I have found out is that when you want to get someones steam inventory you use this:</p> <pre><code>http://api.steampowered.com/IEconItems_{appid}/GetPlayerItems/v0001/?key={apikey}&amp;steamid={steamid}&amp;format=json </code></pre> <p>But the problem is that when I do that for CS:GO (appid: <code>730</code>), I just get an empty response back, even though the user has items in their inventory.</p>
26,011,027
1
4
null
2014-09-22 15:28:25.93 UTC
10
2018-04-04 18:44:04.683 UTC
2018-04-04 18:44:04.683 UTC
null
9,070,242
null
3,414,761
null
1
10
json|steam|steam-web-api
29,253
<p>if you want to get the json just use one of the following links:</p> <p>general steam inventory: ( 1: games, 3: coupons, 6: trading cards, 7: rewards )</p> <pre><code>http://steamcommunity.com/id/&lt;USERURL&gt;/inventory/json/753/1 http://steamcommunity.com/profiles/&lt;STEAMID&gt;/inventory/json/753/1 http://steamcommunity.com/id/&lt;USERURL&gt;/inventory/json/753/3 http://steamcommunity.com/profiles/&lt;STEAMID&gt;/inventory/json/753/3 http://steamcommunity.com/id/&lt;USERURL&gt;/inventory/json/753/6 http://steamcommunity.com/profiles/&lt;STEAMID&gt;/inventory/json/753/6 http://steamcommunity.com/id/&lt;USERURL&gt;/inventory/json/753/7 http://steamcommunity.com/profiles/&lt;STEAMID&gt;/inventory/json/753/7 </code></pre> <p>games :</p> <pre><code>http://steamcommunity.com/id/&lt;USERURL&gt;/inventory/json/&lt;APPID&gt;/2 http://steamcommunity.com/profiles/&lt;STEAMID&gt;/inventory/json/&lt;APPID&gt;/2 </code></pre> <p>the problem was not the counter-strike appid, you just used an old link that only works for the general steam inventory. I suggest you using the link using STEAMID because not every steamuser has set a customurl.</p>
25,550,518
Add EventHandler to ImageView contained in TilePane contained in VBox?
<p>I have the following schema:</p> <ul> <li>A VBox, containing a HBox and a TilePane. </li> </ul> <p>In HBox are buttons, labels, and text fields.</p> <p>Every time I click on the root (HBox), I should add a ImageView to the tile pane. This ImageView shold contain an image (example: "2.jpg"). Maximum of tile pane components is 5.</p> <p>Every time I click the image, i should load a new image to the clicked ImageView, exemple "1.jpg". It is not working. When I click on my image it is like i'm clicking on the root so it creates another cell of TilePane. Here's the code, can you help me?</p> <pre><code>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dadao1; import java.util.HashSet; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * * @author Ambra */ public class Dadao1 extends Application { VBox root; HashSet dadi = new HashSet(); //static int numeroDadi = 0; @Override public void start(Stage primaryStage) { setGui(); Scene scene = new Scene(root, 300, 300); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** *This private method sets up the GUI. * No parameters are required */ private void setGui(){ root = new VBox(); HBox buttons = new HBox(); final Button newGame = new Button("New Game"); final Button print = new Button("Print"); final Button animation = new Button("Moving"); animation.addEventHandler(ActionEvent.ACTION, new EventHandler&lt;ActionEvent&gt;() { // this button is labeled "Moving" at the begin. If pressed it changes its label to "Dissolving" and viceversa. @Override public void handle(ActionEvent event) { if (animation.getText().equals(new String("Moving"))) animation.setText("Dissolving"); else animation.setText("Mooving"); } }); final Label score = new Label("Total"); final TextField points = new TextField(); final Label pointsLabel = new Label("Score"); root.setStyle("-fx-background-color: green"); buttons.getChildren().addAll(newGame,print,animation,score,points,pointsLabel); final TilePane dadiPane = new TilePane(); dadiPane.setVgap(10); dadiPane.setHgap(10); root.getChildren().addAll(buttons, dadiPane); root.setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { if(dadi.size()&lt;5){ System.out.println("Adding img"); final ImageView img = new ImageView("2.jpg"); // should I put final in front of ImageView? img.addEventHandler(ActionEvent.ACTION, new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent event) { // I want that when a tile is pressed an event occours. // that event should be "add a new image to the ImageView just clicked", // for example: img is not "2.jpg" but "3.jpj", by the way, I'm not able neither // to to print the folowing messagge :( // It's like my root is pressed even if my mouse ha clicked at the image in img var. System.out.println("Tile pressed "); } }); dadi.add(img); dadiPane.getChildren().add(img); }else System.out.println("You cannot create more than 5 dices"); } }); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } } </code></pre>
25,554,726
3
2
null
2014-08-28 13:50:25.027 UTC
null
2019-05-15 09:09:41.653 UTC
2016-10-22 23:29:50.233 UTC
null
59,087
null
3,728,918
null
1
7
events|javafx|mouseevent
39,083
<p><code>ImageView</code>s don't generate <code>ActionEvent</code>s; so it is no surprise that your event handler is never invoked. Since the mouse event is not processed by the <code>ImageView</code>, it propagates up to the container.</p> <p>Try</p> <pre><code>img.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler&lt;MouseEvent&gt;() { @Override public void handle(MouseEvent event) { System.out.println("Tile pressed "); event.consume(); } }); </code></pre>
9,343,381
WPF Command Line Arguments, a smart way?
<p>I'm looking for a way that I can parse command line arguments into my WPF application with just a way of reading the value of the argument that the user passed.</p> <p>As an example</p> <pre><code>application.exe /setTime 5 </code></pre> <p>is there a way for me to have some code where I can just say:</p> <pre><code>MessageBox.Show(arg("setTime")); </code></pre> <p>Which will output <code>5</code></p> <p><strong>Working Solution</strong></p> <p><a href="http://sa.ndeep.me/post/how-to-create-smart-wpf-command-line-arguments" rel="noreferrer">How to create smart WPF Command Line Arguments</a></p>
9,343,419
3
4
null
2012-02-18 17:25:17.78 UTC
14
2020-07-03 09:59:39.047 UTC
2016-11-10 10:20:46.733 UTC
null
251,671
null
251,671
null
1
59
c#|wpf|command-line-arguments
73,733
<p>The way I always do it is to specify the arguments as a "name"/"value" pair e.g.</p> <pre><code>myprogram.exe -arg1 value1 -arg2 value2 </code></pre> <p>This means that when you parse the command line you can put the argument/value pairs in a <code>Dictionary</code> with the argument as the key. Then your <code>arg("SetTime")</code> will become:</p> <pre><code>MessageBox.Show(dictionary["SetTime"]); </code></pre> <p>(Obviously you don't want the actual dictionary to be public.)</p> <p>To get the arguments in the first place you can use:</p> <pre><code>string[] args = Environment.GetCommandLineArgs(); </code></pre> <p>This will return all the arguments so you will need to parse the array in steps of two (after first checking that the length is a multiple of two + 1):</p> <p>The first element of the array is the name of the executing program - <a href="http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs.aspx" rel="noreferrer">MSDN Page</a> - so your loop needs to start from one:</p> <pre><code>for (int index = 1; index &lt; args.Length; index += 2) { dictionary.Add(args[index], args[index+1]); } </code></pre> <p>This loops in steps of two as you define each argument is a pair of values: the identifier and the actual value itself, e.g.</p> <pre><code>my.exe -arg1 value1 -arg2 value2 </code></pre> <p>Then you can simply see if the argument is specified by seeing if the key <code>-arg1</code> is in the dictionary and then read it's value:</p> <pre><code>string value; if (dictionary.TryGetValue(arg, out value)) { // Do what ever with the value } </code></pre> <p>This means you can have the arguments in any order and omit any arguments you don't want to specify.</p> <p>The only drawback with this method is if you have a flag like <code>-debug</code> (for example) which could be logically implemented with the presence or absence of the flag will need to be specified as <code>-debug true</code> (or <code>1</code> or <code>on</code>), but it does simplify things if you have flags that <em>do</em> require values (like configuration file paths, database connection strings etc.)</p>
20,054,538
Add a bash script to path
<p>I want to add a small script to the linux PATH so I don't have to actually run it where it's physically placed on disk.</p> <p>The script is quite simple is about giving apt-get access through a proxy I made it like this:</p> <pre><code>#!/bin/bash array=( $@ ) len=${#array[@]} _args=${array[@]:1:$len} sudo http_proxy="http://user:password@server:port" apt-get $_args </code></pre> <p>Then I saved this as apt-proxy.sh, set it to +x (chmod) and everything is working fine when I am in the directory where this file is placed.</p> <p>My question is : how to add this <strong>apt-proxy</strong> to <strong>PATH</strong> so I can actually call it as if it where the real apt-get ? [from anywhere]</p> <p>Looking for command line only solutions, if you know how to do by GUI its nice, but <strong>not what I am looking for</strong>.</p>
20,054,809
5
3
null
2013-11-18 18:00:06.09 UTC
11
2022-09-21 07:22:45.797 UTC
null
null
null
null
2,188,186
null
1
49
linux|bash|shell|path
121,680
<p>Try this:</p> <ul> <li>Save the script as <code>apt-proxy</code> (without the <code>.sh</code> extension) in some directory, like <code>~/bin</code>.</li> <li>Add <code>~/bin</code> to your <code>PATH</code>, typing <code>export PATH=$PATH:~/bin</code></li> <li>If you need it permanently, add that last line in your <code>~/.bashrc</code>. If you're using <code>zsh</code>, then add it to <code>~/.zshrc</code> instead.</li> <li>Then you can just run <code>apt-proxy</code> with your arguments and it will run anywhere.</li> </ul> <p>Note that if you <code>export</code> the PATH variable in a specific window it won't update in other bash instances.</p>
15,318,357
Show/hide image with JavaScript
<p>I have an HTML page with an image that I set to be invisible by CSS <code>visibility: hidden</code>. I want to make a link called "Show image", so that when I click on it, the image appears. </p> <p>Now, I don't know how to make such a link, since normally a link with <code>&lt;a href=...&gt;</code> links to some other page. In my case, I want the link to invoke a JavaScript to display the image.</p>
15,318,372
6
0
null
2013-03-10 02:52:35.263 UTC
8
2018-01-29 00:38:46.263 UTC
null
null
null
null
1,798,675
null
1
26
javascript|html
234,812
<p>If you already have a JavaScript function called <code>showImage</code> defined to show the image, you can link as such:</p> <pre><code>&lt;a href="javascript:showImage()"&gt;show image&lt;/a&gt; </code></pre> <p>If you need help defining the function, I would try:</p> <pre><code>function showImage() { var img = document.getElementById('myImageId'); img.style.visibility = 'visible'; } </code></pre> <p>Or, better yet,</p> <pre><code>function setImageVisible(id, visible) { var img = document.getElementById(id); img.style.visibility = (visible ? 'visible' : 'hidden'); } </code></pre> <p>Then, your links would be:</p> <pre><code>&lt;a href="javascript:setImageVisible('myImageId', true)"&gt;show image&lt;/a&gt; &lt;a href="javascript:setImageVisible('myImageId', false)"&gt;hide image&lt;/a&gt; </code></pre>
15,260,732
Does Typescript support the ?. operator? (And, what's it called?)
<p>Does Typescript currently (or are there plans to) support the <a href="http://mrhaki.blogspot.com.au/2009/08/groovy-goodness-safe-navigation-to.html">safe navigation</a> operator of <code>?.</code></p> <p>ie:</p> <pre><code>var thing = foo?.bar // same as: var thing = (foo) ? foo.bar : null; </code></pre> <p>Also, is there a more common name for this operator (it's incedibly hard to google for).</p>
15,260,828
15
9
null
2013-03-07 00:11:24.4 UTC
75
2022-03-22 12:53:25.963 UTC
2013-03-07 01:36:09.663 UTC
null
59,015
null
59,015
null
1
552
typescript
375,164
<p><strong>Yes.</strong> As of TypeScript 3.7 (released on <a href="https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/" rel="noreferrer">November 5, 2019</a>), this feature is supported and is called <strong>Optional Chaining</strong>:</p> <blockquote> <p>At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a <code>null</code> or <code>undefined</code>. The star of the show in optional chaining is the new <code>?.</code> operator for <em>optional property accesses</em>.</p> </blockquote> <p>Refer to the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining" rel="noreferrer">TypeScript 3.7 release notes</a> for more details.</p> <hr /> <p>Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as <a href="http://github.com/Microsoft/TypeScript/issues/16" rel="noreferrer">Issue #16 on the TypeScript repo</a> (dating back to 2014).</p> <p>As far as <strong>what to call this operator</strong>, there doesn't appear to be a consensus. In addition to &quot;optional chaining&quot; (which is also what it's called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">in JavaScript</a> and <a href="https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html" rel="noreferrer">Swift</a>), there are a couple of other examples:</p> <ul> <li>CoffeeScript refers to it as the <a href="https://coffeescript.org/#existential-operator" rel="noreferrer"><strong>existential operator</strong></a> (specifically, the &quot;accessor variant&quot; of the existential operator):</li> </ul> <blockquote> <p>The accessor variant of the existential operator <code>?.</code> can be used to soak up null references in a chain of properties. Use it instead of the dot accessor <code>.</code> in cases where the base value may be <strong>null</strong> or <strong>undefined</strong>.</p> </blockquote> <ul> <li>C# calls this a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-" rel="noreferrer"><strong>null-conditional operator</strong></a>.</li> </ul> <blockquote> <p>a null-conditional operator applies a member access, <code>?.</code>, or element access, <code>?[]</code>, operation to its operand only if that operand evaluates to non-null; otherwise, it returns <code>null</code>.</p> </blockquote> <ul> <li>Kotlin refers to it as the <a href="https://kotlinlang.org/docs/null-safety.html#safe-calls" rel="noreferrer"><strong>safe call operator</strong></a>.</li> </ul> <p>There are probably lots of other examples, too.</p>
15,237,073
D3.js: "Uncaught SyntaxError: Unexpected token ILLEGAL"?
<p>I've just <a href="http://d3js.org/d3.v3.zip" rel="noreferrer">downloaded D3.js from d3js.org</a> (link to zip file), unzipped it, and referenced it in the following HTML page: </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;D3 Sandbox&lt;/title&gt; &lt;style&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="/d3.v3.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But when I load this page, my console (in Chrome) is giving me this error: </p> <pre><code>Uncaught SyntaxError: Unexpected token ILLEGAL: line 2 </code></pre> <p>It doesn't like the <a href="https://github.com/mbostock/d3/blob/master/d3.js#L2" rel="noreferrer">pi and e symbols at the start of the file</a>. Errrr... what can I do about this? I am serving the file with python's SimpleHTTPServer.</p> <p>Update: yes I know I can just link to a CDN version, but I would prefer to serve the file locally. </p>
15,717,101
5
1
null
2013-03-06 00:57:25.847 UTC
6
2018-10-23 17:40:59.513 UTC
null
null
null
null
194,000
null
1
77
javascript|d3.js
22,332
<p>Try specifying the UTF-8 charset on the HTML host document :</p> <p><code>&lt;meta http-equiv="content-type" content="text/html; charset=UTF8"&gt;</code></p> <p>D3 contains UTF-8 symbols (like π) invalids in non-UTF8 documents.</p>
15,029,860
How to convert a datetime to string in T-SQL
<p>I'm surprised not to be able to find this question here already.</p> <p>I have a date time var and I want to convert it to a string so that I can append it to another string. I want it in a format that can be converted easily back to a date time.</p> <p>How can I do this?</p> <p>(I want the date part and the time part.)</p>
15,029,872
10
2
null
2013-02-22 17:24:34.303 UTC
15
2021-04-29 04:47:10.113 UTC
null
null
null
null
127,434
null
1
106
sql-server|tsql
347,156
<p>The following query will get the current datetime and convert into string. with the following format <br><code>yyyy-mm-dd hh:mm:ss(24h)</code></p> <pre><code>SELECT convert(varchar(25), getdate(), 120) </code></pre> <ul> <li><a href="http://www.sqlfiddle.com/#!3/d41d8/9341" rel="noreferrer">SQLFiddle Demo</a></li> <li><a href="http://www.sql-server-helper.com/tips/date-formats.aspx" rel="noreferrer">SQL Server Date Formats</a></li> </ul>
9,080,403
UPDATE with ORDER BY and LIMIT not working in MYSQL
<p>I am new to MYSQL, and unable to resolve or even with so many answers on this forum, unable to identiy the error in this statement. I am using MYSQL database.</p> <p>I have 2 tables: Ratemaster and rates, in which a customer can have 1 product with different rates. Because of this, there is a duplication of customer and product fields, only the rate field changes. Now Table Ratemaster has all the fields : id, Customer code, Product, Rate, user whereas Table Rates has only: id, cust code, Rate, user. - user field is for checking session_user.</p> <p>Now Table Ratemaster has 3 records with all field values being same except Rate field empty. Table Rates has different rates. I want to have all rates to be updated in Ratemaster from Rates table. I am unable to do this with <code>UPDATE</code> and <code>LIMIT</code> mysql command, it is giving error as: </p> <blockquote> <p>Incorrect usage of UPDATE and LIMIT</p> </blockquote> <pre><code>UPDATE Ratemaster, Rates SET Ratemaster.Rate=Rates.Rate WHERE Ratemaster.user=Rates.user LIMIT 1 </code></pre>
9,080,506
5
7
null
2012-01-31 13:35:41.993 UTC
1
2019-01-22 09:50:40.09 UTC
2012-01-31 13:44:46.093 UTC
null
491,243
null
1,114,409
null
1
15
mysql|limit
53,635
<p>Usually you can use <code>LIMIT</code> and <code>ORDER</code> in your <code>UPDATE</code> statements, but in your case not, as written in the <a href="http://dev.mysql.com/doc/refman/5.0/en/update.html" rel="noreferrer">MySQL Documentation 12.2.10. UPDATE Syntax</a>:</p> <blockquote> <p>For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.</p> </blockquote> <p>Try the following:</p> <pre><code>UPDATE Ratemaster SET Ratemaster.Rate = ( SELECT Rates.Rate FROM Rates WHERE Ratemaster.user = Rates.user ORDER BY Rates.id LIMIT 1 ) </code></pre>
9,037,171
C# || operator not working with nullable booleans
<p>I have the following piece of code in my LINQ:</p> <pre><code> where (tf.Shipped || tf.Ordered || tf.Processed) </code></pre> <p>Note that Shipped, Ordered and Processed are all nullable Boolean fields</p> <p>I am getting the following message:</p> <blockquote> <p>Operator || cannot be applied to operands of type 'bool?' and 'bool?'</p> </blockquote> <p>Not sure how to resolve this as yes, they need to be nullable booleans and I need to use the OR (||).</p>
9,038,205
6
15
null
2012-01-27 17:04:07.277 UTC
3
2012-02-02 09:00:08.707 UTC
2012-01-31 19:11:13.467 UTC
null
44,743
null
996,431
null
1
40
c#|nullable|boolean
2,102
<p>Take a step back and think about the problem. You want a collection of widgets where the widget was ordered, or the widget was shipped, or the widget was processed. </p> <p>There are four possible states for your knowledge of "ordered":</p> <ul> <li>this widget was ordered <strong>and I know that</strong> (true)</li> <li>this widget was not ordered <strong>and I know that</strong> (false)</li> <li>this widget was ordered <strong>but I don't know that</strong> (null)</li> <li>this widget was not ordered <strong>but I don't know that</strong> (null)</li> </ul> <p>There are four states but only three values possible values. Therefore if "ordered" is in the null state <em>you do not know whether it should be included in the query results or not</em>.</p> <p>The compiler doesn't know that either.</p> <p><strong>There simply is not enough information available for the compiler to give you a query that has the semantics you want.</strong> The compiler is not going to make a guess and possibly give you bad results; the compiler is going to tell you that there's not enough information here and you need to do more work to make the query unambiguous.</p> <p>What you have to do is say <em>what to do in the case where you don't know the answer</em>. The query "all the widgets that were ordered, shipped or processed" is impossible because some widgets <em>we don't know</em> whether they were ordered, shipped or processed, and so we don't know whether to include them or not. But the query "all the widgets <em>that I know</em> were ordered, or <em>that I know</em> were shipped, or <em>that I know</em> were processed" is a query that the compiler can make sense of:</p> <pre><code>where (tf.Shipped ?? false) || (tf.Ordered ?? false) || (tf.Processed ?? false) </code></pre> <p>That means "if I don't know whether it was shipped, etc, assume it was not".</p> <p>You might instead want the query "all the widgets that <em>definitely were, or might have been</em> shipped, ordered or processed:</p> <pre><code>where (tf.Shipped ?? true) || (tf.Ordered ?? true) || (tf.Processed ?? true) </code></pre> <p>The compiler isn't going to guess which side you want to err on when there is insufficient information to give accurate results; the compiler might guess wrong and we're not in the business of making decisions on your behalf. You're going to have to make that decision.</p>
23,484,310
Canceling interactive UINavigationController pop gesture does not call UINavigationControllerDelegate methods
<p>If you drag the edge of a <code>UIViewController</code> to begin an interactive pop transition within a <code>UINavigationController</code>, the <code>UIViewController</code> underneath the current has <code>viewWillAppear:</code> called, followed by the <code>UINavigationControllerDelegate</code> method <code>navigationController:willShowViewController:animated:</code>.</p> <p>If you cancel the transition (i.e. the dragged controller is placed back where it was and not popped), <code>viewWillAppear:</code> and <code>viewDidAppear:</code> are called on the top view controller as expected, but the delegate methods <code>navigationController:willShowViewController:animated:</code> and <code>navigationController:didShowViewController:animated:</code> aren't. It seems like at least one or both of these should be called considering the <code>UIViewController</code> view lifecycle methods are called. I am wondering whether this is deliberate or a bug in <code>UINavigationController</code>. </p> <p>What I really need is to be able to see when an interactive pop is cancelled, either within my <code>UINavigationController</code> subclass, or its <code>UINavigationControllerDelegate</code>. Is there an obvious way to do this?</p> <p><strong>edit</strong></p> <p>I'm still looking for a solution to this but would like to mention that I have reported this issue as a bug with Apple. Looking at the documentation, there is no reason these delegate methods should not get called, especially considering the equivalent view lifecycle methods DO get called.</p> <p><strong>edit2</strong></p> <p>My radar ticket (16823313) was closed today (May 21st, 2015) and marked as intended. :(</p> <blockquote> <p>Engineering has determined that this issue behaves as intended based on the following information:</p> <p>This is actually the correct behavior. The navigation transition that's happening from B -> A, if you cancel it mid-transition, you won't get the didShowViewController: method. A cancellation of this transition shouldn't be considered a transition from A -> B because you never actually reached A.</p> <p>view[Will/Did]Appear should still be called as expected too.</p> </blockquote> <p>Quite a bummer this is the case as it is counterintuitive but the workaround in my answer below should work fine for the foreseeable future, at least for my use-case.</p>
23,961,637
3
5
null
2014-05-06 00:57:16.187 UTC
10
2019-10-07 10:48:21.29 UTC
2019-10-07 10:48:21.29 UTC
null
259,521
null
484,304
null
1
26
ios|objective-c|uinavigationcontroller|uikit
6,224
<p>For anyone interested, I have found 2 ways to work around this at the <code>UINavigationControllerDelegate</code> level.</p> <ol> <li><p>Use KVO to observe the <code>state</code> property of the <code>interactivePopGestureRecognizer</code>. Unfortunately, canceling the transition does not change the state to <code>UIGestureRecognizerStateFailed</code> but instead just <code>UIGestureRecognizerStateEnded</code>, so you would need to write a bit of additional code to keep track of what happened if you needed to discern between a cancelled or completed pop.</p></li> <li><p>After testing it, this is probably the better solution: Use the <code>navigationController:willShowViewController:animated:</code> method to add a notification block to the transition coordinator. It looks something like this:</p> <pre><code>- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { [[self transitionCoordinator] notifyWhenInteractionEndsUsingBlock:^(id&lt;UIViewControllerTransitionCoordinatorContext&gt; context) { if([context isCancelled]) { UIViewController *fromViewController = [context viewControllerForKey:UITransitionContextFromViewControllerKey]; [self navigationController:navigationController willShowViewController:fromViewController animated:animated]; if([self respondsToSelector:@selector(navigationController:didShowViewController:animated:)]) { NSTimeInterval animationCompletion = [context transitionDuration] * (double)[context percentComplete]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((uint64_t)animationCompletion * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self navigationController:navigationController didShowViewController:fromViewController animated:animated]; }); } } }]; } </code></pre></li> </ol> <p>I was hesitant to use this solution at first because the documentation was unclear about whether or not you could set more than one of these (since in that case, if an unknowing view controller also set its own notification block, it could potentially either replace this one or get replaced by this one). After testing it though, it appears that it is not a 1:1 relationship and you can add multiple notification blocks safely.</p> <p><strong>edit</strong></p> <p>I edited the code above to delay the <code>navigationController:didShowViewController:animated:</code> call to only be called when the animation is supposed to be completed to more closely match the expected default behavior.</p>
8,886,348
Recommended online snippet manager
<p>I am looking for an online snippet manager for work, personal use and inspiration.</p> <p>My primary needs are google/facebook login, fontification of various programming languages, privacy control, social network integration. </p> <p>What's the recommendation?</p>
9,316,201
9
5
null
2012-01-16 21:14:30.12 UTC
9
2018-05-24 07:39:10 UTC
2012-02-16 18:47:19.743 UTC
null
207,109
null
241,930
null
1
19
language-agnostic|code-snippets
11,431
<p>I enjoy using <a href="https://gist.github.com/" rel="noreferrer">GitHub Gists</a>. It lets you version control your snippets, which is a nice benefit.</p>
4,958,860
Should I comment my log calls when creating my final package?
<p>I have an application that uses a lot of <code>Log.d()</code> or <code>Log.e()</code> calls for debugging. Now I want to create my final package for release. The Android Export feature from Eclipse mentions to remove the <code>"Debuggable"</code> flag in the manifest, which I have done. Should I also comment all the <code>Log</code> calls to improve the performance of my application or these calls will do nothing in the non debuggable final version package ?</p>
4,959,362
4
0
null
2011-02-10 15:14:44.873 UTC
12
2017-08-28 06:48:59.617 UTC
2017-08-28 06:48:59.617 UTC
null
2,219,237
null
578,668
null
1
21
android|android-log
7,092
<p>I have subclassed the Log class to a class called Trace, which mirrors methods on Log. So I do Trace.d(TAG,"blah") and then within the Trace.d method the code only executes based on a static final class variable called LOGGING_LEVEL, which has levels 1-5 (none, errors only, errors &amp; warnings, errors &amp; warnings &amp; info, and everything including debug) . When producing a production APK, Proguard removes all the code that isn't used in the application, so it does it for me.</p> <p>For me, logging is far too important to remove from the source, but it must be removed from the production application, for performance, secure and intellectual property reasons.</p> <p>This structure allows me to add a lot MORE logging to the application, which makes debugging problems much easier, but with no impact whatsoever on the production APK</p> <pre><code>public class Trace { public static final int NONE = 0; public static final int ERRORS_ONLY = 1; public static final int ERRORS_WARNINGS = 2; public static final int ERRORS_WARNINGS_INFO = 3; public static final int ERRORS_WARNINGS_INFO_DEBUG = 4; private static final int LOGGING_LEVEL = ERRORS_ONLY; // Errors + warnings + info + debug (default) public static void e(String tag, String msg) { if ( LOGGING_LEVEL &gt;=1) Log.e(tag,msg); } public static void e(String tag, String msg, Exception e) { if ( LOGGING_LEVEL &gt;=1) Log.e(tag,msg,e); } public static void w(String tag, String msg) { if ( LOGGING_LEVEL &gt;=2) Log.w(tag, msg); } public static void i(String tag, String msg) { if ( LOGGING_LEVEL &gt;=3) Log.i(tag,msg); } public static void d(String tag, String msg) { if ( LOGGING_LEVEL &gt;=4) Log.d(tag, msg); } } </code></pre>
5,387,643
Array initialization syntax when not in a declaration
<p>I can write:</p> <pre><code>AClass[] array = {object1, object2} </code></pre> <p>I can also write:</p> <pre><code>AClass[] array = new AClass[2]; ... array[0] = object1; array[1] = object2; </code></pre> <p>but I can't write:</p> <pre><code>AClass[] array; ... array = {object1, object2}; </code></pre> <p>Why is this blocked by Java?</p> <p>I know how to work around it, but from time to time it would be simpler.</p> <p>For example:</p> <pre><code>public void selectedPointsToMove(cpVect coord) { if (tab == null) { if (arePointsClose(coord, point1, 10)) { cpVect[] tempTab = {point1}; tab = tempTab; } else if (arePointsClose(point2, coord, 10)) { cpVect[] tempTab = {point2}; tab = tempTab; } else { cpVect[] tempTab = {point1,point2}; tab = tempTab; } } } </code></pre> <p><sub><em>This simple question that has been bugging me since I learned how to play with arrays in Java.</em></sub></p>
5,387,693
4
0
null
2011-03-22 06:32:07.29 UTC
30
2017-05-19 11:16:21.183 UTC
2015-07-11 15:48:14.81 UTC
null
63,550
null
440,336
null
1
147
java|arrays
263,143
<blockquote> <p>Why is this blocked by Java?</p> </blockquote> <p>You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.</p> <p>But "why" is immaterial ... the restriction is there, and you have to live with it.</p> <blockquote> <p>I know how to work around it, but from time to time it would be simpler.</p> </blockquote> <p>You can write this:</p> <pre><code>AClass[] array; ... array = new AClass[]{object1, object2}; </code></pre>
5,316,495
Xcode 4 Final - "armv6 armv7" issue while linking with armv6 libs
<p>Until xcode 4 final (I was using 3.latest and 4 GM for the time it was available) this didn't happen. When I upgraded to xcode 4 final version, I started getting a linking error while trying to link the armv7 version with my non armv7 library (my project is set with the default Standard armv6 armv7 valid architectures):</p> <pre><code>ld: warning: ignoring file ../bin/iOS static/arm/libssl.a, file was built for archive which is not the architecture being linked (armv7) ld: warning: ignoring file ../bin/iOS static/arm/libcrypto.a, file was built for archive which is not the architecture being linked (armv7) Undefined symbols for architecture armv7: -- list of symbols -- </code></pre> <p>The armv6 version compiles just fine, but the overall compilation process fails with 77 link errors. </p> <p>I understand this is the expected behavior, it wont link towards armv7 with an armv6 lib. The fix is setting my project to armv6 only. My question here is: why was this working in the previous versions of xcode? </p> <p>If I set to armv6 only, I start to get this warning:</p> <pre><code>Check dependencies [BWARN]warning: all apps should include an armv7 architecture (current ARCHS = "armv6"). </code></pre> <p>I don't like seeing warnings :-) Anybody having similar issues?</p> <p>Thanks,</p> <p>Fernando</p>
5,513,356
5
0
null
2011-03-15 18:48:20.837 UTC
9
2012-09-26 06:51:40.09 UTC
null
null
null
null
545,059
null
1
17
iphone|xcode|static-linking|armv7|armv6
38,254
<p>I just turned the Build active architecture only to Yes in the Project -> Build Setting -> Architectures tab.</p>
5,348,971
How i can convert NSString to long value?
<p>I have one value <code>100023</code> and I have taken it in <code>NSString</code>.</p> <p>Now I want to pass this value in my web service which contains long parameter type so how can I convert string value to long.</p>
5,349,002
6
0
null
2011-03-18 06:56:36.923 UTC
3
2017-03-27 14:39:03.68 UTC
2011-03-18 07:43:48.94 UTC
null
567,929
null
198,680
null
1
29
objective-c|nsstring|long-integer
37,841
<p>You can use <code>NSString</code> methods <code>intValue</code> <code>longLongValue</code>.</p>
5,271,320
allowDefinition='MachineToApplication' msbuild error
<p>We have a ASP.NET MVC with 4-5 different build configurations. Whenever we change the build configuration, we need to delete the obj folder for the web project, since we get the 'allowDefinition='MachineToApplication' error. A pain, but we managed by deleting the folder in pre/post build events. Now I need to configure our CI to build deployment packages. This means that I cannot delete the obj folder. Every time I compile e.g. with the following msbuild parameters </p> <blockquote> <p>/p:CreatePackageOnPublish=true /p:DeployOnBuild=true</p> </blockquote> <p>I recieve the error:</p> <blockquote> <p>web.config(123): error ASPCONFIG: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.</p> </blockquote> <p>As far as I understand, the problem is that there's multiple .config files in the project - In our case, there's not. I could really use some help to find an explanation and find a permanent (no- hack) fix.</p> <p>Edit: This question is marked as a duplicate, but the corresponding answers and cause(s) in the 2 threads, are clearly different from each other. Not sure what is intended with this tag - I've read that particular post before posting this question, as it didn't answer my question. There's multiple causes for this error message. It is 'similar', but definitely not a duplicate! </p>
8,162,738
12
0
null
2011-03-11 09:46:52.52 UTC
11
2016-10-21 11:18:17.4 UTC
2013-03-02 18:31:48.757 UTC
null
45,687
null
45,687
null
1
47
msbuild|web-config
70,692
<p>I too was deleting the obj folder until I had a conflict with a build script which required it. Catch-22, I used the accepted answer on the following SO link to move the location of the Obj folder to <code>C:\Temp\BUILD</code>. You have to do it per csproj file, but it is a great solution.</p> <p>Here is the link: <a href="https://stackoverflow.com/questions/261422/visualstudio-how-to-save-the-obj-folder-somewhere-else">VisualStudio: How to save the obj folder somewhere else</a></p> <p>Note that I am using a variable for the project name. R:\Temp\Build\Debug\$(MSBuildProjectName)</p> <p>I have the above line in both debug and release sections for all my projects, including class projects. My build path is a ram drive for speed. See this SO for more info: <a href="https://stackoverflow.com/questions/8174614/how-to-access-macro-variables-within-csproj-file">How to access macro variables within csproj file?</a></p>
5,161,730
iPhone: How to switch tabs with an animation?
<p>I'm switching tabs programmatically in a tab bar driven application using <code>UITabBarController.selectedIndex</code>. The problem I'm trying to solve is how to animate the transition between the views. ie. from the view of the current tab to the view of the selected tab.</p> <p>The first thought was to make use of the <code>UITabBarControllerDelegate</code>, but it appears that this is not called when programmatically switching tabs. I'm now considering the <code>UITabBarDelegate.didSelectItem</code>: as a possible hook to set a transition animation.</p> <p>Has anyone managed to animate the transitions? If yes, how ?</p>
5,180,104
19
1
null
2011-03-01 23:33:28 UTC
79
2019-08-14 02:19:42.2 UTC
2013-01-22 06:56:22.25 UTC
null
271,725
null
247,090
null
1
109
ios4|uitabbarcontroller|uitabbar
57,679
<p><strong><em>Update 04/2016:</strong> Justed wanted to update this to say thank you to everyone for all the votes. Please also note that this was originally written way back when ... before ARC, before constraints, before ... a lot of stuff! So please take this into account when deciding whether to use these techniques. There may be more modern approaches. Oh, and if you find one. Please add a response so everyone can see. Thanks.</em> </p> <p><strong>Some time later ...</strong></p> <p>After much research I came up with two working solutions. Both of these worked and did the animation between tabs.</p> <p><strong>Solution 1: transition from view (simple)</strong></p> <p>This is the easiest and makes use of a predefined UIView transition method. With this solution we don't need to manage the views because the method does the work for us.</p> <pre><code>// Get views. controllerIndex is passed in as the controller we want to go to. UIView * fromView = tabBarController.selectedViewController.view; UIView * toView = [[tabBarController.viewControllers objectAtIndex:controllerIndex] view]; // Transition using a page curl. [UIView transitionFromView:fromView toView:toView duration:0.5 options:(controllerIndex &gt; tabBarController.selectedIndex ? UIViewAnimationOptionTransitionCurlUp : UIViewAnimationOptionTransitionCurlDown) completion:^(BOOL finished) { if (finished) { tabBarController.selectedIndex = controllerIndex; } }]; </code></pre> <hr> <p><strong>Solution 2: scroll (more complex)</strong></p> <p>A more complex solution, but gives you more control of the animation. In this example we get the views to slide on and off. With this one we need to manage the views ourselves.</p> <pre><code>// Get the views. UIView * fromView = tabBarController.selectedViewController.view; UIView * toView = [[tabBarController.viewControllers objectAtIndex:controllerIndex] view]; // Get the size of the view area. CGRect viewSize = fromView.frame; BOOL scrollRight = controllerIndex &gt; tabBarController.selectedIndex; // Add the to view to the tab bar view. [fromView.superview addSubview:toView]; // Position it off screen. toView.frame = CGRectMake((scrollRight ? 320 : -320), viewSize.origin.y, 320, viewSize.size.height); [UIView animateWithDuration:0.3 animations: ^{ // Animate the views on and off the screen. This will appear to slide. fromView.frame =CGRectMake((scrollRight ? -320 : 320), viewSize.origin.y, 320, viewSize.size.height); toView.frame =CGRectMake(0, viewSize.origin.y, 320, viewSize.size.height); } completion:^(BOOL finished) { if (finished) { // Remove the old view from the tabbar view. [fromView removeFromSuperview]; tabBarController.selectedIndex = controllerIndex; } }]; </code></pre> <p>This Solution in Swift:</p> <pre><code>extension TabViewController: UITabBarControllerDelegate { public func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -&gt; Bool { let fromView: UIView = tabBarController.selectedViewController!.view let toView : UIView = viewController.view if fromView == toView { return false } UIView.transitionFromView(fromView, toView: toView, duration: 0.3, options: UIViewAnimationOptions.TransitionCrossDissolve) { (finished:Bool) in } return true } } </code></pre>
16,792,502
Change Label to Textbox on edit hyperlink click
<p>I am new to ruby on rails and twitter bootstrap. Accept my apologize if my question sound dumb. I am using twitter bootstrap for my site design. I have been trying to use bootstrap to change my label to textbox using hyperlink button click. </p> <pre><code>&lt;div class="control-group"&gt; &lt;label for="name" class="control-label"&gt;&lt;p class="text-info"&gt;Saghir&lt;i class="icon-star"&gt;&lt;/i&gt;&lt;/p&gt;&lt;/label&gt; &lt;div class="controls"&gt; &lt;a href="#"&gt;Edit&lt;/a&gt; &lt;/div&gt; </code></pre> <p>but I am unable to do so, should I use jquery to do so, or I can use bootstrap for that. Please point me to right direction. Thanks in advance</p> <p><strong>Edit</strong> Code is updated with hyperlink(it could be button too). it is like, when I click on "Edit" hyperlink my label should show content "Saghir" that can be used using placeholder attribute of bootstrap. I can submit form to update values to database.</p>
16,793,061
5
3
null
2013-05-28 12:48:16.723 UTC
8
2016-11-20 01:57:17.22 UTC
2014-03-08 23:26:25.73 UTC
null
3,339,122
null
659,944
null
1
10
jquery|ruby-on-rails|twitter-bootstrap
64,158
<p>As Chris said, <code>Bootstrap</code> does not provide this functionality as it is a front-end framework. you can use <code>jQuery</code> to achieve this. Though, you'll need to add some custom id's or classes to your elements to make sure you are only selecting the required elements. You can do something like the following:</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="control-group"&gt; &lt;label for="name" class="control-label"&gt; &lt;p class="text-info"&gt;Saghir&lt;i class="icon-star"&gt;&lt;/i&gt;&lt;/p&gt; &lt;/label&gt; &lt;input type="text" class="edit-input" /&gt; &lt;div class="controls"&gt; &lt;a class="edit" href="#"&gt;Edit&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function() { $('a.edit').click(function () { var dad = $(this).parent().parent(); dad.find('label').hide(); dad.find('input[type="text"]').show().focus(); }); $('input[type=text]').focusout(function() { var dad = $(this).parent(); $(this).hide(); dad.find('label').show(); }); }); </code></pre> <p><strong>CSS</strong></p> <pre><code>.edit-input { display:none; } </code></pre> <p>Here is a working <a href="http://jsfiddle.net/fnVNc/" rel="noreferrer">JSFiddle</a> for your reference.</p>
29,571,671
Basic multiprocessing with while loop
<p>I am brand new to the <code>multiprocessing</code> package in python and my confusion will probably be easy for someone who knows more to clear up. I've been reading about concurrency and have searched for other questions like this and have found nothing. (FYI I do <em>NOT</em> want to use <code>multithreading</code> because the GIL will slow down my application a lot.)</p> <p>I am thinking in the framework of events. I want to have multiple processes running, waiting for an event to happen. If the event happens, it gets assigned to a particular process, which operates and then returns to its idle state. There may be a better way to do this, but my reasoning is that I should spawn all the processes once and keep them open indefinitely, rather than creating then closing a process every time an event happens. Speed is an issue for me and my events can occur many thousands of times per second. </p> <p>I came up with the following toy example, which is meant to send even numbers to one process, and odd numbers to another. Both processes are the same, they just append the number to a list. </p> <pre><code>from multiprocessing import Process, Queue, Pipe slist=['even','odd'] Q={} Q['even'] = Queue() Q['odd'] = Queue() ev,od = [],[] Q['even'].put(ev) Q['odd'].put(od) P={} P['even'] = Pipe() P['odd'] = Pipe() def add_num(s): """ The worker function, invoked in a process. The results are placed in a list that's pushed to a queue.""" # while True : if not P[s][1].recv(): print s,'- do nothing' else: d = Q[s].get() print d d.append(P[s][1].recv()) Q[s].put(d) print Q[s].get() P[s][0].send(False) print 'ya' def piper(s,n): P[s][0].send(n) for k in [S for S in slist if S != s]: P[k][0].send(False) add_num(s) procs = [ Process ( target=add_num, args=(i,) ) for i in ['even','odd']] for s in slist: P[s][0].send(False) for p in procs: p.start() p.join() for i in range(10): print i if i%2==0: s = 'even' else: s = 'odd' piper(s,i) print 'results:', Q['odd'].get(),Q['even'].get() </code></pre> <p>This code produces the following: </p> <p><code>even - do nothing</code></p> <p>Any insight from the wise into this problem, where my code or reasoning falls short etc. would be greatly appreciated. </p>
29,872,356
1
8
null
2015-04-10 22:33:25.31 UTC
8
2015-04-26 00:36:48.243 UTC
2015-04-11 02:48:22.523 UTC
null
2,030,696
null
2,030,696
null
1
12
python|python-2.7|while-loop|multiprocessing|python-multiprocessing
21,630
<p>Here is an approach I've used a couple of times with good success:</p> <ol> <li><p>Launch a <a href="https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool" rel="noreferrer">multiprocessing pool</a>.</p></li> <li><p>Use a multiprocessing <a href="https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.managers.SyncManager" rel="noreferrer">SyncManager</a> to create multiple queues (one for each type of data that needs to be handled differently).</p></li> <li><p>Use <a href="https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool.apply_async" rel="noreferrer">apply_async</a> to launch the functions that process data. Just like the queues, there should be one function for each type of data that needs to be processed differently. Each function launched gets the queue that corresponds to its data as an input argument. The functions will do their work in an infinite loop that starts by getting data from the queue. </p></li> <li><p>Begin processing. During processing, the main process sorts the data and decides which function should be handling it. Once the decision is made, the data is placed on the queue that corresponds to that function.</p></li> <li><p>After all data has been handled, the main process puts a value called a "poison pill" into each queue. The poison pill is a value that the worker processes all recognize as a signal to exit. Since the queues are first-in first-out (FIFO), then they are guaranteed to pull the poison pill as the last item in the queues.</p></li> <li><p>Close and join the multiprocessing pool.</p></li> </ol> <h2>Code</h2> <p>Below is an example of this algorithm. The example code's goal is to use the algorithm previously described to divide odd numbers by 2, and even numbers by -2. All results are placed in a shared list accessible by the main process.</p> <pre><code>import multiprocessing POISON_PILL = "STOP" def process_odds(in_queue, shared_list): while True: # block until something is placed on the queue new_value = in_queue.get() # check to see if we just got the poison pill if new_value == POISON_PILL: break # we didn't, so do the processing and put the result in the # shared data structure shared_list.append(new_value/2) return def process_evens(in_queue, shared_list): while True: new_value = in_queue.get() if new_value == POISON_PILL: break shared_list.append(new_value/-2) return def main(): # create a manager - it lets us share native Python object types like # lists and dictionaries without worrying about synchronization - # the manager will take care of it manager = multiprocessing.Manager() # now using the manager, create our shared data structures odd_queue = manager.Queue() even_queue = manager.Queue() shared_list = manager.list() # lastly, create our pool of workers - this spawns the processes, # but they don't start actually doing anything yet pool = multiprocessing.Pool() # now we'll assign two functions to the pool for them to run - # one to handle even numbers, one to handle odd numbers odd_result = pool.apply_async(process_odds, (odd_queue, shared_list)) even_result = pool.apply_async(process_evens, (even_queue, shared_list)) # this code doesn't do anything with the odd_result and even_result # variables, but you have the flexibility to check exit codes # and other such things if you want - see docs for AsyncResult objects # now that the processes are running and waiting for their queues # to have something, lets give them some work to do by iterating # over our data, deciding who should process it, and putting it in # their queue for i in range(6): if (i % 2) == 0: # use mod operator to see if "i" is even even_queue.put(i) else: odd_queue.put(i) # now we've finished giving the processes their work, so send the # poison pill to tell them to exit even_queue.put(POISON_PILL) odd_queue.put(POISON_PILL) # wait for them to exit pool.close() pool.join() # now we can check the results print(shared_list) # ...and exit! return if __name__ == "__main__": main() </code></pre> <h2>Output</h2> <p>This code produces this output:</p> <blockquote> <p>[0.5, -0.0, 1.5, -1.0, 2.5, -2.0]</p> </blockquote> <p>Notice that the order of the results is unpredictable, because we can't guarantee in what order the functions will be able to get items from their queues and put the results into the list. But you can certainly to whatever post-processing you need, which could include sorting.</p> <h2>Rationale</h2> <p>I think this would be a good solution to your issue because:</p> <ol> <li><p>You're correct that there is huge overhead to spawning processes. This single-producer/multiple-consumer approach eliminates that when you use a pool to keep workers alive for the entire duration of the program.</p></li> <li><p>It addresses your concerns about being able to handle data differently depending on attributes of the data. In your comments, you expressed concerns about being able to send data to specific processes. In this approach, you can choose which processes to give data to, because you have to choose which queue to put it on. (By the way, I think you're thinking of the <a href="https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled" rel="noreferrer">pool.map</a> function, which, as you correctly believe, doesn't allow you to perform different operations in the same job. <code>apply_async</code> does.)</p></li> <li><p>I've found it to be very expandable and flexible. Need to add more types of data handling? Just write your handler function, add one more queue, and add to logic to main to route the data to your new function. Are you finding that one queue is getting backed up and becoming a bottleneck? You can call <code>apply_async</code> with the same target function and queue multiple times to get multiple workers working on the same queue. Just make sure you give the queue enough poison pills so that all of the workers get one.</p></li> </ol> <h2>Limitations</h2> <p>Any data you want to pass on a queue must be picklable (serializable) by the pickle module. Look <a href="https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled" rel="noreferrer">here</a> to see what can and can't be pickled.</p> <p>There are probably other limitations as well, but I can't think of any others off of the top of my head. </p>
12,409,373
SQL - monthly average rather than daily average
<p>I have a table called values that contains 3 columns - Location, value, date</p> <p>I want to work out the average value per month </p> <p>so far I have </p> <pre><code>SELECT Location, Avg(value), date FROM Value GROUP BY Location, date </code></pre> <p>This returns the average values but a value is entered on a daily basis so I have an average per day rather than per month, how can I achieve a monthly average?</p>
12,409,421
4
2
null
2012-09-13 15:08:13.14 UTC
1
2022-04-09 04:52:21.753 UTC
2012-09-13 15:10:48 UTC
null
472,134
null
1,505,127
null
1
6
sql|sql-server|sql-server-2008|tsql
38,201
<p>try this:</p> <pre><code>SELECT Location, Avg(value), month(date), year(date) FROM Value GROUP BY Location, month(date), year(date) </code></pre>
12,346,604
Android- How can I show text selection on textview?
<p>I am implementing a epub reading app where I am using textview for showing text of epub. I want to select text from textview when user long presses on textview and then do multiple operations on selected text of textview like highlight etc.. So, How can I show those cursors to user to select text whatever user wants.</p> <p>*I dont want to use EditText and make it look like textview. May be overriding textview is prefered.</p> <p>*I have attached screenshot to explain what I am looking for- </p> <p><img src="https://i.stack.imgur.com/73OGC.png" alt="Screenshot from moon+reader to show text selection in it which I want in my app"></p>
17,137,052
2
2
null
2012-09-10 06:49:26.147 UTC
10
2013-07-25 14:06:50.367 UTC
2012-09-10 08:34:39.407 UTC
null
966,710
null
966,710
null
1
12
android|textview|android-edittext|textselection
18,549
<p>This is asked long time ago, when I had this problem myself as well. I made a Selectable TextView myself for my own app Jade Reader. I've hosted the solution to GitHub. (The code at BitBucket ties to the application, but it's more complete and polished.)</p> <p><a href="https://github.com/zhouray/SelectableTextView" rel="noreferrer">Selectable TextView (on GitHub)</a></p> <p><a href="https://bitbucket.org/rayzhou/jaderead-restart/overview" rel="noreferrer">Jade Reader (on BitBucket)</a></p> <p><img src="https://i.stack.imgur.com/pfSlW.png" alt="selection"></p> <p>Using the following code will make your TextView selectable.</p> <pre><code>package com.zyz.mobile.example; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; public class MainActivity extends Activity { private SelectableTextView mTextView; private int mTouchX; private int mTouchY; private final static int DEFAULT_SELECTION_LEN = 5; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // make sure the TextView's BufferType is Spannable, see the main.xml mTextView = (SelectableTextView) findViewById(R.id.main_text); mTextView.setDefaultSelectionColor(0x40FF00FF); mTextView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { showSelectionCursors(mTouchX, mTouchY); return true; } }); mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTextView.hideCursor(); } }); mTextView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mTouchX = (int) event.getX(); mTouchY = (int) event.getY(); return false; } }); } private void showSelectionCursors(int x, int y) { int start = mTextView.getPreciseOffset(x, y); if (start &gt; -1) { int end = start + DEFAULT_SELECTION_LEN; if (end &gt;= mTextView.getText().length()) { end = mTextView.getText().length() - 1; } mTextView.showSelectionControls(start, end); } } } </code></pre>
12,518,412
Twitter Bootstrap Responsive Carousel With Multiple Items
<p>I'm trying to setup Twitter Bootstrap carousel with multiple items while maintaining the responsiveness. </p> <p>I have a jsfiddle for testing setup <a href="http://jsfiddle.net/Va8Un/" rel="noreferrer">http://jsfiddle.net/Va8Un/</a></p> <p>What I would like to happen is to display 4 images each with caption to hold item titles and so forth within a carousel pane and they should be resized to fit the screen to stay on the same row at all times. Right now it's completely ignoring any attempts I make to adjust the image size to the screen, I figured setting the img <code>max-width:100%;</code> would do the trick but it doesn't seem to effect it. Moreover, the 4th image is being pushed to a second row because the images aren't resizing:</p> <p><img src="https://i.stack.imgur.com/28Wfe.png" alt="enter image description here"></p> <p>Any way to fix this with pure CSS or should I look for options beyond Twitter Bootstrap?</p> <p>You can view the result here: <a href="http://jsfiddle.net/Va8Un/embedded/result/" rel="noreferrer">http://jsfiddle.net/Va8Un/embedded/result/</a></p> <p>Here is the HTML:</p> <pre><code>&lt;div class="container"&gt; &lt;div class="carousel slide" id="myCarousel"&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item active"&gt; &lt;ul class="thumbnails span12"&gt; &lt;li&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="item"&gt; ... &lt;/div&gt; &lt;div class="item"&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;a data-slide="prev" href="#myCarousel" class="left carousel-control"&gt;‹&lt;/a&gt; &lt;a data-slide="next" href="#myCarousel" class="right carousel-control"&gt;›&lt;/a&gt; &lt;/div&gt; &lt;/diV&gt; </code></pre>
12,520,012
2
2
null
2012-09-20 18:12:23.98 UTC
11
2022-02-06 05:17:58.297 UTC
2012-09-20 18:23:08.543 UTC
null
1,028,922
null
1,028,922
null
1
13
css|twitter-bootstrap|responsive-design
65,008
<p>You can do this with the bootstrap fluid grid alone, just specify a <code>.container-fluid</code> container along with a <code>.row-fluid</code> row and give each one of your list items housing an image a <code>.span*</code> class, in this case 3 (3*4=12).</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { margin-top: 10px; } img { max-width:100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"&gt;&lt;/script&gt; &lt;link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" /&gt; &lt;div class="container-fluid"&gt; &lt;div class="row-fluid"&gt; &lt;div class="carousel slide" id="myCarousel"&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item active"&gt; &lt;ul class="thumbnails"&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;ul class="thumbnails"&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;ul class="thumbnails"&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="span3"&gt; &lt;div class="caption"&gt; &lt;h5&gt;Caption&lt;/h5&gt; &lt;/div&gt; &lt;div class="thumbnail"&gt; &lt;img src="http://placehold.it/260x180" alt=""&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;a data-slide="prev" href="#myCarousel" class="left carousel-control"&gt;‹&lt;/a&gt; &lt;a data-slide="next" href="#myCarousel" class="right carousel-control"&gt;›&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Demo: <a href="http://jsfiddle.net/Va8Un/10/" rel="nofollow noreferrer">http://jsfiddle.net/Va8Un/10/</a></p> <p>EDIT: here is the demo with corrections <a href="http://jsfiddle.net/Va8Un/550/" rel="nofollow noreferrer">http://jsfiddle.net/Va8Un/550/</a></p>
12,277,231
Maximum number of parameter passed in a post
<p>I get this error:</p> <pre><code>Exception during request processing: Caused by javax.servlet.ServletException with message: "Parameter count exceeded allowed maximum: 512" </code></pre> <p>There seems to be a limit on the number of parameter passed in a post.</p> <p>How could I extend this limit in JBoss? </p>
12,277,296
5
3
null
2012-09-05 08:18:57.227 UTC
5
2018-12-14 07:44:52.373 UTC
2012-09-06 08:20:47.5 UTC
null
34,088
null
1,317,264
null
1
17
html|jboss
39,023
<p>The number of parameters was limited in all web servers to plug the <a href="https://stackoverflow.com/questions/8669946/application-vulnerability-due-to-non-random-hash-functions">hashmap collision denial of service attack</a>.</p> <p>You can raise the limit by adding the following system property to the configuration file (e.g. <code>standalone.xml</code>):</p> <pre><code>&lt;property name="org.apache.tomcat.util.http.Parameters.MAX_COUNT" value="10000"/&gt; </code></pre> <p>(<a href="https://community.jboss.org/thread/197650" rel="nofollow noreferrer">source</a>)</p>
12,618,424
ini_set not working
<p>Here is the matter:</p> <pre> ini_set('display_errors', '1'); ini_set('safe_mode', '0'); ini_set('allow_url_fopen', '1'); ini_set('allow_url_include', '1'); print_r(ini_get_all()); </pre> <p>And I get:</p> <pre> Array( [allow_url_fopen] => Array ( [global_value] => 1 [local_value] => 1 [access] => 4 ) [allow_url_include] => Array ( [global_value] => [local_value] => [access] => 4 ) </pre> <p>Why I cannot set that variable within the php ini_set function? The directive is specified as PHP_INI_ALL then it can be defined within the ini_set() function! <a href="http://php.net/manual/en/ini.list.php">http://php.net/manual/en/ini.list.php</a></p>
12,618,546
6
0
null
2012-09-27 09:40:32.487 UTC
1
2019-06-25 21:27:05.097 UTC
2012-09-27 09:47:06.663 UTC
null
1,891,675
null
1,891,675
null
1
19
php
41,801
<p><strong><code>display_errors</code></strong></p> <p>may be set at runtime (with <code>ini_set()</code>), but it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.</p> <p>Use <code>ini_set('display_errors','Off');</code> </p> <p><strong><code>safe_mode</code></strong></p> <p>This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. This directive belongs to <code>PHP_INI_SYSTEM</code> and Cannot be set via <code>ini_set()</code></p> <p><strong><code>allow_url_include</code></strong></p> <p>Use <code>ini_set('allow_url_include', 'On');</code></p> <p><strong><code>allow_url_fopen</code></strong></p> <p>This directive belongs to <code>PHP_INI_SYSTEM</code> and Cannot be set via <code>ini_set()</code></p>
12,590,947
Using Git diff to detect code movement + How to use diff options
<p>Consider that a file (1.c) contains three functions and changes made by authors M and J. If someone runs <code>git blame 1.c</code>, he will get the following output:</p> <pre><code>^869c699 (M 2012-09-25 14:05:31 -0600 1) de24af82 (J 2012-09-25 14:23:52 -0600 2) de24af82 (J 2012-09-25 14:23:52 -0600 3) de24af82 (J 2012-09-25 14:23:52 -0600 4) public int add(int x, int y) { de24af82 (J 2012-09-25 14:23:52 -0600 5) int z = x+y; de24af82 (J 2012-09-25 14:23:52 -0600 6) return z; de24af82 (J 2012-09-25 14:23:52 -0600 7) } de24af82 (J 2012-09-25 14:23:52 -0600 8) ^869c699 (M 2012-09-25 14:05:31 -0600 9) public int multiplication(int y, int z){ ^869c699 (M 2012-09-25 14:05:31 -0600 10) int result = y*z; ^869c699 (M 2012-09-25 14:05:31 -0600 11) return temp; ^869c699 (M 2012-09-25 14:05:31 -0600 12) } ^869c699 (M 2012-09-25 14:05:31 -0600 13) ^869c699 (M 2012-09-25 14:05:31 -0600 14) public void main(){ de24af82 (J 2012-09-25 14:23:52 -0600 15) //this is a comment de24af82 (J 2012-09-25 14:23:52 -0600 16) } </code></pre> <p>Now, if author A changes the position of the <code>multiplication()</code> and <code>add()</code> functions and commits the changes, <code>git blame</code> can detect the code movement. See following output:</p> <pre><code>$ git blame -C -M e4672cf82 1.c ^869c699 (M 2012-09-25 14:05:31 -0600 1) de24af82 (J 2012-09-25 14:23:52 -0600 2) de24af82 (J 2012-09-25 14:23:52 -0600 3) e4672cf8 (M 2012-09-25 14:26:39 -0600 4) de24af82 (J 2012-09-25 14:23:52 -0600 5) ^869c699 (M 2012-09-25 14:05:31 -0600 6) public int multiplication(int y, int z){ ^869c699 (M 2012-09-25 14:05:31 -0600 7) int result = y*z; ^869c699 (M 2012-09-25 14:05:31 -0600 8) return temp; ^869c699 (M 2012-09-25 14:05:31 -0600 9) } ^869c699 (M 2012-09-25 14:05:31 -0600 10) ^869c699 (M 2012-09-25 14:05:31 -0600 11) public void main(){ de24af82 (J 2012-09-25 14:23:52 -0600 12) //this is a comment e4672cf8 (M 2012-09-25 14:26:39 -0600 13) } de24af82 (J 2012-09-25 14:23:52 -0600 14) public int add(int x, int y){ de24af82 (J 2012-09-25 14:23:52 -0600 15) int z = x+y; de24af82 (J 2012-09-25 14:23:52 -0600 16) return z; e4672cf8 (M 2012-09-25 14:26:39 -0600 17) } </code></pre> <p>However, if I try to run <code>git diff</code> between these two revisions, it cannot detect that functions change their location and gives the following output:</p> <pre><code>$ git diff -C -M de24af8..e4672cf82 1.c diff --git a/1.c b/1.c index 5b1fcba..56b4430 100644 --- a/1.c +++ b/1.c @@ -1,10 +1,7 @@ -public int add(int x, int y){ - int z = x+y; - return z; -} + public int multiplication(int y, int z){ int result = y*z; @@ -13,4 +10,8 @@ public int multiplication(int y, int z){ public void main(){ //this is a comment -} \ No newline at end of file +} +public int add(int x, int y){ + int z = x+y; + return z; +} \ No newline at end of file </code></pre> <p>My questions are:</p> <ol> <li><p>How can I enforce detecting code movement in getting diff output? Is it even possible?</p></li> <li><p>Git diff can be applied with several options. For example <code>--minimal</code>, <code>--patience</code>. How can I apply those options here? I tried with one, but get the following error:</p> <pre><code>$ git diff --minimal de24af8..e4672cf82 1.c usage: git diff &lt;options&gt; &lt;rev&gt;{0,2} -- &lt;path&gt;* </code></pre></li> </ol> <p>Can anyone suggest/give sample example how to add these options correctly?</p>
12,805,390
3
1
null
2012-09-25 20:58:24.053 UTC
10
2020-06-01 20:53:28.47 UTC
2018-01-18 17:38:36.987 UTC
null
241,211
null
298,160
null
1
33
git|git-diff
10,967
<blockquote> <p>This was the best answer at the time it was written, but it is <strong>no longer accurate</strong>. In 2017, Git 2.15 upgraded its <code>diff</code> to do move detection. <a href="https://stackoverflow.com/a/47192896/8910547">As explained in the now top voted answer</a>, use <code>git diff --color-moved</code></p> </blockquote> <p><strong>Original answer:</strong></p> <p>What you're running up against here is that Git largely stays out of advanced diffing like this. There's a reason Git allows configuration of external diff and merge tools: you'd go insane without their assistance. Beyond Compare and Araxis Merge would both catch this movement, as an example.</p> <p>The general class of problem you're looking to solve is a "structured merge": <a href="https://stackoverflow.com/questions/14376370/structural-diff-of-two-java-source-files">Structural Diff of two java source files</a></p> <p>You might have a bit more luck with <code>git-format-patch</code> than with <code>git-diff</code> in this case because the former provides more commit info, including author and commit message and also generates a patch file for each commit in the range you specify. Source: <a href="https://stackoverflow.com/questions/4624127/what-is-the-difference-between-git-format-patch-and-git-diff">What is the difference between &#39;git format-patch and &#39;git diff&#39;?</a></p> <p>If you're looking for tips on detecting code moves generally, it's interesting to note that detection of code movement is explicitly <em>not</em> a goal of the all-powerful pickaxe. See this interesting exchange: <a href="http://gitster.livejournal.com/35628.html" rel="nofollow noreferrer">http://gitster.livejournal.com/35628.html</a></p> <p>If you wanted to detect who swapped the order, it seems your only option would be to do something like:</p> <pre><code> git log -S'public int multiplication(int y, int z){ int result = y*z; return temp; } public void main(){ //this is a comment } public int add(int x, int y) { int z = x+y; return z; }' </code></pre> <p>What you're looking for is <code>git blame -M&lt;num&gt; -n</code>, which does something pretty similar to what you're asking:</p> <pre><code>-M|&lt;num&gt;| Detect moved or copied lines within a file. When a commit moves or copies a block of lines (e.g. the original file has A and then B, and the commit changes it to B and then A), the traditional blame algorithm notices only half of the movement and typically blames the lines that were moved up (i.e. B) to the parent and assigns blame to the lines that were moved down (i.e. A) to the child commit. With this option, both groups of lines are blamed on the parent by running extra passes of inspection. &lt;num&gt; is optional but it is the lower bound on the number of alphanumeric characters that git must detect as moving/copying within a file for it to associate those lines with the parent commit. The default value is 20. -n, --show-number Show the line number in the original commit (Default: off). </code></pre>
12,515,861
How to check if a generic type implements a specific type of generic interface in java?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/11798951/generic-type-of-local-variable-at-runtime">Generic type of local variable at runtime</a> </p> </blockquote> <p>I'm new to Java generics, and coming from a .NET world, I'm used to being able to write a method like this:</p> <pre><code>public void genericMethod&lt;T&gt;(T genericObject) { if (genericObject is IList&lt;String&gt;) { //Do something... } } </code></pre> <p>The method accepts an object of a generic type, and checks whether that object implements a <em>specific</em> version of the generic interface <code>IList&lt;&gt;</code>, in this case, <code>IList&lt;String&gt;</code>.</p> <p>Now, in Java, I'm able to do this:</p> <pre><code>public &lt;T&gt; void genericMethod(T genericObject) { if (genericObject instanceof Set&lt;?&gt;) { //Do something... } } </code></pre> <p><strong>BUT</strong></p> <p>Java does <em>not</em> let me do <code>if (genericObject instanceof Set&lt;String&gt;)</code></p> <p>From what I know, because of type erasure, normally in Java this would be taken care of by a class object, and we would do something like the following:</p> <pre><code>public &lt;T&gt; void genericMethod(T genericObject) { Class&lt;OurTestingType&gt; testClass = OurTestingType.class; if (genericObject.getClass() == testClass) { //Do something... } } </code></pre> <p>but since the type I'm checking for is a generic interface, you can't do this:</p> <p><code>Class&lt;Set&lt;String&gt;&gt; testClass = Set&lt;String&gt;.class</code></p> <p>So, how, in Java, do I check if a generic object implements the specific type of <code>Set&lt;String&gt;</code>?</p>
12,515,974
2
1
null
2012-09-20 15:25:19.143 UTC
7
2018-08-24 16:02:56.953 UTC
2017-05-23 11:54:37.177 UTC
null
-1
null
552,843
null
1
36
java|generics|collections
92,586
<p>Java implements erasure, so there's no way to tell on runtime if <code>genericObject</code> is an instance of <code>Set&lt;String&gt;</code> or not. The only way to guarantee this is to use bounds on your generics, or check all elements in the set.</p> <h2>Compile-time Generic Bounds</h2> <p>Using bounds checking, which will be checked at compile-time:</p> <pre><code>public &lt;T extends SomeInterface&gt; void genericMethod(Set&lt;? extends T&gt; tSet) { // Do something with tSet here } </code></pre> <h2>Java 8</h2> <p>We can use streams in Java 8 to do this natively in a single line:</p> <pre><code>public &lt;T&gt; void genericMethod(T t) { if (t instanceof Set&lt;?&gt;) { Set&lt;?&gt; set = (Set&lt;?&gt;) t; if (set.stream().allMatch(String.class:isInstance)) { Set&lt;String&gt; strs = (Set&lt;String&gt;) set; // Do something with strs here } } } </code></pre> <h2>Java 7 and older</h2> <p>With Java 7 and older, we need to use iteration and type checking:</p> <pre><code>public &lt;T&gt; void genericMethod(T t) { Set&lt;String&gt; strs = new HashSet&lt;String&gt;(); Set&lt;?&gt; tAsSet; if (t instanceof Set&lt;?&gt;) { tAsSet = (Set&lt;?&gt;) t; for (Object obj : tAsSet) { if (obj instanceof String) { strs.add((String) obj); } } // Do something with strs here } else { // Throw an exception or log a warning or something. } } </code></pre> <h2>Guava</h2> <p>As per Mark Peters' comment below, Guava also has methods that do this for you if you can add it to your project:</p> <pre><code>public &lt;T&gt; void genericMethod(T t) { if (t instanceof Set&lt;?&gt;) { Set&lt;?&gt; set = (Set&lt;?&gt;) t; if (Iterables.all(set, Predicates.instanceOf(String.class))) { Set&lt;String&gt; strs = (Set&lt;String&gt;) set; // Do something with strs here } } } </code></pre> <p>The statement, <code>Iterables.all(set, Predicates.instanceOf(String.class))</code> is essentially the same thing as <code>set instanceof Set&lt;String&gt;</code>.</p>
24,222,640
Passing Data between View Controllers in Swift
<p>I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift. My Objective-C code is</p> <pre><code>UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; AnsViewController *ansViewController; ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"]; ansViewController.num = theNum; [self presentViewController:ansViewController animated:YES completion:nil]; </code></pre> <p>What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller. I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated!</p> <p>Thanks</p>
26,374,173
7
6
null
2014-06-14 17:49:50.627 UTC
8
2018-09-14 07:28:10.383 UTC
2015-11-23 20:54:25.377 UTC
null
168,594
null
3,491,855
null
1
27
ios|swift|uistoryboard|uistoryboardsegue
52,794
<p>Let's assumed we stand at the <strong>firstView</strong> go to the <strong>DetailView</strong> and want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "segueTest") { //Checking identifier is crucial as there might be multiple // segues attached to same view var detailVC = segue!.destinationViewController as DetailViewController; detailVC.toPass = textField.text } } </code></pre> <p>and then into the class of <strong>DetailView</strong> we declared a variable:</p> <pre><code>var toPass: String! </code></pre> <p>then you can use the variable <code>toPass</code> (of course you can change the type of the variable as you want, in this EX I just demo for string type). </p>
22,467,127
Error :: duplicate files during packaging of APK
<p>Android Studio. I'm getting this kind of error during application run.</p> <p><code>Error:Execution failed for task ':app:packageDebug'. Duplicate files copied in APK META-INF/notice.txt</code></p> <p><strong>build.gradle</strong></p> <pre><code>apply plugin: 'android' android { compileSdkVersion 19 buildToolsVersion "19.0.1" packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/ASL2.0' } defaultConfig { minSdkVersion 7 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:appcompat-v7:19.0.1' compile 'com.j256.ormlite:ormlite-android:4.48' compile 'org.codehaus.jackson:jackson-core-asl:1.9.13' compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13' compile 'com.octo.android.robospice:robospice:1.4.11' compile 'com.octo.android.robospice:robospice-spring-android:1.4.11' } </code></pre> <p>How can I fix this error?</p> <p><strong>EDITED</strong></p> <p>These exclude options solved my problem:</p> <pre><code>packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/notice.txt' exclude 'META-INF/ASL2.0' } </code></pre>
22,471,045
8
5
null
2014-03-17 22:56:45.713 UTC
21
2019-02-02 19:05:48.23 UTC
2017-04-29 05:09:33.243 UTC
null
2,308,683
null
1,474,153
null
1
145
android|android-gradle-plugin
69,300
<p>I think the string comparison is case sensitive. try with <code>exclude 'META-INF/notice.txt'</code></p>
8,855,361
FB OpenGraph og:image not pulling images (possibly https?)
<p>Facebook cannot grasp my <code>og:image</code> files and I have tried every usual solution. I'm beginning to think it might have something to do with <code>https://...</code></p> <ul> <li>I have checked <a href="http://developers.facebook.com/tools/debug" rel="noreferrer">http://developers.facebook.com/tools/debug</a> and have zero warnings or errors.</li> <li>It is finding the images we linked to in the &quot;<code>og:image</code>&quot;, but they're showing up blank. When we click the image(s), however, they DO exist and it takes is straight to them.</li> <li>It DOES show one image -- an image hosted on a non-https server.</li> <li>We've tried square images, jpegs, pngs, larger sizes and smaller sizes. We've put the images right in public_html. Zero are showing up.</li> <li>It's not a caching error, because when we add another <code>og:image</code> to the meta, FB's linter does find and read that. It DOES show a preview. The preview is blank. The <strong>only</strong> exception we're getting is for images that are not on this website.</li> <li>We thought maybe there was some anti-leach on <code>cpanel</code> or the <code>.htaccess</code> that was preventing the images from showing up, so we checked. There was not. We even did a quick <code>&lt; img src=&quot;[remote file]&quot; &gt;</code> on an entirely different server and the image shows up fine.</li> <li>We thought maybe it was the <code>og:type</code> or another oddity with another meta tag. We removed all of them, one at a time and checked it. No change. Just warnings.</li> <li>The same code on a different website shows up without any issue.</li> <li>We thought <em>maybe</em> it was not pulling images because we're using the same product page(s) for multiple products (changing it based on the get value, ie, &quot;details.php?id=xxx&quot;) but it's still pulling in one image (from a different url).</li> <li>Leaving any <code>og:image</code> or image_src off, FB does not find any images.</li> </ul> <p>I am at the end of my rope. If I said how much time myself and others have spent on this, you'd be shocked. The issue is that this is an online store. We absolutely, positively cannot NOT have images. We have to. We have ten or so other sites... This is the only one with <code>og:image</code> problems. It's also the only one on <code>https</code>, so we thought maybe that was the problem. But we can't find any precedent anywhere on the web for that.</p> <p>These are the meta-tags:</p> <pre class="lang-html prettyprint-override"><code>&lt;meta property=&quot;og:title&quot; content=&quot;[The product name]&quot; /&gt; &lt;meta property=&quot;og:description&quot; content=&quot;[the product description]&quot; /&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://www.[ourwebsite].com/images/shirts/overdriven-blues-music-tshirt-details-black.png&quot; /&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://www.[ourwebsite].com/images/shirts/overdriven-blues-music-tshirt-art-black.png&quot; /&gt; &lt;meta property=&quot;og:image&quot; content=&quot;http://www.[ADIFFERENTwebsite].com/wp-content/uploads/2011/06/ARS-Header-Shine2.png&quot; /&gt; &lt;meta property=&quot;og:image&quot; content=&quot;https://www.[ourwebsite].com/images/ARShopHeader.png&quot; /&gt; &lt;meta property=&quot;og:image&quot; content=&quot;http://www.[ourwebsite].com/overdriven-blues-music-tshirt-art-black.JPG&quot; /&gt; &lt;meta property=&quot;og:type&quot; content=&quot;product&quot;/&gt; &lt;meta property=&quot;og:url&quot; content=&quot;https://www.[ourwebsite].com/apparel-details.php?i=10047&quot; /&gt; &lt;meta property=&quot;og:site_name&quot; content=&quot;[our site name]&quot; /&gt; &lt;meta property=&quot;fb:admins&quot; content=&quot;[FB-USER-ID-NUMBER]&quot;/&gt; &lt;meta name=&quot;title&quot; content=&quot;[The product name]&quot; /&gt; &lt;meta name=&quot;description&quot; content=&quot;[The product description]&quot; /&gt; &lt;link rel=&quot;image_src&quot; href=&quot;https://www.[ourwebsite].com/images/shirts/overdriven-blues-music-tshirt-details-black.png&quot; /&gt; &lt;meta name=&quot;keywords&quot; content=&quot;[four typical keywords]&quot;&gt; &lt;meta name=&quot;robots&quot; content=&quot;noarchive&quot;&gt; </code></pre> <p>In case you want it, here's a link to one of our product pages that we've been working on. [Link shortened to try to curb this getting into search results for our site]: <a href="http://rockn.ro/114" rel="noreferrer">http://rockn.ro/114</a></p> <p>EDIT ----</p> <p>Using the &quot;see what facebook sees&quot; scraper tool, we were able to see the following:</p> <pre class="lang-js prettyprint-override"><code>&quot;image&quot;: [ { &quot;url&quot;: &quot;https://www.[httpSwebsite].com/images/shirts/soul-man-soul-music-tshirt-details-safari.png&quot; }, { &quot;url&quot;: &quot;https://www.[httpSwebsite].com/images/shirts/soul-man-soul-music-tshirt-art-safari.png&quot; }, { &quot;url&quot;: &quot;http://www.[theotherNONSECUREwebsite].com/wp-content/uploads/2011/06/ARS-Header-Shine2.png&quot; } ], </code></pre> <p>We tested all links it found for a single page. All were perfectly valid images.</p> <p>EDIT 2 ----</p> <p>We tried a test and added a <em>subdomain</em> to the NONSECURE website (from which images are actually visible through facebook). Subdomain was http://img.[nonsecuresite].com. We then put all images into the main subdomain folder and referenced those. It would not pull those images into FB. However, it would still pull any images that were referenced on the nonsecure main domain.</p> <p>POSTED WORKAROUND ----</p> <p>Thanks to Keegan, we now know that this is a bug in Facebook. To workaround, we placed a subdomain in a different NON-HTTPS website and dumped all images in it. We referenced the coordinating <code>http://img.otherdomain.com/[like-image.jpg]</code> image in <code>og:image</code> on each product page. We then had to go through FB Linter and run EVERY link to refresh the OG data. This worked, but the solution is a band-aid workaround, and if the <code>https</code> issue is fixed and we go back to using the natural https domain, FB will have cached the images from a different website, complicating matters. Hopefully this information helps to save someone else from losing 32 coding hours of <em>their</em> life.</p>
8,910,877
28
7
null
2012-01-13 18:26:14.623 UTC
70
2022-09-06 19:48:37.167 UTC
2021-12-07 10:08:18.827 UTC
null
11,135,174
null
48,957
null
1
363
facebook|facebook-graph-api|facebook-opengraph
303,759
<p>I ran into the same problem and reported it as a bug on the Facebook developer site. It seems pretty clear that <code>og:image</code> URIs using HTTP work just fine and URIs using HTTPS do not. They have now acknowledged that they are "looking into this."</p> <p>Update: As of 2020, the bug is no longer visible in Facebook's ticket system. They never responded and I don't believe this behavior has changed. However, specifying HTTPS URI in <code>og:image:secure</code> does seem to be working fine.</p>
20,453,449
sign changes when going from int to float and back
<p>Consider the following code, which is an <a href="http://sscce.org/">SSCCE</a> of my actual problem:</p> <pre><code>#include &lt;iostream&gt; int roundtrip(int x) { return int(float(x)); } int main() { int a = 2147483583; int b = 2147483584; std::cout &lt;&lt; a &lt;&lt; " -&gt; " &lt;&lt; roundtrip(a) &lt;&lt; '\n'; std::cout &lt;&lt; b &lt;&lt; " -&gt; " &lt;&lt; roundtrip(b) &lt;&lt; '\n'; } </code></pre> <p>The output on my computer (Xubuntu 12.04.3 LTS) is:</p> <pre><code>2147483583 -&gt; 2147483520 2147483584 -&gt; -2147483648 </code></pre> <p>Note how the positive number <code>b</code> ends up negative after the roundtrip. Is this behavior well-specified? I would have expected int-to-float round-tripping to at least preserve the sign correctly...</p> <p>Hm, <a href="http://ideone.com/Mo8Umt">on ideone</a>, the output is different:</p> <pre><code>2147483583 -&gt; 2147483520 2147483584 -&gt; 2147483647 </code></pre> <p>Did the g++ team fix a bug in the meantime, or are both outputs perfectly valid?</p>
20,453,520
2
4
null
2013-12-08 12:34:33.293 UTC
8
2013-12-13 13:25:34.323 UTC
2013-12-08 18:45:31.747 UTC
null
501,557
null
252,000
null
1
42
c++|floating-point|type-conversion|ieee-754|twos-complement
4,073
<p>Your program is invoking undefined behavior because of an overflow in the conversion from floating-point to integer. What you see is only the usual symptom on x86 processors.</p> <p>The <code>float</code> value nearest to <code>2147483584</code> is 2<sup>31</sup> exactly (the conversion from integer to floating-point usually rounds to the nearest, which can be up, and is up in this case. To be specific, the behavior when converting from integer to floating-point is implementation-defined, most implementations define rounding as being “according to the FPU rounding mode”, and the FPU's default rounding mode is to round to the nearest).</p> <p>Then, while converting from the float representing 2<sup>31</sup> to <code>int</code>, an overflow occurs. This overflow is undefined behavior. Some processors raise an exception, others saturate. The IA-32 instruction <code>cvttsd2si</code> typically generated by compilers happens to always return <code>INT_MIN</code> in case of overflow, regardless of whether the float is positive or negative.</p> <p>You should not rely on this behavior even if you know you are targeting an Intel processor: when targeting x86-64, compilers can emit, for the conversion from floating-point to integer, <a href="http://blog.frama-c.com/index.php?post/2013/10/09/Overflow-float-integer" rel="noreferrer">sequences of instructions that take advantage of the undefined behavior to return results other than what you might otherwise expect for the destination integer type</a>.</p>
22,015,354
Rename existing file name
<p>I have the following code which copies a file to a specific folder and then renames it. When a file with that name already exists I get the following exception:</p> <pre><code>Cannot create a file when that file already exists </code></pre> <p>Is there a way to overwrite the file and rename it? or I should delete the old one and then change the name?</p> <p>Here is my code:</p> <pre><code> File.Copy(FileLocation, NewFileLocation, true); //Rename: File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt")); </code></pre>
22,015,404
6
6
null
2014-02-25 13:15:26.96 UTC
1
2021-05-06 09:17:53.617 UTC
2014-02-25 13:33:11.783 UTC
null
1,611,834
null
1,016,179
null
1
11
c#|.net|file-io
90,291
<p>Try to use only:</p> <pre><code>if (File.Exists("newfilename")) { System.IO.File.Delete("newfilename"); } System.IO.File.Move("oldfilename", "newfilename"); </code></pre>
11,215,598
Check if input is textbox, select, textarea or radio
<p>I have a form with different html input fields...</p> <pre><code>1) &lt;input type="text"&gt; 2) &lt;textarea&gt;&lt;/textarea&gt; 3) &lt;input type="checkbox"&gt; 4) &lt;input type="radio"&gt; 5) &lt;select&gt;&lt;/select&gt; </code></pre> <p>How would I be able to determine what type of input field it is using jQuery. <em>For example: If I wanted to do a check to see if input = "select" then do stuff.</em></p>
11,215,652
7
2
null
2012-06-26 20:42:07.233 UTC
1
2017-01-02 10:42:55.167 UTC
null
null
null
null
1,211,946
null
1
10
jquery
44,420
<pre><code>$('input') // selects all types of inputs $('input:checkbox') // selects checkboxes $('select') // selects select element $('input:radio') // selects radio inputs $('input[type="text"]') // selects text inputs </code></pre> <p>you can use <code>event.target.type</code>, this alerts what type of <code>input</code>, <code>textrea</code> or <code>select</code> is the target of the event. </p> <pre><code>$('input, textarea, select').change(function(event){ alert(event.target.type) }) </code></pre> <p><a href="http://jsfiddle.net/Q4BNH/">http://jsfiddle.net/Q4BNH/</a></p>
11,068,565
Printf is not printing anything to output? C++ SDL
<p>I am trying to use "printf" in my Visual C++ project however it is not working. Using Lazy Foo's tutorial, I set up SDL in my project, but when I play it, printf doesnt do anything.</p> <pre><code>#include "SDL.h" #include &lt;stdio.h&gt; int main( int argc, char* args[] ) { printf("Testing"); return 0; } </code></pre> <p>The output looks like this:</p> <pre><code>The program '[4664] SDL Testing.exe: Native' has exited with code 0 (0x0). </code></pre> <p>And that's about it. What could be wrong?</p>
11,070,193
8
19
null
2012-06-17 02:48:22.067 UTC
3
2013-12-19 01:24:42.073 UTC
null
null
null
null
857,071
null
1
18
c++|visual-c++|sdl|printf
60,924
<p>SDL by default redirects stdout to a file, <code>stdout.txt</code>. You should find it in your program's working directory.</p>
11,068,648
Launching an intent for file and MIME type?
<p>I've reviewed all the similar questions here, but I can't for the life of me figure out what I'm doing wrong.</p> <p>I've written an application that tries to launch various files, sort of a file browser. When a file is clicked, it tries to launch the program based on its associated MIME type or it presents the "Choose Application to Launch" dialog.</p> <p>Here's the code I'm using to launch:</p> <pre><code> File file = new File(app.mediaPath() + "/" +_mediaFiles.get(position)); Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW); String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()); String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); myIntent.setDataAndType(Uri.fromFile(file),mimetype); startActivity(myIntent); </code></pre> <p>This fails and generates the error:</p> <pre><code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///file:/mnt/sdcard/roms/nes/Baseball_simulator.nes } </code></pre> <p>Now if I install OI File Manager for instance, it opens instead of this error being thrown, and then if I click the same file from within in it, it launches the approriate dialogs.</p> <p>I have noticed that the MIME type for that particular file fails, but other mime types like <code>.zip</code> do return values.</p> <p>Am I missing something that when the MIME type is null to call a dialog that lets the user select?</p> <p>I've tried other variations of launching the app, including not setting the MIME type and only using <code>.setData</code> with no success.</p> <p>The action I want to happen is, a user clicks a file, if it's associated with an application that app launches, if not, the user gets the "Complete action using" dialog with a list of apps.</p> <p>Thanks for any advice.</p>
11,088,980
2
2
null
2012-06-17 03:09:25.06 UTC
12
2012-12-06 09:48:06.627 UTC
2012-06-17 06:13:45.027 UTC
null
31,044
null
65,281
null
1
20
android|android-intent|file-browser
30,226
<p>Well thanks to the Open Intent guys, I missed the answer the first time through their code in their file manager, here's what I ended up with:</p> <pre><code> File file = new File(filePath); MimeTypeMap map = MimeTypeMap.getSingleton(); String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); String type = map.getMimeTypeFromExtension(ext); if (type == null) type = "*/*"; Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(file); intent.setDataAndType(data, type); startActivity(intent); </code></pre> <p>If you use a mime type of <code>"* / *"</code> when you can't determine it from the system(it is <code>null</code>) it fires the appropriate select application dialog.</p>
11,094,981
Changing The Font Of Text Area
<p>I think this is a simple and a silly question. I have included a text area in my html script. </p> <p>Is it possible to change the default font of the text area?</p> <p>The default one doesn't look good. I hope there is a way to change it.</p>
11,094,989
4
0
null
2012-06-19 05:38:05.34 UTC
1
2021-01-06 18:41:07.043 UTC
2012-06-19 12:46:50.79 UTC
null
848,454
null
1,430,289
null
1
24
html|textarea
83,452
<p>Yes, using the CSS <a href="http://www.w3.org/TR/CSS21/fonts.html#font-family-prop" rel="nofollow noreferrer"><code>font-family</code> property</a>, just like any other element.</p> <p>The W3C has a <a href="http://www.w3.org/wiki/Web_Standards_Curriculum#CSS" rel="nofollow noreferrer">CSS tutorial</a> as does <a href="https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics" rel="nofollow noreferrer">Mozilla</a></p>
10,936,815
Is System.Web.Caching or System.Runtime.Caching preferable for a .NET 4 web application
<p>I am adding caching to an ASP.NET web application. This is .NET 4, so I can use the classes in the System.Runtime.Caching namespace (which, as I understand it, was added to provide similar functionality to that found in System.Web.Caching, but for non-Web-apps.)</p> <p>But since this <em>is</em> a web app, am I better off using System.Web.Caching? Or is the newer System.Runtime.Caching superior in some way?</p>
10,955,456
2
0
null
2012-06-07 17:30:21.737 UTC
13
2013-11-22 15:32:07.383 UTC
null
null
null
null
254,364
null
1
45
c#|asp.net|caching|.net-4.0
22,666
<p>Microsoft recommends using System.Runtime.Caching for all caching purposes. See this: <a href="http://msdn.microsoft.com/en-us/library/dd997357.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/dd997357.aspx</a></p> <p>Although, I have come across a couple threads where people are having issues with the MemoryCache.Default instance. After a while, it stops working properly. Any item you add using the Add or Set method does not actually get added to the cache. I tried the same and was able to reproduce this issue with explicitly calling MemoryCache.Default.Dispose() method.</p> <p>Here are the links: <a href="https://stackoverflow.com/questions/7422859/memorycache-disposed-in-web-application">MemoryCache Empty : Returns null after being set</a></p> <p><a href="http://forums.asp.net/t/1736572.aspx/1" rel="noreferrer">http://forums.asp.net/t/1736572.aspx/1</a></p> <p>My recommendation is to use the System.Web.Caching (HttpContext.Current.Cache)</p> <p><strong>UPDATE:</strong></p> <p>This issue has been fixed by MS. Check the accepted answer in the post below: <a href="https://stackoverflow.com/questions/7422859/memorycache-disposed-in-web-application">Runtime Cache Issue Resolved</a></p>
10,902,504
R markdown: Accessing variable from code chunk (variable scope)
<p>In R markdown (knitr package), can I access a variable within the body of the document that was calculated in a code chunk?</p>
10,903,654
3
0
null
2012-06-05 18:06:46.663 UTC
8
2018-02-12 12:36:25.377 UTC
2018-02-12 12:36:25.377 UTC
null
3,001,626
null
824,383
null
1
64
r|knitr|r-markdown
79,929
<p>Yes. You can simply call any previously evaluated variable inline.</p> <p>e.g. If you had previously created a <code>data.frame</code> in a chunk with <code>df &lt;- data.frame(x=1:10)</code></p> <pre><code>`r max(df$x)` </code></pre> <p>Should produce</p> <pre><code>10 </code></pre>
11,438,634
Opening a CHM file produces: "navigation to the webpage was canceled"
<p>I am trying to open a .chm file.</p> <p>I downloaded the source, extracted it, and double clicked on <code>Waffle.chm</code> and clicked "Open" but no matter what element in the chm file I click, I get the message:</p> <pre><code>Navigation to the webpage was canceled. What you can try: Retype the address. </code></pre> <p><img src="https://i.stack.imgur.com/mVDyx.jpg" alt="enter image description here"></p> <p>What's going on here?</p>
11,438,732
10
0
null
2012-07-11 18:00:17.4 UTC
15
2021-01-27 21:02:08.303 UTC
2014-06-26 22:30:34.043 UTC
null
321,731
null
445,131
null
1
84
windows|chm
125,931
<p><strong>Summary</strong></p> <p>Microsoft Security Updates 896358 &amp; 840315 block display of CHM file contents when opened from a network drive (or a <a href="https://www.trustwave.com/support/kb/KnowledgebaseArticle10870.aspx" rel="noreferrer">UNC path</a>). This is Windows' attempt to stop attack vectors for viruses/malware from infecting your computer and has blocked out the .chm file that draw data over the "InfoTech" protocol, which this chm file uses.</p> <p>Microsoft's summary of the problem: <a href="http://support.microsoft.com/kb/896054" rel="noreferrer">http://support.microsoft.com/kb/896054</a></p> <p><strong>Solutions</strong></p> <ol> <li><p>If you are using Windows Server 2008, Windows 7, windows has created a quick fix. <strong>Right click the chm file, and you will get the "yourfile.chm Properties" dialog box, at the bottom, a button called "Unblock" appears. Click Unblock and press OK,</strong> and try to open the chm file again, it works correctly. This option is not available for earlier versions of Windows before WindowsXP (SP3). </p> <p><img src="https://i.stack.imgur.com/N1jEQ.png"></p></li> <li><p>Solve the problem by moving your chm file OFF the network drive. You may be unaware you are using a network drive, double check now: Right click your .chm file, click properties and look at the "location" field. If it starts with two backslashes like this: <code>\\epicserver\blah\</code>, then you are using a networked drive. <strong>So to fix it, Copy the chm file, and paste it into a local drive, like C:\ or E:.</strong> Then try to reopen the chm file, windows does not freak out.</p></li> <li><p>Last resort, if you can't copy/move the file off the networked drive. If you must open it where it sits, and you are using a lesser version of windows like XP, Vista, ME or other, you will have to <strong>manually tell Windows not to freak out over this .chm file. <a href="http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/" rel="noreferrer">HHReg (HTML Help Registration Utility)</a> Utility Automates this Task.</strong> Basically you download the HHReg utility, load your .chm file, press OK, and it will create the necessary registry keys to tell Windows not to block it. For more info: <a href="http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/" rel="noreferrer">http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/</a></p></li> </ol> <p>Windows 8 or 10? --> Upgrade to Windows XP.</p>
12,960,598
get value count in an array with smarty
<p>I have an array called <code>$mydata</code> that looks like this:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 1282 [type] =&gt;2 ) [1] =&gt; Array ( [id] =&gt; 1281 [type] =&gt;1 ) [2] =&gt; Array ( [id] =&gt; 1266 [type] =&gt;2 ) [3] =&gt; Array ( [id] =&gt; 1265 [type] =&gt;3 ) ) </code></pre> <p>I've assigned the array to smarty <code>$smarty-&gt;assign("results", $mydata)</code></p> <p>Now, in the template, I need to print how much of each "type" there is in the array. Can anyone help me do this?</p>
12,960,928
3
2
null
2012-10-18 17:46:18.06 UTC
null
2016-02-22 15:16:01.727 UTC
2014-02-12 07:55:13.753 UTC
null
642,572
null
1,496,029
null
1
13
php|smarty
52,476
<p><strong>PHP 5.3, 5.4:</strong></p> <p>As of Smarty 3 you can do</p> <pre><code>{count($mydata)} </code></pre> <p>You can also pipe it in Smarty 2 or 3:</p> <pre><code>{$mydata|count} </code></pre> <p>To count up "type" values you'll have to walk through the array in either PHP or Smarty:</p> <pre><code>{$type_count = array()} {foreach $mydata as $values} {$type = $values['type']} {if $type_count[$type]} {$type_count[$type] = $type_count[$type] + 1} {else} {$type_count[$type] = 1} {/if} {/foreach} Count of type 2: {$type_count[2]} </code></pre> <p><strong>PHP 5.5+:</strong></p> <p>With PHP 5.5+ and Smarty 3 you can use the new <code>array_column</code> function:</p> <pre><code>{$type_count = array_count_values(array_column($mydata, 'type'))} Count of type 2: {$type_count['2']} </code></pre>
12,883,759
Maintaining Clean Architecture in Spring MVC with a data-centric approach
<h1>Maintaining Clean Architecture in Spring MVC with a data-centric approach</h1> <p>I'm trying to map out the architecture for the front-end of a new Java-based web app (portal type application) we are making at work. I want to get this right from day one, and I would like to kick off a discussion here to help me implement Uncle Bob's <a href="http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html" rel="noreferrer">Clean Architecture</a> in my architectural design.</p> <p>Here's a quick run-down of our tech stack, top to bottom (the technology isn't importance, the structure is):</p> <ul> <li>Oracle Database</li> <li>Oracle Service Bus exposing services using WSDLs</li> <li>JAX-WS generated Java-classes from the WSDLs (let's call this the "generated service layer")</li> <li>A Domain module consisting of POJOs mapped to the generated data objects</li> <li>A Consumer-module exposing the "generated service layer" to the front-end application</li> <li>A Spring MVC based front-end module using FreeMarker to render the views</li> </ul> <p>A key point:</p> <blockquote> <p>In particular, the name of something declared in an outer circle must not be mentioned by the code in the an inner circle. That includes, functions, classes. variables, or any other named software entity.</p> </blockquote> <p>Attempting to adhere to Bob's Clean Architecture, I've gone back and forth a bit with myself regarding where to place the <em>application logic</em>, namely the "Use Case"-layer in his architecture.</p> <p>Here is the approach I've come up with:</p> <h2>Layer 1 - Entities</h2> <blockquote> <p>Entities encapsulate Enterprise wide business rules. </p> </blockquote> <p>This is where our Domain module containing the <em>domain-objects</em> lives, these are self-containing objects with minimal dependencies on each other. Only logic pertaining to the objects themselves may live on these domain objects, and no use-case specific logic.</p> <p>Access to our database is exposed via WSDLs using a service bus that transforms the data, as opposed to an ORM like JPA or Hibernate. Because of this, we do not have "entities" in the traditional sense (with Ids), but a <em>data-centric approach</em> making this layer a data access layer, presented to the rest of the application by the Consumer-module.</p> <h2>Layer 2 - Use Cases</h2> <blockquote> <p>The software in this layer contains application specific business rules.</p> </blockquote> <p>This is where logic specific to our application's use cases lives. Changes to this layer should not affect the data access layer (layer 1). Changes to the GUI or framework implementation (Spring MVC) should not affect this layer.</p> <p><strong>This is where it gets a little tricky:</strong> Since our data access layer (in layer 1) must be kept clean of application logic, we need a layer that facilitates use of that layer in a fashion that suits the use cases. One solution I've found to this problem is the use a variant of the "<em>MVVM-pattern</em>" that I choose to call <em>MVC-VM</em>. See below for an explanation. The "VM"-part of this lives in this Use Case-layer, represented by <code>*ViewModel</code>-classes that encapsulate this Use Case-specific logic.</p> <h2>Layer 3 - Interface Adapters</h2> <blockquote> <p>The software in this layer is a set of adapters that convert data from the format most convenient for the use cases and entities, to the format most convenient for some external agency such as the Database or the Web.</p> </blockquote> <p>This is where the MVC-architecture of our GUI lives (the "MVC" in our "MVC-VM"). Essentially this is when the <code>Controller</code>-classes get data from the <code>*ViewModel</code>-classes and puts it in Spring MVC's <code>ModelMap</code> ojects that are used directly by the FreeMarker-templates in the View.</p> <p>The way I see it, the servicebus would in our case also fall in under this layer.</p> <h2>Layer 4 - Frameworks and Drivers</h2> <blockquote> <p>Generally you don’t write much code in this layer other than glue code that communicates to the next circle inwards.</p> </blockquote> <p>This layer is really just a configuration-layer in our application, namely the Spring configuration. This would for example be where we specify that FreeMarker is used to render the view.</p> <hr> <h3>Model View ViewModel Pattern</h3> <blockquote> <p>MVVM facilitates a clear separation of the development of the graphical user interface (either as markup language or GUI code) from the development of the business logic or back end logic known as the model (also known as the data model to distinguish it from the view model). The view model of MVVM is a value converter meaning that the view model is responsible for exposing the data objects from the model in such a way that those objects are easily managed and consumed.</p> </blockquote> <p>More on the MVVM-pattern at <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Wikipedia</a>.</p> <p>The MVC-VM roles would be fulfilled in our application like so:</p> <ul> <li><strong>Model</strong> - represented simply by the <code>ModelMap</code> datastructure in Spring MVC that is used by the view templates.</li> <li><strong>View</strong> - FreeMarker templates</li> <li><p><strong>Controller</strong> Spring's <code>Controller</code>-classes that directs <em>HTTP URL requests</em> to specific <em>handlers</em> (and as such functions as a FrontController). The handlers in these classes are responsible for fetching data from the use case-layer and pushing it out to the view templates when showing data(HTTP <code>GET</code>), as well as sending data down for storing (HTTP <code>POST</code>). This way it essentially functions as a <em>binder</em> between the ViewModel and View, using the Model.</p></li> <li><p><strong>ViewModel</strong> - These classes are responsible for 1) structuring data from the data access layer in a fashion that is usable by the View and 2) treat data-input from the View. "Treat" means to validate and to break down the data so that it can be sent down the stack for storing. This layer would take form as <code>&lt;UseCase&gt;VM</code>-classes in a <code>viewmodel</code> package in our Spring MVC front-end module.</p></li> </ul> <p>A key component here is the implicit binding that happens in Spring MVC between <code>ModelMap</code> and the FreeMarker-templates. The templates only use the model (<code>ModelMap</code>s), where the controller has put the data in a format it can use. That way we can make templates like so:</p> <pre><code>&lt;body&gt; &lt;h1&gt;Welcome ${user}!&lt;/h1&gt; &lt;p&gt;Our latest product: &lt;a href="${latestProduct.url}"&gt;${latestProduct.name}&lt;/a&gt;! &lt;/body&gt; </code></pre> <hr> <p>I apologize for the verbose explanation, but I could not explain this (relatively simple) architecture in fewer words. </p> <p>I would greatly appreciate some input on my approach here - am I on the right track? Does the MVC-VM thing make sense? Am I violating any Clean Architecture Principles?</p> <p>There are of course many solutions to this, but I am trying to find a solution that is 1) not over-engineered and 2) adheres to the principles of Bob's Clean Architecture.</p> <hr> <h2>Update:</h2> <p>I think the key issue that puts me off here is what form the "Use case" layer takes in this application. Remember we have an MVC front-end that gets data from a data access layer. If the MVC part fits in Bob's "Interfaces adapters", and the domain models of the data layer fit in Bob's "Entities" layer, then what do I call the use case classes that implement application logic? I am tempted to just call them <code>&lt;UseCase&gt;Model</code>s and put them in the MVC project, but according to Bob</p> <blockquote> <p>The models are likely just data structures that are passed from the controllers to the use cases, and then back from the use cases to the presenters and views.</p> </blockquote> <p>so that means my model objects should be "dumb" (like a simple <code>Map</code>. <code>ModelMap</code> in Spring) and it is then the responsibility of the controller to put data from the Use Case class into this Map-structure. </p> <p>So again, what form does my Use Case-classes take? How about <code>&lt;UseCase&gt;Interactor</code>?</p> <p><strong>But in conclusion</strong> I realize that the MVC-MV-thing is over-engineering (or simply incorrect) - as "mikalai" indicates below this essentially just a two-layer applcation in its current form; a data access layer and a front-end MVC layer. Simple as that.</p>
12,941,244
3
1
null
2012-10-14 15:40:54.74 UTC
15
2013-09-12 15:34:27.243 UTC
2013-09-12 15:34:27.243 UTC
null
727,208
null
1,645,498
null
1
15
java|spring-mvc|model-view-controller|mvvm|architecture
9,417
<h2>My solution</h2> <p>So it turns out that implementing Bob's "Clean Architecture" in Java/Spring MVC is borderline non-trivial and requires more architectural facets than I originally had included.<br> And I could actually not find any example of implementations online.</p> <p>Evidently my architecture was missing a separate module for the "Use Case"-layer as this logic should not live in the Spring MVC Web module (and not be called "<code>*ViewModel</code>"). The Web/MVC module is simply a detail of the application, and the application logic should be completely separated from it, and separately testable.</p> <p>This new "Use Case"-module now contains <code>*Interactor</code>-classes which get data from the domain module (entities). Moreover, "<em>Request/Response Objects</em>" are needed to facilitate the communication between the MVC/Web-module and the Use Case module.</p> <p>My dependency chain now looks like this:</p> <p>Spring MVC module -> Use Case module -> Domain module</p> <p>where every arrow (dependency) takes form as a <em>Boundary</em>, meaning an interface is defined in the module to the right of the arrow that is implemented where required and injected where needed (Inversion of Control).</p> <p>Here are the interfaces I ended up with (per Use Case):</p> <p><code>I&lt;UseCase&gt;Request</code> - implemented in the MVC module, instantiated in the Controller <code>I&lt;UseCase&gt;Response</code> - implemented in the Use Case module, instantiated in the Interactor <code>I&lt;UseCase&gt;Interactor</code> - implemented in the UseCase module, injected in the Controller <code>I&lt;UseCase&gt;Consumer</code> - implemented in the Domain module, injected in the Interactor</p> <p><strong>How it works?</strong><br> The <code>Controller</code> takes parameters from the HTTP request and packs it in a <code>RequestModel</code> which it passes down to the <code>Interactor</code>. The <code>Interactor</code> fetches the data it needs from the domain module <code>*Consumer</code> and imposes it's application specific logic on it, then puts it in a <code>ResponseModel</code> and sends it back up to the <code>Controller</code>. The <code>Controller</code> then finally simply puts this (now GUI-friendly) simple data in a <code>Map</code> object and forwards it to the FreeMarker template which then uses this data directly and renders the HTML.</p> <p>A <code>Presenter</code> could get involved in that last part there, making this an implementation of the Model-View-Presenter pattern, but I'm leaving that for now.</p> <h2>My conclusion</h2> <p>I ended up with more files than what is necessary this early in development, strictly speaking. However as the complexity and size of the application grows, I am confident that this structure keeps it easy for us to maintain low coupling and high cohesion. Also, the Web-module is now easily replaceable - it just delivers requests to the use-case module and receives response-objects. Moreover, each layer of the application (domain logic, application logic, and GUI logic) is separately testable, with only the View-part requiring a webserver in order to be tested.</p> <p>Thanks for all advice and pointers I received here. And please comment on my solution - I don't claim that it is perfect. </p>
13,195,048
Show div after scrolling 100px from the top of the page
<p>I found this, but this does it 100px before the bottom of the page. I need it 100px from the top of the page. I know how to implement it, I've done other jquery animations, just not what needs to be in this one.</p> <pre><code>$(window).scroll(function(){ if($(window).scrollTop() + 100 &gt; $(document).height() - $(window).height() ){ alert("at bottom"); } }); </code></pre> <p>And also, I need to know how to reverse this so the div disappears when the user scroll back up before the 100px.</p> <p>This will be used for a navigation bar.</p> <p>Edit2> This worked also:</p> <pre><code>$(window).scroll(function(){ if($(window).scrollTop() &gt; 100){ $("#div").fadeIn("slow"); } }); $(window).scroll(function(){ if($(window).scrollTop() &lt; 100){ $("#div").fadeOut("fast"); } }); </code></pre>
13,195,073
3
0
null
2012-11-02 12:14:48.02 UTC
6
2015-02-12 14:42:44.767 UTC
2012-11-02 19:15:23.967 UTC
null
1,082,553
null
1,082,553
null
1
16
javascript|jquery|html
58,732
<p>Try this:</p> <pre><code>$(window).scroll(function() { if ($(window).scrollTop() &gt; 100) { // &gt; 100px from top - show div } else { // &lt;= 100px from top - hide div } }); </code></pre>
12,965,032
Controlling Internet Explorer local intranet using Excel VBA
<p>I am using Excel VBA code to click a button on our website. I know this isn't the best of things to be doing, but it is the least objectionable option available to me.</p> <p>I can using this code, successfully load imdb.com, google, etc. But when I load our local site, I lose control of the ie object, I can't check readyState, I can't Quit.</p> <p>Here is the error I get.</p> <blockquote> <p>Run-time error '-2147023179 (800706b5)':<br> Automation error<br> The interface is unknown</p> </blockquote> <p>Every so often I instead get this message:</p> <blockquote> <p>Run-time error '-2147417848 (80010108)':<br> Automation error<br> The object invoked has disconnected from its clients.</p> </blockquote> <p>Clicking Debug indicates the <code>ie.readyState</code>, I commented that out and then it points to <code>ie.Quit</code></p> <pre><code>Sub dothestuff() Dim ie As InternetExplorer Set ie = New InternetExplorer ie.Visible = True ie.Navigate "http://www.google.com/" anerror = webload(ie) ie.Quit Set ie = Nothing End Sub Function webload(ie) Do Until ie.ReadyState = READYSTATE_COMPLETE DoEvents Loop End Function </code></pre>
19,221,313
11
1
null
2012-10-18 22:59:45.477 UTC
13
2020-01-27 22:28:59.387 UTC
2020-01-27 22:28:59.387 UTC
null
-1
null
1,713,178
null
1
19
excel|vba|internet-explorer
86,639
<p>Here is a quick and easy solution for this issue:</p> <p>Instead of:</p> <pre><code>set IE = createobject("internetexplorer.application") </code></pre> <p>Use:</p> <pre><code>Set IE = New InternetExplorerMedium </code></pre> <p>No need to tweak the IE settings</p>
12,733,238
Retain Twitter Bootstrap Collapse state on Page refresh/Navigation
<p>I'm using Bootstrap "collapse" plugin to make an accordion for a long list of links. The accordion-body tag includes "collapse" so all the groups are collapsed when the page loads. When you open a group and click on a link, it takes you to a new page to see some detail and then you click a back link or the browser back to return to the list. Unfortunately, when you return the accordion is back in its collapsed state and you have to open the group again and find where you were. I anticipate a lot of this back and forth navigation and this behavior is going to be frustrating.</p> <p>Is there some way to preserve the user's place and go back to it, or just prevent the page from reloading or the javascript from firing again.</p> <p>I thought the solution might be along these lines, but not sure. <a href="https://stackoverflow.com/questions/10918801/twitter-bootstrap-adding-a-class-to-the-open-accordion-title">Twitter bootstrap: adding a class to the open accordion title</a></p>
13,471,196
7
3
null
2012-10-04 18:11:33.49 UTC
13
2021-05-24 12:56:20.743 UTC
2017-05-23 11:54:36.703 UTC
null
-1
null
1,720,917
null
1
32
javascript|jquery|twitter-bootstrap|twitter-bootstrap-3
49,424
<p>You can very easily solve this by a cookie. There is a lot of simplified libraries, like <a href="https://github.com/carhartl/jquery-cookie">https://github.com/carhartl/jquery-cookie</a> as I use in the example below :</p> <pre><code>&lt;script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"&gt;&lt;/script&gt; </code></pre> <p>add the following code to a script section (<code>#accordion2</code> refers to the modfied twitter bootstrap example, I list afterwards)</p> <pre><code>$(document).ready(function() { var last=$.cookie('activeAccordionGroup'); if (last!=null) { //remove default collapse settings $("#accordion2 .collapse").removeClass('in'); //show the last visible group $("#"+last).collapse("show"); } }); //when a group is shown, save it as the active accordion group $("#accordion2").bind('shown', function() { var active=$("#accordion2 .in").attr('id'); $.cookie('activeAccordionGroup', active) }); </code></pre> <p>And you are done! Here a modified version of the example at <a href="http://twitter.github.com/bootstrap/javascript.html#collapse">http://twitter.github.com/bootstrap/javascript.html#collapse</a> with clickable links, when you go back - the last shown accordion group opens up automatically</p> <pre><code>&lt;div class="accordion" id="accordion2"&gt; &lt;div class="accordion-group"&gt; &lt;div class="accordion-heading"&gt; &lt;a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"&gt; Collapsible Group Item #1 &lt;/a&gt; &lt;/div&gt; &lt;div id="collapseOne" class="accordion-body collapse in"&gt; &lt;div class="accordion-inner"&gt; Link : &lt;a href="http://google.com"&gt;google.com&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="accordion-group"&gt; &lt;div class="accordion-heading"&gt; &lt;a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"&gt; Collapsible Group Item #2 &lt;/a&gt; &lt;/div&gt; &lt;div id="collapseTwo" class="accordion-body collapse"&gt; &lt;div class="accordion-inner"&gt; Link : &lt;a href="http://stackoverflow.com"&gt;stackoverflow.com&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="accordion-group"&gt; &lt;div class="accordion-heading"&gt; &lt;a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree"&gt; Collapsible Group Item #3 &lt;/a&gt; &lt;/div&gt; &lt;div id="collapseThree" class="accordion-body collapse"&gt; &lt;div class="accordion-inner"&gt; Link : &lt;a href="http://cryptozoologynews.blogspot.com/"&gt;cryptozoology news&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
12,778,187
Examples of very concise Forth applications?
<p>In <a href="http://www.ultratechnology.com/1xforth.htm">this talk</a>, Chuck Moore (the creator of Forth) makes some very bold, sweeping claims, such as:</p> <ol> <li>"Every application that I have seen that I didn't code has ten times as much code in it as it needs"</li> <li>"About a thousand instructions seems about right to me to do about anything"</li> <li>"If you are writing code that needs [local variables] you are writing non-optimal code. Don't use local variables."</li> </ol> <p>I'm trying to figure out whether Mr. Moore is a) an absolutely brilliant genius or b) a crackpot. But that's a subjective question, and I'm not looking for the answer to that question here. What I am looking for are examples of complex, real-world problems which can be solved in "1000 instructions or less" using Forth, and source code demonstrating how to do so. An example showing just one non-trivial piece of a real-world system would be fine, but no "toy" code samples which could be duplicated in 5 or 10 lines of another high-level language, please.</p> <p>If you have written real-world systems in Forth, using just a small amount of source code, but aren't at liberty to show the source (because it is proprietary), I'd still like to hear about it.</p>
12,846,101
5
2
null
2012-10-08 08:47:15.043 UTC
13
2013-03-28 18:24:37.793 UTC
2013-03-28 18:24:37.793 UTC
user1228
null
null
960,828
null
1
35
forth
8,573
<p>You need to understand that <a href="http://en.wikipedia.org/wiki/Charles_H._Moore">Chuck Moore</a> is a little different than you and me. He was trained in an era when mainframe computers consisted of 16&nbsp;KB or its equivalent in core memory, and he was able to do quite a lot of things with the computers of the time. Perhaps the biggest success for Forth, outside of his OKAD-II chip design package (that's not a typo), was a multi-user multi-tasking Forth system responsible for concurrently controlling data acquisition instruments and data analysis/visualization software at <a href="http://en.wikipedia.org/wiki/National_Radio_Astronomy_Observatory">NRAO</a> on a fairly modestly sized computer barely able to compile <a href="http://en.wikipedia.org/wiki/Fortran">Fortran</a> source code on its own.</p> <p>What he calls an "application", we might consider to be a "component" of a larger, more nebulous thing called an application. More generally, it's good to keep in mind that one Moore "application" is more or less equivalent to one "view" in an <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> triad today. To keep memory consumption small, he relies heavily on overlays and just-in-time compilation techniques. When switching from one program interface to another, it typically involves recompiling the entire application/view from source. This happens so fast you don't know it's happening. Kind of like how Android recompiles <a href="http://en.wikipedia.org/wiki/Dalvik_%28software%29">Dalvik</a> code to native <a href="http://en.wikipedia.org/wiki/ARM_architecture">ARM</a> code when you activate an application every time today.</p> <p>At any given time, OKAD-II has no more than about 2.5&nbsp;KB of its code loaded into memory and running. However, the on-disk source for OKAD-II is considerably larger than 2.5&nbsp;KB. Though, it is still significantly more compact than its nearest competitor, <a href="http://en.wikipedia.org/wiki/SPICE">SPICE</a>.</p> <p>I'm often curious about Chuck Moore's views and find his never-ending strive for simplicity fascinating. So, in <a href="http://en.wikipedia.org/wiki/MythBusters">MythBusters</a> fashion, I put his claims to the test by trying to design my own system as minimally as I could make it. I'm happy to report he's very nearly spot-on in his claims, on both hardware and software issues. Case in point, during last September's <a href="http://www.forth.org/svfig/">Silicon Valley Forth Interest Group</a> (SVFIG) meeting, I used my Kestrel-2 itself to generate video for the slide deck. This required I wrote a slide presentation program for it, which took up 4&nbsp;KB of memory for the code, and 4&nbsp;KB for the slide deck data structures. With an average space of six bytes per Forth word (for reasons I won't go into here), the estimate of "about 1000 (Forth) instructions" for the application is just about spot on to what Chuck Moore estimates his own "applications" to be.</p> <p>If you're interested in speaking to real-world Forth coders (or who have done so in the past, as it increasingly seems to be), and you happen to be in the <a href="http://en.wikipedia.org/wiki/San_Francisco_Bay_Area">Bay Area</a>, the Silicon Valley Forth Interest Group still meets every fourth Saturday of the month, except for November and December, which is the third Saturday. If you're interested in attending a meeting, even if only to interview Forth coders and get a taste of what "real-world" Forth is like, check us out on meetup.com and tag along. We also new stream our meetings on YouTube, but we're not very good at it. We're abusing inappropriate hardware and software to do our bidding, since we have a budget of zero for this sort of thing. :)</p>
12,900,538
Fastest way to tell if two files have the same contents in Unix/Linux?
<p>I have a shell script in which I need to check whether two files contain the same data or not. I do this a for a lot of files, and in my script the <code>diff</code> command seems to be the performance bottleneck.</p> <p>Here's the line:</p> <pre><code>diff -q $dst $new &gt; /dev/null if ($status) then ... </code></pre> <p>Could there be a faster way to compare the files, maybe a custom algorithm instead of the default <code>diff</code>?</p>
12,900,693
9
2
null
2012-10-15 17:06:13.09 UTC
66
2022-08-09 07:38:52.453 UTC
2021-01-11 23:02:58.923 UTC
null
1,394,729
null
624,869
null
1
313
linux|file|unix|diff
269,311
<p>I believe <code>cmp</code> will stop at the first byte difference:</p> <pre><code>cmp --silent $old $new || echo "files are different" </code></pre>