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
5,468,912
PHP get the last 3 elements of an associative array while preserving the keys?
<p>I have an array: </p> <pre><code>[13] =&gt; Array ( [0] =&gt; joe [1] =&gt; 0 [14] =&gt; Array ( [0] =&gt; bob [1] =&gt; 0 ) [15] =&gt; Array ( [0] =&gt; sue [1] =&gt; 0 ) [16] =&gt; Array ( [0] =&gt; john [1] =&gt; 0 ) [17] =&gt; Array ( [0] =&gt; harry [1] =&gt; 0 ) [18] =&gt; Array ( [0] =&gt; larry [1] =&gt; 0 ) </code></pre> <p>How can I get the last 3 elements while preserving the keys? (the number of elements in the array may vary, so I cannot simply slice after the 2nd element)</p> <p>So the output would be:</p> <pre><code> [16] =&gt; Array ( [0] =&gt; john [1] =&gt; 0 ) [17] =&gt; Array ( [0] =&gt; harry [1] =&gt; 0 ) [18] =&gt; Array ( [0] =&gt; larry [1] =&gt; 0 ) </code></pre>
5,468,954
4
0
null
2011-03-29 06:52:32.95 UTC
10
2022-04-24 09:41:05.43 UTC
2022-04-24 09:41:05.43 UTC
null
1,145,388
null
677,640
null
1
74
php|arrays
69,887
<p>If you want to preserve key, you can pass in true as the fourth argument:</p> <pre><code>array_slice($a, -3, 3, true); </code></pre>
4,946,013
Set ASP Literal text with Javascript
<p>I have an asp:Literal on my page (<strong>which cannot be converted to a Label or any other control</strong>) that I need to change the text of via JavaScript. I have the following code that works for a <em>Label</em>. Can anybody help?</p> <pre><code>&lt;script type="text/javascript"&gt; function changeText() { document.getElementById('&lt;%= Test.ClientID %&gt;').innerHTML = 'New Text'; } &lt;/script&gt; &lt;a href="#" onclick='changeText()'&gt;Change Text&lt;/a&gt; &lt;asp:Label id="Test" runat="server" Text="Original Text" /&gt; </code></pre> <p>Thanks <hr> <strong>UPDATE:</strong> I cannot change from a literal as the code behind writes HTML/CSS to it for an Information Message e.g:</p> <pre><code>LITMessage.Text = "&lt;div class='success'&gt;Information Successfully Updated&lt;/div&gt;" </code></pre>
4,946,054
5
5
null
2011-02-09 14:14:52.243 UTC
2
2012-10-18 20:38:10.693 UTC
2011-02-09 14:26:09.72 UTC
null
545,436
null
545,436
null
1
9
javascript|asp.net|literals
55,650
<p><code>&lt;asp:Literal&gt;</code> controls don't create their own HTML tag.<br> Therefore, there is no element that you can manipulate.</p> <p>Instead, you can wrap the <code>&lt;asp:Literal&gt;</code> in a <code>&lt;div&gt;</code> tag with an ID.</p>
5,595,485
php, file download
<p>I am using the simple file downloading script:</p> <pre><code>if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } </code></pre> <p>It is working on my localserver upto 200mb. </p> <p>When i try this code in my website it downloads 173KB instead of 200MB file. </p> <p>I checked everything, wrote some custom code (using ob functions and fread instead of readfile) but can't download big files.</p> <p>Thank you for your answers.</p> <ul> <li>I am using Apache 2.2, PHP 5.3</li> <li>All PHP settings to deal with big files are ok. (execution times, memory limits, ...</li> </ul>
5,595,862
5
1
null
2011-04-08 13:07:26.157 UTC
10
2013-12-10 07:34:55.493 UTC
2013-06-26 00:28:03.917 UTC
null
2,185,093
null
208,302
null
1
18
php|file|header|download
26,112
<p>One issue I have with the following code is you have no control over the output stream, your letting PHP handle it without knowing exactly what is going on within the background:</p> <p>What you should do is set up an output system that you can control and replicated accros servers.</p> <p>For example:</p> <pre><code>if (file_exists($file)) { if (FALSE!== ($handler = fopen($file, 'r'))) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: chunked'); //changed to chunked header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); //header('Content-Length: ' . filesize($file)); //Remove //Send the content in chunks while(false !== ($chunk = fread($handler,4096))) { echo $chunk; } } exit; } echo "&lt;h1&gt;Content error&lt;/h1&gt;&lt;p&gt;The file does not exist!&lt;/p&gt;"; </code></pre> <p>This is only basic but give it a go!</p> <p>Also read my reply here: <a href="https://stackoverflow.com/questions/5249279/file-get-contents-php-fatal-error-allowed-memory-exhausted/5249971#5249971">file_get_contents =&gt; PHP Fatal error: Allowed memory exhausted</a></p>
5,261,085
How to easily get network path to the file you are working on?
<p>In Excel 2003 there used to be a command that I added to my toolbar that was called Address (if I remember correctly) and it would show the fully-qualified network path to the file I had open. For example: <code>\\ads\IT-DEPT-DFS\data\Users\someguy\somefile.xls</code></p> <p>This made it easy to grab this string and pop it in an email when you wanted to share the file with a coworker. I don't see this option in Excel 2010 but find myself needing to send/receive Excel files a lot now. Coworkers will give vague references to "it is on the share drive" or email the file as an attachment (ugh!).</p> <p>Anyone know if something comparable exists in Excel 2010?</p> <p>UPDATE: I found this mapping of Excel 2003 to 2007 commands. <a href="http://office.microsoft.com/en-us/excel-help/redir/AM010186429.aspx?CTT=5&amp;origin=HA010086048" rel="noreferrer">http://office.microsoft.com/en-us/excel-help/redir/AM010186429.aspx?CTT=5&amp;origin=HA010086048</a></p> <p>Web>Address is what I was using - looks like that became "Document Location" in 2007. But they removed/obfuscated this again in 2010. I am trying to find a mapping like this for 2007 to 2010.</p>
7,918,443
9
0
null
2011-03-10 14:30:29.997 UTC
4
2015-04-08 06:45:21.067 UTC
2012-07-16 17:19:10.54 UTC
null
190,829
null
368,327
null
1
9
excel|filepath|excel-2010
119,930
<p>Answer to my own question. The only way I have found that works consistently and instantaneously is to:</p> <p>1) Create a link in my "Favorites" to the directory I use</p> <p>2) Update the properties on that favorite to be an absolute path (\\ads\IT-DEPT-DFS\Data\MAILROOM)</p> <p>3) When saving a new file, I navigate to that directory only via the Favorites directory created above (or you can use any Shortcut with an absolute path)</p> <p>4) After saving, go to the File tab and the full path can be copied from the top of the Info (default) section</p>
4,842,956
Python: How to remove empty lists from a list?
<p>I have a list with empty lists in it:</p> <pre><code>list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText'] </code></pre> <p>How can I remove the empty lists so that I get:</p> <pre><code>list2 = ['text', 'text2', 'moreText'] </code></pre> <p>I tried list.remove('') but that doesn't work.</p>
4,842,965
9
2
null
2011-01-30 12:49:03.337 UTC
26
2018-11-14 13:51:01.537 UTC
2011-07-02 10:11:47.153 UTC
null
201,665
null
595,771
null
1
95
python|list
152,075
<p>Try</p> <pre><code>list2 = [x for x in list1 if x != []] </code></pre> <p>If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use</p> <pre><code>list2 = [x for x in list1 if x] </code></pre>
16,581,420
How to get table column index using jQuery?
<p>I have adequate knowledge about jQuery and its usage but today i got into a trouble of getting the column index of matching label inside <code>th</code> element of <code>table</code> using jQuery. I want to get the index of <code>th</code> element having <code>label</code> text as <strong>Mobile</strong>. The index should be 2 in this case. I am getting the actual index but this is not the correct way of doing it. So i want to know why jQuery is not giving me the right index using <code>index()</code> method.</p> <p>I have also written the <a href="http://jsfiddle.net/furqansafdar/DHkb4/2/" rel="noreferrer">JS Fiddler</a> for this.</p> <p><strong>jQuery</strong></p> <pre class="lang-js prettyprint-override"><code>var elem = $('#tbl th'); var rIndex; alert('Length : ' + elem.length); var index = elem.filter( function(index){ var labelText = $(this).find('label').text(); //alert(index + ' - ' + labelText); var result = labelText == 'Mobile'; if (result) rIndex = index; return result; }).index(); alert("jQuery Index : " + index); alert("Actual Index : " + rIndex); </code></pre> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;table id="tbl"&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;th&gt;&lt;label&gt;Application No.&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;/td&gt; &lt;th&gt;&lt;label&gt;Name&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;/td&gt; &lt;th&gt;&lt;label&gt;Mobile&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;/td&gt; &lt;th&gt;&lt;label&gt;Gender&lt;/label&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
16,581,712
8
0
null
2013-05-16 07:27:30.717 UTC
1
2018-01-25 08:05:30.913 UTC
2017-01-21 21:29:30.057 UTC
null
4,370,109
null
387,058
null
1
8
jquery|html|indexing|html-table
53,394
<p>If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.</p> <p>This will give you real index <strong><a href="http://jsfiddle.net/DHkb4/4/">DEMO</a></strong></p> <pre><code>elem.each(function(){ if( $(this).find('label').text()=='Mobile') { alert(elem.index(this)); } }); </code></pre>
12,116,524
Python 2.7.3 . . . Write .jpg/.png image file?
<p>So I have a .jpg/.png and I opened it up in Text Edit which I provided below:</p> <p><strong>Is there anyway I can save these exotic symbols to a string in Python to later write that to a file to produce an image?</strong></p> <p>I tried to import a string that had the beta symbol in it and I got an error that send Non-ASCII so I am assuming the same would happen for this.</p> <p>Is there anyway to get around this problem?</p> <p>Thanks</p> <p>Portion of Image.png in Text Edit:</p> <p><img src="https://i.stack.imgur.com/rfbbL.png" alt="enter image description here"></p>
12,116,606
2
2
null
2012-08-24 20:55:15.257 UTC
3
2020-12-24 11:03:27.423 UTC
null
null
null
null
678,572
null
1
6
python|image|file|text|fwrite
57,094
<p>What you are looking at in your text edit is a binary file, trying to represent it all in human readable characters.</p> <p>Just open the file as binary in python:</p> <pre><code>with open('picture.png', 'rb') as f: data = f.read() with open('picture_out.png', 'wb') as f: f.write(data) </code></pre>
12,301,071
multidimensional confidence intervals
<p>I have numerous tuples (par1,par2), i.e. points in a 2 dimensional parameter space obtained from repeating an experiment multiple times.</p> <p>I'm looking for a possibility to calculate and visualize confidence ellipses (not sure if thats the correct term for this). Here an example plot that I found in the web to show what I mean:</p> <p><img src="https://i.stack.imgur.com/T26Cc.png" alt="enter image description here"></p> <p>source: blogspot.ch/2011/07/classification-and-discrimination-with.html</p> <p>So in principle one has to fit a multivariate normal distribution to a 2D histogram of data points I guess. Can somebody help me with this?</p>
12,321,306
4
3
null
2012-09-06 13:20:39.267 UTC
20
2016-09-28 14:09:50.26 UTC
null
null
null
null
1,138,523
null
1
20
python|matplotlib|scipy
27,028
<p>It sounds like you just want the 2-sigma ellipse of the scatter of points?</p> <p>If so, consider something like this (From some code for a paper here: <a href="https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py" rel="noreferrer">https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py</a>):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse def plot_point_cov(points, nstd=2, ax=None, **kwargs): """ Plots an `nstd` sigma ellipse based on the mean and covariance of a point "cloud" (points, an Nx2 array). Parameters ---------- points : An Nx2 array of the data points. nstd : The radius of the ellipse in numbers of standard deviations. Defaults to 2 standard deviations. ax : The axis that the ellipse will be plotted on. Defaults to the current axis. Additional keyword arguments are pass on to the ellipse patch. Returns ------- A matplotlib ellipse artist """ pos = points.mean(axis=0) cov = np.cov(points, rowvar=False) return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs) def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs): """ Plots an `nstd` sigma error ellipse based on the specified covariance matrix (`cov`). Additional keyword arguments are passed on to the ellipse patch artist. Parameters ---------- cov : The 2x2 covariance matrix to base the ellipse on pos : The location of the center of the ellipse. Expects a 2-element sequence of [x0, y0]. nstd : The radius of the ellipse in numbers of standard deviations. Defaults to 2 standard deviations. ax : The axis that the ellipse will be plotted on. Defaults to the current axis. Additional keyword arguments are pass on to the ellipse patch. Returns ------- A matplotlib ellipse artist """ def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:,order] if ax is None: ax = plt.gca() vals, vecs = eigsorted(cov) theta = np.degrees(np.arctan2(*vecs[:,0][::-1])) # Width and height are "full" widths, not radius width, height = 2 * nstd * np.sqrt(vals) ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs) ax.add_artist(ellip) return ellip if __name__ == '__main__': #-- Example usage ----------------------- # Generate some random, correlated data points = np.random.multivariate_normal( mean=(1,1), cov=[[0.4, 9],[9, 10]], size=1000 ) # Plot the raw points... x, y = points.T plt.plot(x, y, 'ro') # Plot a transparent 3 standard deviation covariance ellipse plot_point_cov(points, nstd=3, alpha=0.5, color='green') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/vUzAh.png" alt="enter image description here"></p>
12,053,107
Test a string if it's Unicode, which UTF standard is and get its length in bytes?
<p>I need to test if a string is Unicode, and then if it whether it's UTF-8. After that, get the string's length in bytes including the <a href="http://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">BOM</a>, if it ever uses that. How can this be done in Python?</p> <p>Also for didactic purposes, what does a byte list representation of a UTF-8 string look like? I am curious how a UTF-8 string is represented in Python.</p> <p>Latter edit: pprint does that pretty well.</p>
12,053,219
3
7
null
2012-08-21 10:37:10.943 UTC
13
2013-11-25 14:38:59.363 UTC
2013-11-25 14:38:59.363 UTC
null
1,577,343
null
1,577,343
null
1
24
python|string|unicode|utf-8|python-2.5
61,329
<pre><code>try: string.decode('utf-8') print "string is UTF-8, length %d bytes" % len(string) except UnicodeError: print "string is not UTF-8" </code></pre> <p>In Python 2, <code>str</code> is a sequence of bytes and <code>unicode</code> is a sequence of characters. You use <code>str.decode</code> to decode a byte sequence to <code>unicode</code>, and <code>unicode.encode</code> to encode a sequence of characters to <code>str</code>. So for example, <code>u"é"</code> is the unicode string containing the single character U+00E9 and can also be written <code>u"\xe9"</code>; encoding into UTF-8 gives the byte sequence <code>"\xc3\xa9"</code>.</p> <p>In Python 3, this is changed; <code>bytes</code> is a sequence of bytes and <code>str</code> is a sequence of characters.</p>
12,400,567
Difference between "on .. and" and "on .. where" in SQL Left Join?
<p>Sql statement.</p> <pre><code>1.select a.* from A a left join B b on a.id =b.id and a.id=2; 2.select a.* from A a left join B b on a.id =b.id where a.id=2; </code></pre> <p>what is the difference of this two sql statement?</p>
12,401,086
6
5
null
2012-09-13 06:26:14.07 UTC
10
2022-02-09 23:02:39.347 UTC
2012-09-14 01:27:31.39 UTC
null
120,753
null
1,613,066
null
1
28
sql|join|syntax|where
17,402
<pre><code>create table A(id int); create table B(id int); INSERT INTO A VALUES(1); INSERT INTO A VALUES(2); INSERT INTO A VALUES(3); INSERT INTO B VALUES(1); INSERT INTO B VALUES(2); INSERT INTO B VALUES(3); SELECT * FROM A; SELECT * FROM B; id ----------- 1 2 3 id ----------- 1 2 3 </code></pre> <p>Filter on the JOIN to prevent rows from being added during the JOIN process.</p> <pre><code>select a.*,b.* from A a left join B b on a.id =b.id and a.id=2; id id ----------- ----------- 1 NULL 2 2 3 NULL </code></pre> <p>WHERE will filter after the JOIN has occurred.</p> <pre><code>select a.*,b.* from A a left join B b on a.id =b.id where a.id=2; id id ----------- ----------- 2 2 </code></pre>
12,593,768
How is Lisp dynamic and compiled?
<p>I don't understand how Lisp can be compiled and dynamic. For a language to be able to manipulate and modify and generate code, isn't it a requirement to be interpreted? Is it possible for a language to be completely compiled and still be dynamic? Or am I missing something? What is Lisp doing that allows it to be both compiled and dynamic?</p>
12,595,700
3
5
null
2012-09-26 02:31:38.263 UTC
12
2019-05-31 15:54:33.003 UTC
null
null
null
null
1,024,501
null
1
40
lisp|common-lisp
11,576
<p>Lisp is a wide family of language and implementations.</p> <p><em>Dynamic</em> in the context of Lisp means that the code has a certain flexibility at runtime. It can be changed or replaced for example. This is not the same as <em>dynamically typed</em>.</p> <p><strong>Compilation in Lisp</strong></p> <p>Often Lisp implementations have a compiler available at runtime. When this compiler is <em>incremental</em>, it does not need whole programs, but can compile single Lisp forms. Then we say that the compiler supports <em>incremental</em> compilation.</p> <p>Note that most Lisp compilers are not <em>Just In Time</em> compilers. You as a programmer can invoke the compiler, for example in Common Lisp with the functions <a href="http://www.lispworks.com/documentation/HyperSpec/Body/f_cmp.htm" rel="noreferrer"><code>COMPILE</code></a> and <a href="http://www.lispworks.com/documentation/HyperSpec/Body/f_cmp_fi.htm" rel="noreferrer"><code>COMPILE-FILE</code></a>. Then Lisp code gets compiled.</p> <p>Additionally most Lisp systems with both a compiler and an interpreter allow the execution of interpreted and compiled code to be freely mixed.</p> <p>In Common Lisp the compiler can also be instructed how dynamic the compiled code should be. A more advanced Lisp compiler like the compiler of <a href="http://www.sbcl.org/" rel="noreferrer">SBCL</a> (or many others) can then generate different code.</p> <p><strong>Example</strong></p> <pre><code>(defun foo (a) (bar a 3)) </code></pre> <p>Above function <code>foo</code> calls the function <code>bar</code>.</p> <p>If we have a global function <code>bar</code> and redefine it, then we expect in Lisp usually that the new function <code>bar</code> will be called by <code>foo</code>. We don't have to recompile <code>foo</code>.</p> <p>Let's look at <a href="http://www.clisp.org/" rel="noreferrer">GNU CLISP</a>. It compiles to <em>byte code</em> for a <em>virtual machine</em>. It's not native machine code, but for our purpose here it is easier to read.</p> <pre><code>CL-USER 1 &gt; (defun foo (a) (bar a 3)) FOO CL-USER 2 &gt; (compile 'foo) FOO NIL NIL [3]&gt; (disassemble #'foo) Disassembly of function FOO (CONST 0) = 3 (CONST 1) = BAR 1 required argument 0 optional arguments No rest parameter No keyword parameters 4 byte-code instructions: 0 (LOAD&amp;PUSH 1) 1 (CONST&amp;PUSH 0) ; 3 2 (CALL2 1) ; BAR 4 (SKIP&amp;RET 2) </code></pre> <p><strong>Runtime lookup</strong></p> <p>So you see that the call to <code>BAR</code>does a runtime lookup. It looks at the <em>symbol</em> <code>BAR</code> and then calls the symbol's function. Thus the symbol table serves as a registry for global functions.</p> <p>This runtime lookup in combination with an incremental compiler - available at runtime - allows us to generate Lisp code, compile it, load it into the current Lisp system and have it modify the Lisp program piece by piece.</p> <p>This is done by using an indirection. At runtime the Lisp system looks up the current function named <code>bar</code>. But note, this has nothing to do with compilation or interpretation. If your compiler compiles <code>foo</code> and the generated code uses this mechanism, then it is <em>dynamic</em>. So you would have the lookup overhead both in the interpreted and the compiled code.</p> <p>Since the 70s the Lisp community put a lot of effort into making the semantics of compiler and interpreter as similar as possible.</p> <p>A language like Common Lisp also allows the compiler to make the compiled code less dynamic. For example by not looking up functions at run time for certain parts of the code.</p>
12,508,180
How do you "Mavenize" a project using Intellij?
<p>I have seen many posts about using eclipse to Mavenize a project. Is there a easy way to do that in IntelliJ? From what I understand about "Mavenize", it's just add some xml in pom.xml and the directory structure is in src/main/java, src/main/test ....</p>
42,914,032
5
1
null
2012-09-20 07:49:40.493 UTC
11
2022-05-04 06:51:55.86 UTC
2017-03-21 00:08:48.747 UTC
null
1,292,323
null
1,290,668
null
1
61
java|maven|intellij-idea
50,692
<p>For those that benefit from a visual, as I did:</p> <p><a href="https://i.stack.imgur.com/xXkRW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xXkRW.png" alt="enter image description here"></a></p> <p>Essentially, just right-click on the folder. In this example, it's called <code>StackOverFlow</code> and choose <code>Add Framework Support</code> and then check the <code>Maven</code> box. Please note, that this option only exists when you have created a class within the <code>src</code> folder.</p>
12,575,965
Is it possible to develop Google Chrome extensions using node.js?
<p>I'd like to start developing Google Chrome extension using node.js (since I've already written a "text-to-song" script in node.js, and I'd like to turn it into a Chrome extension.) What would be the most straightforward way of approaching this problem?</p>
14,174,691
3
6
null
2012-09-25 03:53:05.76 UTC
33
2022-01-05 19:59:10.153 UTC
null
null
null
null
975,097
null
1
63
node.js|google-chrome-extension
78,704
<p>Actually it is. Look at this <a href="http://www.youtube.com/watch?v=gkb_x9ZN0Vo" rel="nofollow noreferrer">Developers Live-cast</a>. This is something I've been looking for as well, and this would help you.</p> <p>This brings your node applications bundled to your browser. Here is the <a href="https://github.com/substack/node-browserify" rel="nofollow noreferrer">repo</a>!</p> <p><strong>EDIT:</strong></p> <p>I've noticed that this old answer of mine keeps getting upvotes now and then (thank you all).</p> <p>But nowadays I'm more an advocate of using web apps instead of bundling your application into many platforms like the chrome store or whatever. You can check the google's post <a href="https://blog.chromium.org/2016/08/from-chrome-apps-to-web.html" rel="nofollow noreferrer">here</a> and <a href="https://web.dev/progressive-web-apps/" rel="nofollow noreferrer">here</a> indicating some directions.</p> <p>In practice I advise for you to start building a progressive web app (PWA) with offline capabilities using service worker and progressive stuff.</p> <p>There are plenty of resources around the web nowadays and you can offer a much richer application that may achieve a much broader audience if you do it the right way.</p> <p>Thanks again, and good coding.</p>
12,402,092
File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?
<p>I upgraded <a href="http://en.wikipedia.org/wiki/Xcode" rel="noreferrer">Xcode</a> version and when using external static libraries, I get this message:</p> <blockquote> <p>ld: file is universal (3 slices) but does not contain a(n) armv7s slice: /file/location for architecture armv7s clang: error: linker command failed with exit code 1 (use -v to see invocation)</p> </blockquote> <p>Is there any way to bypass this and add support to the library if the developer of the library hasn't updated their library yet?</p>
12,402,966
8
1
null
2012-09-13 08:15:38.833 UTC
98
2020-07-16 17:53:31.027 UTC
2013-02-16 09:35:12.423 UTC
null
63,550
null
1,667,961
null
1
407
ios|objective-c|xcode|ios6|static-libraries
163,348
<p>If you want to remove the support for any architecture, for example, <a href="http://en.wikipedia.org/wiki/ARM_architecture#ARM_cores" rel="noreferrer">ARMv7-s</a> in your case, use menu <em>Project</em> -> <em>Build Settings</em> -> remove the architecture from "valid architectures".</p> <p>You can use this as a temporary solution until the library has been updated. You have to remove the architecture from your main project, not from the library.</p> <p>Alternatively, you can set the flag for your debug configuration's "Build Active Architecture Only" to Yes. Leave the release configuration's "Build Active Architecture Only" to No, just so you'll get a reminder before releasing that you ought to upgrade any third-party libraries you're using.</p>
24,447,786
Notepad ++ doesn't save document on exit?
<p>Situation:</p> <p>Open a text file in n++, make some modification, press ALT-F4 or Close program. The N++ won't ask "Do you want to save your changes". Instead it quits and text file on hdd remains unchanged.</p> <p>But when I open the N++ again, the MODIFIED file is still in there. Red tab is indicating unsaved changes and I can save it by ctrl-s. I can also save it by closing the tab (n++ will ask).</p> <p>I want to save the file automatically every time I close the n++. All of my other istallations does that but this. I could not find any settings in the n++ options. Any idea?</p>
24,448,488
5
4
null
2014-06-27 08:55:27.16 UTC
8
2020-06-06 09:53:36.56 UTC
2017-03-08 07:33:22.143 UTC
null
2,828,213
null
2,828,213
null
1
54
notepad++
37,820
<p>New feature added in Notepad 6.6 for which the <a href="http://notepad-plus-plus.org/news/notepad-6.6-release.html" rel="nofollow noreferrer">release notes</a> say:</p> <blockquote> <p>The main feature of this release is Session snapshot &amp; periodic backup. If this feature is enabled (enabled by default), user won't be asked to save unsaved file as he quits Notepad++, and on startup Notepad++ restores the unsaved file and unsaved untitled document of last session.</p> </blockquote> <p>This facility is controlled via menu => <strong>Settings</strong> => <strong>Preferences</strong> => <strong>Backup</strong>. For more details see also <a href="https://npp-user-manual.org/docs/preferences/#backup" rel="nofollow noreferrer">this section</a> of the <a href="https://npp-user-manual.org/" rel="nofollow noreferrer">Notepad++ User Manual</a>.</p>
3,983,613
Find tunnel 'center line'?
<p>I have some map files consisting of 'polylines' (each line is just a list of vertices) representing tunnels, and I want to try and find the tunnel 'center line' (shown, roughly, in red below). </p> <p><img src="https://i.stack.imgur.com/5aBy0.png" alt="alt text"></p> <p>I've had some success in the past using <a href="http://en.wikipedia.org/wiki/Delaunay_triangulation" rel="noreferrer">Delaunay triangulation</a> but I'd like to avoid that method as it does not (in general) allow for easy/frequent modification of my map data.</p> <p>Any ideas on how I might be able to do this?</p>
4,013,342
3
14
null
2010-10-21 01:24:05.187 UTC
12
2013-08-06 12:01:51.167 UTC
2011-02-28 02:42:53.77 UTC
null
353,410
null
338,803
null
1
11
algorithm|image|language-agnostic|graphics|geometry
4,675
<hr> <h1>An "algorithm" that works well with localized data changes. </h1> <hr> <h2>The critic's view</h2> <p> </p> <p><b><a href="http://en.wikipedia.org/wiki/The_Good,_the_Bad_and_the_Ugly" rel="noreferrer">The Good</a></b> </p> <p>The nice part is that it uses a mixture of image processing and graph operations available in most libraries, may be parallelized easily, is reasonable fast, may be tuned to use a relatively small memory footprint and doesn't have to be recalculated outside the modified area if you store the intermediate results.</p> <p><b><a href="http://en.wikipedia.org/wiki/The_Good,_the_Bad_and_the_Ugly" rel="noreferrer">The Bad</a></b> </p> <p>I wrote "algorithm", in quotes, just because I developed it and surely is not robust enough to cope with pathological cases. If your graph has a lot of cycles you may end up with some phantom lines. More on this and examples later.</p> <p><b><a href="http://en.wikipedia.org/wiki/The_Good,_the_Bad_and_the_Ugly" rel="noreferrer">And The Ugly</a></b></p> <p>The ugly part is that you need to be able to flood fill the map, which is not always possible. I posted a comment a few days ago asking if your graphs can be flood filled, but didn't receive an answer. So I decided to post it anyway. </p> <hr> <h2>The Sketch</h2> <p>The idea is:</p> <ol> <li>Use image processing to get a fine line of pixels representing the center path </li> <li>Partition the image in chunks commensurated to the tunnel thinnest passages</li> <li>At each partition, represent a point at the "center of mass" of the contained pixels</li> <li>Use those pixels to represent the Vertices of a Graph</li> <li>Add Edges to the Graph based on a "near neighbour" policy</li> <li>Remove spurious small cycles in the induced Graph </li> <li>End- The remaining Edges represent your desired path </li> </ol> <p>The parallelization opportunity arises from the fact that the partitions may be computed in standalone processes, and the resulting graph may be partitioned to find the small cycles that need to be removed. These factors also allow to reduce the memory needed by serializing instead of doing calcs in parallel, but I didn't go trough this. </p> <hr> <h2>The Plot</h2> <p>I'll no provide pseudocode, as the difficult part is just that not covered by your libraries. Instead of pseudocode I'll post the images resulting from the successive steps. I wrote the program in <a href="http://www.wolfram.com/" rel="noreferrer">Mathematica</a>, and I can post it if is of some service to you. </p> <p><b>A- Start with a nice flood filled tunnel image </b></p> <p><img src="https://i.stack.imgur.com/RJUs9.png" alt="alt text"></p> <p><b>B- Apply a Distance Transformation </b> </p> <p>The <a href="http://reference.wolfram.com/mathematica/ref/DistanceTransform.html" rel="noreferrer">Distance Transformation</a> gives the distance transform of image, where the value of each pixel is replaced by its distance to the nearest background pixel.<br> You can see that our desired path is the Local Maxima within the tunnel </p> <p><img src="https://i.stack.imgur.com/mE6JN.png" alt="alt text"> </p> <p><b>C- Convolve the image with an appropriate kernel </b> </p> <p>The selected kernel is a <a href="http://reference.wolfram.com/mathematica/ref/LaplacianGaussianFilter.html" rel="noreferrer">Laplacian-of-Gaussian kernel</a> of pixel radius 2. It has the magic property of enhancing the gray level edges, as you can see below. </p> <p><img src="https://i.stack.imgur.com/AJiEu.png" alt="alt text"> </p> <p><b>D- Cutoff gray levels and Binarize the image </b> </p> <p>To get a nice view of the center line! </p> <p><img src="https://i.stack.imgur.com/5rjm6.png" alt="alt text"></p> <p><b> Comment </b> </p> <p>Perhaps that is enough for you, as you ay know how to transform a thin line to an approximate piecewise segments sequence. As that is not the case for me, I continued this path to get the desired segments. </p> <p><b>E- Image Partition</b> </p> <p>Here is when some advantages of the algorithm show up: you may start using parallel processing or decide to process each segment at a time. You may also compare the resulting segments with the previous run and re-use the previous results </p> <p><img src="https://i.stack.imgur.com/Glmcy.png" alt="alt text"></p> <p><b>F- Center of Mass detection</b> </p> <p>All the white points in each sub-image are replaced by only one point at the center of mass<br> <code> X<sub>CM</sub> = (&Sigma; <sub>i∈<i>Points</i></sub> X<sub>i</sub>)/NumPoints<br> </code><br> <code> Y<sub>CM</sub> = (&Sigma; <sub>i∈<i>Points</i></sub> Y<sub>i</sub>)/NumPoints </code></p> <p>The white pixels are difficult to see (asymptotically difficult with param "a" <i>age</i>), but there they are.</p> <p><img src="https://i.stack.imgur.com/Axsqk.png" alt="alt text"></p> <p><b>G- Graph setup from Vertices</b> </p> <p>Form a Graph using the selected points as Vertex. Still no Edges. </p> <p><img src="https://i.stack.imgur.com/S2mwO.png" alt="alt text"></p> <p><b>H- select Candidate Edges</b> </p> <p>Using the Euclidean Distance between points, select candidate edges. A cutoff is used to select an appropriate set of Edges. Here we are using 1.5 the subimagesize. </p> <p>As you can see the resulting Graph have a few small cycles that we are going to remove in the next step.</p> <p><img src="https://i.stack.imgur.com/VKrQB.png" alt="alt text"> </p> <p><b>H- Remove Small Cycles</b> </p> <p>Using a Cycle detection routine we remove the small cycles up to a certain length. The cutoff length depends on a few parms and you should figure it empirically for your graphs family </p> <p><img src="https://i.stack.imgur.com/8EpIm.png" alt="alt text"> </p> <p><b>I- That's it!</b> </p> <p>You can see that the resulting center line is shifted a little bit upwards. The reason is that I'm superimposing images of different type in Mathematica ... and I gave up trying to convince the program to do what I want :)</p> <p><img src="https://i.stack.imgur.com/PeSsf.png" alt="alt text"></p> <hr> <h1>A Few Shots</h1> <p>As I did the testing, I collected a few images. They are probably the most un-tunnelish things in the world, but my Tunnels-101 went astray. </p> <p>Anyway, here they are. Remember that I have a displacement of a few pixels upwards ...</p> <p><img src="https://i.stack.imgur.com/56XqZ.png" alt="alt text"></p> <h2>HTH !</h2> <p>. </p> <h1>Update</h1> <p>Just in case you have access to <a href="http://www.wolfram.com/" rel="noreferrer">Mathematica 8</a> (I got it today) there is a new function <strong>Thinning</strong>. Just look: </p> <p><img src="https://i.stack.imgur.com/yE1e0.png" alt="alt text"> </p>
8,413,369
Parallel computing with clusters other than snow SOCK
<p>The recent addition of direct support for parallel computing in R2.14 sparked a question in my mind. There are numerous options for creating clusters in R. I use <code>snow</code> SOCK clusters on a regular basis, but I know that there are other ways such as MPI. I use SOCK <code>snow</code> clusters because I do not need to install any additional software (I use Fedora 13). </p> <p>So, my concrete questions: </p> <ol> <li>Is there a gain in performance when using non-SOCK clusters? </li> <li>Is it easier to create clusters on multiple computers using non-SOCK clusters?</li> </ol>
8,417,445
1
6
null
2011-12-07 09:53:50.77 UTC
9
2011-12-07 15:22:43.513 UTC
2011-12-07 15:22:43.513 UTC
null
1,033,808
null
1,033,808
null
1
18
r|parallel-processing|mpi
2,503
<p>1) there is a limited number of benchmarks available which proof that MPI will be faster than SOCKets. But as an R user you probably will not care about these differences. They are in the area of milli seconds and the number of communications is not that high in embarrassingly parallel problems</p> <p>2) Yes, you do not have to provide a list of machine names or IPs. For a computer cluster with 100 nodes this gets complicated. But everything depends on your computer cluster. In most cases MPI or PVM is already preinstalled and everything works out of the box using Rmpi, ...</p>
20,705,702
STL-pair-like triplet class - do I roll my own?
<p>I want to use a triplet class, as similar as possible to std::pair. STL doesn't seem to have one. I don't want to use something too heavy, like Boost. Is there some useful FOSS non-restrictive-license triplet class I could lift from somewhere? Should I roll my own? Should I do something else entirely?</p> <p><strong>Edit:</strong> About <code>std::tuple</code>...</p> <p>Is there really no benefit to a triplet-specific class? I mean, with tuple, I can't do</p> <pre><code>template&lt;typename T1, typename T2, typename T3&gt; std::tuple&lt;T1, T2, T3&gt; triple; </code></pre> <p>now can I? Won't I have to typedef individual-type-combination triples?</p>
20,705,724
5
7
null
2013-12-20 14:23:35.677 UTC
2
2021-04-16 15:35:29.48 UTC
2016-06-16 22:43:28.963 UTC
null
1,593,077
null
1,593,077
null
1
39
c++|c++-standard-library|stdtuple|triplet
26,381
<p>No, don't roll your own. Instead, take a look at <a href="http://en.cppreference.com/w/cpp/utility/tuple" rel="noreferrer"><code>std::tuple</code></a> - it's a generalization of <code>std::pair</code>. So here's a value-initialized triple of <code>int</code>s:</p> <pre><code>std::tuple&lt;int, int, int&gt; triple; </code></pre> <p>If you want, you can have a type alias for triples only:</p> <pre><code>template&lt;typename T1, typename T2, typename T3&gt; using triple = std::tuple&lt;T1, T2, T3&gt;; </code></pre>
10,889,357
Internet Explorer blocked this website from displaying content with security certificate errors
<p>I have a security certificate hosted by a CDN provider. The website is https:www.connect4fitness.com</p> <p>Navigating to the site in IE gives the following error:</p> <pre><code>"Internet Explorer blocked this website from displaying content with security certificate errors." </code></pre> <p>When I pull the site up in firefox or chrome, everything works fine. But I do see a warning about "Mixed content" and "Partially encrypted content" when I probe the certificate details.</p> <p>All the outbound links on the site are https. It's probably some content injected by the CDN that is triggering the message. But how do I pinpoint the exact part of the webpage that is not being encrypted? I need that information to work with the Tech Support of the CDN company as they are claiming everything is fine.</p> <p>Are there any tools or techniques that I can use to find out which part of the rendered page received by the browser was NOT encrypted?</p> <p><strong>Additional information:</strong></p> <p>Purging the CDN cache resolved the error messages for Firefox and Chrome. IE still complains about mixed content though I do not see any "http" requests going out on the Network tab. Any ideas? </p>
11,679,442
3
3
null
2012-06-04 22:36:29.267 UTC
1
2015-07-03 13:21:34.05 UTC
2012-06-05 15:25:11.223 UTC
null
421,227
null
421,227
null
1
6
security|internet-explorer|ssl
47,388
<p>I finally found the issue.</p> <p>I had javascript plugin for client-side exception logging (exceptionhub). This plugin inserted runtime JS to make an https call to it's servers for logging and got a certificate error. Apparently only IE found this objectionable as the other browsers did not complain.</p> <p>In the end I just got rid of the plugin because per their website they took care of the issue when they last had it (<a href="http://help.exceptionhub.com/discussions/problems/16-ssl-error-in-ie6" rel="nofollow">See here</a>). I think it probably recurred and I am not about to experiment with it as it was a nice-to-have plugin.</p>
11,367,727
How can I SHA512 a string in C#?
<p>I am trying to write a function to take a string and sha512 it like so?</p> <pre><code>public string SHA512(string input) { string hash; ~magic~ return hash; } </code></pre> <p>What should the magic be?</p>
11,367,793
12
0
null
2012-07-06 18:28:02.053 UTC
11
2022-07-21 08:39:08.477 UTC
2019-02-13 11:01:31.14 UTC
null
410,072
null
410,072
null
1
59
c#|hash
84,791
<p>Your code is correct, but you should dispose of the SHA512Managed instance:</p> <pre><code>using (SHA512 shaM = new SHA512Managed()) { hash = shaM.ComputeHash(data); } </code></pre> <p>512 bits are 64 bytes.</p> <p>To convert a string to a byte array, you need to specify an encoding. UTF8 is okay if you want to create a hash code:</p> <pre><code>var data = Encoding.UTF8.GetBytes("text"); using (... </code></pre>
12,697,427
Clear Selections of a Combobox
<p>I have a combobox with values that when selected, lead to other questions.</p> <p>I have a button that I want to be an "Up one level" button that clears all the following questions. It should reset the display of of the combobox to nothing, like before any options were selected, so the user can make a selection.</p> <p>I tried setting the Value = 0, the ListIndex = -1.</p> <p>I don't want to use "Clear" because I want to preserve the values in the combobox.</p> <p>I looked through the properties of a combobox and I can't pick out which one will do what I want.</p>
12,697,753
3
4
null
2012-10-02 20:03:21.307 UTC
null
2019-08-25 07:24:23.71 UTC
2019-04-18 14:48:51.893 UTC
null
-1
null
1,649,589
null
1
10
excel|vba|combobox
57,707
<pre><code>Listbox.Value=null </code></pre> <p>should do the trick.</p>
13,120,226
Wordpress localhost ftp
<p>I have wordpress running on my localhost on mac Lion.</p> <p>Everytime I try to install or delete plugins it asks me for hostname, ftp username and ftp password.</p> <p>I configured my localhost to 127.0.0.1, but I have never configured the ftp username and password for my localhost. How can I get which user and password it's by default?</p> <p>I have tried almost every user and pass I have on mysql, my osx admin, etc. with no results.</p> <p>Any ideas?</p>
13,121,012
6
5
null
2012-10-29 10:53:24.36 UTC
18
2021-01-09 10:58:59.763 UTC
null
null
null
user1617218
null
null
1
44
php|macos|wordpress|localhost
50,566
<p>In my experience, WordPress can be a bit fussy about permissions and ownership when it comes to self-update without FTP, so using FTP to localhost is a perfectly valid tactic, I'd say. But as others have said, just ensuring that everything from your WordPress root directory on downwards is writable by the PHP process, and owned by the same user, may well be enough to avoid the need for FTP.</p> <p>If you do want to use FTP, are you sure you've <a href="http://www.itworld.com/software/191971/enable-ftp-server-mac-os-x-lion">enabled the FTP server</a>? If so, you should just use a user who has permission to get to the directory via FTP (you can test with the command-line ftp tool.) As my sites are set up in my personal <code>Sites</code> directory, I just use my normal username and password (e.g. for <code>/Users/matt/Sites/whatever</code> I log in as <code>matt</code>.)</p> <p>Other things to check: What happens if you try <code>ftp localhost</code> on the command line? Can you log in there?</p>
13,110,542
How to get a timestamp in Dart?
<p>I've been learning Dart, but I don't know how to generate a timestamp. I have tried this:</p> <pre><code>void main() { print((new Date()).millisecondsSinceEpoch); } </code></pre> <p>Thanks to the IDE I was able to get this far, but I'm getting a confusing error:</p> <pre><code>Exception: No such method: 'Date' </code></pre> <p>Help?</p>
13,110,669
6
0
null
2012-10-28 16:11:05.593 UTC
18
2022-05-16 23:51:52.597 UTC
2012-12-30 20:09:21.707 UTC
null
638,061
user1781056
null
null
1
158
dart|epoch
129,174
<p>You almost had it right. You just did not use a <a href="http://www.dartlang.org/docs/dart-up-and-running/ch02.html#ch02-constructors-named" rel="noreferrer">named constructor</a>:</p> <pre class="lang-dart prettyprint-override"><code>void main() { print(DateTime.now().millisecondsSinceEpoch); } </code></pre> <p>Gives:</p> <blockquote> <p>1351441456747</p> </blockquote> <p>See the API documentation for more: <a href="https://api.dart.dev/stable/2.10.1/dart-core/DateTime-class.html" rel="noreferrer">https://api.dart.dev/stable/2.10.1/dart-core/DateTime-class.html</a></p>
12,919,980
Nohup is not writing log to output file
<p>I am using the following command to run a python script in the background:</p> <pre><code>nohup ./cmd.py &gt; cmd.log &amp; </code></pre> <p>But it appears that nohup is not writing anything to the log file. cmd.log is created but is always empty. In the python script, I am using <code>sys.stdout.write</code> instead of <code>print</code> to print to standard output. Am I doing anything wrong?</p>
12,920,094
7
3
null
2012-10-16 17:09:04.377 UTC
45
2021-02-08 12:03:23.86 UTC
null
null
null
user1642513
null
null
1
174
python|nohup
105,497
<p>It looks like you need to flush stdout periodically (e.g. <code>sys.stdout.flush()</code>). In my testing Python doesn't automatically do this even with <code>print</code> until the program exits.</p>
30,689,251
Failed to load sql modules into the database cluster during PostgreSQL Installation
<p>I have attempted to install PostgreSQL 9.4 and 8.4 multiple times and it is failing no matter what I have tried. I am attempting to install on Windows 7 SP1 x64. After each failed install I have uninstalled and deleted the installation folder to start fresh.</p> <p>Each time I attempt the install I get an error pop up near the end of installation that says: <em>"failed to load sql modules into the database cluster".</em></p> <p>Then another error pop up displays immediately after that says: <em>"Error running post install step. Installation may not complete correctly. Error reading C:/Program Files/PostgreSQL/9.4/postgresql.conf"</em></p> <p>I have attempted installation with the following actions:</p> <ul> <li>Always installed as administrator</li> <li>Turned off all virus protection and windows firewall</li> <li>Changed the installation directory to something other than the Program Files directory.</li> <li>Changed the data directory to something other than the installation directory of postgres</li> </ul> <p>None of the actions above have helped and I always receive the error. Any help that someone can provide would be greatly appreciated!</p>
31,815,962
15
8
null
2015-06-07 01:42:14.363 UTC
11
2021-07-07 16:21:45.767 UTC
null
null
null
null
4,982,424
null
1
45
postgresql
60,802
<p>I was getting this same error when trying to install PostgreSQL v9.4.4 on Windows 10 Pro. Starting with <a href="https://dba.stackexchange.com/questions/10241/postgresql-the-database-cluster-initialization-failed">a solution hosted on Stack Exchange</a>, I came up with the following steps that allowed the installer to run successfully:</p> <blockquote> <p>1) Create a new user account, called <em>postgres</em><br> 2) Add the new account to the <em>Administrators</em> and <em>Power Users</em> groups<br> 3) Restart the computer<br> &nbsp;&nbsp;&nbsp; NOTE: I added step #3, since step #4 didn't work without it<br> 4) Run a command prompt as the postgres user, using the command:<br> &nbsp;&nbsp;&nbsp; <em>runas /user:postgres cmd.exe</em><br> 5) Run the installer from the <em>postgres</em> command window<br> 6) Delete the <em>postgres</em> user account, as well as the user directory<br> &nbsp;&nbsp;&nbsp; NOTE: I added step #6, since the postgres account is not required after installation</p> </blockquote>
16,862,459
'numpy.float64' object is not iterable
<p>I'm trying to iterate an array of values generated with numpy.linspace:</p> <pre><code>slX = numpy.linspace(obsvX, flightX, numSPts) slY = np.linspace(obsvY, flightY, numSPts) for index,point in slX: yPoint = slY[index] arcpy.AddMessage(yPoint) </code></pre> <p>This code worked fine on my office computer, but I sat down this morning to work from home on a different machine and this error came up:</p> <pre><code>File "C:\temp\gssm_arcpy.1.0.3.py", line 147, in AnalyzeSightLine for index,point in slX: TypeError: 'numpy.float64' object is not iterable </code></pre> <p><code>slX</code> is just an array of floats, and the script has no problem printing the contents -- just, apparently iterating through them. Any suggestions for what is causing it to break, and possible fixes?</p>
16,865,814
1
6
null
2013-05-31 13:44:12.317 UTC
4
2021-04-14 12:14:41.813 UTC
2013-05-31 20:30:38.143 UTC
null
2,118,067
Erica
2,118,067
null
1
24
python|numpy|iterator
208,686
<p><code>numpy.linspace()</code> gives you a one-dimensional NumPy array. For example:</p> <pre><code>&gt;&gt;&gt; my_array = numpy.linspace(1, 10, 10) &gt;&gt;&gt; my_array array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]) </code></pre> <p>Therefore:</p> <pre><code>for index,point in my_array </code></pre> <p>cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:</p> <pre><code>&gt;&gt;&gt; two_d = numpy.array([[1, 2], [4, 5]]) &gt;&gt;&gt; two_d array([[1, 2], [4, 5]]) </code></pre> <p>Now you can do this:</p> <pre><code>&gt;&gt;&gt; for x, y in two_d: print(x, y) 1 2 4 5 </code></pre>
16,888,574
ExpandableListView child click listener not firing
<p>Not sure why my onChildClick isn't firing. Everything works perfectly, except that when one of the child items is tapped, absolutely nothing happens. Otherwise, the expandable groups work as expected. </p> <p>I've traced this back to my usage of the checkbox in the child xml file. When I remove this checkbox, the onChildClick fires as expected. But I need this checkbox for the functionality of this activity. What I am I doing wrong? Thanks!</p> <pre><code>public class MySettings extends Activity { private ExpandListAdapter expAdapter; private ArrayList&lt;ExpandListGroup&gt; expListItems; private ExpandableListView expandableList; private String client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_settings); expandableList = (ExpandableListView) findViewById(R.id.expandable_list); expListItems = SetStandardGroups(); //works fine - can show code if needed expAdapter = new ExpandListAdapter(MySettings.this, expListItems); expandableList.setAdapter(expAdapter); expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { //Nothing here ever fires System.err.println("child clicked"); Toast.makeText(getApplicationContext(), "child clicked", Toast.LENGTH_SHORT).show(); return true; } }); } </code></pre> <p>Here are the xml files:</p> <p>activity_my_settings.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:background="@drawable/background" &gt; &lt;ImageView android:id="@+id/logo" android:layout_marginTop="5dip" android:layout_alignParentTop="true" android:layout_width="wrap_content" android:layout_height="70dp" android:layout_gravity="left" android:contentDescription="@string/blank" android:src="@raw/logo" &gt; &lt;/ImageView&gt; &lt;TextView android:id="@+id/my_settings" android:textColor="#000000" android:layout_below="@id/logo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="@string/my_settings" android:textSize="30sp" android:textStyle="bold" /&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/my_settings" &gt; &lt;ExpandableListView android:id="@+id/expandable_list" android:scrollingCache="false" android:layout_marginTop="20dip" android:layout_height="wrap_content" android:layout_width="match_parent" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>expandlist_group_item.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="55dip" android:background="#FF7C7C7C" &gt; &lt;TextView android:id="@+id/group_header" android:layout_marginLeft="40dp" android:layout_width="fill_parent" android:layout_height="40dp" android:gravity="center_vertical" android:textColor="#000000" android:textSize="22sp" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>expandlist_child_item.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="55dip" android:orientation="horizontal" &gt; &lt;CheckBox android:id="@+id/check_box" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/expand_list_item" android:paddingLeft="10dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="@dimen/smart_finder_settings_font_size" android:textColor="#FFFFFF" /&gt; &lt;/LinearLayout&gt; </code></pre>
16,890,318
6
0
null
2013-06-03 00:20:57.15 UTC
7
2017-01-03 05:52:13.7 UTC
2013-06-03 04:48:45.573 UTC
null
1,024,973
null
1,024,973
null
1
28
android|expandablelistview|onclicklistener
34,658
<p>I got it. All I had to do was add</p> <pre><code>android:focusable="false" </code></pre> <p>within the CheckBox section of my expandlist_child_item.xml file.</p> <p>I hope that this helps somebody.</p>
25,770,180
How can I insert 10 million records in the shortest time possible?
<p>I have a file (which has 10 million records) like below:</p> <pre class="lang-none prettyprint-override"><code> line1 line2 line3 line4 ....... ...... 10 million lines </code></pre> <p>So basically I want to insert 10 million records into the database. so I read the file and upload it to SQL Server.</p> <p>C# code</p> <pre class="lang-cs prettyprint-override"><code>System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt"); while((line = file.ReadLine()) != null) { // insertion code goes here //DAL.ExecuteSql("insert into table1 values("+line+")"); } file.Close(); </code></pre> <p>but insertion will take a long time. How can I insert 10 million records in the shortest time possible using C#?</p> <p><strong>Update 1:</strong><br> Bulk INSERT:</p> <pre class="lang-sql prettyprint-override"><code>BULK INSERT DBNAME.dbo.DATAs FROM 'F:\dt10000000\dt10000000.txt' WITH ( ROWTERMINATOR =' \n' ); </code></pre> <p>My Table is like below:</p> <pre class="lang-sql prettyprint-override"><code>DATAs ( DatasField VARCHAR(MAX) ) </code></pre> <p>but I am getting following error:</p> <blockquote> <p>Msg 4866, Level 16, State 1, Line 1<br> The bulk load failed. The column is too long in the data file for row 1, column 1. Verify that the field terminator and row terminator are specified correctly. </p> <p>Msg 7399, Level 16, State 1, Line 1<br> The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.</p> <p>Msg 7330, Level 16, State 2, Line 1<br> Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".</p> </blockquote> <p>Below code worked:</p> <pre class="lang-sql prettyprint-override"><code>BULK INSERT DBNAME.dbo.DATAs FROM 'F:\dt10000000\dt10000000.txt' WITH ( FIELDTERMINATOR = '\t', ROWTERMINATOR = '\n' ); </code></pre>
25,773,471
4
9
null
2014-09-10 16:08:43.263 UTC
29
2018-06-19 06:34:20.97 UTC
2017-10-24 15:49:07.917 UTC
null
577,765
null
1,508,913
null
1
33
c#|sql-server|import|bulkinsert|table-valued-parameters
24,426
<p>Please do <em>not</em> create a <code>DataTable</code> to load via BulkCopy. That is an ok solution for smaller sets of data, but there is absolutely no reason to load all 10 million rows into memory before calling the database.</p> <p>Your best bet (outside of <code>BCP</code> / <code>BULK INSERT</code> / <code>OPENROWSET(BULK...)</code>) is to stream the contents from the file into the database via a Table-Valued Parameter (TVP). By using a TVP you can open the file, read a row &amp; send a row until done, and then close the file. This method has a memory footprint of just a single row. I wrote an article, <a href="http://www.sqlservercentral.com/articles/SQL+Server+2008/66554/">Streaming Data Into SQL Server 2008 From an Application</a>, which has an example of this very scenario.</p> <p>A simplistic overview of the structure is as follows. I am assuming the same import table and field name as shown in the question above.</p> <p>Required database objects:</p> <pre class="lang-sql prettyprint-override"><code>-- First: You need a User-Defined Table Type CREATE TYPE ImportStructure AS TABLE (Field VARCHAR(MAX)); GO -- Second: Use the UDTT as an input param to an import proc. -- Hence "Tabled-Valued Parameter" (TVP) CREATE PROCEDURE dbo.ImportData ( @ImportTable dbo.ImportStructure READONLY ) AS SET NOCOUNT ON; -- maybe clear out the table first? TRUNCATE TABLE dbo.DATAs; INSERT INTO dbo.DATAs (DatasField) SELECT Field FROM @ImportTable; GO </code></pre> <p>C# app code to make use of the above SQL objects is below. Notice how rather than filling up an object (e.g. DataTable) and then executing the Stored Procedure, in this method it is the executing of the Stored Procedure that initiates the reading of the file contents. The input parameter of the Stored Proc isn't a variable; it is the return value of a method, <code>GetFileContents</code>. That method is called when the <code>SqlCommand</code> calls <code>ExecuteNonQuery</code>, which opens the file, reads a row and sends the row to SQL Server via the <code>IEnumerable&lt;SqlDataRecord&gt;</code> and <code>yield return</code> constructs, and then closes the file. The Stored Procedure just sees a Table Variable, @ImportTable, that can be access as soon as the data starts coming over (<em>note: the data does persist for a short time, even if not the full contents, in tempdb</em>).</p> <pre class="lang-cs prettyprint-override"><code>using System.Collections; using System.Data; using System.Data.SqlClient; using System.IO; using Microsoft.SqlServer.Server; private static IEnumerable&lt;SqlDataRecord&gt; GetFileContents() { SqlMetaData[] _TvpSchema = new SqlMetaData[] { new SqlMetaData("Field", SqlDbType.VarChar, SqlMetaData.Max) }; SqlDataRecord _DataRecord = new SqlDataRecord(_TvpSchema); StreamReader _FileReader = null; try { _FileReader = new StreamReader("{filePath}"); // read a row, send a row while (!_FileReader.EndOfStream) { // You shouldn't need to call "_DataRecord = new SqlDataRecord" as // SQL Server already received the row when "yield return" was called. // Unlike BCP and BULK INSERT, you have the option here to create a string // call ReadLine() into the string, do manipulation(s) / validation(s) on // the string, then pass that string into SetString() or discard if invalid. _DataRecord.SetString(0, _FileReader.ReadLine()); yield return _DataRecord; } } finally { _FileReader.Close(); } } </code></pre> <p>The <code>GetFileContents</code> method above is used as the input parameter value for the Stored Procedure as shown below:</p> <pre class="lang-cs prettyprint-override"><code>public static void test() { SqlConnection _Connection = new SqlConnection("{connection string}"); SqlCommand _Command = new SqlCommand("ImportData", _Connection); _Command.CommandType = CommandType.StoredProcedure; SqlParameter _TVParam = new SqlParameter(); _TVParam.ParameterName = "@ImportTable"; _TVParam.TypeName = "dbo.ImportStructure"; _TVParam.SqlDbType = SqlDbType.Structured; _TVParam.Value = GetFileContents(); // return value of the method is streamed data _Command.Parameters.Add(_TVParam); try { _Connection.Open(); _Command.ExecuteNonQuery(); } finally { _Connection.Close(); } return; } </code></pre> <p>Additional notes:</p> <ol> <li>With some modification, the above C# code can be adapted to batch the data in.</li> <li>With minor modification, the above C# code can be adapted to send in multiple fields (the example shown in the "Steaming Data..." article linked above passes in 2 fields).</li> <li>You can also manipulate the value of each record in the <code>SELECT</code> statement in the proc.</li> <li>You can also filter out rows by using a WHERE condition in the proc.</li> <li>You can access the TVP Table Variable multiple times; it is READONLY but not "forward only".</li> <li>Advantages over <code>SqlBulkCopy</code>: <ol> <li><code>SqlBulkCopy</code> is INSERT-only whereas using a TVP allows the data to be used in any fashion: you can call <code>MERGE</code>; you can <code>DELETE</code> based on some condition; you can split the data into multiple tables; and so on.</li> <li>Due to a TVP not being INSERT-only, you don't need a separate staging table to dump the data into.</li> <li>You can get data back from the database by calling <code>ExecuteReader</code> instead of <code>ExecuteNonQuery</code>. For example, if there was an <code>IDENTITY</code> field on the <code>DATAs</code> import table, you could add an <code>OUTPUT</code> clause to the <code>INSERT</code> to pass back <code>INSERTED.[ID]</code> (assuming <code>ID</code> is the name of the <code>IDENTITY</code> field). Or you can pass back the results of a completely different query, or both since multiple results sets can be sent and accessed via <code>Reader.NextResult()</code>. Getting info back from the database is not possible when using <code>SqlBulkCopy</code> yet there are several questions here on S.O. of people wanting to do exactly that (at least with regards to the newly created <code>IDENTITY</code> values).</li> <li>For more info on why it is sometimes faster for the overall process, even if slightly slower on getting the data from disk into SQL Server, please see this whitepaper from the SQL Server Customer Advisory Team: <a href="http://blogs.msdn.com/b/sqlcat/archive/2013/09/23/maximizing-throughput-with-tvp.aspx">Maximizing Throughput with TVP</a></li> </ol></li> </ol>
70,202,832
Is it possible to deprecate implicit conversion while allowing explicit conversion?
<p>Suppose I have a simple <code>Duration</code> class:</p> <pre><code>class Duration { int seconds; public: Duration(int t_seconds) : seconds(t_seconds) { } }; int main() { Duration t(30); t = 60; } </code></pre> <p>And I decide that I don't like being able to implicitly convert from <code>int</code> to <code>Duration</code>. I can make the constructor <code>explicit</code>:</p> <pre><code>class Duration { int seconds; public: explicit Duration(int t_seconds) : seconds(t_seconds) { } }; int main() { Duration t(30); // This is fine, conversion is explicit t = 60; // Doesn't compile: implicit conversion no longer present for operator= } </code></pre> <p>But what if I don't want to immediately break all calling code that's implicitly converting to <code>Duration</code>? What I would like to have is something like:</p> <pre><code>class Duration { int seconds; public: [[deprecated]] Duration(int t_seconds) : seconds(t_seconds) { } explicit Duration(int t_seconds) : seconds(t_seconds) { } }; int main() { Duration t(30); // Compiles, no warnings, uses explicit constructor t = 60; // Compiles but emits a deprecation warning because it uses implicit conversion } </code></pre> <p>This would allow existing code to compile while identifying any places that currently rely on implicit conversion, so they can either be rewritten to use explicit conversion if it's intended or rewritten to have correct behavior if not.</p> <p>However this is impossible because I can't overload <code>Duration::Duration(int)</code> with <code>Duration::Duration(int)</code>.</p> <p>Is there a way to achieve something like this effect short of &quot;Make the conversion explicit, accept that calling code won't compile until you've written the appropriate changes&quot;?</p>
70,203,119
1
3
null
2021-12-02 16:07:20.52 UTC
1
2021-12-13 19:06:32.123 UTC
null
null
null
null
12,334,309
null
1
30
c++|type-conversion
1,467
<p>You can turn <code>Duration(int t_seconds)</code> into a template function that can accept an <code>int</code> and set it to deprecated.</p> <pre><code>#include&lt;concepts&gt; class Duration { int seconds; public: template&lt;std::same_as&lt;int&gt; T&gt; [[deprecated(&quot;uses implicit conversion&quot;)]] Duration(T t_seconds) : Duration(t_seconds) { } explicit Duration(int t_seconds) : seconds(t_seconds) { } }; </code></pre> <p>If you allow <code>t = 0.6</code>, just change the <code>same_as</code> to <code>convertible_to</code>.</p> <p><a href="https://godbolt.org/z/a77v4bETG" rel="noreferrer">Demo.</a></p>
9,698,675
Add image source in Jquery
<p>In my MVC app, the images will b in the App_Data folder. I want to give the source to my img tag in Jquery. Here is how I do it:</p> <pre><code>var src1 = &lt;%=Url.Content(Server.MapPath("/AppData/1.jpg"))%&gt; $("#imgLocation").attr("src", src1); </code></pre> <p>But it doesn't work. Why?</p>
9,699,162
2
0
null
2012-03-14 09:02:45.953 UTC
2
2012-03-14 09:31:17.433 UTC
2012-03-14 09:10:02.587 UTC
null
966,638
null
966,638
null
1
6
jquery
45,930
<p>try following:</p> <pre><code>var src1 = '&lt;%=Url.Content(Server.MapPath("~/AppData/1.jpg"))%&gt;'; $("#imgLocation").attr("src", src1); </code></pre>
9,791,024
int[] array (sort lowest to highest)
<p>So I am not sure why this is becoming so hard for me, but I need to sort high to low and low to high.</p> <p>For high to low I have:</p> <pre><code>int a, b; int temp; int sortTheNumbers = len - 1; for (a = 0; a &lt; sortTheNumbers; ++a) { for (b = 0; b &lt; sortTheNumbers; ++b) { if (array[b] &lt; array[b + 1]) { temp = array[b]; array[b] = array[b + 1]; array[b + 1] = temp; } } } </code></pre> <p>However, I can't for the life of me get it to work in reverse (low to high), I have thought the logic through and it always returns 0's for all the values. Any help appreciated!</p> <p>The bigger picture is that I have a JTable with 4 columns, each column with entries of numbers, names, or dates. I need to be able to sort those back and forth.</p> <p>Thanks!</p>
9,791,300
11
3
null
2012-03-20 16:36:36.62 UTC
7
2018-03-30 14:51:08.587 UTC
2012-03-21 10:05:54.9 UTC
null
203,657
null
1,018,901
null
1
9
java|arrays|sorting
96,373
<p>Unless you think using already available sort functions and autoboxing is cheating:</p> <pre><code>Integer[] arr = { 12, 67, 1, 34, 9, 78, 6, 31 }; Arrays.sort(arr, new Comparator&lt;Integer&gt;() { @Override public int compare(Integer x, Integer y) { return x - y; } }); System.out.println("low to high:" + Arrays.toString(arr)); </code></pre> <p>Prints <code>low to high:[1, 6, 9, 12, 31, 34, 67, 78]</code></p> <p>if you need high to low change <code>x-y</code> to <code>y-x</code> in the comparator</p>
9,932,498
signing applications automatically with password in ant
<p>Currently i have a build process in place for all of our apps using <code>ANT</code>. I am adding the ability to build a <code>release</code> now and sign the apps.</p> <p>Currently i have the <code>ant.properties</code> with the correct properties. And it is in all the projects. And when i build the projects it works fine. Signs, aligns and gives me what i need. HOWEVER, we have many apps and they are all built in the build process.</p> <p>So the problem is, the user is having to type the password in at the <code>Please enter keystore password</code> and the <code>Please enter password for alias</code>.</p> <p>I was wondering if there was a way to get <code>ant</code> to enter that password for us or is there another way to sign using <code>ant</code> that would work? Maybe i could supply the password when the build process starts and just use that password every time it is asked to be used.</p> <p>Thanks</p>
9,933,151
2
0
null
2012-03-29 19:54:02.13 UTC
8
2013-02-06 11:39:00.48 UTC
null
null
null
null
427,763
null
1
20
android|ant|adt
9,826
<p>I just have these lines in my ant.properties and it signs automatically</p> <pre><code>key.store.password=mypasswordOne key.alias.password=mypasswordTwo key.store=c:/users/myname/my-release-key.keystore key.alias=release_alias </code></pre>
9,766,661
SQL Server: how to write an alter index statement to add a column to the unique index?
<p>I have a <code>UNIQUE, NON CLUSTERED</code> index on a table that is currently using 4 columns for the index. </p> <p>I want to create an alter script that can merely add another column to this index. The new column type is <code>varchar</code>. </p> <p>The database is SQL Server 2005. </p> <p>Thanks in advance. </p>
9,766,846
4
3
null
2012-03-19 07:53:39.603 UTC
11
2021-07-05 09:18:50.04 UTC
2012-03-19 08:13:10.603 UTC
null
13,302
null
41,543
null
1
66
sql-server-2005|indexing|alter
101,756
<p>You cannot alter an index - all you can do is</p> <ol> <li><p>drop the old index (<code>DROP INDEX (indexname) ON (tablename)</code>)</p> </li> <li><p>re-create the new index with the additional column in it:</p> <pre><code> CREATE UNIQUE NONCLUSTERED INDEX (indexname) ON dbo.YourTableName(columns to include) </code></pre> </li> </ol> <p>The <code>ALTER INDEX</code> statement in SQL Server (see <a href="https://docs.microsoft.com/en-us/sql/relational-databases/indexes/modify-an-index?view=sql-server-ver15" rel="noreferrer">docs</a>) is available to alter certain properties (storage properties etc.) of an existing index, but it doesn't allow changes to the columns that make up the index.</p>
9,954,794
Execute a shell function with timeout
<p>Why would this work</p> <pre><code>timeout 10s echo "foo bar" # foo bar </code></pre> <p>but this wouldn't</p> <pre><code>function echoFooBar { echo "foo bar" } echoFooBar # foo bar timeout 10s echoFooBar # timeout: failed to run command `echoFooBar': No such file or directory </code></pre> <p>and how can I make it work?</p>
9,954,867
11
1
null
2012-03-31 09:40:21.523 UTC
22
2022-01-30 18:48:39.403 UTC
2018-03-12 17:13:54.943 UTC
null
6,862,601
null
263,589
null
1
93
bash|function|shell|timeout
134,180
<p><code>timeout</code> is a command - so it is executing in a subprocess of your bash shell. Therefore it has no access to your functions defined in your current shell.</p> <p>The command <code>timeout</code> is given is executed as a subprocess of timeout - a grand-child process of your shell.</p> <p>You might be confused because <code>echo</code> is both a shell built-in and a separate command.</p> <p>What you can do is put your function in it's own script file, chmod it to be executable, then execute it with <code>timeout</code>.</p> <p>Alternatively fork, executing your function in a sub-shell - and in the original process, monitor the progress, killing the subprocess if it takes too long.</p>
10,145,946
What is causing the error `string.split is not a function`?
<p>Why am I getting...</p> <blockquote> <p>Uncaught TypeError: string.split is not a function</p> </blockquote> <p>...when I run...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var string = document.location; var split = string.split('/');</code></pre> </div> </div> </p>
10,145,979
5
1
null
2012-04-13 18:02:37.483 UTC
19
2021-02-05 15:27:38.503 UTC
2018-10-23 13:54:18.22 UTC
null
381,802
null
381,802
null
1
143
javascript|jquery|split
461,434
<p>Change this...</p> <pre><code>var string = document.location; </code></pre> <p>to this...</p> <pre><code>var string = document.location + ''; </code></pre> <p>This is because <code>document.location</code> is a <a href="https://developer.mozilla.org/en/DOM/window.location#Location_object">Location object</a>. The default <code>.toString()</code> returns the location in string form, so the concatenation will trigger that.</p> <hr> <p>You could also use <a href="https://developer.mozilla.org/en/Document_Object_Model_%28DOM%29/document.URL"><code>document.URL</code></a> to get a string.</p>
11,530,050
Perform UI Changes on main thread using dispatch_async or performSelectorOnMainThread?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5225130/grand-central-dispatch-gcd-vs-performselector-need-a-better-explanation">Grand Central Dispatch (GCD) vs. performSelector - need a better explanation</a> </p> </blockquote> <p>To execute "stuff" on the main thread, should I use <code>dispatch_async</code> or <code>performSelectorOnMainThread</code>? Is there a preferred way, right/or wrong, and/or best practice?</p> <p>Example: I'm performing some logic within the block of an <code>NSURLConnection sendAsynchronousRequest:urlRequest</code> method. Because I'm doing stuff to the main view such as presenting a <code>UIAlertView</code> I need to show the <code>UIAlertView</code> on the main thread. To do this I'm using the following code.</p> <pre><code>[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { // code snipped out to keep this question short if(![NSThread isMainThread]) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; }); } }]; </code></pre> <p>Within that same <code>if(![NSThread isMainThread])</code> statement I also call some custom methods. The question is, should I use the <code>dispatch_async</code> method that I'm using above or is it better to use <code>performSelectorOnMainThread</code> instead? For example, full code below:</p> <pre><code>[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { // code snipped out to keep this question short if(![NSThread isMainThread]) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; // call custom methods in dispatch_async? [self hideLoginSpinner]; }); // or call them here using performSelectorOnMainThread??? [self performSelectorOnMainThread:@selector(hideLoginSpinner) withObject:nil waitUntilDone:NO]; } }]; </code></pre> <p>FYI - If I DO NOT perform these actions on he main thread I see a few second delay when presenting the <code>UIAlertView</code> and I receive the following message in the debugger <code>wait_fences: failed to receive reply: 10004003</code>. I've learned that this is because you need to make changes to the UI on the main thread... In case someone is wondering why I'm doing what I'm doing...</p>
11,532,036
1
2
null
2012-07-17 20:04:49.52 UTC
10
2016-05-30 15:09:12.457 UTC
2017-05-23 12:07:58.473 UTC
null
-1
null
1,104,563
null
1
14
ios|objective-c|asynchronous|grand-central-dispatch|nsthread
27,806
<p>As mentioned in the links provided by Josh Caswell, the two are almost equivalent. The most notable differences is that <code>performSelectorOnMainThread</code> will only execute in the default run loop mode and will wait if the run loop is running in a tracking or other mode. However, there are some significant differences for writing and maintaining the code.</p> <ol> <li><code>dispatch_async</code> has the big advantage that the compiler does all its usual tests. If you mistype the method in <code>performSelectorOnMainThread</code> you fail at run time, rather than compile time.</li> <li><code>dispatch_async</code> makes it much easier to return data from the main thread using the <code>__block</code> qualifier.</li> <li><code>dispatch_async</code> makes it much easier to handle primitive arguments since you don't have to wrap them in an object. However, this comes with a potential pitfall. If you have a pointer to some data remember that block capture does not deep copy the data. On the other hand wrapping the data in an object as you would be forced to do for <code>performSelectorOnMainThread</code> does deep copy (unless you set special options). Without a deep copy you can run into intermittent bugs that are frustrating to debug. So this means you should wrap things like <code>char *</code> in <code>NSString</code> before you call <code>dispatch_async</code>.</li> </ol>
11,555,355
Calculating the distance between 2 points
<p>I have two points (x1,y1) and (x2,y2). I want to know whether the points are within 5 meters of one another.</p>
11,555,445
8
2
null
2012-07-19 06:49:54.687 UTC
3
2021-11-15 09:35:56.8 UTC
2016-06-01 23:04:37.623 UTC
null
477,420
null
1,307,376
null
1
17
c#
121,632
<p>measure the square distance from one point to the other:</p> <pre><code>((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) &lt; d*d </code></pre> <p>where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.</p> <p>or if you prefer: </p> <pre><code>(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) &lt; (d*d); </code></pre> <p>Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call <code>Math.Sqrt</code>, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.</p> <p>Of course you are talking in meters and I supposed point coordinates are expressed in meters too.</p>
11,589,308
d3.js how to dynamically add nodes to a tree
<p>I am using a d3.js tree, and would like to add nodes dynamically, rather than pre-loading the entire tree.</p> <p>How would i modify the following in order to dynamically add additional JSON nodes when a node is clicked? (see link below, and code below)</p> <p><a href="http://mbostock.github.com/d3/talk/20111018/tree.html">http://mbostock.github.com/d3/talk/20111018/tree.html</a></p> <p>So rather than pre-loading the entire tree, instead i would like to retrieve the child nodes only when the parent is clicked. I can retrieve the json for the child nodes in the toggle function, however i can't figure out how i can add them to the tree.</p> <pre><code>var m = [20, 120, 20, 120], w = 1280 - m[1] - m[3], h = 800 - m[0] - m[2], i = 0, root; var tree = d3.layout.tree() .size([h, w]); var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); var vis = d3.select("#body").append("svg:svg") .attr("width", w + m[1] + m[3]) .attr("height", h + m[0] + m[2]) .append("svg:g") .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); d3.json("flare.json", function(json) { root = json; root.x0 = h / 2; root.y0 = 0; function toggleAll(d) { if (d.children) { d.children.forEach(toggleAll); toggle(d); } } // Initialize the display to show a few nodes. root.children.forEach(toggleAll); toggle(root.children[1]); toggle(root.children[1].children[2]); toggle(root.children[9]); toggle(root.children[9].children[0]); update(root); }); function update(source) { var duration = d3.event &amp;&amp; d3.event.altKey ? 5000 : 500; // Compute the new tree layout. var nodes = tree.nodes(root).reverse(); // Normalize for fixed-depth. nodes.forEach(function(d) { d.y = d.depth * 180; }); // Update the nodes… var node = vis.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("svg:g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; }) .on("click", function(d) { toggle(d); update(d); }); nodeEnter.append("svg:circle") .attr("r", 1e-6) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeEnter.append("svg:text") .attr("x", function(d) { return d.children || d._children ? -10 : 10; }) .attr("dy", ".35em") .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; }) .text(function(d) { return d.name; }) .style("fill-opacity", 1e-6); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }); nodeUpdate.select("circle") .attr("r", 4.5) .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }); nodeUpdate.select("text") .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 1e-6); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links… var link = vis.selectAll("path.link") .data(tree.links(nodes), function(d) { return d.target.id; }); // Enter any new links at the parent's previous position. link.enter().insert("svg:path", "g") .attr("class", "link") .attr("d", function(d) { var o = {x: source.x0, y: source.y0}; return diagonal({source: o, target: o}); }) .transition() .duration(duration) .attr("d", diagonal); // Transition links to their new position. link.transition() .duration(duration) .attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(duration) .attr("d", function(d) { var o = {x: source.x, y: source.y}; return diagonal({source: o, target: o}); }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children. function toggle(d) { // I could retrieve the child nodes here, but how to add them to the tree? if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } } </code></pre>
11,590,093
2
0
null
2012-07-21 03:53:28.167 UTC
24
2018-06-06 00:30:56.21 UTC
2014-02-01 20:38:35.833 UTC
null
3,052,751
null
1,363,882
null
1
32
javascript|dom|svg|d3.js|transition
22,469
<p>I was able to dynamically add nodes by adding the following code in the toggle function:</p> <pre><code>$.getJSON(addthese.json, function(addTheseJSON) { var newnodes = tree.nodes(addTheseJSON.children).reverse(); d.children = newnodes[0]; update(d); }); </code></pre> <p>Notes: I am using jQuery to retrieve the json file</p>
11,813,498
Make Twitter Bootstrap navbar link active
<p>What's the standard way to make the active link in a Twitter Bootstrap navbar bolded? It's clear that a link gains the active appearance by gaining the "active" class. For example, the <code>Home</code> link below is active. When I click any link in the navbar, should a use jQuery to remove all classes from <code>li</code> elements and then add the <code>active</code> class to the link I've id'd? </p> <pre><code>&lt;ul class="nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>EDIT</strong>: I included</p> <pre><code>&lt;script type="text/javascript"&gt; $('.nav li a').on('click', function() { alert('clicked'); $(this).parent().parent().find('.active').removeClass('active'); $(this).parent().addClass('active'); }); &lt;/script&gt; </code></pre> <p>after the links. The alert appears when I click a link, but the "active" class is not added to the link.</p> <p>Here's all of my navbar HTML:</p> <pre><code>&lt;div class="navbar navbar-fixed-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;a class="brand" href="#"&gt;AuctionBase&lt;/a&gt; &lt;div class="nav-collapse"&gt; &lt;ul class="nav"&gt; &lt;li&gt;&lt;a href="home.php"&gt;Search&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="about.php"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
11,814,284
10
0
null
2012-08-05 02:21:57.5 UTC
24
2022-06-14 04:42:58.483 UTC
2012-08-05 05:56:42.743 UTC
null
81,053
null
365,298
null
1
39
php|jquery|twitter-bootstrap
81,309
<p>You need to ensure that you set the <em>active</em> class as part of the request response (as the page loads) and not before ie when the user clicks a link to request a different page.</p> <p>First you need to determine which <code>navlink</code> should be set as active and then add the <em>active</em> class to the <code>&lt;li&gt;</code>. The code would look something like this</p> <p><strong>Tested by asker</strong>:</p> <p><strong>HTML within php file</strong></p> <p>Call a php function inline within the <code>&lt;li&gt;</code> markup passing in the links destination request uri</p> <pre><code>&lt;ul class="nav"&gt; &lt;li &lt;?=echoActiveClassIfRequestMatches("home")?&gt;&gt; &lt;a href="home.php"&gt;Search&lt;/a&gt;&lt;/li&gt; &lt;li &lt;?=echoActiveClassIfRequestMatches("about")?&gt;&gt; &lt;a href="about.php"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>PHP function</strong></p> <p>The php function simple needs to compare the passed in request uri and if it matches the current page being rendered output <em>active</em> class</p> <pre><code>&lt;?php function echoActiveClassIfRequestMatches($requestUri) { $current_file_name = basename($_SERVER['REQUEST_URI'], ".php"); if ($current_file_name == $requestUri) echo 'class="active"'; } ?&gt; </code></pre>
11,857,615
Placing labels at the center of nodes in d3.js
<p>I am starting with d3.js, and am trying to create a row of nodes each of which contains a centered number label.</p> <p>I am able to produce the desired result visually, but the way I did it is hardly optimal as it involves hard-coding the x-y coordinates for each text element. Below is the code:</p> <pre><code>var svg_w = 800; var svg_h = 400; var svg = d3.select("body") .append("svg") .attr("width", svg_w) .attr("weight", svg_h); var dataset = []; for (var i = 0; i &lt; 6; i++) { var datum = 10 + Math.round(Math.random() * 20); dataset.push(datum); } var nodes = svg.append("g") .attr("class", "nodes") .selectAll("circle") .data(dataset) .enter() .append("circle") .attr("class", "node") .attr("cx", function(d, i) { return (i * 70) + 50; }) .attr("cy", svg_h / 2) .attr("r", 20); var labels = svg.append("g") .attr("class", "labels") .selectAll("text") .data(dataset) .enter() .append("text") .attr("dx", function(d, i) { return (i * 70) + 42 }) .attr("dy", svg_h / 2 + 5) .text(function(d) { return d; }); </code></pre> <p>The <code>node</code> class is custom CSS class I've defined separately for the <code>circle</code> elements, whereas classes <code>nodes</code> and <code>labels</code> are not explicitly defined and they are borrowed from this <a href="https://stackoverflow.com/questions/11102795/d3-node-labeling/11109803#11109803">answer</a>.</p> <p>As seen, the positioning of each text label is hard-coded so that it appears at the center of the each node. Obviously, this is not the right solution.</p> <p>My question is that how should I correctly associate each text label with each node circle dynamically so that if the positioning of a label changes along with that of a circle automatically. Conceptual explanation is extremely welcome with code example.</p>
11,865,807
3
3
null
2012-08-08 04:21:06.807 UTC
10
2015-07-13 17:00:48.503 UTC
2017-05-23 11:47:13.56 UTC
null
-1
null
548,240
null
1
57
javascript|svg|d3.js
63,467
<p>The <a href="http://www.w3.org/TR/SVG/text.html#TextAnchorProperty">text-anchor</a> attribute works as expected on an svg element created by D3. However, you need to append the <code>text</code> and the <code>circle</code> into a common <code>g</code> element to ensure that the <code>text</code> and the <code>circle</code> are centered with one another.</p> <p>To do this, you can change your <code>nodes</code> variable to:</p> <pre><code>var nodes = svg.append("g") .attr("class", "nodes") .selectAll("circle") .data(dataset) .enter() // Add one g element for each data node here. .append("g") // Position the g element like the circle element used to be. .attr("transform", function(d, i) { // Set d.x and d.y here so that other elements can use it. d is // expected to be an object here. d.x = i * 70 + 50, d.y = svg_h / 2; return "translate(" + d.x + "," + d.y + ")"; }); </code></pre> <p>Note that the <code>dataset</code> is now a list of objects so that <code>d.y</code> and <code>d.x</code> can be used instead of just a list of strings.</p> <p>Then, replace your <code>circle</code> and <code>text</code> append code with the following:</p> <pre><code>// Add a circle element to the previously added g element. nodes.append("circle") .attr("class", "node") .attr("r", 20); // Add a text element to the previously added g element. nodes.append("text") .attr("text-anchor", "middle") .text(function(d) { return d.name; }); </code></pre> <p>Now, instead of changing the position of the <code>circle</code> you change the position of the <code>g</code> element which moves both the <code>circle</code> and the <code>text</code>.</p> <p>Here is a <a href="http://jsfiddle.net/brantolsen/Ld6Uz/">JSFiddle</a> showing centered text on circles.</p> <p>If you want to have your text be in a separate <code>g</code> element so that it always appears on top, then use the <code>d.x</code> and <code>d.y</code> values set in the first <code>g</code> element's creation to <code>transform</code> the text.</p> <pre><code>var text = svg.append("svg:g").selectAll("g") .data(force.nodes()) .enter().append("svg:g"); text.append("svg:text") .attr("text-anchor", "middle") .text(function(d) { return d.name; }); text.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); </code></pre>
11,757,016
Performance differences between visibility:hidden and display:none
<p>I want to simplify things in my jQuery Backbone.js web application. One such simplification is the behavior of my menu and dialog widgets. </p> <p>Previously I created the div boxes of my menus at start and hid them using <code>display: none; opacity:0;</code>. When I needed a menu, I changed its style to <code>display:block</code> then used the jQuery ui position utility to position the div box (since elements with <code>display:none</code> cannot be positioned) and when it was done, finally changed its style to <code>opacity:1</code>. </p> <p>Now I want to just hide them with <code>visibility:hidden</code>, and when I need one, I use the position utility and then change the style to <code>visibility:visible</code>. When I begin using this new approach, I will have around 10 div boxes throughout the web application session that are hidden but occupy space, in contrast to the previous div boxes hidden with <code>display:none</code>. </p> <p>What are the implications of my new approach? Does it effect browser performance in any regard? </p>
11,757,068
8
0
null
2012-08-01 10:08:42.223 UTC
14
2020-12-15 06:06:04.65 UTC
2012-08-02 02:27:21.99 UTC
null
582,541
null
780,522
null
1
69
javascript|html|css|performance
62,456
<p>I'm not aware of any performance difference between <code>display:none</code> and <code>visibility:hidden</code> - even if there is, for as little as 10 elements it will be completely negligible. Your main concern should be, as you say, whether you want the elements to remain within the document flow, in which case <code>visibility</code> is a better option as it maintains the box model of the element.</p>
11,544,073
How do I deal with the max macro in windows.h colliding with max in std?
<p>So I was trying to get valid integer input from cin, and used an answer to this <a href="https://stackoverflow.com/questions/5864540/a-simple-question-about-cin/5864560#comment15263994_5864560">question</a>.</p> <p>It recommended:</p> <pre><code>#include &lt;Windows.h&gt; // includes WinDef.h which defines min() max() #include &lt;iostream&gt; using std::cin; using std::cout; void Foo() { int delay = 0; do { if(cin.fail()) { cin.clear(); cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } cout &lt;&lt; "Enter number of seconds between submissions: "; } while(!(cin &gt;&gt; delay) || delay == 0); } </code></pre> <p>Which gives me an error on Windows, saying that the <code>max</code> macro doesn't take that many arguments. Which means I have to do this</p> <pre><code>do { if(cin.fail()) { cin.clear(); #undef max cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); } cout &lt;&lt; "Enter number of seconds between submissions: "; } while(!(cin &gt;&gt; delay) || delay == 0); </code></pre> <p>To get it to work. That's pretty ugly; is there a better way to work around this issue? Maybe I should be storing the definition of <code>max</code> and redefining it afterward?</p>
11,544,154
6
5
null
2012-07-18 14:45:22.323 UTC
9
2022-07-19 13:31:34.3 UTC
2017-05-23 11:55:09.53 UTC
null
-1
null
290,072
null
1
79
c++|iostream|cin
37,989
<p>Define the macro <a href="http://support.microsoft.com/kb/143208"><code>NOMINMAX</code></a>:</p> <blockquote> <p>This will suppress the min and max definitions in Windef.h. </p> </blockquote>
19,894,995
Pydev Perspective Not Showing After Install For Eclipse
<p>After installing the latest version of Pydev on eclipse it is not showing under the list of available perspectives. </p> <p>Eclipse does however list pydev as being installed which seems weird to me. I would also like to add that I installed pydev through the standard method (Through the "install new software" option under help).</p> <p>Any help on how to resolve this would be greatly appreciated.</p>
19,897,351
18
3
null
2013-11-10 20:48:28.953 UTC
10
2022-03-31 14:49:41.463 UTC
2018-02-04 08:31:22.81 UTC
null
745,828
null
2,318,338
null
1
29
python|eclipse|pydev
43,738
<p>I spent hours trying to get PyDev 3.0.0 plugin working with Eclipse Kepler on my mac. I tried </p> <ol> <li>Marketplace installation</li> <li>Install Software through Update Site </li> <li>Dropping plugin files under eclipse/dropins</li> </ol> <p>Nothing worked until I finally tried version 2.8.2 of the plugin. I would say get a zip of 2.8.2 from <a href="http://sourceforge.net/projects/pydev/files/pydev/PyDev%202.8.2/PyDev%202.8.2.zip/download" rel="noreferrer">here</a> and put the unzippied version in your /dropins folder of Eclipse. Restart Eclipse. Then go to the preference menu and notice PyDev entry should be there. Sometime it is better to start the Eclipse with admin credentials. Something like this on command line:</p> <pre><code>sudo /Users/username/Softwares/eclipse/Eclipse.app/Contents/MacOS/eclipse </code></pre>
3,941,793
What is guaranteed about the size of a function pointer?
<p>In C, I need to know the size of a struct, which has function pointers in it. Can I be guaranteed that on all platforms and architectures:</p> <ul> <li>the size of a void* is the same size as a function pointer?</li> <li>the size of the function pointer does not differ due to its return type?</li> <li>the size of the function pointer does not differ due to its parameter types?</li> </ul> <p>I assume the answer is yes to all of these, but I want to be sure. For context, I'm calling <code>sizeof(struct mystruct)</code> and nothing more.</p>
3,941,867
4
0
null
2010-10-15 11:30:05.573 UTC
10
2014-09-04 10:13:02.193 UTC
null
null
null
null
104,021
null
1
37
c|pointers|type-conversion|function-pointers|sizeof
20,713
<p>From C99 spec, section 6.2.5, paragraph 27:</p> <blockquote> <p>A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.</p> </blockquote> <p>So no; no guarantee that a <code>void *</code> can hold a function pointer.</p> <p>And section 6.3.2.3, paragraph 8:</p> <blockquote> <p>A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.</p> </blockquote> <p>implying that one function pointer type can hold any other function pointer value. Technically, that's not the same as guaranteeing that function-pointer types can't vary in size, merely that their values occupy the same range as each other.</p>
3,854,113
What is an opaque value in C++?
<p>What is an "opaque value" in C++?</p>
3,854,144
5
7
null
2010-10-04 09:50:48.547 UTC
12
2018-07-14 11:00:56.927 UTC
2018-07-14 11:00:56.927 UTC
Roger Pate
1,033,581
null
174,614
null
1
41
c++|language-agnostic|terminology
20,454
<p>An example for an Opaque Value is <code>FILE</code> (from the C library):</p> <pre><code>#include &lt;stdio.h&gt; int main() { FILE * fh = fopen( "foo", "r" ); if ( fh != NULL ) { fprintf( fh, "Hello" ); fclose( fh ); } return 0; } </code></pre> <p>You get a <code>FILE</code> pointer from <code>fopen()</code>, and use it as a parameter for other functions, but you never bother with what it actually points <em>to</em>. </p>
3,539,120
Using Cython with Django. Does it make sense?
<p>Is it possible to optimize speed of a mission critical application developed in Django with Cython?</p> <p>Recently I have read on the internet, that Cython can turn a Python code to C like speed. Is this possible with Django?</p>
3,539,374
6
1
null
2010-08-21 21:44:46.083 UTC
11
2018-09-20 10:04:40.107 UTC
2017-02-22 09:10:10.56 UTC
null
1,783,163
null
280,100
null
1
38
python|django|cython
16,987
<blockquote> <p>Is it possible to optimize speed of a mission critical application developed in Django with Cython</p> </blockquote> <p>It's doubtful. </p> <p>Most of a web application response time is the non-HTML elements that must be downloaded separately. The usual rule of thumb is 8 static files per HTML page. (.CSS, .JS, images, etc.) </p> <p>Since none of that static content comes from Django, most of your web application's time-line is Apache (or Nginx or some other server software outside Django).</p> <p>When looking at just the time to produce the HTML, you'll find that most of the time is spent waiting for the database (even if it's in-memory SQLite, you'll see that the database tends to dominate the timeline)</p> <p>When you're through making Apache and the database go fast, then -- and only then -- you can consider the Python elements.</p> <p>Bottom Line. Don't waste any of your time on making Django and Python go faster.</p>
3,529,137
Is there a console scroll lock in IntelliJ?
<p>I've recently moved from Eclipse to IntelliJ and one feature I'm missing (or maybe just can't find) is the console scroll lock i.e. stop refocusing on the latest console entry.</p> <p>Is this possible in IntelliJ? I'm using v9 Ultimate edition.</p>
3,529,373
6
0
null
2010-08-20 08:03:29.44 UTC
1
2017-06-24 05:26:50.72 UTC
null
null
null
null
42,435
null
1
45
intellij-idea
10,985
<p>It depends where your cursor is. Just click on the part you want to be scroll locked.</p>
3,560,103
How to force a class to be initialised?
<p>What is the best and cleanest way to do this? Specifically, I need some code in a static initializer block to run in that class, but I'd like to make this as clean-looking as possible.</p>
3,560,261
6
6
null
2010-08-24 19:09:42.78 UTC
4
2016-08-10 15:54:50.897 UTC
2016-08-10 15:54:50.897 UTC
null
476,716
null
120,237
null
1
50
java|coding-style|static-initializer
24,675
<p>Loading != Initialization.</p> <p>You want your class to be initialized (this is when static blocks executed, among other things).</p> <p>An excerpt from the <a href="http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.4.1" rel="noreferrer">Java Language Specification</a> says:</p> <blockquote> <p>A class or interface type T will be initialized immediately before the first occurrence of >any one of the following:</p> <ul> <li>T is a class and an instance of T is created.</li> <li>T is a class and a static method declared by T is invoked.</li> <li>A static field declared by T is assigned.</li> <li>A static field declared by T is used and the field is not a constant variable (§4.12.4).</li> <li>T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed. </li> </ul> <p>Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.</p> </blockquote> <p>Doh, anovstrup, already said it: Just make an empty static function called <code>init</code>. Be sure to document that well... I personally can't see any use case for this in the context of well formed code though.</p>
3,333,553
How can I change the Java Runtime Version on Windows (7)?
<p>How can I change the Java Runtime Version on Windows.</p> <p>I installed Java&nbsp;7 for some tests, and now I need the old java6 as system default, but I don't want to uninstall the Java&nbsp;7 (I need it for later tests). Can I change the system-used <a href="https://en.wikipedia.org/wiki/Java_virtual_machine" rel="noreferrer">JRE</a> in the control panel/Java/JRE tab? I can change/edit/add/delete the user-used version, but not the system-used.</p>
3,338,059
8
0
null
2010-07-26 09:20:13.803 UTC
30
2018-05-24 16:54:21.283 UTC
2016-01-24 21:31:26.38 UTC
null
63,550
null
36,895
null
1
61
java|windows|registry|controls|panel
250,873
<p>For Java <strong>applications</strong>, i.e. programs that are delivered (usually) as <code>.jar</code> files and started with <code>java -jar xxx.jar</code> or via a shortcut that does the same, the JRE that will be launched will be the first one found on the <code>PATH</code>. </p> <p>If you installed a JRE or JDK, the likely places to find the <code>.exe</code>s are below directories like <code>C:\Program Files\JavaSoft\JRE\x.y.z</code>. However, I've found some "out of the box" Windows installations to (also?) have copies of <code>java.exe</code> and <code>javaw.exe</code> in <code>C:\winnt\system32</code> (NT and 2000) or <code>C:\windows\system</code> (Windows 95, 98). This is usually a pretty elderly version of Java: 1.3, maybe? You'll want to do <code>java -version</code> in a command window to check that you're not running some antiquated version of Java.</p> <p>You can of course override the PATH setting or even do without it by explicitly stating the path to java.exe / javaw.exe in your command line or shortcut definition.</p> <hr> <p>If you're running <strong>applets</strong> from the browser, or possibly also <strong>Java Web Start applications</strong> (they look like applications insofar as they have their own window, but you start them from the browser), the choice of JRE is determined by a set of registry settings:</p> <pre><code>Key: HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment Name: CurrentVersion Value: (e.g.) 1.3 </code></pre> <p>More registry keys are created using this scheme:</p> <pre><code>(e.g.) HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3 HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3.1 </code></pre> <p>i.e. one for the major and one including the minor version number. Each of these keys has values like these (examples shown):</p> <pre><code>JavaHome : C:\program Files\JavaSoft\JRE\1.3.1 RuntimeLib : C:\Program Files\JavaSoft\JRE\1.3.1\bin\hotspot\jvm.dll MicroVersion: 1 </code></pre> <p>... and your browser will look to these settings to determine which JRE to fire up.</p> <p>Since Java versions are changing pretty frequently, there's now a "wizard" called the "Java Control Panel" for manually switching your browser's Java version. This works for IE, Firefox and probably others like Opera and Chrome as well: It's the 'Java' applet in Windows' <code>System Settings</code> app. You get to pick any one of the installed JREs. I believe that wizard fiddles with those registry entries.</p> <p>If you're like me and have "uninstalled" old Java versions by simply wiping out directories, you'll find these "ghosts" among the choices too; so make sure the JRE you choose corresponds to an intact Java installation!</p> <hr> <p>Some other answers are recommending setting the <em>environment</em> variable <code>JAVA_HOME</code>. This is meanwhile outdated advice. Sun came to realize, around Java 2, that this environment setting is </p> <ol> <li>unreliable, as users often set it incorrectly, and </li> <li>unnecessary, as it's easy enough for the runtime to find the Java library directories, knowing they're in a fixed path relative to the path from which java.exe or javaw.exe was launched. </li> </ol> <p>There's hardly any modern Java software left that needs or respects the <code>JAVA_HOME</code> environment variable.</p> <hr> <p>More Information: </p> <ul> <li><a href="http://java.sun.com/j2se/1.3/runtime_win32.html" rel="noreferrer">http://java.sun.com/j2se/1.3/runtime_win32.html</a> </li> <li><a href="http://www.rgagnon.com/javadetails/java-0604.html" rel="noreferrer">http://www.rgagnon.com/javadetails/java-0604.html</a></li> </ul> <p>...and some useful information on multi-version support:</p> <ul> <li><a href="http://www.rgagnon.com/javadetails/java-0604.html" rel="noreferrer">http://www.rgagnon.com/javadetails/java-0604.html</a></li> </ul>
3,855,956
Check if an executable exists in the Windows path
<p>If I run a process with <code>ShellExecute</code> (or in .net with <code>System.Diagnostics.Process.Start()</code>) the filename process to start doesn't need to be a full path.</p> <p>If I want to start notepad, I can use</p> <pre><code>Process.Start("notepad.exe"); </code></pre> <p>instead of</p> <pre><code>Process.Start(@"c:\windows\system32\notepad.exe"); </code></pre> <p>because the direcotry <code>c:\windows\system32</code> is part of the PATH environment variable.</p> <p>how can I check if a file exists on the PATH without executing the process and without parsing the PATH variable?</p> <pre><code>System.IO.File.Exists("notepad.exe"); // returns false (new System.IO.FileInfo("notepad.exe")).Exists; // returns false </code></pre> <p>but I need something like this:</p> <pre><code>System.IO.File.ExistsOnPath("notepad.exe"); // should return true </code></pre> <p>and</p> <pre><code>System.IO.File.GetFullPath("notepad.exe"); // (like unix which cmd) should return // c:\windows\system32\notepad.exe </code></pre> <p>Is there a predefined class to do this task available in the BCL?</p>
3,856,090
8
3
null
2010-10-04 14:01:16.783 UTC
7
2021-05-19 14:48:26.75 UTC
2015-10-16 17:42:48.307 UTC
null
1,364,007
null
98,491
null
1
69
c#|.net|file
38,652
<p>I think there's nothing built-in, but you could do something like this with <a href="http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx" rel="noreferrer">System.IO.File.Exists</a>:</p> <pre><code>public static bool ExistsOnPath(string fileName) { return GetFullPath(fileName) != null; } public static string GetFullPath(string fileName) { if (File.Exists(fileName)) return Path.GetFullPath(fileName); var values = Environment.GetEnvironmentVariable("PATH"); foreach (var path in values.Split(Path.PathSeparator)) { var fullPath = Path.Combine(path, fileName); if (File.Exists(fullPath)) return fullPath; } return null; } </code></pre>
3,318,902
Picking a Random Object in an NSArray
<p>Say I have an array with objects, <em>1, 2, 3 and 4.</em> How would I pick a random object from this array? </p>
3,319,205
8
2
null
2010-07-23 14:08:49.86 UTC
32
2018-07-12 07:46:08.343 UTC
null
null
null
null
92,714
null
1
85
objective-c|cocoa
38,744
<p>@Darryl's answer is correct, but could use some minor tweaks:</p> <pre><code>NSUInteger randomIndex = arc4random() % theArray.count; </code></pre> <p>Modifications:</p> <ul> <li>Using <code>arc4random()</code> over <code>rand()</code> and <code>random()</code> is simpler because it does not require seeding (calling <code>srand()</code> or <code>srandom()</code>).</li> <li>The <a href="http://en.wikipedia.org/wiki/Modulo_operator" rel="noreferrer">modulo operator</a> (<code>%</code>) makes the overall statement shorter, while also making it semantically clearer.</li> </ul>
3,723,316
What is causing "Unable to allocate memory for pool" in PHP?
<p>I've occasionally run up against a server's memory allocation limit, particularly with a bloated application like Wordpress, but never encountered "Unable to allocate memory for pool" and having trouble tracking down any information.</p> <p>Does anyone know what this means? I've tried increasing the <code>memory_limit</code> without success. I also haven't made any significant changes to the application. One day there was no problem, the next day I hit this error.</p>
3,723,338
12
0
null
2010-09-16 02:33:43.89 UTC
56
2016-03-29 09:11:24.913 UTC
2013-01-16 18:40:35.85 UTC
null
122,162
null
288,112
null
1
133
php|caching|memory|apc
172,367
<p><strong><a href="https://bugs.php.net/bug.php?id=58982" rel="noreferrer">Probably is APC related.</a></strong></p> <p>For the people having this problem, please specify you .ini settings. Specifically your apc.mmap_file_mask setting.</p> <p>For file-backed mmap, it should be set to something like:</p> <pre><code>apc.mmap_file_mask=/tmp/apc.XXXXXX </code></pre> <p>To mmap directly from /dev/zero, use:</p> <pre><code>apc.mmap_file_mask=/dev/zero </code></pre> <p>For POSIX-compliant shared-memory-backed mmap, use:</p> <pre><code>apc.mmap_file_mask=/apc.shm.XXXXXX </code></pre>
3,616,359
Who sets response content-type in Spring MVC (@ResponseBody)
<p>I'm having in my Annotation driven Spring MVC Java web application runned on jetty web server (currently in maven jetty plugin).</p> <p>I'm trying to do some AJAX support with one controller method returning just String help text. Resources are in UTF-8 encoding and so is the string, but my response from server comes with </p> <pre><code>content-encoding: text/plain;charset=ISO-8859-1 </code></pre> <p>even when my browser sends </p> <pre><code>Accept-Charset windows-1250,utf-8;q=0.7,*;q=0.7 </code></pre> <p>I'm using somehow default configuration of spring</p> <p>I have found a hint to add this bean to the configuration, but I think it's just not used, because it says it does not support the encoding and a default one is used instead.</p> <pre><code>&lt;bean class="org.springframework.http.converter.StringHttpMessageConverter"&gt; &lt;property name="supportedMediaTypes" value="text/plain;charset=UTF-8" /&gt; &lt;/bean&gt; </code></pre> <p>My controller code is (note that this change of response type is not working for me):</p> <pre><code>@RequestMapping(value = "ajax/gethelp") public @ResponseBody String handleGetHelp(Locale loc, String code, HttpServletResponse response) { log.debug("Getting help for code: " + code); response.setContentType("text/plain;charset=UTF-8"); String help = messageSource.getMessage(code, null, loc); log.debug("Help is: " + help); return help; } </code></pre>
3,617,594
16
0
null
2010-09-01 08:49:15.09 UTC
67
2018-01-14 20:03:44.98 UTC
2012-01-12 11:43:52.23 UTC
null
3,598
null
104,856
null
1
136
java|web-applications|spring-mvc|character-encoding
283,934
<p>Simple declaration of the <code>StringHttpMessageConverter</code> bean is not enough, you need to inject it into <code>AnnotationMethodHandlerAdapter</code>:</p> <pre><code>&lt;bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;array&gt; &lt;bean class = "org.springframework.http.converter.StringHttpMessageConverter"&gt; &lt;property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" /&gt; &lt;/bean&gt; &lt;/array&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>However, using this method you have to redefine all <code>HttpMessageConverter</code>s, and also it doesn't work with <code>&lt;mvc:annotation-driven /&gt;</code>.</p> <p>So, perhaps the most convenient but ugly method is to intercept instantiation of the <code>AnnotationMethodHandlerAdapter</code> with <code>BeanPostProcessor</code>:</p> <pre><code>public class EncodingPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { if (bean instanceof AnnotationMethodHandlerAdapter) { HttpMessageConverter&lt;?&gt;[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters(); for (HttpMessageConverter&lt;?&gt; conv: convs) { if (conv instanceof StringHttpMessageConverter) { ((StringHttpMessageConverter) conv).setSupportedMediaTypes( Arrays.asList(new MediaType("text", "html", Charset.forName("UTF-8")))); } } } return bean; } public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { return bean; } } </code></pre> <p>-</p> <pre><code>&lt;bean class = "EncodingPostProcessor " /&gt; </code></pre>
8,222,495
How to compare strings in an "if" statement?
<p>I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:</p> <pre><code>#include &lt;stdio.h&gt; int main() { char favoriteDairyProduct[30]; scanf("%s",favoriteDairyProduct); if(favoriteDairyProduct == "cheese") { printf("You like cheese too!"); } else { printf("I like cheese more."); } return 0; } </code></pre> <p>(What I actually want to do is much longer than this but this is the main part I'm stuck on.) So how would one compare two strings in C?</p>
8,222,511
5
1
null
2011-11-22 05:41:21.597 UTC
5
2019-07-25 14:02:51.86 UTC
2012-09-27 11:54:09.447 UTC
null
94,977
null
1,031,904
null
1
19
c|string
178,413
<p>You're looking for the function <code>strcmp</code>, or <code>strncmp</code> from <code>string.h</code>.</p> <p>Since strings are just arrays, you need to compare each character, so this function will do that for you:</p> <pre><code>if (strcmp(favoriteDairyProduct, "cheese") == 0) { printf("You like cheese too!"); } else { printf("I like cheese more."); } </code></pre> <p>Further reading: <a href="http://www.cplusplus.com/reference/clibrary/cstring/strcmp/" rel="noreferrer">strcmp at cplusplus.com</a></p>
7,893,857
How do you style the dropdown on Google Places Autocomplete API?
<p>We need to tweak the styling of the dropdown that shows the autocomplete place suggestions when using the Google Places/Maps Autocomplete API.</p> <p>Does anyone know if this is even possible? If so, I guess we just need to know the CSS classnames/IDs.</p> <p>There's a screen grab of the bit I am referring to here:</p> <p><img src="https://i.stack.imgur.com/hMPYm.jpg" alt="Screengrab &gt;"></p>
7,951,791
9
3
null
2011-10-25 18:13:13.94 UTC
26
2022-06-15 17:55:35.797 UTC
2018-07-16 00:12:35.4 UTC
null
10,076,737
null
1,013,280
null
1
77
css|google-maps|autocomplete
76,900
<p>If you use firebug (as mentioned in a comment to your question...) you see that the container with the autocomplete results is a DIV with the class "pac-container" and the suggestions are inside it as a DIV with the class "pac-item". so just style with CSS.</p>
8,066,525
Prevent segue in prepareForSegue method?
<p>Is it possible to cancel a segue in the <code>prepareForSegue:</code> method?</p> <p>I want to perform some check before the segue, and if the condition is not true (in this case, if some <code>UITextField</code> is empty), display an error message instead of performing the segue.</p>
12,818,366
10
0
null
2011-11-09 14:33:30.04 UTC
44
2018-07-10 15:58:49.39 UTC
2013-09-22 21:14:44.673 UTC
null
1,709,587
null
592,035
null
1
257
ios|cocoa-touch|uiviewcontroller|storyboard|segue
96,906
<p>It's possible in iOS 6 and later: You have to implement the method </p> <pre><code>- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender </code></pre> <p>In your view controller. You do your validation there, and if it's OK then <code>return YES;</code> if it's not then <code>return NO;</code> and the prepareForSegue is not called.</p> <p>Note that this method doesn't get called automatically when triggering segues programmatically. If you need to perform the check, then you have to call shouldPerformSegueWithIdentifier to determine whether to perform segue.</p>
4,264,379
It is possible export table sqlite3 table to csv or similiar?
<p>It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3. </p>
4,264,673
3
1
null
2010-11-24 07:28:13.707 UTC
10
2014-02-14 21:11:07.53 UTC
2014-02-14 21:11:07.53 UTC
null
881,229
null
481,650
null
1
5
python|sqlite
7,522
<p>I knocked this very basic script together using a slightly modified example class from <a href="http://docs.python.org/library/csv.html" rel="noreferrer">the docs</a>; it simply exports an entire table to a CSV file:</p> <pre><code>import sqlite3 import csv, codecs, cStringIO class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([unicode(s).encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) conn = sqlite3.connect('yourdb.sqlite') c = conn.cursor() c.execute('select * from yourtable') writer = UnicodeWriter(open("export.csv", "wb")) writer.writerows(c) </code></pre> <p>Hope this helps!</p> <p><strong>Edit:</strong> If you want headers in the CSV, the quick way is to manually add another row before you write the data from the database, e.g:</p> <pre><code># Select whichever rows you want in whatever order you like c.execute('select id, forename, surname, email from contacts') writer = UnicodeWriter(open("export.csv", "wb")) # Make sure the list of column headers you pass in are in the same order as your SELECT writer.writerow(["ID", "Forename", "Surname", "Email"]) writer.writerows(c) </code></pre> <p><strong>Edit 2:</strong> To output pipe-separated columns, register a custom CSV dialect and pass that into the writer, like so:</p> <pre><code>csv.register_dialect('pipeseparated', delimiter = '|') writer = UnicodeWriter(open("export.csv", "wb"), dialect='pipeseparated') </code></pre> <p>Here's <a href="http://docs.python.org/library/csv.html#csv-fmt-params" rel="noreferrer">a list of the various formatting parameters</a> you can use with a custom dialect.</p>
4,698,467
schema.sql not creating even after setting schema_format = :sql
<p>I want to create schema.sql instead of schema.rb. After googling around I found that it can be done by setting sql schema format in <code>application.rb</code>. So I set following in application.rb</p> <pre><code>config.active_record.schema_format = :sql </code></pre> <p>But if I set schema_format to :sql, schema.rb/schema.sql is not created at all. If I comment the line above it creates schema.rb but I need schema.sql. I am assuming that it will have database structure dumped in it and I know that the database structure can be dumped using</p> <pre><code>rake db:structure:dump </code></pre> <p>But I want it to be done automatically when database is migrated.</p> <p>Is there anything I am missing or assuming wrong ?</p>
6,410,179
3
0
null
2011-01-15 07:19:25.163 UTC
9
2016-10-11 11:50:22.257 UTC
2016-10-11 11:50:22.257 UTC
null
230,293
null
230,293
null
1
29
ruby-on-rails|ruby-on-rails-3|schema
9,182
<p>Five months after the original question the problem still exists. The answer is that you did everything correctly, but there is a bug in Rails.</p> <p>Even in <a href="http://edgeguides.rubyonrails.org/migrations.html#types-of-schema-dumps">the guides</a> it looks like all you need is to change the format from :ruby to :sql, but the migrate task is defined like this (activerecord/lib/active_record/railties/databases.rake line 155):</p> <pre><code>task :migrate =&gt; [:environment, :load_config] do ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby end </code></pre> <p>As you can see, nothing happens unless the schema_format equals :ruby. Automatic dumping of the schema in SQL format was working in Rails 1.x. Something has changed in Rails 2, and has not been fixed.</p> <p>The problem is that even if you manage to create the schema in SQL format, there is no task to load this into the database, and the task <code>rake db:setup</code> will ignore your database structure.</p> <p>The bug has been noticed recently: <a href="https://github.com/rails/rails/issues/715">https://github.com/rails/rails/issues/715</a> (and <a href="https://github.com/rails/rails/issues/743">issues/715</a>), and there is a patch at <a href="https://gist.github.com/971720">https://gist.github.com/971720</a></p> <p>You may want to wait until the patch is applied to Rails (the edge version still has this bug), or apply the patch yourself (you may need to do it manually, since line numbers have changed a little).</p> <hr> <p><strong>Workaround:</strong></p> <p>With bundler it's relatively hard to patch the libraries <em>(upgrades are so easy, that they are done very often and the paths are polluted with strange numbers - at least if you use edge rails ;-)</em>, so, instead of patching the file directly, you may want to create two files in your <code>lib/tasks</code> folder:</p> <p><strong><code>lib/tasks/schema_format.rake</code>:</strong></p> <pre><code>import File.expand_path(File.dirname(__FILE__)+"/schema_format.rb") # Loads the *_structure.sql file into current environment's database. # This is a slightly modified copy of the 'test:clone_structure' task. def db_load_structure(filename) abcs = ActiveRecord::Base.configurations case abcs[Rails.env]['adapter'] when /mysql/ ActiveRecord::Base.establish_connection(Rails.env) ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0') IO.readlines(filename).join.split("\n\n").each do |table| ActiveRecord::Base.connection.execute(table) end when /postgresql/ ENV['PGHOST'] = abcs[Rails.env]['host'] if abcs[Rails.env]['host'] ENV['PGPORT'] = abcs[Rails.env]['port'].to_s if abcs[Rails.env]['port'] ENV['PGPASSWORD'] = abcs[Rails.env]['password'].to_s if abcs[Rails.env]['password'] `psql -U "#{abcs[Rails.env]['username']}" -f #{filename} #{abcs[Rails.env]['database']} #{abcs[Rails.env]['template']}` when /sqlite/ dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile'] `sqlite3 #{dbfile} &lt; #{filename}` when 'sqlserver' `osql -E -S #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -i #{filename}` # There was a relative path. Is that important? : db\\#{Rails.env}_structure.sql` when 'oci', 'oracle' ActiveRecord::Base.establish_connection(Rails.env) IO.readlines(filename).join.split(";\n\n").each do |ddl| ActiveRecord::Base.connection.execute(ddl) end when 'firebird' set_firebird_env(abcs[Rails.env]) db_string = firebird_db_string(abcs[Rails.env]) sh "isql -i #{filename} #{db_string}" else raise "Task not supported by '#{abcs[Rails.env]['adapter']}'" end end namespace :db do namespace :structure do desc "Load development_structure.sql file into the current environment's database" task :load =&gt; :environment do file_env = 'development' # From which environment you want the structure? # You may use a parameter or define different tasks. db_load_structure "#{Rails.root}/db/#{file_env}_structure.sql" end end end </code></pre> <p>and <strong><code>lib/tasks/schema_format.rb</code>:</strong></p> <pre><code>def dump_structure_if_sql Rake::Task['db:structure:dump'].invoke if ActiveRecord::Base.schema_format == :sql end Rake::Task['db:migrate' ].enhance do dump_structure_if_sql end Rake::Task['db:migrate:up' ].enhance do dump_structure_if_sql end Rake::Task['db:migrate:down'].enhance do dump_structure_if_sql end Rake::Task['db:rollback' ].enhance do dump_structure_if_sql end Rake::Task['db:forward' ].enhance do dump_structure_if_sql end Rake::Task['db:structure:dump'].enhance do # If not reenabled, then in db:migrate:redo task the dump would be called only once, # and would contain only the state after the down-migration. Rake::Task['db:structure:dump'].reenable end # The 'db:setup' task needs to be rewritten. Rake::Task['db:setup'].clear.enhance(['environment']) do # see the .clear method invoked? Rake::Task['db:create'].invoke Rake::Task['db:schema:load'].invoke if ActiveRecord::Base.schema_format == :ruby Rake::Task['db:structure:load'].invoke if ActiveRecord::Base.schema_format == :sql Rake::Task['db:seed'].invoke end </code></pre> <p>Having these files, you have monkeypatched rake tasks, and you still can easily upgrade Rails. Of course, you should monitor the changes introduced in the file <code>activerecord/lib/active_record/railties/databases.rake</code> and decide whether the modifications are still necessary.</p>
4,524,412
jQuery selector to target any class name (of multiple present) starting with a prefix?
<p>I'm considering one selection statement that would target one of many css class names in a single class attribute value based on a string prefix.</p> <p>For example, I want any <code>detail-</code> prefixed class names to get targeted from the following sample links. </p> <pre><code>&lt;a href="eg.html" class="detail-1 pinkify another"&gt; &lt;a href="eg.html" class="something detail-55 minded"&gt; &lt;a href="eg.html" class="swing narrow detail-Z"&gt; &lt;a href="eg.html" class="swing narrow detail-Z detail-88 detail-A"&gt; </code></pre> <p>It's reminiscent of how <a href="http://api.jquery.com/attribute-contains-prefix-selector/" rel="noreferrer"><code>[class|="detail"]</code></a> prefix selector works on a scalar attribute value, and also of <a href="http://api.jquery.com/hasClass/" rel="noreferrer"><code>.hasClass(className)</code></a>, but my question needs both concepts applied simultaneously. </p> <p><em>Note:</em> The <code>detail-</code> prefix won't necessarily be the first class name of the bunch.</p>
4,524,477
4
0
null
2010-12-24 05:26:34.677 UTC
11
2014-06-07 14:07:20.437 UTC
2011-12-20 17:40:53.74 UTC
null
106,224
null
179,972
null
1
11
javascript|jquery|html|jquery-selectors
4,124
<p>Because of the way the <code>class</code> attribute is designed, you'll need to make use of at least two other attribute selectors (notice the whitespace in <code>[class*=" detail-"]</code>):</p> <pre><code>$('a[class^="detail-"], a[class*=" detail-"]'); </code></pre> <p>This selects <code>&lt;a&gt;</code> elements with a <code>class</code> attribute that</p> <ul> <li>starts with <code>detail-</code>, or</li> <li>contains a class prefixed with <code>detail-</code>. Class names are separated by whitespace <a href="http://www.w3.org/TR/html4/struct/global.html#h-7.5.2" rel="noreferrer">per the HTML spec</a>, hence the significant space character.</li> </ul> <p>If you'd like to turn this into a custom selector expression, you can do this:</p> <pre><code>$.expr[':']['class-prefix'] = function(elem, index, match) { var prefix = match[3]; if (!prefix) return true; var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]'; return $(elem).is(sel); }; </code></pre> <p>Then select it like this:</p> <pre><code>$('a:class-prefix(detail-)'); </code></pre> <p>Or if you'd like to place this in a plugin:</p> <pre><code>$.fn.filterClassPrefix = function(prefix) { if (!prefix) return this; var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]'; return this.filter(sel); }; </code></pre> <p>Then call it like this:</p> <pre><code>$('a').filterClassPrefix('detail-'); </code></pre>
4,837,565
Objective-C : (private / public properties) making a property readonly for outside class calls and readwrite for self calls
<p>Would you know a way to make a property readonly for outside calls and readwrite for inside calls ?</p> <p>I've read times ago somthing that seemed like </p> <p>In the .h</p> <pre><code>@property(nonatomic, readonly) NSDate* theDate; </code></pre> <p>In the .m</p> <pre><code>@interface TheClassName() @property(nonatomic, retain) NSDate* theDate; @end </code></pre> <p>but this raises a warning when compiling the .m "Property theDate attribute in TheClassName class continuation does not match class TheClassName property".</p> <p>Anyway, it seems to work (can read but not set from outside the class, can do both from inside) but I should have missed somehting to avoid the warning. Or if you know a better way to do this...</p>
4,837,626
4
0
null
2011-01-29 15:07:19.653 UTC
14
2012-07-26 18:33:17.013 UTC
2011-11-18 16:16:41.797 UTC
null
499,417
null
499,417
null
1
32
objective-c|cocoa
13,830
<p>In your .h:</p> <pre><code>@property(nonatomic, retain, readonly) NSDate* theDate; </code></pre> <p>In your .m:</p> <pre><code>@interface TheClassName() @property(nonatomic, retain, readwrite) NSDate* theDate; @end </code></pre>
4,164,521
Compare if BigDecimal is greater than zero
<p>How can I compare if <code>BigDecimal</code> value is greater than zero?</p>
4,164,539
7
3
null
2010-11-12 12:18:01.337 UTC
27
2022-03-09 12:25:43.867 UTC
2013-12-10 16:56:16.243 UTC
null
1,731,935
null
171,365
null
1
313
java|compare|bigdecimal
380,910
<p>It's as simple as:</p> <pre><code>if (value.compareTo(BigDecimal.ZERO) &gt; 0) </code></pre> <p>The <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal)" rel="noreferrer">documentation for <code>compareTo</code></a> actually specifies that it will return -1, 0 or 1, but the more general <code>Comparable&lt;T&gt;.compareTo</code> method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.</p>
4,650,509
Different db for testing in Django?
<pre><code>DATABASES = { # 'default': { # 'ENGINE': 'postgresql_psycopg2', # ... # } # for unit tests 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } } </code></pre> <p>I have two databases: one I'd like to use for unit tests, and one for everything else. Is it possible to configure this in Django 1.2.4?</p> <p>(The reason I ask is because with postgresql I'm getting the following error:</p> <pre><code>foo@bar:~/path/$ python manage.py test Creating test database 'default'... Got an error creating the test database: permission denied to create database Type 'yes' if you would like to try deleting the test database 'test_baz', or 'no' to cancel: yes Destroying old test database... Got an error recreating the test database: database "test_baz" does not exist </code></pre> <p>Why could I be getting this error? I guess I don't really care if I can always use SQLite for unit tests, as that works fine.)</p>
4,650,651
10
3
null
2011-01-10 19:13:45.777 UTC
16
2022-04-05 10:34:07.297 UTC
2011-01-10 19:39:42.63 UTC
null
147,601
null
147,601
null
1
72
django|unit-testing|sqlite|postgresql
47,251
<p>In your <code>settings.py</code> (or <code>local_settings.py</code>):</p> <pre><code>import sys if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } </code></pre>
14,425,291
Culture is not supported
<p>I'm using Visual Studio 2012 Ultimate version.</p> <p>I've got this error and I don't know how to solve it.</p> <p>Culture is not supported. Parameter name: name en-UK is an invalid culture identifier.</p> <blockquote> <p>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </p> <p>Exception Details: System.Globalization.CultureNotFoundException: Culture is not supported. Parameter name: name en-UK is an invalid culture identifier.</p> </blockquote> <p>please help me</p>
14,425,311
3
4
null
2013-01-20 14:06:29.51 UTC
1
2018-07-16 16:15:40.26 UTC
2013-01-20 14:10:52.607 UTC
null
447,156
null
1,973,763
null
1
11
c#|asp.net|cultureinfo
49,548
<p>You should try <code>en-GB</code> for English (United Kingdom)</p> <p><a href="http://www.csharp-examples.net/culture-names/" rel="noreferrer">List of Cultures</a></p>
14,732,465
NLTK Tagging spanish words using a corpus
<p>I am trying to learn how to tag spanish words using NLTK.</p> <p>From the <a href="http://nltk.org/book/ch05.html">nltk book</a>, It is quite easy to tag english words using their example. Because I am new to nltk and all language processing, I am quite confused on how to proceeed.</p> <p>I have downloaded the <code>cess_esp</code> corpus. Is there a way to specifiy a corpus in <code>nltk.pos_tag</code>. I looked at the <code>pos_tag</code> documentation and didn't see anything that suggested I could. I feel like i'm missing some key concepts. Do I have to manually tag the words in my text agains the cess_esp corpus? (by manually I mean tokenize my sentance and run it agains the corpus) Or am I off the mark entirely. Thank you</p>
14,742,406
4
0
null
2013-02-06 15:19:25.387 UTC
12
2020-02-18 11:46:13.243 UTC
2013-02-06 15:35:44.963 UTC
null
594,589
null
594,589
null
1
20
python|nltk
35,090
<p>First you need to <strong>read the tagged sentence from a corpus.</strong> NLTK provides a nice interface to no bother with different formats from the different corpora; you can simply import the corpus use the corpus object functions to access the data. See <a href="http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml" rel="noreferrer">http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml</a> . </p> <p>Then you have to <strong>choose your choice of tagger and train the tagger</strong>. There are more fancy options but you can start with the N-gram taggers.</p> <p>Then you can use the tagger to tag the sentence you want. Here's an example code:</p> <pre><code>from nltk.corpus import cess_esp as cess from nltk import UnigramTagger as ut from nltk import BigramTagger as bt # Read the corpus into a list, # each entry in the list is one sentence. cess_sents = cess.tagged_sents() # Train the unigram tagger uni_tag = ut(cess_sents) sentence = "Hola , esta foo bar ." # Tagger reads a list of tokens. uni_tag.tag(sentence.split(" ")) # Split corpus into training and testing set. train = int(len(cess_sents)*90/100) # 90% # Train a bigram tagger with only training data. bi_tag = bt(cess_sents[:train]) # Evaluates on testing data remaining 10% bi_tag.evaluate(cess_sents[train+1:]) # Using the tagger. bi_tag.tag(sentence.split(" ")) </code></pre> <p>Training a tagger on a large corpus may take a significant time. Instead of training a tagger every time we need one, it is convenient to save a trained tagger in a file for later re-use. </p> <p>Please look at <strong>Storing Taggers</strong> section in <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html" rel="noreferrer">http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html</a></p>
14,786,623
Batch file Copy using %1 for drag and drop
<p>I tried to make a drag-and-drop batch file.</p> <p>I have the problem that a file exists but the batch file couldn't find it...</p> <p>I want to copy <code>.png</code> files (like <code>pict_2013020808172137243.png</code>) to another folder and rename it.</p> <p>In the path are symbols like <code>_</code> and spaces, also I don't know how to make multi-drag-and-drop to make the same function (rename and add to <code>.zip</code>).</p> <p>I tried this but with no result :(</p> <pre><code>@ECHO OFF ECHO %1 COPY "%1" "%CD%\test\" /Y /S REN "%CD%\mob\*.png" "%CD%\test\test.png" 7za u -tzip "%appdata%\.virto\pack.zip" "test" -r </code></pre>
14,787,643
1
0
null
2013-02-09 09:18:53.663 UTC
7
2021-03-29 06:24:35.623 UTC
2018-08-16 11:02:41.807 UTC
null
995,714
null
2,056,750
null
1
23
batch-file|parameters|path|drag-and-drop|copy
67,698
<p>Drag &amp; drop is badly implemented for batch files.<br /> The names are quoted, if a space is present, but not if a special character is found, like <code>&amp;,;^</code></p> <p>For spaces only in your filenames, you need to change your code only a bit.</p> <pre><code>@ECHO OFF ECHO &quot;%~1&quot; COPY &quot;%~1&quot; &quot;%CD%\test\&quot; /Y /S MOVE &quot;%CD%\mob\*.png&quot; &quot;%CD%\test\test.png&quot; 7za u -tzip &quot;%appdata%\.virto\pack.zip&quot; &quot;test&quot; -r </code></pre> <p><code>%~1</code> expands always to an unquoted version, so can always quote them in a safe way.</p> <pre><code>&quot;c:\Docs and sets&quot; -&gt; %~1 -&gt; c:\Docs and sets -&gt; &quot;%~1&quot; -&gt; &quot;c:\Docs and sets&quot; c:\Programs -&gt; %~1 -&gt; c:\Programs -&gt; &quot;%~1&quot; -&gt; &quot;c:\Programs&quot; </code></pre> <p>For more details read <a href="https://stackoverflow.com/a/5192427/463115">Drag and drop batch file for multiple files?</a></p>
14,463,289
Check object empty
<p>Basically how do you check if an object is null or empty. What I mean is that if I have an object instantiated but all its values or fields are null, the how do I check in code if it is empty?</p> <p>I have tried;</p> <pre><code>if (doc != null){ .... do something </code></pre> <p>But it doesn't seem to work.</p>
14,463,338
10
2
null
2013-01-22 16:27:18.147 UTC
5
2022-09-22 16:40:22.153 UTC
2013-01-22 16:28:01.77 UTC
null
1,679,863
null
1,620,690
null
1
35
java
225,915
<p>You can't do it directly, you should provide your own way to check this. Eg.</p> <pre><code>class MyClass { Object attr1, attr2, attr3; public boolean isValid() { return attr1 != null &amp;&amp; attr2 != null &amp;&amp; attr3 != null; } } </code></pre> <p>Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.</p>
14,590,279
error : NameError: name 'subprocess' is not defined
<pre><code>#!/usr/bin/python3 username = 'joe' # generate passphrase pw_length = 6 phrase = subprocess.check_output(['pwgen', str(pw_length), '1']) phrase = phrase.decode('utf-8').strip() dev_null = open('/dev/null', 'w') passwd = subprocess.Popen(['sudo', 'passwd', user], stdin=subprocess.PIPE, stdout=dev_null.fileno(), stderr=subprocess.STDOUT) passwd.communicate( ((phrase + '\n')*2).encode('utf-8') ) if passwd.returncode != 0: raise OSError('password setting failed') </code></pre> <p>how do i fix this error :</p> <pre><code>bash-3.00# python ./pass2.py Traceback (most recent call last): File "./pass2.py", line 6, in ? phrase = subprocess.check_output(['pwgen', str(pw_length), '1']) NameError: name 'subprocess' is not defined </code></pre>
14,590,294
1
1
null
2013-01-29 19:01:54.383 UTC
3
2013-01-29 19:27:20.32 UTC
2013-01-29 19:27:20.32 UTC
null
869,912
null
730,858
null
1
44
python|solaris
74,516
<p>Subprocess is a module. You need to import it.</p> <p>Put this as the second line in your file: <code>import subprocess</code></p>
3,119,814
Using \parindent and \parskip with \paragraph{} has no effect
<p>I'm creating documents using the <code>memoir</code> class in <code>XeLaTeX</code>. I'm having trouble creating proper paragraph presentation, and in particular my when I create paragraphs with <code>\paragraph{}lorem ipsum</code> LaTeX ignores the <code>\parskip</code> and <code>\parindent</code> settings.</p> <p>For example, if I have a document</p> <pre><code>\documentclass[oneside,11pt]{memoir} \usepackage{fontspec}% font selecting commands \usepackage{xunicode}% unicode character macros \usepackage{xltxtra} % some fixes/extras \begin{document} \setlength{\parskip}{0pt} % 1ex plus 0.5ex minus 0.2ex} \setlength{\parindent}{0pt} \pagestyle{plain} \paragraph{}orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \paragraph{}ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \end{document} </code></pre> <p>This typesets like so:</p> <blockquote> <p>&emsp;&emsp;&emsp; orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst.</p> <p>&emsp;&emsp;&emsp;ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst.</p> </blockquote> <p>This incorrectly has both paragraph indentation and skip, in spite of <code>\parskip</code> and <code>\parindent</code> being set to zero.</p> <p>One would expect the typeset output to look like this (which is an ugly choice of paragraph formatting, but illustrates the issue):</p> <blockquote> <p>orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst.<br/> ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. </p> </blockquote> <p>I note that when I separate paragraphs by two newlines (i.e. don't use <code>\paragraph{}</code>, and) the <code>\parskip</code> and <code>\parindent</code> settings are honoured.</p> <p>I'd be very grateful to know why, when using <code>\paragraph{}</code>, the <code>\parskip</code> and <code>\parindent</code> commands are not honoured, and how one might either have these commands honoured or alternatively what commands would achieve the same effect with paragraphs created with <code>\paragraph{}</code>.</p> <p>Thank you for reading.</p> <p>Brian</p>
3,120,809
2
0
null
2010-06-25 16:46:12.383 UTC
1
2010-06-25 19:51:11.727 UTC
null
null
null
null
19,212
null
1
5
latex|typesetting|memoir|xelatex
64,026
<p>@Brian -- I started putting this in a comment following your comment to Norman Gray's response, but the code sample made it too large. \paragraph{} doesn't change the typesetting of <em>regular</em> paragraphs. It's just that, counter-intuitively, the paragraph begun by the \paragraph{} command is not a regular paragraph; it's a section element in the document. Play with the code below to see how the \parskip and \parindent affects the regular paragraphs but not the "\paragraph" section element. (Actually, \parskip affects even the \paragraph{} items but the spacing before a \paragraph{} item is calculated to always be slightly more than \parskip, which is why there's always a space between \paragraph{} elements even if \parskip is 0.)</p> <p>I think 99% of LaTeX docs probably never use the \paragraph{} section command. Regular paragraphs in LaTeX are separated by (1) a blank line ("regular paragraphs" 1 and 2 below) or (2) by the \par command ("regular paragraphs" 3 and 4 below).</p> <pre><code>\documentclass[oneside,11pt]{memoir} \usepackage{fontspec}% font selecting commands %\usepackage{xunicode}% unicode character macros %\usepackage{xltxtra} % some fixes/extras \begin{document} \setlength{\parskip}{0pt} % 1ex plus 0.5ex minus 0.2ex} \setlength{\parindent}{0pt} \pagestyle{plain} \paragraph{paragraph section 2}adorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. regular paragraph 1 -- orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. regular paragraph 2 -- orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \paragraph{paragraph section 2}ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \par regular paragraph 3 -- orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \par regular paragraph 4 -- orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \end{document} </code></pre>
1,599,204
Core Data backed UITableView with indexing
<p>I am trying to implement a Core Data backed UITableView that supports indexing (eg: the characters that appear down the side, and the section headers that go with them). I have no problems at all implementing this without Core Data using:</p> <pre><code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView; </code></pre> <p>I also have no problem implementing a UITableView that is backed by Core Data without using the indexing.</p> <p>What I am trying to figure out is how to elegantly combine the two? Obviously once you index and re-section content, you can no longer use the standard NSFetchedResultsController to retrieve things at a given index path. So I am storing my index letters in an NSArray and my indexed content in an NSDictionary. This all works fine for display, but I have some real headaches when it comes to adding and deleting rows, specifically how to properly implement these methods:</p> <pre><code>- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller; - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath; - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id &lt;NSFetchedResultsSectionInfo&gt;)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type; - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller; </code></pre> <p>Because the index paths it's returning me have no correlation with the ones in core data. I got add working by simply rebuilding my index NSArray and NSDictionary when the user adds a row, but doing the same when they delete one crashes the whole application.</p> <p>Is there a simple pattern/example I'm missing here to make all this work properly?</p> <p>Edit: Just to clarify I know that the NSFetchedResultsController does this out of the box, but what I want is to replicate the functionality like the Contacts app, where the index is the first letter of the first name of the person.</p>
1,603,428
1
0
null
2009-10-21 07:11:42.313 UTC
10
2009-11-17 07:54:28.52 UTC
2009-11-16 19:36:10.77 UTC
null
161,815
null
6,044
null
1
8
iphone|core-data|uitableview|nsfetchedresultscontroller|cocoa-design-patterns
13,249
<p>You should use your CoreData NSFetchedResultsController to get your sections/indexes.<br> You can specify the section key in the fetch request (I think it has to match the first sort key): </p> <pre><code>NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" // this key defines the sort ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"name" // this key defines the sections cacheName:@"Root"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; </code></pre> <p>Then, you can get the section names like this:</p> <pre><code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { id &lt;NSFetchedResultsSectionInfo&gt; sectionInfo = [[fetchedResultsController sections] objectAtIndex:section]; return [sectionInfo name]; } </code></pre> <p>And the section indexes are here:</p> <pre><code>id &lt;NSFetchedResultsSectionInfo&gt; sectionInfo = [[fetchedResultsController sections] objectAtIndex:section]; [sectionInfo indexTitle]; // this is the index </code></pre> <p>Changes to the content just indicate that the table needs to be updated: </p> <pre><code>- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView reloadData]; } </code></pre> <p><strong>UPDATE</strong><br> This only works for the index and fast index scrolling, not for the section headers.<br> See <a href="https://stackoverflow.com/questions/1741093/how-to-use-the-first-character-as-a-section-name/1741131#1741131">this answer</a> to "How to use the first character as a section name" for more information and details on how to implement first letters for section headers as well as the index.</p>
1,656,652
Syncing SQL Server 2008 Databases over HTTP using WCF & Sync Framework
<p>Has anyone here worked with Sync Framework and syncing through WCF endpoints? Please share code samples or sample projects. I am specifically looking for offline scenarios where client comes online only to fetch updates from the Server.</p>
1,669,477
1
0
null
2009-11-01 08:20:37.213 UTC
21
2013-07-10 05:15:57.85 UTC
2013-07-10 05:15:57.85 UTC
null
167,726
null
167,726
null
1
23
c#|.net|sql-server-2008|microsoft-sync-framework
12,989
<p>I did the following to get Sync Framework working using WCF with SQL Server 2008</p> <ul> <li>Enabled Change Tracking in SQL Server 2008</li> <li>Enabled change tracking for tables participating in the Sync</li> <li>Added a metadata table named anchor </li> <li>Added a table to track client Ids named "guid"</li> <li>Used SqlExpressClientSyncProvider available from MSF's codeplex project site as Client Sync Provider</li> <li><p>Used SqlSyncAdapterBuilder to build adapters for tables participating in the Sync</p> <pre><code>foreach (var item in anchorTables) { // Use adapter builder to generate T-SQL for querying change tracking data and CRUD SqlSyncAdapterBuilder builder = new SqlSyncAdapterBuilder(); builder.Connection = new SqlConnection(this.connectionStringFactory.ConnectionString); builder.ChangeTrackingType = ChangeTrackingType.SqlServerChangeTracking; builder.SyncDirection = SyncDirection.Bidirectional; builder.TableName = item.TableName; // Get sync adapters from builder SyncAdapter clientAdapter = builder.ToSyncAdapter(); clientAdapter.TableName = item.TableName; this.clientSyncProvider.SyncAdapters.Add(clientAdapter); } </code></pre></li> <li><p>Added anchor commands</p> <pre><code>SqlCommand anchroCommand = new SqlCommand { CommandText = "SELECT @" + SyncSession.SyncNewReceivedAnchor + " = change_tracking_current_version()" }; anchroCommand.Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.BigInt) .Direction = ParameterDirection.Output; this.clientSyncProvider.SelectNewAnchorCommand = anchroCommand; </code></pre></li> <li><p>Implemented a WCF Service using a instance of DbServerSyncProvider functioning as Server sync provider. You will have generate sync adapters and set anchor command as shown in previous step for Server provider too.</p> <pre><code>[ServiceContract] public interface ISyncService { [OperationContract] SyncContext ApplyChanges(SyncGroupMetadata groupMetadata, DataSet dataSet, SyncSession syncSession); [OperationContract] SyncContext GetChanges(SyncGroupMetadata groupMetadata, SyncSession syncSession); [OperationContract] SyncSchema GetSchema(Collection&lt;string&gt; tableNames, SyncSession syncSession); [OperationContract] SyncServerInfo GetServerInfo(SyncSession syncSession); } </code></pre></li> <li><p>Created a proxy class implementing ServerSyncProvider to access WCF service</p> <pre><code>public class DbServerSyncProviderProxy : ServerSyncProvider { SyncServiceProxy.SyncServiceClient serviceProxy = new SyncServiceProxy.SyncServiceClient(); public override SyncContext ApplyChanges(SyncGroupMetadata groupMetadata, DataSet dataSet, SyncSession syncSession) { return serviceProxy.ApplyChanges(groupMetadata, dataSet, syncSession); } } </code></pre></li> <li>Created an instance of SyncAgent and set RemoteProvider with an instance of proxy class which is used to access WCF service. LocalProvider is set with instance of SqlExpressClientSyncProvider</li> <li>Added tables and sync groups to SyncAgent configuration</li> <li>SyncAgent.Synchronize()</li> </ul>
50,275,834
How do you sort an Observable<Item[]> in Angular 6 with rxjs 6?
<p>I just want to sort data on an observable of my class type 'Category'. So Observable &lt; Category[] > I want to sort.</p> <p>So I upgraded to Angular6 and rxjs6 with it. One issue that is probably simple Typescript that I do know is how do I just do a 'sort' operation like:</p> <pre><code>sort((x,y) =&gt; x.description &lt; y.description ? -1 : 1) </code></pre> <p>Inside of the new Angular6? I used to do this in 5</p> <pre><code>var response = this.http.get&lt;Category[]&gt;(this.endpoint); .map((result: Response) =&gt; this.alphabetize(result)); alphabetize = (result: Response) =&gt; this.Categories = result.json() .sort((x,y) =&gt; x.description &lt; y.description ? -1 : 1) </code></pre> <p>And it worked fine. Now in the HttpCLIENTModule and HttpClient that Angular wants you to use it is simpler:</p> <pre><code>var data = this.http.get&lt;Category[]&gt;(this.endpoint); </code></pre> <p>I just put the magic &lt;(object)> before my endpoint and it does it for me. Cool. But I am not seeing how you get inside the object easily to sort from it with Source, Pipe, from, of. I know it is probably something simple I just don't know the syntax for.</p>
50,276,301
2
0
null
2018-05-10 14:56:22.883 UTC
3
2022-02-10 19:32:13.99 UTC
null
null
null
null
580,428
null
1
28
typescript|angular6|rxjs6
31,255
<p>It is:</p> <pre><code>this.http.get&lt;Category[]&gt;(this.endpoint).pipe( map(results =&gt; results.sort(...)) ); </code></pre> <p>Or since <code>sort</code> modifies existing array, it's more semantically correct to provide side effects in <code>do</code>/<code>tap</code>:</p> <pre><code>this.http.get&lt;Category[]&gt;(this.endpoint).pipe( tap(results =&gt; { results.sort() }) ); </code></pre>
35,926,917
asyncio web scraping 101: fetching multiple urls with aiohttp
<p>In earlier question, one of authors of <code>aiohttp</code> kindly suggested way to <a href="https://stackoverflow.com/q/35879769/">fetch multiple urls with aiohttp</a> using the new <code>async with</code> syntax from <code>Python 3.5</code>:</p> <pre><code>import aiohttp import asyncio async def fetch(session, url): with aiohttp.Timeout(10): async with session.get(url) as response: return await response.text() async def fetch_all(session, urls, loop): results = await asyncio.wait([loop.create_task(fetch(session, url)) for url in urls]) return results if __name__ == '__main__': loop = asyncio.get_event_loop() # breaks because of the first url urls = ['http://SDFKHSKHGKLHSKLJHGSDFKSJH.com', 'http://google.com', 'http://twitter.com'] with aiohttp.ClientSession(loop=loop) as session: the_results = loop.run_until_complete( fetch_all(session, urls, loop)) # do something with the the_results </code></pre> <p>However when one of the <code>session.get(url)</code> requests breaks (as above because of <code>http://SDFKHSKHGKLHSKLJHGSDFKSJH.com</code>) the error is not handled and the whole thing breaks.</p> <p>I looked for ways to insert tests about the result of <code>session.get(url)</code>, for instance looking for places for a <code>try ... except ...</code>, or for a <code>if response.status != 200:</code> but I am just not understanding how to work with <code>async with</code>, <code>await</code> and the various objects.</p> <p>Since <code>async with</code> is still very new there are not many examples. It would be very helpful to many people if an <code>asyncio</code> wizard could show how to do this. After all one of the first things most people will want to test with <code>asyncio</code> is getting multiple resources concurrently.</p> <p><strong>Goal</strong></p> <p>The goal is that we can inspect <code>the_results</code> and quickly see either: </p> <ul> <li>this url failed (and why: status code, maybe exception name), or</li> <li>this url worked, and here is a useful response object</li> </ul>
35,928,605
2
0
null
2016-03-10 20:45:13.373 UTC
13
2016-03-11 08:00:43.697 UTC
2017-05-23 12:32:31.727 UTC
null
-1
null
3,602,383
null
1
26
python|python-3.x|web-scraping|python-asyncio|aiohttp
10,273
<p>I would use <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.gather"><code>gather</code></a> instead of <code>wait</code>, which can return exceptions as objects, without raising them. Then you can check each result, if it is instance of some exception.</p> <pre><code>import aiohttp import asyncio async def fetch(session, url): with aiohttp.Timeout(10): async with session.get(url) as response: return await response.text() async def fetch_all(session, urls, loop): results = await asyncio.gather( *[fetch(session, url) for url in urls], return_exceptions=True # default is false, that would raise ) # for testing purposes only # gather returns results in the order of coros for idx, url in enumerate(urls): print('{}: {}'.format(url, 'ERR' if isinstance(results[idx], Exception) else 'OK')) return results if __name__ == '__main__': loop = asyncio.get_event_loop() # breaks because of the first url urls = [ 'http://SDFKHSKHGKLHSKLJHGSDFKSJH.com', 'http://google.com', 'http://twitter.com'] with aiohttp.ClientSession(loop=loop) as session: the_results = loop.run_until_complete( fetch_all(session, urls, loop)) </code></pre> <p>Tests:</p> <pre><code>$python test.py http://SDFKHSKHGKLHSKLJHGSDFKSJH.com: ERR http://google.com: OK http://twitter.com: OK </code></pre>
44,859,191
split string in python to get one value?
<p>Need help, let's assume that I have a string 'Sam-Person' in a variable called 'input'</p> <pre><code>name, kind = input.split('-') </code></pre> <p>By doing the above, I get two variable with different strings 'Sam' and 'Person'</p> <p>is there a way to only get the first value name = 'Sam' without the need of the extra variable 'kind' and without having to work with lists?</p> <p>When doing this, assuming that I was going to get only 'Sam':</p> <pre><code>name = input.split('-') </code></pre> <p>I get a list, and then I can access the values by index name[0] or name[1], but it is not what I want, I just want to directly get 'Sam' into the variable 'name', is there a way to do that or an alternative to split?</p>
44,859,226
2
0
null
2017-07-01 09:03:52.117 UTC
1
2020-07-14 15:29:42.8 UTC
2020-07-14 15:29:42.8 UTC
null
4,960,855
null
8,223,993
null
1
10
python|string|list
40,197
<p>Assign the first item directly to the variable.</p> <pre><code>&gt;&gt;&gt; string = 'Sam-Person' &gt;&gt;&gt; name = string.split('-')[0] &gt;&gt;&gt; name 'Sam' </code></pre> <p>You can specify <code>maxsplit</code> argument, because you want to get only the first item.</p> <pre><code>&gt;&gt;&gt; name = string.split('-', 1)[0] </code></pre>
36,243,538
python sqlite3, how often do I have to commit?
<p>I have a for loop that is making many changes to a database with a sqlite manager class I wrote, but I am unsure about how often I have to commit...</p> <pre><code>for i in list: c.execute('UPDATE table x=y WHERE foo=bar') conn.commit() c.execute('UPDATE table x=z+y WHERE foo=bar') conn.commit() </code></pre> <p> Basically my question is whether I have to call commit twice there, or if I can just call it once after I have made both changes?</p>
36,244,223
1
0
null
2016-03-27 03:31:40.033 UTC
18
2018-04-14 11:38:57.25 UTC
2018-04-14 11:38:57.25 UTC
null
9,449,426
null
4,400,804
null
1
34
python|sql|sqlite
45,652
<p>Whether you call <code>conn.commit()</code> once at the end of the procedure of after every single database change depends on several factors.</p> <h2>What concurrent readers see</h2> <p>This is what everybody thinks of at first sight: When a change to the database is committed, it becomes visible for other connections. Unless it is committed, it remains visible only locally for the connection to which the change was done. Because of the limited concurrency features of <code>sqlite</code>, the database can only be read while a transaction is open.</p> <p>You can investigate what happens by running the <a href="https://github.com/flaschbier/StillLearningPython/blob/master/transaction/try.py" rel="noreferrer">following script</a> and investigating its output:</p> <pre><code>import os import sqlite3 _DBPATH = "./q6996603.sqlite" def fresh_db(): if os.path.isfile(_DBPATH): os.remove(_DBPATH) with sqlite3.connect(_DBPATH) as conn: cur = conn.cursor().executescript(""" CREATE TABLE "mytable" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, -- rowid "data" INTEGER ); """) print "created %s" % _DBPATH # functions are syntactic sugar only and use global conn, cur, rowid def select(): sql = 'select * from "mytable"' rows = cur.execute(sql).fetchall() print " same connection sees", rows # simulate another script accessing tha database concurrently with sqlite3.connect(_DBPATH) as conn2: rows = conn2.cursor().execute(sql).fetchall() print " other connection sees", rows def count(): print "counting up" cur.execute('update "mytable" set data = data + 1 where "id" = ?', (rowid,)) def commit(): print "commit" conn.commit() # now the script fresh_db() with sqlite3.connect(_DBPATH) as conn: print "--- prepare test case" sql = 'insert into "mytable"(data) values(17)' print sql cur = conn.cursor().execute(sql) rowid = cur.lastrowid print "rowid =", rowid commit() select() print "--- two consecutive w/o commit" count() select() count() select() commit() select() print "--- two consecutive with commit" count() select() commit() select() count() select() commit() select() </code></pre> <p>Output:</p> <pre><code>$ python try.py created ./q6996603.sqlite --- prepare test case insert into "mytable"(data) values(17) rowid = 1 commit same connection sees [(1, 17)] other connection sees [(1, 17)] --- two consecutive w/o commit counting up same connection sees [(1, 18)] other connection sees [(1, 17)] counting up same connection sees [(1, 19)] other connection sees [(1, 17)] commit same connection sees [(1, 19)] other connection sees [(1, 19)] --- two consecutive with commit counting up same connection sees [(1, 20)] other connection sees [(1, 19)] commit same connection sees [(1, 20)] other connection sees [(1, 20)] counting up same connection sees [(1, 21)] other connection sees [(1, 20)] commit same connection sees [(1, 21)] other connection sees [(1, 21)] $ </code></pre> <p>So it depends whether you can live with the situation that a cuncurrent reader, be it in the same script or in another program, will be off by two at times.</p> <p>When a large number of changes is to be done, two other aspects enter the scene:</p> <h2>Performance</h2> <p>The performance of database changes dramatically depends on how you do them. It is already noted as a <a href="https://www.sqlite.org/faq.html#q19" rel="noreferrer">FAQ</a>:</p> <blockquote> <p>Actually, SQLite will easily do 50,000 or more INSERT statements per second on an average desktop computer. But it will only do a few dozen transactions per second. [...]</p> </blockquote> <p>It is absolutely helpful to understand the details here, so do not hesitate to follow the <a href="https://www.sqlite.org/faq.html#q19" rel="noreferrer">link</a> and dive in. Also see this <a href="https://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite">awsome analysis</a>. It's written in C, but the results would be similar would one do the same in Python.</p> <p>Note: While both resources refer to <code>INSERT</code>, the situation will be very much the same for <code>UPDATE</code> for the same arguments.</p> <h2>Exclusively locking the database</h2> <p>As already mentioned above, an open (uncommitted) transaction will block changes from concurrent connections. So it makes sense to bundle many changes to the database into a single transaction by executing them and the jointly committing the whole bunch of them.</p> <p>Unfortunately, sometimes, computing the changes may take some time. When concurrent access is an issue you will not want to lock your database for that long. Because it can become rather tricky to collect pending <code>UPDATE</code> and <code>INSERT</code> statements somehow, this will usually leave you with a tradeoff between performance and exclusive locking.</p>
27,047,310
Path variables in Spring WebSockets @SendTo mapping
<p>I have, what I think to be, a very simple Spring WebSocket application. However, I'm trying to use path variables for the subscription as well as the message mapping.</p> <p>I've posted a paraphrased example below. I would expect the <code>@SendTo</code> annotation to return back to the subscribers based on their <code>fleetId</code>. ie, a <code>POST</code> to <code>/fleet/MyFleet/driver/MyDriver</code> should notify subscribers of <code>/fleet/MyFleet</code>, but I'm not seeing this behavior.</p> <p>It's worth noting that subscribing to literal <code>/fleet/{fleetId}</code> works. Is this intended? Am I missing some piece of configuration? Or is this just not how it works?</p> <p>I'm not very familiar with WebSockets or this Spring project yet, so thanks in advance.</p> <p><strong>Controller.java</strong></p> <pre><code>... @MessageMapping("/fleet/{fleetId}/driver/{driverId}") @SendTo("/topic/fleet/{fleetId}") public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) { return new Simple(fleetId, driverId); } ... </code></pre> <p><strong>WebSocketConfig.java</strong></p> <pre><code>@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/live"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/fleet").withSockJS(); } } </code></pre> <p><strong>index.html</strong></p> <pre><code>var socket = new SockJS('/fleet'); var stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { // Doesn't Work stompClient.subscribe('/topic/fleet/MyFleet', function(greeting) { // Works stompClient.subscribe('/topic/fleet/{fleetId}', function(greeting) { // Do some stuff }); }); </code></pre> <p><strong>Send Sample</strong></p> <pre><code> stompClient.send("/live/fleet/MyFleet/driver/MyDriver", {}, JSON.stringify({ // Some simple content })); </code></pre>
27,055,764
3
0
null
2014-11-20 18:51:59.363 UTC
23
2020-03-29 18:47:43.99 UTC
null
null
null
null
621,686
null
1
57
java|spring|websocket|stomp|sockjs
57,891
<p>Even though <code>@MessageMapping</code> supports placeholders, they are not exposed / resolved in <code>@SendTo</code> destinations. Currently, there's no way to define dynamic destinations with the <code>@SendTo</code> annotation (see issue <a href="https://jira.spring.io/browse/SPR-12170">SPR-12170</a>). You could use the <code>SimpMessagingTemplate</code> for the time being (that's how it works internally anyway). Here's how you would do it:</p> <pre><code>@MessageMapping("/fleet/{fleetId}/driver/{driverId}") public void simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) { simpMessagingTemplate.convertAndSend("/topic/fleet/" + fleetId, new Simple(fleetId, driverId)); } </code></pre> <p>In your code, the destination '<em>/topic/fleet/{fleetId}</em>' is treated as a literal, that's the reason why subscribing to it works, just because you are sending to the exact same destination.</p> <p>If you just want to send some initial user specific data, you could return it directly in the subscription:</p> <pre><code>@SubscribeMapping("/fleet/{fleetId}/driver/{driverId}") public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) { return new Simple(fleetId, driverId); } </code></pre> <p><strong>Update:</strong> In Spring 4.2, destination variable placeholders are supported it's now possible to do something like:</p> <pre><code>@MessageMapping("/fleet/{fleetId}/driver/{driverId}") @SendTo("/topic/fleet/{fleetId}") public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) { return new Simple(fleetId, driverId); } </code></pre>
27,307,131
Selenium webdriver: How do I find ALL of an element's attributes?
<p>In the Python Selenium module, once I have a <code>WebElement</code> object I can get the value of any of its attributes with <code>get_attribute()</code>:</p> <pre><code>foo = elem.get_attribute('href') </code></pre> <p>If the attribute named <code>'href'</code> doesn't exist, <code>None</code> is returned.</p> <p>My question is, how can I get a list of all of the attributes that an element has? There doesn't seem to be a <code>get_attributes()</code> or <code>get_attribute_names()</code> method.</p> <p>I'm using version 2.44.0 of the Selenium module for Python.</p>
27,307,235
4
0
null
2014-12-05 01:05:39.577 UTC
22
2019-05-30 18:47:47.23 UTC
2018-09-17 01:20:02.663 UTC
null
1,893,164
null
1,893,164
null
1
71
python|selenium|selenium-webdriver
94,274
<p>It is <strong>not possible</strong> using a selenium webdriver API, but you can <a href="https://stackoverflow.com/questions/21681897/getting-all-attributes-from-an-iwebelement-with-selenium-webdriver"><em>execute a javascript code</em> to get all attributes</a>:</p> <pre><code>driver.execute_script('var items = {}; for (index = 0; index &lt; arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; from selenium import webdriver &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; driver = webdriver.Firefox() &gt;&gt;&gt; driver.get('https://stackoverflow.com') &gt;&gt;&gt; &gt;&gt;&gt; element = driver.find_element_by_xpath('//div[@class="network-items"]/a') &gt;&gt;&gt; attrs = driver.execute_script('var items = {}; for (index = 0; index &lt; arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element) &gt;&gt;&gt; pprint(attrs) {u'class': u'topbar-icon icon-site-switcher yes-hover js-site-switcher-button js-gps-track', u'data-gps-track': u'site_switcher.show', u'href': u'//stackexchange.com', u'title': u'A list of all 132 Stack Exchange sites'} </code></pre> <hr> <p>For completeness sake, an alternative solution would be to get the tag's <code>outerHTML</code> and parse the attributes using an HTML parser. Example (using <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer"><code>BeautifulSoup</code></a>):</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; html = element.get_attribute('outerHTML') &gt;&gt;&gt; attrs = BeautifulSoup(html, 'html.parser').a.attrs &gt;&gt;&gt; pprint(attrs) {u'class': [u'topbar-icon', u'icon-site-switcher', u'yes-hover', u'js-site-switcher-button', u'js-gps-track'], u'data-gps-track': u'site_switcher.show', u'href': u'//stackexchange.com', u'title': u'A list of all 132 Stack Exchange sites'} </code></pre>
40,366,717
Firebase for Android, How can I loop through a child (for each child = x do y)
<p>This is what my test looks like:</p> <p><a href="https://i.stack.imgur.com/AKQLW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AKQLW.png" alt="enter image description here"></a></p> <p>I won't use the fields above, it's just a dummy. But I would like to go through all the children on "users" and for each email return a: </p> <pre><code>System.out.println(emailString); </code></pre> <p>The only way I found of listing an object is using firebaseAdapter, is there another way of doing it?</p>
40,367,515
5
1
null
2016-11-01 18:52:02.877 UTC
11
2021-01-27 21:56:20.58 UTC
2016-11-01 20:39:03.823 UTC
null
5,637,321
null
712,312
null
1
24
java|android|firebase|firebase-realtime-database
39,396
<p>The easiest way is with a ValueEventListener.</p> <pre><code> FirebaseDatabase.getInstance().getReference().child("users") .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { User user = snapshot.getValue(User.class); System.out.println(user.email); } } @Override public void onCancelled(DatabaseError databaseError) { } }); </code></pre> <p>The <code>User</code> class can be defined like this:</p> <pre><code>class User { private String email; private String userId; private String username; // getters and setters... } </code></pre>
3,072,349
Capture screenshot Including Semitransparent windows in .NET
<p>I would like a relatively hack-free way to do this, any ideas? For example, the following takes a screenshot that doesn't include the semi-transparent window:</p> <pre><code>Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown Text = "Opaque Window" Dim win2 As New Form win2.Opacity = 0.5 win2.Text = "Tranparent Window" win2.Show() win2.Top = Top + 50 win2.Left = Left() + 50 Dim bounds As Rectangle = System.Windows.Forms.Screen.GetBounds(Point.Empty) Using bmp As Bitmap = New Bitmap(bounds.Width, bounds.Height) Using g As Graphics = Graphics.FromImage(bmp) g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size) End Using bmp.Save("c:\temp\scn.gif") End Using Process.Start(New Diagnostics.ProcessStartInfo("c:\temp\scn.gif") With {.UseShellExecute = True}) End Sub End Class </code></pre> <p>Either my google-fu really sucks or this is not as easy as it sounds. I'm pretty sure why this is happening because of the way the video driver would have to separate the memory to make this work, but I don't care why it doesn't work, I just want to do it without...<br> * print-screen key hacks<br> * 3rd party software<br> * SDK functions are OK but I'll upvote every object owned by the user that can show me it in pure framework (Just kidding but it would be nice). </p> <p>If <a href="http://weseetips.com/2008/07/14/how-to-capture-the-screenshot-of-window/" rel="noreferrer">This</a> is the only way to do it, how to I do that in VB?<br> 1M thanks.</p>
3,072,580
1
1
null
2010-06-18 18:53:10.147 UTC
31
2016-08-11 06:02:03.257 UTC
null
null
null
null
37,769
null
1
32
c#|.net|windows|vb.net|sdk
23,042
<p>Forms that have the TransparencyKey or Opacity property set are so-called layered windows. They are shown using the "overlay" feature of the video adapter. Which make them being able to have their transparency effects.</p> <p>Capturing them requires turning on the CopyPixelOperation.CaptureBlt option in the CopyFromScreen overload that accepts the CopyPixelOperation argument.</p> <p>Unfortunately, this overload has a critical bug that prevents this from working. It doesn't validate the value properly. Still not fixed in .NET 4.0. There is no other good fix but fall back to using P/Invoke to make the screen shot. Here's an example:</p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Size sz = Screen.PrimaryScreen.Bounds.Size; IntPtr hDesk = GetDesktopWindow(); IntPtr hSrce = GetWindowDC(hDesk); IntPtr hDest = CreateCompatibleDC(hSrce); IntPtr hBmp = CreateCompatibleBitmap(hSrce, sz.Width, sz.Height); IntPtr hOldBmp = SelectObject(hDest, hBmp); bool b = BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); Bitmap bmp = Bitmap.FromHbitmap(hBmp); SelectObject(hDest, hOldBmp); DeleteObject(hBmp); DeleteDC(hDest); ReleaseDC(hDesk, hSrce); bmp.Save(@"c:\temp\test.png"); bmp.Dispose(); } // P/Invoke declarations [DllImport("gdi32.dll")] static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, CopyPixelOperation rop); [DllImport("user32.dll")] static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDc); [DllImport("gdi32.dll")] static extern IntPtr DeleteDC(IntPtr hDc); [DllImport("gdi32.dll")] static extern IntPtr DeleteObject(IntPtr hDc); [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr ptr); } } </code></pre> <p>Fwiw, a later Windows version provided a workaround for this bug. Not exactly sure which, I think it was Win7 SP1. The BitBlt() function will now do what you want if you pass <em>only</em> the CopyPixelOperation.CaptureBlt option. But of course that workaround wasn't applied retro-actively to earlier Windows versions so you can't really depend on it.</p>
31,593,445
moment.js get yesterday time range from midnight to midnight
<p>How can I get the time range for yesterday from midnight until midnight:</p> <p>Example:</p> <p>Yesterday 22.07.2015</p> <p>Result:</p> <p>22.07.2015 00:00:00 (AM)</p> <p>22.07.2015 23:59:59 (PM)</p> <p>Date format doesn't matter this is just an example.</p>
31,758,270
1
0
null
2015-07-23 16:46:57.373 UTC
7
2018-09-11 13:50:31.16 UTC
null
null
null
null
2,818,430
null
1
62
javascript|momentjs
45,537
<pre><code>moment().subtract(1,'days').startOf('day').toString() </code></pre> <blockquote> <p>"Thu Jul 30 2015 00:00:00 GMT-0600"</p> </blockquote> <pre><code>moment().subtract(1,'days').endOf('day').toString() </code></pre> <blockquote> <p>"Thu Jul 30 2015 23:59:59 GMT-0600"</p> </blockquote>
44,454,797
Pull to refresh recyclerview android
<p>Hi I've a tabbed activity, and in the first tab I fetch data from server and show it in a recyclerview within card views. For fetching the data from server I use the volley library. I want to implement the Pull to refresh to load the data (so whenever I pull it has to do the request to the network). And I want also to disable the network request whenever I switch between tabs (because when I change tab focus in my app it starts to fetching data) I want to do the network request only 1 time (when user log in first time) and then others requests maneged only by pull to refresh. </p> <p>Here's my fragment where I've recyclerview and show the data:</p> <pre><code>public class Tab1History extends Fragment { private RecyclerView recyclerView; private CespiteAdapter adapter; UserSessionManager session; private static final String URL_DATA = "http://mydata.php"; private List&lt;CespiteOgg&gt; cespiteOggList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tab1history, container, false); recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view); recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); cespiteOggList = new ArrayList&lt;&gt;(); loadRecyclerViewData(); return rootView; } private void loadRecyclerViewData() { // Session class instance session = new UserSessionManager(getActivity()); //get user data from session HashMap&lt;String, String&gt; user = session.getUserDetails(); //get name String name = user.get(UserSessionManager.KEY_NAME); // get username final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME); final ProgressDialog progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("Carimento dati..."); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String s) { progressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(s); JSONArray array = jsonObject.getJSONArray("dates"); for(int i=0; i&lt;array.length(); i++) { JSONObject o = array.getJSONObject(i); CespiteOgg item = new CespiteOgg( o.getString("CodNumInventario"), o.getString("Nome"), o.getString("DtCatalogazione"), o.getString("CodIdA"), o.getString("username") ); cespiteOggList.add(item); } adapter = new CespiteAdapter(cespiteOggList, getActivity()); recyclerView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); } }) { @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("Username", usernameUtente); return params; } }; RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest); } } </code></pre> <p><strong>And it's the adapter:</strong></p> <pre><code>public class CespiteAdapter extends RecyclerView.Adapter&lt;CespiteAdapter.ViewHolder&gt; { private List&lt;CespiteOgg&gt; cespiteOggList; private Context context; public CespiteAdapter(List&lt;CespiteOgg&gt; cespiteOggList, Context context) { this.cespiteOggList = cespiteOggList; this.context = context; } public class ViewHolder extends RecyclerView.ViewHolder { public CardView cv; public TextView txtNumInventario; public TextView txtNomeCespite; public TextView txtDtCatalogazione; public TextView txtAula; public TextView txtNomeUser; ViewHolder(View itemView) { super (itemView); //cv = (CardView) itemView.findViewById(R.id.cardView); txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario); txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite); txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione); txtAula = (TextView) itemView.findViewById(R.id.txtAula); txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser); } } @Override public CespiteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View cespiteView = inflater.inflate(R.layout.cespite_card_view, parent, false); return new ViewHolder(cespiteView); } @Override public void onBindViewHolder(ViewHolder holder, int position) { CespiteOgg cespiteOgg = cespiteOggList.get(position); holder.txtNumInventario.setText(cespiteOgg.getNumInventario()); holder.txtNomeCespite.setText(cespiteOgg.getNomeCespite()); holder.txtDtCatalogazione.setText(cespiteOgg.getDtCatalogazione()); holder.txtAula.setText(cespiteOgg.getAula()); holder.txtNomeUser.setText(cespiteOgg.getNomeUser()); } @Override public int getItemCount() { return cespiteOggList.size(); } } </code></pre>
44,455,823
7
1
null
2017-06-09 09:58:32.503 UTC
23
2022-07-08 04:38:27.093 UTC
null
null
null
null
8,083,156
null
1
72
android|android-fragments|android-volley|android-cardview|pull-to-refresh
96,783
<p>You can use android <a href="https://developer.android.com/training/swipe/add-swipe-interface.html" rel="noreferrer">SwipeRefreshLayout</a> widget instead of <code>ProgressDialog</code>.</p> <p><strong>Follow below steps to integrate <code>SwipeRefreshLayout</code> in your <code>Tab1history</code> fragment:</strong></p> <p><strong>1.</strong> In your layout <code>tab1history</code>, add <code>SwipeRefreshLayout</code> as a root layout and place <code>RecyclewrView</code> inside it.</p> <pre><code>// tab1history.xml &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe_container" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/android.support.v4.widget.SwipeRefreshLayout&gt; </code></pre> <p><strong>2.</strong> In your <code>Tab1History</code> fragment, use <code>SwipeRefreshLayout</code> as below to load data from server:</p> <pre><code>// Tab1History.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class Tab1History extends Fragment implements SwipeRefreshLayout.OnRefreshListener { SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView recyclerView; private CespiteAdapter adapter; UserSessionManager session; private static final String URL_DATA = "http://mydata.php"; private List&lt;CespiteOgg&gt; cespiteOggList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tab1history, container, false); recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view); recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); cespiteOggList = new ArrayList&lt;&gt;(); // SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_dark, android.R.color.holo_orange_dark, android.R.color.holo_blue_dark); /** * Showing Swipe Refresh animation on activity create * As animation won't start on onCreate, post runnable is used */ mSwipeRefreshLayout.post(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(true); // Fetching data from server loadRecyclerViewData(); } }); return rootView; } /** * This method is called when swipe refresh is pulled down */ @Override public void onRefresh() { // Fetching data from server loadRecyclerViewData(); } private void loadRecyclerViewData() { // Showing refresh animation before making http call mSwipeRefreshLayout.setRefreshing(true); // Session class instance session = new UserSessionManager(getActivity()); //get user data from session HashMap&lt;String, String&gt; user = session.getUserDetails(); //get name String name = user.get(UserSessionManager.KEY_NAME); // get username final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String s) { try { JSONObject jsonObject = new JSONObject(s); JSONArray array = jsonObject.getJSONArray("dates"); for(int i=0; i&lt;array.length(); i++) { JSONObject o = array.getJSONObject(i); CespiteOgg item = new CespiteOgg( o.getString("CodNumInventario"), o.getString("Nome"), o.getString("DtCatalogazione"), o.getString("CodIdA"), o.getString("username") ); cespiteOggList.add(item); } adapter = new CespiteAdapter(cespiteOggList, getActivity()); recyclerView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } // Stopping swipe refresh mSwipeRefreshLayout.setRefreshing(false); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Stopping swipe refresh mSwipeRefreshLayout.setRefreshing(false); } }) { @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("Username", usernameUtente); return params; } }; RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest); } } </code></pre> <p>Hope this will work properly.</p>
26,018,756
Bootstrap button drop-down inside responsive table not visible because of scroll
<p>I have a problem with drop-down buttons inside tables when are responsive and scroll active because the drop-down is not visible because of <code>overflow: auto;</code> property. How can I fix that in order to show drop-down option of button when this is collapsed? I can use some jQuery but after I have problems with scroll left-right so I decided to find another solution. I have attached a photo to understand better.<img src="https://i.stack.imgur.com/Ibu5y.png" alt="enter image description here"></p> <p><strong><a href="http://jsfiddle.net/D2RLR/6917/" rel="noreferrer">Here is a small js fiddle:</a></strong></p>
26,097,713
28
0
null
2014-09-24 13:55:31.073 UTC
29
2022-04-21 17:11:14.433 UTC
2014-09-25 15:03:41.817 UTC
null
171,456
null
1,192,687
null
1
110
javascript|jquery|css|twitter-bootstrap|overflow
139,771
<p>I solved myself this and I put the answer in scope to help other user that have same problem: We have an event in bootstrap and we can use that event to set <code>overflow: inherit</code> but this will work if you don't have the css property on your parent container.</p> <pre><code>$('.table-responsive').on('show.bs.dropdown', function () { $('.table-responsive').css( &quot;overflow&quot;, &quot;inherit&quot; ); }); $('.table-responsive').on('hide.bs.dropdown', function () { $('.table-responsive').css( &quot;overflow&quot;, &quot;auto&quot; ); }) </code></pre> <p><strong><a href="http://jsfiddle.net/D2RLR/6936/" rel="noreferrer">and this is the fiddle</a></strong></p> <p><code>info:</code> In this fiddle example works strange and I'm not sure why but in my project works just fine.</p>
2,583,429
How to differentiate between time to live and time to idle in ehcache
<p>The docs on ehache says:</p> <pre><code>timeToIdleSeconds: Sets the time to idle for an element before it expires. i.e. The maximum amount of time between accesses before an element expires timeToLiveSeconds: Sets the time to live for an element before it expires. i.e. The maximum time between creation time and when an element expires. </code></pre> <p>I understand <strong>timeToIdleSeconds</strong></p> <p>But does it means that after the creation &amp; first access of a cache item, the <strong>timeToLiveSeconds</strong> is not applicable anymore ?</p>
2,583,553
3
0
null
2010-04-06 08:08:38.08 UTC
24
2017-10-03 09:05:31.78 UTC
2010-04-06 08:43:09.1 UTC
null
70,604
null
27,328
null
1
112
java|ehcache
64,794
<p><code>timeToIdleSeconds</code> enables cached object to be kept in as long as it is requested in periods shorter than <code>timeToIdleSeconds</code>. <code>timeToLiveSeconds</code> will make the cached object be invalidated after that many seconds regardless of how many times or when it was requested.</p> <p>Let's say that <code>timeToIdleSeconds = 3</code>. Then the object will be invalidated if it hasn't been requested for 4 seconds.</p> <p>If <code>timeToLiveSeconds = 90</code>, then the object will be removed from cache after 90 seconds, even if it has been requested few milliseconds in the 90th second of its short life. </p>
37,764,670
Android Retrofit 2.0 Refresh Tokens
<p>I am using <code>Retrofit 2.0</code> with <code>Jackson</code> converter for communication with a Rest API. Some of the requests require tokens on authorization. If the tokens that I have are out-of-date, I need to refresh them with another request and repeat the last request that failed because of it.</p> <p>My question: do I need to do it manually each time or is there any way to automate it ?</p> <p>Here is the way I implement it at the moment:</p> <p><strong>TrackerService</strong></p> <pre><code>public interface TrackerService { @POST("auth/sendPassword") Call&lt;ResponseMessage&gt; sendPassword(@Header("app-type") String appType, @Body User userMobile); @FormUrlEncoded @POST("oauth/token") Call&lt;TokenResponse&gt; oathToken(@Field("client_id") String clientId, @Field("client_secret") String clientSecret, @Field("grant_type") String grantType, @Field("username") String username, @Field("password") String password); @FormUrlEncoded @POST("oauth/token") Call&lt;TokenResponse&gt; refreshToken(@Field("client_id") String clientId, @Field("client_secret") String clientSecret, @Field("grant_type") String grantType, @Field("refresh_token") String username); @PUT("me/profile") Call&lt;Profile&gt; updateProfile(@Header("app-type") String appType, @Header("Authorization") String token, @Body Profile profile); } </code></pre> <p><strong>ServiceGateway</strong></p> <pre><code>public class ServiceGateway { private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); private static Retrofit retrofit; public static &lt;S&gt; S createService(Class&lt;S&gt; serviceClass) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS) .writeTimeout(20 * 1000, TimeUnit.MILLISECONDS) .readTimeout(20 * 1000, TimeUnit.MILLISECONDS) .addInterceptor(interceptor).build(); Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(JacksonConverterFactory.create()); retrofit = builder.client(httpClient.build()) .client(client) .build(); return retrofit.create(serviceClass); } public static Retrofit getRetrofit() { return retrofit; } } </code></pre> <p><strong>How I call function and treat it when tokens are out of date</strong></p> <pre><code> trackerService = ServiceGateway.createService(TrackerService.class); Call&lt;Profile&gt; call = trackerService.updateProfile(getString(R.string.app_type), "Bearer " + userPrefs.accessToken().get(), new Profile(trimedInvitationMessage, title, String.valueOf(selectedCountry.getCountryCode()), mobilePhone, countryISO, fullName)); call.enqueue(new Callback&lt;Profile&gt;() { @Override public void onResponse(Call&lt;Profile&gt; call, Response&lt;Profile&gt; response) { if (response.body() != null) { } else { if (response.raw().code() == 401) { Call&lt;TokenResponse&gt; refreshTokenCall = trackerService.refreshToken(userPrefs.clientId().get(), userPrefs.clientSecret().get(), "refresh_token", userPrefs.refreshToken().get()); refreshTokenCall.enqueue(new Callback&lt;TokenResponse&gt;() { @Override public void onResponse(Call&lt;TokenResponse&gt; call, Response&lt;TokenResponse&gt; response) { if (response.body() != null) { updateAdviserProfile(trimedInvitationMessage, title, mobilePhone, countryISO, fullName); } else { userPrefs.clear(); Intent intent = new Intent(WelcomeActivity_.launcher(EditProfileActivity.this)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); startActivity(WelcomeActivity_.launcher(EditProfileActivity.this)); } } @Override public void onFailure(Call&lt;TokenResponse&gt; call, Throwable t) { } }); } else if (response.raw().code() == 422) } } @Override public void onFailure(Call&lt;Profile&gt; call, Throwable t) { } }); </code></pre>
37,796,084
3
0
null
2016-06-11 14:07:42.003 UTC
20
2021-04-11 11:43:22.82 UTC
2017-11-01 10:05:45.82 UTC
null
5,047,398
null
6,453,655
null
1
30
android|jackson|retrofit
33,526
<p>I searched this topic since 2-3 months ago and found <code>OkHttp's Authenticator</code>. You can use it. There is one link here: <a href="https://stackoverflow.com/questions/22450036/refreshing-oauth-token-using-retrofit-without-modifying-all-calls">refreshing-oauth-token-using-retrofit-without-modifying-all-calls</a></p> <p>It works like that: If your request returns <code>401</code>, then <code>Authenticator</code> moves in, and refreshes your token. But don't forget to <code>return null</code> or put any try limit. If you don't limit, it will try to refresh multiple times when your refresh request fails. Also, make synchronous requests when refreshing your token.</p> <p>Also, I have a question and answer -both written by myself- about refreshing the Oauth2 token:</p> <p>Question: <a href="https://stackoverflow.com/questions/35516626/solved-android-retrofit2-refresh-oauth-2-token">android-retrofit2-refresh-oauth-2-token</a></p> <p>Answer: <a href="https://stackoverflow.com/a/35630788/5047398">android-retrofit2-refresh-oauth-2-token-answer</a></p> <p><strong>Additionally:</strong> For example if you have a token and you need to refresh it per 3 hours. You can write an <code>Interceptor</code> too. In <code>Interceptor</code>: compare time and refresh your token without getting any <code>401</code> response.</p> <p>Square's documentation for <code>Interceptor</code>: <a href="https://square.github.io/okhttp/interceptors/" rel="noreferrer">OkHttp Interceptors</a></p> <p>Square's documentation for <code>Authenticator</code>: <a href="https://square.github.io/okhttp/recipes/#handling-authentication-kt-java" rel="noreferrer">OkHttp handling-authentication</a></p> <p>I know there is no code here, but see links and edit your question then I will try to help you.</p>
28,709,411
Add users to group in GitLab
<p>I am filled with chagrin having to ask this, but I can't figure out how to add users in GitLab. I get to the screen where it allows me to add new members as follows:</p> <blockquote> <p>From my Group page -> click the 'members' icon on the toolbar along the left edge -> click 'Add Members' expando button -> enter username in 'Find existing member by name' or 'People' fields and get no results.</p> </blockquote> <p>The 'People' field auto-populates with a bunch of names I don't recognize. But won't let me find a user who has registered by username or actual name. Am I missing something?</p>
28,709,577
3
0
null
2015-02-25 01:10:16.6 UTC
2
2021-09-26 11:28:54.707 UTC
null
null
null
null
1,296,030
null
1
22
gitlab
75,143
<p>What version? These instructions are for gitlab community edition on ubuntu; the deb was named gitlab_7.4.3-omnibus.5.1.0.ci-1_amd64: </p> <ol> <li>Login</li> <li>Click the gears icon (top right) to enter the Admin area</li> <li>Click the Groups link (top center) to enter the Groups page</li> <li>Click the name of the group you wish to extend ("Mygroup")</li> <li>Look at the right side of the screen; if you have the right privs you should see "Add user(s) to the group:"</li> <li>Type the first few letters of the user name into the box, a drop-down should appear so you can select the user.</li> </ol> <p>HTH</p>
38,218,174
How do I find the variable names and values that are saved in a checkpoint?
<p>I want to see the variables that are saved in a TensorFlow checkpoint along with their values. How can I find the variable names that are saved in a TensorFlow checkpoint?</p> <p>I used <code>tf.train.NewCheckpointReader</code> which is explained <a href="https://github.com/tensorflow/tensorflow/blob/861644c0bcae5d56f7b3f439696eefa6df8580ec/tensorflow/python/training/saver_test.py#L1203" rel="noreferrer">here</a>. But, it is not given in the documentation of TensorFlow. Is there any other way?</p>
38,226,516
6
0
null
2016-07-06 07:12:20.83 UTC
19
2021-03-17 07:40:10.367 UTC
2019-03-10 21:50:30.79 UTC
null
429,972
null
806,160
null
1
39
tensorflow
40,859
<p>You can use the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/inspect_checkpoint.py" rel="noreferrer"><code>inspect_checkpoint.py</code></a> tool.</p> <p>So, for example, if you stored the checkpoint in the current directory, then you can print the variables and their values as follows</p> <pre><code>import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file latest_ckp = tf.train.latest_checkpoint('./') print_tensors_in_checkpoint_file(latest_ckp, all_tensors=True, tensor_name='') </code></pre>
1,330,798
How can I generate convenient date ranges based on a given NSDate?
<p>I'm creating a report generator in Cocoa, and I need to produce convenient date ranges such as "Today", "This Week", "This Month", "This Year", etc.</p> <p>Is there a good way to do this? Here is my skeleton thus far:</p> <pre><code>@interface DateRange : NSObject { NSDate startDate; NSDate endDate; } @property (nonatomic, retain) NSDate * startDate; @property (nonatomic, retain) NSDate * endDate; + (DateRange *)rangeForDayContainingDate:(NSDate *)date; + (DateRange *)rangeForWeekContainingDate:(NSDate *)date; + (DateRange *)rangeForMonthContainingDate:(NSDate *)date; + (DateRange *)rangeForYearContainingDate:(NSDate *)date; @end </code></pre> <p>Some example use cases would be as follows:</p> <pre><code>DateRange * thisWeek = [DateRange rangeForWeekContainingDate:[NSDate date]]; DateRange * thisYear = [DateRange rangeForYearContainingDate:[NSDate date]]; </code></pre> <p>Essentially, I want the returned <code>DateRange</code> object to contain the start and end dates for the week, month or year surrounding the target date. For example (in pseudocode):</p> <pre><code>NSDate * today = [August 25, 2009]; DateRange * thisWeek = [DateRange rangeForWeekContainingDate:today]; assert(thisWeek.startDate == [August 23, 3009]); assert(thisWeek.endDate == [August 29, 3009]); </code></pre> <p><strong>update:</strong></p> <p>I was able to get this working thanks to the <a href="https://stackoverflow.com/questions/1330798/how-can-i-generate-convenient-date-ranges-based-on-a-given-nsdate/1330821#1330821">answer provided by Kendall Helmstetter Geln</a>. Here is the complete method for a one-week range:</p> <pre><code>+ (DateRange *)rangeForWeekContainingDate:(NSDate *)date { DateRange * range = [[self alloc] init]; // start of the week NSDate * firstDay; [[self calendar] rangeOfUnit:NSWeekCalendarUnit startDate:&amp;firstDay interval:0 forDate:date]; [range setStartDate:firstDay]; // end of the week NSDateComponents * oneWeek = [[NSDateComponents alloc] init]; [oneWeek setWeek:1]; [range setEndDate:[[self calendar] dateByAddingComponents:oneWeek toDate:firstDay options:0]]; [oneWeek release]; return [range autorelease]; } </code></pre>
1,330,821
2
2
null
2009-08-25 20:31:45.983 UTC
9
2011-09-25 23:05:03.603 UTC
2017-05-23 12:10:19.847 UTC
null
-1
null
33,686
null
1
5
cocoa|nsdate
3,513
<p>Well since timeInterval is in seconds, just do the math to figure out how many seconds are in a day:</p> <p>60 seconds * 60 minutes * 24 hours = 1 day.</p> <p>Then in your <code>rangeForDayContainingDate</code> method you could extract date components, get the current day, create a new date based on the day with hours and minutes set to 0:00, and the create the end date adding the time interval as calculated above.</p>
3,138,992
.vimrc for IntelliJ Idea's vim plugin
<p>I am using the vim plugin for IntelliJ Idea.<br> Where should I place the .vimrc for that plugin.<br> Using Windows XP</p>
3,141,345
5
2
null
2010-06-29 08:26:44.267 UTC
5
2022-09-06 21:35:03.17 UTC
2020-07-09 19:49:32.853 UTC
null
223,386
null
49,560
null
1
45
intellij-idea|vim
21,437
<pre><code>echo %homepath% </code></pre> <p>gives me my "home directory" on Windows XP,<br> where I need to put my .vimrc.</p>
2,706,913
How to make an app's background image repeat
<p>I have set a background image in my app, but the background image is small and I want it to be repeated and fill in the whole screen. What should I do?</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg" android:tileMode="repeat"&gt; </code></pre>
2,706,944
5
0
null
2010-04-25 02:25:59.27 UTC
131
2018-02-11 09:16:27.07 UTC
2018-02-11 09:16:27.07 UTC
null
2,649,012
null
238,061
null
1
319
android|image|layout
211,964
<p>Ok, here's what I've got in my app. It includes a hack to prevent <code>ListView</code>s from going black while scrolling.</p> <p><strong>drawable/app_background.xml</strong>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/actual_pattern_image" android:tileMode="repeat" /&gt; </code></pre> <p><strong>values/styles.xml</strong>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;style name="app_theme" parent="android:Theme"&gt; &lt;item name="android:windowBackground"&gt;@drawable/app_background&lt;/item&gt; &lt;item name="android:listViewStyle"&gt;@style/TransparentListView&lt;/item&gt; &lt;item name="android:expandableListViewStyle"&gt;@style/TransparentExpandableListView&lt;/item&gt; &lt;/style&gt; &lt;style name="TransparentListView" parent="@android:style/Widget.ListView"&gt; &lt;item name="android:cacheColorHint"&gt;@android:color/transparent&lt;/item&gt; &lt;/style&gt; &lt;style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView"&gt; &lt;item name="android:cacheColorHint"&gt;@android:color/transparent&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p><strong>AndroidManifest.xml</strong>:</p> <pre><code>// &lt;application android:theme="@style/app_theme"&gt; // </code></pre>
3,114,769
Selecting entries by date - >= NOW(), MySQL
<p>I have a Calendar of Events table and I would like to select events with dates equal to or greater than today. When I use the following SELECT statement, it only retrieves events in the future (> NOW()):</p> <pre><code>&lt;?php $db-&gt;query("SELECT * FROM events WHERE event_date &gt;= NOW()"); ?&gt; </code></pre> <p>How would I go about selecting all events that are either today or in the future?</p> <p>Thank you</p>
3,114,778
6
0
null
2010-06-25 00:08:28.173 UTC
10
2017-03-17 15:06:18.317 UTC
2010-06-25 01:01:56.183 UTC
null
135,152
null
321,597
null
1
34
sql|mysql|date
77,952
<p>You are looking for <a href="http://www.w3schools.com/sql/func_curdate.asp" rel="noreferrer"><code>CURDATE()</code></a>:</p> <pre><code>$db-&gt;query("SELECT * FROM events WHERE event_date &gt;= CURDATE()"); </code></pre> <p>Or:</p> <pre><code>$db-&gt;query("SELECT * FROM events WHERE event_date &gt;= CURRENT_DATE()"); </code></pre>
2,955,402
How do I create directory if it doesn't exist to create a file?
<p>I have a piece of code here that breaks if the directory doesn't exist:</p> <pre><code>System.IO.File.WriteAllText(filePath, content); </code></pre> <p>In one line (or a few lines), is it possible to check if the directory leading to the new file doesn't exist and if not, to create it before creating the new file?</p> <p>I'm using .NET 3.5.</p>
2,955,425
6
2
null
2010-06-02 06:14:58.603 UTC
37
2021-05-12 07:22:08.963 UTC
2016-01-14 12:38:06.227 UTC
null
531,524
null
279,911
null
1
238
c#|.net|file-io
186,024
<h3>To Create</h3> <p><code>(new FileInfo(filePath)).Directory.Create()</code> before writing to the file.</p> <h3>....Or, if it exists, then create (else do nothing)</h3> <pre><code>System.IO.FileInfo file = new System.IO.FileInfo(filePath); file.Directory.Create(); // If the directory already exists, this method does nothing. System.IO.File.WriteAllText(file.FullName, content); </code></pre>
2,724,760
How to write "C++" in LaTeX
<p>How can I write "C++" in LaTeX so that the output looks nice. For example <code>C$++$</code> doesn't look good: the plus signs are too big and there is too much space.</p>
2,724,826
7
2
null
2010-04-27 20:18:27.56 UTC
17
2019-11-16 10:58:16.103 UTC
2011-02-13 14:02:25.087 UTC
null
90,563
null
1,169,720
null
1
60
latex
55,842
<p>The standard solution for cases like this is to use verbatim:</p> <pre><code>\verb!C++! </code></pre>
2,499,176
iOS: Download image from url and save in device
<p>I am trying to download the image from the url <a href="http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg" rel="noreferrer">http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg</a></p> <p>I am using the following code, but image is not saved in the device. I want to know what I am doing wrong.</p> <pre><code> NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]]; [NSURLConnection connectionWithRequest:request delegate:self]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"]; NSData *thedata = NULL; [thedata writeToFile:localFilePath atomically:YES]; UIImage *img = [[UIImage alloc] initWithData:thedata]; </code></pre>
2,499,241
9
3
null
2010-03-23 10:44:59.5 UTC
87
2015-12-01 20:11:06.807 UTC
2012-08-14 03:28:54.68 UTC
null
299,797
null
299,797
null
1
48
iphone|ios|image|cocoa-touch|ipad
90,522
<p>If you set <code>theData</code> to <code>nil</code>, what do you expect it to write to the disk?</p> <p>What you can use is <code>NSData* theData = [NSData dataWithContentsOfURL:yourURLHere];</code> to load the data from the disk and then save it using <code>writeToFile:atomically:</code>. If you need more control over the loading process or have it in background, look at the documentation of <code>NSURLConnection</code> and the associated guide.</p>
2,904,689
How to initialize var?
<p>Can I initialize var with null or some empty value?</p>
2,904,783
11
5
null
2010-05-25 12:47:56.387 UTC
18
2017-04-02 13:47:03.587 UTC
2014-01-16 10:19:58.717 UTC
null
661,933
null
324,831
null
1
76
c#|initialization
271,053
<p>C# is a <strong>strictly/strongly typed language</strong>. var was introduced for compile-time type-binding for <a href="https://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="noreferrer">anonymous types</a> yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.</p> <p>When you say, </p> <pre><code>var x = null; </code></pre> <p>the compiler cannot resolve this because there's no type bound to null. You can make it like this.</p> <pre><code>string y = null; var x = y; </code></pre> <p>This will work because now x can know its type at compile time that is string in this case.</p>
3,069,589
How to disable breadcrumbs in Eclipse
<p>How can I disable the Java editor breadcrumb in Eclipse?</p> <p><a href="https://i.stack.imgur.com/MEkh3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MEkh3.png" alt="enter image description here" /></a></p>
3,069,751
11
0
null
2010-06-18 12:35:13.013 UTC
41
2021-06-24 10:55:46.537 UTC
2021-06-24 10:55:46.537 UTC
null
733,637
null
171,950
null
1
334
eclipse|breadcrumbs
106,204
<p>If you are referring to the breadcrumbs in the help file of a RCP application, there is <del>only</del> a <a href="http://dev.eclipse.org/newslists/news.eclipse.platform/msg68472.html" rel="noreferrer">manual way to do it</a>.</p> <p>Since <a href="http://giano.com.dist.unige.it/eclipseMirror/eclipse/downloads/drops/S-3.4M5-200802071530/eclipse-news-M5.html" rel="noreferrer">Ganymede 3.4M5</a>:</p> <p><img src="https://i.stack.imgur.com/pu5vU.png" alt="Initial Breadcrump GUI"></p> <ul> <li><a href="https://stackoverflow.com/users/16883/michael-borgwardt">Michael Borgwardt</a> <a href="https://stackoverflow.com/a/3069794/6309">mentions</a> the toolbar icon <img src="https://i.stack.imgur.com/wKewV.jpg" alt="dd"></li> <li><a href="https://stackoverflow.com/users/352708/slava-semushin">Slava Semushin</a> <a href="https://stackoverflow.com/a/9869403/6309">provides</a> a native shortcut based on <kbd>Ctrl</kbd>+<kbd>3</kbd>+<code>bread</code>, which points directly to the <code>Toggle Java Editor Breadcrumb</code> option.</li> <li><a href="https://stackoverflow.com/users/2034700/shachi">Shachi</a> reminds us <a href="https://stackoverflow.com/a/15154516/6309">below</a> that you can right-click on any icon on the breadcrumb, and select the entry named "<code>Hide Breadcrumb</code>".</li> </ul> <p><img src="https://i.stack.imgur.com/ODWFJ.png" alt="Hide breadcrumbs"></p> <hr> <p>Original answer (manual way, through key mapping)</p> <blockquote> <p>Find the file <code>org.eclipse.help.webapp\advanced\breadcrumbs.css</code> and replace its contents with.</p> </blockquote> <pre><code>.help_breadcrumbs { display: none; } </code></pre> <hr> <p>For the Java Editor breadcrumb, you need to assign a shortcut to the "Toggle Java Editor Breadcrumb" command (I have tested <kbd>Alt</kbd>+<kbd>B</kbd>, for instance)</p> <p><img src="https://i.stack.imgur.com/Vyptq.png" alt="alt text"></p> <p>That shortcut will make the breadcrumb bar appear/disappear at will.</p>
2,618,059
In Java, what does NaN mean?
<p>I have a program that tries to shrink a <code>double</code> down to a desired number. The output I get is <code>NaN</code>.</p> <p>What does <code>NaN</code> mean in Java?</p>
2,618,081
11
3
null
2010-04-11 17:57:46.797 UTC
24
2019-04-30 08:57:45.587 UTC
2015-10-28 05:55:50.77 UTC
null
2,776,146
null
282,315
null
1
125
java|nan
301,935
<p>Taken from <a href="http://www.ica.luz.ve/dfinol/mat/javafloat.html" rel="noreferrer">this page</a>:</p> <blockquote> <p>"NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.</p> </blockquote>
2,494,452
Rails Polymorphic Association with multiple associations on the same model
<p>My question is essentially the same as this one: <a href="https://stackoverflow.com/questions/1168047/polymorphic-association-with-multiple-associations-on-the-same-model">Polymorphic Association with multiple associations on the same model</a></p> <p>However, the proposed/accepted solution does not work, as illustrated by a commenter later.</p> <p>I have a Photo class that is used all over my app. A post can have a single photo. However, I want to re-use the polymorphic relationship to add a secondary photo.</p> <p>Before:</p> <pre><code>class Photo belongs_to :attachable, :polymorphic =&gt; true end class Post has_one :photo, :as =&gt; :attachable, :dependent =&gt; :destroy end </code></pre> <p>Desired:</p> <pre><code>class Photo belongs_to :attachable, :polymorphic =&gt; true end class Post has_one :photo, :as =&gt; :attachable, :dependent =&gt; :destroy has_one :secondary_photo, :as =&gt; :attachable, :dependent =&gt; :destroy end </code></pre> <p>However, this fails as it cannot find the class "SecondaryPhoto". Based on what I could tell from that other thread, I'd want to do:</p> <pre><code> has_one :secondary_photo, :as =&gt; :attachable, :class_name =&gt; "Photo", :dependent =&gt; :destroy </code></pre> <p>Except calling Post#secondary_photo simply returns the same photo that is attached via the Photo association, e.g. Post#photo === Post#secondary_photo. Looking at the SQL, it does WHERE type = "Photo" instead of, say, "SecondaryPhoto" as I'd like...</p> <p>Thoughts? Thanks!</p>
3,078,286
12
1
null
2010-03-22 17:41:48.427 UTC
30
2021-04-07 08:07:04.13 UTC
2017-05-23 12:18:25.157 UTC
null
-1
null
2,590
null
1
61
ruby-on-rails|polymorphic-associations
30,879
<p>I have done that in my project.</p> <p>The trick is that photos need a column that will be used in has_one condition to distinguish between primary and secondary photos. Pay attention to what happens in <code>:conditions</code> here.</p> <pre><code>has_one :photo, :as =&gt; 'attachable', :conditions =&gt; {:photo_type =&gt; 'primary_photo'}, :dependent =&gt; :destroy has_one :secondary_photo, :class_name =&gt; 'Photo', :as =&gt; 'attachable', :conditions =&gt; {:photo_type =&gt; 'secondary_photo'}, :dependent =&gt; :destroy </code></pre> <p>The beauty of this approach is that when you create photos using <code>@post.build_photo</code>, the photo_type will automatically be pre-populated with corresponding type, like 'primary_photo'. ActiveRecord is smart enough to do that.</p>
45,678,817
error "ETXTBSY: text file is busy" on npm install
<p>When running <code>npm install [any package]</code> or even <code>npm install</code> on homestead I get the following error:</p> <pre><code>npm ERR! ETXTBSY: text file is busy, rmdir '/home/vagrant/valemus-shop-starter/valemus-shop/node_modules/fsevents' </code></pre> <p>Debug log can be seen <a href="https://gist.github.com/martijnimhoff/118aab71ef9fe4ceb9b97be03e33f1df" rel="noreferrer">here</a></p> <ul> <li>Box 'laravel/homestead' (v3.0.0) </li> <li>Node: v8.2.1 </li> <li>NPM: 5.3.0</li> </ul> <p>I tried removing the <code>fsevents</code> directory, however, it doesn't exist.</p> <p>How do I fix this?</p>
53,099,324
9
0
null
2017-08-14 16:20:13.94 UTC
6
2018-12-06 06:31:11.823 UTC
2018-07-30 13:14:43.72 UTC
null
2,520,628
null
5,688,047
null
1
33
javascript|node.js|laravel|npm|homestead
26,553
<p>Downgraing the npm version to 5.7.1 did the trick for me.</p> <p>Command used to downgrade: <code>npm install -g [email protected]</code></p> <p>I am using Win10, Vagrant, Ubuntu v14.04 and Node v8.11.4</p>
42,305,275
creating a .bat file with npm install command
<p>I created the following file</p> <p>//npminstall.bat</p> <pre><code>npm install echo hello </code></pre> <p>When I run the following command from Windows 10 Command Line (dos) <code>npminstall.bat</code>, the <code>npm install</code> command fires, but the <code>echo hello</code> doesn't fire. I tried putting a semi-color after the first line like this <code>npm install;</code>, but all that did was give me the help instructions of npm .</p> <p>How do I get the second line <code>echo hello</code> to fire after the <code>npm install</code>?</p> <p><strong>Additional Notes</strong></p> <p>I have found that this also causes the same behaviour:</p> <p>//npminstall.bat</p> <pre><code>webpack echo hello </code></pre> <p>I think it's because both the <code>npm install</code> command and <code>webpack</code> command takes time to execute, and during that time it doe ssomething I don't expect to the second line.</p> <p><strong>Followup 2</strong></p> <p>//npminstall.bat</p> <pre><code>START /WAIT npm install echo hello </code></pre> <p>This seems to almost do what I want to do. Except the npm install command causes a pop up window, and i have to shut down teh pop up window before it continues execution to echo hello world. Can I get rid of the popup window?</p>
42,306,073
1
0
null
2017-02-17 18:44:19.807 UTC
16
2017-02-17 19:36:42.16 UTC
2017-02-17 19:18:14.663 UTC
null
27,305
null
27,305
null
1
119
batch-file|npm-install
41,680
<p>When you access another batch file from a batch file, you need to use the CALL command to return control to parent process otherwise control is passed to the batch file being executed.</p> <pre><code>call npm install </code></pre>
10,424,997
android, How to rename a file?
<p>In my application, I need to record video. Before start of recording in I'm assigning a name and directory to it. After recording is finished user has ability to rename his file. I wrote following code but seem it doesn't work. </p> <p>When user enters name of file and click on button I'll do this:</p> <pre><code>private void setFileName(String text) { String currentFileName = videoURI.substring(videoURI.lastIndexOf("/"), videoURI.length()); currentFileName = currentFileName.substring(1); Log.i("Current file name", currentFileName); File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME); File from = new File(directory, "currentFileName"); File to = new File(directory, text.trim() + ".mp4"); from.renameTo(to); Log.i("Directory is", directory.toString()); Log.i("Default path is", videoURI.toString()); Log.i("From path is", from.toString()); Log.i("To path is", to.toString()); } </code></pre> <p>Text: is the name which is entered by user. Current Filename: is the name which is assigned by me before recording MEDIA_NAME: name of folder</p> <p>Logcat shows this:</p> <pre><code>05-03 11:56:37.295: I/Current file name(12866): Mania-Karaoke_20120503_115528.mp4 05-03 11:56:37.295: I/Directory is(12866): /mnt/sdcard/Movies/Mania-Karaoke 05-03 11:56:37.295: I/Default path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/Mania-Karaoke_20120503_115528.mp4 05-03 11:56:37.295: I/From path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/currentFileName 05-03 11:56:37.295: I/To path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/hesam.mp4 </code></pre> <p>Any suggestion would be appreciated.</p>
10,425,106
9
0
null
2012-05-03 04:11:02.063 UTC
13
2020-06-25 08:14:41.123 UTC
2014-05-15 06:28:58.13 UTC
null
1,611,444
null
513,413
null
1
48
android|file-rename
101,333
<p>The problem is in this line,</p> <pre><code>File from = new File(directory, "currentFileName"); </code></pre> <p>Here <code>currentFileName</code> is actually a String you dont have to use <code>"</code></p> <p>try it this way,</p> <pre><code>File from = new File(directory, currentFileName ); ^ ^ //You dont need quotes </code></pre>
10,591,543
MongoDB: How to query for records where field is null or not set?
<p>I have an <code>Email</code> document which has a <code>sent_at</code> date field:</p> <pre><code>{ 'sent_at': Date( 1336776254000 ) } </code></pre> <p>If this <code>Email</code> has not been sent, the <code>sent_at</code> field is either null, or non-existant.</p> <p>I need to get the count of all sent/unsent <code>Emails</code>. I'm stuck at trying to figure out the right way to query for this information. I think this is the right way to get the sent count:</p> <pre><code>db.emails.count({sent_at: {$ne: null}}) </code></pre> <p>But how should I get the count of the ones that aren't sent?</p>
10,591,601
9
0
null
2012-05-14 21:47:54.26 UTC
23
2021-11-16 13:37:06.643 UTC
2015-05-30 12:28:40.78 UTC
null
1,480,391
null
48,523
null
1
129
mongodb|null|mongodb-query|exists
161,876
<p>If the <code>sent_at</code> field is not there when its not set then:</p> <pre class="lang-javascript prettyprint-override"><code>db.emails.count({sent_at: {$exists: false}}) </code></pre> <p>If it's there and null, or not there at all:</p> <pre class="lang-javascript prettyprint-override"><code>db.emails.count({sent_at: null}) </code></pre> <p>If it's there and null:</p> <pre class="lang-javascript prettyprint-override"><code>db.emails.count({sent_at: { $type: 10 }}) </code></pre> <hr /> <p>The <a href="https://docs.mongodb.com/manual/tutorial/query-for-null-fields/" rel="noreferrer">Query for Null or Missing Fields</a> section of the MongoDB manual describes how to query for null and missing values.</p> <blockquote> <h2>Equality Filter</h2> <p>The <code>{ item : null }</code> query matches documents that either contain the item field whose value is <code>null</code> <em>or</em> that do not contain the <code>item</code> field.</p> <pre class="lang-javascript prettyprint-override"><code>db.inventory.find( { item: null } ) </code></pre> </blockquote> <blockquote> <h2>Existence Check</h2> <p>The following example queries for documents that do not contain a field.</p> <p>The <code>{ item : { $exists: false } }</code> query matches documents that do not contain the <code>item</code> field:</p> <pre class="lang-javascript prettyprint-override"><code>db.inventory.find( { item : { $exists: false } } ) </code></pre> </blockquote> <blockquote> <h2>Type Check</h2> <p>The <code>{ item : { $type: 10 } }</code> query matches <em>only</em> documents that contain the <code>item</code> field whose value is <code>null</code>; i.e. the value of the item field is of <a href="https://docs.mongodb.com/manual/reference/bson-types/" rel="noreferrer">BSON Type</a> <code>Null</code> (type number <code>10</code>) :</p> <pre class="lang-javascript prettyprint-override"><code>db.inventory.find( { item : { $type: 10 } } ) </code></pre> </blockquote>