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
8,157,345
Entity Framework Stored Procedure Table Value Parameter
<p>I'm trying to call a stored procedure that accepts a table value parameter. I know that this isn't directly supported in Entity Framework yet but from what I understand you can do it using the <code>ExecuteStoreQuery</code> command off of the <code>ObjectContext</code>. I have a generic entity framework repository where I have the following <code>ExecuteStoredProcedure</code> method:</p> <pre><code>public IEnumerable&lt;T&gt; ExecuteStoredProcedure&lt;T&gt;(string procedureName, params object[] parameters) { StringBuilder command = new StringBuilder(); command.Append("EXEC "); command.Append(procedureName); command.Append(" "); // Add a placeholder for each parameter passed in for (int i = 0; i &lt; parameters.Length; i++) { if (i &gt; 0) command.Append(","); command.Append("{" + i + "}"); } return this.context.ExecuteStoreQuery&lt;T&gt;(command.ToString(), parameters); } </code></pre> <p>The command string ends up like this:</p> <pre><code>EXEC someStoredProcedureName {0},{1},{2},{3},{4},{5},{6},{7} </code></pre> <p>I tried to run this method on a stored procedure that accepts a table valued parameter and it breaks. I read <a href="https://stackoverflow.com/questions/6084061/udt-as-a-parameter-in-ef4-query">here</a> that the parameters needed to be of type <code>SqlParameter</code> and the table valued parameter needs to have the <code>SqlDbType</code> set to <code>Structured</code>. So I did this and I get an error stating:</p> <pre><code>The table type parameter p6 must have a valid type name </code></pre> <p>So, I set the SqlParameter.TypeName to the name of the user defined type I created on the database and then when I run the query I get the following truly helpful error:</p> <pre><code>Incorrect syntax near '0'. </code></pre> <p>I can get the query to run if I revert back to ADO.NET and and execute a data reader but I was hoping to get it to work using the data context.</p> <p>Is there a way to pass a table value parameter using <code>ExecuteStoreQuery</code>? Also, I am actually using Entity Framework Code First and casting the <code>DbContext</code> to an <code>ObjectContext</code> to get the <code>ExecuteStoreQuery</code> method available. Is this necessary or can I do this against the <code>DbContext</code> as well?</p>
9,837,927
6
3
null
2011-11-16 19:16:38.047 UTC
32
2018-05-15 04:20:59.693 UTC
2017-10-23 12:06:24.407 UTC
null
1,741,690
null
489,213
null
1
72
c#|entity-framework|stored-procedures|ef-code-first|table-valued-parameters
101,563
<p><strong>UPDATE</strong></p> <p>I've added support for this on Nuget Package - <a href="https://github.com/Fodsuk/EntityFrameworkExtras#nuget" rel="noreferrer">https://github.com/Fodsuk/EntityFrameworkExtras#nuget</a> (EF4,EF5,EF6)</p> <p>Check out the <a href="https://github.com/Fodsuk/EntityFrameworkExtras" rel="noreferrer">GitHub</a> repository for code examples.</p> <hr> <p>Slightly off question, but none the less useful for people trying to pass user-defined tables into a stored procedure. After playing around with Nick's example and other Stackoverflow posts, I came up with this:</p> <pre><code>class Program { static void Main(string[] args) { var entities = new NewBusinessEntities(); var dt = new DataTable(); dt.Columns.Add("WarningCode"); dt.Columns.Add("StatusID"); dt.Columns.Add("DecisionID"); dt.Columns.Add("Criticality"); dt.Rows.Add("EO01", 9, 4, 0); dt.Rows.Add("EO00", 9, 4, 0); dt.Rows.Add("EO02", 9, 4, 0); var caseId = new SqlParameter("caseid", SqlDbType.Int); caseId.Value = 1; var userId = new SqlParameter("userid", SqlDbType.UniqueIdentifier); userId.Value = Guid.Parse("846454D9-DE72-4EF4-ABE2-16EC3710EA0F"); var warnings = new SqlParameter("warnings", SqlDbType.Structured); warnings.Value= dt; warnings.TypeName = "dbo.udt_Warnings"; entities.ExecuteStoredProcedure("usp_RaiseWarnings_rs", userId, warnings, caseId); } } public static class ObjectContextExt { public static void ExecuteStoredProcedure(this ObjectContext context, string storedProcName, params object[] parameters) { string command = "EXEC " + storedProcName + " @caseid, @userid, @warnings"; context.ExecuteStoreCommand(command, parameters); } } </code></pre> <p>and the stored procedure looks like this:</p> <pre><code>ALTER PROCEDURE [dbo].[usp_RaiseWarnings_rs] (@CaseID int, @UserID uniqueidentifier = '846454D9-DE72-4EF4-ABE2-16EC3710EA0F', --Admin @Warnings dbo.udt_Warnings READONLY ) AS </code></pre> <p>and the user-defined table looks like this:</p> <pre><code>CREATE TYPE [dbo].[udt_Warnings] AS TABLE( [WarningCode] [nvarchar](5) NULL, [StatusID] [int] NULL, [DecisionID] [int] NULL, [Criticality] [int] NULL DEFAULT ((0)) ) </code></pre> <p>Constraints I found include:</p> <ol> <li>The parameters you pass into <code>ExecuteStoreCommand</code> have to be in order with the parameters in your stored procedure</li> <li>You have to pass every column in to your user-defined table, even if they are have defaults. So it seems i couldn't have a IDENTITY(1,1) NOT NULL column on my UDT</li> </ol>
7,835,304
Why would a post-build step (xcopy) occasionally exit with code 2 in a TeamCity build?
<p>A few projects in my client's solution have a post-build event: <code>xcopy</code> the build output to a specific folder. This works fine when building locally. However, in TeamCity, I <em>occasionally</em> get </p> <blockquote> <p>xcopy [...] exited with code 2</p> </blockquote> <p>If I use regular <code>copy</code>, it exits with code 1. I expect this has something to do with file locks, although the specific files being copied are not the same, so perhaps just locking on the shared destination directory. I use <code>/y</code> to not prompt on overwriting files.</p> <p>Why this fails in TeamCity but not locally?</p>
14,637,854
6
7
null
2011-10-20 11:33:33.873 UTC
17
2019-02-19 16:24:13.507 UTC
2017-12-13 06:54:25.72 UTC
null
1,033,581
null
487,544
null
1
100
teamcity|xcopy
77,645
<p>Even if you provide the <code>/Y</code> switch with xcopy, you'll still get an error when xcopy doesn't know if the thing you are copying is a file or a directory. This error will appear as "exited with code 2". When you run the same xcopy at a command prompt, you'll see that xcopy is asking for a response of file or directory.</p> <p>To resolve this issue with an automated build, you can echo in a pre-defined response with a pipe.</p> <p>To say the thing you are copying is a file, echo in <code>F</code>:</p> <pre><code>echo F|xcopy /y ... </code></pre> <p>To say the thing you are copying is a directory, echo in <code>D</code>:</p> <pre><code>echo D|xcopy /y ... </code></pre> <p>Sometimes the above can be resolved by simply using a copy command instead of xcopy:</p> <pre><code>copy /y ... </code></pre> <p>However, if there are non-existent directories leading up to the final file destination, then an "exited with code 1" will occur.</p> <p>Remember: use the <code>/C</code> switch and xcopy with caution.</p>
8,311,604
Check if a double is infinite in Java
<p>I'm making a simple calculator for this homework, and Java is returning "Infinity" when divided by 0.</p> <p>I need to display some error message, when I get infinity. The problem is I don't know how to do the condition</p> <pre><code>double result; result = 4/0; //if result == infinity then some message - need help with this </code></pre>
8,311,657
7
5
null
2011-11-29 13:34:24.59 UTC
2
2020-08-18 13:04:46.177 UTC
2017-02-22 09:44:57.91 UTC
null
1,743,880
null
928,611
null
1
31
java
45,943
<p>You can use <code>Double.isInfinite(double)</code></p> <p>Here's <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html" rel="noreferrer">double doc</a></p>
7,704,976
Submit an HTML form without having a submit button?
<p>Can I submit a html <code>&lt;form&gt;</code> with <code>&lt;div&gt;</code> instead of <code>&lt;input type=&quot;submit&quot;&gt;</code> ?</p> <p>Like this:</p> <pre><code>&lt;form method=&quot;post&quot; action=&quot;&quot; id=&quot;myForm&quot;&gt; &lt;textarea name=&quot;reply&quot;&gt;text&lt;/textarea&gt; &lt;/form&gt; &lt;div&gt;Submit the form by clicking this&lt;/div&gt; </code></pre>
7,704,985
11
0
null
2011-10-09 16:48:45.01 UTC
4
2020-10-22 10:52:33.62 UTC
2020-10-22 10:44:30.893 UTC
null
4,861,760
null
616,855
null
1
21
jquery|html|forms
93,728
<p>The method you can use to submit a specific form is the following:</p> <pre class="lang-js prettyprint-override"><code>// Grab the form element and manually trigger the 'submit' method on it: document.getElementById(&quot;myForm&quot;).submit(); </code></pre> <p>So in your example, you can add a click event handler on any element you like and trigger the form's submit method through that:</p> <pre class="lang-html prettyprint-override"><code>&lt;form method=&quot;post&quot; id=&quot;myForm&quot;&gt; &lt;textarea name=&quot;reply&quot;&gt;text&lt;/textarea&gt; &lt;/form&gt; &lt;div class=&quot;submit&quot;&gt;Submit the form by clicking this&lt;/div&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>const myForm = document.getElementById(&quot;myForm&quot;); document.querySelector(&quot;.submit&quot;).addEventListener(&quot;click&quot;, function(){ myForm.submit(); }); </code></pre> <p>And if you want to do it jQuery style (which <strong>I do not recommend for such a simple task</strong>);</p> <pre class="lang-js prettyprint-override"><code>$(&quot;#myForm&quot;).submit(); </code></pre> <p>In its full form:</p> <pre class="lang-js prettyprint-override"><code>const myForm = $(&quot;#myForm&quot;); $(&quot;.submit&quot;).click(function(){ myForm.submit(); }); </code></pre> <hr /> <p><strong>References:</strong></p> <ul> <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit" rel="noreferrer">submit()</a> method of HTML Form elements (native <code>JavaScript API</code>)</li> <li>The <code>jQuery</code> <a href="https://api.jquery.com/submit/" rel="noreferrer">submit()</a> API</li> </ul>
4,805,577
When importing a java library class from jar, is this considered static linking? or dynamic?
<p>say I have jcifs-1.3.14.jar in my lib folder, and I have a class that is importing from the library and uses the classes like:</p> <pre><code>import jcifs.smb.*; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, pass); SmbFile file = new SmbFile(path, auth); // do some operations with the file here </code></pre> <p>When using the library in this fashion is it considered to be: A) Static Linking OR B) Dynamic Linking OR C) something else?</p>
4,805,744
3
4
null
2011-01-26 14:22:20.5 UTC
2
2020-09-23 12:56:46.987 UTC
null
null
null
null
6,153
null
1
28
java|dynamic|static|linker|jar
19,048
<p>If you are looking for information about applying various software licenses on Java programs, then searching Google for <code>&lt;license name&gt; Java</code> usually results in a useful hit.</p> <p>E.g for <code>LGPL Java</code>, <a href="http://www.gnu.org/licenses/lgpl-java.html" rel="noreferrer">this</a> is the first hit. In this particular case, the bottom line is:</p> <blockquote> <p>Applications which link to LGPL libraries need not be released under the LGPL. Applications need only follow the requirements in section 6 of the LGPL: allow new versions of the library to be linked with the application; and allow reverse engineering to debug this.</p> </blockquote> <p>I.e. as long as the library is provided in a separate JAR file that can be easily replaced, LGPL allows it.</p> <p>PS: I Am Not A Lawyer! If in doubt, consult one. As a matter of fact, depending on where you live, it might make sense to consult one regardless if you are in doubt or not.</p>
14,808,351
Disable then re-enable click function jQuery
<p>I have a file upload system, after the upload button is clicked, the file is then uploaded through AJAX. While the file is uploaded I want to disable the click function that is on the "Select Images" button. Currently this is the click function on the file-selection button:</p> <pre><code>$(document).ready(function() { $("#file-button").click(function() { $('#file').trigger('click'); }); }); </code></pre> <p>That works fine, but I want to disable the click function in the progress phase of the XmlHttpRequest, and then re-enable the click function when I get a 200 response from the server. I have tried <code>bind()</code> and <code>unbind()</code> and it works fine in Chrome, but in firefox, during the upload, the button cannot be clicked, which is what I want, and then after I get a response from the server the button is re-enabled, but in firefox two file-selection dialogue windows open at the same time. This is because of the function above, and me binding the function again using <code>bind()</code>. Does anyone have any suggestions on how to enable, then disable the button without re-entering the code (function) of the click event.</p> <p>Something like this would be preferable:</p> <pre><code>$('#file-button').disable(); $('#file-button').enable(); </code></pre> <p>I have tried the <code>on()</code> and <code>off()</code> and they do not seem to work either.</p>
15,016,697
4
0
null
2013-02-11 08:28:26.767 UTC
null
2013-02-22 04:11:11.567 UTC
2013-02-21 20:26:43.88 UTC
null
561,731
null
1,994,446
null
1
7
javascript|jquery|firefox
43,649
<p><strong>SOLUTION</strong> -- thanks to Eric</p> <p>I changed my initial click function to the following:</p> <pre><code>$(document).ready(function() { $("#file-button").click(function() { if ( $('#file-button').attr('disabled') == "disabled" ) { return false; } else { $('#file').trigger('click'); } }); }); </code></pre> <p>And I set the following to disable the button</p> <pre><code>$('#file-button').attr('disabled','disabled'); </code></pre> <p>And this to re-enable it:</p> <pre><code>$('#file-button').removeAttr('disabled'); </code></pre>
4,575,032
Why does Linux on x86 use different segments for user processes and the kernel?
<p>So, I know that Linux uses four default segments for an x86 processor (kernel code, kernel data, user code, user data), but they all have the same base and limit (0x00000000 and 0xfffff), meaning each segment maps to the same set of linear addresses. </p> <p>Given this, why even have user/kernel segments? I understand why there should be separate segments for code and data (just due to how the x86 processor deals with the cs and ds registers), but why not have a single code segment and a single data segment? Memory protection is done through paging, and the user and kernel segments map to the same linear addresses anyway.</p>
4,575,256
4
0
null
2011-01-01 18:01:56.487 UTC
11
2018-09-28 09:44:18.183 UTC
2015-11-09 16:49:49.21 UTC
null
895,245
user220878
null
null
1
19
linux-kernel|x86|memory-segmentation
6,428
<p>The x86 architecture associates a type and a privilege level with each segment descriptor. The type of a descriptor allows segments to be made read only, read/write, executable, etc., but the main reason for different segments having the same base and limit is to allow a different descriptor privilege level (DPL) to be used.</p> <p>The DPL is two bits, allowing the values 0 through 3 to be encoded. When the privilege level is 0, then it is said to be <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Ring_%28computer_security%29" rel="noreferrer">ring 0</a>, which is the most privileged. The segment descriptors for the Linux kernel are ring 0 whereas the segment descriptors for user space are ring 3 (least privileged). This is true for most segmented operating systems; the core of the operating system is ring 0 and the rest is ring 3.</p> <p>The Linux kernel sets up, as you mentioned, four segments:</p> <ul> <li>__KERNEL_CS (Kernel code segment, base=0, limit=4GB, type=10, DPL=0)</li> <li>__KERNEL_DS (Kernel data segment, base=0, limit=4GB, type=2, DPL=0)</li> <li>__USER_CS (User code segment, base=0, limit=4GB, type=10, DPL=3)</li> <li>__USER_DS (User data segment, base=0, limit=4GB, type=2, DPL=3)</li> </ul> <p>The base and limit of all four are the same, but the kernel segments are DPL 0, the user segments are DPL 3, the code segments are executable and readable (not writable), and the data segments are readable and writable (not executable).</p> <p>See also:</p> <ul> <li><a href="http://book.opensourceproject.org.cn/kernel/kernel3rd/opensource/0596005652/understandlk-chp-2-sect-3.html" rel="noreferrer">Segmentation in Linux</a></li> <li><a href="http://www.cs.cmu.edu/~410/doc/segments/segments.html" rel="noreferrer">x86 Segmentation for the 15-410 Student</a></li> <li><a href="http://pdos.csail.mit.edu/6.828/2005/readings/i386/s05_01.htm" rel="noreferrer">5.1.1 Descriptors</a></li> <li><a href="http://pdos.csail.mit.edu/6.828/2005/readings/i386/s06_03.htm" rel="noreferrer">6.3.1 Descriptors Store Protection Parameters</a></li> </ul>
4,104,474
Rails 3 UTF-8 query string showing up in URL?
<p>I have a search query form on my home page (/)</p> <pre><code>&lt;% form_tag(search_path, :method =&gt; :get) do %&gt; &lt;%= text_field_tag 'query' %&gt; &lt;%= submit_tag "Search", :name =&gt; nil%&gt; &lt;% end %&gt; </code></pre> <p>When I submit this search form, I want to end up at (/search?query=foo). However, right now I get /search?utf8=%E2%9C%93&amp;query=foo. What's that utf8 parameter doing there? How can I get rid of it?</p> <p>Thanks.</p>
4,104,728
4
0
null
2010-11-05 08:49:42.003 UTC
6
2015-11-09 23:40:05.947 UTC
null
null
null
null
553,044
null
1
33
ruby-on-rails|string|url|ruby-on-rails-3
15,994
<p>The utf8 parameter (formerly known as <a href="http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen">snowman</a>) is a Rails 3 workaround for an Internet Explorer bug.</p> <p>The short answer is that Internet Explorer ignores POST data UTF8 encoding unless at least one UTF8 char is included in the POST data. For this reason, Rails injects an UTF8 character in the form to force IE to treat everything as UTF8 encoded.</p>
4,789,605
How do I enable automatic folds in Vim?
<p>How do I enable automatic folding in Vim? <code>set foldmethod=syntax</code> doesn't seem to do much of anything. </p>
4,789,615
4
0
null
2011-01-25 03:05:23 UTC
45
2021-04-13 11:39:46.217 UTC
null
null
null
null
58,089
null
1
80
javascript|perl|vim|folding
27,762
<p>To allow folds based on syntax add something like the following to your <code>.vimrc</code>:</p> <pre><code>set foldmethod=syntax set foldlevelstart=1 let javaScript_fold=1 &quot; JavaScript let perl_fold=1 &quot; Perl let php_folding=1 &quot; PHP let r_syntax_folding=1 &quot; R let ruby_fold=1 &quot; Ruby let sh_fold_enabled=1 &quot; sh let vimsyn_folding='af' &quot; Vim script let xml_syntax_folding=1 &quot; XML </code></pre> <p>Syntax based folding is defined in the syntax files of the language which are located in <code>$VIM/syntax</code> or <code>/usr/share/vim/vimXX/syntax/</code>. But some languages do not have folding rules built into their syntax files; for example Python. For those languages you need to download something from <a href="http://vim.sf.net" rel="nofollow noreferrer">http://vim.sf.net</a> that does folds. Otherwise you will need to use folds based on indents. To do this effectively you will likely want to add the following to your <code>.vimrc</code> file:</p> <pre><code>set foldmethod=indent set foldnestmax=2 </code></pre> <h1>Other kinds of folding</h1> <p>There are 6 types of folds:</p> <pre><code>manual manually define folds indent more indent means a higher fold level expr specify an expression to define folds syntax folds defined by syntax highlighting diff folds for unchanged text marker folds defined by markers in the text </code></pre> <p>Personally, I only use syntax folds. Usually, I just want to fold the method and not fold every indent level. Inconsistent indenting and weirdly formatted legacy code at work often makes indent folding difficult or impossible. Adding marks to the document is tedious and people who do not use Vim will not maintain them when they edit the document. Manual folds work great until someone edits your code in source control and all your folds are now in the wrong place.</p> <h1>More reading</h1> <ol> <li>See <code>:help fold-methods</code> to learn the details of different fold methods.</li> <li>See <code>:help folding</code> to learn the keyboard commands for manipulate folds.</li> <li>See <code>:help folds</code> for help on the entire topic of folding.</li> </ol>
4,580,982
javax.crypto.BadPaddingException
<p>I am working on AES algorithm, and I have this exception which I couldn't solve.</p> <pre><code>javax.crypto.BadPaddingException: Given final block not properly padded at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..) at javax.crypto.Cipher.doFinal(DashoA13*..) </code></pre> <p>the exception happens in the decryption part. I initialize the key in a different place from where the decryption algorithm is </p> <pre><code>KeyGenerator kgen = KeyGenerator.getInstance("AES");//key generation for AES kgen.init(128); // 192 and 256 bits may not be available </code></pre> <p>then I pass it with the cipher text which I read from file to the following method</p> <pre><code> public String decrypt(String message, SecretKey skey) { byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // Instantiate the cipher Cipher cipher; byte[] original = null; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); System.out.println("Original string: " + message); original = cipher.doFinal(message.trim().getBytes()); //here where I got the exception String originalString = new String(original); } //catches </code></pre> <p><strong>EDIT</strong> here's the encryption method.</p> <pre><code>public String encrypt(String message, SecretKey skey) { byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // Instantiate the cipher Cipher cipher; byte[] encrypted = null; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); encrypted = cipher.doFinal(message.getBytes()); System.out.println("raw is " + encrypted); } catches return asHex(encrypted); } </code></pre> <p>and here's the asHex method</p> <pre><code> public static String asHex(byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i &lt; buf.length; i++) { if (((int) buf[i] &amp; 0xff) &lt; 0x10) { strbuf.append("0"); } strbuf.append(Long.toString((int) buf[i] &amp; 0xff, 16)); } return strbuf.toString(); } </code></pre> <p>Here's where I read the cipher text form the file</p> <pre><code>static public String readFile(String filePath) { StringBuilder file = new StringBuilder(); String line = null; try { FileReader reader = new FileReader(filePath); BufferedReader br = new BufferedReader(reader); if (br != null) { line = br.readLine(); while (line != null) { file.append(line); // System.out.println("line is " + line); line = br.readLine(); } } br.close(); reader.close(); } catch (IOException ex) { Logger.getLogger(FileManagement.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("line is " + file.toString()); return String.valueOf(file); } </code></pre> <p>can someone help?</p>
4,581,156
5
3
null
2011-01-02 22:59:01.66 UTC
14
2016-06-27 19:45:23.193 UTC
2013-08-06 18:41:28.857 UTC
null
940,217
null
2,067,571
null
1
25
java|exception|cryptography|encryption
112,428
<p>Ok, so the problem is that you are converting the encrypted bytes to a hex string (using the <code>asHex</code> method) but are not converting the hex string back to a byte array correctly for decryption. You can't use <code>getBytes</code>.</p> <p>You can use the following <a href="https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java">method</a> to convert a hex string to a byte array:</p> <pre><code>public static byte[] fromHexString(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4) + Character.digit(s.charAt(i+1), 16)); } return data; } </code></pre> <p>and then change your decrypt method to use:</p> <pre><code>original = cipher.doFinal(fromHexString(message)); </code></pre>
4,538,226
How does the "Remember my password" checkbox work?
<p>There are numerous login forms with the little check box "Remember my password" so that the next time you visit the website, the browser automatically fills up the password field for you.</p> <p>But I have noticed a behavior in modern browsers, such as Chrome/Firefox, which shows up a notification bar to save the user name/passoword even though that particular web page does not have any "remember password" check box.</p> <p>so my questions are:</p> <ol> <li>If I have to put the "remember password" check box in a login form, what do I have to do when the user checks it? I mean, do I have to store the password in browser cookies (or Local Storage)? If so, should the password be encrypted or plain text?</li> <li>The "Save password" notification bar is a browser's functionality or is there any way to invoke it from the web page?</li> </ol>
4,540,915
6
0
null
2010-12-27 11:02:07.557 UTC
14
2014-01-12 09:22:37.67 UTC
null
null
null
null
42,372
null
1
44
html|cookies|passwords
53,460
<p>The "save password" part comes from the browser's password manager whenever it sees an <code>&lt;input type="password"&gt;</code> that looks like it really is asking for a password. You can use the autocomplete attribute to suppress this in most browsers:</p> <pre><code>&lt;input type="password" name="password" autocomplete="off"&gt; </code></pre> <p>This won't validate but that usually doesn't matter.</p> <p>The "remember me" part is completely separate from the browser's password manager. The "remember me" flag is the server's business and all it does is fiddle with the expiry date on the cookie that it sends back. The server will always send a cookie back (unless they're not using cookies for tracking sessions but that's rare and wouldn't need a "remember me" anyway) with something inside it to identify the client user.</p> <p>If you check "remember me" then you're telling the server that you want a persistent session. To achieve this, the server will include an expiry date with the cookie and that expiry date will be some time in the future. When the date arrives, the browser will expire and delete the cookie; without the cookie, the server won't know who you are anymore and you'll have to login again.</p> <p>If you don't check "remember me" then you'll get a session cookie. Session cookies don't have expiry dates on them so automatically expire when the browser exits. Session cookies are useful for shared machines.</p> <p>Executive summary:</p> <ul> <li>"Save password" is from the browser's password manager.</li> <li>"Remember me" is about the login cookie's expiry time.</li> </ul> <p>Sorry to be so long winded but there seems to be some confusion and a lack of clarity in the other answers.</p>
4,787,995
How to disable beforeunload action when user is submitting a form?
<p>I have this little piece of code:</p> <pre><code>&lt;script&gt; $(window).bind('beforeunload', function() { $.ajax({ async: false, type: 'POST', url: '/something' }); }); &lt;/script&gt; </code></pre> <p>I wonder, how could I disable this request when user hits the submit button.</p> <p>Basically something like here, on SO. When your asking a question and decide to close the page, you get a warning window, but that doesn't happen when you're submitting the form.</p>
4,788,033
7
0
null
2011-01-24 22:32:45.567 UTC
5
2020-04-17 18:08:20.173 UTC
null
null
null
null
244,751
null
1
33
javascript|jquery|ajax|onbeforeunload
43,245
<p>Call <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=1&amp;ved=0CBMQFjAA&amp;url=http%3A%2F%2Fapi.jquery.com%2Funbind%2F&amp;ei=df89TZm1KIX6lweLv_Rg&amp;usg=AFQjCNFbSCFR47fB4EUSCcAb2kOwYKuU0Q&amp;sig2=btOaSEmQvj91dxupI95GeQ"><code>unbind</code></a> using the <code>beforeunload</code> event handler:</p> <pre><code>$('form#someForm').submit(function() { $(window).unbind('beforeunload'); }); </code></pre> <p>To prevent the form from being submitted, add the following line:</p> <pre><code> return false; </code></pre>
4,576,222
Fastest way to write to file?
<p>I made a method that takes a <code>File</code> and a <code>String</code>. It replaces the file with a new file with that string as its contents.</p> <p>This is what I made: </p> <pre><code>public static void Save(File file, String textToSave) { file.delete(); try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(textToSave); out.close(); } catch (IOException e) { } } </code></pre> <p>However it is painfully slow. It sometimes takes over a minute.</p> <p>How can I write large files with tens of thousands to maybe up to a million characters in them?</p>
4,576,234
7
8
null
2011-01-01 23:06:16.327 UTC
16
2022-08-16 00:19:25.033 UTC
2011-01-02 11:30:23.903 UTC
null
85,421
user263078
null
null
1
37
java|file-io
97,340
<p>Make sure you allocate a large enough buffer:</p> <pre><code>BufferedWriter out = new BufferedWriter(new FileWriter(file), 32768); </code></pre> <p>What sort of OS are you running on? That can make a big difference too. However, taking a <em>minute</em> to write out a file of less-than-enormous size sounds like a system problem. On Linux or other *ix systems, you can use things like <code>strace</code> to see if the JVM is making lots of unnecessary system calls. (A very long time ago, Java I/O was pretty dumb and would make insane numbers of low-level <code>write()</code> system calls if you weren't careful, but when I say "a long time ago" I mean 1998 or so.)</p> <p><em>edit</em> &mdash; note that the situation of a Java program writing a simple file in a simple way, and yet being really slow, is an inherently odd one. Can you tell if the CPU is heavily loaded while the file is being written? It shouldn't be; there should be almost no CPU load from such a thing. </p>
4,080,456
fputcsv and newline codes
<p>I'm using fputcsv in PHP to output a comma-delimited file of a database query. When opening the file in gedit in Ubuntu, it looks correct - each record has a line break (no visible line break characters, but you can tell each record is separated,and opening it in OpenOffice spreadsheet allows me to view the file correctly.)</p> <p>However, we're sending these files on to a client on Windows, and on their systems, the file comes in as one big, long line. Opening it in Excel, it doesn't recognize multiple lines at all.</p> <p>I've read several questions on here that are pretty similar, including <a href="https://stackoverflow.com/questions/2378268/fputcsv-and-notepad">this one</a>, which includes a link to the really informative <a href="http://www.codinghorror.com/blog/2010/01/the-great-newline-schism.html" rel="noreferrer">Great Newline Schism</a> explanation.</p> <p>Unfortunately, we can't just tell our clients to open the files in a "smarter" editor. They need to be able to open them in Excel. Is there any programmatic way to ensure that the correct newline characters are added so the file can be opened in a spreadsheet program on any OS?</p> <p>I'm already using a custom function to force quotes around all values, since fputcsv is selective about it. I've tried doing something like this:</p> <pre><code>function my_fputcsv($handle, $fieldsarray, $delimiter = "~", $enclosure ='"'){ $glue = $enclosure . $delimiter . $enclosure; return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure."\r\n"); } </code></pre> <p>But when the file is opened in a Windows text editor, it still shows up as a single long line.</p>
4,197,612
8
3
null
2010-11-02 17:35:53.003 UTC
9
2016-09-09 16:57:54.483 UTC
2017-05-23 11:33:16.553 UTC
null
-1
null
341,611
null
1
32
php|newline|fputcsv
42,329
<p>I did eventually get an answer over at experts-exchange; here's what worked:</p> <pre><code>function my_fputcsv($handle, $fieldsarray, $delimiter = "~", $enclosure ='"'){ $glue = $enclosure . $delimiter . $enclosure; return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure.PHP_EOL); } </code></pre> <p>to be used in place of standard fputcsv.</p>
4,555,932
"public" or "private" attribute in Python ? What is the best way?
<p>In Python, I have the following example class :</p> <pre><code>class Foo: self._attr = 0 @property def attr(self): return self._attr @attr.setter def attr(self, value): self._attr = value @attr.deleter def attr(self): del self._attr </code></pre> <p>As you can see, I have a simple "private" attribute "_attr" and a property to access it. There is a lot of codes to declare a simple private attribute and I think that it's not respecting the "KISS" philosophy to declare all attributes like that.</p> <p>So, why not declare all my attributes as public attributes if I don't need a particular getter/setter/deleter ?</p> <p>My answer will be : Because the principle of encapsulation (OOP) says otherwise!</p> <p>What is the best way ?</p>
4,555,970
9
3
null
2010-12-29 16:41:39.413 UTC
23
2020-01-13 20:21:02.247 UTC
2017-11-04 19:45:01.207 UTC
null
3,329,664
null
259,576
null
1
73
python|oop|properties|encapsulation
127,108
<p>Typically, Python code strives to adhere to the <a href="http://en.wikipedia.org/wiki/Uniform_access_principle" rel="noreferrer">Uniform Access Principle</a>. Specifically, the accepted approach is:</p> <ul> <li>Expose your instance variables directly, allowing, for instance, <code>foo.x = 0</code>, not <code>foo.set_x(0)</code></li> <li>If you need to wrap the accesses inside methods, for whatever reason, use <code>@property</code>, which preserves the access semantics. That is, <code>foo.x = 0</code> now invokes <code>foo.set_x(0)</code>.</li> </ul> <p>The main advantage to this approach is that the caller gets to do this:</p> <pre><code>foo.x += 1 </code></pre> <p>even though the code might really be doing:</p> <pre><code>foo.set_x(foo.get_x() + 1) </code></pre> <p>The first statement is infinitely more readable. Yet, with properties, you can add (at the beginning, or later on) the access control you get with the second approach.</p> <p>Note, too, that instance variables starting with a single underscore are <em>conventionally</em> private. That is, the underscore signals to other developers that you consider the value to be private, and they shouldn't mess with it directly; however, nothing in the language <em>prevents</em> them from messing with it directly.</p> <p>If you use a double leading underscore (e.g., <code>__x</code>), Python does a little obfuscation of the name. The variable is still accessible from outside the class, via its obfuscated name, however. It's not truly private. It's just kind of ... more opaque. And there are valid arguments against using the double underscore; for one thing, it can make debugging more difficult.</p>
14,720,134
Is it possible to random_shuffle an array of int elements?
<p>I was reading up on this : <a href="http://www.cplusplus.com/reference/algorithm/random_shuffle/" rel="noreferrer">http://www.cplusplus.com/reference/algorithm/random_shuffle/</a> and wondered if its possible to random_shuffle an array of int elements. This is my code</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; int main() { int a[10]={1,2,3,4,5,6,7,8,9,10}; cout &lt;&lt; a &lt;&lt; endl &lt;&lt; endl; random_shuffle(a[0],a[9]); cout&lt;&lt;a; } </code></pre> <p>I got this error: </p> <pre><code>error C2893: Failed to specialize function template 'iterator_traits&lt;_Iter&gt;::difference_type *std::_Dist_type(_Iter)'. </code></pre> <p>My question are:</p> <ol> <li><p>Is it possible to shuffle an int array using <code>random_shuffle</code>. If yes, I would like to learn how to do it.</p></li> <li><p>Is <code>random_shuffle</code> only applicable to templates?</p></li> <li><p>What does my error mean?</p></li> </ol>
14,720,159
5
0
null
2013-02-06 01:33:49.273 UTC
null
2017-07-21 09:29:17.423 UTC
2014-08-29 04:21:10.323 UTC
null
608,639
null
1,832,057
null
1
26
c++|algorithm|shuffle
65,334
<p>You need to pass pointers to <code>a[0]</code> and <code>a[10]</code>, not the elements themselves:</p> <pre><code>random_shuffle(&amp;a[0], &amp;a[10]); // end must be 10, not 9 </code></pre> <p>In C++11, you can use <code>std::begin</code> and <code>std::end</code>:</p> <pre><code>random_shuffle(std::begin(a), std::end(a)); </code></pre>
14,454,929
One-liner to create a dictionary with one entry
<p>I have a method which takes a <code>Dictionary&lt;int, int&gt;</code> as a parameter</p> <pre><code>public void CoolStuff(Dictionary&lt;int, int&gt; job) </code></pre> <p>I want to call that method with one dictionary entry, such as </p> <pre><code>int a = 5; int b = 6; var param = new Dictionary&lt;int, int&gt;(); param.Add(a, b); CoolStuff(param); </code></pre> <p>How can I do it in one line? </p>
14,454,948
2
1
null
2013-01-22 09:09:02.807 UTC
1
2013-01-22 09:10:19.337 UTC
null
null
null
null
98,317
null
1
52
c#|dictionary
32,399
<p>This is it, if you do not need the <code>a</code> and <code>b</code> variables:</p> <pre><code>var param = new Dictionary&lt;int, int&gt; { { 5, 6 } }; </code></pre> <p>or even</p> <pre><code>CoolStuff(new Dictionary&lt;int, int&gt; { { 5, 6 } }); </code></pre> <p>Please, read <a href="http://msdn.microsoft.com/en-us/library/vstudio/bb531208.aspx">How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)</a></p>
14,665,713
The name does not exist in the namespace error in XAML
<p>Using VS2012 working on a VB.NET WPF application. I have a simple MusicPlayer tutorial app I am using to learn WPF. I am converting a C# version of the tutorial to VB.NET step by step.</p> <p>It has 2 classes in the app that are both under the same namespace. I am able to reference the namespace in the XAML but when I try to reference the class object in XAML I get an error and I am not able to compile.</p> <p>Strange thing is that the IntelliSense works fine with both referencing the namespace via the xmlns:c= tag and also when typing the class object using <code>&lt;c:</code> But the object is underlined and errors are generated trying to build or work in the designer.</p> <p>The .vb class files are in a folder called \Controls. The Main project Root Namespace is intentionaly left blank. The class is coded like this...</p> <pre><code>Namespace MusicPlayer.Controls Public Class UpdatingMediaElement .... code here End Public End Namespace </code></pre> <p>The xaml looks like this</p> <p>(namespace defined in the <code>&lt;Window &gt;</code> tag</p> <pre><code>xmlns:c="clr-namespace:MusicPlayer.Controls" </code></pre> <p>(object defined in a <code>&lt;Grid&gt;</code> )</p> <pre><code> &lt;c:UpdatingMediaElement Name="MyMediaElement" /&gt; </code></pre> <p>(error displayed) The name "UpdatingMediaElement" does not exist in the namespace "clr-namespace:MusicPlayer.Controls".</p> <p>Not sure what is wrong or how to fix it?</p>
25,078,916
44
4
null
2013-02-02 19:40:00.403 UTC
37
2022-08-03 08:00:06.067 UTC
null
null
null
null
2,035,866
null
1
151
wpf|vb.net|xaml|visual-studio-2012
157,311
<p>When you are writing your wpf code and VS tell that "The name ABCDE does not exist in the namespace clr-namespace:ABC". But you can totally build your project successfully, there is only a small inconvenience because you can not see the UI designing (or just want to clean the code). </p> <p>Try to do these:</p> <ul> <li><p>In VS, right click on your Solution -> Properties -> Configuration Properties</p></li> <li><p>A new dialog is opened, try to change the project configurations from Debug to Release or vice versa. </p></li> </ul> <p>After that, re-build your solution. It can solve your problem.</p>
52,701,459
I can't use @PostConstruct and @PostDestroy with Java 11
<p>I've got problem with using <code>@PostConstruct</code> and<code>@PostDestroy</code> annotations in my project. I can't use these annotations and it looks like these doesn't exist despite the fact that I imported Java's annotations. I am using Java 11 and that is content of my <code>build.gradle</code> file:</p> <pre><code>dependencies { testCompile group: 'junit', name: 'junit', version: '4.11' testCompile group: 'junit', name: 'junit', version: '4.12' compile group: 'org.springframework', name: 'spring-webmvc', version: '5.1.0.RELEASE' compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.7' compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2' provided group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1' } </code></pre>
55,622,713
3
0
null
2018-10-08 11:40:35.323 UTC
8
2021-02-08 13:57:57.623 UTC
2018-10-08 12:00:13.047 UTC
null
6,916,147
user8116296
null
null
1
40
java|spring-mvc|annotations
28,287
<p>Note that both <code>@PostConstruct</code> and <code>@PreDestroy</code> annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations:</p> <p>For Maven</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;javax.annotation&lt;/groupId&gt; &lt;artifactId&gt;javax.annotation-api&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>If using Gradle</p> <pre><code>implementation &quot;javax.annotation:javax.annotation-api:1.3.2&quot; </code></pre> <p>Found here: <a href="https://www.baeldung.com/spring-postconstruct-predestroy" rel="noreferrer">https://www.baeldung.com/spring-postconstruct-predestroy</a></p>
49,907,455
Hide Code when exporting Jupyter notebook to HTML
<p>I'm looking for a way to hide code cells (inputs) when export my .iipynb file to a HTML. I don't want the code cells to be visible at all (not some button that turn them off/on). The output is for people that have no idea what a programming language is. I tried many things that I found on the internet but nothing seems to work. </p> <p>Thanks</p>
49,916,688
11
3
null
2018-04-18 19:18:08.09 UTC
29
2022-09-22 14:14:27.46 UTC
null
null
null
null
9,160,548
null
1
76
python|jupyter
76,715
<p>I finaly found that : <a href="https://pypi.org/project/hide_code/0.2.0/" rel="nofollow noreferrer">https://pypi.org/project/hide_code/0.2.0/</a></p> <p>It's a jupyter extension and it's working like a charm. I use the command prompt to convert the notebook into an html, since the buttons that comes with the extension don't work for me.</p>
27,863,604
How can I find a file in my git repository with SourceTree?
<p>How can I find a file in my git repository with SourceTree?</p> <p>Currently, the file has to be present in some branch log, but I want to search on the repository.</p> <p>I want to:</p> <ul> <li>right-click the file</li> <li><blockquote> <blockquote> <p>Log Selected... </p> </blockquote> </blockquote></li> <li><blockquote> <blockquote> <p>and peek at it's history.</p> </blockquote> </blockquote></li> </ul> <p>The SourceTree file history is quite good.</p> <p><img src="https://i.stack.imgur.com/npj6y.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/EpmDQ.png" alt="enter image description here"></p>
32,160,418
2
0
null
2015-01-09 15:13:13.117 UTC
2
2021-10-15 07:39:22.947 UTC
2021-09-03 03:59:04.307 UTC
null
1,402,846
null
2,614,299
null
1
33
git|file|atlassian-sourcetree|history
26,337
<p>In the working copy view there is a dropdown where you can select a filter for the visible files in the column below. Just select "All Files" instead of the "Pending" default.</p> <p>On the right side there also is a Searchbox to filter this file list.</p> <p><a href="https://i.stack.imgur.com/mGdwl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mGdwl.png" alt="SourceTree Working Copy View Screenshot"></a></p>
2,378,515
XAMPP when configured to port 8080 and hosts file (and WordPress-mu install) issue
<p>I am trying to install <a href="http://en.wikipedia.org/wiki/WordPress#Multi-blogging" rel="noreferrer">WordPress MU</a> in my <a href="http://en.wikipedia.org/wiki/XAMPP" rel="noreferrer">XAMPP</a> localhost server (that is configured to port 8080).</p> <p>Using this address in the browser >><a href="http://localhost:8080/wordpress-mu/" rel="noreferrer">http://localhost:8080/wordpress-mu/</a>&lt;&lt; gets this response >>WPMU only works without the port number in the URL.&lt;&lt;</p> <p>This is the last line in my hosts file: 127.0.0.1 localhost.localdomain</p> <p>(This points to my IIS7 localhost server not to my XAMPP local host)</p> <p>I am guessing I need to add another entry in this hosts file to configure this for XAMPP and WordPress MU but am not sure what it should be? </p>
2,378,709
3
1
null
2010-03-04 10:37:43.227 UTC
3
2017-08-06 10:08:23.733 UTC
2010-03-04 13:00:14.123 UTC
null
63,550
null
247,135
null
1
8
xampp
42,232
<p>Are you using IIS at all?</p> <p>If not, just <strong>Stop the Server</strong> and point your XAMPP to port 80.</p> <p>If you are, you can do the <strong>reverse</strong>, just open Default Website properties and in the <em>Website Bindings</em> just change 80 to 8080.</p> <p>In your <strong>XAMPP</strong> instalation change the port to 80:</p> <ul> <li>Open C:\XAMPP\APACHE\httpd.conf</li> <li>Search for Listen (default instalation, on line 47)</li> <li>Change the port</li> <li>Restart Apache</li> </ul>
7,321,398
Terminate process running inside valgrind
<p>Killing the valgrind process itself leaves no report on the inner process' execution.</p> <p>Is it possible to send a terminate signal to a process running inside valgrind?</p>
7,326,526
1
0
null
2011-09-06 14:17:16.36 UTC
6
2017-03-09 16:04:31.993 UTC
null
null
null
null
198,011
null
1
33
valgrind
37,506
<p>There is no "inner process" as both valgrind itself and the client program it is running execute in a single process.</p> <p>Signals sent to that process will be delivered to the client program as normal. If the signal causes the process to terinate then valgrind's normal exit handlers will run and (for example) report any leaks.</p> <p>So, for example, if we start valgrind on a sleep command:</p> <pre><code>bericote [~] % valgrind sleep 240 ==9774== Memcheck, a memory error detector ==9774== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==9774== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info ==9774== Command: sleep 240 ==9774== </code></pre> <p>then kill that command:</p> <pre><code>bericote [~] % kill -TERM 9774 </code></pre> <p>then the process will exit and valgrind's exit handlers will run:</p> <pre><code>==9774== ==9774== HEAP SUMMARY: ==9774== in use at exit: 0 bytes in 0 blocks ==9774== total heap usage: 30 allocs, 30 frees, 3,667 bytes allocated ==9774== ==9774== All heap blocks were freed -- no leaks are possible ==9774== ==9774== For counts of detected and suppressed errors, rerun with: -v ==9774== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6) [1] 9774 terminated valgrind sleep 240 </code></pre> <p>The only exception would be for <code>kill -9</code> as in that case the process is killed by the kernel without ever being informed of the signal so valgrind has no opportunity to do anything.</p>
22,816,335
Java HttpRequest JSON & Response Handling
<p>I have looked at several other questions, but I still don't fully understand this. I want to POST a JSON string to a remote address and then retrieve the values from the JSON response. I am using the Apache libraries for Java.</p> <pre><code>public HttpResponse http(String url, String body) throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(body); request.addHeader("content-type", "application/json"); request.setEntity(params); //httpClient.execute(request); HttpResponse result = httpClient.execute(request); } catch (IOException ex) { } return null; } </code></pre> <p>And as body, I would pass the following (an example):</p> <pre><code>{"example":1,"fr":"lol"} </code></pre> <p>I have absolutely no idea about how to retrieve the JSON values from the response, either.</p>
22,816,851
1
0
null
2014-04-02 15:34:40.27 UTC
8
2019-04-11 20:38:23.707 UTC
2014-11-15 11:40:49.69 UTC
null
3,376,245
null
3,376,245
null
1
18
java|json|http|apache-httpclient-4.x
132,592
<p>The simplest way is using libraries like <a href="http://code.google.com/p/google-http-java-client/">google-http-java-client</a> but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use <a href="http://www.json.org/java/index.html">org.json</a>, <a href="http://code.google.com/p/json-simple/">json-simple</a>, <a href="https://code.google.com/p/google-gson/">Gson</a>, <a href="https://github.com/ralfstx/minimal-json">minimal-json</a>, <a href="http://wiki.fasterxml.com/JacksonDownload">jackson-mapper-asl</a> (from 1.x)... etc</p> <p>A set of simple examples:</p> <p><strong>Using Gson:</strong></p> <pre><code>import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class Gson { public static void main(String[] args) { } public HttpResponse http(String url, String body) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(body); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse result = httpClient.execute(request); String json = EntityUtils.toString(result.getEntity(), "UTF-8"); com.google.gson.Gson gson = new com.google.gson.Gson(); Response respuesta = gson.fromJson(json, Response.class); System.out.println(respuesta.getExample()); System.out.println(respuesta.getFr()); } catch (IOException ex) { } return null; } public class Response{ private String example; private String fr; public String getExample() { return example; } public void setExample(String example) { this.example = example; } public String getFr() { return fr; } public void setFr(String fr) { this.fr = fr; } } } </code></pre> <p><strong>Using json-simple:</strong></p> <pre><code>import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JsonSimple { public static void main(String[] args) { } public HttpResponse http(String url, String body) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(body); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse result = httpClient.execute(request); String json = EntityUtils.toString(result.getEntity(), "UTF-8"); try { JSONParser parser = new JSONParser(); Object resultObject = parser.parse(json); if (resultObject instanceof JSONArray) { JSONArray array=(JSONArray)resultObject; for (Object object : array) { JSONObject obj =(JSONObject)object; System.out.println(obj.get("example")); System.out.println(obj.get("fr")); } }else if (resultObject instanceof JSONObject) { JSONObject obj =(JSONObject)resultObject; System.out.println(obj.get("example")); System.out.println(obj.get("fr")); } } catch (Exception e) { // TODO: handle exception } } catch (IOException ex) { } return null; } } </code></pre> <p>etc...</p>
3,005,540
How to remove subviews in Objective-C?
<p>I have added UIButton and UITextView as subviews to my view programmatically.</p> <pre><code>notesDescriptionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)]; notesDescriptionView.backgroundColor = [UIColor redColor]; [self.view addSubview:notesDescriptionView]; textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,320,420)]; [self.view addSubview:textView]; printf("\n description button \n"); button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchDown]; [button setTitle:@"OK" forState:UIControlStateNormal]; button.frame = CGRectMake(80.0, 420.0, 160.0, 40.0); [self.view addSubview:button]; </code></pre> <p>I need to remove all subviews when the button is clicked.</p> <p>I have tried:</p> <pre><code>[self.view removeFromSuperView] </code></pre> <p>but it's not working.</p>
3,005,589
3
0
null
2010-06-09 11:57:54.56 UTC
8
2018-11-12 04:36:06.467 UTC
2018-11-12 04:33:36.197 UTC
null
1,033,581
null
290,189
null
1
26
objective-c|subview
56,422
<p>I assume you're calling <code>[self.view removeFromSuperView]</code> from a method in the same class as the above snippet.</p> <p>In that case <code>[self.view removeFromSuperView]</code> removes self.view from its own superview, but self is the object from whose view you wish to remove subviews. If you want to remove all the subviews of the object, you need to do this instead:</p> <pre><code>[notesDescriptionView removeFromSuperview]; [button.view removeFromSuperview]; [textView removeFromSuperview]; </code></pre> <p>Perhaps you'd want to store those subviews in an <code>NSArray</code> and loop over that array invoking <code>removeFromSuperview</code> on each element in that array.</p>
2,350,072
Custom data types in numpy arrays
<p>I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it. </p> <pre><code>class Kernel: pass &gt;&gt;&gt; L = np.empty(4,dtype=Kernel) TypeError: data type not understood </code></pre> <p>I can do this:</p> <pre><code>&gt;&gt;&gt; L = np.empty(4,dtype=object) </code></pre> <p>and then assign each element of <code>L</code> as a <code>Kernel</code> object (or any other type of object). It would be so neat were I able to have an array of <code>Kernel</code>s, though, from both a programming point of view (type checking) and a mathematical one (operations on sets of functions). </p> <p>Is there any way for me to specify the data type of a numpy array using an arbitrary class?</p>
2,352,846
3
0
null
2010-02-28 04:21:15.393 UTC
11
2010-02-28 21:57:18.603 UTC
null
null
null
null
270,572
null
1
30
python|numpy
25,656
<p>If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do</p> <pre><code>kerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)]) arr = np.empty(dims, dtype=kerneldt) </code></pre> <p>You'll have to do some coercion to turn them into objects of class Kernel every time you want to manipulate methods of a single kernel but that's one way to store the actual data in a NumPy array. If you want to only store a reference, then the object dtype is the best you can do without subclassing ndarray.</p>
3,076,968
Converting a void* to a std::string
<p>After perusing the web and messing around myself, I can't seem to convert a void*'s target (which is a string) to a std::string. I've tried using <code>sprintf(buffer, "%p", *((int *)point));</code> as recommended by <a href="http://www.daniweb.com/forums/thread221261.html" rel="noreferrer">this page</a> to get to a C string, but to no avail. And sadly, yes, I have to use a void*, as that's what SDL uses in their USEREVENT struct.</p> <p>The code I'm using to fill the Userevent, for those interested, is:</p> <pre><code>std::string filename = "ResumeButton.png"; SDL_Event button_press; button_press.type = BUTTON_PRESS; button_press.user.data1 = &amp;filename; SDL_PushEvent(&amp;button_press); </code></pre> <p>Any ideas?</p> <p>EDIT: Thanks for all the responses, I just needed to cast the void* to a std::string*. Silly me. Thank you guys so much!</p>
3,077,027
4
6
null
2010-06-19 19:41:56.8 UTC
5
2018-02-25 07:11:36.573 UTC
2010-06-19 23:51:15.107 UTC
null
371,207
null
371,207
null
1
31
c++|string|printf|void-pointers
51,111
<p>You just need to dynamically allocate it (because it probably needs to outlive the scope you're using it in), then cast it back and forth:</p> <pre><code>// Cast a dynamically allocated string to 'void*'. void *vp = static_cast&lt;void*&gt;(new std::string("it's easy to break stuff like this!")); // Then, in the function that's using the UserEvent: // Cast it back to a string pointer. std::string *sp = static_cast&lt;std::string*&gt;(vp); // You could use 'sp' directly, or this, which does a copy. std::string s = *sp; // Don't forget to destroy the memory that you've allocated. delete sp; </code></pre>
2,677,564
How to create custom javadoc tags?
<p>How do I create custom javadoc tags such as @pre / @post? I found some links that explain it but I haven't had luck with them. These are some of the links:</p> <p><a href="http://www.developer.com/java/other/article.php/3085991/Javadoc-Programming.html" rel="noreferrer">http://www.developer.com/java/other/article.php/3085991/Javadoc-Programming.html</a></p> <p><a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html</a></p>
7,428,109
4
0
null
2010-04-20 18:15:32.803 UTC
12
2021-03-01 00:30:50.68 UTC
2015-07-06 19:44:38.477 UTC
null
3,964,927
null
287,893
null
1
33
java|javadoc
29,470
<p><strong>java code</strong></p> <pre><code>/** * @custom.mytag hey ho... */ </code></pre> <p><strong>java doc option</strong></p> <pre><code>-tag custom.mytag:a:"This is my Tag:" </code></pre> <p><strong>output</strong></p> <blockquote> <p><strong>This is my Tag:</strong></p> <blockquote> <p>hey ho...</p> </blockquote> </blockquote>
29,129,095
Save additional attributes in Pandas Dataframe
<p>I recall from my MatLab days using structured arrays wherein you could store different data as an attribute of the main structure. Something like:</p> <pre><code>a = {} a.A = magic(10) a.B = magic(50); etc. </code></pre> <p>where <code>a.A</code> and <code>a.B</code> are completely separate from each other allowing you to store different types within <code>a</code> and operate on them as desired. Pandas allows us to do something similar, but not quite the same. </p> <p>I am using Pandas and want to store attributes of a dataframe without actually putting it within a dataframe. This can be done via:</p> <pre><code>import pandas as pd a = pd.DataFrame(data=pd.np.random.randint(0,100,(10,5)),columns=list('ABCED') # now store an attribute of &lt;a&gt; a.local_tz = 'US/Eastern' </code></pre> <p>Now, the local timezone is stored in a, but I cannot save this attribute when I save the dataframe (i.e. after re-loading a there is no <code>a.local_tz</code>). Is there a way to save these attributes? </p> <p>Currently, I am just making new columns in the dataframe to hold information like timezone, latitude, longituded, etc., but this seems to be a bit of a waste. Further, when I do analysis on the data I run into problems of having to exclude these other columns.</p> <p>################## BEGIN EDIT ##################</p> <p>Using unutbu's advice, I now store the data in h5 format. As mentioned, loading metadata back in as attributes of the dataframe is risky. However, since I am the creator of these files (and the processing algorithms) I can choose what is stored as metadata and what is not. When processing the data that will go into the h5 files, I choose to store the metadata in a dictionary that is initialized as an attribute of my classes. I made a simple IO class to import the h5 data, and made the metadata as class attributes. Now I can work on my dataframes without risk of losing the metadata. </p> <pre><code>class IO(): def __init__(self): self.dtfrmt = 'dummy_str' def h5load(self,filename,update=False): '''h5load loads the stored HDF5 file. Both the dataframe (actual data) and the associated metadata are stored in the H5file NOTE: This does not load "any" H5 file, it loads H5 files specifically created to hold dataframe data and metadata. When multi-indexed dataframes are stored in the H5 format the date values (previously initialized with timezone information) lose their timezone localization. Therefore, &lt;h5load&gt; re-localizes the 'DATE' index as UTC. Parameters ---------- filename : string/path path and filename of H5 file to be loaded. H5 file must have been created using &lt;h5store&gt; below. udatedf : boolean True/False default: False If the selected dataframe is to be updated then it is imported slightly different. If update==True, the &lt;metadata&gt; attribute is returned as a dictionary and &lt;data&gt; is returned as a dataframe (i.e., as a stand-alone dictionary with no attributes, and NOT an instance of the IO() class). Otherwise, if False, &lt;metadata&gt; is returned as an attribute of the class instance. Output ------ data : Pandas dataframe with attributes The dataframe contains only the data as collected by the instrument. Any metadata (e.g. timezone, scaling factor, basically anything that is constant throughout the file) is stored as an attribute (e.g. lat is stored as &lt;data.lat&gt;).''' with pd.HDFStore(filename,'r') as store: self.data = store['mydata'] self.metadata = store.get_storer('mydata').attrs.metadata # metadata gets stored as attributes, so no need to make &lt;metadata&gt; an attribute of &lt;self&gt; # put metadata into &lt;data&gt; dataframe as attributes for r in self.metadata: setattr(self,r,self.metadata[r]) # unscale data self.data, self.metadata = unscale(self.data,self.metadata,stringcols=['routine','date']) # when pandas stores multi-index dataframes as H5 files the timezone # initialization is lost. Remake index with timezone initialized: only # for multi-indexed dataframes if isinstance(self.data.index,pd.core.index.MultiIndex): # list index-level names, and identify 'DATE' level namen = self.data.index.names date_lev = namen.index('DATE') # extract index as list and remake tuples with timezone initialized new_index = pd.MultiIndex.tolist(self.data.index) for r in xrange( len(new_index) ): tmp = list( new_index[r] ) tmp[date_lev] = utc.localize( tmp[date_lev] ) new_index[r] = tuple(tmp) # reset multi-index self.data.index = pd.MultiIndex.from_tuples( new_index, names=namen ) if update: return self.metadata, self.data else: return self def h5store(self,data, filename, **kwargs): '''h5store stores the dataframe as an HDF5 file. Both the dataframe (actual data) and the associated metadata are stored in the H5file Parameters ---------- data : Pandas dataframe NOT a class instance Must be a dataframe, not a class instance (i.e. cannot be an instance named &lt;data&gt; that has an attribute named &lt;data&gt; (e.g. the Pandas data frame is stored in data.data)). If the dataframe is under data.data then the input variable must be data.data. filename : string/path path and filename of H5 file to be loaded. H5 file must have been created using &lt;h5store&gt; below. **kwargs : dictionary dictionary containing metadata information. Output ------ None: only saves data to file''' with pd.HDFStore(filename,'w') as store: store.put('mydata',data) store.get_storer('mydata').attrs.metadata = kwargs </code></pre> <p>H5 files are then loaded via <code>data = IO().h5load('filename.h5')</code> the dataframe is stored under data.data I retain the metadata dictionary under data.metadata and have created individual metadata attributes (e.g. <code>data.lat</code> created from <code>data.metadata['lat']</code>).</p> <p>My index time stamps are localized to <code>pytz.utc()</code>. However, when a multi-indexed dataframe is stored to h5 the timezone localization is lost (using Pandas 15.2), so I correct for this in <code>IO().h5load</code>.</p>
29,130,146
3
1
null
2015-03-18 17:43:25.19 UTC
27
2020-08-16 13:16:55.693 UTC
2020-01-23 11:01:26.917 UTC
null
12,086,055
null
1,678,467
null
1
24
python-2.7|pandas
14,346
<p><a href="https://github.com/pydata/pandas/issues/2485">There is an open issue</a> regarding the storage of custom metadata in NDFrames. But due to the multitudinous ways pandas functions may return DataFrames, the <code>_metadata</code> attribute is not (yet) preserved in all situations.</p> <p>For the time being, you'll just have to store the metadata in an auxilliary variable.</p> <p>There are multiple options for storing DataFrames + metadata to files, depending on what format you wish to use -- pickle, JSON, HDF5 are all possibilities. </p> <p>Here is how you could store and load a DataFrame with metadata using HDF5. The recipe for storing the metadata comes from the <a href="http://pandas.pydata.org/pandas-docs/dev/cookbook.html#hdfstore">Pandas Cookbook</a>.</p> <pre><code>import numpy as np import pandas as pd def h5store(filename, df, **kwargs): store = pd.HDFStore(filename) store.put('mydata', df) store.get_storer('mydata').attrs.metadata = kwargs store.close() def h5load(store): data = store['mydata'] metadata = store.get_storer('mydata').attrs.metadata return data, metadata a = pd.DataFrame( data=pd.np.random.randint(0, 100, (10, 5)), columns=list('ABCED')) filename = '/tmp/data.h5' metadata = dict(local_tz='US/Eastern') h5store(filename, a, **metadata) with pd.HDFStore(filename) as store: data, metadata = h5load(store) print(data) # A B C E D # 0 9 20 92 43 25 # 1 2 64 54 0 63 # 2 22 42 3 83 81 # 3 3 71 17 64 53 # 4 52 10 41 22 43 # 5 48 85 96 72 88 # 6 10 47 2 10 78 # 7 30 80 3 59 16 # 8 13 52 98 79 65 # 9 6 93 55 40 3 </code></pre> <hr> <pre><code>print(metadata) </code></pre> <p>yields</p> <pre><code>{'local_tz': 'US/Eastern'} </code></pre>
233,081
What's the 'obj' directory for in .NET?
<p>What exactly is the purpose of the 'obj' directory in .NET?</p>
233,085
2
0
null
2008-10-24 10:57:28.337 UTC
6
2018-02-10 20:53:41.17 UTC
2018-02-10 20:53:41.17 UTC
null
397,817
Andy J
12,767
null
1
68
c#|.net
19,472
<p>The <strong>"obj" folder</strong> is used to store temporary object files and other files used in order to create the final binary during the compilation process.</p> <p>The <strong>"bin" folder</strong> is the output folder for complete binaries (assemblies).</p>
618,900
Enable ASP.NET ASMX web service for HTTP POST / GET requests
<p>I would like to enable a ASP.NET classic (ASMX) web service for HTTP POST and GET requests. I realise this can be done on a machine or application level by adding ...</p> <pre><code>&lt;webServices&gt; &lt;protocols&gt; &lt;add name="HttpGet"/&gt; &lt;add name="HttpPost"/&gt; &lt;/protocols&gt; &lt;/webServices&gt; </code></pre> <p>.. to the machine.config or web.config. My question is can HTTP POST and GET requests be enabled per web service or web method level rather than per application or machine?</p> <p>My web service is written in c# using net 3.5sp1.</p>
618,968
2
0
null
2009-03-06 13:44:06.077 UTC
24
2012-02-24 05:10:19.56 UTC
2011-08-08 20:37:36.07 UTC
null
76,337
null
254
null
1
71
asp.net|web-services|asmx
150,704
<p>Try to declare UseHttpGet over your method.</p> <pre><code>[ScriptMethod(UseHttpGet = true)] public string HelloWorld() { return "Hello World"; } </code></pre>
2,602,981
jQuery HOW TO?? pass additional parameters to success callback for $.ajax call?
<p>I am trying, in vain it seems, to be able to pass additional parameters back to the success callback method that I have created for a successful ajax call. A little background. I have a page with a number of dynamically created textbox / selectbox pairs. Each pair having a dynamically assigned unique name such as name="unique-pair-1_txt-url" and name="unique-pair-1_selectBox" then the second pair has the same but the prefix is different.</p> <p>In an effort to reuse code, I have crafted the callback to take the data and a reference to the selectbox. However when the callback is fired the reference to the selectbox comes back as 'undefined'. I read <a href="https://stackoverflow.com/questions/1997531/javascript-callback-function-and-parameters">here</a> that it should be doable. I have even tried taking advantage of the 'context' option but still nothing. Here is the script block that I am trying to use:</p> <pre class="lang-js prettyprint-override"><code>&lt;script type="text/javascript" language="javascript"&gt; $j = jQuery.noConflict(); function getImages(urlValue, selectBox) { $j.ajax({ type: "GET", url: $j(urlValue).val(), dataType: "jsonp", context: selectBox, success:function(data){ loadImagesInSelect(data) } , error:function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } function loadImagesInSelect(data) { var select = $j(this); select.empty(); $j(data).each(function() { var theValue = $j(this)[0]["@value"]; var theId = $j(this)[0]["@name"]; select.append("&lt;option value='" + theId + "'&gt;" + theValue + "&lt;/option&gt;"); }); select.children(":first").attr("selected", true); } &lt;/script&gt; </code></pre> <p>From what I have read, I feel I am close but I just cant put my finger on the missing link. Please help in your typical ninja stealthy ways. TIA</p> <p>****UPDATE**** Nick is a true Ninja. They should invent a new badge for that! His answer below does the trick. As he mentions it's 1.4 specific but I can live with that. Here is my final code that is working for any Ninjas in training (and my future reference):</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; $j = jQuery.noConflict(); function getImages(urlValue, selectBox) { $j.ajax({ type: "GET", url: urlValue+ '?callback=?', dataType: "jsonp", context: selectBox, success: jQuery.proxy(function (data) { var select = $j(this); select.empty(); $j(data).each(function() { var theValue = $j(this)[0]["@value"]; var theId = $j(this)[0]["@name"]; select.append("&lt;option value='" + theId + "'&gt;" + theValue + "&lt;/option&gt;"); }); select.children(":first").attr("selected", true); }, selectBox), error:function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } &lt;/script&gt; </code></pre>
2,603,861
5
5
null
2010-04-08 19:54:13.847 UTC
9
2016-05-24 06:46:18.51 UTC
2017-05-23 12:34:30.167 UTC
null
-1
null
110,561
null
1
19
jquery|jquery-callback
56,527
<p><strong>Updated:</strong> If you're using jQuery 1.4 use this to simplify things a bit:</p> <pre><code>success: jQuery.proxy(function (data) { var select = $j(this); select.empty(); $j(data).each(function() { var theValue = $j(this)[0]["@value"]; var theId = $j(this)[0]["@name"]; select.append("&lt;option value='" + theId + "'&gt;" + theValue + "&lt;/option&gt;"); }); select.children(":first").attr("selected", true); }, selectBox) </code></pre>
2,526,772
Search for string within text column in MySQL
<p>I have mysql table that has a column that stores xml as a string. I need to find all tuples where the xml column contains a given string of 6 characters. Nothing else matters--all I need to know is if this 6 character string is there or not. </p> <p>So it probably doesn't matter that the text is formatted as xml.</p> <p>Question: how can I search within mysql? ie <code>SELECT * FROM items WHERE items.xml [contains the text '123456']</code></p> <p>Is there a way I can use the LIKE operator to do this?</p>
2,526,806
6
1
null
2010-03-26 21:10:06.32 UTC
13
2019-03-22 23:40:28.307 UTC
2013-12-14 02:13:01.207 UTC
null
210,916
null
94,154
null
1
76
mysql|search|sql-like
273,230
<p>You could probably use the <A href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html" rel="noreferrer"><code>LIKE</code> clause</a> to do some simple string matching:</p> <pre><code>SELECT * FROM items WHERE items.xml LIKE '%123456%' </code></pre> <p>If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: <A href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html" rel="noreferrer"><a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html</a></a></p>
2,805,362
Can Stopwatch be used in production code?
<p>I need an accurate timer, and DateTime.Now seems not accurate enough. From the descriptions I read, System.Diagnostics.Stopwatch seems to be exactly what I want. </p> <p>But I have a phobia. I'm nervous about using anything from System.Diagnostics in actual production code. (I use it extensively for debugging with Asserts and PrintLns etc, but never yet for production stuff.) I'm not merely trying to use a timer to benchmark my functions - my app needs an actual timer. I've read on another forum that System.Diagnostics.StopWatch is only for benchmarking, and shouldn't be used in retail code, though there was no reason given. Is this correct, or am I (and whoever posted that advice) being too closed minded about System.Diagnostics? ie, is it ok to use System.Diagnostics.Stopwatch in production code? Thanks Adrian</p>
2,805,409
7
4
null
2010-05-10 18:30:18.647 UTC
5
2016-04-16 22:22:13.137 UTC
null
null
null
null
337,547
null
1
78
c#|timer|system.diagnostics|stopwatch
18,465
<p>Under the hood, pretty much all Stopwatch does is wrap <a href="http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx" rel="noreferrer">QueryPerformanceCounter</a>. As I understand it, Stopwatch is there to provide access to the high-resolution timer - if you need this resolution in production code I don't see anything wrong with using it.</p>
2,617,752
Newline character in StringBuilder
<p>How do you append a new line(\n\r) character in <code>StringBuilder</code>?</p>
2,617,760
8
3
null
2010-04-11 16:34:16.137 UTC
4
2019-11-03 13:01:29.3 UTC
2019-11-03 12:48:28.27 UTC
null
63,550
null
274,364
null
1
100
c#|stringbuilder
193,241
<p>I would make use of the <a href="http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx" rel="noreferrer">Environment.NewLine property</a>.</p> <p>Something like:</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.AppendFormat("Foo{0}Bar", Environment.NewLine); string s = sb.ToString(); </code></pre> <p>Or</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.Append("Foo"); sb.Append("Foo2"); sb.Append(Environment.NewLine); sb.Append("Bar"); string s = sb.ToString(); </code></pre> <p>If you wish to have a new line after each append, you can have a look at <a href="https://stackoverflow.com/questions/2617752/newline-character-in-stringbuilder/2617767#2617767">Ben Voigt's answer</a>.</p>
2,997,364
Select by Month of a field
<p>How can I get records from my table using month/year? I have a table like this:</p> <pre><code>Name - varchar DueDate -datetime Status -boll </code></pre> <p><code>DueDate</code> is project due date, I want record corresponding to month/year, not full date, I mean record for specific month.</p> <p>How can I do this in mysql?</p>
2,997,388
9
1
null
2010-06-08 12:49:31.05 UTC
8
2020-02-05 08:02:47.873 UTC
2011-07-18 09:36:02.427 UTC
null
180,239
null
217,603
null
1
25
mysql
96,417
<p>Simply use <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_month" rel="noreferrer">MONTH()</a> and <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_year" rel="noreferrer">YEAR()</a>:</p> <pre><code>SELECT * FROM Project WHERE MONTH(DueDate) = 1 AND YEAR(DueDate) = 2010 </code></pre>
2,851,327
Combine a list of data frames into one data frame by row
<p>I have code that at one place ends up with a list of data frames which I really want to convert to a single big data frame. </p> <p>I got some pointers from an <a href="https://stackoverflow.com/questions/1652522/rbind-dataframes-in-a-list-of-lists">earlier question</a> which was trying to do something similar but more complex. </p> <p>Here's an example of what I am starting with (this is grossly simplified for illustration):</p> <pre><code>listOfDataFrames &lt;- vector(mode = "list", length = 100) for (i in 1:100) { listOfDataFrames[[i]] &lt;- data.frame(a=sample(letters, 500, rep=T), b=rnorm(500), c=rnorm(500)) } </code></pre> <p>I am currently using this:</p> <pre><code> df &lt;- do.call("rbind", listOfDataFrames) </code></pre>
49,017,065
9
4
null
2010-05-17 17:38:24.907 UTC
180
2021-11-18 21:53:11.253 UTC
2021-02-24 16:53:48.18 UTC
null
1,851,712
null
37,751
null
1
450
r|list|dataframe|r-faq
299,160
<p>Use <code>bind_rows()</code> from the <strong>dplyr</strong> package:</p> <pre><code>bind_rows(list_of_dataframes, .id = &quot;column_label&quot;) </code></pre>
2,654,010
How can I run a static constructor?
<p>I'd like to execute the static constructor of a class (i.e. I want to "load" the class) without creating an instance. How do I do that?</p> <p>Bonus question: Are there any differences between .NET 4 and older versions?</p> <p>Edit:</p> <ul> <li>The class is not static.</li> <li>I want to run it before creating instances because it takes a while to run, and I'd like to avoid this delay at first access.</li> <li>The static ctor initializes <code>private static readonly</code> fields thus cannot be run in a method instead.</li> </ul>
2,654,684
10
0
null
2010-04-16 15:09:45.587 UTC
14
2020-03-24 08:50:37.853 UTC
2010-04-16 15:29:16.92 UTC
null
39,590
null
39,590
null
1
51
c#|.net|static-constructor
25,531
<p>The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (i.e. reflection), you can use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimehelpers.runclassconstructor" rel="noreferrer"><code>RunClassConstructor</code></a>:</p> <pre><code>Type type = ...; System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle); </code></pre>
2,522,933
How to find whether a string contains any of the special characters?
<p>I want to find whether a string contains any of the special characters like !,@,#,$,%,^,&amp;,*,(,)....etc.</p> <p>How can I do that without looping thorugh all the characters in the string?</p>
2,522,978
11
0
null
2010-03-26 11:41:48.883 UTC
3
2021-06-13 13:27:51.487 UTC
null
null
null
null
119,732
null
1
24
c#
99,626
<pre><code> Regex RgxUrl = new Regex("[^a-z0-9]"); blnContainsSpecialCharacters = RgxUrl.IsMatch(stringToCheck); </code></pre>
2,637,643
How do I list all files in a subdirectory in scala?
<p>Is there a good "scala-esque" (I guess I mean functional) way of recursively listing files in a directory? What about matching a particular pattern?</p> <p>For example recursively all files matching <code>"a*.foo"</code> in <code>c:\temp</code>.</p>
2,638,109
23
1
null
2010-04-14 13:21:06.82 UTC
25
2021-09-16 06:23:41.653 UTC
null
null
null
null
5,346
null
1
100
scala
70,310
<p>Scala code typically uses Java classes for dealing with I/O, including reading directories. So you have to do something like:</p> <pre><code>import java.io.File def recursiveListFiles(f: File): Array[File] = { val these = f.listFiles these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles) } </code></pre> <p>You could collect all the files and then filter using a regex:</p> <pre><code>myBigFileArray.filter(f =&gt; """.*\.html$""".r.findFirstIn(f.getName).isDefined) </code></pre> <p>Or you could incorporate the regex into the recursive search:</p> <pre><code>import scala.util.matching.Regex def recursiveListFiles(f: File, r: Regex): Array[File] = { val these = f.listFiles val good = these.filter(f =&gt; r.findFirstIn(f.getName).isDefined) good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_,r)) } </code></pre>
23,616,226
Insert HTML with React Variable Statements (JSX)
<p>I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:</p> <pre><code>var thisIsMyCopy = '&lt;p&gt;copy copy copy &lt;strong&gt;strong copy&lt;/strong&gt;&lt;/p&gt;'; </code></pre> <p>and to insert it into react like so, and have it work?</p> <pre><code>render: function() { return ( &lt;div className="content"&gt;{thisIsMyCopy}&lt;/div&gt; ); } </code></pre> <p>and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work.</p>
23,663,555
10
0
null
2014-05-12 18:28:55.013 UTC
55
2022-06-18 06:30:29.88 UTC
2022-01-31 09:35:55.957 UTC
null
3,689,450
null
140,448
null
1
292
javascript|html|reactjs
346,270
<p>You can use <a href="https://stackoverflow.com/questions/19266197/reactjs-convert-to-html">dangerouslySetInnerHTML</a>, e.g.</p> <pre><code>render: function() { return ( &lt;div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}&gt;&lt;/div&gt; ); } </code></pre>
10,518,372
How to deserialize xml to object
<pre><code>&lt;StepList&gt; &lt;Step&gt; &lt;Name&gt;Name1&lt;/Name&gt; &lt;Desc&gt;Desc1&lt;/Desc&gt; &lt;/Step&gt; &lt;Step&gt; &lt;Name&gt;Name2&lt;/Name&gt; &lt;Desc&gt;Desc2&lt;/Desc&gt; &lt;/Step&gt; &lt;/StepList&gt; </code></pre> <p>I have this XML, How should i model the Class so i will be able to deserialize it using <code>XmlSerializer</code> object?</p>
10,518,657
2
0
null
2012-05-09 14:41:55.29 UTC
41
2021-02-22 12:35:37.2 UTC
null
null
null
null
829,174
null
1
140
c#|xml-deserialization
281,340
<p>Your classes should look like this</p> <pre><code>[XmlRoot("StepList")] public class StepList { [XmlElement("Step")] public List&lt;Step&gt; Steps { get; set; } } public class Step { [XmlElement("Name")] public string Name { get; set; } [XmlElement("Desc")] public string Desc { get; set; } } </code></pre> <p>Here is my testcode.</p> <pre><code>string testData = @"&lt;StepList&gt; &lt;Step&gt; &lt;Name&gt;Name1&lt;/Name&gt; &lt;Desc&gt;Desc1&lt;/Desc&gt; &lt;/Step&gt; &lt;Step&gt; &lt;Name&gt;Name2&lt;/Name&gt; &lt;Desc&gt;Desc2&lt;/Desc&gt; &lt;/Step&gt; &lt;/StepList&gt;"; XmlSerializer serializer = new XmlSerializer(typeof(StepList)); using (TextReader reader = new StringReader(testData)) { StepList result = (StepList) serializer.Deserialize(reader); } </code></pre> <p>If you want to read a text file you should load the file into a FileStream and deserialize this.</p> <pre><code>using (FileStream fileStream = new FileStream("&lt;PathToYourFile&gt;", FileMode.Open)) { StepList result = (StepList) serializer.Deserialize(fileStream); } </code></pre>
10,516,201
Updating and committing only a file's permissions using git version control
<p>Just turned an <code>some.sh</code> file into an executable (<code>chmod 755 ...</code>), the permissions were updated but not the content. Is there a way to <em>commit</em> the file into git, so that the executable bit will be restored/set on <em>clone</em> / <em>checkout</em> / <em>pull</em> ?</p> <p><strong>Update:</strong> how can I track that the new permissions were submitted to <code>github</code>?</p>
10,516,406
2
0
null
2012-05-09 12:34:03.347 UTC
61
2019-06-12 21:07:59.137 UTC
2018-09-27 02:19:50.733 UTC
null
1,033,581
null
366,472
null
1
253
git
235,200
<p>By default, git will update execute file permissions if you change them. It will not change or track any other permissions.</p> <p>If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.</p> <p>Look into your project, in the <code>.git</code> folder for the <code>config</code> file and you should see something like this:</p> <pre><code>[core] filemode = false </code></pre> <p>You can either change it to <code>true</code> in your favorite text editor, or run:</p> <pre><code>git config core.filemode true </code></pre> <p>Then, you should be able to commit normally your files. It will only commit the permission changes.</p>
19,503,647
Getting Value of Either
<p>Besides using <code>match</code>, is there an Option-like way to <code>getOrElse</code> the actual content of the <code>Right</code> or <code>Left</code> value?</p> <pre><code>scala&gt; val x: Either[String,Int] = Right(5) scala&gt; val a: String = x match { case Right(x) =&gt; x.toString case Left(x) =&gt; "left" } a: String = 5 </code></pre>
19,503,745
4
0
null
2013-10-21 20:03:36.223 UTC
3
2021-11-05 10:24:26.16 UTC
null
null
null
null
409,976
null
1
32
scala|either
33,951
<p>I don't particularly like <code>Either</code> and as a result I'm not terribly familiar with it, but I believe you're looking for projections: <code>either.left.getOrElse</code> or <code>either.right.getOrElse</code>.</p> <p>Note that projections can be used in for-comprehensions as well. This is an example straight from the documentation:</p> <pre><code>def interactWithDB(x: Query): Either[Exception, Result] = try { Right(getResultFromDatabase(x)) } catch { case ex =&gt; Left(ex) } // this will only be executed if interactWithDB returns a Right val report = for (r &lt;- interactWithDB(someQuery).right) yield generateReport(r) if (report.isRight) send(report) else log("report not generated, reason was " + report.left.get) </code></pre>
32,172,704
Is GZIP Automatically Decompressed by Browser?
<p>I have enabled gzip compression in IIS 8.0 by following the url <a href="http://ericsowell.com/blog/2013/6/7/enabling-gzip-in-iis-on-windows-8" rel="noreferrer">Enabling Gzip in IIS on Windows 8</a> I am calling external rest services from my application via jquery ajax call and C# code, currently my external web service is not gzip compressed. If i ask my service partner to gzip their response, do i need to write any decompression logic in my code on jquery side and c# side or browser automatically decompress the response for me ?</p>
32,172,835
2
0
null
2015-08-23 23:49:42.307 UTC
5
2019-07-31 19:48:12.823 UTC
2018-01-19 06:11:19.17 UTC
null
1,819,000
null
5,075,511
null
1
34
javascript|c#|jquery|iis|gzip
21,461
<p>All modern browsers can handle a gzip encoded response. In fact, if you look at their requests, they'll have a header that says something along the lines of <code>Accept-Encoding: gzip</code> which is their way of saying to the server that they can handle gzipped responses.</p> <p>The important part is that your server can return both gzip and uncompressed responses depending on the existence and value of that header. If a client doesn't send the <code>Accept-Encoding</code> header, you shouldn't compress it. If the client does send it, you can optionally encode the response using gzip. Not all content needs to be compressed as it may already be compressed and you're wasting CPU cycles. JPEG images are usually a good example of this. Most likely, IIS is making an intelligent decision here as well and only compressing what is necessary, when necessary.</p> <p>You can verify IIS is doing what it should be by looking at the response headers coming back from your server and looking for the <code>Content-Encoding: gzip</code> header. That tells the client, or browser, that the content is encoded using gzip compression and it should decompress it appropriately.</p> <p>All browser based requests (e.g., XHR/AJAX/jQuery, regular requests) will automatically be decompressed without additional effort from you. The browser is the client responsible for determining if it can handle gzip and will add the <code>Accept-Encoding</code> header if it does. Your JavaScript code will receive the uncompressed version of it in your response handler.</p> <p><strong>TL;DR</strong>: Turning it on is usually a good idea and you shouldn't need to do additional work.</p>
47,235,921
Ionic3/Angular Error: Must supply a value for form control with name: 'jobStatus'
<p>I have a Modal Form with the following code in the template markup</p> <pre><code> &lt;form [formGroup]="modalFG"&gt; ... &lt;ion-item *ngIf="isChangeStatus()"&gt; &lt;ion-select formControlName="jobStatus" (ionChange)="jobStatusChangeHandler($event)"&gt; &lt;ion-option value=4&gt;Success&lt;/ion-option&gt; &lt;ion-option value=5&gt;Failure&lt;/ion-option&gt; &lt;ion-option value=6&gt;Terminated&lt;/ion-option&gt; &lt;ion-option value=8&gt;Inactive&lt;/ion-option&gt; &lt;/ion-select&gt; &lt;/ion-item&gt; &lt;/form&gt; </code></pre> <p>In the Typescript I've specified a value, but I can't get past this error.</p> <p><strong>Error: Must supply a value for form control with name: 'jobStatus'.</strong></p> <p><em>Can someone tell me what I'm doing wrong?</em></p> <pre><code>... private modalFG:FormGroup; private jobStatus:number; constructor( private navParams:NavParams, private view:ViewController, private fb: FormBuilder, ... ) { this.changeStatus = false; this.modalFG = fb.group({ comment: ['', Validators.required], jobStatus: this.jobStatus }); } private ionViewWillLoad():void { const data = this.navParams.get('data'); this.modalFG.setValue({'jobStatus': this.jobStatus}); } private jobStatusChangeHandler(ev:any) { console.log(ev); } private isChangeStatus():boolean { return this.changeStatus; } </code></pre> <p>I also have button handler for submit with this:</p> <pre><code>this.exitData.jobStatus = this.modalFG.get('jobStatus').value; this.view.dismiss(this.exitData); </code></pre> <p>This is the full error message:</p> <pre><code>Error: Must supply a value for form control with name: 'jobStatus'. at http://localhost:8100/build/vendor.js:22102:23 at http://localhost:8100/build/vendor.js:22026:66 at Array.forEach (&lt;anonymous&gt;) at FormGroup._forEachChild (http://localhost:8100/build/vendor.js:22026:36) at FormGroup._checkAllValuesPresent (http://localhost:8100/build/vendor.js:22100:14) at FormGroup.setValue (http://localhost:8100/build/vendor.js:21907:14) at ModalPage.webpackJsonp.124.ModalPage.ionViewWillLoad (http://localhost:8100/build/main.js:648:22) at ModalImpl.ViewController._lifecycle (http://localhost:8100/build/vendor.js:17471:33) at ModalImpl.ViewController._willLoad (http://localhost:8100/build/vendor.js:17331:14) at OverlayPortal.NavControllerBase._willLoad (http://localhost:8100/build/vendor.js:44112:18) </code></pre> <p>Since it says ionViewWillLoad in the call stack, the error must be something in that section AFAIK!</p>
47,236,709
6
0
null
2017-11-11 08:25:42.783 UTC
3
2021-09-10 15:28:00.003 UTC
2017-11-11 09:57:17.603 UTC
null
495,157
null
495,157
null
1
17
angular|typescript|ionic3|angular-reactive-forms|ion-select
42,120
<p>Right... I had a form that used to only have a single form control, called 'comment'.</p> <p>When I added a second, conditional form element, the syntax you need to use changes for setValue...</p> <p>I needed to modify it from something like this:</p> <pre><code> this.modalFG.setValue({'comment': data.comment}); this.modalFG.setValue({'jobStatus': 0}); </code></pre> <p>to:</p> <pre><code> this.modalFG.controls['jobStatus'].setValue(0); this.modalFG.controls['comment'].setValue(data.comment); </code></pre> <p>because I now had two fields on the form...</p> <p>Then everything fell into place and the misleading message about not having supplied form field disappeared. </p> <p>I hate the syntax of Angular here, changing it's functioning behaviour when you go from 1 to n values!</p>
47,200,440
Kotlin - how to find number of repeated values in a list?
<p>I have a list, e.g like:</p> <pre><code>val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana") </code></pre> <p>How can i check how many times apple is duplicated in this list?</p>
47,200,528
2
0
null
2017-11-09 11:15:48.753 UTC
8
2017-11-09 11:35:03.163 UTC
null
null
null
null
5,434,346
null
1
56
functional-programming|kotlin
38,388
<pre><code>list.count { it == "apple" } </code></pre> <p>Documentation: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/" rel="noreferrer">https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/</a>, <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html" rel="noreferrer">https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html</a></p>
31,461,267
Using a different manifestPlaceholder for each Build Variant
<p>I will start by saying that I am very new to Gradle, so I apologize if this has already been answered.</p> <p>I'm working on an Android application that uses an API key to access a 3rd party tool. A different API key needs to be used depending on both the <strong>flavor</strong> and <strong>build type</strong> of the app.</p> <p>Here is a basic outline of what I'm trying to do:</p> <pre><code>android { defaultConfig { manifestPlaceholders = [ apiKey:"DEBUG_KEY" ] } buildTypes{ debug{ // Some debug setup } release{ // Some release setup } } productFlavors { // List of flavor options } productFlavors.all{ flavor-&gt; if (flavor.name.equals("someFlavor")) { if (buildType.equals("release")) { manifestPlaceholders = [ apiKey:"RELEASE_KEY_1" ] } else { manifestPlaceholders = [ apiKey:"DEBUG_KEY" ] } } else { if (buildType.equals("release")) { manifestPlaceholders = [ apiKey:"RELEASE_KEY_2" ] } else { manifestPlaceholders = [ apiKey:"DEBUG_KEY" ] } } } } </code></pre> <p>So far the <code>manifestPlaceholders</code> statement is working in a very simple case, but I don't know how to reference the <strong>buildType</strong> from within the <strong>productFlavors</strong> block so that I can use it as a conditional.</p>
32,503,193
8
0
null
2015-07-16 17:54:51.173 UTC
8
2021-12-21 15:37:47.373 UTC
2015-07-16 18:05:25.747 UTC
null
2,058,757
null
1,088,502
null
1
31
android|gradle|android-gradle-plugin
18,967
<p>I would guess that you are referring to Fabric ApiKey? :) I just spent hours trying to do it in a similar way with the placeholders and specifying the ApiKey in the gradle file although it does not seem possible as of <code>com.android.tools.build:gradle:1.3.1</code>. It is possible to specify a placeholder for a specific flavor but not for a flavor AND buildType. </p> <p>Just to correct your syntax, the way you would have to do it (<em>if it was possible</em>) would be something like that but manifestPlaceholders are unknown to variants.</p> <pre><code>applicationVariants.all{ variant-&gt; if (variant.productFlavors.get(0).name.equals("someFlavor")) { if (variant.buildType.name.equals("release")) { manifestPlaceholders = [ apiKey:"RELEASE_KEY_1" ] } else { manifestPlaceholders = [ apiKey:"DEBUG_KEY" ] } } else { if (variant.buildType.name.equals("release")) { manifestPlaceholders = [ apiKey:"RELEASE_KEY_2" ] } else { manifestPlaceholders = [ apiKey:"DEBUG_KEY" ] } } } </code></pre> <p>What you actually need to do is to keep the key in the <code>AndroidManifest.xml</code> and handle it with multiple manifest file</p> <p><strong>src/AndroidManifest.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"&gt; &lt;application&gt; &lt;meta-data android:name="io.fabric.ApiKey" android:value="DEBUG_KEY" tools:replace="android:value"/&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p><strong>src/someFlavorRelease/AndroidManifest.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"&gt; &lt;application&gt; &lt;meta-data android:name="io.fabric.ApiKey" android:value="RELEASE_KEY_1" tools:replace="android:value"/&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p><strong>src/someOtherFlavorRelease/AndroidManifest.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"&gt; &lt;application&gt; &lt;meta-data android:name="io.fabric.ApiKey" android:value="RELEASE_KEY_2" tools:replace="android:value"/&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>The manifestMerger will handle the replacement and you will end up with the proper key in every scenario. I just implemented it successfully. I just hope you were really referring to the Fabric key! :)</p> <p>Hope this helps!</p>
38,517,593
Relative imports in Go
<p>I have a go Project with the following directory structure</p> <pre><code>utils(pkg) | auth.go (has a function names test1) controllers(pkg) | login.go (has a function names test2) </code></pre> <p>I am trying to access function test1 from login.go. Here is what I have done</p> <pre><code>import "../utils" func test2(c *gin.Context) bool{ utils.test1() } </code></pre> <p>But I always get <code>Unresolved reference test1</code>. I am new to go . Can anyone help why I am getting this error?</p>
38,518,202
6
0
null
2016-07-22 03:16:51.827 UTC
11
2022-07-14 20:09:43.187 UTC
2018-07-08 09:02:47.3 UTC
null
13,860
null
5,996,587
null
1
56
go
76,941
<p>No there is no relative import in Go.<br /> you should use the absolute path considering GOPATH:</p> <p>The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you'll need to set when developing Go code. To get started, create a workspace directory and set GOPATH accordingly. see: <a href="https://golang.org/doc/code.html#GOPATH" rel="noreferrer">https://golang.org/doc/code.html#GOPATH</a></p> <blockquote> <h3>Import paths</h3> <p><strong>An import path is a string that uniquely identifies a package</strong>. A package's import path corresponds to its location inside a workspace or in a remote repository (explained below).</p> <p>The packages from the standard library are given short import paths such as &quot;fmt&quot; and &quot;net/http&quot;. For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries.</p> <p><strong>If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have a GitHub account at github.com/user, that should be your base path</strong>.</p> <p>Note that you don't need to publish your code to a remote repository before you can build it. It's just a good habit to organize your code as if you will publish it someday. In practice you can choose any arbitrary path name, as long as it is unique to the standard library and greater Go ecosystem.</p> </blockquote> <p><strong>Example:</strong></p> <p>This example assumes you have set <code>GOPATH=/goworkdir</code> in your OS environment.</p> <p>File: <code>goworkdir/src/project1/utils/auth.go</code></p> <pre><code>package utils func Test1() string { return &quot;Test1&quot; } </code></pre> <p>File: <code>goworkdir/src/project1/controllers/login.go</code></p> <pre><code>package controllers import &quot;project1/utils&quot; func Test2() string { return utils.Test1() } </code></pre> <p>File: <code>goworkdir/src/project1/main.go</code></p> <pre><code>package main import ( &quot;fmt&quot; &quot;project1/controllers&quot; ) func main() { fmt.Println(controllers.Test2()) } </code></pre> <p>Now if you <code>go run main.go</code> you should see output:</p> <pre><code>Test1 </code></pre>
38,949,034
Nested Recyclerview scrolls by itself
<p>I have a parent recyclerview that has 3 child view in it. The last two of the child are recyclerview.</p> <pre><code>Parent recyclerview - child view 1 - child view 2 (horizontal rv) - child view 3 (horizontal rv) </code></pre> <p>The issue is every time this fragment is visible, it scrolls itself to align with <code>child view 2</code>'s bottom.</p> <p>I have set the parent rv to listen for scroll. This is what I end up with:</p> <pre><code>dy: 108 dy: 72 dy: 75 dy: 62 dy: 48 dy: 42 dy: 34 dy: 27 dy: 22 dy: 16 dy: 12 dy: 10 dy: 7 dy: 5 dy: 3 dy: 3 dy: 1 dy: 1 dy: 1 </code></pre> <p>It seems like the starting <code>dy</code> of parent recyclerview is set to <code>0</code> to the <code>child view 2</code> rv. Everything above it is in -ve value. However, I'm not sure if this was the case as I'm still finding out what causes it.</p> <p>Any fix?</p>
40,492,486
7
0
null
2016-08-15 03:43:49.107 UTC
12
2020-12-04 13:53:57.47 UTC
null
null
null
null
996,701
null
1
36
android|android-recyclerview
18,606
<p>We have a similar problem. We have a vertical <code>RecyclerView</code>. Each item of this vertical <code>RecyclerView</code> contains an horizontal <code>RecyclerView</code>, like in the Android TV app.</p> <p>When we upgraded the support libs from 23.4.0 to 24.0.0 the automatic scroll suddenly appeared. In particular, when we open an <code>Activity</code> and we then go back, the vertical <code>RecyclerView</code> scrolls up so that the current horizontal <code>RecyclerView</code> row does not get cut and the row is displayed completely.</p> <p>There is an easy fix. Add this to your <strong>outer/parent</strong> <code>RecyclerView</code>:</p> <pre><code>android:descendantFocusability="blocksDescendants" </code></pre> <p>I've found the solution in this questions:</p> <ul> <li><a href="https://stackoverflow.com/q/37968010/4034572">nested scrollview + recyclerview, strange autoscroll behaviour</a></li> <li><a href="https://stackoverflow.com/q/37782485/4034572">Android prevent nested recyclerview from automatically repositioning</a></li> </ul> <p>Additionally, I've found <a href="https://code.google.com/p/android/issues/detail?id=222911" rel="noreferrer">another solution</a>, which also works. In our case the vertical <code>RecyclerView</code> is contained inside a <code>FrameLayout</code>. If I add <code>android:focusableInTouchMode="true"</code> to this <code>FrameLayout</code>, the problem goes away.</p> <p>By the way, there is also an <a href="https://code.google.com/p/android/issues/detail?id=222911" rel="noreferrer">open issue on the AOSP</a>.</p>
38,622,470
Using JSON.stringify in an expression in Angular2 template
<p>I have a small expression to check whether 2 objects are different or not, in order to display this element (via adding class name):</p> <pre><code>&lt;div ngClass='{{JSON.stringify(obj1) != JSON.stringify(obj2) ? "div-show" : ""}}'&gt;&lt;/div&gt; </code></pre> <p>The problem is I get this error: <code>Cannot read property 'stringify' of undefined</code>.</p> <p>What I need a way to work around, or a proper solution if available. Thanks.</p> <p>PS: I use JSON.stringify() to compare 2 simple objects, nothing fancy here.</p>
50,857,666
3
0
null
2016-07-27 20:18:58.207 UTC
7
2018-06-14 12:33:37.777 UTC
null
null
null
null
5,343,511
null
1
40
html|angular
35,304
<p>2 Years later but, you can do it the <a href="https://angular.io/api/common/JsonPipe" rel="noreferrer">Angular Way</a> using the built in pipe 'JsonPipe' from @angular/common</p> <pre><code>@Component({ selector: 'json-pipe', template: `&lt;div&gt; &lt;p&gt;Without JSON pipe:&lt;/p&gt; &lt;pre&gt;{{object}}&lt;/pre&gt; &lt;p&gt;With JSON pipe:&lt;/p&gt; &lt;pre&gt;{{object | json}}&lt;/pre&gt; &lt;/div&gt;` }) export class JsonPipeComponent { object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}}; } </code></pre>
38,609,262
Change text color of alert dialog
<p>I have a popup for downloading the audio instruction in my app. What I am trying to do is to change the default text color of &quot;OK&quot; to blue. I tried something but it's not working. Here is my code:</p> <pre><code> private void showDownloadPgmPopup() { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity()); builder.setTitle(&quot;Download instructional audio?&quot;); builder.setMessage(ParamConstants.AUDIODOWNLOADPERMISSION); builder.setNegativeButton(&quot;No&quot;, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { WwDatabaseHelper.storeSelectedWeekAndDay(getActivity(), mSelectedWeekDataModel); goToMoveScreen(); } }); builder.setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AndroidDownloadFileByProgressBarActivity.StartAudioAssetDownload(getActivity()); } }).create(); // change the text color of download instruction ok button final android.app.AlertDialog dialog = builder.show(); dialog.setOnShowListener( new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface arg0) { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor(&quot;#ff5722&quot;)); } }); dialog.setCanceledOnTouchOutside(false); dialog.show(); } </code></pre> <p>But the change is not taking effect, can anyone tell me what I am doing wrong?</p>
38,609,618
9
1
null
2016-07-27 09:40:23.233 UTC
3
2022-02-22 22:07:37.377 UTC
2022-02-22 22:07:37.377 UTC
null
8,623,521
null
5,845,117
null
1
52
android|android-alertdialog
59,441
<p>You have to provide a custom style id in the AlertDialog constructor:</p> <pre><code>AlertDialog.Builder(Context context, int themeResId) </code></pre> <p>and the style file should be something like:</p> <pre><code>&lt;style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert"&gt; &lt;item name="android:colorAccent"&gt;#0000FF&lt;/item&gt; &lt;/style&gt; </code></pre>
63,459,424
How to add multiple graphs to Dash app on a single browser page?
<p><img src="https://i.stack.imgur.com/7OQsr.png" alt="enter image description here" /></p> <p>How do I add multiple graphs show in in picture on a same page? I am trying to add html.Div components to following code to update the page layout to add more graphs like that on single page, but these newly added graphs do not get shown on a page, only old graph is shown in picture is visible. What element should I modify, to let's say to add graph shown in uploaded image 3 times on single page of dash app on browser?</p> <pre><code> import dash import dash_core_components as dcc import dash_html_components as html i[enter image description here][1]mport plotly.express as px import pandas as pd external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a &quot;long-form&quot; data frame # see https://plotly.com/python/px-arguments/ for more options df = pd.DataFrame({ &quot;Fruit&quot;: [&quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;, &quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;], &quot;Amount&quot;: [4, 1, 2, 2, 4, 5], &quot;City&quot;: [&quot;SF&quot;, &quot;SF&quot;, &quot;SF&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;] }) fig = px.bar(df, x=&quot;Fruit&quot;, y=&quot;Amount&quot;, color=&quot;City&quot;, barmode=&quot;group&quot;) app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ == '__main__': app.run_server(debug=True) </code></pre>
63,464,209
1
0
null
2020-08-17 22:25:29.95 UTC
10
2021-09-17 09:19:06.523 UTC
2021-09-17 09:19:06.523 UTC
null
12,892,553
null
12,860,141
null
1
16
python|html|plotly|plotly-dash
27,030
<p>To add the same figure multiple times, you just need to extend your <code>app.layout</code>. I have extended you code below as an example.</p> <pre><code>import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.express as px external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a &quot;long-form&quot; data frame # see https://plotly.com/python/px-arguments/ for more options df_bar = pd.DataFrame({ &quot;Fruit&quot;: [&quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;, &quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;], &quot;Amount&quot;: [4, 1, 2, 2, 4, 5], &quot;City&quot;: [&quot;SF&quot;, &quot;SF&quot;, &quot;SF&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;] }) fig = px.bar(df_bar, x=&quot;Fruit&quot;, y=&quot;Amount&quot;, color=&quot;City&quot;, barmode=&quot;group&quot;) app.layout = html.Div(children=[ # All elements from the top of the page html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='graph1', figure=fig ), ]), # New Div for all elements in the new 'row' of the page html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='graph2', figure=fig ), ]), ]) if __name__ == '__main__': app.run_server(debug=True) </code></pre> <p><a href="https://i.stack.imgur.com/7i4HK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7i4HK.png" alt="enter image description here" /></a></p> <p>The way I have structured the layout is by nesting the <code>html.Div</code> components. For every figure and corresponding titles, text, etc. we make another <code>html.Div</code> that makes a new 'row' in our application.</p> <p>The one thing to keep in mind is that different components need <strong>unique ids</strong>. In this example we have the same graph displayed twice, but they are not the exact same object. We are making two <code>dcc.Graph</code> objects using the same plotly.express figure</p> <p>I have made another example for you where I have a added another figure that is <em>dynamic</em>. The second figure is updated every time a new colorscale is selected from the dropdown menu. This is were the real potential of Dash lies. You can read more about callback functions in this <a href="https://dash.plotly.com/basic-callbacks" rel="noreferrer">tutorial</a></p> <pre class="lang-py prettyprint-override"><code>import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.express as px external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a &quot;long-form&quot; data frame # see https://plotly.com/python/px-arguments/ for more options df_bar = pd.DataFrame({ &quot;Fruit&quot;: [&quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;, &quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;], &quot;Amount&quot;: [4, 1, 2, 2, 4, 5], &quot;City&quot;: [&quot;SF&quot;, &quot;SF&quot;, &quot;SF&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;] }) fig = px.bar(df_bar, x=&quot;Fruit&quot;, y=&quot;Amount&quot;, color=&quot;City&quot;, barmode=&quot;group&quot;) # Data for the tip-graph df_tip = px.data.tips() app.layout = html.Div(children=[ # All elements from the top of the page html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure=fig ), ]), # New Div for all elements in the new 'row' of the page html.Div([ dcc.Graph(id='tip-graph'), html.Label([ &quot;colorscale&quot;, dcc.Dropdown( id='colorscale-dropdown', clearable=False, value='bluyl', options=[ {'label': c, 'value': c} for c in px.colors.named_colorscales() ]) ]), ]) ]) # Callback function that automatically updates the tip-graph based on chosen colorscale @app.callback( Output('tip-graph', 'figure'), [Input(&quot;colorscale-dropdown&quot;, &quot;value&quot;)] ) def update_tip_figure(colorscale): return px.scatter( df_color, x=&quot;total_bill&quot;, y=&quot;tip&quot;, color=&quot;size&quot;, color_continuous_scale=colorscale, render_mode=&quot;webgl&quot;, title=&quot;Tips&quot; ) if __name__ == '__main__': app.run_server(debug=True) </code></pre> <p><a href="https://i.stack.imgur.com/BzKJa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BzKJa.png" alt="enter image description here" /></a></p> <p>Your next question may be, how do i place multiple figures side by side? This is where CSS and stylesheets are important.</p> <p>You have already added an external stylesheet <code>https://codepen.io/chriddyp/pen/bWLwgP.css</code>, which enables us to better structure our layout using the <code>className</code> component of divs.</p> <p>The width of a web page is set to 12 columns no matter the screen size. So if we want to have two figures side by side, each occupying 50% of the screen they need to fill 6 columns each.</p> <p>We can achieve this by nesting another <code>html.Div</code> as our top half row. In this upper div we can have another two divs in which we specify the style according to classname <code>six columns</code>. This splits the first row in two halves</p> <pre><code>import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.express as px from jupyter_dash import JupyterDash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a &quot;long-form&quot; data frame # see https://plotly.com/python/px-arguments/ for more options df_bar = pd.DataFrame({ &quot;Fruit&quot;: [&quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;, &quot;Apples&quot;, &quot;Oranges&quot;, &quot;Bananas&quot;], &quot;Amount&quot;: [4, 1, 2, 2, 4, 5], &quot;City&quot;: [&quot;SF&quot;, &quot;SF&quot;, &quot;SF&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;, &quot;Montreal&quot;] }) fig = px.bar(df_bar, x=&quot;Fruit&quot;, y=&quot;Amount&quot;, color=&quot;City&quot;, barmode=&quot;group&quot;) app.layout = html.Div(children=[ # All elements from the top of the page html.Div([ html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='graph1', figure=fig ), ], className='six columns'), html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='graph2', figure=fig ), ], className='six columns'), ], className='row'), # New Div for all elements in the new 'row' of the page html.Div([ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='graph3', figure=fig ), ], className='row'), ]) if __name__ == '__main__': app.run_server(debug=True) </code></pre> <p><a href="https://i.stack.imgur.com/Cq6EA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cq6EA.png" alt="enter image description here" /></a></p>
33,785,755
Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip
<p>I'm getting an error <code>Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?</code> when trying to install lxml through pip.</p> <pre><code> c:\users\f\appdata\local\temp\xmlXPathInitqjzysz.c(1) : fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* error: command 'C:\\Users\\f\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2 </code></pre> <p>I don't find any libxml2 dev packages to install via pip.</p> <p>Using Python 2.7 and Python 3.x on x86 in a virtualenv under Windows 10.</p>
33,785,756
11
0
null
2015-11-18 16:49:22.18 UTC
32
2022-06-08 17:45:01.427 UTC
2020-07-17 08:47:38.473 UTC
null
2,573,375
null
2,573,375
null
1
119
python
124,269
<p>Install lxml from <a href="http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#lxml" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml</a> for your python version. It's a precompiled WHL with required modules/dependencies.</p> <p>The site lists several packages, when e.g. using Win32 Python 3.9, use <code>lxml‑4.5.2‑cp39‑cp39‑win32.whl</code>.</p> <p>Download the file, and then install with:</p> <pre><code>pip install C:\path\to\downloaded\file\lxml‑4.5.2‑cp39‑cp39‑win32.whl </code></pre>
27,884,508
How to select elements from array in Julia matching predicate?
<p>Julia appears to have a lot of Matlab like features. I'd like to select from an array using a predicate. In Matlab I can do this like:</p> <pre><code>&gt;&gt; a = 2:7 ; &gt;&gt; a &gt; 4 ans = 0 0 0 1 1 1 &gt;&gt; a(a&gt;4) ans = 5 6 7 </code></pre> <p>I found a kind of clunky seeming way to do part of this in Julia:</p> <pre><code>julia&gt; a = 2:7 2:7 julia&gt; [int(x &gt; 3) for x in a] 6-element Array{Any,1}: 0 0 1 1 1 1 </code></pre> <p>(Using what wikipedia calls <a href="https://en.wikipedia.org/wiki/List_comprehension#Julia" rel="noreferrer">list comprehension</a>). I haven't figured out how to apply a set like this to select with in Julia, but may be barking up the wrong tree. How would one do a predicate selection from an array in Julia?</p>
27,884,583
5
0
null
2015-01-11 06:10:43.917 UTC
4
2021-02-02 22:56:51.55 UTC
null
null
null
null
189,270
null
1
31
arrays|julia
30,472
<p>You can use a very Matlab-like syntax if you use a dot <code>.</code> for <a href="http://julia.readthedocs.org/en/latest/manual/arrays/#vectorized-operators-and-functions">elementwise</a> comparison:</p> <pre><code>julia&gt; a = 2:7 2:7 julia&gt; a .&gt; 4 6-element BitArray{1}: false false false true true true julia&gt; a[a .&gt; 4] 3-element Array{Int32,1}: 5 6 7 </code></pre> <p>Alternatively, you can call <code>filter</code> if you want a more functional predicate approach:</p> <pre><code>julia&gt; filter(x -&gt; x &gt; 4, a) 3-element Array{Int32,1}: 5 6 7 </code></pre>
27,535,289
What is the correct way to return an Iterator (or any other trait)?
<p>The following Rust code compiles and runs without any issues.</p> <pre><code>fn main() { let text = "abc"; println!("{}", text.split(' ').take(2).count()); } </code></pre> <p>After that, I tried something like this .... but it didn't compile</p> <pre><code>fn main() { let text = "word1 word2 word3"; println!("{}", to_words(text).take(2).count()); } fn to_words(text: &amp;str) -&gt; &amp;Iterator&lt;Item = &amp;str&gt; { &amp;(text.split(' ')) } </code></pre> <p>The main problem is that I'm not sure what return type the function <code>to_words()</code> should have. The compiler says:</p> <pre class="lang-none prettyprint-override"><code>error[E0599]: no method named `count` found for type `std::iter::Take&lt;std::iter::Iterator&lt;Item=&amp;str&gt;&gt;` in the current scope --&gt; src/main.rs:3:43 | 3 | println!("{}", to_words(text).take(2).count()); | ^^^^^ | = note: the method `count` exists but the following trait bounds were not satisfied: `std::iter::Iterator&lt;Item=&amp;str&gt; : std::marker::Sized` `std::iter::Take&lt;std::iter::Iterator&lt;Item=&amp;str&gt;&gt; : std::iter::Iterator` </code></pre> <p>What would be the correct code to make this run? .... and where is my knowledge gap?</p>
27,535,594
2
0
null
2014-12-17 21:39:10.733 UTC
53
2021-09-12 12:53:30.053 UTC
2017-10-29 17:14:55.693 UTC
null
155,423
null
541,794
null
1
183
rust
52,593
<p>I've found it useful to let the compiler guide me:</p> <pre><code>fn to_words(text: &amp;str) { // Note no return type text.split(' ') } </code></pre> <p>Compiling gives:</p> <pre class="lang-none prettyprint-override"><code>error[E0308]: mismatched types --&gt; src/lib.rs:5:5 | 5 | text.split(' ') | ^^^^^^^^^^^^^^^ expected (), found struct `std::str::Split` | = note: expected type `()` found type `std::str::Split&lt;'_, char&gt;` help: try adding a semicolon | 5 | text.split(' '); | ^ help: try adding a return type | 3 | fn to_words(text: &amp;str) -&gt; std::str::Split&lt;'_, char&gt; { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ </code></pre> <p>Following the compiler's suggestion and copy-pasting that as my return type (with a little cleanup):</p> <pre><code>use std::str; fn to_words(text: &amp;str) -&gt; str::Split&lt;'_, char&gt; { text.split(' ') } </code></pre> <p>The problem is that you cannot return a trait like <code>Iterator</code> because a trait doesn't have a size. That means that Rust doesn't know how much space to allocate for the type. You <a href="https://stackoverflow.com/questions/32682876/is-there-any-way-to-return-a-reference-to-a-variable-created-in-a-function">cannot return a reference to a local variable, either</a>, so returning <code>&amp;dyn Iterator</code> is a non-starter. </p> <h3>Impl trait</h3> <p>As of Rust 1.26, you can use <a href="https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md" rel="noreferrer"><code>impl trait</code></a>:</p> <pre><code>fn to_words&lt;'a&gt;(text: &amp;'a str) -&gt; impl Iterator&lt;Item = &amp;'a str&gt; { text.split(' ') } fn main() { let text = "word1 word2 word3"; println!("{}", to_words(text).take(2).count()); } </code></pre> <p>There are restrictions on how this can be used. You can only return a single type (no conditionals!) and it must be used on a free function or an inherent implementation.</p> <h3>Boxed</h3> <p>If you don't mind losing a little bit of efficiency, you can return a <code>Box&lt;dyn Iterator&gt;</code>:</p> <pre><code>fn to_words&lt;'a&gt;(text: &amp;'a str) -&gt; Box&lt;dyn Iterator&lt;Item = &amp;'a str&gt; + 'a&gt; { Box::new(text.split(' ')) } fn main() { let text = "word1 word2 word3"; println!("{}", to_words(text).take(2).count()); } </code></pre> <p>This is the primary option that allows for <em>dynamic dispatch</em>. That is, the exact implementation of the code is decided at run-time, rather than compile-time. That means this is suitable for cases where you need to return more than one concrete type of iterator based on a condition.</p> <h3>Newtype</h3> <pre><code>use std::str; struct Wrapper&lt;'a&gt;(str::Split&lt;'a, char&gt;); impl&lt;'a&gt; Iterator for Wrapper&lt;'a&gt; { type Item = &amp;'a str; fn next(&amp;mut self) -&gt; Option&lt;&amp;'a str&gt; { self.0.next() } fn size_hint(&amp;self) -&gt; (usize, Option&lt;usize&gt;) { self.0.size_hint() } } fn to_words(text: &amp;str) -&gt; Wrapper&lt;'_&gt; { Wrapper(text.split(' ')) } fn main() { let text = "word1 word2 word3"; println!("{}", to_words(text).take(2).count()); } </code></pre> <h3>Type alias</h3> <p>As <a href="https://stackoverflow.com/questions/27535289/correct-way-to-return-an-iterator#comment43509185_27535594">pointed out by reem</a></p> <pre><code>use std::str; type MyIter&lt;'a&gt; = str::Split&lt;'a, char&gt;; fn to_words(text: &amp;str) -&gt; MyIter&lt;'_&gt; { text.split(' ') } fn main() { let text = "word1 word2 word3"; println!("{}", to_words(text).take(2).count()); } </code></pre> <h3>Dealing with closures</h3> <p>When <code>impl Trait</code> isn't available for use, closures make things more complicated. Closures create anonymous types and these cannot be named in the return type:</p> <pre><code>fn odd_numbers() -&gt; () { (0..100).filter(|&amp;v| v % 2 != 0) } </code></pre> <pre class="lang-none prettyprint-override"><code>found type `std::iter::Filter&lt;std::ops::Range&lt;{integer}&gt;, [closure@src/lib.rs:4:21: 4:36]&gt;` </code></pre> <p>In certain cases, these closures can be replaced with functions, which can be named:</p> <pre><code>fn odd_numbers() -&gt; () { fn f(&amp;v: &amp;i32) -&gt; bool { v % 2 != 0 } (0..100).filter(f as fn(v: &amp;i32) -&gt; bool) } </code></pre> <pre class="lang-none prettyprint-override"><code>found type `std::iter::Filter&lt;std::ops::Range&lt;i32&gt;, for&lt;'r&gt; fn(&amp;'r i32) -&gt; bool&gt;` </code></pre> <p>And following the above advice:</p> <pre><code>use std::{iter::Filter, ops::Range}; type Odds = Filter&lt;Range&lt;i32&gt;, fn(&amp;i32) -&gt; bool&gt;; fn odd_numbers() -&gt; Odds { fn f(&amp;v: &amp;i32) -&gt; bool { v % 2 != 0 } (0..100).filter(f as fn(v: &amp;i32) -&gt; bool) } </code></pre> <h3>Dealing with conditionals</h3> <p>If you need to conditionally choose an iterator, refer to <a href="https://stackoverflow.com/q/29760668/155423">Conditionally iterate over one of several possible iterators</a>.</p>
29,862,234
Thread vs Threadstart
<p>In C#, practically, I haven't observed any difference between the following:</p> <pre><code>new Thread(SomeMethod).Start(); </code></pre> <p>,</p> <pre><code>new Thread(new ParameterizedThreadStart(SomeMethod)); </code></pre> <p>and</p> <pre><code>new Thread(new ThreadStart(SomeMethod)); </code></pre> <p>What is the difference, if there is any at all?</p>
29,862,262
3
0
null
2015-04-25 07:15:21.33 UTC
7
2019-08-17 18:24:38.073 UTC
2015-04-25 07:18:56.533 UTC
null
97,000
null
3,727,060
null
1
28
c#|.net|multithreading
27,985
<p>The <code>Thread(ThreadStart)</code> constructor can only be used when the signature of your <code>SomeMethod</code> method matches the <code>ThreadStart</code> delegate. Conversely, <code>Thread(ParameterizedThreadStart)</code> requires <code>SomeMethod</code> to match the <code>ParameterizedThreadStart</code> delegate. The signatures are below:</p> <pre><code>public delegate void ThreadStart() public delegate void ParameterizedThreadStart(Object obj) </code></pre> <p>Concretely, this means that you should use <code>ThreadStart</code> when your method does not take any parameters, and <code>ParameterizedThreadStart</code> when it takes a single <code>Object</code> parameter. Threads created with the former should be started by calling <code>Start()</code>, whilst threads created with the latter should have their argument specified through <code>Start(Object)</code>.</p> <pre><code>public static void Main(string[] args) { var threadA = new Thread(new ThreadStart(ExecuteA)); threadA.Start(); var threadB = new Thread(new ParameterizedThreadStart(ExecuteB)); threadB.Start("abc"); threadA.Join(); threadB.Join(); } private static void ExecuteA() { Console.WriteLine("Executing parameterless thread!"); } private static void ExecuteB(Object obj) { Console.WriteLine($"Executing thread with parameter \"{obj}\"!"); } </code></pre> <p>Finally, you can call the <code>Thread</code> constructors without specifying the <code>ThreadStart</code> or <code>ParameterizedThreadStart</code> delegate. In this case, the compiler will match your method to the constructor overload based on its signature, performing the cast implicitly. </p> <pre><code>var threadA = new Thread(ExecuteA); // implicit cast to ThreadStart threadA.Start(); var threadB = new Thread(ExecuteB); // implicit cast to ParameterizedThreadStart threadB.Start("abc"); </code></pre>
34,770,169
Using Concurrent Futures without running out of RAM
<p>I'm doing some file parsing that is a CPU bound task. No matter how many files I throw at the process it uses no more than about 50MB of RAM. The task is parrallelisable, and I've set it up to use concurrent futures below to parse each file as a separate process:</p> <pre><code> from concurrent import futures with futures.ProcessPoolExecutor(max_workers=6) as executor: # A dictionary which will contain a list the future info in the key, and the filename in the value jobs = {} # Loop through the files, and run the parse function for each file, sending the file-name to it. # The results of can come back in any order. for this_file in files_list: job = executor.submit(parse_function, this_file, **parser_variables) jobs[job] = this_file # Get the completed jobs whenever they are done for job in futures.as_completed(jobs): # Send the result of the file the job is based on (jobs[job]) and the job (job.result) results_list = job.result() this_file = jobs[job] # delete the result from the dict as we don't need to store it. del jobs[job] # post-processing (putting the results into a database) post_process(this_file, results_list) </code></pre> <p>The problem is that when I run this using futures, RAM usage rockets and before long I've run out and Python has crashed. This is probably in large part because the results from parse_function are several MB in size. Once the results have been through <code>post_processing</code>, the application has no further need of them. As you can see, I'm trying <code>del jobs[job]</code> to clear items out of <code>jobs</code>, but this has made no difference, memory usage remains unchanged, and seems to increase at the same rate. </p> <p>I've also confirmed it's not because it's waiting on the <code>post_process</code> function by only using a single process, plus throwing in a <code>time.sleep(1)</code>.</p> <p>There's nothing in the futures docs about memory management, and while a brief search indicates it has come up before in real-world applications of futures (<a href="https://stackoverflow.com/questions/31720674/clear-memory-in-python-loop">Clear memory in python loop</a> and <a href="http://grokbase.com/t/python/python-list/1458ss5etz/real-world-use-of-concurrent-futures" rel="noreferrer">http://grokbase.com/t/python/python-list/1458ss5etz/real-world-use-of-concurrent-futures</a>) - the answers don't translate to my use-case (they're all concerned with timeouts and the like).</p> <p>So, how do you use Concurrent futures without running out of RAM? (Python 3.5)</p>
34,771,248
4
0
null
2016-01-13 15:10:56.813 UTC
9
2022-01-05 12:25:16.317 UTC
2017-05-23 12:25:08.173 UTC
null
-1
null
1,316,981
null
1
20
python|python-3.x|memory-management|parallel-processing
11,309
<p>I'll take a shot (Might be a wrong guess...)</p> <p>You might need to submit your work bit by bit since on each submit you're making a copy of parser_variables which may end up chewing your RAM.</p> <p>Here is working code with "&lt;----" on the interesting parts </p> <pre><code>with futures.ProcessPoolExecutor(max_workers=6) as executor: # A dictionary which will contain a list the future info in the key, and the filename in the value jobs = {} # Loop through the files, and run the parse function for each file, sending the file-name to it. # The results of can come back in any order. files_left = len(files_list) #&lt;---- files_iter = iter(files_list) #&lt;------ while files_left: for this_file in files_iter: job = executor.submit(parse_function, this_file, **parser_variables) jobs[job] = this_file if len(jobs) &gt; MAX_JOBS_IN_QUEUE: break #limit the job submission for now job # Get the completed jobs whenever they are done for job in futures.as_completed(jobs): files_left -= 1 #one down - many to go... &lt;--- # Send the result of the file the job is based on (jobs[job]) and the job (job.result) results_list = job.result() this_file = jobs[job] # delete the result from the dict as we don't need to store it. del jobs[job] # post-processing (putting the results into a database) post_process(this_file, results_list) break; #give a chance to add more jobs &lt;----- </code></pre>
34,923,788
Prometheus - Convert cpu_user_seconds to CPU Usage %?
<p>I'm monitoring docker containers via Prometheus.io. My problem is that I'm just getting <code>cpu_user_seconds_total</code> or <code>cpu_system_seconds_total</code>.</p> <p>How to convert this ever-increasing value to a CPU percentage?</p> <p>Currently I'm querying:</p> <pre><code>rate(container_cpu_user_seconds_total[30s]) </code></pre> <p>But I don't think that it is quite correct (comparing to top).</p> <p>How to convert <code>cpu_user_seconds_total</code> to CPU percentage? (Like in top)</p>
34,930,574
4
0
null
2016-01-21 12:25:40.17 UTC
10
2022-04-01 15:40:36.32 UTC
2020-11-13 12:50:16.94 UTC
null
1,788,806
null
3,737,635
null
1
36
performance|performance-testing|cpu-usage|prometheus
103,435
<p>Rate returns a per second value, so multiplying by 100 will give a percentage:</p> <p><code>rate(container_cpu_user_seconds_total[30s]) * 100</code></p>
35,080,907
How to know which tomcat version embedded in spring boot
<p>I used spring boot in project. It has inbuild tomcat server. I find out a jar <code>spring-boot-starter-tomcat-1.2.5.RELEASE.jar</code>. I required to do certain tomcat related configuration on linux server.</p> <p>How can I get to know which tomcat version used in this?</p>
35,081,005
9
0
null
2016-01-29 09:24:33.21 UTC
10
2021-11-16 13:23:04.407 UTC
2019-02-01 07:51:57.193 UTC
null
1,033,581
null
1,427,460
null
1
36
java|maven|tomcat|spring-boot
80,729
<p>Via <a href="http://search.maven.org/" rel="noreferrer">http://search.maven.org/</a>, in <a href="https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/1.2.5.RELEASE/spring-boot-dependencies-1.2.5.RELEASE.pom" rel="noreferrer">https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-dependencies/1.2.5.RELEASE/spring-boot-dependencies-1.2.5.RELEASE.pom</a>:</p> <pre><code>&lt;tomcat.version&gt;8.0.23&lt;/tomcat.version&gt; </code></pre>
49,879,438
Dart: Do I have to cancel Stream subscriptions and close StreamSinks?
<p>I know I have to cancel <code>Stream</code> Subscriptions when I no longer want to receive any events. Do I have to this even after I receive a 'Done' event? Or do I get memory leaks?</p> <p>What happens to Streams that are passed to <code>addStream</code> of another Stream? Are they automatically canceled? </p> <p>Same Question on the <code>StreamSink</code> side do I have to close them if the stream is already done?</p>
49,884,064
2
1
null
2018-04-17 13:28:19.407 UTC
9
2020-03-23 20:08:09.537 UTC
null
null
null
null
1,412,966
null
1
42
stream|dart
23,086
<p>Short-answer: <em>no, but you should</em>. Nothing in the contract of either <code>StreamSubscription</code> or <code>StreamSink</code> <em>requires</em> closing the resources, but some use cases can lead to memory leaks if you don't close them, even though in some cases, doing so might be confusing. Part of the confusion around these classes is that they are overloaded, and handle two fairly distinct use cases:</p> <ol> <li>Resource streams (like file I/O, network access)</li> <li>Event streams (like click handlers)</li> </ol> <p>Let's tackle these subjects one at a time, first, <code>StreamSubscription</code>:</p> <h2><a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/StreamSubscription-class.html" rel="noreferrer"><code>StreamSubscription</code></a></h2> <p>When you <a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/Stream/listen.html" rel="noreferrer"><code>listen</code></a> to a <code>Stream</code>, you receive a <a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/StreamSubscription-class.html" rel="noreferrer"><code>StreamSubscription</code></a>. In general, when you are <em>done</em> listening to that <code>Stream</code>, for any reason, you should close the subscription. Not all streams will leak memory if choose not to, but, some will - for example, if you are reading input from a file, not closing the stream means the handle to the file may remain open.</p> <p>So, while not <em>strictly required</em>, I'd <strong>always</strong> <a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/StreamSubscription/cancel.html" rel="noreferrer"><code>cancel</code></a> when done accessing the stream.</p> <h2><a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/StreamSink-class.html" rel="noreferrer"><code>StreamSink</code></a></h2> <p>The most common implementation of <code>StreamSink</code> is <a href="https://api.dartlang.org/dev/2.0.0-dev.48.0/dart-async/StreamController-class.html" rel="noreferrer"><code>StreamController</code></a>, which is a programmatic interface to creating a <code>Stream</code>. In general, when your stream is <em>complete</em> (i.e. all data emitted), you should close the controller.</p> <p>Here is where it gets a little confusing. Let's look at those two cases:</p> <h3>File I/O</h3> <p>Imagine you were creating an API to asynchronously read a File line-by-line:</p> <pre><code>Stream&lt;String&gt; readLines(String path); </code></pre> <p>To implement this, you might use a <code>StreamController</code>:</p> <pre><code>Stream&lt;String&gt; readLines(String path) { SomeFileResource someResource; StreamController&lt;String&gt; controller; controller = new StreamController&lt;String&gt;( onListen: () { someResource = new SomeFileResource(path); // TODO: Implement adding to the controller. }, ); return controller.stream; } </code></pre> <p>In this case, it would make lots of sense to <em>close</em> the <code>controller</code> when the last line has been read. This gives a signal to the user (a <em>done</em> event) that the file has been read, and is meaningful (you can close the File resource at that time, for example).</p> <h3>Events</h3> <p>Imagine you were creating an API to listen to news articles on HackerNews:</p> <pre><code>Stream&lt;String&gt; readHackerNews(); </code></pre> <p>Here it makes less sense to <em>close</em> the underlying sink/controller. Does HackerNews ever <em>stop</em>? Event streams like this (or <code>click</code> handlers in UI programs) don't traditionally "stop" without the user accessing for it (i.e cancelling the <code>StreamSubscription</code>).</p> <p>You <em>could</em> close the controller when you are done, but it's not required.</p> <hr> <p>Hope that makes sense and helps you out!</p>
45,079,988
Ingress vs Load Balancer
<p>I am quite confused about the roles of Ingress and Load Balancer in Kubernetes.</p> <p>As far as I understand Ingress is used to map incoming traffic from the internet to the services running in the cluster.</p> <p>The role of load balancer is to forward traffic to a host. In that regard how does ingress differ from load balancer? Also what is the concept of load balancer inside kubernetes as compared to Amazon ELB and ALB?</p>
45,084,511
10
0
null
2017-07-13 11:59:29.55 UTC
113
2022-08-13 04:33:22.33 UTC
2021-06-24 04:56:08.707 UTC
null
15,747,395
null
1,299,991
null
1
403
kubernetes|load-balancing|kubernetes-ingress
132,630
<p><strong>Load Balancer:</strong> A kubernetes LoadBalancer service is a service that points to external load balancers that are NOT in your kubernetes cluster, but exist elsewhere. They can work with your pods, assuming that your pods are externally routable. Google and AWS provide this capability natively. In terms of Amazon, this maps directly with ELB and kubernetes when running in AWS can automatically provision and configure an ELB instance for each LoadBalancer service deployed.</p> <p><strong>Ingress:</strong> An ingress is really just a set of rules to pass to a controller that is listening for them. You can deploy a bunch of ingress rules, but nothing will happen unless you have a controller that can process them. A LoadBalancer service could listen for ingress rules, if it is configured to do so.</p> <p>You can also create a <strong>NodePort</strong> service, which has an externally routable IP outside the cluster, but points to a pod that exists within your cluster. This could be an Ingress Controller.</p> <p>An Ingress Controller is simply a pod that is configured to interpret ingress rules. One of the most popular ingress controllers supported by kubernetes is nginx. In terms of Amazon, ALB <a href="https://github.com/kubernetes/ingress/tree/master/controllers/nginx" rel="noreferrer">can be used</a> as an ingress controller.</p> <p>For an example, <a href="https://github.com/kubernetes/ingress/tree/master/controllers/nginx" rel="noreferrer">this</a> nginx controller is able to ingest ingress rules you have defined and translate them to an nginx.conf file that it loads and starts in its pod.</p> <p>Let's for instance say you defined an ingress as follows:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: ingress.kubernetes.io/rewrite-target: / name: web-ingress spec: rules: - host: kubernetes.foo.bar http: paths: - backend: serviceName: appsvc servicePort: 80 path: /app </code></pre> <p>If you then inspect your nginx controller pod you'll see the following rule defined in <code>/etc/nginx.conf</code>:</p> <pre><code>server { server_name kubernetes.foo.bar; listen 80; listen [::]:80; set $proxy_upstream_name "-"; location ~* ^/web2\/?(?&lt;baseuri&gt;.*) { set $proxy_upstream_name "apps-web2svc-8080"; port_in_redirect off; client_max_body_size "1m"; proxy_set_header Host $best_http_host; # Pass the extracted client certificate to the backend # Allow websocket connections proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header X-Real-IP $the_real_ip; proxy_set_header X-Forwarded-For $the_x_forwarded_for; proxy_set_header X-Forwarded-Host $best_http_host; proxy_set_header X-Forwarded-Port $pass_port; proxy_set_header X-Forwarded-Proto $pass_access_scheme; proxy_set_header X-Original-URI $request_uri; proxy_set_header X-Scheme $pass_access_scheme; # mitigate HTTPoxy Vulnerability # https://www.nginx.com/blog/mitigating-the-httpoxy-vulnerability-with-nginx/ proxy_set_header Proxy ""; # Custom headers proxy_connect_timeout 5s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_redirect off; proxy_buffering off; proxy_buffer_size "4k"; proxy_buffers 4 "4k"; proxy_http_version 1.1; proxy_cookie_domain off; proxy_cookie_path off; rewrite /app/(.*) /$1 break; rewrite /app / break; proxy_pass http://apps-appsvc-8080; } </code></pre> <p>Nginx has just created a rule to route <code>http://kubernetes.foo.bar/app</code> to point to the service <code>appsvc</code> in your cluster.</p> <p>Here is <a href="https://crondev.com/kubernetes-nginx-ingress-controller/" rel="noreferrer">an example</a> of how to implement a kubernetes cluster with an nginx ingress controller. Hope this helps!</p>
45,121,828
Android Studio, Suddenly got GPU Driver Issue when running emulator
<p> I have a laptop that I mainly use for android development on android studio, today all of the sudden got this error message (or an outdated version of it) when i ran my emulator</p> <pre class="lang-none prettyprint-override"><code>Your GPU driver information: GPU #1 Make: 8086 Model: Intel(R) HD Graphics Family Device ID: 0a16 Driver version: 10.18.10.3945 GPU #2 Make: 10de Model: NVIDIA GeForce 820M Device ID: 1140 Driver version: 22.21.13.8476 Some users have experienced emulator stability issues with this driver version. As a result, were selecting a compatibility renderer. Please check with your manufacturer to see if there is an updated driver available. </code></pre> <p>Updated the geforce driver, but no use, tried to update the intel one but failed, is there a way to disable this? bypass the compatibility renderer and work as I used to, the emulator is awful now. Any explanation why that occurred all of the sudden?</p> <p>Also I'm using windows 7 64-bit if that will help with anything, had an update few days ago.</p>
45,124,147
11
0
null
2017-07-15 19:08:48.743 UTC
33
2021-11-16 16:56:30.333 UTC
2018-08-23 14:47:08.97 UTC
null
145,173
null
6,468,781
null
1
74
android|android-studio|android-emulator
97,083
<p>I am using Win10 but have the same problem. Emulator started crashing my app after last emulator update. In my case, problem is that emulator does not run on hardware even though I never had a problem with my GPUs. Also, the "GPU driver issue" window that pops up doesn't even label WHICH one of the GPUs it thinks is the problem. </p> <p>For me the solution that worked is to run emulator from terminal, forcing it to run using hardware graphics (instead of letting emulator decide on which) using command</p> <pre><code>emulator -avd avd_name -gpu mode </code></pre> <p>where <i>mode</i> is <b>host</b> so that it will run with hardware.</p> <p>For example:</p> <p>Using Android Studio terminal move to folder where the emulator is located. Default on Win10 is: C:\Users\<i>userName</i>\AppData\Local\Android\sdk\emulator</p> <p>Find emulator to run by listing available ones: <code>emulator -list-avds</code></p> <p>Run emulator with <i>-gpu host</i> option: <code>emulator -avd avd_name -gpu host</code></p> <p>More info on <a href="https://developer.android.com/studio/run/emulator-acceleration.html" rel="noreferrer">this link</a> </p>
44,485,616
Web scraping image inside canvas
<p>I am web scraping a page where with various numbers appears also images of small price charts.</p> <p>If I click on this images inside the browser I can save that chart as a <code>.png</code> image.</p> <p>When I look at the source code that element looks like this when inspected:</p> <pre><code>&lt;div class="performance_2d_sparkline graph ng-isolate-scope ng-scope" x-data-percent-change-day="ticker.pct_chge_1D" x-sparkline="watchlistData.sparklineData[ticker.ticker]"&gt; &lt;span class="inlinesparkline ng-binding"&gt; &lt;canvas width="100" height="40" style="display: inline-block; width: 100px; height: 40px; vertical-align: top;"&gt; &lt;/canvas&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>Is there any way I can save through web scraping the same images that I can save manually through the browser?</p>
44,485,983
1
0
null
2017-06-11 15:37:31.613 UTC
9
2017-06-11 16:15:13.09 UTC
2017-06-11 15:42:33.563 UTC
null
354,577
null
3,755,529
null
1
9
python|image|canvas|web-scraping|beautifulsoup
5,238
<p>If you are using Selenium for your web scraping, you can get the canvas element and save it to the image file using the following code snippet:</p> <pre><code># get the base64 representation of the canvas image (the part substring(21) is for removing the padding "data:image/png;base64") base64_image = driver.execute_script("return document.querySelector('.inlinesparkline canvas').toDataURL('image/png').substring(21);") # decode the base64 image output_image = base64.b64decode(base64_image) # save to the output image with open("image.png", 'wb') as f: f.write(output_image) </code></pre>
26,015,521
MySQL Import Database Schema
<p>I'm having issues attempting to import a database of 195MB via the command line.</p> <pre><code>mysql -u root -p [DB_NAME] C:\Users\user_name\Downloads\file.sql </code></pre> <p>When I run this command all I receive from MySQL is a list of variables and options available.</p> <p>What am I doing wrong?</p> <p>Also like to add I'm using a fresh install of XAMPP.</p>
26,015,638
1
0
null
2014-09-24 11:14:54.403 UTC
4
2014-09-24 11:21:48.84 UTC
null
null
null
null
1,353,384
null
1
13
mysql|command-line|mysqldump
44,345
<p>You're missing a <code>&lt;</code>, which means you want to direct the content of the file into mysql.</p> <pre><code>mysql -u root -p [DB_NAME] &lt; C:\Users\user_name\Downloads\file.sql </code></pre>
22,822,427
Bootstrap select dropdown list placeholder
<p>I am trying to make a dropdown list that contains a placeholder. It doesn't seem to support <code>placeholder="stuff"</code> as other forms do. Is there a different way to obtain a placeholder in my dropdown?</p>
23,279,223
20
0
null
2014-04-02 20:33:42.957 UTC
31
2021-11-05 15:38:02.93 UTC
2015-01-28 14:18:10.09 UTC
null
2,232,744
null
2,232,744
null
1
120
html|twitter-bootstrap|placeholder
314,689
<p>Yes just "selected disabled" in the option.</p> <pre><code>&lt;select&gt; &lt;option value="" selected disabled&gt;Please select&lt;/option&gt; &lt;option value=""&gt;A&lt;/option&gt; &lt;option value=""&gt;B&lt;/option&gt; &lt;option value=""&gt;C&lt;/option&gt; &lt;/select&gt; </code></pre> <p><a href="http://jsfiddle.net/LXp4h/" rel="noreferrer">Link to fiddle</a></p> <p>You can also view the answer at</p> <p><a href="https://stackoverflow.com/a/5859221/1225125">https://stackoverflow.com/a/5859221/1225125</a></p>
27,063,312
How do I do the equivalent of setTimeout + clearTimeout in Dart?
<p>I'm porting some JavaScript to Dart. I have code that uses <code>window.setTimeout</code> to run a callback after a period of time. In some situations, that callback gets canceled via <code>window.clearTimeout</code>.</p> <p>What is the equivalent of this in Dart? I can use <code>new Future.delayed</code> to replace <code>setTimeout</code>, but I can't see a way to cancel this. Nor can I find away to call <code>clearTimeout</code> from Dart.</p>
27,063,355
2
0
null
2014-11-21 14:12:59.387 UTC
2
2020-11-15 06:26:39.627 UTC
2014-11-21 14:20:37.913 UTC
null
217,408
null
25,124
null
1
37
dart|settimeout|dart-async
22,611
<p>You can use the <a href="https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:async.Timer" rel="noreferrer">Timer class</a></p> <pre class="lang-dart prettyprint-override"><code>import 'dart:async'; var timer = Timer(Duration(seconds: 1), () =&gt; print('done')); timer.cancel(); </code></pre>
3,148,177
The right way to get http referrer from jquery
<p>Command $(document).referrer is the correct way to get referrer with Jquery?</p>
3,148,183
1
2
null
2010-06-30 10:03:56.997 UTC
4
2011-04-23 02:11:25.39 UTC
null
null
null
null
188,912
null
1
25
javascript|jquery
39,710
<p>How about just:</p> <pre><code>document.referrer </code></pre>
2,708,990
What's the new way to iterate over a Java Map in Scala 2.8.0?
<p>How does <code>scala.collection.JavaConversions</code> supercede the answers given in Stack Overflow question <em><a href="https://stackoverflow.com/questions/495741">Iterating over Java collections in Scala</a></em> (it doesn't work because the "jcl" package is gone) and in <em><a href="http://www.eishay.com/2009/05/iterating-over-map-with-scala.html" rel="nofollow noreferrer">Iterating over Map with Scala</a></em> (it doesn't work for me in a complicated test which I'll try to boil down and post here later).</p> <p>The latter is actually a Scala Map question, but I think I need to know both answers in order to iterate over a <code>java.util.Map</code>.</p>
2,709,031
1
0
null
2010-04-25 16:46:09.733 UTC
13
2013-06-09 20:21:07.35 UTC
2017-05-23 10:30:04.887 UTC
null
-1
null
196,032
null
1
36
scala|language-features|scala-2.8
20,145
<p>In 2.8, you import <code>scala.collection.JavaConversions._</code> and use as a Scala map. Here's an example (in 2.8.0.RC1):</p> <pre><code>scala&gt; val jmap:java.util.Map[String,String] = new java.util.HashMap[String,String] jmap: java.util.Map[String,String] = {} scala&gt; jmap.put("Hi","there") res0: String = null scala&gt; jmap.put("So","long") res1: String = null scala&gt; jmap.put("Never","mind") res2: String = null scala&gt; import scala.collection.JavaConversions._ import scala.collection.JavaConversions._ scala&gt; jmap.foreach(kv =&gt; println(kv._1 + " -&gt; " + kv._2)) Hi -&gt; there Never -&gt; mind So -&gt; long scala&gt; jmap.keys.map(_.toUpperCase).foreach(println) HI NEVER SO </code></pre> <p>If you specifically want a Scala iterator, use <code>jmap.iterator</code> (after the conversions import).</p>
46,504,322
Creating a class library in visual studio code
<p>It might be a silly question, Let's say I don't have a Windows OS, have a Linux. I have created a .Net core console app, also want to create a class library and reference it in console app. I can't find if i am able to do it also couldn't find a sample on Microsoft .Net core page. Is there an extension in vs code? Or isn't it possible with it? If i am mistaken could you please guide me?</p>
46,504,463
1
0
null
2017-09-30 15:43:38.02 UTC
10
2018-03-08 15:05:32.687 UTC
null
null
null
null
3,250,122
null
1
14
.net-core|portable-class-library
16,667
<p>The best way to do it is from the console, since you are using the latest supported templates this way. VSCode also has an integrated terminal you can use for this.</p> <pre><code>$ dotnet new lib -o MyLib $ dotnet new sln #assuming there is no .sln file yet. if there is, skip this $ dotnet sln add MyLib/MyLib.csproj $ cd MyConsoleApp $ dotnet add reference ../MyLib/MyLib.csproj </code></pre> <p>If you need different frameworks, you can use the <code>-f</code> argument:</p> <pre><code>$ dotnet new lib -o MyLib -f netcoreapp2.0 </code></pre> <p>or manually change the <code>&lt;TargetFramework&gt;</code> element inside the generated <code>.csproj</code> file.</p>
21,013,678
How to verify ios In-App Purchase on your server
<p>I am up to build my first in-app purchase app. I would like to know whether there is a way to verify purchase on your server.</p> <p>I have to build the whole user management, and I would like to know for all registered user what they already bought on their iOS devices, so that they get web app for free, or something like that. So, is there a way for me to check on Apple store side, if this user has already buy some product?</p> <p>EDIT:</p> <p>Scenario is like this:</p> <p>User A buy app B on mobile device. After this I would like to check on my server (on my web page,...) if user A is bought app B, or (similar) which app was bought by user A.</p> <p>I don't want to send message from mobile device to my server that user A buy app B, because users can reproduce this call on server even if they didn't buy app B. </p> <p>I would check on server side whit app Store if user A bought app B.</p>
28,465,202
6
0
null
2014-01-09 07:04:22.863 UTC
11
2020-11-11 18:32:39.657 UTC
2014-01-09 17:14:00.957 UTC
null
881,229
null
2,791,346
null
1
29
ios|app-store|in-app-purchase
31,062
<p>Fetch the app's receipt (from the file at <code>[[NSBundle mainBundle] appStoreReceiptURL]</code>) and send it to your server. Then either…</p> <ul> <li><p>Parse the receipt and check its signature against Apple's certificate <a href="https://developer.apple.com/library/mac/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html">as described here</a> (on your server, not in the app). Or,</p></li> <li><p>Send the receipt (again, from your server) to the app store for validation <a href="https://developer.apple.com/library/mac/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html">as described here</a>.</p></li> </ul>
37,514,810
How to get the region of the current user from boto?
<p>Problem:</p> <p>I'm trying to get the region of the authenticated user from boto3.</p> <p>Use case:</p> <p>I'm working on adding cache to <a href="https://github.com/pmazurek/aws-fuzzy-finder" rel="noreferrer">https://github.com/pmazurek/aws-fuzzy-finder</a>. I would prefer to cache the result on <em>per-region</em> basis.</p> <p>This package uses boto to get user authentication data (keys and the region). The problem is the region is never passed explicitly by the user, its being taken from one of the many murky places that boto reads so I don't really have a way of getting it. </p> <p>I have tried searching through boto3 api and googling, but couldn't find anything like a <code>get_region</code> or <code>get_user_data</code> method. Is it possible?</p>
37,519,906
5
0
null
2016-05-29 20:45:58.273 UTC
7
2022-01-24 02:40:24.87 UTC
null
null
null
null
2,521,248
null
1
56
python|amazon-web-services|amazon-ec2|boto|aws-sdk
51,207
<p>You should be able to read the <a href="https://boto3.readthedocs.io/en/latest/reference/core/session.html#boto3.session.Session.region_name" rel="noreferrer"><code>region_name</code></a> from the <code>session.Session</code> object like</p> <pre><code>my_session = boto3.session.Session() my_region = my_session.region_name </code></pre> <p><code>region_name</code> is basically defined as <code>session.get_config_variable('region')</code></p>
32,278,305
Why do enums have computed properties but not stored properties in Swift?
<p>I am new to Swift and just came across this in the documentation:</p> <blockquote> <p>Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.</p> </blockquote> <p>Why is that? Do associated values for enum work like stored properties? It seems like they had stored properties initially - <a href="https://stackoverflow.com/questions/24029581/why-no-stored-type-properties-for-classes-in-swift">Why no stored type properties for classes in swift?</a></p>
32,280,830
4
0
null
2015-08-28 19:14:46.12 UTC
10
2017-06-16 00:11:29.27 UTC
2017-05-23 12:00:13.92 UTC
null
-1
null
142,588
null
1
42
swift|enums|language-features
35,094
<p><code>enum</code>s do have stored <em>type</em> properties - i.e., <code>static</code> properties. They don't have stored <em>instance</em> properties. I don't know if there is a technical reason why stored instance properties are not available for <code>enum</code>s. You may have to ask your question on the dev forum if you want a technical answer for "why".</p> <p>In your question you ask if associated values work like stored properties. In fact, they do, and are more flexible (in some ways) than stored properties for <code>struct</code>s and <code>class</code>es. Each <code>case</code> in an <code>enum</code> can have its own specialized set of data that is associated with it. Rather than have one set of stored properties that apply to all <code>case</code>s, you get to individualize the stored properties for each <code>case</code>.</p>
55,674,176
django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17))
<p>I've cloned a django project to a Centos 7 vps and I'm trying to run it now, but I get this error when trying to <code>migrate</code>:</p> <pre><code>$ python manage.py migrate django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). </code></pre> <p>When I checked the version for sqlite, it was 3.7.17, so I downloaded the newest version from sqlite website and replaced it with the old one, and now when I version it, it gives:</p> <pre><code>$ sqlite3 --version 3.27.2 2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7 </code></pre> <p>Still when I try to migrate the project, I get the exact same message as before which means the newer version is not found. I'm new to linux and would appreciate any help.</p>
55,775,310
13
3
null
2019-04-14 10:20:18.557 UTC
14
2022-03-14 04:13:00.89 UTC
null
null
null
null
4,457,315
null
1
48
python|django|sqlite|centos7
93,463
<p>To check which version of SQLite Python is using:</p> <pre><code>$ python Python 3.7.3 (default, Apr 12 2019, 16:23:13) &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.sqlite_version '3.27.2' </code></pre> <p>For me the new version of sqlite3 is in /usr/local/bin so I had to recompile Python, telling it to look there:</p> <pre><code>sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations sudo LD_RUN_PATH=/usr/local/lib make altinstall </code></pre>
36,766,234
NodeJS: Merge two PDF files into one using the buffer obtained by reading them
<p>I am using fill-pdf npm module for filling template pdf's and it creates new file which is read from the disk and returned as buffer to callback. I have two files for which i do the same operation. I want to combine the two buffers there by to form a single pdf file which i can send back to the client. I tried different methods of buffer concatenation. The buffer can be concatenated using Buffer.concat, like,</p> <pre><code>var newBuffer = Buffer.concat([result_pdf.output, result_pdf_new.output]); </code></pre> <p>The size of new buffer is also the sum of the size of the input buffers. But still when the <code>newBuffer</code> is sent to client as response, it shows only the file mentioned last in the array. </p> <pre><code>res.type("application/pdf"); return res.send(buffer); </code></pre> <p>Any idea ?</p>
50,063,545
3
1
null
2016-04-21 10:03:16.023 UTC
10
2020-08-05 14:49:49.597 UTC
null
null
null
null
3,223,450
null
1
23
node.js|pdf|npm
30,466
<p><a href="https://github.com/galkahana/HummusJS" rel="noreferrer">HummusJS</a> supports combining PDFs using its <a href="https://github.com/galkahana/HummusJS/wiki/Embedding-pdf#basic-page-appending" rel="noreferrer">appendPDFPagesFromPDF</a> method</p> <p>Example using streams to work with buffers:</p> <pre><code>const hummus = require('hummus'); const memoryStreams = require('memory-streams'); /** * Concatenate two PDFs in Buffers * @param {Buffer} firstBuffer * @param {Buffer} secondBuffer * @returns {Buffer} - a Buffer containing the concactenated PDFs */ const combinePDFBuffers = (firstBuffer, secondBuffer) =&gt; { var outStream = new memoryStreams.WritableStream(); try { var firstPDFStream = new hummus.PDFRStreamForBuffer(firstBuffer); var secondPDFStream = new hummus.PDFRStreamForBuffer(secondBuffer); var pdfWriter = hummus.createWriterToModify(firstPDFStream, new hummus.PDFStreamForResponse(outStream)); pdfWriter.appendPDFPagesFromPDF(secondPDFStream); pdfWriter.end(); var newBuffer = outStream.toBuffer(); outStream.end(); return newBuffer; } catch(e){ outStream.end(); throw new Error('Error during PDF combination: ' + e.message); } }; combinePDFBuffers(PDFBuffer1, PDFBuffer2); </code></pre>
25,702,991
enabling cors in codeigniter ( restserver by @chriskacerguis )
<p>http.get request in agularJs controller works fine when my client app and api are in localhost. when api is moved to server., issue arised.</p> <p>client side using angularJs</p> <pre><code>$http.get('http://example.com/api/spots/2/0').success(function(data){ console.log(data); }); </code></pre> <p>log gives: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="http://example.com/api/spots/2/0" rel="nofollow noreferrer">http://example.com/api/spots/2/0</a>. This can be fixed by moving the resource to the same domain or enabling CORS.</p> <p>i have added these two lines to my controller construct</p> <pre><code>header(&quot;Access-Control-Allow-Origin: *&quot;); header(&quot;Access-Control-Allow-Methods: GET&quot;); </code></pre> <p>still same error.</p>
25,703,960
10
0
null
2014-09-06 17:38:13.147 UTC
7
2022-05-15 16:57:36.05 UTC
2022-03-02 11:23:39.243 UTC
null
3,098,242
null
3,098,242
null
1
12
php|angularjs|codeigniter|codeigniter-restserver
62,636
<p>Try adding <code>OPTIONS</code> to the allowed methods.</p> <pre><code>header("Access-Control-Allow-Methods: GET, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding"); </code></pre> <p>and return immediately when the request is method 'OPTIONS' once you have set the headers.</p> <pre><code>if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) { die(); } </code></pre> <p>See also <a href="https://stackoverflow.com/questions/15602099/http-options-error-in-phil-sturgeons-codeigniter-restserver-and-backbone-js?rq=1">this answer</a>.</p> <p>Angular sends a <a href="http://www.w3.org/TR/cors/#resource-preflight-requests" rel="noreferrer">W3C CORS spec compliant preflight request</a> that will check for the right allowed methods before actually attempting it.</p> <p>Personally, I find the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" rel="noreferrer">Mozilla Developer Network CORS page</a> a bit easier to read on the matter to help understand the flow of CORS.</p>
28,185,807
Bootstrap image and text side by side in a div
<p>I am trying to put an image and texts side by side in bootstrap inside a single div.. For that I used the <code>class</code> of <code>thumbnail</code>. But using bootstrap thumbnail it makes the image to go at the top and all the texts at the bottom. </p> <p>So I changed it a bit to put the image and the texts within the thumbnail only and dividing the thumbnail into two parts. But on resizing the screen into small the problem is arising.. The texts are shifting over the image..</p> <p>Here is the code of what I tried till now</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-sm-6 col-md-6 col-xs-6"&gt; &lt;div class="thumbnail" style="border:none; background:white; height:210px;"&gt; &lt;div class="col-sm-6 col-md-6 col-xs-6"&gt; &lt;img src="images/online_learning.jpg" style="height:200px; margin-left:-15px;" /&gt; &lt;/div&gt; &lt;div class="col-sm-6 col-md-6 col-xs-6"&gt; &lt;h3&gt;Hello World&lt;/h3&gt; &lt;p style="font-size:10px; color:#03225C;"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit adipiscing blandit. Aliquam placerat, velit a fermentum fermentum, mi felis vehicula justo, a dapibus quam augue non massa. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="http://tinypic.com/view.php?pic=dvhmwy&amp;s=8#.VMiAc993M8o" rel="noreferrer">Screenshot without resizing</a></p> <p><a href="http://tinypic.com/view.php?pic=21bsnqr&amp;s=8#.VMiByd93M8o" rel="noreferrer">Screenshot after resizing</a></p>
28,185,938
2
0
null
2015-01-28 06:11:41.397 UTC
1
2015-04-02 06:51:23.333 UTC
2015-01-28 06:29:44.8 UTC
null
4,464,215
null
4,464,215
null
1
8
html|css|twitter-bootstrap
85,933
<p>Try this</p> <pre><code>&lt;div class="col-sm-6 col-md-6 col-xs-6"&gt; &lt;div class="thumbnail" style="border:none; background:white;"&gt; &lt;div class="col-sm-6 col-md-6 col-xs-12 image-container"&gt; &lt;img src="images/online_learning.jpg" style="height:200px; margin-left:-15px;" /&gt; &lt;/div&gt; &lt;div class="col-sm-6 col-md-6 col-xs-12"&gt; &lt;h3&gt;Hello World&lt;/h3&gt; &lt;p style="font-size:10px; color:#03225C;"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed hendrerit adipiscing blandit. Aliquam placerat, velit a fermentum fermentum, mi felis vehicula justo, a dapibus quam augue non massa. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>css code write this in media query if u need only for mobile</p> <pre><code>.image-container{text-align:center} </code></pre> <p>in case if u need both the image and text side by side in mobile device, remove the height for the image in media query to mobile devices resolution, give width 100% to the image </p>
28,313,664
Remove empty commits in git
<p>I just migrated a project from Mercurial to Git. Mercurial adds empty commits when you add tags, so I ended up with empty commits in Git that I would like to remove.</p> <p>How do I remove empty commits (commits that do not have any files in them) from Git?</p> <p>Thanks.</p>
28,313,729
2
0
null
2015-02-04 04:43:37.667 UTC
11
2017-06-01 16:55:57.127 UTC
2017-06-01 16:55:57.127 UTC
null
135,138
null
1,795,917
null
1
34
git|version-control|git-commit
19,654
<p>One simple (but slow) way to do this is with <code>git filter-branch</code> and <code>--prune-empty</code>. With no other filters, no other commits will be altered, but any empty ones will be discarded (which will cause all subsequent commits to have new parent-IDs and is therefore still "rewrites history": not a big deal if this is your initial import from hg to git, but is a big deal if others are using this repository already).</p> <p>Note all the usual caveats with filter-branch. (Also, as a side note, an "empty commit" is really one that has the same tree as the previous commit: it's not that it has no files at all, it's that it has all the same files, with the same modes, and the same contents, as its parent commit. This is because git stores complete snapshots for each commit, not differences from one commit to the next.)</p> <hr> <p>Here is a tiny example that hides a lot of places you can do fancier things:</p> <pre><code>$ ... create repository ... $ cd some-tmp-dir; git clone --mirror file://path-to-original </code></pre> <p>(This first clone step is for safety: <code>filter-branch</code> can be quite destructive so it's always good to start it on a new clone rather than the original. Using <code>--mirror</code> means all its branches and tags are mirrored in this copy, too.)</p> <pre><code>$ git filter-branch --prune-empty --tag-name-filter cat -- --all </code></pre> <p>(Now wait a potentially very long time; see documentation on methods to speed this up a bit.)</p> <pre><code>$ git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d </code></pre> <p>(This step is copied out of the documentation: it discards all the original branches from before running the filter. In other words, it makes the filtering permanent. Since this is a clone, that's reasonably safe to do even if the filter went wrong.)</p> <pre><code>$ cd third-tmp-dir; git clone --mirror file://path-to-filtered-tmp </code></pre> <p>(This makes a clean, nicely-compressed copy of the filtered copy, with no leftover objects from the filtering steps.)</p> <pre><code>$ git log # and other commands to inspect </code></pre> <p>Once you're sure the clone of the filtered clone is good, you don't need the filtered clone, and can use the last clone in place of the first. (That is, you can replace the "true original" with the final clone.)</p>
8,938,817
Image comparison using Matlab
<p>I want to compare two images in Matlab (I learned that Matlab has more features for comparing images and processing them). Can anyone suggest a good and simple method for doing the same? And the image needs to be exactly same. So the brightness and position of the image need not be considered. </p> <p>I need to complete my project in two months so I would be glad if any one helps me with a good algorithm or method.</p>
8,938,857
4
0
null
2012-01-20 08:52:45.39 UTC
1
2017-12-14 15:23:38.933 UTC
2012-01-20 19:07:54.953 UTC
null
597,607
null
1,140,476
null
1
2
matlab
38,851
<p>When you load an image into MATLAB, they are stored as matrices. Anything you can use to compare matrices can compare the images (for e.g. ISEQUAL). But if you want to compare the images more in an image processing sense, look at the demos for the Image Processing Toolbox and see <a href="https://www.mathworks.com/examples/image" rel="nofollow noreferrer">here</a> which (if any) of the demos fit your definition of "compare".</p>
47,693,093
Angular 5 and Service Worker: How to exclude a particular path from ngsw-config.json
<p>I have <code>ngsw-config.json</code> (taken from the <a href="https://angular.io/guide/service-worker-getting-started#step-4-create-the-configuration-file-ngsw-configjson" rel="noreferrer">docs</a>):</p> <pre class="lang-js prettyprint-override"><code> { "index": "/index.html", "assetGroups": [{ "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html" ], "versionedFiles": [ "/*.bundle.css", "/*.bundle.js", "/*.chunk.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ] } }] } </code></pre> <p>On my site there is a link to the RSS feed <code>/api/rss</code>, which should open in a new browser tab without loading Angular app. How can I exclude it from a list of resources whose request is redirected to <code>index.html</code>?</p> <p><strong>UPD</strong>: I tried but not working the following config (see <code>!/api/rss</code>):</p> <pre class="lang-js prettyprint-override"><code> { "index": "/index.html", "assetGroups": [{ "name": "app", "installMode": "prefetch", "patterns": ["!/api/rss"], "resources": { "files": [ "/favicon.ico", "/index.html", "!/api/rss" ], "versionedFiles": [ "/*.bundle.css", "/*.bundle.js", "/*.chunk.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ] } }] } </code></pre>
47,849,647
7
2
null
2017-12-07 10:37:12.62 UTC
3
2020-08-19 14:53:55.87 UTC
2020-03-25 11:27:08.337 UTC
null
4,956,569
null
1,716,560
null
1
37
angular|service-worker|angular-service-worker
22,378
<p>Thanks to the <strong>Pedro Arantes</strong> <a href="https://stackoverflow.com/a/47849072/1716560">advice</a>, I reached the next working config (see <code>dataGroups</code> and <code>"maxAge": "0u"</code>):</p> <pre class="lang-js prettyprint-override"><code>{ "index": "/index.html", "dataGroups": [ { "name": "api", "urls": ["/api"], "cacheConfig": { "maxSize": 0, "maxAge": "0u", "strategy": "freshness" } } ], "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html" ], "versionedFiles": [ "/*.bundle.css", "/*.bundle.js", "/*.chunk.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**" ] } } ] } </code></pre>
30,704,078
How to download a file through ajax request in asp.net MVC 4
<p>Below is my code : </p> <pre><code>ActionResult DownloadAttachment(student st) { var file = db.EmailAttachmentReceived.FirstOrDefault(x =&gt; x.LisaId == st.Lisaid); byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename); } </code></pre> <p>This is the script which i'm using</p> <pre><code>$(function () { $("#DownloadAttachment").click(function () { $.ajax({ url: '@Url.Action("DownloadAttachment", "PostDetail")', contentType: 'application/json; charset=utf-8', datatype: 'json', type: "GET", success: function () { alert("sucess"); } }); }); }); </code></pre> <p>How to return the file for download pursing above code?</p>
30,704,519
5
0
null
2015-06-08 08:09:48.763 UTC
7
2019-08-01 06:33:00.253 UTC
2016-01-28 23:22:46.513 UTC
null
30,001
null
2,226,434
null
1
16
jquery|json|asp.net-mvc-4|asp.net-ajax
106,992
<p>Please, try this in ajax success </p> <pre><code>success: function () { window.location = '@Url.Action("DownloadAttachment", "PostDetail")'; } </code></pre> <p>Updated answer:</p> <pre><code>public ActionResult DownloadAttachment(int studentId) { // Find user by passed id // Student student = db.Students.FirstOrDefault(s =&gt; s.Id == studentId); var file = db.EmailAttachmentReceived.FirstOrDefault(x =&gt; x.LisaId == studentId); byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename); } </code></pre> <p>Ajax request:</p> <pre><code>$(function () { $("#DownloadAttachment").click(function () { $.ajax( { url: '@Url.Action("DownloadAttachment", "PostDetail")', contentType: 'application/json; charset=utf-8', datatype: 'json', data: { studentId: 123 }, type: "GET", success: function () { window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })'; } }); }); }); </code></pre>
812,428
How to schedule SSIS package to run as something other than SQL Agent Service Account
<p>In SQL Server 2005, is it possible to schedule an SSIS package to run something other than the SQL Agent Service Account?</p> <p>I've got an SSIS package that makes a connection to a database and runs a stored procedure. My criteria is that I will not specify usernames/passwords in a package or package configuration, so I want to use integrated authentication. </p> <p>The problem is that by default a step in a job runs as SQL Agent Service Account, and our server group does not want to grant that account execute rights on the stored procedures that my package will execute. So we're trying to find a way to specify a different account in the step, so the package will run under a different context. Is that possible?</p>
812,486
3
0
null
2009-05-01 17:45:59.783 UTC
5
2020-07-31 18:43:32.107 UTC
2017-09-13 15:13:35.193 UTC
null
4,801,920
null
9,266
null
1
13
sql-server|sql-server-2005|ssis
60,450
<p>If you want to execute the SSIS package from SQL Agent jobs, then you can create a proxy. Check <a href="http://msdn.microsoft.com/en-us/library/ms190698.aspx" rel="noreferrer" title="SQL Server Proxy">here</a> for more information.</p>
789,521
How do I use EXPLAIN to *predict* performance of a MySQL query?
<p>I'm helping maintain a program that's essentially a friendly read-only front-end for a big and complicated MySQL database -- the program builds ad-hoc SELECT queries from users' input, sends the queries to the DB, gets the results, post-processes them, and displays them nicely back to the user.</p> <p>I'd like to add some form of reasonable/heuristic prediction for the constructed query's expected performance -- sometimes users inadvertently make queries that are inevitably going to take a very long time (because they'll return huge result sets, or because they're "going against the grain" of the way the DB is indexed) and I'd like to be able to display to the user some "somewhat reliable" information/guess about how long the query is going to take. It doesn't have to be perfect, as long as it doesn't get so badly and frequently out of whack with reality as to cause a "cry wolf" effect where users learn to disregard it;-) Based on this info, a user might decide to go get a coffee (if the estimate is 5-10 minutes), go for lunch (if it's 30-60 minutes), kill the query and try something else instead (maybe tighter limits on the info they're requesting), etc, etc.</p> <p>I'm not very familiar with MySQL's EXPLAIN statement -- I see a lot of information around on how to use it to <em>optimize</em> a query or a DB's schema, indexing, etc, but not much on how to use it for my more limited purpose -- simply make a prediction, taking the DB as a given (of course if the predictions are reliable enough I may eventually switch to using them also to choose between alternate forms a query could take, but, that's for the future: for now, I'd be plenty happy just to show the performance guesstimates to the users for the above-mentioned purposes).</p> <p>Any pointers...?</p>
789,540
3
0
null
2009-04-25 19:00:07.24 UTC
11
2015-11-09 13:33:32.397 UTC
null
null
null
null
95,810
null
1
56
mysql|sql-execution-plan
8,402
<p>EXPLAIN won't give you any indication of how long a query will take. At best you could use it to guess which of two queries might be faster, but unless one of them is obviously badly written then even that is going to be very hard.</p> <p>You should also be aware that if you're using sub-queries, even running EXPLAIN can be slow (almost as slow as the query itself in some cases).</p> <p>As far as I'm aware, MySQL doesn't provide any way to estimate the time a query will take to run. Could you log the time each query takes to run, then build an estimate based on the history of past similar queries?</p>
66,963,289
useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>
<p>I am trying to use <code>useRef</code> with TypeScript but am having some trouble.</p> <p>With my <code>RefObject</code> (I assume) I need to access <code>current</code>. (ie <code>node.current</code>)</p> <p>I have tried the following</p> <ul> <li><code>const node: RefObject&lt;HTMLElement&gt; = useRef(null);</code></li> <li><code>const node = useRef&lt;HTMLElement | null&gt;(null);</code></li> </ul> <p>but when I go to set the <code>ref</code> I am always told that X <code>is not assignable to type 'LegacyRef&lt;HTMLDivElement&gt; | undefined'.</code></p> <p><code>return &lt;div ref={ node }&gt;{ children }&lt;/div&gt;</code></p> <p>Edit: this should not be restricted to any one type of element so not just <code>HTMLDivElement | HTMLFormElement | HTMLInputElement</code></p> <p>Edit: This should work as an example</p> <pre><code>import React, { useRef, RefObject } from 'react'; function Test() { // const node = useRef(null); // const node: RefObject&lt;HTMLElement&gt; = useRef(null); const node = useRef&lt;HTMLElement | null&gt;(null); if ( node &amp;&amp; node.current &amp;&amp; node.current.contains() ){ console.log(&quot;current accessed&quot;)} return &lt;div ref={ node }&gt;&lt;/div&gt; } </code></pre>
66,963,712
6
0
null
2021-04-06 05:48:46.547 UTC
7
2022-07-22 19:33:33.537 UTC
2021-04-06 06:49:05.627 UTC
null
10,297,365
null
10,297,365
null
1
78
reactjs|typescript|tsx
53,715
<p>Just import React:</p> <pre class="lang-js prettyprint-override"><code>import React, { useRef } from 'react'; function Test() { const node = useRef&lt;HTMLDivElement&gt;(null); if ( node &amp;&amp; node.current &amp;&amp; node.current.contains() ){ console.log(&quot;current accessed&quot;)} return &lt;div ref={node}&gt;&lt;/div&gt; } </code></pre> <p>I made an update. Use <code>HTMLDivElement</code> as generic parameter instead of <code>HTMLElement | null</code>. Also, <code>contains</code> expects an argument.</p> <p><strong>UPDATE</strong> <code>useRef</code> expects generic argument of DOM element type. You don't need to use <code>| null</code> because <code>RefObject</code> already knows that <code>current</code> might be null.</p> <p>See next type:</p> <pre class="lang-js prettyprint-override"><code>interface RefObject&lt;T&gt; { readonly current: T | null } </code></pre> <p>TS &amp; React are smart enough to figure out that your ref might be null</p>
35,127,108
How to set "value" to input web element using selenium?
<p>I have element in my code that looks like this:</p> <pre><code>&lt;input id="invoice_supplier_id" name="invoice[supplier_id]" type="hidden" value=""&gt; </code></pre> <p>I want to set its value, so I created a web element with it's xpath:</p> <pre><code> val test = driver.findElements(By.xpath("""//*[@id="invoice_supplier_id"]""")) </code></pre> <p>but now I dont see an option to set the value...</p>
35,127,217
3
2
null
2016-02-01 09:35:59.87 UTC
4
2020-07-28 04:37:19.277 UTC
2016-02-01 12:39:48.013 UTC
null
3,642,244
null
3,412,425
null
1
42
java|selenium|xpath|selenium-webdriver|selenium-chromedriver
167,292
<p>Use <code>findElement</code> instead of <code>findElements</code></p> <pre><code>driver.findElement(By.xpath(&quot;//input[@id='invoice_supplier_id'])).sendKeys(&quot;your value&quot;); </code></pre> <p><strong>OR</strong></p> <pre><code>driver.findElement(By.id(&quot;invoice_supplier_id&quot;)).sendKeys(&quot;value&quot;, &quot;your value&quot;); </code></pre> <p><strong>OR using JavascriptExecutor</strong></p> <pre><code>WebElement element = driver.findElement(By.xpath(&quot;enter the xpath here&quot;)); // you can use any locator JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript(&quot;arguments[0].value='enter the value here';&quot;, element); </code></pre> <p><strong>OR</strong></p> <pre><code>(JavascriptExecutor) driver.executeScript(&quot;document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML=&quot;+ DesiredText); </code></pre> <p><strong>OR (in javascript)</strong></p> <pre><code>driver.findElement(By.xpath(&quot;//input[@id='invoice_supplier_id'])).setAttribute(&quot;value&quot;, &quot;your value&quot;) </code></pre> <p>Hope it will help you :)</p>
28,518,238
How can I use my own external class in CakePHP 3.0?
<p>I am creating an application in CakePHP 3.0, in this application I want to draw SVG graphs of data using a php class that I have written. What would be the proper way to go about using this class in my CakePHP 3 project?</p> <p>More specifically:</p> <ul> <li><p>What are the naming conventions? Do I need to use a specific namespace?</p></li> <li><p>Where do I put the file that contains the PHP class?</p></li> <li><p>How can I include it and use it in a controller or a view?</p></li> </ul>
28,527,683
1
2
null
2015-02-14 17:31:56.913 UTC
12
2018-01-22 18:56:49.593 UTC
2018-01-22 18:56:49.593 UTC
null
3,885,376
null
4,567,066
null
1
16
php|cakephp|cakephp-3.0
14,102
<p><strong>What are the naming conventions? Do I need to use a specific namespace?</strong></p> <p>Your SVG graphs class should have a namespaces. For namespaces you can see <a href="http://php.net/manual/en/language.namespaces.rationale.php" rel="noreferrer">http://php.net/manual/en/language.namespaces.rationale.php</a> </p> <p><strong>Where do I put the file that contains the PHP class?</strong></p> <ol> <li><p>Create a folder by author(here might be your name, as you are the author) in vendor</p></li> <li><p>Then create your class inside of it convention is vendor/$author/$package . You can read more <a href="http://book.cakephp.org/3.0/en/core-libraries/app.html#loading-vendor-files" rel="noreferrer">http://book.cakephp.org/3.0/en/core-libraries/app.html#loading-vendor-files</a></p></li> </ol> <p><strong>How can I include it and use it in a controller or a view?</strong></p> <p><em>a) To include:</em> </p> <p>require_once(ROOT .DS. 'Vendor' . DS . 'MyClass' . DS . 'MyClass.php'); </p> <p>(replace MyClass by your foldername and MyClass.php by your filename.php)</p> <p><em>b) To use it</em>:</p> <p>add <code>use MyClass\MyClass;</code> in your controller</p> <blockquote> <p><strong>For example</strong> I want to add MyClass in a controller. Steps that worked for me</p> </blockquote> <ol> <li>Creating vendor\MyClass folder</li> <li>Pasting MyClass.php in that folder</li> <li>adding <code>namespace MyClass;</code> at the top of MyClass.php</li> </ol> <p>MyClass.php have following code for example:</p> <pre><code>namespace MyClass; class MyClass { public $prop1 = "I'm a class property!"; public function setProperty($newval) { $this-&gt;prop1 = $newval; } public function getProperty() { return $this-&gt;prop1 . "&lt;br /&gt;"; } } </code></pre> <ol start="4"> <li><p>Adding <code>use MyClass\MyClass;</code> at the top of controller</p></li> <li><p>Then including it in my controller action. My action sample</p> <pre><code> public function test() { require_once(ROOT .DS. "Vendor" . DS . "MyClass" . DS . "MyClass.php"); $obj = new MyClass; $obj2 = new MyClass; echo $obj-&gt;getProperty(); echo $obj2-&gt;getProperty(); exit; } </code></pre></li> </ol>
20,428,732
How do I retrieve the version of Selenium currently installed, from Python
<p>The title says it all, I want to programmatically get the version of Selenium I have installed on my Python environment.</p>
20,428,836
4
0
null
2013-12-06 16:22:37.493 UTC
4
2021-02-19 20:21:42.193 UTC
null
null
null
null
661,517
null
1
19
python|selenium
55,710
<p>As simply as </p> <pre><code>&gt;&gt;&gt; import selenium &gt;&gt;&gt; selenium.__version__ '2.37.2' </code></pre> <p>or for command line:</p> <pre><code>$ python -c "import selenium; print(selenium.__version__)" 2.37.2 </code></pre>
6,208,348
How do i compare values of BigInteger to be used as a condition in a loop?
<p>I am trying to compare if the value of one BigInteger(base) is > the value of another BigInteger(prime) and if the value of 'a' is not equal to one. If value of a is not 1, it should break out of the loop. How should i compare them?</p> <pre><code> Random ran = new Random(); BigInteger prime = new BigInteger(16,ran); BigInteger base,a,one; one = new BigInteger("1"); for (int i = 0; i &lt; 65535; i++){ while (base&gt;prime){ base = new BigInteger(16,ran); } a = base.modPow(prime.subtract(one),prime); System.out.println("a: "+a); if (a != one){ break; } } </code></pre>
6,208,357
3
0
null
2011-06-01 22:10:48.41 UTC
4
2018-07-25 10:50:34.807 UTC
2011-06-01 22:16:09.583 UTC
null
139,010
null
780,242
null
1
21
java|biginteger
61,779
<p>You can compare them using <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html#compareTo%28java.math.BigInteger%29" rel="noreferrer"><code>BigInteger.compareTo(BigInteger)</code></a>.</p> <p>In your case, this would be <code>while (base.compareTo(prime) &gt; 0) {...}</code>.</p> <p>Also, your termination condition should be changed from <code>if (a != one)</code> to <code>if (!a.equals(one))</code> since two <code>BigInteger</code> variables with the same integer value are not necessarily referencing the same object (which is all that <code>==</code> and <code>!=</code> test).</p>
6,261,593
Custom ListView with Date as SectionHeader (Used custom SimpleCursorAdapter)
<p>I want to display ListView with Date as SectionHeader. </p> <p><strong>What i have :</strong> I am displaying ListView from sqlite database using custom SimpleCursorAdapter.</p> <p>My Custom SimpleCursorAdapter is :</p> <pre class="lang-java prettyprint-override"><code>public class DomainAdapter extends SimpleCursorAdapter{ private Cursor dataCursor; private LayoutInflater mInflater; public DomainAdapter(Context context, int layout, Cursor dataCursor, String[] from, int[] to) { super(context, layout, dataCursor, from, to); this.dataCursor = dataCursor; mInflater = LayoutInflater.from(context); } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.todo_row, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(R.id.label);//Task Title holder.text2 = (TextView) convertView.findViewById(R.id.label2);//Task Date holder.img = (ImageView) convertView.findViewById(R.id.task_icon); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } dataCursor.moveToPosition(position); int title = dataCursor.getColumnIndex("title"); String task_title = dataCursor.getString(title); int title_date = dataCursor.getColumnIndex("day"); String task_day = dataCursor.getString(title_date); int description_index = dataCursor.getColumnIndex("priority"); int priority = dataCursor.getInt(description_index); holder.text1.setText(task_title); holder.text2.setText(task_day); if(priority==1) holder.img.setImageResource(R.drawable.redbutton); else if(priority==2) holder.img.setImageResource(R.drawable.bluebutton); else if(priority==3)holder.img.setImageResource(R.drawable.greenbutton); else holder.img.setImageResource(R.drawable.redbuttonchecked); return convertView; } static class ViewHolder { TextView text1; TextView text2; ImageView img; } } </code></pre> <p><strong>Google Results so far :</strong></p> <p><a href="https://github.com/commonsguy/cwac-merge" rel="nofollow noreferrer">MergeAdapter</a></p> <p><a href="http://jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/" rel="nofollow noreferrer">Jeff Sharkey</a></p> <p><a href="http://code.google.com/p/android-amazing-listview/" rel="nofollow noreferrer">Amazing ListView</a></p> <p><a href="https://stackoverflow.com/questions/3841078/section-header-in-listview-not-show-correctly">SO Question</a></p> <p><strong>Problem :</strong> I want to display listview with Date as section headers. Ofcourse Date values come from sqlite database.</p> <p>Can anyone please guide me how can i achieve this task.</p> <p>Or Provide me a Sample Code or Exact(like) Code related to the same.</p> <p><strong>Edited</strong> According to Graham Borald's Answer (This works fine. However it was a quick fix.)</p> <pre class="lang-java prettyprint-override"><code>public class DomainAdapter extends SimpleCursorAdapter{ private Cursor dataCursor; private LayoutInflater mInflater; public DomainAdapter(Context context, int layout, Cursor dataCursor, String[] from, int[] to) { super(context, layout, dataCursor, from, to); this.dataCursor = dataCursor; mInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.tasks_row, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(R.id.label);//Task Title holder.text2 = (TextView) convertView.findViewById(R.id.label2);//Task Date holder.img = (ImageView) convertView.findViewById(R.id.taskImage); holder.sec_hr=(TextView) convertView.findViewById(R.id.sec_header); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } dataCursor.moveToPosition(position); int title = dataCursor.getColumnIndex("title"); String task_title = dataCursor.getString(title); int title_date = dataCursor.getColumnIndex("due_date"); String task_day = dataCursor.getString(title_date); int description_index = dataCursor.getColumnIndex("priority"); int priority = dataCursor.getInt(description_index); String prevDate = null; if (dataCursor.getPosition() &gt; 0 &amp;&amp; dataCursor.moveToPrevious()) { prevDate = dataCursor.getString(title_date); dataCursor.moveToNext(); } if(task_day.equals(prevDate)) { holder.sec_hr.setVisibility(View.GONE); } else { holder.sec_hr.setText(task_day); holder.sec_hr.setVisibility(View.VISIBLE); } holder.text1.setText(task_title); holder.text2.setText(task_day); if(priority==1) holder.img.setImageResource(R.drawable.redbutton); else if(priority==2) holder.img.setImageResource(R.drawable.bluebutton); else if(priority==3)holder.img.setImageResource(R.drawable.greenbutton); else holder.img.setImageResource(R.drawable.redbuttonchecked); return convertView; } static class ViewHolder { TextView text1; TextView text2; TextView sec_hr; ImageView img; } } </code></pre> <p><strong>Edited</strong> According to CommonsWare's Answer</p> <pre class="lang-java prettyprint-override"><code>public class DomainAdapter extends SimpleCursorAdapter{ private Cursor dataCursor; private TodoDbAdapter adapter; private LayoutInflater mInflater; boolean header; String last_day; public DomainAdapter(Context context, int layout, Cursor dataCursor, String[] from, int[] to) { super(context, layout, dataCursor, from, to); this.dataCursor = dataCursor; mInflater = LayoutInflater.from(context); header=true; adapter=new TodoDbAdapter(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; TitleHolder title_holder = null; if(getItemViewType(position)==1) { //convertView= mInflater.inflate(R.layout.todo_row, parent, false); if (convertView == null) { convertView = mInflater.inflate(R.layout.todo_row, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(R.id.label);//Task Title holder.text2 = (TextView) convertView.findViewById(R.id.label2);//Task Date holder.img = (ImageView) convertView.findViewById(R.id.task_icon); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } dataCursor.moveToPosition(position); int title = dataCursor.getColumnIndex("title"); String task_title = dataCursor.getString(title); int title_date = dataCursor.getColumnIndex("day"); String task_day = dataCursor.getString(title_date); int description_index = dataCursor.getColumnIndex("priority"); int priority = dataCursor.getInt(description_index); holder.text1.setText(task_title); holder.text2.setText(task_day); if(priority==1) holder.img.setImageResource(R.drawable.redbutton); else if(priority==2) holder.img.setImageResource(R.drawable.bluebutton); else if(priority==3)holder.img.setImageResource(R.drawable.greenbutton); else holder.img.setImageResource(R.drawable.redbuttonchecked); } else { if (convertView == null) { convertView = mInflater.inflate(R.layout.section_header, null); title_holder = new TitleHolder(); title_holder.datee = (TextView) convertView.findViewById(R.id.sec_header);//Task Title convertView.setTag(title_holder); } else { title_holder = (TitleHolder) convertView.getTag(); } dataCursor.moveToPosition(position); int title_date = dataCursor.getColumnIndex("day"); String task_day = dataCursor.getString(title_date); title_holder.datee.setText(task_day); } return convertView; } static class ViewHolder { TextView text1; TextView text2; ImageView img; } static class TitleHolder{ TextView datee; } @Override public int getCount() { return dataCursor.getCount()+1; //just for testing i took no. of headers=1 } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { dataCursor.moveToPosition(position); **Long id=dataCursor.getLong(position);** Cursor date=adapter.fetchTodo(id); int title_date = date.getColumnIndex("day"); String task_day = date.getString(title_date); Log.i("tag",task_day); if(last_day.equals(task_day)) return 1;//Display Actual Row else { last_day=task_day;//Displaying Header return 0; } } /* @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view; if(getItemViewType(cursor.getPosition())==1) view= mInflater.inflate(R.layout.todo_row, parent, false); else view=mInflater.inflate(R.layout.section_header,parent, false); return view; } @Override public void bindView(View convertView, Context context, Cursor cursor) { long id = cursor.getPosition(); }*/ } </code></pre> <p>I am getting <em>Null Pointer Exception</em> at line : <code>Cursor date=adapter.fetchTodo(id);</code> Seems that Cursor is not getting any data.</p>
6,276,697
3
1
null
2011-06-07 06:54:01.593 UTC
27
2018-05-17 17:17:25.44 UTC
2018-05-17 17:17:25.44 UTC
null
6,512,057
null
610,940
null
1
27
android|sqlite|listview|android-custom-view
20,049
<p>By far the simplest way to do this is to embed the date header view <em>in every item</em>. Then, all you need to do in <code>bindView</code> is compare the previous row's date to this row's date, and hide the date if it's the same. Something like this:</p> <pre class="lang-java prettyprint-override"><code> String thisDate = cursor.getString(dateIndex); String prevDate = null; // get previous item's date, for comparison if (cursor.getPosition() &gt; 0 &amp;&amp; cursor.moveToPrevious()) { prevDate = cursor.getString(dateIndex); cursor.moveToNext(); } // enable section heading if it's the first one, or // different from the previous one if (prevDate == null || !prevDate.equals(thisDate)) { dateSectionHeaderView.setVisibility(View.VISIBLE); } else { dateSectionHeaderView.setVisibility(View.GONE); } </code></pre>
5,875,646
Database schema for ACL
<p>I want to create a schema for a ACL; however, I'm torn between a couple of ways of implementing it.</p> <p>I am pretty sure I don't want to deal with cascading permissions as that leads to a lot of confusion on the backend and for site administrators.</p> <p>I think I can also live with users only being in one role at a time. A setup like this will allow roles and permissions to be added as needed as the site grows without affecting existing roles/rules.</p> <p>At first I was going to normalize the data and have three tables to represent the relations.</p> <pre><code>ROLES { id, name } RESOURCES { id, name } PERMISSIONS { id, role_id, resource_id } </code></pre> <p>A query to figure out whether a user was allowed somewhere would look like this:</p> <pre><code>SELECT id FROM resources WHERE name = ? SELECT * FROM permissions WHERE role_id = ? AND resource_id = ? ($user_role_id, $resource-&gt;id) </code></pre> <p>Then I realized that I will only have about 20 resources, each with up to 5 actions (create, update, view, etc..) and perhaps another 8 roles. This means that I can exercise blatant disregard for data normalization as I will never have more than a couple of hundred possible records.</p> <p>So perhaps a schema like this would make more sense.</p> <pre><code>ROLES { id, name } PERMISSIONS { id, role_id, resource_name } </code></pre> <p>which would allow me to lookup records in a single query</p> <pre><code>SELECT * FROM permissions WHERE role_id = ? AND permission = ? ($user_role_id, 'post.update') </code></pre> <p><strong>So which of these is more correct? Are there other schema layouts for ACL?</strong></p>
5,950,425
3
2
null
2011-05-03 20:58:09.98 UTC
24
2012-10-02 17:45:01.847 UTC
2012-10-02 17:45:01.847 UTC
null
1,312,971
null
99,923
null
1
28
mysql|acl
34,081
<p>In my experience, the real question mostly breaks down to whether or not any amount of user-specific access-restriction is going to occur.</p> <p>Suppose, for instance, that you're designing the schema of a community and that you allow users to toggle the visibility of their profile.</p> <p>One option is to stick to a public/private profile flag and stick to broad, pre-emptive permission checks: 'users.view' (views public users) vs, say, 'users.view_all' (views all users, for moderators).</p> <p>Another involves more refined permissions, you might want them to be able to configure things so they can make themselves (a) viewable by all, (b) viewable by their hand-picked buddies, (c) kept private entirely, and perhaps (d) viewable by all except their hand-picked bozos. In this case you need to store owner/access-related data for individual rows, and you'll need to heavily abstract some of these things in order to avoid materializing the transitive closure of a dense, oriented graph.</p> <p>With either approach, I've found that added complexity in role editing/assignment is offset by the resulting ease/flexibility in <em>assigning</em> permissions to individual pieces of data, and that the following to worked best:</p> <ol> <li>Users can have multiple roles</li> <li>Roles and permissions merged in the same table with a flag to distinguish the two (useful when editing roles/perms)</li> <li>Roles can assign other roles, and roles and perms can assign permissions (but permissions cannot assign roles), from within the same table.</li> </ol> <p>The resulting oriented graph can then be pulled in two queries, built once and for all in a reasonable amount of time using whichever language you're using, and cached into Memcache or similar for subsequent use.</p> <p>From there, pulling a user's permissions is a matter of checking which roles he has, and processing them using the permission graph to get the final permissions. Check permissions by verifying that a user has the specified role/permission or not. And then run your query/issue an error based on that permission check.</p> <p>You can extend the check for individual nodes (i.e. <code>check_perms($user, 'users.edit', $node)</code> for "can edit this node" vs <code>check_perms($user, 'users.edit')</code> for "may edit a node") if you need to, and you'll have something very flexible/easy to use for end users.</p> <p>As the opening example should illustrate, be wary of steering too much towards row-level permissions. The performance bottleneck is less in checking an individual node's permissions than it is in pulling a list of valid nodes (i.e. only those that the user can view or edit). I'd advise against anything beyond flags and user_id fields within the rows themselves if you're not (very) well versed in query optimization.</p>
6,029,497
Can't Add A View to EF Data Model
<p>I have a view that I am trying to add to my ADO.NET Entity Data Model. Every time I try to Update From Database, and check the view, it refreshes everything else, but does not add the view.<br/>I get no error message or output, so I have no idea what is wrong with the view. Other views are no problem. Am I missing something, is there a way to turn error messages on? Visual Studio 2008 sp1</p> <p><strong>Update</strong>: I found this link but the problem didn't solve with these solutions. <a href="http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/93ad4730-78ec-4aac-bfc8-500231b792c1" rel="noreferrer">MSDN Forum</a></p> <p><strong>Update:</strong> The view that i can't add it will query from another view.</p> <p><strong>Update:</strong> Help</p> <pre><code>WITH cte AS (SELECT dbo.TBL_Gharardad.PK_Shenase, dbo.TBL_Gharardad.FK_NoeKhedmat AS NoeKhedmatId, dbo.TBL_NoeKhedmat.NoeKhedmat AS [نوع خدمت], dbo.TBL_Gharardad.OnvaneKhedmat AS [عنوان خدمت], dbo.TBL_Gharardad.MahaleEraeieKhedmat AS [محل ارائه خدمت], dbo.TBL_Gharardad.FK_NahveieTaieeneBarande AS NahveieTaeeneBararndeId, dbo.TBL_NahveieTaieeneBarande.NahveieTaieeneBarande AS [نحوه تعيين برنده], dbo.TBL_Gharardad.TarikheShorooeGharardad_Jalali AS [تاريخ شروع قرارداد], dbo.TBL_Gharardad.TarikhePayaneGharardad_Jalali AS [تاريخ پايان قرارداد], dbo.TBL_Gharardad.FK_VahedeArz AS VahedeArzId, dbo.TBL_VahedeArz.VahedeArz AS [واحد ارز], dbo.TBL_Gharardad.MablagheDariaftiKol AS [مبلغ دريافتي کل], dbo.TBL_Gharardad.MablaghePardakhtieKol AS [مبلغ پرداختي کل], dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت کارفرما], 100 - dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت پيمانکار], dbo.TBL_Gharardad.TedadNirooyeMard AS [تعداد نيروي مرد], dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد نيروي زن], dbo.TBL_Gharardad.TedadNirooyeMard + dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد کل نيروها], dbo.TBL_Gharardad.FK_TarafeGharardad AS TarafeGharardadId, CASE TBL_TarafeGharardad.Hoghooghi WHEN 0 THEN ISNULL(TBL_TarafeGharardad.Naam, ' ') + ' ' + ISNULL(TBL_TarafeGharardad.NaameKhanevadegi, ' ') ELSE TBL_TarafeGharardad.NameSherkat END AS [طرف قرارداد], dbo.TBL_Gharardad.FK_VahedeVagozarKonande AS VahedeVagozarKonandeId, dbo.TBL_VahedeVagozarKonande.VahedeVagozarKonande AS [واحد واگذار کننده], dbo.TBL_Gharardad.ShomareGharardad AS [شماره قرارداد], dbo.TBL_Gharardad.TarikheGharardad_Jalali AS [تاريخ قرارداد], CASE VaziateGharardad WHEN 0 THEN N'لغو شده' WHEN 1 THEN N'ثبت اوليه' WHEN 2 THEN N'فسخ' WHEN 3 THEN N'ثبت نهايي ' WHEN 4 THEN N' جاري ' WHEN 5 THEN N'تمام شده ' WHEN 6 THEN N' متمم ' END AS [وضعيت قرارداد], dbo.TBL_NoeMoamele.NoeMoamele AS [نوع معامله] FROM dbo.TBL_Gharardad INNER JOIN dbo.TBL_NoeKhedmat ON dbo.TBL_Gharardad.FK_NoeKhedmat = dbo.TBL_NoeKhedmat.PK_Id INNER JOIN dbo.TBL_NahveieTaieeneBarande ON dbo.TBL_Gharardad.FK_NahveieTaieeneBarande = dbo.TBL_NahveieTaieeneBarande.PK_Id INNER JOIN dbo.TBL_VahedeArz ON dbo.TBL_Gharardad.FK_VahedeArz = dbo.TBL_VahedeArz.PK_Id INNER JOIN dbo.TBL_TarafeGharardad ON dbo.TBL_Gharardad.FK_TarafeGharardad = dbo.TBL_TarafeGharardad.PK_Id INNER JOIN dbo.TBL_VahedeVagozarKonande ON dbo.TBL_Gharardad.FK_VahedeVagozarKonande = dbo.TBL_VahedeVagozarKonande.PK_Id INNER JOIN dbo.TBL_NoeMoamele ON dbo.TBL_Gharardad.FK_NoeMoamele = dbo.TBL_NoeMoamele.PK_Id) SELECT v_Gharardad.شناسه, v_Gharardad.NoeKhedmatId, v_Gharardad.[نوع خدمت], v_Gharardad.[عنوان خدمت], v_Gharardad.[محل ارائه خدمت], v_Gharardad.NahveieTaeeneBararndeId, v_Gharardad.[نحوه تعيين برنده], v_Gharardad.[تاريخ شروع قرارداد], v_Gharardad.[تاريخ پايان قرارداد], v_Gharardad.VahedeArzId, v_Gharardad.[واحد ارز], v_Gharardad.[مبلغ دريافتي کل], v_Gharardad.[مبلغ پرداختي کل], v_Gharardad.[درصد مشارکت کارفرما], v_Gharardad.[درصد مشارکت پيمانکار], v_Gharardad.[تعداد نيروي مرد], v_Gharardad.[تعداد نيروي زن], v_Gharardad.[تعداد کل نيروها], v_Gharardad.TarafeGharardadId, v_Gharardad.[طرف قرارداد], v_Gharardad.VahedeVagozarKonandeId, v_Gharardad.[واحد واگذار کننده], v_Gharardad.[شماره قرارداد], v_Gharardad.[تاريخ قرارداد], v_Gharardad.[وضعيت قرارداد], v_Gharardad.[نوع معامله] FROM dbo.TBL_Gharardad AS TBL_Gharardad_3 INNER JOIN dbo.v_GharardadRecords AS v_Gharardad ON v_Gharardad.شناسه = TBL_Gharardad_3.PK_Shenase WHERE (TBL_Gharardad_3.FK_GharardadeAsli IS NULL) AND (TBL_Gharardad_3.PK_Shenase NOT IN (SELECT FK_GharardadeAsli FROM dbo.TBL_Gharardad AS TBL_Gharardad_2 WHERE (FK_GharardadeAsli IS NOT NULL))) UNION SELECT sub.FK_GharardadeAsli AS شناسه, cte_2.NoeKhedmatId, cte_2.[نوع خدمت], cte_2.[عنوان خدمت], cte_2.[محل ارائه خدمت], cte_2.NahveieTaeeneBararndeId, cte_2.[نحوه تعيين برنده], cte_2.[تاريخ شروع قرارداد], cte_2.[تاريخ پايان قرارداد], cte_2.VahedeArzId, cte_2.[واحد ارز], cte_2.[مبلغ دريافتي کل], cte_2.[مبلغ پرداختي کل], cte_2.[درصد مشارکت کارفرما], cte_2.[درصد مشارکت پيمانکار], cte_2.[تعداد نيروي مرد], cte_2.[تعداد نيروي زن], cte_2.[تعداد کل نيروها], cte_2.TarafeGharardadId, cte_2.[طرف قرارداد], cte_2.VahedeVagozarKonandeId, cte_2.[واحد واگذار کننده], cte_2.[شماره قرارداد], cte_2.[تاريخ قرارداد], cte_2.[وضعيت قرارداد], cte_2.[نوع معامله] FROM dbo.v_GharardadRecords AS cte_2 INNER JOIN (SELECT FK_GharardadeAsli, MAX(PK_Shenase) AS PK_Shenase, MAX(TarikheSabt) AS TarikheSabt FROM dbo.TBL_Gharardad AS TBL_Gharardad_1 WHERE (FK_GharardadeAsli IS NOT NULL) GROUP BY FK_GharardadeAsli) AS sub ON sub.PK_Shenase = cte_2.شناسه </code></pre>
6,031,708
14
7
null
2011-05-17 10:28:01.503 UTC
4
2021-06-12 01:02:53.617 UTC
2019-04-02 08:09:31.41 UTC
null
4,390,133
null
726,631
null
1
37
entity-framework|visual-studio-2008-sp1
35,114
<p>I have experienced this same behaviour when I try to add a view that doesn't select a primary key from another table. (Like Ladislav Mrnka has commented)</p> <p>My strategy for solving this is to reduce the view to as simple as possible (1 column) and try and to get it added. Once you have it added to the model, slowly bring in more columns and refresh the model to make sure the view is still there. You can usually identify what section of the view is giving EDM problems.</p>
5,839,359
java.lang.OutOfMemoryError: GC overhead limit exceeded
<p>I am getting this error in a program that creates several (hundreds of thousands) HashMap objects with a few (15-20) text entries each. These Strings have all to be collected (without breaking up into smaller amounts) before being submitted to a database.</p> <p>According to Sun, the error happens "if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown.".</p> <p>Apparently, one could use the command line to pass arguments to the JVM for</p> <ul> <li>Increasing the heap size, via "-Xmx1024m" (or more), or </li> <li>Disabling the error check altogether, via "-XX:-UseGCOverheadLimit".</li> </ul> <p>The first approach works fine, the second ends up in another java.lang.OutOfMemoryError, this time about the heap.</p> <p>So, question: is there any programmatic alternative to this, for the particular use case (i.e., several small HashMap objects)? If I use the HashMap clear() method, for instance, the problem goes away, but so do the data stored in the HashMap! :-)</p> <p>The issue is also discussed in a <a href="https://stackoverflow.com/questions/1393486/what-means-the-error-message-java-lang-outofmemoryerror-gc-overhead-limit-excee">related topic in StackOverflow.</a></p>
5,839,392
16
4
null
2011-04-30 03:49:33.197 UTC
92
2021-08-10 14:17:56.853 UTC
2021-08-10 14:17:56.853 UTC
null
5,459,839
null
834,316
null
1
322
java|hashmap|heap-memory|g1gc
616,483
<p>You're essentially running out of memory to run the process smoothly. Options that come to mind:</p> <ol> <li>Specify more memory like you mentioned, try something in between like <code>-Xmx512m</code> first</li> <li>Work with smaller batches of <code>HashMap</code> objects to process at once if possible</li> <li>If you have a lot of duplicate strings, use <a href="http://java.sun.com/javase/7/docs/api/java/lang/String.html#intern()" rel="noreferrer"><code>String.intern()</code></a> on them before putting them into the <code>HashMap</code></li> <li>Use the <a href="http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html#HashMap%28int,%20float%29" rel="noreferrer"><code>HashMap(int initialCapacity, float loadFactor)</code></a> constructor to tune for your case</li> </ol>
39,226,928
React - adding class to children components
<p>im using react and I have a component that simply needs to render the children and add them a class according to a condition. Whats the best way of doing it?</p>
39,549,768
5
1
null
2016-08-30 11:59:59.85 UTC
5
2019-12-21 21:44:31.977 UTC
null
null
null
null
3,674,127
null
1
30
reactjs
41,328
<p>I figured it out a week ago, this is what I wanted :</p> <pre><code>export default class ContainerComponent extends React.Component { constructor(props) { super(props); this.modifyChildren = this.modifyChildren.bind(this); } modifyChildren(child) { const className = classNames( child.props.className, {...otherClassses} ); const props = { className }; return React.cloneElement(child, props); } render() { return (&lt;div&gt; {React.Children.map(this.props.children, child =&gt; this.modifyChildren(child))} &lt;/div&gt;); } } </code></pre>
39,342,195
Intercept/handle browser's back button in React-router?
<p>I'm using Material-ui's Tabs, which are controlled and I'm using them for (React-router) Links like this:</p> <pre><code> &lt;Tab value={0} label="dashboard" containerElement={&lt;Link to="/dashboard/home"/&gt;}/&gt; &lt;Tab value={1} label="users" containerElement={&lt;Link to="/dashboard/users"/&gt;} /&gt; &lt;Tab value={2} label="data" containerElement={&lt;Link to="/dashboard/data"/&gt;} /&gt; </code></pre> <p>If I'm currenlty visting dashboard/data and I click browser's back button I go (for example) to dashboard/users but the highlighted Tab still stays on dashboard/data (value=2)</p> <p>I can change by setting state, but I don't know how to handle the event when the browser's back button is pressed?</p> <p>I've found this:</p> <pre><code>window.onpopstate = this.onBackButtonEvent; </code></pre> <p>but this is called each time state is changed (not only on back button event)</p>
39,363,278
16
1
null
2016-09-06 06:44:06.363 UTC
27
2021-10-13 18:43:13.783 UTC
2016-09-07 07:05:07.853 UTC
null
6,772,899
null
6,772,899
null
1
89
javascript|reactjs|react-router|material-ui
186,047
<p>here is how I ended up doing it:</p> <pre><code>componentDidMount() { this._isMounted = true; window.onpopstate = ()=&gt; { if(this._isMounted) { const { hash } = location; if(hash.indexOf('home')&gt;-1 &amp;&amp; this.state.value!==0) this.setState({value: 0}) if(hash.indexOf('users')&gt;-1 &amp;&amp; this.state.value!==1) this.setState({value: 1}) if(hash.indexOf('data')&gt;-1 &amp;&amp; this.state.value!==2) this.setState({value: 2}) } } } </code></pre> <p>thanks everybody for helping lol</p>
39,019,857
3 ways to flatten a list of lists. Is there a reason to prefer one of them?
<p>Assume we have a list as follows. <code>CoreResult</code> has a field of type <code>List&lt;Double&gt;</code>.</p> <pre><code>final List&lt;CoreResult&gt; list = new LinkedList&lt;&gt;(SOME_DATA); </code></pre> <p>The objective is to flatten the list after extracting that specific field from each <code>CoreResult</code> object. Here are 3 possible options. Is any one of them preferable to the others?</p> <p><strong>Option 1</strong>: extract a field via <code>map()</code> and flatten inside collector</p> <pre><code>final List&lt;Double&gt; A = list.stream().map(CoreResult::getField) .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll); </code></pre> <p><strong>Option 2</strong>: extract a field via <code>map()</code>, flatten via <code>flatMap()</code>, simple collector</p> <pre><code>final List&lt;Double&gt; B = list.stream().map(CoreResult::getField) .flatMap(Collection::stream).collect(Collectors.toList()); </code></pre> <p><strong>Option 3</strong>: extract a field and flatten in one go via <code>flatMap()</code>, simple collector</p> <pre><code>final List&lt;Double&gt; C = list.stream().flatMap( x -&gt; x.getField().stream()).collect(Collectors.toList()); </code></pre> <p>Would the answer be different if there was no need to extract any field from CoreResult, and instead one wanted to simply flatten a <code>List&lt;List&lt;Double&gt;&gt;</code>?</p>
39,019,983
3
1
null
2016-08-18 13:44:58.313 UTC
5
2016-08-18 13:50:08.283 UTC
null
null
null
null
478,116
null
1
25
java|java-8|java-stream
44,501
<p>I'm not sure about the performance of each one, but an important aspect of the builder pattern utilized by java streams is that it allows for <strong>readability</strong>. I personally find the option 2 to be the most readable. Option 3 is good, too. I would avoid option one because it kind of "cheats" the flattening of the collection.</p> <p>Put each method on its own line and determine which is the most intuitive to read. I rather like the second one:</p> <pre><code>final List&lt;Double&gt; B = list.stream() .map(CoreResult::getField) .flatMap(Collection::stream) .collect(Collectors.toList()); </code></pre>
44,165,629
Pandas pivot table for multiple columns at once
<p>Let's say I have a DataFrame:</p> <pre><code> nj ptype wd wpt 0 2 1 2 1 1 3 2 1 2 2 1 1 3 1 3 2 2 3 3 4 3 1 2 2 </code></pre> <p>I would like to aggregate this data using <code>ptype</code> as the index like so:</p> <pre><code> nj wd wpt 1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ptype 1 1 1 1 0 2 1 2 1 0 2 0 1 1 1 0 1 0 1 1 </code></pre> <p>You could build each one of the top level columns for the final value by creating a pivot table with <code>aggfunc='count'</code> and then concatenating them all, like so:</p> <pre><code>nj = df.pivot_table(index='ptype', columns='nj', aggfunc='count').ix[:, 'wd'] wpt = df.pivot_table(index='ptype', columns='wpt', aggfunc='count').ix[:, 'wd'] wd = df.pivot_table(index='ptype', columns='wd', aggfunc='count').ix[:, 'nj'] out = pd.concat([nj, wd, wpt], axis=1, keys=['nj', 'wd', 'wpt']).fillna(0) out.columns.names = [None, None] print(out) nj wd wpt 1 2 3 1 2 3 1 2 3 ptype 1 1.0 1.0 1.0 0.0 2.0 1.0 2.0 1.0 0.0 2 0.0 1.0 1.0 1.0 0.0 1.0 0.0 1.0 1.0 </code></pre> <p>But I really dislike this and it feels wrong. I would like to know if there is a way to do this in a simpler fashion preferably with a builtin method. Thanks in advance!</p>
44,165,817
3
0
null
2017-05-24 18:04:57.787 UTC
8
2019-11-19 16:48:21.987 UTC
null
null
null
null
5,061,557
null
1
11
python|pandas|pivot-table|multi-index
74,479
<p>Instead of doing it in one step, you can do the aggregation firstly and then <code>pivot</code> it using <code>unstack</code> method:</p> <pre><code>(df.set_index('ptype') .groupby(level='ptype') # to do the count of columns nj, wd, wpt against the column ptype using # groupby + value_counts .apply(lambda g: g.apply(pd.value_counts)) .unstack(level=1) .fillna(0)) # nj wd wpt # 1 2 3 1 2 3 1 2 3 #ptype #1 1.0 1.0 1.0 0.0 2.0 1.0 2.0 1.0 0.0 #2 0.0 1.0 1.0 1.0 0.0 1.0 0.0 1.0 1.0 </code></pre> <hr> <p>Another option to avoid using <code>apply</code> method:</p> <pre><code>(df.set_index('ptype').stack() .groupby(level=[0,1]) .value_counts() .unstack(level=[1,2]) .fillna(0) .sort_index(axis=1)) </code></pre> <p><a href="https://i.stack.imgur.com/XhjFZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XhjFZ.png" alt="enter image description here"></a></p> <p><em>Naive Timing</em> on the sample data:</p> <p>Original solution:</p> <pre><code>%%timeit nj = df.pivot_table(index='ptype', columns='nj', aggfunc='count').ix[:, 'wd'] wpt = df.pivot_table(index='ptype', columns='wpt', aggfunc='count').ix[:, 'wd'] wd = df.pivot_table(index='ptype', columns='wd', aggfunc='count').ix[:, 'nj'] out = pd.concat([nj, wd, wpt], axis=1, keys=['nj', 'wd', 'wpt']).fillna(0) out.columns.names = [None, None] # 100 loops, best of 3: 12 ms per loop </code></pre> <p>Option one:</p> <pre><code>%%timeit (df.set_index('ptype') .groupby(level='ptype') .apply(lambda g: g.apply(pd.value_counts)) .unstack(level=1) .fillna(0)) # 100 loops, best of 3: 10.1 ms per loop </code></pre> <p>Option two:</p> <pre><code>%%timeit (df.set_index('ptype').stack() .groupby(level=[0,1]) .value_counts() .unstack(level=[1,2]) .fillna(0) .sort_index(axis=1)) # 100 loops, best of 3: 4.3 ms per loop </code></pre>
21,909,860
access denied on nginx and php
<p>Using nginx web server and php. nginx is working, I see 'Welcome to nginx!' but I get 'access denied' when trying to access a php page. I also installed php-fastcgi.</p> <p>Here is my nginx default conf: </p> <pre><code># redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root /usr/share/nginx/html; fastcgi_index index.php; fastcgi_pass unix:/var/run/php5-fpm.sock; include fastcgi_params; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } </code></pre> <p>I activited <code>security.limit_extensions = .php .php3 .php4 .php5 .html</code> and <code>listen = /var/run/php5-fpm.sock</code> in /etc/php-fpm.d/www.conf and <code>cgi.fix_pathinfo = 0</code> in /etc/php5/fpm/php.ini</p> <p>I restarted nginx and php5-fpm.</p> <p>Thanks for helping.</p>
24,243,627
4
0
null
2014-02-20 13:53:08.74 UTC
2
2018-12-21 14:18:35.343 UTC
2014-02-20 13:58:16.587 UTC
null
1,398,425
null
2,518,839
null
1
11
php|nginx
48,632
<p>Do like this where you have your secondary location</p> <pre><code>location / { try_files $uri $uri/ =404; root /path/to/your/www; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } </code></pre> <p>These 2 parameters are the magic sauce:</p> <pre><code>fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; </code></pre>
42,245,587
Get month name of last month using moment
<p>I use the following code to get startDate and endDate of the last months.</p> <pre><code>// Previous month var startDateMonthMinusOne = moment().subtract(1, "month").startOf("month").unix(); var endDateMonthMinusOne = moment().subtract(1, "month").endOf("month").unix(); // Previous month - 1 var startDateMonthMinusOne = moment().subtract(2, "month").startOf("month").unix(); var endDateMonthMinusOne = moment().subtract(2, "month").endOf("month").unix(); </code></pre> <p>How can i do to get also the month name ? (January, February, ...) </p>
42,245,774
2
1
null
2017-02-15 09:37:30.92 UTC
4
2018-02-02 10:47:36.287 UTC
null
null
null
null
1,076,026
null
1
48
javascript|momentjs
116,800
<p>Instead of <code>unix()</code> use the <code>format()</code> function to format the datetime using the <code>MMMM</code> format specifier for the month name.</p> <pre><code>var monthMinusOneName = moment().subtract(1, "month").startOf("month").format('MMMM'); </code></pre> <p>See the chapter <a href="https://momentjs.com/docs/#/displaying/format/" rel="noreferrer">Display / Format in the documentation</a></p>
33,462,532
Using Resolve In Angular2 Routes
<p>In Angular 1 my config looks like this:</p> <pre><code>$routeProvider .when("/news", { templateUrl: "newsView.html", controller: "newsController", resolve: { message: function(messageService){ return messageService.getMessage(); } } }) </code></pre> <p>How to use resolve in Angular2?</p>
42,616,484
5
2
null
2015-11-01 13:15:52.55 UTC
15
2017-11-06 15:26:42.127 UTC
2017-11-06 15:26:42.127 UTC
null
4,720,935
null
5,512,553
null
1
32
angular|angular2-routing
26,192
<p>@AndréWerlang's answer was good, but if you want the resolved data on the page to change <em>when the route parameter changes</em>, you need to:</p> <p><strong>Resolver:</strong></p> <pre><code>@Injectable() export class MessageResolver implements Resolve&lt;Message&gt; { constructor(private messageService: MessageService, private router: Router) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable&lt;Message&gt; { const id = +route.params['id']; return this.messageService.getById(id); } } </code></pre> <p><strong>Your component:</strong></p> <pre><code>ngOnInit() { this.route.data.subscribe((data: { message: Message }) =&gt; { this.message = data.message; }); } </code></pre>
9,081,900
Reference coordinate system changes between OpenCV, OpenGL and Android Sensor
<p>I am working with <strong>OpenCV</strong>, <strong>Android</strong> and <strong>OpenGL</strong> for an Augmented Reality project. As far as I know the coordintate system in OpenGL is</p> <p><img src="https://i.stack.imgur.com/mzEZy.jpg" alt="enter image description here"></p> <p>The OpenCV coordinate system is:</p> <p><img src="https://i.stack.imgur.com/4iFEV.png" alt="enter image description here"></p> <p>When combining these devices with android sensors how can I do the coordinate system conversions and [R|t] matrix conversion? Is there a good tutorial or documentation were all of this conffusing stuff is explained?</p>
9,082,349
1
0
null
2012-01-31 15:12:54.347 UTC
9
2012-01-31 16:46:51.077 UTC
2012-01-31 16:46:51.077 UTC
null
44,729
null
744,859
null
1
18
opengl-es|opencv|rotation|android-sensors|coordinate-transformation
12,312
<p>If you look at the picture, then you see, that the both coordinate systems have the same handednes, but the OpenCV one is rotated by pi around the x axis. This can be represented by the following rotation matrix:</p> <pre><code> 1 0 0 0 -1 0 0 0 -1 </code></pre>