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
1,023,768
Sieve of Atkin explanation
<p>I am doing a project at the moment and I need an efficient method for calculating prime numbers. I have used the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">sieve of Eratosthenes</a> but, I have been searching around and have found that the <a href="http://en.wikipedia.org/wiki/Sieve_of_Atkin" rel="noreferrer">sieve of Atkin</a> is a more efficient method. I have found it difficult to find an explanation (that I have been able to understand!) of this method. How does it work? Example code (preferably in C or python) would be brilliant.</p> <p><em>Edit:</em> thanks for your help, the only thing that I still do not understand is what the x and y variables are referring to in the pseudo code. Could someone please shed some light on this for me?</p>
1,023,777
5
3
null
2009-06-21 12:13:35.36 UTC
9
2019-01-04 09:04:04.283 UTC
2010-10-05 23:08:50.43 UTC
Roger Pate
null
null
47,204
null
1
22
primes|sieve-of-eratosthenes|sieve-of-atkin
21,470
<p>The <a href="http://en.wikipedia.org/wiki/Sieve_of_atkin" rel="nofollow noreferrer">wiki page</a> is always a good place to start, since it explains the algorithm in full and provides commented pseudocode. (N.B. There's a lot of detail, and since the wiki website is reliably up, I won't quote it here.)</p> <p>For references in the specific languages you mentioned:</p> <ul> <li><a href="http://cr.yp.to/primegen.html" rel="nofollow noreferrer">C implementation</a> (optimised)</li> <li><a href="https://github.com/mccricardo/sieve_of_atkin" rel="nofollow noreferrer">Python implementation</a></li> </ul> <p>Hope that helps.</p>
888,965
What methods are available to stop multiple postbacks of a form in ASP.NET MVC?
<p>A common web problem is where a user clicks the submit button of a form multiple times so the server processes the form more than once. This can also happen when a user hits the back button having submitted a form and so it gets processed again.</p> <p>What is the best way of stopping this from happening in ASP.NET MVC?</p> <p>Possibilities as I see it are:</p> <ol> <li>Disable the button after submit - this gets round the multiple clicks but not the navigation</li> <li>Have the receiving action redirect immediately - browsers seem to leave these redirects out of the history</li> <li>Place a unique token in the session and on the form - if they match process the form - if not clear the form for a fresh submit</li> </ol> <p>Are there more?</p> <p>Are there some specific implementations of any of these?</p> <p>I can see the third option being implemented as an ActionFilter with a HtmlHelper extension in a similar manner to the anti-forgery stuff.</p> <p>Looking forward to hearing from you MVC'ers out there.</p>
889,739
6
0
null
2009-05-20 16:29:59.383 UTC
18
2015-08-02 04:47:42.673 UTC
null
null
null
null
94,898
null
1
21
asp.net-mvc|postback|submit|action-filter
8,129
<p>Often people overlook the most conventional way to handle this which is to use <strong>nonce keys</strong>.</p> <p>You can use <strong><a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="noreferrer">PRG</a></strong> as others have mentioned but the downside with PRG is that it doesn't solve the double-click problem, it requires an extra trip to the server for the redirect, and since the last step is a GET request you don't have direct access to the data that was just posted (though it could be passed as a query param or maintained on the server side).</p> <p>I like the Javascript solution because it works <em>most</em> of the time.</p> <p><strong>Nonce keys</strong> however, work all the time. The nonce key is a random unique GUID generated by the server (also saved in the database) and embedded in the form. When the user POSTs the form, the nonce key also gets posted. As soon as a POST comes in to the server, the server verifies the nonce key exists in its database. If it does, the server deletes the key from the database and processes the form. Consequently if the user POSTs twice, the second POST won't be processed because the nonce key was deleted after processing the first POST.</p> <p>The nonce key has an added advantage in that it brings additional security by preventing <a href="http://en.wikipedia.org/wiki/Replay_attack" rel="noreferrer">replay attacks</a> (a man in the middle sniffs your HTTP request and then replays it to the server which treats it as a legitimate).</p>
625,241
How can I use OpenOffice in server mode as a multithreaded service?
<p>What is the experience of working with <a href="http://en.wikipedia.org/wiki/OpenOffice.org" rel="noreferrer">OpenOffice</a> in server mode? I know OpenOffice is not multithreaded and now I need to use its services in our server.<br> What can I do to overcome this problem? </p> <p>I'm using Java.</p>
628,069
6
2
null
2009-03-09 06:53:22.777 UTC
13
2018-06-14 12:18:55.11 UTC
2010-03-06 19:29:19.613 UTC
Dave Webb
63,550
null
63,898
null
1
23
java|multithreading|openoffice.org
24,977
<p>Yes, I am using OpenOffice as a document conversion server.</p> <p>Unfortunately, the solution to your problem is to spawn a pool of OpenOffice processes.</p> <p>The <a href="http://jodconverter.svn.sourceforge.net/viewvc/jodconverter/branches/3.0.x-200801-commons-pool/" rel="noreferrer">commons-pool</a> branch of JODConverter (before it moved to <code>code.google.com</code>) implemented this out-of-the-box for you.</p>
914,951
Show and hide divs at a specific time interval using jQuery
<p>I would like to show divs at a specific interval (10 seconds) and show next div and as go on and repeat the same. <br/></p> <p>**</p> <blockquote> <p><strong><em>Sequence :</em></strong></p> </blockquote> <p>** On 10th second show div1 , hide other divs ,<br> After 5seconds interval Show div 2 and hide other divs, <br> After 5 seconds interval Show div 3 and hide other divs, <br /> and repeat the same for every 10 seconds.</p> <hr> <blockquote> <p><strong><em>Code Follows:</em></strong></p> </blockquote> <hr> <pre><code>&lt;div id='div1' style="display:none;"&gt; &lt;!-- content --&gt; &lt;/div&gt; &lt;div id='div2' style="display:none;"&gt; &lt;!-- content --&gt; &lt;/div&gt; &lt;div id='div3' style="display:none;"&gt; &lt;!-- content --&gt; &lt;/div&gt; </code></pre>
915,016
6
0
null
2009-05-27 10:10:17.7 UTC
21
2019-07-23 05:03:17.863 UTC
2009-05-27 10:21:04.387 UTC
null
1,450
null
98,807
null
1
27
javascript|jquery|css|html|timeout
139,084
<p><strong><a href="http://jsbin.com/acumo" rel="nofollow noreferrer">Working Example</a></strong> here - add <strong>/edit</strong> to the URL to play with the code</p> <p>You just need to use JavaScript <a href="https://developer.mozilla.org/En/Window.setInterval" rel="nofollow noreferrer"><code>setInterval</code></a> function</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('html').addClass('js'); $(function() { var timer = setInterval(showDiv, 5000); var counter = 0; function showDiv() { if (counter == 0) { counter++; return; } $('div', '#container') .stop() .hide() .filter(function() { return this.id.match('div' + counter); }) .show('fast'); counter == 3 ? counter = 0 : counter++; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt; &lt;title&gt;Sandbox&lt;/title&gt; &lt;meta http-equiv="Content-type" content="text/html; charset=utf-8" /&gt; &lt;style type="text/css" media="screen"&gt; body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; } .display { width: 300px; height: 200px; border: 2px solid #000; } .js .display { display: none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Example of using setInterval to trigger display of Div&lt;/h2&gt; &lt;p&gt;The first div will display after 10 seconds...&lt;/p&gt; &lt;div id='container'&gt; &lt;div id='div1' class='display' style="background-color: red;"&gt; div1 &lt;/div&gt; &lt;div id='div2' class='display' style="background-color: green;"&gt; div2 &lt;/div&gt; &lt;div id='div3' class='display' style="background-color: blue;"&gt; div3 &lt;/div&gt; &lt;div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>EDIT:</strong></p> <p>In response to your comment about the container div, just modify this</p> <pre><code>$('div','#container') </code></pre> <p>to this</p> <pre><code>$('#div1, #div2, #div3') </code></pre>
1,217,180
How do I byte-compile everything in my .emacs.d directory?
<p>I have decided to check out Emacs, and I liked it very much. Now, I'm using the <a href="http://github.com/technomancy/emacs-starter-kit/tree/master" rel="noreferrer">Emacs Starter Kit</a>, which sort of provides better defaults and some nice customizations to default install of Emacs.</p> <p>I have customized it a little, added some stuff like <a href="http://code.google.com/p/yasnippet/" rel="noreferrer">yasnippet</a>, <a href="http://www.nongnu.org/color-theme/" rel="noreferrer">color-themes</a>, <a href="http://www.emacswiki.org/emacs/unbound.el" rel="noreferrer">unbound</a>, and other stuff. I've set up a <a href="http://github.com/Irwin1138/emacs-starter-kit/tree/master" rel="noreferrer">github repository</a> where I keep all of the customizations so I can access them from multiple places or in case something goes bad and I lose my .emacs.d directory.</p> <p>All of this is very nice, but there is a problem: Emacs takes about 1-2 seconds to load. AFAIK I can compile individual .el files with M-x byte-compile-file to .elc, and it works. But there are a lot of .el files, and I wonder if there is a way to compile them all with a simple command or something, to speed up the loading of Emacs. My Emacs is not always open, and I open and close it quite frequently, especially after I've set it up as a default editor for edit command in Total Commander to get used to it faster (yeah, windows xp here).</p> <p>My Emacs version is 22.3. And yes, the default Emacs installation without any customizations fires up instantly.</p> <p>I am not sure which version is preferred when loading, the .el or compiled .elc one by the way O.o</p> <p>So, is there an elisp command or Emacs command line switch to make Emacs byte-compile everything in .emacs.d directory?</p>
1,217,249
6
0
null
2009-08-01 18:34:01.33 UTC
77
2020-08-19 20:00:15.763 UTC
null
null
null
null
141,147
null
1
144
emacs|elisp|bytecode|dot-emacs
43,810
<p><code>C-u 0 M-x byte-recompile-directory</code></p> <p>will compile all the .el files in the directory and in all subdirectories below.</p> <p>The <code>C-u 0</code> part is to make it not ask about every .el file that does not have a .elc counterpart.</p>
32,234,711
Which sorting algorithm works best on very large data set that won't fit in the main memory
<p>I was searching on the Internet to find which sorting algorithm is best suitable for a very large data set. I found that many have an opinion that merge sort is best because it is fair, as well as that it ensures that time complexity is O(n log n) and quick sort is not safe: It is also true that variations of quicksort can also be not safe because the real data set can be anything.</p> <p>If swapping of the two elements has negligible time cost, then why can't we choose heap sort as the best sorting algorithm in this case because it is in place as well as O(n log n)?</p> <p>In case of Merge sort it requires another O(n) space; if the data is very large then we can't use this algorithm.</p> <p>Which algorithm should be the best in this scenario?</p>
32,234,821
2
10
null
2015-08-26 19:04:44.87 UTC
11
2022-06-04 09:28:25.25 UTC
2022-06-04 09:28:25.25 UTC
null
1,145,388
null
5,151,912
null
1
22
algorithm|sorting
53,295
<p>There's no one algorithm that's clearly the &quot;best&quot; algorithm. If there were, we'd be using it everywhere! Instead, it depends on a bunch of factors.</p> <p>For starters, can you fit your data into main memory? If you can't, then you'd need to rely on an external sorting algorithm. These algorithms are often based on quicksort and mergesort.</p> <p>Second, do you know anything about your input distribution? If it's mostly sorted, then something like Timsort might be a great option, since it's designed to work well on sorted data. If it's mostly random, Timsort is probably not a good choice.</p> <p>Third, what kind of elements are you sorting? If you are sorting generic objects, then you're pretty much locked into comparison sorting. If not, perhaps you could use a non-comparison sort like counting sort or radix sort.</p> <p>Fourth, how many cores do you have? Some sorting algorithms (quicksort, mergesort, MSD radix sort) parallelize really well, while others do not (heapsort).</p> <p>Fifth, how are your data represented? If they're stored in an array, quicksort or a quicksort variant will likely do well because of locality of reference, while mergesort might be slow due to the extra memory needed. If they're in a linked list, though, the locality of reference from quicksort goes away and mergesort suddenly becomes competitive again.</p> <p>The best option is probably to take a lot of different factors into account and then make a decision from there. One of the reason it's so fun to design and study algorithms is that there's rarely one single best choice; often, the best option depends a ton on your particular situation and changes based on what you're seeing.</p> <p>(You mentioned a few details about quicksort, heapsort, and mergesort that I wanted to touch on before wrapping up this answer. While you're right that quicksort has a degenerate O(n<sup>2</sup>) worst case, there are many ways to avoid this. The introsort algorithm keeps track of the recursion depth and switches the algorithm to heapsort if it looks like the quicksort will degenerate. This guarantees O(n log n) worst-case behavior with low memory overhead and maximizes the amount of benefit you get from quicksort. Randomized quicksort, while still having an O(n<sup>2</sup>) worst case, has a vanishingly small probability of actually hitting that worst case.</p> <p>Heapsort is a good algorithm in practice, but isn't as fast as the other algorithms in some cases because it doesn't have good locality of reference. That said, the fact that it never degenerates and needs only O(1) auxiliary space is a huge selling point.</p> <p>Mergesort does need a lot of auxiliary memory, which is one reason why you might not want to use it if you have a huge amount of data to sort. It's worth knowing about, though, since its variants are widely used.)</p>
35,689,431
determine OS distribution of a docker image
<p>I need to determine the OS distribution name for any docker image. I can tag <strong>ubuntu:latest</strong> as <strong>image1:latest</strong>, but I should be able to get the distribution information of image1:latest when it is launched.</p> <p>For achieving this, I used the below mentioned command to determine the OS version:</p> <pre><code>$ docker tag ubuntu image1 $ $ docker run -it image1 /bin/sh -c "echo import platform &gt; test.py; echo print\(platform.dist\(\)\) &gt;&gt; test.py; python3 test.py" ('Ubuntu', '14.04', 'trusty') $ </code></pre> <p>However, this has a dependency on whether the image has <strong>python2</strong> or <strong>python3</strong> in it. It fails for ubuntu:12.04 and I need to use python2 there.</p> <pre><code>$ docker run -it ubuntu /bin/sh -c "echo import platform &gt; test.py; echo print\(platform.dist\(\)\) &gt;&gt; test.py; python3 test.py" ('Ubuntu', '14.04', 'trusty') $ $ docker run -it ubuntu:12.04 /bin/sh -c "echo import platform &gt; test.py; echo print\(platform.dist\(\)\) &gt;&gt; test.py; python3 test.py" /bin/sh: 1: python3: not found $ $ docker run -it ubuntu:12.04 /bin/sh -c "echo import platform &gt; test.py; echo print\(platform.dist\(\)\) &gt;&gt; test.py; python2 test.py" ('Ubuntu', '12.04', 'precise') $ </code></pre> <p>Q1. Is there a way I can achieve the same without knowing which version of python is there in a particular image?</p> <p>NOTE: The goal is to determine which was the base image used to build this image. I don't have access to the Dockerfile used to build this image.</p> <p>Q2. There is another approach of using entrypoint. I can build a separate image from the current image using Dockerfile. Or, I can specify entrypoint in cmdline when creating container but I need the script to be accessible within the container. I am guessing that I might need shared storage when using cmdline, is there a better way to achieve this? Any pointers would be really helpful.</p> <p>Thanks.</p>
35,690,567
5
3
null
2016-02-28 23:07:05.48 UTC
7
2020-08-06 10:28:19.107 UTC
2016-02-28 23:15:18.473 UTC
null
670,629
null
670,629
null
1
28
python|docker|dockerfile
24,372
<p>The Filesystem Hierarchy Standard has a <a href="https://www.freedesktop.org/software/systemd/man/os-release.html" rel="noreferrer">standard definition for <code>/etc/os-release</code></a>, which should be available on most distributions:</p> <blockquote> <p>The /etc/os-release and /usr/lib/os-release files contain operating system identification data.</p> <p>The basic file format of os-release is a newline-separated list of environment-like shell-compatible variable assignments. It is possible to source the configuration from shell scripts.</p> </blockquote> <p>This means you can just source <code>/etc/os-release</code> and use <code>$NAME</code> or <code>$ID</code> to identify the distribution. As an example, on Fedora it looks like this:</p> <pre><code>% source /etc/os-release % echo $NAME Fedora % echo $ID fedora </code></pre> <p>On Debian:</p> <pre><code>% source /etc/os-release % echo $NAME Debian GNU/Linux % echo $ID debian </code></pre>
44,352,870
How to handle database migrations in Spring Boot with Hibernate?
<p>My database background comes from the Django framework (python). In Django, getting started with database migrations was easy: <a href="https://docs.djangoproject.com/en/1.11/topics/migrations/" rel="noreferrer">Django migrations</a>. The Django framework provided tool for creating the migrations based on your models, and also a tool to apply the migrations on your database. I think this way of doing worked in both development and in production. You did not have to write migrations by yourself, the framework created them for you.</p> <p>Now I have started a project with Spring Boot and Hibernate. I configure my application to use hibernate with JPA. With these settings, I now would need to know how does my framework handle database migrations? I mean if I change a column, either it's type, or even might remove it, then how do I migrate the database to the change? I know that spring boot will automatically detect column changes on startup, and create columns that do not exist based on the models (Entity's). I guess it has something to do with variable </p> <blockquote> <p>spring.jpa.hibernate.ddl-auto</p> </blockquote> <p>But how does it handle the existing database objects? Does it add the column to them too, and with what value? The default value I set? What if I change the column type? Can it then handle the change? These settings and spring-boot automated database management probably are not enough in the long run?</p> <p><strong>What I want to know is, that what are the best practices on how to handle database migrations with Spring Boot and hibernate combination?</strong> I believe there is a standard how most of the people with this combination handle the migrations? I hope it is as easy as with Django... I know about flyway, but don't know if I really need it, or if it is used much with this combination of mine (including spring boot and hibernate).</p>
44,353,848
1
2
null
2017-06-04 10:01:03.92 UTC
8
2017-06-04 14:25:35.483 UTC
null
null
null
null
4,662,347
null
1
31
java|spring|hibernate|jpa|spring-boot
18,025
<p>Liquibase or Flyway are the two main options for versioning/handling database migrations. <code>ddl-auto</code> is quick and dirty, but it does not, nor can it, take into account everything that needs to be handled. THere's also the chance of race-conditions (two instances trying to update the DDL at the same time).</p> <p>This answer goes into more detail about <code>ddl-auto</code> in a production environment, and why you shouldn't. </p> <p><a href="https://stackoverflow.com/questions/221379/hibernate-hbm2ddl-auto-update-in-production">Hibernate: hbm2ddl.auto=update in production?</a></p> <p><a href="https://www.credera.com/blog/technology-insights/java/liquibase-fed-inconsistent-schemas/" rel="noreferrer">https://www.credera.com/blog/technology-insights/java/liquibase-fed-inconsistent-schemas/</a> has bit more info on the why/concepts. </p>
23,128,353
zsh shortcut 'ctrl + A' not working
<p>I recently switch from bash to zsh shell. To be more precise, the <a href="https://github.com/robbyrussell/oh-my-zsh">oh-my-zsh</a> Very nice, but the shortcut I most often use; jumping to the beginning/end of the line doesn't work anymore. From the <a href="http://www.geekmind.net/2011/01/shortcuts-to-improve-your-bash-zsh.html">docs</a> it should be</p> <pre><code>ctrl + A --&gt; beginning ctrl + E --&gt; end </code></pre> <p>However, when I do that I get the following</p> <pre><code>$~&gt; my-command $~&gt; my-command^A # did a ctrl + A here </code></pre> <p>Although I see this working by everybody else, on my system something seems to be different. Any suggestions what that might be ?</p>
23,134,765
3
2
null
2014-04-17 08:36:52.507 UTC
5
2019-05-24 05:09:26.427 UTC
null
null
null
null
419,425
null
1
29
shell|keyboard-shortcuts|zsh|shortcut
11,585
<p>you don't have to config the <kbd>Ctrl</kbd>+<kbd>A</kbd> behavior if you use default keymap (<code>emacs</code> keymap). It does what you are expecting.</p> <p>However if you set your zle to use <code>vi</code> keymap, you have to define the <code>keybind</code> for <code>vi-beginning-of-line</code>. same for <kbd>Ctrl</kbd>+<kbd>E</kbd>.</p> <p>So check which keymap did you set in config. If it was vi, try pressing <kbd>ESC</kbd> then <kbd>^</kbd> and <kbd>$</kbd> should do what you want.</p>
2,041,859
Javascript - how to find hebrew?
<p>i"m trying to fint if a string starts(first letter) width an RTL language/ hebrew.</p> <p>any ideas?</p>
2,041,895
5
0
null
2010-01-11 12:47:56.177 UTC
9
2020-09-20 04:33:03.847 UTC
2013-06-05 11:40:33.45 UTC
null
569,101
Gilad
null
null
1
24
javascript|regex|hebrew|right-to-left
16,102
<p>This will find hebrew letters encoded in the <a href="http://www.alanwood.net/unicode/hebrew.html" rel="noreferrer">Hebrew</a> Unicode code point range: <code>[\u0590-\u05FF]</code></p>
2,299,339
User Control vs. Windows Form
<p>What is the difference between a user control and a windows form in Visual Studio - C#?</p>
2,299,368
5
0
null
2010-02-19 20:29:52.943 UTC
12
2022-07-21 18:45:32.02 UTC
null
null
null
null
258,482
null
1
64
c#|visual-studio|winforms
62,003
<p>Put very simply:</p> <p>User controls are a way of making a custom, reusable component. A user control can contain other controls but must be hosted by a form.</p> <p>Windows forms are the container for controls, including user controls. While it contains many similar attributes as a user control, it's primary purpose is to host controls.</p>
1,734,896
R - capturing elements of R output into text files
<p>I am trying to run an analysis by invoking R through the command line as follows: </p> <pre><code>R --no-save &lt; SampleProgram.R &gt; SampleProgram.opt </code></pre> <p>For example, consider the simple R program below: </p> <pre><code>mydata = read.csv("test.txt", header=T) attach(mydata) summary(Variable1) q() </code></pre> <p>The output is displayed in SampleProgram.opt (only partially shown): </p> <pre><code>&gt; mydata = read.csv("test.txt", header=T) &gt; attach(mydata) &gt; summary(Variable1) Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 1.00 2.00 2.47 3.00 4.00 &gt; q() </code></pre> <p>This simple R program is going to be executed by a script that needs to use the summary statistics displayed for Variable1. </p> <p>The question is this: Is there any way in R to capture the output of summary(Variable1) and write the results into an output file? In other words, I need R to run the summary statistics for Variable1, capture the "Min", "Median" and "Max" values and write those alone to an output text file. In this example, the output file should contain only one line with the values "1.00, 2.00, 4.00" (i.e. the "Min", "Median" and "Max" values). </p> <p>The example above talks about the summary function. But, I need to do that with other commands as well (such as glm)</p> <p>I am fairly new to R and was wondering if there was a way in R that I could do this? </p> <p>Thanks for the help. </p>
1,735,807
6
0
null
2009-11-14 17:15:32.253 UTC
13
2014-09-24 23:23:19.797 UTC
2010-04-08 17:44:31.517 UTC
null
168,225
null
211,082
null
1
21
command-line|r
49,660
<p>You can also access individual attributes of the <code>summary</code> command. For example</p> <pre><code>&gt; x=summary(seq(1:10)) &gt; attributes(x) &gt; attributes(x) $names [1] "Min." "1st Qu." "Median" "Mean" "3rd Qu." "Max." $class [1] "table" &gt; x["1st Qu."] 1st Qu. 3.25 </code></pre>
1,685,221
accurately measure time python function takes
<p>I need to measure the time certain parts of my program take (not for debugging but as a feature in the output). Accuracy is important because the total time will be a fraction of a second.</p> <p>I was going to use the <a href="http://docs.python.org/library/time.html" rel="noreferrer">time module</a> when I came across <a href="http://docs.python.org/library/timeit.html" rel="noreferrer">timeit</a>, which claims to <em>avoid a number of common traps for measuring execution times</em>. Unfortunately it has an awful interface, taking a string as input which it then eval's. </p> <p>So, do I need to use this module to measure time accurately, or will time suffice? And what are the pitfalls it refers to?</p> <p>Thanks</p>
1,685,263
7
2
null
2009-11-06 03:25:04.083 UTC
20
2019-12-26 16:43:03.507 UTC
null
null
null
null
105,066
null
1
49
python|time|profiling|timeit
36,448
<p>According to the Python <a href="http://docs.python.org/library/timeit.html" rel="noreferrer">documentation</a>, it has to do with the accuracy of the time function in different operating systems:</p> <blockquote> <p>The default timer function is platform dependent. On Windows, time.clock() has microsecond granularity but time.time()‘s granularity is 1/60th of a second; on Unix, time.clock() has 1/100th of a second granularity and time.time() is much more precise. On either platform, the default timer functions measure wall clock time, not the CPU time. This means that other processes running on the same computer may interfere with the timing ... On Unix, you can use time.clock() to measure CPU time.</p> </blockquote> <p>To pull directly from <code>timeit.py</code>'s code:</p> <pre><code>if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time </code></pre> <p>In addition, it deals directly with setting up the runtime code for you. If you use <code>time</code> you have to do it yourself. This, of course <strong>saves you time</strong></p> <p>Timeit's setup:</p> <pre><code>def inner(_it, _timer): #Your setup code %(setup)s _t0 = _timer() for _i in _it: #The code you want to time %(stmt)s _t1 = _timer() return _t1 - _t0 </code></pre> <h2>Python 3:</h2> <p>Since Python 3.3 you can use <a href="http://docs.python.org/3/library/time.html#time.perf_counter" rel="noreferrer"><code>time.perf_counter()</code></a> (system-wide timing) or <a href="http://docs.python.org/3/library/time.html#time.process_time" rel="noreferrer"><code>time.process_time()</code></a> (process-wide timing), just the way you used to use <code>time.clock()</code>:</p> <pre><code>from time import process_time t = process_time() #do some stuff elapsed_time = process_time() - t </code></pre> <p>The new function <code>process_time</code> will not include time elapsed during sleep.</p> <h2>Python 3.7+:</h2> <p>Since Python 3.7 you can also use <a href="https://docs.python.org/3/library/time.html#time.process_time_ns" rel="noreferrer"><code>process_time_ns()</code></a> which is similar to <code>process_time()</code>but returns time in nanoseconds.</p>
1,581,551
download webpage and dependencies, including css images
<p>Often I need to download a webpage and then edit it offline. I have tried a few tools and the main feature they lack is downloading images referenced in the CSS files.</p> <p>Is there a tool (for Linux) that will download everything so that the webpage will render the same offline (excluding AJAX)?</p>
1,581,553
7
3
null
2009-10-17 06:07:06.357 UTC
34
2020-04-15 14:43:47.497 UTC
2016-12-02 14:33:06.1 UTC
null
773,263
null
105,066
null
1
75
html|css|image|download
75,837
<pre><code>wget --page-requisites http://example.com/your/page.html </code></pre> <blockquote> <p><a href="http://www.gnu.org/software/wget/manual/wget.html#index-page-requisites" rel="noreferrer">This option</a> causes Wget to download all the files that are necessary to properly display a given html page. This includes such things as inlined images, sounds, and referenced stylesheets.</p> </blockquote> <p><del>EDIT: meder is right: stock wget does not parse and download css images. There is, however, a patch that adds this feature: [<a href="https://savannah.gnu.org/bugs/index.php?20395" rel="noreferrer">1</a>, <a href="http://www.mail-archive.com/wget@sunsite.dk/msg09502.html" rel="noreferrer">2</a>]</del></p> <p>UPDATE: The patch mentioned above <a href="http://git.savannah.gnu.org/cgit/wget.git/tree/NEWS?id=e1df67a4f09d4fa86729e71b6e6ceb53c4f0b52b#n115" rel="noreferrer">has been merged into wget 1.12</a>, released 22-Sep-2009:</p> <pre><code>** Added support for CSS. This includes: - Parsing links from CSS files, and from CSS content found in HTML style tags and attributes. - Supporting conversion of links found within CSS content, when --convert-links is specified. - Ensuring that CSS files end in the ".css" filename extension, when --convert-links is specified. </code></pre>
1,962,389
What is the state of the art in HTML content extraction?
<p>There's a lot of scholarly work on HTML content extraction, e.g., Gupta &amp; Kaiser (2005) <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.60.357" rel="nofollow noreferrer">Extracting Content from Accessible Web Pages</a>, and some signs of interest here, e.g., <a href="https://stackoverflow.com/questions/435547/html-downloading-and-text-extraction">one</a>, <a href="https://stackoverflow.com/questions/1386107/text-extraction-from-html-java">two</a>, and <a href="https://stackoverflow.com/questions/1696914/extracting-pure-content-text-from-html-pages-by-excluding-navigation-and-chrome">three</a>, but I'm not really clear about how well the practice of the latter reflects the ideas of the former. What is the best practice?</p> <p>Pointers to good (in particular, open source) implementations and good scholarly surveys of implementations would be the kind of thing I'm looking for.</p> <p><strong>Postscript the first</strong>: To be precise, the kind of survey I'm after would be a paper (published, unpublished, whatever) that discusses both criteria from the scholarly literature, and a number of existing implementations, and analyses how unsuccessful the implementations are from the viewpoint of the criteria. And, really, a post to a mailing list would work for me too.</p> <p><strong>Postscript the second</strong> To be clear, after Peter Rowell's answer, which I have accepted, we can see that this question leads to two subquestions: (i) the solved problem of cleaning up non-conformant HTML, for which Beautiful Soup is the most recommended solution, and (ii) the unsolved problem or separating cruft (mostly site-added boilerplate and promotional material) from meat (the contentthat the kind of people who think the page might be interesting in fact find relevant. To address the state of the art, new answers need to address the cruft-from-meat peoblem explicitly.</p>
1,962,521
8
3
null
2009-12-26 01:22:48.48 UTC
27
2015-03-18 21:25:45.807 UTC
2017-05-23 12:01:55.357 UTC
null
-1
null
222,815
null
1
18
html|html-content-extraction|text-extraction
5,673
<p>Extraction can mean different things to different people. It's one thing to be able to deal with all of the mangled HTML out there, and Beautiful Soup is a clear winner in this department. But BS won't tell you what is cruft and what is meat.</p> <p>Things look different (and ugly) when considering content extraction from the point of view of a computational linguist. When analyzing a page I'm interested only in the <em>specific content</em> of the page, minus all of the navigation/advertising/etc. cruft. And you can't begin to do the interesting stuff -- co-occurence analysis, phrase discovery, weighted attribute vector generation, etc. -- until you have gotten rid of the cruft.</p> <p>The first paper referenced by the OP indicates that this was what they were trying to achieve -- analyze a site, determine the overall structure, then subtract that out and Voila! you have just the meat -- but they found it was harder than they thought. They were approaching the problem from an improved accessibility angle, whereas I was an early search egine guy, but we both came to the same conclusion:</p> <p><strong>Separating cruft from meat is hard.</strong> And (to read between the lines of your question) even once the cruft is removed, without carefully applied semantic markup it is <em>extremely</em> difficult to determine 'author intent' of the article. Getting the meat out of a site like citeseer (cleanly &amp; predictably laid out with a very high Signal-to-Noise Ratio) is <em>2 or 3 orders of magnitude</em> easier than dealing with random web content.</p> <p>BTW, if you're dealing with longer documents you might be particularly interested in work done by <a href="http://people.ischool.berkeley.edu/~hearst/" rel="noreferrer">Marti Hearst</a> (now a prof at UC Berkely). Her <a href="http://people.ischool.berkeley.edu/~hearst/papers/phdthesis.pdf" rel="noreferrer">PhD thesis</a> and other papers on doing subtopic discovery in large documents gave me a lot of insight into doing something similar in smaller documents (which, surprisingly, can be more difficult to deal with). But you can only do this after you get rid of the cruft.</p> <hr> <p>For the few who might be interested, here's some backstory (probably Off Topic, but I'm in that kind of mood tonight):</p> <p>In the 80's and 90's our customers were mostly government agencies whose eyes were bigger than their budgets and whose dreams made Disneyland look drab. They were collecting everything they could get their hands on and then went looking for a silver bullet technology that would somehow ( <em>giant hand wave</em> ) extract the 'meaning' of the document. Right. They found us because we were this weird little company doing "content similarity searching" in 1986. We gave them a couple of demos (real, not faked) which freaked them out.</p> <p>One of the things we already knew (and it took a long time for them to believe us) was that every collection is different and needs it's own special scanner to deal with those differences. For example, if all you're doing is munching straight newspaper stories, life is pretty easy. The headline mostly tells you something interesting, and the story is written in pyramid style - the first paragraph or two has the meat of who/what/where/when, and then following paras expand on that. Like I said, this is the easy stuff.</p> <p>How about magazine articles? Oh God, don't get me started! The titles are almost always meaningless and the structure varies from one mag to the next, and even from one section of a mag to the next. Pick up a copy of Wired and a copy of Atlantic Monthly. Look at a major article and try to figure out a <em>meaningful</em> 1 paragraph summary of what the article is about. Now try to describe how a program would accomplish the same thing. Does the same set of rules apply across all articles? Even articles from the same magazine? No, they don't.</p> <p>Sorry to sound like a curmudgeon on this, but this problem is <em>genuinely hard</em>.</p> <p>Strangely enough, a big reason for google being as successful as it is (from a search engine perspective) is that they place a lot of weight on the words in and surrounding a link <em>from another site</em>. That link-text represents a sort of mini-summary <em>done by a human</em> of the site/page it's linking to, exactly what you want when you are searching. And it works across nearly all genre/layout styles of information. It's a positively brilliant insight and I wish I had had it myself. But it wouldn't have done my customers any good because there <em>were no links</em> from last night's Moscow TV listings to some random teletype message they had captured, or to some badly OCR'd version of an Egyptian newspaper.</p> <p>/mini-rant-and-trip-down-memory-lane</p>
1,757,097
How to determine file age using PHP?
<p>Any way to determine file age of an image in a folder using PHP?</p> <p>I want to delete older files than 2 hours, is this possible without adding timestamp-names to their filenames on upload to the folder?</p> <p>If so, please give me an example!</p> <p>thanks</p>
1,757,115
8
0
null
2009-11-18 16:09:36.78 UTC
6
2020-03-07 02:04:31.09 UTC
null
null
null
user188962
null
null
1
55
php
40,211
<p>You can use <a href="http://www.php.net/manual/en/function.filemtime.php" rel="noreferrer">filemtime</a> function to get the last modified date/time and use that to see how old the file is.</p>
2,066,917
Overriding equals() & hashCode() in sub classes ... considering super fields
<p>Is there a specific rule on how Overriding <code>equals()</code> &amp; <code>hashCode()</code> in <strong>sub classes</strong> considering <strong>super fields</strong> ?? knowing that there is many parameters : super fields are private/public , with/without getter ...</p> <p>For instance, Netbeans generated equals() &amp; hashCode() will not consider the super fields ... and</p> <pre><code> new HomoSapiens("M", "80", "1.80", "Cammeron", "VeryHot").equals( new HomoSapiens("F", "50", "1.50", "Cammeron", "VeryHot")) </code></pre> <p>will return true :(</p> <pre><code>public class Hominidae { public String gender; public String weight; public String height; public Hominidae(String gender, String weight, String height) { this.gender = gender; this.weight = weight; this.height = height; } ... } public class HomoSapiens extends Hominidae { public String name; public String faceBookNickname; public HomoSapiens(String gender, String weight, String height, String name, String facebookId) { super(gender, weight, height); this.name = name; this.faceBookNickname = facebookId; } ... } </code></pre> <p>If you want to see the Netbeans generated equals() &amp; hashCode() :</p> <pre><code>public class Hominidae { ... @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Hominidae other = (Hominidae) obj; if ((this.gender == null) ? (other.gender != null) : !this.gender.equals(other.gender)) { return false; } if ((this.weight == null) ? (other.weight != null) : !this.weight.equals(other.weight)) { return false; } if ((this.height == null) ? (other.height != null) : !this.height.equals(other.height)) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 37 * hash + (this.gender != null ? this.gender.hashCode() : 0); hash = 37 * hash + (this.weight != null ? this.weight.hashCode() : 0); hash = 37 * hash + (this.height != null ? this.height.hashCode() : 0); return hash; } } public class HomoSapiens extends Hominidae { ... @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final HomoSapiens other = (HomoSapiens) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.faceBookNickname == null) ? (other.faceBookNickname != null) : !this.faceBookNickname.equals(other.faceBookNickname)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 89 * hash + (this.faceBookNickname != null ? this.faceBookNickname.hashCode() : 0); return hash; } } </code></pre>
2,067,401
10
1
null
2010-01-14 19:26:43.393 UTC
24
2018-06-06 12:34:11.417 UTC
null
null
null
null
236,223
null
1
73
java|inheritance|overriding|equals|hashcode
66,283
<p><b>Children should not examine the private members of their parents</b></p> <p>But <em>obviously</em>, all significant fields should be taken into account for equality and hashing.</p> <p>Fortunately, you you can easily satisfy both rules.</p> <p>Assuming you're not stuck using the NetBeans-generated equals and hashcode, you can modify Hominidae's equals method to use instanceof comparison rather than class equality, and then use it straightforwardly. Something like this:</p> <pre><code> @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if (! super.equals(obj)) return false; else { // compare subclass fields } </code></pre> <p>Of course, hashcode is easy:</p> <pre><code> @Override public int hashCode() { int hash = super.hashCode(); hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 89 * hash + (this.faceBookNickname != null ? this.faceBookNickname.hashCode() : 0); return hash; } </code></pre> <p>Seriously, though: what's up with NetBeans not taking superclass fields into account by calling the superclass methods?</p>
1,710,476
How to print a query string with parameter values when using Hibernate
<p>Is it possible in Hibernate to print generated SQL queries with real values instead of question marks?</p> <p>How would you suggest to print queries with real values if it is not possible with Hibernate API?</p>
1,713,464
32
1
null
2009-11-10 19:17:59.55 UTC
181
2021-12-08 18:18:47.893 UTC
2017-12-13 04:14:50.137 UTC
null
7,848,065
null
162,461
null
1
482
java|sql|hibernate|orm
482,538
<p>You need to enable <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging" rel="noreferrer">logging</a> for the the following categories:</p> <ul> <li><code>org.hibernate.SQL</code> &nbsp;&nbsp;- set to <code>debug</code> to log all SQL DML statements as they are executed</li> <li><code>org.hibernate.type</code> - set to <code>trace</code> to log all JDBC parameters</li> </ul> <p>So a log4j configuration could look like:</p> <pre><code># logs the SQL statements log4j.logger.org.hibernate.SQL=debug # Logs the JDBC parameters passed to a query log4j.logger.org.hibernate.type=trace </code></pre> <p>The first is equivalent to <code>hibernate.show_sql=true</code> legacy <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-optional" rel="noreferrer">property</a>, the second <strong>prints the bound parameters among other things.</strong></p> <p>Another solution (non hibernate based) would be to use a JDBC proxy driver like <a href="https://github.com/p6spy/p6spy" rel="noreferrer">P6Spy</a>.</p>
8,587,321
Are Github pages created automatically in the fork of a repo which has a gh-pages branch?
<p>Are github pages within my account created automatically when I fork a repo which already includes gh-pages branch?</p>
8,592,337
6
2
null
2011-12-21 09:07:47.97 UTC
6
2016-07-11 23:38:50.903 UTC
2015-04-12 06:32:29.887 UTC
null
895,245
null
217,288
null
1
41
github|github-pages
9,792
<p>There needs to be at least one push to trigger a page build so by doing a <code>git push origin master</code>, I got the page to rebuild.</p>
18,179,915
One line if/else condition in linux shell scripting
<p>I would like to have the equivelant of the following in a one line if/else condition.</p> <pre><code>$maxline=`cat journald.conf | grep "#SystemMaxUse="` if [ $maxline == "#SystemMaxUse=" ] then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf &gt; journald.conf2 mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually." fi </code></pre> <p>I'm attempting to put this into a one line command. So far I've gotten it all but the else portion of the command. Here's what I have so far...</p> <pre><code>maxline=`cat journald.conf | grep "#SystemMaxUse="` &amp;&amp; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf &gt; journald.conf2 &amp;&amp; mv journald.conf2 journald.conf; fi </code></pre> <p>So how can I include the else portion of the above code into my command? Thank you for your help in advance.</p>
18,180,051
4
3
null
2013-08-12 05:13:31.147 UTC
12
2022-08-15 14:52:32.023 UTC
null
null
null
null
2,529,482
null
1
61
linux|shell|if-statement
155,702
<p>It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&amp;&amp;".</p> <pre><code>maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf &gt; journald.conf2 &amp;&amp; mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi </code></pre> <p>Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.</p>
17,939,556
How to get the execution directory path in java
<p>I have made a pure java app which tells me about number of files in a given directory. Now I set current directory by using the following code:</p> <pre><code>`File f = new File(".");` </code></pre> <p>After that I made an installer with its jar file and installed it in my windows 8 and then I add it to the windows right click drop down menu (context menu). When I launch it from the context menu it always tells me about the number of files in the directory where it is actually installed in however I want to know the number of files of that directory from where I am executing it.</p> <p>So plz help me. I am a novice in this field and I don't want you to confuse me in current directory and the current execution directory. So I write this so long and hoping for a clean answer in very simple words.</p> <p>Thanks</p>
17,939,617
5
2
null
2013-07-30 06:16:26.977 UTC
5
2017-04-05 12:20:01.717 UTC
2017-04-05 12:20:01.717 UTC
null
617,450
null
2,229,597
null
1
24
java
94,753
<p>As Jarrod Roberson states in <a href="https://stackoverflow.com/a/3153440/19679">his answer here</a>:</p> <blockquote> <p>One way would be to use the <a href="http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperty%28java.lang.String%29" rel="noreferrer">system property</a> <code>System.getProperty("user.dir");</code> this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the <code>java</code> command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.</p> <p>The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.</p> <pre><code>public class Test { public static void main(final String[] args) { final String dir = System.getProperty("user.dir"); System.out.println("current dir = " + dir); } } </code></pre> <p>if you are in <code>/User/me/</code> and your .jar file containing the above code is in <code>/opt/some/nested/dir/</code> the command <code>java -jar /opt/some/nested/dir/test.jar Test</code> will output <code>current dir = /User/me</code>.</p> <p>You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend <a href="http://martiansoftware.com/jsap/" rel="noreferrer">JSAP</a>, the Java Simple Argument Parser. This would let you use <code>System.getProperty("user.dir")</code> and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on <code>user.dir</code> if nothing was passed in.</p> </blockquote> <p>Example : GetExecutionPath</p> <pre><code>import java.util.*; import java.lang.*; public class GetExecutionPath { public static void main(String args[]) { try{ String executionPath = System.getProperty("user.dir"); System.out.print("Executing at =&gt;"+executionPath.replace("\\", "/")); }catch (Exception e){ System.out.println("Exception caught ="+e.getMessage()); } } } </code></pre> <p>output for the above will be like </p> <pre><code>C:\javaexamples&gt;javac GetExecutionPath.jav C:\javaexamples&gt;java GetExecutionPath Executing at =&gt;C:/javaexamples </code></pre>
44,806,474
Disable error reporting entirely in Laravel production?
<p>I would like to disable error reporting entirely on production, because we have some very old code we still need to fix but for now does work (yes I don't like it either). We cannot fix everything in a few days, so we need to just supress the warnings and exceptions like we always did.</p> <p>The real problem is that it already throws an exception on a simple lazy bug like (because var is not defined)</p> <pre><code>if(!$var) { // do whatever } </code></pre> <p><strong>tried</strong></p> <blockquote> <p>APP_DEBUG=false</p> <p>APP_LOG_LEVEL=emergency</p> </blockquote> <pre><code>display_errors(false); set_error_handler(null); set_exception_handler(null); </code></pre> <p>But it still shows an <code>ErrorException</code> </p> <blockquote> <p>Undefined variable: script_name_vars_def</p> </blockquote> <p><strong>edit</strong>: The code works like this</p> <p><strong>web.php</strong></p> <pre><code>Route::any('/someroute', 'somecontroller@controllerFunc'); </code></pre> <p><strong>somecontroller.php</strong></p> <pre><code>public controllerFunc() { ob_start(); require '/old_index.php'; $html = ob_get_clean(); return response($html); } </code></pre> <p>This way we use Laravel routing without having to rewrite the old code immediately.</p> <p>I know I can fix this warning very easy, but there are many, many more of these errors and we need to use Laravel routing now. Fix the problems later.</p> <p><strong>ideas</strong></p> <ul> <li>Use some wildcard in <code>$dontReport</code>.</li> <li>Use a <code>@</code> suppression at the right place</li> <li>Can it be <a href="http://php.net/manual/en/scream.examples-simple.php" rel="noreferrer">http://php.net/manual/en/scream.examples-simple.php</a> </li> </ul> <p><strong>edit to explain after which steps middleware didn't work</strong></p> <p>1) create midddleware</p> <pre><code>php artisan make:middleware SuppressExceptions </code></pre> <p>2) Write it</p> <p><em>SuppressExceptions.php</em></p> <pre><code>public function handle($request, Closure $next) { error_reporting(0); return $next($request); } </code></pre> <p>3) Register</p> <p><em>laravel/app/Http/Kernel.php</em></p> <pre><code>protected $middlewareGroups = [ 'web' =&gt; [ \App\Http\Middleware\SuppressExceptions::class, ], </code></pre>
44,862,789
8
15
null
2017-06-28 15:13:19.15 UTC
7
2020-12-30 13:45:08.623 UTC
2017-07-04 20:13:08.027 UTC
null
2,754,599
null
2,754,599
null
1
21
php|laravel|laravel-5|laravel-5.3|laravel-5.4
48,616
<p>Yes you can change the error reporting. In fact, the framework provides a place to intercept the exceptions: <code>App\Exceptions\Handler</code>. By default the <code>render</code> method will convert the exception thrown to a HTML response. The <code>APP_ENV</code> and <code>APP_DEBUG</code> values will only change how this error response will render (details on the exception stack trace or not, basically).</p> <p>Try changing the <code>render</code> method to</p> <pre><code>public function render($request, Exception $exception) { if ($exception instanceof ErrorException) { error_reporting(0); $kernel = app(\Illuminate\Contracts\Http\Kernel::class); $response = $kernel-&gt;handle($request)-&gt;send(); return $kernel-&gt;terminate($request, $response); } return parent::render($request, $exception); } </code></pre> <p>This basically turns reporting off and then attempts to re-handle the request. In the <code>if</code> clause you may check for any condition you want (the class of the exception, the severity, etc.). Catching <code>ErrorException</code> will probably cover your needs, but notice that you may not be able to recover from a fatal error this way.</p> <p>Anyway, you should take that as a "proof of concept"... For non-idempotent requests, this "re-handle" approach is not good. Instead, just <a href="https://laravel.com/docs/5.4/middleware#defining-middleware" rel="noreferrer">create a Middleware</a> with</p> <pre><code>public function handle($request, Closure $next) { error_reporting(0); return $next($request); } </code></pre> <p>Same as before, fatal errors can't be recovered this way. But you can show a custom error message combining this middleware with the exception handler approach from before:</p> <pre><code>public function render($request, Exception $exception) { if ($exception instanceof FatalErrorException) { return view('fatal-error', ['exception' =&gt; $exception]); } return parent::render($request, $exception); } </code></pre>
18,869,141
Using Python mock to spy on calls to an existing object
<p>I'm using the Python mock module for tests. I would like to replace an active object with a mock, and automatically have all calls made to the mock object forwarded to the original object. I think this is called a "Spy" in standard testing terminology. At the moment I'm doing inside a test:</p> <pre><code># Insert a mock replacement orig_active_attr = server.active_attr server.active_attr = mock.Mock() # Set up side effects to 'proxy' to the original object server.active_attr.meth1.side_effect = orig_active_attr.meth1 server.active_attr.meth2.side_effect = orig_active_attr.meth2 # Call the method being tested server.method_being_tested() # Assert stuff on the mock. server.active_attr.meth2.assert_called_once() </code></pre> <p>It would be nice if all method calls on the mock could be forwarded to the live object automatically without the boilerplate.</p>
20,130,972
6
2
null
2013-09-18 09:55:50.22 UTC
6
2022-07-26 14:48:57.913 UTC
2013-09-18 17:45:17.46 UTC
null
64,633
null
1,113,345
null
1
53
python|unit-testing|mocking
36,916
<p>I seem to have stumbled across the solution:</p> <pre><code>import mock class A(object): def meth(self, a): return a a = A() ma = mock.Mock(wraps=a) </code></pre> <p>Seems to work okay for functions, methods and properties, but not for class or instance attributes.</p> <p>See <a href="https://docs.python.org/3/library/unittest.mock.html#the-mock-class" rel="noreferrer">the documentation</a>.</p>
19,110,668
Static table view inside UIViewController [Xcode 5]
<p>I'm aware of the problem that one is not able to have static table view content in a UIViewController in <p>I don't get a warning/error but he also doesn't compile. Is there a trick to it or do I have to use the old ways around it?</p> <p>Thanks in advance.</p>
19,110,821
5
2
null
2013-10-01 07:44:34.48 UTC
10
2014-03-27 09:10:36.563 UTC
null
null
null
null
2,818,444
null
1
26
objective-c|xcode
27,014
<p><strong>UPDATE: With the latest update (Xcode 5.1) it seems that it's no longer possible to put static cells inside regular UIViewController. My answer still applies for UITableViewController though.</strong></p> <hr> <p>Yes, you can have static table view content in UIViewController.</p> <p>All you need to do is:</p> <p>-Create the table's static cells in interface builder and design them the way you like.</p> <p>-Make the UIViewController implement table view's data source and delegate:</p> <p><code>@interface MyViewController : UIViewController&lt;UITableViewDataSource, UITableViewDelegate&gt;</code></p> <p>-Connect the table view's delegate and dataSource to the view controller in interface builder</p> <p>-Implement <code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section</code> to return the number of your cells. (e.g. <code>return 10</code>, yes simple as that)</p> <p>-Connect your cells to your code as IBOutlets in Interface Builder. <strong>IMPORTANT:</strong> Make sure they are <code>strong</code>, weak won't work. e.g. <code>@property (strong, nonatomic) IBOutlet UITableViewCell *myFirstCell;</code></p> <p>-Implement <code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath</code> to return the correct cell at index path. e.g:</p> <pre><code>int num = indexPath.row; UITableViewCell *cell; switch (num) { case 0: cell = self.myFirstCell; break; case 1: cell = self.mySecondCell; break; } return cell; </code></pre> <p>If you apply all these steps, you should have working static cells that works for tables with not many cells. Perfect for tables that you have a few (probably no more than 10-20 would be enough) content. I've ran the same issue a few days ago and I confirm that it works. More info on my answer here: <a href="https://stackoverflow.com/questions/13847093/best-approach-to-add-static-tableview-cells-to-a-uiviewcontroller/19003972#19003972">Best approach to add Static-TableView-Cells to a UIViewcontroller?</a></p>
34,933,146
Prevent Captive Portal auto-close after authentication (Android)
<p>So the simple idea is that we have a RADIUS server setup to allow users to authenticate with our Ruckus controller via user credentials. On authentication the user should be redirected to a page that allows them to manage MAC authenticated devices.</p> <p>On everything we have tested so far, including "older" Android devices this seems to be no issue and things run as they should. However with Lollipop (5.0+) versions of Android the captive portal has changed quite a bit, and part of that change is to automatically close the captive portal that launches when you join the network. Because we want them to be redirected to a MAC device management page after authentication so they can add the device they currently logged in with and avoid having to log in again, this is bad.</p> <p><strong>What I have tried:</strong></p> <ol> <li><p>Detecting if the browser is being launched in a mobile device and popping an alert in <em>onbeforeunload</em> that attempts to keep the browser open.</p></li> <li><p>Opening a new browser window, pointing to the redirection URL, when successful authentication is detected (essentially managing the redirect ourselves).</p></li> <li><p>Performing Option 2, and then Option 1 on the redirected URL</p></li> </ol> <p><strong>What won't work:</strong></p> <ul> <li><p>Asking users to disable the captive portal option on their device. Not trying to point general users to advanced controls.</p></li> <li><p>Creating an open network to access the MAC manager, it must be behind some authentication.</p></li> </ul> <p><strong>Solution For Now:</strong></p> <p>We are unhappy with this solution, but for now we are simply asking users to authenticate with the network and then open their browser and go to the basic login portal page (non-network authentication) that users use to manually add devices they can't connect with (like printers, gaming devices, etc.). Though this works, it is a pain for users to have to login, open a browser, manually enter a url, and login again. </p> <p>This isn't a problem that people haven't run into, <a href="http://forum.mikrotik.com/viewtopic.php?t=102180">see here</a>, I just haven't been able to find a solution from anyone that has run into the problem. Certainly there is some way of utilizing javascript or something to keep the browser open in this situation. If not, anyone have any better ideas for managing things?</p>
44,331,058
3
6
null
2016-01-21 19:58:10.427 UTC
11
2019-11-18 19:33:06.493 UTC
2019-11-18 19:33:06.493 UTC
null
1,839,439
null
2,387,054
null
1
14
javascript|android|authentication|captivenetwork
14,973
<p>We have managed to keep the UAM Browser / captive portal browser open on lollipop by adding firewall rules blocking : </p> <ul> <li>clients3.google.com</li> <li>clients1.google.com , </li> <li>android.clients.google.com</li> <li>connectivitycheck.android.com</li> <li>connectivitycheck.gstatic.com</li> </ul> <p>Thus after the user is authenticated the UAM / Captive Browser stays open.</p> <p>You can keep UAM open as long as you need, you can close it by invoking a reverse proxied 204 redirect to google's connectivity page.</p>
40,973,687
Create new dataframe in pandas with dynamic names also add new column
<p>I have a dataframe df </p> <pre><code> df = pd.DataFrame({'A':['-a',1,'a'], 'B':['a',np.nan,'c'], 'ID':[1,2,2], 't':[pd.tslib.Timestamp.now(),pd.tslib.Timestamp.now(), np.nan]}) </code></pre> <p>Added a new column </p> <pre><code>df['YearMonth'] = df['t'].map(lambda x: 100*x.year + x.month) </code></pre> <p>Now I want to write a function or macro which will do date comparasion, create a new dataframe also add a new column to dataframe.</p> <p>I tried like this but seems I am going wrong:</p> <pre><code>def test(df,ym): df_new=df if(ym &lt;= df['YearMonth']): df_new+"_"+ym=df_new return df_new+"_"+ym df_new+"_"+ym['new_col']=ym </code></pre> <p>Now when I call test function I want a new dataframe should get created named as <code>df_new_201612</code> and this new dataframe should have one more column, named as <code>new_col</code> that has value of <code>ym</code> for all the rows.</p> <pre><code>test(df,201612) </code></pre> <p>The output of new dataframe is:</p> <p><strong>df_new_201612</strong></p> <pre><code>A B ID t YearMonth new_col -a a 1 2016-12-05 12:37:56.374620 201612 201612 1 NaN 2 2016-12-05 12:37:56.374644 201208 201612 a c 2 nat nan 201612 </code></pre>
40,974,699
2
4
null
2016-12-05 11:53:39.103 UTC
4
2022-07-07 07:19:07.063 UTC
2016-12-05 15:39:59.157 UTC
null
4,245,148
null
4,245,148
null
1
9
python|pandas|numpy
44,169
<p>Creating variables with dynamic names is typically a bad practice.</p> <p>I think the best solution for your problem is to store your dataframes into a dictionary and dynamically generate the name of the key to access each dataframe.</p> <pre><code>import copy dict_of_df = {} for ym in [201511, 201612, 201710]: key_name = 'df_new_'+str(ym) dict_of_df[key_name] = copy.deepcopy(df) to_change = df['YearMonth']&lt; ym dict_of_df[key_name].loc[to_change, 'new_col'] = ym dict_of_df.keys() Out[36]: ['df_new_201710', 'df_new_201612', 'df_new_201511'] dict_of_df Out[37]: {'df_new_201511': A B ID t YearMonth new_col 0 -a a 1 2016-12-05 07:53:35.943 201612 201612 1 1 NaN 2 2016-12-05 07:53:35.943 201612 201612 2 a c 2 2016-12-05 07:53:35.943 201612 201612, 'df_new_201612': A B ID t YearMonth new_col 0 -a a 1 2016-12-05 07:53:35.943 201612 201612 1 1 NaN 2 2016-12-05 07:53:35.943 201612 201612 2 a c 2 2016-12-05 07:53:35.943 201612 201612, 'df_new_201710': A B ID t YearMonth new_col 0 -a a 1 2016-12-05 07:53:35.943 201612 201710 1 1 NaN 2 2016-12-05 07:53:35.943 201612 201710 2 a c 2 2016-12-05 07:53:35.943 201612 201710} # Extract a single dataframe df_2015 = dict_of_df['df_new_201511'] </code></pre>
4,877,326
How can I tell if a string contains multibyte characters in Javascript?
<p>Is it possible in Javascript to detect if a string contains multibyte characters? If so, is it possible to tell which ones?</p> <p>The problem I'm running into is this (apologies if the Unicode char doesn't show up right for you)</p> <pre><code>s = ""; alert(s.length); // '2' alert(s.charAt(0)); // '��' alert(s.charAt(1)); // '��' </code></pre> <hr> <p><strong>Edit for a bit of clarity here <em>(I hope)</em>.</strong> <em>As I understand it now</em>, all strings in Javascript are represented as a series of UTF-16 code points, which means that regular characters actually take up 2 bytes (16 bits), so my usage of "multibyte" in the title was a bit off. Some characters do not fall in the Basic Multilingual Plane (BMP), such as the string in the example above, and so they take up two code points (32 bits). That is the question I was asking. I'm also not editing the original title, since to someone who doesn't know much about this stuff (and hence would be searching SO for info about it), "multibyte" would make sense.</p>
4,885,062
2
6
null
2011-02-02 16:56:21.523 UTC
17
2022-08-10 13:49:38.347 UTC
2011-02-03 17:18:58.293 UTC
null
9,021
null
9,021
null
1
27
javascript|string|internationalization|multibyte
11,299
<p>JavaScript strings are UCS-2 encoded but can represent Unicode code points outside the Basic Multilingual Pane (<code>U+0000</code> - <code>U+D7FF</code> and <code>U+E000</code> - <code>U+FFFF</code>) using two 16 bit numbers (a UTF-16 <em>surrogate pair</em>), the first of which must be in the range <code>U+D800</code> - <code>U+DFFF</code>.</p> <p>Based on this, it's easy to detect whether a string contains any characters that lie outside the Basic Multilingual Plane (which is what I think you're asking: you want to be able to identify whether a string contains any characters that lie outside the range of code points that JavaScript represents as a single character):</p> <pre><code>function containsSurrogatePair(str) { return /[\uD800-\uDFFF]/.test(str); } alert( containsSurrogatePair("foo") ); // false alert( containsSurrogatePair("f") ); // true </code></pre> <p>Working out precisely which code points are contained in your string is a little harder and requires a UTF-16 decoder. The following will convert a string into an array of Unicode code points:</p> <pre><code>var getStringCodePoints = (function() { function surrogatePairToCodePoint(charCode1, charCode2) { return ((charCode1 &amp; 0x3FF) &lt;&lt; 10) + (charCode2 &amp; 0x3FF) + 0x10000; } // Read string in character by character and create an array of code points return function(str) { var codePoints = [], i = 0, charCode; while (i &lt; str.length) { charCode = str.charCodeAt(i); if ((charCode &amp; 0xF800) == 0xD800) { codePoints.push(surrogatePairToCodePoint(charCode, str.charCodeAt(++i))); } else { codePoints.push(charCode); } ++i; } return codePoints; } })(); alert( getStringCodePoints("f").join(",") ); // 102,119558 </code></pre>
5,376,387
Do you know of any free SOAP webservices (for tutorial purpose)
<p>Only for tutorial purpose, I would like to try to use a free SOAP web services available.</p> <p>Which ones come to your mind ?</p> <p>The business implied behind is not important/relevant: Only the ease of access (free access), and simplicity of the service contract.</p> <p>Any indication welcome !</p>
5,376,425
2
1
null
2011-03-21 10:30:49.293 UTC
3
2016-04-11 20:41:39.85 UTC
2016-04-11 20:41:39.85 UTC
null
356,440
null
356,440
null
1
30
soap|webservice-client
72,955
<p>You can look at this post</p> <p><a href="https://stackoverflow.com/questions/311654/public-free-web-services-for-testing-soap-client">Public free web services for testing soap client</a></p>
939,563
C# return a variable as read only from get; set;
<p>I swear I have seen an example of this but have been googling for a bit and can not find it.</p> <p>I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).</p> <p>Thanks</p>
939,591
7
3
null
2009-06-02 13:33:38.01 UTC
7
2016-03-21 14:18:29.837 UTC
2009-06-02 13:37:41.373 UTC
null
3,043
null
6,486
null
1
36
c#|properties|readonly
24,365
<p>No, there's no way of doing this. For instance, if you return a <code>List&lt;string&gt;</code> (and it's not immutable) then callers <em>will</em> be able to add entries.</p> <p>The normal way round this is to return an immutable wrapper, e.g. <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx" rel="noreferrer"><code>ReadOnlyCollection&lt;T&gt;</code></a>.</p> <p>For other mutable types, you may need to clone the value before returning it.</p> <p>Note that just returning an immutable interface view (e.g. returning <code>IEnumerable&lt;T&gt;</code> instead of <code>List&lt;T&gt;</code>) won't stop a caller from casting back to the mutable type and mutating.</p> <p>EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)</p>
220,149
How do I access the HTTP request header fields via JavaScript?
<p>I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?</p> <hr> <p>Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.</p> <blockquote> <p><strong>Related:</strong><br> <a href="https://stackoverflow.com/questions/220231/accessing-http-headers-in-javascript">Accessing the web page&#39;s HTTP Headers in JavaScript</a></p> </blockquote>
220,169
7
1
null
2008-10-20 22:21:21.14 UTC
12
2020-10-31 18:28:31.397 UTC
2017-05-23 11:47:19.92 UTC
dacracot
-1
dacracot
13,930
null
1
66
javascript|http|http-headers
166,762
<p>If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.</p> <p>To retrieve the referrer, use <a href="https://developer.mozilla.org/en-US/docs/DOM/document.referrer" rel="noreferrer"><code>document.referrer</code></a>.<br> To access the user-agent, use <a href="https://developer.mozilla.org/en-US/docs/DOM/window.navigator.userAgent" rel="noreferrer"><code>navigator.userAgent</code></a>.</p> <p>As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.</p>
602,237
Where does 'Hello world' come from?
<p>'<code>hello, world</code>' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.</p> <p>I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.</p> <p>So my question is:<br> Where does the practice to use '<code>hello, world</code>' as the first example for computer languages originate from?<br> Where was it first used?</p> <p><strong>Update</strong><br> Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when '<code>hello world</code>' was first <em>used</em>.<br> So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?</p>
12,785,204
7
0
2009-03-02 15:13:31.43 UTC
2009-03-02 12:55:27.487 UTC
24
2021-02-24 15:18:22.76 UTC
2016-11-30 09:06:15.257 UTC
Jacco
22,674
Jacco
22,674
null
1
119
history
79,104
<p>Brian Kernighan actually wrote the first &quot;hello, world&quot; program as part of the documentation for the BCPL programming language developed by Martin Richards. BCPL was used while C was being developed at Bell Labs a few years before the publication of Kernighan and Ritchie's C book in 1972.</p> <p><a href="https://i.stack.imgur.com/wU0xv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wU0xv.png" alt="enter image description here" /></a></p> <p>As part of the research for a book I was writing about the Alice programming environment, I corresponded with both Prof. Kernighan at Princeton and Martin Richards at Cambridge (when I was teaching a seminar there in the 1990’s). They helped me to track the first documented use of code to print the message &quot;Hello, World!” Brian Kernighan remembered writing the code for part of the I/O section of the BCPL manual. Martin Richards -- who seems to have a treasure trove of notes, old documents, etc. -- found the manual and confirmed that this was the original appearance of the program. The code was used for early testing of the C compiler and made its way into Kernighan and Ritchie's book. Later, it was one of the first programs used to test Bjarne Stroustrup's C++ compiler.</p> <p>It became a standard for new programmers after it appeared in Kernighan and Ritchie, which is probably the best selling introduction to programming of all time.</p>
916,190
VS2010 and VS2008 project compatibility
<p>Does anyone know if VS2010 will use the same project &amp; solution file format as 2008, or will the 2008 project files need to be upgraded to 2010 format before they'll open in that version?</p>
916,229
8
1
null
2009-05-27 14:51:07.587 UTC
9
2013-03-05 08:25:05.923 UTC
null
null
null
null
36,297
null
1
21
visual-studio-2008|visual-studio-2010
61,355
<p>"Visual Studio 2010 will allow you to move your projects from previous versions of Visual Studios to VS 2010 with ease, I will call this process as “Converting” the project from VS 200X to VS 2010… </p> <p>VS 2010 will also allow you to change your project’s Target Framework Version to .NET 4.0 from .NET 2.0, 3.0 or 3.5… I will call this process as “Upgrading”…"</p> <p>extracted from <a href="http://vishaljoshi.blogspot.com/2009/05/vs-2010-project-conversion-upgrade.html" rel="noreferrer">http://vishaljoshi.blogspot.com/2009/05/vs-2010-project-conversion-upgrade.html</a></p>
1,268,738
ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller
<p>What is the correct way to find the absolute path to the App_Data folder from a Controller in an ASP.NET MVC project? I'd like to be able to temporarily work with an .xml file and I don't want to hardcode the path.</p> <p>This does not work: </p> <pre><code>[HandleError] public class HomeController : Controller { public ActionResult Index() { string path = VirtualPathUtility.ToAbsolute("~/App_Data/somedata.xml"); //.... do whatever return View(); } } </code></pre> <p>I think outside of the web context VirtualPathUtility.ToAbsolute() doesn't work. string path comes back as "C:\App_Data\somedata.xml"</p> <p>Where should I determine the path of the .xml file in an MVC app? global.asax and stick it an application-level variable?</p>
1,268,755
8
1
null
2009-08-12 21:06:30.573 UTC
62
2021-07-21 12:22:22.037 UTC
null
null
null
null
36,590
null
1
294
.net|asp.net-mvc|absolute-path
281,618
<h3>ASP.NET MVC1 -> MVC3</h3> <pre><code>string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml"); </code></pre> <hr> <h3>ASP.NET MVC4</h3> <pre><code>string path = Server.MapPath("~/App_Data/somedata.xml"); </code></pre> <p><hr> MSDN Reference:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath(v=vs.110).aspx" rel="noreferrer">HttpServerUtility.MapPath Method</a></p>
876,115
How can I determine if a div is scrolled to the bottom?
<p>How do I determine, without using jQuery or any other JavaScript library, if a div with a vertical scrollbar is scrolled all the way to the bottom?</p> <p>My question is not how to scroll to the bottom. I know how to do that. I want to determine if the the div is scrolled to the bottom already.</p> <p>This does not work:</p> <pre><code>if (objDiv.scrollTop == objDiv.scrollHeight) </code></pre>
876,134
8
2
null
2009-05-18 03:19:05.747 UTC
25
2021-07-03 18:02:56.513 UTC
2010-03-24 22:23:04.203 UTC
Roger Pate
null
null
66,475
null
1
117
javascript|scroll|scrollbar
75,480
<p>You're pretty close using <code>scrollTop == scrollHeight</code>.</p> <p><code>scrollTop</code> refers to the top of the scroll position, which will be <code>scrollHeight - offsetHeight</code></p> <p>Your if statement should look like so (don't forget to use triple equals):</p> <pre><code>if( obj.scrollTop === (obj.scrollHeight - obj.offsetHeight)) { } </code></pre> <p>Edit: Corrected my answer, was completely wrong</p>
156,438
What Does It Mean For a C++ Function To Be Inline?
<p>See title: what does it mean for a C++ function to be inline?</p>
156,458
9
1
null
2008-10-01 06:25:18.093 UTC
10
2022-02-28 00:36:06 UTC
2015-02-19 21:52:38.87 UTC
Lars Westergren
3,001,761
Tim Sally
7,545
null
1
32
c++|inline-functions
18,988
<p>The function is placed in the code, rather than being called, similar to using macros (conceptually).</p> <p>This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies).</p> <p>You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you.</p> <p>This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it).</p>
528,648
How to structure my javascript/jquery code?
<p>I am toying around with a pretty intensive ajax based jquery web application. It is getting to a point where I almost loose track of what events that should trigger what actions etc.</p> <p>I am sort of left with a feeling that my javascript structure is wrong, on a more basic level. How do you guys structure your javascript/jquery code, the event handling etc., any advise for a newbie javascript developer.</p>
8,127,152
10
1
null
2009-02-09 15:36:39.697 UTC
59
2018-05-12 06:51:38.783 UTC
null
null
null
Egil Hansen
32,809
null
1
65
javascript|jquery
24,704
<p>AMDS!</p> <p>It's been awhile since first answers got posted to this question and many things have changed. First and foremost, the JS browser world seems to be moving towards AMDs (asynchronous module definition) for code organization.</p> <p>The way that works is you write ALL your code as AMD modules, e.g.:</p> <pre><code>define('moduleName', ['dependency1', 'dependency2'], function (dependency1, dependency2) { /*This function will get triggered only after all dependency modules loaded*/ var module = {/*whatever module object, can be any JS variable here really*/}; return module; }); </code></pre> <p>And then modules get loaded using AMD loaders like <strong>curl.js</strong> or <strong>require.js</strong> etc, for example:</p> <pre><code>curl( [ 'myApp/moduleA', 'myApp/moduleB' ], ).then( function success (A, B) { // load myApp here! }, function failure (ex) { alert('myApp didn't load. reason: ' + ex.message); } ); </code></pre> <p>Advantages are:</p> <ol> <li><p>You only have to include single <code>&lt;script&gt;</code> element on your page that loads AMD loader itself (some of them are quite tiny).</p></li> <li><p>After that all JS files will be fetched automatically in asynchronous NON BLOCKING! fashion, thus way faster!</p></li> <li><p>Necessary modules will get executed only after its dependencies got loaded.</p></li> <li><p>Modular (which means code that is easier to maintain and re-use).</p></li> <li><p>Global variables pollution can be completely curbed if used correctly.</p></li> </ol> <p>Honestly, once concept has <strong>clicked</strong> in your head, you'll never go back to your old ways. </p> <p>P.S: jQuery does register itself as AMD module starting from version 1.7.</p> <p>More information on AMDS:</p> <ul> <li><a href="https://github.com/cujojs/curl" rel="nofollow noreferrer">https://github.com/cujojs/curl</a></li> <li><a href="http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition" rel="nofollow noreferrer">http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition</a></li> <li><a href="http://requirejs.org/" rel="nofollow noreferrer">http://requirejs.org/</a></li> <li><a href="http://www.bennadel.com/blog/2275-Using-RequireJS-For-Asynchronous-Script-Loading-And-JavaScript-Dependency-Management.htm" rel="nofollow noreferrer">http://www.bennadel.com/blog/2275-Using-RequireJS-For-Asynchronous-Script-Loading-And-JavaScript-Dependency-Management.htm</a></li> <li><a href="https://github.com/Integralist/Blog-Posts/blob/master/2012-01-04-Beginners-guide-to-AMD-and-RequireJS.md" rel="nofollow noreferrer">https://github.com/Integralist/Blog-Posts/blob/master/2012-01-04-Beginners-guide-to-AMD-and-RequireJS.md</a></li> </ul>
853,405
What does the Subversion status symbol "~" mean?
<p>I am getting a tilde symbol when I do an <code>svn status</code>.</p> <p>Here is the output of the project after editing it in XCode.</p> <pre><code>svn status M build/Currency_Converter.build/Currency_Converter.pbxindex/imports.pbxbtree M build/Currency_Converter.build/Currency_Converter.pbxindex/pbxindex.header M build/Currency_Converter.build/Currency_Converter.pbxindex/symbols0.pbxsymbols ~ build/Currency_Converter.build/Currency_Converter.pbxindex/strings.pbxstrings M main.m //more changed files </code></pre> <p>Any idea what that means? Can't seem to find it on google or any of the svn cheat sheets.</p> <p>Interestingly, I only edited main.m, but there are lots of modified files. I don't know why that would be. Anyone have any tips for working with SVN and XCode? Should I only be putting my source files under version control?</p> <p><strong>Edit:</strong> Caused by a file that was already under version control being replaced by a file of another type. In this case, strings.pbxstrings used to be a file and now became a directory. Moral of the story is don't put your build folder into version control.</p>
853,418
11
1
null
2009-05-12 15:36:49.503 UTC
23
2021-02-19 16:19:35.66 UTC
2021-02-19 16:19:35.66 UTC
null
1,783,163
null
78,093
null
1
114
svn|xcode|status
75,330
<p>The <a href="http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.status.html" rel="noreferrer">SVN Book</a> says:</p> <blockquote> <p>Item is versioned as one kind of object (file, directory, link), but has been replaced by different kind of object.</p> </blockquote> <p>So perhaps it was originally a single file, but you changed it to a directory, or something along those lines?</p>
965,694
What's the official way of storing settings for Python programs?
<p><code>Django</code> uses real Python files for settings, <code>Trac</code> uses a <code>.ini</code> file, and some other pieces of software uses XML files to hold this information.</p> <p>Are one of these approaches blessed by Guido and/or the Python community more than another?</p>
965,795
13
3
null
2009-06-08 16:13:02.43 UTC
15
2021-11-27 17:59:26.927 UTC
2021-05-05 00:41:28.193 UTC
null
98,855
null
98,855
null
1
65
python|settings
44,343
<p>Depends on the predominant intended audience.</p> <p>If it is programmers who change the file anyway, just use python files like settings.py</p> <p>If it is end users then, think about ini files.</p>
262,727
How do you measure the quality of your unit tests?
<p>If you (or your organization) aspires to thoroughly unit test your code, how do you measure the success or quality of your efforts? </p> <ul> <li>Do you use code coverage, what percentage do you aim for? </li> <li>Do you find that philosophies like TDD have a better impact than metrics?</li> </ul>
262,888
14
0
null
2008-11-04 17:57:22.653 UTC
9
2021-09-22 02:19:55.407 UTC
2013-11-14 22:01:06.173 UTC
user1228
null
vfilby
24,279
null
1
41
unit-testing|testing|tdd
12,971
<p>My tip is not a way to determine whether you have good unit tests per se, but it's a way to grow a good test suite over time.</p> <p>Whenever you encounter a bug, either in your development or reported by someone else, fix it twice. You first create a unit test that reproduces the problem. When you've got a failing test, then you go and fix the problem.</p> <p>If a problem was there in the first place it's a hint about a subtlety about the code or the domain. Adding a test for it lets you make sure it's never going to be reintroduced in the future.</p> <p>Another interesting aspect about this approach is that it'll help you understand the problem from a higher level before you actually go and look at the intricacies of the code.</p> <p>Also, +1 for the value and pitfalls of test coverage already mentioned by others.</p>
209,418
What are some JavaScript unit testing and mocking frameworks you have used?
<p>My main JavaScript framework is <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>, so I would like my unit test and mocking frameworks to be compatible with that. I'd rather not have to introduce another JavaScript framework.</p> <p>I am currently using <a href="http://docs.jquery.com/QUnit" rel="nofollow noreferrer">QUnit</a> for unit testing and <a href="https://github.com/keronsen/jack" rel="nofollow noreferrer">Jack</a> for mocking, but I am pretty new to the whole unit testing of JavaScript.</p> <p>Is there a better tool to suggest? What has worked for you?</p>
209,692
14
3
null
2008-10-16 16:56:34.497 UTC
29
2021-06-27 09:38:00.55 UTC
2021-01-11 07:13:13.517 UTC
JasonBunting
63,550
Elijah Manor
4,481
null
1
42
javascript|jquery|unit-testing|mocking|qunit
22,518
<p><a href="http://docs.jquery.com/QUnit" rel="nofollow noreferrer">QUnit</a> <br/> <a href="http://code.google.com/p/jqunit/" rel="nofollow noreferrer">jqUnit</a> <br/> <a href="http://wiki.fluidproject.org/display/fluid/Writing+JavaScript+Unit+Tests" rel="nofollow noreferrer">Writing JavaScript tests with QUnit and jqUnit</a></p> <p>QUnit is the unit testing framework for the jQuery JavaScript framework. The testing framework itself uses the jQuery library, but the tests can be written for any JavaScript and do not require the code to use jQuery.</p> <p>jqUnit is a modified version of QUnit that adds in the setup, teardown, and assert functions that are more typical of an xUnit framework, and encapsulates everything in one global variable.</p> <p>The visual interface of the testrunner page is nice, allowing you to drill down and see each assert in every test method. Writing tests is fairly easy, and you can run the test code directly on the testRunner page [8]. This allows for easy and visible DOM testing.</p> <p>QUnit: MIT or GPL (choose) jqUnit: MIT License</p> <p><strong>Pros</strong></p> <ul> <li>Asynchronous support</li> <li>Good for DOM testing</li> <li>Tests always run sequentially in the order they are added to a suite</li> <li>Debug on test page using firebug</li> <li>Syntax is similar to JUnit if using jqUnit, but simple to learn if using QUnit</li> </ul> <p><strong>Cons</strong></p> <ul> <li>Automation would be difficult to implement</li> </ul>
1,070,354
How do I get the current date in Cocoa
<p>I'm getting started developing for the iPhone and as such I am looking at different tutorials online as well as trying some different things out myself. Currently, I'm trying to create a countdown until midnight. To get the number of hour, minutes, and seconds, I do the following (which I found somewhere):</p> <pre><code>NSDate* now = [NSDate date]; int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay]; int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour]; int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute]; countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec]; </code></pre> <p>However, each place I use <code>-dateWithCalendarFormat:timeZone:</code> I get the following error:</p> <pre><code>warning: 'NSDate' may not respond to '-dateWithCalendarFormat:timeZone:' (Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments.) warning: no '-hourOfDay' method found error: invalid operands to binary - (have 'int' and 'id') </code></pre> <p>This seems like something very simple. What am I missing?</p> <p>Also, I've noticed at different places and at different times the asterisk (*) is located either right after the time <code>NSDate* now</code> or right before the variable <code>NSDate *now</code>. What is the difference in the two and why would you use one versus the other? </p>
1,070,412
14
0
null
2009-07-01 17:25:18.233 UTC
23
2015-12-13 10:17:22.347 UTC
2009-07-01 21:26:26.603 UTC
null
120,292
null
91,632
null
1
60
objective-c|cocoa|nsdate
131,526
<p>You must use the following:</p> <pre><code>NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere]; NSInteger hour = [dateComponents hour]; NSInteger minute = [dateComponents minute]; NSInteger second = [dateComponents second]; [gregorian release]; </code></pre> <p>There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.</p>
228,620
Garbage Collection in C++ -- why?
<p>I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right?</p> <p>My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it.</p> <p>What advantages could garbage collection offer an experienced C++ developer?</p>
228,722
16
3
null
2008-10-23 05:24:59.43 UTC
26
2015-05-06 16:43:12.703 UTC
2008-10-23 05:31:03.677 UTC
coppro
16,855
Head Geek
12,193
null
1
48
c++|garbage-collection|c++11
15,071
<h2>I keep hearing people complaining that C++ doesn't have garbage collection.</h2> <p>I am so sorry for them. Seriously.</p> <p>C++ has RAII, and I always complain to find no RAII (or a castrated RAII) in Garbage Collected languages.</p> <h2>What advantages could garbage collection offer an experienced C++ developer?</h2> <p>Another tool.</p> <p>Matt J wrote it quite right in his post (<a href="https://stackoverflow.com/questions/228620/garbage-collection-in-c-why#228640">Garbage Collection in C++ -- why?</a>): We don't need C++ features as most of them could be coded in C, and we don't need C features as most of them could coded in Assembly, etc.. <strong>C++ must evolve.</strong></p> <p>As a developer: I don't care about GC. I tried both RAII and GC, and I find RAII vastly superior. As said by Greg Rogers in his post (<a href="https://stackoverflow.com/questions/228620/garbage-collection-in-c-why#228670">Garbage Collection in C++ -- why?</a>), memory leaks are not so terrible (at least in C++, where they are rare if C++ is really used) as to justify GC instead of RAII. GC has non deterministic deallocation/finalization and is just a way to <strong>write a code that just don't care with specific memory choices</strong>.</p> <p>This last sentence is important: It is important to write code that &quot;juste don't care&quot;. In the same way in C++ RAII we don't care about ressource freeing because RAII do it for us, or for object initialization because constructor do it for us, it is sometimes important to just code without caring about who is owner of what memory, and what kind pointer (shared, weak, etc.) we need for this or this piece of code. <strong>There seems to be a need for GC in C++.</strong> (even if I personaly fail to see it)</p> <h2>An example of good GC use in C++</h2> <p>Sometimes, in an app, you have &quot;floating data&quot;. Imagine a tree-like structure of data, but no one is really &quot;owner&quot; of the data (and no one really cares about when exactly it will be destroyed). Multiple objects can use it, and then, discard it. You want it to be freed when no one is using it anymore.</p> <p>The C++ approach is using a smart pointer. The boost::shared_ptr comes to mind. So each piece of data is owned by its own shared pointer. Cool. The problem is that when each piece of data can refer to another piece of data. You cannot use shared pointers because they are using a reference counter, which won't support circular references (A points to B, and B points to A). So you must know think a lot about where to use weak pointers (boost::weak_ptr), and when to use shared pointers.</p> <p>With a GC, you just use the tree structured data.</p> <p>The downside being that you must not care <strong>when</strong> the &quot;floating data&quot; will really be destroyed. Only that it <strong>will be</strong> destroyed.</p> <h2>Conclusion</h2> <p>So in the end, if done properly, and compatible with the current idioms of C++, GC would be a <strong>Yet Another Good Tool for C++</strong>.</p> <p>C++ is a multiparadigm language: Adding a GC will perhaps make some C++ fanboys cry because of treason, but in the end, it could be a good idea, and I guess the C++ Standards Comitee won't let this kind of major feature break the language, so we can trust them to make the necessary work to enable a correct C++ GC that won't interfere with C++: <strong>As always in C++, if you don't need a feature, don't use it and it will cost you nothing.</strong></p>
434,597
Open document with default OS application in Python, both in Windows and Mac OS
<p>I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?</p>
434,612
16
1
null
2009-01-12 06:23:51.247 UTC
43
2022-08-17 11:59:22.387 UTC
2019-05-08 05:57:13.53 UTC
null
202,229
Abdullah Jibaly
47,110
null
1
165
python|windows|macos
122,492
<p><code>open</code> and <code>start</code> are command-interpreter things for Mac OS/X and Windows respectively, to do this.</p> <p>To call them from Python, you can either use <code>subprocess</code> module or <code>os.system()</code>. </p> <p>Here are considerations on which package to use:</p> <ol> <li><p>You can call them via <code>os.system</code>, which works, but...</p> <p><strong>Escaping:</strong> <code>os.system</code> only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. <code>A:\abc\def\a.txt</code>), or else these need to be escaped. There is <code>shlex.quote</code> for Unix-like systems, but nothing really standard for Windows. Maybe see also <a href="https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex">python, windows : parsing command lines with shlex</a></p> <ul> <li>MacOS/X: <code>os.system("open " + shlex.quote(filename))</code></li> <li>Windows: <code>os.system("start " + filename)</code> where properly speaking <code>filename</code> should be escaped, too.</li> </ul></li> <li><p>You can also call them via <code>subprocess</code> module, but...</p> <p>For Python 2.7 and newer, simply use</p> <pre><code>subprocess.check_call(['open', filename]) </code></pre> <p>In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile</p> <pre><code>subprocess.run(['open', filename], check=True) </code></pre> <p>If you need to be compatible all the way back to Python 2.4, you can use <code>subprocess.call()</code> and implement your own error checking:</p> <pre><code>try: retcode = subprocess.call("open " + filename, shell=True) if retcode &lt; 0: print &gt;&gt;sys.stderr, "Child was terminated by signal", -retcode else: print &gt;&gt;sys.stderr, "Child returned", retcode except OSError, e: print &gt;&gt;sys.stderr, "Execution failed:", e </code></pre> <p>Now, what are the advantages of using <code>subprocess</code>?</p> <ul> <li><strong>Security:</strong> In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type <code>'filename ; rm -rf /'</code>" problem, and <strong>if</strong> the file name can be corrupted, using <code>subprocess.call</code> gives us little additional protection.</li> <li><strong>Error handling:</strong> It doesn't actually give us any more error detection, we're still depending on the <code>retcode</code> in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).</li> <li><strong>Spawns a (non-blocking) subprocess</strong>: We don't need to wait for the child process, since we're by problem statement starting a separate process.</li> </ul> <p>To the objection "But <code>subprocess</code> is preferred." However, <code>os.system()</code> is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using <code>os.system()</code> is therefore also a correct answer.</p> <p>A marked <strong>disadvantage</strong> is that the Windows <code>start</code> command <em>requires</em> you to pass in <code>shell=True</code> which negates most of the benefits of using <code>subprocess</code>.</p></li> </ol>
202,302
Rounding to an arbitrary number of significant digits
<p>How can you round <em>any</em> number (not just integers > 0) to N significant digits?</p> <p>For example, if I want to round to three significant digits, I'm looking for a formula that could take:</p> <p>1,239,451 and return 1,240,000</p> <p>12.1257 and return 12.1</p> <p>.0681 and return .0681</p> <p>5 and return 5</p> <p>Naturally the algorithm should not be hard-coded to only handle N of 3, although that would be a start.</p>
1,581,007
17
1
null
2008-10-14 18:37:17.603 UTC
23
2020-07-12 13:28:07.47 UTC
2017-05-04 20:18:18.193 UTC
Cristi&#225;n Romo
63,550
DougN
7,442
null
1
85
algorithm|rounding|significant-digits
41,788
<p>Here's the same code in Java without the 12.100000000000001 bug other answers have</p> <p>I also removed repeated code, changed <code>power</code> to a type integer to prevent floating issues when <code>n - d</code> is done, and made the long intermediate more clear</p> <p>The bug was caused by multiplying a large number with a small number. Instead I divide two numbers of similar size.</p> <p><strong>EDIT</strong><br> Fixed more bugs. Added check for 0 as it would result in NaN. Made the function actually work with negative numbers (The original code doesn't handle negative numbers because a log of a negative number is a complex number)</p> <pre><code>public static double roundToSignificantFigures(double num, int n) { if(num == 0) { return 0; } final double d = Math.ceil(Math.log10(num &lt; 0 ? -num: num)); final int power = n - (int) d; final double magnitude = Math.pow(10, power); final long shifted = Math.round(num*magnitude); return shifted/magnitude; } </code></pre>
101,055
When is a language considered a scripting language?
<p>What makes a language a scripting language? I've heard some people say &quot;when it gets interpreted instead of compiled&quot;. That would make PHP (for example) a scripting language. Is that the only criterion? Or are there other criteria?</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/98268/whats-the-difference-between-a-script-and-an-application">What’s the difference between a “script” and an “application”?</a></li> </ul>
101,077
40
10
2010-06-15 21:34:53.79 UTC
2008-09-19 10:51:26.717 UTC
72
2014-07-03 10:04:39.903 UTC
2020-06-20 09:12:55.06 UTC
Andy Lester
-1
Sietse de Kaper
6,400
null
1
107
programming-languages|scripting|terminology|semantics
129,137
<p>A scripting language is a language that "scripts" other things to do stuff. The primary focus isn't primarily building your own apps so much as getting an existing app to act the way you want, e.g. JavaScript for browsers, VBA for MS Office.</p>
487,073
How to check if element is visible after scrolling?
<p>I'm loading elements via AJAX. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?</p>
488,073
46
11
null
2009-01-28 10:00:55.303 UTC
509
2022-02-25 09:01:26.353 UTC
2020-07-02 19:59:13.703 UTC
user10758159
362,780
yoavf
1,011
null
1
1,336
javascript|jquery|scroll
850,959
<p>This should do the trick:</p> <pre><code>function isScrolledIntoView(elem) { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom &lt;= docViewBottom) &amp;&amp; (elemTop &gt;= docViewTop)); } </code></pre> <p><strong>Simple Utility Function</strong> This will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.</p> <pre><code>function Utils() { } Utils.prototype = { constructor: Utils, isElementInView: function (element, fullyInView) { var pageTop = $(window).scrollTop(); var pageBottom = pageTop + $(window).height(); var elementTop = $(element).offset().top; var elementBottom = elementTop + $(element).height(); if (fullyInView === true) { return ((pageTop &lt; elementTop) &amp;&amp; (pageBottom &gt; elementBottom)); } else { return ((elementTop &lt;= pageBottom) &amp;&amp; (elementBottom &gt;= pageTop)); } } }; var Utils = new Utils(); </code></pre> <p><strong>Usage</strong></p> <pre><code>var isElementInView = Utils.isElementInView($('#flyout-left-container'), false); if (isElementInView) { console.log('in view'); } else { console.log('out of view'); } </code></pre>
6,958,413
Xcode: show documentation for my custom classes
<p>How can I force Xcode to show my own documentation for custom classes, methods, etc.? I'm used to Java and Eclipse, which shows me documentation for my classes as shown here:</p> <p><img src="https://i.stack.imgur.com/czyo4.png" alt="Eclipse showing Javadocs documentation"></p> <p>How can I achieve the same in Xcode? Are there special comments that Xcode can recognize and display?</p> <p><img src="https://i.stack.imgur.com/AvFpa.png" alt="Xcode showing generic documentation for NSObject"></p>
19,258,190
5
2
null
2011-08-05 15:02:07.197 UTC
21
2015-06-23 17:44:49.837 UTC
2015-02-05 14:36:00.55 UTC
null
3,366,929
null
47,190
null
1
49
xcode
15,946
<p>As of Xcode 5.0, Doxygen and HeaderDoc formatting for variables and methods is automatically parsed and rendered in the Quick Help popover. More information about it <a href="http://confusatory.org/post/63488534619/documentation-in-xcode-5" rel="noreferrer">here</a>, but here's some key bits:</p> <pre><code>/** * Add a data point to the data source. * (Removes the oldest data point if the data source contains kMaxDataPoints objects.) * * @param aDataPoint An instance of ABCDataPoint. * @return The oldest data point, if any. */ - (ABCDataPoint *)addDataToDataSource:(ABCDataPoint *)aDataPoint; </code></pre> <p>renders in Xcode as:</p> <p><img src="https://media.tumblr.com/bb59b3c3066ca01074c4c5458d8f57d6/tumblr_inline_mud7ufhJ4Q1qzs6su.png" alt=""></p> <p>As for properties, it's as easy as:</p> <pre><code>/// Base64-encoded data. @property (nonatomic, strong) NSData *data; </code></pre> <p>When option-clicked, this lovely popover appears:</p> <p><img src="https://media.tumblr.com/22e6403fae4f63663ff433791006b937/tumblr_inline_mud80we32h1qzs6su.png" alt=""></p>
6,892,044
Add virtual attribute to json output
<p>Let's say I have an app that handles a TODO list. The list has finished and unfinished items. Now I want to add two virtual attributes to the list object; the count of finished and unfinished items in the list. I also need these to be displayed in the json output.</p> <p>I have two methods in my model which fetches the unfinished/finished items:</p> <pre><code>def unfinished_items self.items.where("status = ?", false) end def finished_items self.items.where("status = ?", true) end </code></pre> <p>So, how can I get the count of these two methods in my json output?</p> <p>I'm using Rails 3.1</p>
6,892,207
8
1
null
2011-07-31 20:16:34.54 UTC
11
2021-01-26 11:28:30.497 UTC
2015-03-29 16:31:02.467 UTC
null
650,711
null
650,711
null
1
68
ruby-on-rails|json
32,826
<p>The serialization of objects in Rails has two steps:</p> <ul> <li>First, <code>as_json</code> is called to convert the object to a simplified Hash.</li> <li>Then, <code>to_json</code> is called on the <code>as_json</code> return value to get the final JSON string.</li> </ul> <p>You generally want to leave <code>to_json</code> alone so all you need to do is add <a href="http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json" rel="noreferrer">your own <code>as_json</code> implementation</a> sort of like this:</p> <pre><code>def as_json(options = { }) # just in case someone says as_json(nil) and bypasses # our default... super((options || { }).merge({ :methods =&gt; [:finished_items, :unfinished_items] })) end </code></pre> <p>You could also do it like this:</p> <pre><code>def as_json(options = { }) h = super(options) h[:finished] = finished_items h[:unfinished] = unfinished_items h end </code></pre> <p>if you wanted to use different names for the method-backed values.</p> <p>If you care about XML and JSON, have a look at <a href="http://api.rubyonrails.org/classes/ActiveModel/Serialization.html" rel="noreferrer"><code>serializable_hash</code></a>.</p>
6,953,487
Hide Tab Header on C# TabControl
<p>I am developing a Windows Form Application with several pages. I am using a TabControl to implement this. Instead of using the header to switch between tabs, I want my application to control this e.g. the next tab should open after the user has filled in a text box and clicked the next button.</p>
6,953,766
10
7
null
2011-08-05 08:31:09.053 UTC
22
2020-10-27 02:36:39.687 UTC
2015-04-24 14:06:12.407 UTC
null
4,516,316
null
860,721
null
1
54
c#|winforms|tabcontrol
54,196
<p>You can replace tabcontrol with a hand made panel that mimic like you want:</p> <pre><code>class MultiPagePanel : Panel { private int _currentPageIndex; public int CurrentPageIndex { get { return _currentPageIndex; } set { if (value &gt;= 0 &amp;&amp; value &lt; Controls.Count) { Controls[value].BringToFront(); _currentPageIndex = value; } } } public void AddPage(Control page) { Controls.Add(page); page.Dock = DockStyle.Fill; } } </code></pre> <p>And then add pages and set current visible page:</p> <pre><code>MultiPagePanel p; // MyTabPage is a Control derived class that represents one page on your form. MyTabPage page = new MyTabPage(); p.AddPage(page); p.CurrentPageIndex = 0; </code></pre>
57,507,832
Unable to allocate array with shape and data type
<p>I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS.</p> <p>I am trying to allocate memory for a numpy array with shape <code>(156816, 36, 53806)</code> with </p> <pre><code>np.zeros((156816, 36, 53806), dtype='uint8') </code></pre> <p>and while I'm getting an error on Ubuntu OS</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.zeros((156816, 36, 53806), dtype='uint8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; numpy.core._exceptions.MemoryError: Unable to allocate array with shape (156816, 36, 53806) and data type uint8 </code></pre> <p>I'm not getting it on MacOS:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.zeros((156816, 36, 53806), dtype='uint8') array([[[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], [[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], [[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], ..., [[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], [[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], [[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]]], dtype=uint8) </code></pre> <p>I've read somewhere that <code>np.zeros</code> shouldn't be really allocating the whole memory needed for the array, but only for the non-zero elements. Even though the Ubuntu machine has 64gb of memory, while my MacBook Pro has only 16gb.</p> <p>versions:</p> <pre><code>Ubuntu os -&gt; ubuntu mate 18 python -&gt; 3.6.8 numpy -&gt; 1.17.0 mac os -&gt; 10.14.6 python -&gt; 3.6.4 numpy -&gt; 1.17.0 </code></pre> <p>PS: also failed on Google Colab</p>
57,511,555
8
13
null
2019-08-15 09:48:35.317 UTC
77
2022-08-12 13:35:28.977 UTC
2019-08-15 15:29:28.85 UTC
null
1,968
null
5,123,537
null
1
188
python|numpy|data-science
620,677
<p>This is likely due to your system's <a href="https://www.kernel.org/doc/Documentation/vm/overcommit-accounting" rel="noreferrer">overcommit handling</a> mode.</p> <p>In the default mode, <code>0</code>,</p> <blockquote> <p>Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. The root is allowed to allocate slightly more memory in this mode. This is the default.</p> </blockquote> <p>The exact heuristic used is not well explained here, but this is discussed more on <a href="https://stackoverflow.com/questions/38688824/linux-over-commit-heuristic">Linux over commit heuristic</a> and <a href="http://engineering.pivotal.io/post/virtual_memory_settings_in_linux_-_the_problem_with_overcommit/" rel="noreferrer">on this page</a>.</p> <p>You can check your current overcommit mode by running</p> <pre><code>$ cat /proc/sys/vm/overcommit_memory 0 </code></pre> <p>In this case, you're allocating</p> <pre><code>&gt;&gt;&gt; 156816 * 36 * 53806 / 1024.0**3 282.8939827680588 </code></pre> <p>~282 GB and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.</p> <p>If (as root) you run:</p> <pre><code>$ echo 1 &gt; /proc/sys/vm/overcommit_memory </code></pre> <p>This will enable the &quot;always overcommit&quot; mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).</p> <p>I tested this myself on a machine with 32 GB of RAM. With overcommit mode <code>0</code> I also got a <code>MemoryError</code>, but after changing it back to <code>1</code> it works:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.zeros((156816, 36, 53806), dtype='uint8') &gt;&gt;&gt; a.nbytes 303755101056 </code></pre> <p>You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.</p>
16,028,678
AngularJS - access elements outside of ng-view
<p>I have a setup with an ng-view (an admin panel) that lets me display orders. I have a search box outside of ng-view that I would like to use to modify my json request. I've seen some posts on accessing things such as the title but was not able to get them to work - perhaps outdated.</p> <p>Main app stuff:</p> <pre><code>angular.module('myApp', ['myApp.controllers', 'myApp.filters', 'myApp.services', 'myApp.directives', 'ui.bootstrap']). config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when('/', { templateUrl: '/partials/order/manage.html', controller: 'ManageOrderCtrl' }). when('/order/:id', { templateUrl: '/partials/order/view.html', controller: 'ViewOrderCtrl' }). otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]); </code></pre> <p>Manage controller:</p> <pre><code>angular.module('myApp.controllers', []) .controller('ManageOrderCtrl', ['$scope', '$http', '$dialog', 'config', 'Page', function($scope, $http, $dialog, config, Page) { // would like to have search value from input #search available here var getData = function() { $http.get('/orders'). success(function(data, status, headers, config) { $scope.orders = data.orders; }); }; getData(); }) </code></pre> <p>View:</p> <pre><code>&lt;body ng-app="myApp" &gt; &lt;input type="text" id="search"&gt; &lt;div class="ng-cloak" &gt; &lt;div ng-view&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
16,030,862
3
0
null
2013-04-16 04:15:05.27 UTC
11
2014-08-18 12:56:29.113 UTC
null
null
null
null
856,498
null
1
20
javascript|angularjs
30,732
<p>If you're going to access stuff outside the <code>&lt;div ng-view&gt;&lt;/div&gt;</code>, I think a better approach would be to create a controller for the outer region as well. Then you create a service to share data between the controllers:</p> <pre class="lang-html prettyprint-override"><code>&lt;body ng-app="myApp" &gt; &lt;div ng-controller="MainCtrl"&gt; &lt;input type="text" id="search"&gt; &lt;/div&gt; &lt;div class="ng-cloak" &gt; &lt;div ng-view&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>(<code>ng-controller="MainCtrl"</code> can also be placed on the <code>&lt;body&gt;</code> tag - then the ng-view $scope would be a child of the MainCtrl $scope instead of a sibling.)</p> <p>Creating the service is as simple as this:</p> <pre class="lang-js prettyprint-override"><code>app.factory('Search',function(){ return {text:''}; }); </code></pre> <p>And it's injectable like this:</p> <pre class="lang-js prettyprint-override"><code>app.controller('ManageOrderCtrl', function($scope,Search) { $scope.searchFromService = Search; }); app.controller('MainCtrl',function($scope,Search){ $scope.search = Search; }); </code></pre> <p>This way you don't have to rely on sharing data through the global $rootScope (which is kinda like relying on global variables in javascript - a bad idea for all sorts of reasons) or through a $parent scope which may or may not be present.</p> <p>I've created a <a href="http://plnkr.co/edit/8LwPRy3ssdT6wWLuvqNB" rel="noreferrer"><strong>plnkr</strong> that tries to show the difference</a> between the two solutions.</p>
15,923,664
Rendering different views in one action
<p>I want to have 2 kinds of views for the same posts in my rails application. For instance - in one where a logged in user can update and edit the post, and in the other any user can just view it and comment on it or select it.</p> <p>How should I go about this? Do I need a separate class? I know I need a separate view for each, but how about the model and the controller?</p>
15,923,870
1
0
null
2013-04-10 10:45:52.377 UTC
6
2014-08-22 08:27:39.457 UTC
2013-04-10 12:37:40.823 UTC
null
1,279,707
null
1,043,612
null
1
29
ruby-on-rails|ruby-on-rails-3|class|model-view-controller|view
18,590
<p><strong><em>1.case:</em></strong> your views are going to have similar content, but only the signed in users will have extra options like editing. </p> <p>You should use a partial view and in your main view you should write something like this:</p> <pre><code>&lt;% if signed_in? %&gt; &lt;%= render 'edit_form' %&gt; &lt;% end %&gt; </code></pre> <p>Remember, the name of the partial should always start with a underscore, so your partial in this case would be called <code>_edit_form.html.erb</code> or <code>_edit_form.html.haml</code>, depending on what you are using.</p> <p><strong><em>2.case:</em></strong> depending on if the user is signed in or not, you want to render completely different views, then you should handle it in your controller:</p> <pre><code>def show if signed_in? render 'show_with_edit' else render 'show_without_edit` end end </code></pre> <p>And your files would be named <code>show_with_edit.html.erb</code> and <code>show_without_edit.html.erb</code></p> <p>Also, if your view for a signed in user was called <code>show</code> then you could just do this:</p> <pre><code>def show render 'show_without_edit' unless signed_in? end </code></pre> <p><strong><em>3.case:</em></strong> if you want to change basically EVERYTHING depending if the user is signed in or not, you could create some custom methods and call them inside your original action like this:</p> <pre><code>def show if singed_in? show_signed_in else show_not_signed_in end end private def show_signed_in # declaring some instance variables to use in the view.. render 'some_view' end def show_not_signed_in # declaring some other instance variables to use in the view.. render 'some_other_view' end </code></pre>
15,746,271
Point of declaration in C++
<p>Why isn't the output <code>101</code> while I assigned the previous <code>x</code> to the new <code>x</code>?</p> <pre><code>int x = 101; { int x = x; std::cout &lt;&lt; x &lt;&lt; std::endl; } </code></pre> <p>Output (garbage):</p> <blockquote> <p>422634</p> </blockquote> <p>I thought the second <code>x</code> would be initialized to <code>101</code> but it isn't initialized.</p> <p>Note: The solution in this case is <code>int x = ::x</code> but the question is <em>why</em> it happens.</p>
15,746,272
3
2
null
2013-04-01 15:26:28.28 UTC
6
2015-01-27 07:23:48.437 UTC
2013-10-02 07:04:56.73 UTC
null
952,747
null
952,747
null
1
33
c++
2,095
<h2><em>Point of declaration</em></h2> <blockquote> <p>The point of declaration for a name is immediately after its complete declarator and before its initializer... [C++ Standard § 3.3.2/1]</p> </blockquote> <p>Compiler completes the declaration when it knows enough about declarator.</p> <p>Above code is equal to the below one:</p> <pre><code>int x = 101; { int x; x = x; &lt;------------------// Self assignment, assigns an indeterminate value. std::cout &lt;&lt; x &lt;&lt; std::endl; } </code></pre> <p>Because, the declaration of inner <code>x</code> completed before <code>=</code> (assignment)</p> <pre><code>int x = x; &lt;--// Now, we have the new `x` which hides the older one, ^ // so it assigns itself to itself | +---// Point of declaration, // here compiler knows everything to declare `x`. // then declares it. </code></pre> <p>&nbsp;</p> <p>On the other hand, when we declaring complex objects, the point of declaration is farther. So, the behavior is different.</p> <p>For example, below code is OK</p> <pre><code>const int i = 2; { int i[i]; ^ | +----// Point of declaration // compiler has to reach to "]" // therefore before declaring `i` as an array // there is just one `i`, the `i` of `const int i=2` } </code></pre> <p>In above code, compiler has to know the actual size of the array to complete the declaration, so the point of declaration is <code>]</code>. Therefore the <code>i</code> within <code>[i]</code> is the outer <code>i</code> because declaration of the <code>i</code> of <code>int i[...</code> isn't completed yet. Thus, it declares an array with <code>2</code> elements (<code>int i[2];</code>).</p> <p>&nbsp;</p> <p>Also, this example shows the point of declaration for an enumerator</p> <pre><code>const int x = 12; { enum { x = x }; ^ | +---// Point of declaration // compiler has to reach to "}" then // there is just one `x`, the `x` of `const int x=12` } </code></pre> <p>The enumerator <code>x</code> is initialized with the value of the constant <code>x</code>, namely <code>12</code>.</p>
10,325,095
ThreeJS camera.lookAt() has no effect, is there something I'm doing wrong?
<p>In Three.js, I want a camera to be pointed at a point in 3D space.</p> <p>For this purpose, I tried using the <code>camera.lookAt</code> function like so:</p> <pre><code>camera.lookAt(new THREE.Vector3(-100,-100,0)); </code></pre> <p>However, I found out that the call has no effect whatsoever. It just does nothing at all. I tried changing the numbers in the vector, and I always get the same look on screen, when it should be changing.</p> <p>I just found now that if I remove the <code>THREE.TrackballControls</code> I have in my code, the <code>camera.lookAt()</code> works as it should. Is there something wrong with how I use THREE.TrackballControls? This is how I initialize them:</p> <pre><code> controls = new THREE.TrackballControls( camera, renderer.domElement ); controls.rotateSpeed = 10.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.2; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 1.0; var radius = 5; controls.minDistance = radius * 1.1; controls.maxDistance = radius * 100; controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]*/ </code></pre> <p>And then in my render function I do:</p> <pre><code>function render() { controls.update(); renderer.render(scene, camera); } </code></pre> <p>Documentation on Three.js is pretty scarce, so I thought I'd ask here. Am I doing something wrong?</p>
10,337,588
6
6
null
2012-04-25 23:12:32.05 UTC
5
2022-02-23 23:54:04.727 UTC
2012-04-26 12:29:16.533 UTC
null
363,078
null
363,078
null
1
38
javascript|macos|google-chrome|3d|three.js
25,644
<p>Looking at the source code of <a href="https://github.com/mrdoob/three.js/blob/master/src/extras/controls/TrackballControls.js"><code>THREE.TrackballControls</code></a>, I figured out that I can make the camera look where I want by setting <code>trackballControls.target</code> to the <code>THREE.Vector3</code> I want it to look at, and then rerendering the scene.</p>
25,368,337
Tuple or list when using 'in' in an 'if' clause?
<p>Which approach is better? Using a tuple, like:</p> <pre><code>if number in (1, 2): </code></pre> <p>or a list, like:</p> <pre><code>if number in [1, 2]: </code></pre> <p>Which one is recommended for such uses and why (both logical and performance wise)? </p>
25,368,371
1
7
null
2014-08-18 16:58:06.463 UTC
12
2020-05-14 04:11:02.29 UTC
2014-08-18 17:16:18 UTC
null
100,297
null
433,940
null
1
36
python|list|optimization|tuples|python-internals
2,475
<p>The CPython interpreter <em>replaces the second form with the first</em>.</p> <p>That's because loading the tuple from a constant is one operation, but the list would be 3 operations; load the two integer contents and build a new list object.</p> <p>Because you are using a list literal that isn't otherwise reachable, it is substituted for a tuple:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile('number in [1, 2]', '&lt;stdin&gt;', 'eval')) 1 0 LOAD_NAME 0 (number) 3 LOAD_CONST 2 ((1, 2)) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE </code></pre> <p>Here the second bytecode loads a <code>(1, 2)</code> tuple as a constant, in <em>one</em> step. Compare this to creating a list object not used in a membership test:</p> <pre><code>&gt;&gt;&gt; dis.dis(compile('[1, 2]', '&lt;stdin&gt;', 'eval')) 1 0 LOAD_CONST 0 (1) 3 LOAD_CONST 1 (2) 6 BUILD_LIST 2 9 RETURN_VALUE </code></pre> <p>Here N+1 steps are required for a list object of length N.</p> <p>This substitution is a CPython-specific peephole optimisation; see the <a href="http://hg.python.org/cpython/file/66d6fa61ac38/Python/peephole.c#l84" rel="noreferrer"><code>Python/peephole.c</code> source</a>. For <strong>other</strong> Python implementations then, you want to stick with immutable objects instead.</p> <p>That said, the <em>best</em> option when using Python 3.2 and up, is to use a <em>set literal</em>:</p> <pre><code>if number in {1, 2}: </code></pre> <p>as the peephole optimiser will replace that with a <code>frozenset()</code> object and membership tests against sets are O(1) constant operations:</p> <pre><code>&gt;&gt;&gt; dis.dis(compile('number in {1, 2}', '&lt;stdin&gt;', 'eval')) 1 0 LOAD_NAME 0 (number) 3 LOAD_CONST 2 (frozenset({1, 2})) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE </code></pre> <p>This optimization was added in <a href="https://docs.python.org/3/whatsnew/3.2.html#optimizations" rel="noreferrer">Python 3.2</a> but wasn't backported to Python 2.</p> <p>As such, the Python 2 optimiser doesn't recognize this option and the cost of building either a <code>set</code> or <code>frozenset</code> from the contents is almost guaranteed to be more costly than using a tuple for the test.</p> <p>Set membership tests are O(1) and fast; testing against a tuple is O(n) worst case. Although testing against a set has to calculate the hash (higher constant cost, cached for immutable types), the cost for testing against a tuple <em>other than the first element</em> is always going to be higher. So on average, sets are easily faster:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('1 in (1, 3, 5)', number=10**7) # best-case for tuples 0.21154764899984002 &gt;&gt;&gt; timeit.timeit('8 in (1, 3, 5)', number=10**7) # worst-case for tuples 0.5670104179880582 &gt;&gt;&gt; timeit.timeit('1 in {1, 3, 5}', number=10**7) # average-case for sets 0.2663505630043801 &gt;&gt;&gt; timeit.timeit('8 in {1, 3, 5}', number=10**7) # worst-case for sets 0.25939063701662235 </code></pre>
40,027,974
Interesting 16x16 grid sum
<p>EDIT: Path, not line --- it can wind around and stuff. The path connects adjacent squares. You cannot go diagonally.</p> <p>Also, my proposed solution was an attempt to take every possible string of 50-digit numbers base 4 - so that, you start at each square, and move left, right, up or down --- in every possible combination 4^50</p> <p>This problem asks you to find the greatest sum of 50 numbers that can be connected by a path, without going diagonally, in this 16x16 grid:</p> <pre><code> {{50,54,46,55,45,56,44,53,47,59,41,60,40,59,41,59}, {47,57,46,49,52,46,53,47,53,41,59,40,60,41,59,41}, {56,42,54,51,48,54,47,53,53,57,48,54,49,57,46,59}, {48,50,52,54,56,58,57,47,48,49,48,47,46,53,52,51}, {50,56,50,48,49,50,51,59,42,60,39,62,38,63,38,50}, {60,40,50,50,50,50,60,40,55,45,55,45,56,44,56,44}, {60,45,46,37,56,50,43,39,50,53,56,39,50,58,39,49}, {26,56,54,38,48,50,67,64,32,54,50,49,48,47,46,45}, {28,45,35,57,54,34,34,32,64,57,58,74,24,64,34,50}, {40,50,60,54,45,56,46,47,35,36,39,27,38,50,51,52}, {29,38,47,58,48,37,50,58,37,46,50,50,50,50,50,50}, {47,48,49,50,52,65,64,52,49,47,43,47,58,46,30,32}, {59,47,47,56,65,34,45,56,75,24,35,45,56,65,50,54}, {53,46,35,45,29,46,46,50,23,32,40,46,64,64,64,20}, {53,54,56,58,60,43,43,34,34,35,64,30,50,40,49,59}, </code></pre> <p>This algorithm tries <strong>random</strong> paths and turns after each of the 50 steps - up, right, down, left - without crossing over itself. It gets me to about 2750, but I need at least 2800 to complete the assignment. //lol</p> <pre><code>import java.util.ArrayList; public class lol { private int[][] square = {{50,54,46,55,45,56,44,53,47,59,41,60,40,59,41,59}, {47,57,46,49,52,46,53,47,53,41,59,40,60,41,59,41}, {56,42,54,51,48,54,47,53,53,57,48,54,49,57,46,59}, {48,50,52,54,56,58,57,47,48,49,48,47,46,53,52,51}, {50,56,50,48,49,50,51,59,42,60,39,62,38,63,38,50}, {60,40,50,50,50,50,60,40,55,45,55,45,56,44,56,44}, {60,45,46,37,56,50,43,39,50,53,56,39,50,58,39,49}, {26,56,54,38,48,50,67,64,32,54,50,49,48,47,46,45}, {28,45,35,57,54,34,34,32,64,57,58,74,24,64,34,50}, {40,50,60,54,45,56,46,47,35,36,39,27,38,50,51,52}, {29,38,47,58,48,37,50,58,37,46,50,50,50,50,50,50}, {47,48,49,50,52,65,64,52,49,47,43,47,58,46,30,32}, {59,47,47,56,65,34,45,56,75,24,35,45,56,65,50,54}, {53,46,35,45,29,46,46,50,23,32,40,46,64,64,64,20}, {53,54,56,58,60,43,43,34,34,35,64,30,50,40,49,59}, {52,12,17,50,63,62,62,64,50,51,52,57,43,44,42,69}}; ; public static void main(String [] args) { lol lol1 = new lol(); } public lol() { ArrayList&lt;Integer&gt; record = new ArrayList&lt;Integer&gt;(); int max =0; for(int count = 0; count&lt;10000; count++) { for(int startx=0; startx&lt;16; startx++) { for(int starty =0; starty&lt;16; starty++) { int[] pos = new int[2]; pos[0] = starty; pos[1] = startx; ArrayList&lt;Integer&gt; past = new ArrayList&lt;Integer&gt;(); int total = 0; for(int i=0; i&lt;50; i++) { int random = (int)(Math.random()*4); int switchcount = 0; past.add(100*pos[0] + pos[1]); total+= square[pos[0]][pos[1]]; if(random == 0) { if(pos[0] == 0 || checkexists((pos[0]-1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]--; } } if(random == 1) { if(pos[0] == 15 || checkexists((pos[0]+1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]++; } } if(random == 2) { if(pos[1] == 0 || checkexists((pos[0])*100+pos[1]-1,past)) { random++; switchcount++; } else { pos[1]--; } } if(random == 3) { if(pos[1] == 15 || checkexists((pos[0])*100+pos[1]+1,past)) { if(switchcount &gt;= 3) { break; } else { random = 0; if(pos[0] == 0 || checkexists((pos[0]-1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]--; } if(random == 1) { if(pos[0] == 15 || checkexists((pos[0]+1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]++; } } if(random == 2) { if(pos[1] == 0 || checkexists((pos[0])*100+pos[1]-1,past)) { break; } else { pos[1]--; } } } } else { pos[1]++; } } } if (total&gt;max) { max = total; record = past; } } } } for(int p = 0; p&lt;record.size(); p++) { System.out.println(record.get(p)); } System.out.println("\n\n" + max); } public boolean checkexists(int pos, ArrayList&lt;Integer&gt; past) { for(int i=0; i&lt;past.size(); i++) { if(past.get(i) == pos) { //System.out.println("TRUE"); return true; } } return false; } } </code></pre> <p>This is my attempt at a full solution - it attempt to take every possible string of 50-digit numbers base 4 - so that, you start at each square, and move left, right, up or down --- in every possible combination 4^50</p> <pre><code>import java.util.ArrayList; public class lol2 { private int[][] square = {{50,54,46,55,45,56,44,53,47,59,41,60,40,59,41,59}, {47,57,46,49,52,46,53,47,53,41,59,40,60,41,59,41}, {56,42,54,51,48,54,47,53,53,57,48,54,49,57,46,59}, {48,50,52,54,56,58,57,47,48,49,48,47,46,53,52,51}, {50,56,50,48,49,50,51,59,42,60,39,62,38,63,38,50}, {60,40,50,50,50,50,60,40,55,45,55,45,56,44,56,44}, {60,45,46,37,56,50,43,39,50,53,56,39,50,58,39,49}, {26,56,54,38,48,50,67,64,32,54,50,49,48,47,46,45}, {28,45,35,57,54,34,34,32,64,57,58,74,24,64,34,50}, {40,50,60,54,45,56,46,47,35,36,39,27,38,50,51,52}, {29,38,47,58,48,37,50,58,37,46,50,50,50,50,50,50}, {47,48,49,50,52,65,64,52,49,47,43,47,58,46,30,32}, {59,47,47,56,65,34,45,56,75,24,35,45,56,65,50,54}, {53,46,35,45,29,46,46,50,23,32,40,46,64,64,64,20}, {53,54,56,58,60,43,43,34,34,35,64,30,50,40,49,59}, {52,12,17,50,63,62,62,64,50,51,52,57,43,44,42,69}}; public static void main(String [] args) { lol2 lol1 = new lol2(); } public lol2() { ArrayList&lt;Integer&gt; record = new ArrayList&lt;Integer&gt;(); int max =0; for(int count = 0; count&lt;10000; count++) { for(int startx=0; startx&lt;16; startx++) { for(int starty =0; starty&lt;16; starty++) { for(int a1 = 0; a1 &lt;4; a1++) { for(int a2 = 0; a2 &lt;4; a2++) { for(int a3 = 0; a3 &lt;4; a3++) { for(int a4 = 0; a4 &lt;4; a4++) { for(int a5 = 0; a5 &lt;4; a5++) { for(int a6 = 0; a6 &lt;4; a6++) { for(int a7 = 0; a7 &lt;4; a7++) { for(int a8 = 0; a8 &lt;4; a8++) { for(int a9 = 0; a9 &lt;4; a9++) { for(int a10 = 0; a10 &lt;4; a10++) { for(int a11 = 0; a11 &lt;4; a11++) { for(int a12 = 0; a12 &lt;4; a12++) { for(int a13 = 0; a13 &lt;4; a13++) { for(int a14 = 0; a14 &lt;4; a14++) { for(int a15 = 0; a15 &lt;4; a15++) { for(int a16 = 0; a16 &lt;4; a16++) { for(int a17 = 0; a17 &lt;4; a17++) { for(int a18 = 0; a18 &lt;4; a18++) { for(int a19 = 0; a19 &lt;4; a19++) { for(int a20 = 0; a20 &lt;4; a20++) { for(int a21 = 0; a21 &lt;4; a21++) { for(int a22 = 0; a22 &lt;4; a22++) { for(int a23 = 0; a23 &lt;4; a23++) { for(int a24 = 0; a24 &lt;4; a24++) { for(int a25 = 0; a25 &lt;4; a25++) { for(int a26 = 0; a26 &lt;4; a26++) { for(int a27 = 0; a27 &lt;4; a27++) { for(int a28 = 0; a28 &lt;4; a28++) { for(int a29 = 0; a29 &lt;4; a29++) { for(int a30 = 0; a30 &lt;4; a30++) { for(int a31 = 0; a31 &lt;4; a31++) { for(int a32 = 0; a32 &lt;4; a32++) { for(int a33 = 0; a33 &lt;4; a33++) { for(int a34 = 0; a34 &lt;4; a34++) { for(int a35 = 0; a35 &lt;4; a35++) { for(int a36 = 0; a36 &lt;4; a36++) { for(int a37 = 0; a37 &lt;4; a37++) { for(int a38 = 0; a38 &lt;4; a38++) { for(int a39 = 0; a39 &lt;4; a39++) { System.out.println("SPAM"); for(int a40 = 0; a40 &lt;4; a40++) { for(int a41 = 0; a41 &lt;4; a41++) { for(int a42 = 0; a42 &lt; 4; a42++){ for(int a43=0; a43&lt;4; a43++){ for(int a44 =0; a44&lt;4; a44++){ for(int a45=0; a45&lt;4; a45++){ for(int a46=0; a46&lt;4; a46++){ for(int a47=0; a47&lt;4; a47++){ for(int a48=0; a48&lt;4; a48++){ for(int a49=0; a49&lt;4; a49++){ for(int a50=0; a50&lt;4; a50++){ int[] pos = new int[2]; pos[0] = starty; pos[1] = startx; ArrayList&lt;Integer&gt; past = new ArrayList&lt;Integer&gt;(); int total = 0; String path = "" + a1 + a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12+a13+a14+a15+a16+a17+a18+a19+a20+a21+a22+a23+a24+a25+a26+a27+a28+a29+a30+a31+a32+a33+a34+a35+a36+a37+a38+a39+a40+a41+a42+a43+a44+a45+a46+a47+a48+a49+a50; for(int i =0; i&lt;50; i++) { int random = Integer.parseInt(path.substring(i,i+1)); int switchcount = 0; past.add(100*pos[0] + pos[1]); total+= square[pos[0]][pos[1]]; if(random == 0) { if(pos[0] == 0 || checkexists((pos[0]-1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]--; } } if(random == 1) { if(pos[0] == 15 || checkexists((pos[0]+1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]++; } } if(random == 2) { if(pos[1] == 0 || checkexists((pos[0])*100+pos[1]-1,past)) { random++; switchcount++; } else { pos[1]--; } } if(random == 3) { if(pos[1] == 15 || checkexists((pos[0])*100+pos[1]+1,past)) { if(switchcount &gt;= 3) { break; } else { random = 0; if(pos[0] == 0 || checkexists((pos[0]-1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]--; } if(random == 1) { if(pos[0] == 15 || checkexists((pos[0]+1)*100+pos[1],past)) { random++; switchcount++; } else { pos[0]++; } } if(random == 2) { if(pos[1] == 0 || checkexists((pos[0])*100+pos[1]-1,past)) { break; } else { pos[1]--; } } } } else { pos[1]++; } } } if (total&gt;max) max = total;f } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } for(int p = 0; p&lt;record.size(); p++) { System.out.println(record.get(p)); } System.out.println("\n\n" + max); } public boolean checkexists(int pos, ArrayList&lt;Integer&gt; past) { for(int i=0; i&lt;past.size(); i++) { if(past.get(i) == pos) { //System.out.println("TRUE"); return true; } } return false; } /*public ArrayList&lt;String&gt; setint() { ArrayList&lt;String&gt; bob = new ArrayList&lt;String&gt;(); for(BigInteger i =1267650600228229401496703205376; ; i&lt;2535301200456458802993406410752; i++) { String number = i + ""; bob.add(BigInteger.toString(BigInteger.parseInt(number, 10), 4)); } return bob; } */ </code></pre> <p>}</p>
40,062,500
3
12
null
2016-10-13 18:04:16.73 UTC
10
2016-10-17 20:50:47.003 UTC
2016-10-13 23:01:18.807 UTC
null
6,392,876
null
6,392,876
null
1
5
java|algorithm|sum
7,400
<p>EDIT: Here is some sample code demonstrating some of the techniques I've outlined. It solves this problem reasonably well. While experimenting, I did find some improvements that are not in code below. Improving the speed/efficiency of this program is 100% possible, but left as an exercise to any future reader</p> <pre><code>import java.util.*; public class SquareSolver { /** * The LRU_Cache data structure is useful in a LOT of optimization problems, where storing all the problems you've solved so far * is infeasible, but there's significant time savings to be had if your program can * realize "Wait, I've solved this sub-problem already", and just re-use earlier answers. * It stores things, until it gets above LRUCacheSize, then it automatically ejects the least recently used entry. * This is strictly an optimization, because things get ejected from the cache automatically, you should not rely on * presence (or not) of an element for correctness. */ private HashMap&lt;Integer, LRUCache&gt; leastRecentlyUsedCache; private Map&lt;Integer, Integer&gt; bestShortPathScores; private Map&lt;Integer, Integer&gt; depthEarlyCutoffsMap; private Map&lt;Integer, Integer&gt; depthCacheHitsMap; private int squareSize, targetLength; private Map&lt;Coords, Integer&gt; coordScores; private Set&lt;Coords&gt; neighborOffsets; private Path bestPath; private boolean isLongPath; private long startTime; private long timeout; private class LRUCache extends LinkedHashMap&lt;Path, Integer&gt;{ private int LRUCacheSize; LRUCache(int LRUCacheSize){ super(LRUCacheSize * 4 / 3, 0.75f, true); this.LRUCacheSize = LRUCacheSize; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() &gt; LRUCacheSize; } } public SquareSolver(int LRUCacheSize, int squareSize, int targetLength) { neighborOffsets = new HashSet&lt;&gt;(Arrays.asList(new Coords[]{new Coords(-1, 0), new Coords(1, 0), new Coords(0, -1), new Coords(0, 1)})); this.targetLength = targetLength; this.squareSize = squareSize; leastRecentlyUsedCache = new HashMap&lt;&gt;(); for(int i = 0; i &lt;= targetLength; i++) { leastRecentlyUsedCache.put(i, new LRUCache(LRUCacheSize / targetLength)); } coordScores = new HashMap&lt;&gt;(); } public static void main(String[] args) { int[][] testSquare = new int[][]{ {50, 54, 46, 55, 45, 56, 44, 53, 47, 59, 41, 60, 40, 59, 41, 59}, {47, 57, 46, 49, 52, 46, 53, 47, 53, 41, 59, 40, 60, 41, 59, 41}, {56, 42, 54, 51, 48, 54, 47, 53, 53, 57, 48, 54, 49, 57, 46, 59}, {48, 50, 52, 54, 56, 58, 57, 47, 48, 49, 48, 47, 46, 53, 52, 51}, {50, 56, 50, 48, 49, 50, 51, 59, 42, 60, 39, 62, 38, 63, 38, 50}, {60, 40, 50, 50, 50, 50, 60, 40, 55, 45, 55, 45, 56, 44, 56, 44}, {60, 45, 46, 37, 56, 50, 43, 39, 50, 53, 56, 39, 50, 58, 39, 49}, {26, 56, 54, 38, 48, 50, 67, 64, 32, 54, 50, 49, 48, 47, 46, 45}, {28, 45, 35, 57, 54, 34, 34, 32, 64, 57, 58, 74, 24, 64, 34, 50}, {40, 50, 60, 54, 45, 56, 46, 47, 35, 36, 39, 27, 38, 50, 51, 52}, {29, 38, 47, 58, 48, 37, 50, 58, 37, 46, 50, 50, 50, 50, 50, 50}, {47, 48, 49, 50, 52, 65, 64, 52, 49, 47, 43, 47, 58, 46, 30, 32}, {59, 47, 47, 56, 65, 34, 45, 56, 75, 24, 35, 45, 56, 65, 50, 54}, {53, 46, 35, 45, 29, 46, 46, 50, 23, 32, 40, 46, 64, 64, 64, 20}, {53, 54, 56, 58, 60, 43, 43, 34, 34, 35, 64, 30, 50, 40, 49, 59}, {52, 12, 17, 50, 63, 62, 62, 64, 50, 51, 52, 57, 43, 44, 42, 69}}; SquareSolver testSolver = new SquareSolver(500 * 1000, 16, 50); Path bestPath = testSolver.solveSquare(testSquare, 30 * 1000); System.out.println("Best Score:\t" + bestPath.getScore()); System.out.println("Best Path:\t" + bestPath.toString()); } private boolean inSquare(Coords coords) { int x = coords.getX(); int y = coords.getY(); return x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; squareSize &amp;&amp; y &lt; squareSize; } public void solveSquareHelper(Path currentPath) { // Base Case if (currentPath.size() == targetLength) { synchronized (bestPath) { if (currentPath.getScore() &gt; bestPath.getScore()) { System.out.print("."); bestPath = currentPath; } } return; } // Don't run forever. if (System.currentTimeMillis() &gt; startTime + timeout){ return; } // Least Recently Used Cache can save us a lot of work if (lru_hit(currentPath)) { return; } // Early Cutoff can save us a lot of work too if (can_early_cutoff(currentPath)) { return; } // Recursive Case expandLegalNeighbors(currentPath); } private void expandLegalNeighbors(Path currentPath) { Coords currentCoords = currentPath.getCurrentCoords(); neighborOffsets.stream() .map(currentCoords::add) // Get all neighbors of current coords .filter(this::inSquare) // Filter out coords outside the square .filter(currentPath::doesNotContain) // Filter out coords already in currentPath .sorted(Comparator.comparing(Coords::getProximityToOrigin)) // This order maximizes the usefulness of LRUCache .forEachOrdered(neighbor -&gt; solveSquareHelper(new Path(currentPath, neighbor))); } private boolean can_early_cutoff(Path currentPath) { int futurePathLength = targetLength - currentPath.size(); int upperBoundFutureScore = bestShortPathScores.get(futurePathLength); if (currentPath.getScore() + upperBoundFutureScore &lt;= bestPath.getScore()) { depthEarlyCutoffsMap.put(currentPath.size(), depthEarlyCutoffsMap.get(currentPath.size()) + 1); return true; } else { return false; } } private boolean lru_hit(Path currentPath) { LRUCache currentDepthCache = leastRecentlyUsedCache.get(currentPath.size()); if (currentDepthCache.containsKey(currentPath)) { depthCacheHitsMap.put(currentPath.size(), depthCacheHitsMap.get(currentPath.size()) + 1); currentDepthCache.put(currentPath, currentDepthCache.get(currentPath) + 1); return true; } else { currentDepthCache.put(currentPath, 0); } return false; } public Path solveSquare(int[][] square, long timeout){ Map&lt;Integer, Integer&gt; smallPathScores = new HashMap&lt;&gt;(); smallPathScores.put(1, -10); for(int i =0; i &lt; squareSize; i++){ for(int j = 0; j &lt; squareSize; j++){ if(square[i][j] &gt; smallPathScores.get(1)){ smallPathScores.put(1, square[i][j]); } } } Coords fakeCoords = new Coords(-10, -10); coordScores.put(fakeCoords, -10); Path bestSmallPath = new Path(fakeCoords); for(int i = 2; i &lt; targetLength; i++){ SquareSolver smallSolver = new SquareSolver(500 * 1000, squareSize, i); bestSmallPath = smallSolver.solveSquare(square, timeout * i, smallPathScores, bestSmallPath); smallPathScores.put(i, bestSmallPath.getScore()); System.gc(); } return solveSquare(square, timeout * targetLength, smallPathScores, bestSmallPath); } public Path solveSquare(int[][] square, long timeout, Map&lt;Integer, Integer&gt; shortPathScores, Path initialBestPath) { bestPath = initialBestPath; bestShortPathScores = shortPathScores; System.out.println("=============================Target Length:\t" + targetLength + "(Timeout:\t" + timeout/60000.0 + " minutes)==========================="); System.out.println("Best Short Path Scores (for early cutoff):\t" + bestShortPathScores); startTime = System.currentTimeMillis(); this.timeout = timeout; depthCacheHitsMap = new HashMap&lt;&gt;(); depthEarlyCutoffsMap = new HashMap&lt;&gt;(); for (int i = 1; i &lt; targetLength; i++) { depthCacheHitsMap.put(i, 0); depthEarlyCutoffsMap.put(i, 0); } for (int i = 0; i &lt; squareSize; i++) { for (int j = 0; j &lt; squareSize; j++) { coordScores.put(new Coords(i, j), square[i][j]); } } System.out.print("Expanding from best shorter node"); expandLegalNeighbors(initialBestPath); System.out.println("Starting from every spot"); coordScores.keySet() .stream() .sorted(Comparator.comparing(Coords::getProximityToOrigin)) .forEachOrdered(startingCoords -&gt; solveSquareHelper(new Path(startingCoords))); System.out.println(); System.out.println("Best Path:\t" + bestPath); System.out.println("Best Score:\t" + bestPath.getScore()); System.out.println("LRU Cache stats:\t" + depthCacheHitsMap); System.out.println("Early Cutoff stats:\t" + depthEarlyCutoffsMap); return bestPath; } private class Coords implements Comparable&lt;Coords&gt; { private int x, y; private double proximityToOrigin; Coords(int x, int y) { this.x = x; this.y = y; this.proximityToOrigin = Math.sqrt((x - squareSize/2) * (x - squareSize/2) + (y - squareSize/2) * (y - squareSize/2)); } int getX() { return this.x; } int getY() { return this.y; } double getProximityToOrigin() { return proximityToOrigin; } Coords add(Coords other) { return new Coords(this.x + other.x, this.y + other.y); } @Override public int compareTo(Coords o) { int xdiff = this.x - o.x; if (xdiff == 0) return this.y - o.y; else return xdiff; } @Override public boolean equals(Object other) { if (other instanceof Coords) { Coords o = (Coords) other; return this.x == o.x &amp;&amp; this.y == o.y; } else { return false; } } @Override public int hashCode() { return this.x * squareSize + this.y; } @Override public String toString() { return "(" + this.x + ", " + this.y + ")"; } } private class Path { private TreeSet&lt;Coords&gt; usedCoords; private Coords currentCoords; private int score; Path(Coords newCoords) { this.usedCoords = new TreeSet&lt;&gt;(); usedCoords.add(newCoords); currentCoords = newCoords; this.score = coordScores.get(newCoords); } Path(Path previousPath, Coords newCoords) { this(newCoords); this.usedCoords.addAll(previousPath.usedCoords); this.score += previousPath.score; } Coords getCurrentCoords() { return this.currentCoords; } int size() { return usedCoords.size(); } int getScore() { return this.score; } boolean doesNotContain(Coords coords) { return !usedCoords.contains(coords); } @Override public String toString() { return this.usedCoords.toString(); } @Override public int hashCode() { return this.usedCoords.hashCode(); } @Override public boolean equals(Object other) { if (other instanceof Path) { Path o = (Path) other; return this.usedCoords.equals(o.usedCoords) &amp;&amp; this.currentCoords.equals(o.currentCoords); } else { return false; } } } } </code></pre> <p>Some key insights that allow us to do something more efficient than brute force:</p> <p><strong>Insight</strong> Two sub-paths with the same current node and same set of used nodes, have the same top-score.</p> <p><strong>How We Use This</strong> Use an LRU_Cache which recognizes paths which use the same nodes and have the same current node, as equivalent. This causes MANY early cutoffs, at depths as early as 4. Subtrees whose root node is at a depth of 4 with respect to the main tree contain 3^46 paths each. Pruning an appreciable fraction of them out is huge.</p> <p><strong>Insight</strong> A sub-path of length k can only obtain a maximum score of sub-path.score + best_length_n-k_path.score</p> <p><strong>How We Use This</strong> First solve for the best path of length 2, then use that to find the best path of length 3. Use both of them to find the best path of length 4, etc. You can early cutoff anytime a current path of length k cannot exceed the max score even with your previous best n-k length path added on. Solving for n = 2, 3, 4, 5 ... 50 seems like a lot more work than just solving n = 50 directly, but for this problem it turns out the savings from early pruning are worth more.</p>
13,322,108
MVC Layout VS MVC Master Page
<p>I'm starting learning MVC4. I came across the two possibilities of creating a View based on a Razor template or a Master Page.</p> <p><em>I would like to understand the practical differences between the two</em>.</p> <p>For now, I can see that if I create a View using a Master Page, I can override several sections. For example, if my Master defines a "left column" placeholder and a "body" placeholder I can not only define the body for a specific View, but I can also render contents in the "left column" section for example to display controls that are bound to the context in which the page is (from a search box to a stock quote viewer). Also, Master Pages cannot be defined by making use of Razor templates, which are much less verbose than other syntax (partially wrong: <a href="http://www.hanselman.com/blog/MixingRazorViewsAndWebFormsMasterPagesWithASPNETMVC3.aspx" rel="noreferrer">someone</a> managed to hack this aspect).</p> <p>With Razor Layouts, I can only define <strong>one</strong> contiguous block of the page that can be overridden by specific View, and I should use multiple layouts (breaking DRY) for little changes in other parts of the page. <strong>Is my previous statement correct</strong> or am I missing something?</p> <p>Obviously I can render contents in any part of the page by making good use of jQuery, but that's another matter</p>
13,322,309
2
1
null
2012-11-10 12:35:22.997 UTC
5
2018-09-24 15:20:33.66 UTC
2014-01-13 14:59:40.557 UTC
null
2,579,850
null
471,213
null
1
19
razor|asp.net-mvc-4|master-pages
48,614
<p>You could use sections with Razor. Scott Gu blogged about them here: <a href="http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx">http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx</a></p> <p>In your Layout you could define as many sections as you wish:</p> <pre><code>&lt;div id="leftMenu"&gt; @RenderSection("LeftMenu", required: false) &lt;/div&gt; </code></pre> <p>which you could override in your views:</p> <pre><code>@section LeftMenu { &lt;div&gt;... here comes the left menu for this view ...&lt;/div&gt; } </code></pre> <p>You could also test whether a section has been defined in a view and if not provide some default content:</p> <pre><code>@if (IsSectionDefined("LeftMenu")) { @RenderSection("LeftMenu") } else { &lt;div&gt;Some default left menu&lt;/div&gt; } </code></pre>
13,660,118
Running a flask app with nginx and gunicorn
<p>I'm new at this and have only been using nginx to serve static files. I have now installed flask and gunicorn. If I run <code>gunicorn -b 127.0.0.2:8000 hello:app</code> and then wget it from the server it works well. If I try to access it from a browser, however, it returns a 404 error (I am running this on a server that hosts a wordpress site which is locatet at root).</p> <p>The flask app:</p> <pre><code>from flask import Flask from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__) @app.route('/') def hello(): return "Hello world!" app.wsgi_app = ProxyFix(app.wsgi_app) if __name__ == '__main__': app.run() </code></pre> <p>And the relevant part of my nginx configuration:</p> <pre><code>location /flask { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_\ for; proxy_pass http://127.0.0.2:8000; proxy_redirect off; } </code></pre> <p>I hope this is all the relevant info. If not, do tell. Thanks!</p>
13,661,593
1
1
null
2012-12-01 13:54:38.393 UTC
19
2013-03-18 22:40:33.07 UTC
2013-03-18 22:40:33.07 UTC
null
1,626,395
null
1,856,869
null
1
20
python|nginx|flask|gunicorn
18,905
<p>This is how I serve my flask apps in Nginx:</p> <p>Run gunicorn daemonized using a socket:</p> <pre><code> sudo gunicorn app:app --bind unix:/tmp/gunicorn_flask.sock -w 4 -D </code></pre> <p>Related nginx config:</p> <pre><code> upstream flask_server { # swap the commented lines below to switch between socket and port server unix:/tmp/gunicorn_flask.sock fail_timeout=0; #server 127.0.0.1:5000 fail_timeout=0; } server { listen 80; server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { listen 80; client_max_body_size 4G; server_name example.com; keepalive_timeout 5; # path for static files location /static { alias /path/to/static; autoindex on; expires max; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://flask_server; break; } } } } </code></pre>
13,728,041
Move markers in google map v2 android
<p>I am doing map clustering in Android Google maps v2. I just want to animate the marker from one geopoint to another. Is there a way to move a marker in Google maps v2?</p>
13,912,034
5
0
null
2012-12-05 16:39:48.337 UTC
26
2019-09-24 16:20:38.723 UTC
2014-03-01 23:41:02.063 UTC
null
2,460,971
null
1,434,806
null
1
28
android|google-maps-api-2
72,792
<p>There's one example of moving marker in google map v2 <a href="https://github.com/googlemaps/android-samples" rel="nofollow noreferrer">demo app</a> .. in the sample of the play library!! </p> <p>I have looked into that!! here the code for moving an marker : -- ></p> <pre><code> public void animateMarker(final Marker marker, final LatLng toPosition, final boolean hideMarker) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); Projection proj = mGoogleMapObject.getProjection(); Point startPoint = proj.toScreenLocation(marker.getPosition()); final LatLng startLatLng = proj.fromScreenLocation(startPoint); final long duration = 500; final Interpolator interpolator = new LinearInterpolator(); handler.post(new Runnable() { @Override public void run() { long elapsed = SystemClock.uptimeMillis() - start; float t = interpolator.getInterpolation((float) elapsed / duration); double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude; double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude; marker.setPosition(new LatLng(lat, lng)); if (t &lt; 1.0) { // Post again 16ms later. handler.postDelayed(this, 16); } else { if (hideMarker) { marker.setVisible(false); } else { marker.setVisible(true); } } } }); } </code></pre> <p>Hope it help every one!!</p>
13,355,233
Python lambda closure scoping
<p>I am trying to use closures to eliminate a variable from a function signature (the application is to make writing all the functions needed for connecting Qt signals for an interface to control a largish number of parameters to the dictionary that stores the values ). </p> <p>I do not understand why the case of using the <code>lambda</code> not wrapped in another function returns the last name for all cases.</p> <pre><code>names = ['a', 'b', 'c'] def test_fun(name, x): print(name, x) def gen_clousure(name): return lambda x: test_fun(name, x) funcs1 = [gen_clousure(n) for n in names] funcs2 = [lambda x: test_fun(n, x) for n in names] # this is what I want In [88]: for f in funcs1: ....: f(1) a 1 b 1 c 1 # I do not understand why I get this In [89]: for f in funcs2: ....: f(1) c 1 c 1 c 1 </code></pre>
13,355,291
1
0
null
2012-11-13 03:34:45.557 UTC
11
2018-01-20 03:15:35.643 UTC
2018-01-20 03:15:35.643 UTC
null
380,231
null
380,231
null
1
34
python|lambda|closures
8,343
<p>The reason is that closures (lambdas or otherwise) close over names, not values. When you define <code>lambda x: test_fun(n, x)</code>, the n is not evaluated, because it is inside the function. It is evaluated when the function is <em>called</em>, at which time the value that is there is the last value from the loop.</p> <p>You say at the beginning that you want to "use closures to eliminate a variable from a function signature", but it doesn't really work that way. (See below, though, for a way that may satisfy you, depending on what you mean by "eliminate".) Variables inside the function body will not be evaluated when the function is defined. In order to get the function to take a "snapshot" of the variable as it exists at function-definition time, you <em>must</em> pass the variable as an argument. The usual way to do this is to give the function an argument whose default value is the variable from the outer scope. Look at the difference between these two examples:</p> <pre><code>&gt;&gt;&gt; stuff = [lambda x: n+x for n in [1, 2, 3]] &gt;&gt;&gt; for f in stuff: ... print f(1) 4 4 4 &gt;&gt;&gt; stuff = [lambda x, n=n: n+x for n in [1, 2, 3]] &gt;&gt;&gt; for f in stuff: ... print f(1) 2 3 4 </code></pre> <p>In the second example, passing <code>n</code> as an argument to the function "locks in" the current value of n to that function. You have to do something like this if you want to lock in the value in this way. (If it didn't work this way, things like global variables wouldn't work at all; it's essential that free variables be looked up at the time of use.)</p> <p>Note that nothing about this behavior is specific to lambdas. The same scoping rules are in effect if you use <code>def</code> to define a function that references variables from the enclosing scope.</p> <p>If you really want to, you can avoid adding the extra argument to your returned function, but to do so you must wrap that function in yet another function, like so:</p> <pre><code>&gt;&gt;&gt; def makeFunc(n): ... return lambda x: x+n &gt;&gt;&gt; stuff = [makeFunc(n) for n in [1, 2, 3]] &gt;&gt;&gt; for f in stuff: ... print f(1) 2 3 4 </code></pre> <p>Here, the inner lambda still looks up the value of <code>n</code> when it is called. But the <code>n</code> it refers to is no longer a global variable but a local variable inside the enclosing function <code>makeFunc</code>. A new value of this local variable is created every time <code>makeFunc</code> is called, and the returned lambda creates a closure that "saves" the local variable value that was in effect for that invocation of <code>makeFunc</code>. Thus each function created in the loop has its own "private" variable called <code>x</code>. (For this simple case, this can also be done using a lambda for the outer function --- <code>stuff = [(lambda n: lambda x: x+n)(n) for n in [1, 2, 3]]</code> --- but this is less readable.)</p> <p>Notice that you still have to pass your <code>n</code> as an argument, it's just that, by doing it this way, you don't pass it as an argument to the same function that winds up going into the <code>stuff</code> list; instead you pass it as an argument to a helper function that creates the function you want to put into <code>stuff</code>. The advantage of using this two-function approach is that the returned function is "clean" and doesn't have the extra argument; this could be useful if you were wrapping functions that accepted a lot of arguments, in which case it could become confusing to remember where the <code>n</code> argument was in the list. The disadvantage is that, doing it this way, the process of making the functions is more complicated, since you need another enclosing function.</p> <p>The upshot is that there is a tradeoff: you can make the function-creation process simpler (i.e., no need for two nested functions), but then you must make the resulting function a bit more complicated (i.e., it has this extra <code>n=n</code> argument). Or you can make the function simpler (i.e., it has no <code>n=</code>n argument), but then you must make the function-creation process more complicated (i.e., you need two nested functions to implement the mechanism).</p>
13,380,590
Is it possible to start activity through adb shell?
<p>I want to start activity through adb shell. So that I can launch a specific activity that is needed</p>
13,380,685
6
1
null
2012-11-14 14:21:39.847 UTC
41
2019-07-11 04:45:59.473 UTC
null
null
null
null
1,369,752
null
1
143
android
199,081
<p>Launch adb shell and enter the command as follows</p> <pre><code>am start -n yourpackagename/.activityname </code></pre>
13,237,623
Copy data into another table
<p>How to copy/append data from one table into another table with same schema in SQL Server?</p> <p><strong>Edit:</strong></p> <p>let's say there is a query </p> <pre><code>select * into table1 from table2 where 1=1 </code></pre> <p>which creates <code>table1</code> with the same schema as well as data as in <code>table2</code>. </p> <p>Is there any short query like this to only copy entire data only into an already existing table?</p>
13,237,661
11
3
null
2012-11-05 17:54:44.22 UTC
46
2021-10-19 10:07:38.597 UTC
2020-04-21 12:25:43.247 UTC
null
857,475
null
857,475
null
1
201
sql|sql-server|sql-server-2008
615,450
<p>If both tables are truly the same schema:</p> <pre><code>INSERT INTO newTable SELECT * FROM oldTable </code></pre> <p>Otherwise, you'll have to specify the column names (the column list for <code>newTable</code> is optional if you are specifying a value for all columns and selecting columns in the same order as <code>newTable</code>'s schema):</p> <pre><code>INSERT INTO newTable (col1, col2, col3) SELECT column1, column2, column3 FROM oldTable </code></pre>
9,128,015
Getting "Cannot read property 'nodeType' of null" when calling ko.applyBindings
<p>I have this knockout code:</p> <pre><code>function Task(data) { this.title = ko.observable(data.title); this.isDone = ko.observable(data.isDone); } function TaskListViewModel() { // Data var self = this; self.tasks = ko.observableArray([]); self.newTaskText = ko.observable(); self.incompleteTasks = ko.computed(function() { return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() }); }); // Operations self.addTask = function() { self.tasks.push(new Task({ title: this.newTaskText() })); self.newTaskText(""); }; self.removeTask = function(task) { self.tasks.remove(task) }; } ko.applyBindings(new TaskListViewModel()); </code></pre> <p>This html:</p> <pre class="lang-html prettyprint-override"><code>&lt;head&gt; &lt;script type="text/javascript" src="jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="knockout-2.0.0.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Tasks&lt;/h3&gt; &lt;form data-bind="submit: addTask"&gt; Add task: &lt;input data-bind="value: newTaskText" placeholder="What needs to be done?" /&gt; &lt;button type="submit"&gt;Add&lt;/button&gt; &lt;/form&gt; &lt;ul data-bind="foreach: tasks, visible: tasks().length &gt; 0"&gt; &lt;li&gt; &lt;input type="checkbox" data-bind="checked: isDone" /&gt; &lt;input data-bind="value: title, disable: isDone" /&gt; &lt;a href="#" data-bind="click: $parent.removeTask"&gt;Delete&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; You have &lt;b data-bind="text: incompleteTasks().length"&gt;&amp;nbsp;&lt;/b&gt; incomplete task(s) &lt;span data-bind="visible: incompleteTasks().length == 0"&gt; - it's beer time!&lt;/span&gt; &lt;/body&gt; </code></pre> <p>The example is the same as the one found on the Knockout website, but when I run it, it returns this message on Chrome Fire Bug:</p> <blockquote> <p>Uncaught TypeError: Cannot read property 'nodeType' of null</p> </blockquote> <p>This one is related to the knockout file and to this line of my script:</p> <pre><code>ko.applyBindings(new TaskListViewModel()); </code></pre> <p>And this error is pointing to this line (1766) on knockout:</p> <pre><code>var isElement = (nodeVerified.nodeType == 1); </code></pre> <p>What am I doing wrong?</p>
9,128,306
4
2
null
2012-02-03 11:33:21.46 UTC
8
2015-03-18 10:44:14.79 UTC
2015-01-26 22:37:10.803 UTC
null
419,956
user745235
null
null
1
100
javascript|knockout.js
78,407
<p>This problem was happening because I was trying to bind an <code>HTML</code> element before it was created.</p> <p>My script was loaded on top of the <code>HTML</code> (in the head) but it needed to be loaded at the bottom of my <code>HTML</code> code (just before the closing body tag).</p> <p>Thanks for your attention <a href="https://stackoverflow.com/users/790695/james-allardice">James Allardice</a>.</p> <p>A possible workaround is using <code>defer="defer"</code></p> <pre><code>&lt;script src="script.js" type="text/javascript" defer="defer"&gt;&lt;/script&gt; </code></pre> <p>Use this if the script is not going to generate any document content. This will tell the browser that it can wait for the content to be loaded before loading the script.</p> <p><a href="http://www.w3.org/TR/html4/interact/scripts.html#edef-SCRIPT" rel="noreferrer">Further reading</a>.</p> <p>Hope it helps.</p>
29,722,270
Is it possible to import modules from all files in a directory, using a wildcard?
<p>With ES6, I can import several exports from a file like this:</p> <pre><code>import {ThingA, ThingB, ThingC} from 'lib/things'; </code></pre> <p>However, I like the organization of having one module per file. I end up with imports like this:</p> <pre><code>import ThingA from 'lib/things/ThingA'; import ThingB from 'lib/things/ThingB'; import ThingC from 'lib/things/ThingC'; </code></pre> <p>I would love to be able to do this:</p> <pre><code>import {ThingA, ThingB, ThingC} from 'lib/things/*'; </code></pre> <p>or something similar, with the understood convention that each file contains one default export, and each module is named the same as its file.</p> <p>Is this possible?</p>
29,722,646
14
3
null
2015-04-18 20:10:41.293 UTC
80
2022-07-25 14:43:16.23 UTC
2018-08-23 02:22:09.127 UTC
null
4,642,212
null
1,253,312
null
1
340
javascript|ecmascript-6|es6-modules
330,758
<p>I don't think this is possible, but afaik the resolution of module names is up to module loaders so there might a loader implementation that does support this.</p> <p>Until then, you could use an intermediate "module file" at <code>lib/things/index.js</code> that just contains</p> <pre><code>export * from 'ThingA'; export * from 'ThingB'; export * from 'ThingC'; </code></pre> <p>and it would allow you to do</p> <pre><code>import {ThingA, ThingB, ThingC} from 'lib/things'; </code></pre>
16,117,043
Regular expression replace in C#
<p>I'm fairly new to using regular expressions, and, based on a few tutorials I've read, I'm unable to get this step in my Regex.Replace formatted properly.</p> <p>Here's the scenario I'm working on... When I pull my data from the listbox, I want to format it into a <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="noreferrer">CSV</a> like format, and then save the file. Is using the Replace option an ideal solution for this scenario?</p> <p>Before the regular expression formatting example.</p> <pre><code>FirstName LastName Salary Position ------------------------------------- John Smith $100,000.00 M </code></pre> <p>Proposed format after regular expression replace</p> <pre><code>John Smith,100000,M </code></pre> <p>Current formatting status output:</p> <pre><code>John,Smith,100000,M </code></pre> <p>*Note - is there a way I can replace the first comma with a whitespace?</p> <p>Snippet of my code</p> <pre><code>using(var fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write)) { using(var sw = new StreamWriter(fs)) { foreach (string stw in listBox1.Items) { StringBuilder sb = new StringBuilder(); sb.AppendLine(stw); //Piecing the list back to the original format sb_trim = Regex.Replace(stw, @"[$,]", ""); sb_trim = Regex.Replace(sb_trim, @"[.][0-9]+", ""); sb_trim = Regex.Replace(sb_trim, @"\s", ","); sw.WriteLine(sb_trim); } } } </code></pre>
16,117,150
4
6
null
2013-04-20 05:37:39.543 UTC
6
2021-11-03 11:14:21.677 UTC
2013-10-22 17:28:29.267 UTC
null
63,550
null
1,626,856
null
1
48
c#|regex
166,996
<p>You can do it this with two replace's</p> <pre><code>//let stw be "John Smith $100,000.00 M" sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ","); //sb_trim becomes "John Smith,100,000.00,M" sb_trim = Regex.Replace(sb_trim, @"(?&lt;=\d),(?=\d)|[.]0+(?=,)", ""); //sb_trim becomes "John Smith,100000,M" sw.WriteLine(sb_trim); </code></pre>
16,521,472
Assignment operator in Go language
<p>Lately I was playing with google's new programming language <a href="http://golang.org/" rel="nofollow noreferrer">Go</a> and was wondering why the assignment operator <code>:=</code> has a <em>colon</em> in front of the equal sign <code>=</code>.</p> <p>Is there a particular reason why the authors of the language wanted to use <code>name := &quot;John&quot;</code> instead of <code>name = &quot;John&quot;</code>?</p>
16,521,530
7
2
null
2013-05-13 11:56:27.713 UTC
10
2022-05-03 20:30:22.753 UTC
2022-05-03 20:30:22.753 UTC
null
814,702
null
555,983
null
1
96
syntax|go
31,075
<p>The <code>:=</code> notation serves both as a declaration and as initialization.</p> <pre><code>foo := "bar" </code></pre> <p>is equivalent to</p> <pre><code>var foo = "bar" </code></pre> <p>Why not using only <code>foo = "bar"</code> like in any scripting language, you may ask ? Well, that's to avoid typos.</p> <pre><code>foo = "bar" fooo = "baz" + foo + "baz" // Oops, is fooo a new variable or did I mean 'foo' ? </code></pre>
16,196,268
Where should I put my own python module so that it can be imported
<p>I have my own package in python and I am using it very often. what is the most elegant or conventional directory where i should put my package so it is going to be imported without playing with PYTHONPATH or sys.path?</p> <p>What about site-packages for example? <code>/usr/lib/python2.7/site-packages</code>.<br> Is it common in python to copy and paste the package there ?</p>
16,196,400
6
3
null
2013-04-24 15:38:18.97 UTC
43
2020-07-01 10:45:18.827 UTC
2013-04-24 16:17:25.75 UTC
null
347,777
null
1,508,904
null
1
106
python|python-2.7
105,980
<p>I usually put the stuff i want to have ready to import in the user site directory:</p> <pre><code>~/.local/lib/pythonX.X/site-packages </code></pre> <p>To show the right directory for your platform, you can use <code>python -m site --user-site</code></p> <hr> <p>edit: it will show up in <code>sys.path</code> once you create it:</p> <pre><code>mkdir -p "`python -m site --user-site`" </code></pre>
55,417,410
Kubernetes create deployment unexpected SchemaError
<p>I'm following that tutorial (<a href="https://www.baeldung.com/spring-boot-minikube" rel="noreferrer">https://www.baeldung.com/spring-boot-minikube</a>) I want to create Kubernetes deployment in yaml file (simple-crud-dpl.yaml):</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: simple-crud spec: selector: matchLabels: app: simple-crud replicas: 3 template: metadata: labels: app: simple-crud spec: containers: - name: simple-crud image: simple-crud:latest imagePullPolicy: Never ports: - containerPort: 8080 </code></pre> <p>but when I run <code>kubectl create -f simple-crud-dpl.yaml</code> i got: <code>error: SchemaError(io.k8s.api.autoscaling.v2beta2.MetricTarget): invalid object doesn't have additional properties</code></p> <p>I'm using the newest version of kubectl: </p> <pre><code>kubectl version Client Version: version.Info{Major:"1", Minor:"10", GitVersion:"v1.10.11", GitCommit:"637c7e288581ee40ab4ca210618a89a555b6e7e9", GitTreeState:"clean", BuildDate:"2018-11-26T14:38:32Z", GoVersion:"go1.9.3", Compiler:"gc", Platform:"darwin/amd64"} Server Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.0", GitCommit:"641856db18352033a0d96dbc99153fa3b27298e5", GitTreeState:"clean", BuildDate:"2019-03-25T15:45:25Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"} </code></pre> <p>I'm also using minikube locally as it's described in tutorial. Everything is working till deployment and service. I'm not able to do it.</p>
55,564,032
18
4
null
2019-03-29 12:25:58.26 UTC
11
2020-05-21 21:44:44.2 UTC
2019-03-29 12:41:21.94 UTC
null
9,958,058
null
4,072,507
null
1
73
kubernetes|kubectl|kubernetes-deployment
40,297
<p>After installing kubectl with brew you should run: </p> <ol> <li><p><code>rm /usr/local/bin/kubectl</code></p></li> <li><p><code>brew link --overwrite kubernetes-cli</code></p></li> </ol> <p>And also optionally:</p> <p><code>brew link --overwrite --dry-run kubernetes-cli</code>.</p>
15,174,798
render partial on click
<p>I would like to call partials on some standard operations. I am using this method for calling the partial:</p> <pre><code> %li= link_to 'Delete Event', 'javascript:void(0);', :class =&gt; 'alert tiny button', :data =&gt; {'reveal-id' =&gt; :RevealDelete} = render 'layouts/reveal_delete', :item =&gt; event_display(@event.event), :resource =&gt; @event </code></pre> <p>Then in my partial,</p> <pre><code>#RevealDelete.reveal-modal %a.close-reveal-modal × %h3= "Delete #{item}" %p Are you sure you want to delete this? =link_to "Delete #{item}", resource, :method =&gt; :delete, :remote =&gt; :true, :confirm =&gt; resource, :class =&gt; 'button close-reveal-modal' %a.button.alert.close-reveal-modal Cancel </code></pre> <p>How can I have this has as something like:</p> <pre><code>link_to 'Delete', '#', :partial =&gt; 'layouts/delete', :remote =&gt; :true? </code></pre> <p>so that I only render that partial when clicked and not when the page loads?</p>
15,174,908
3
0
null
2013-03-02 13:02:10.953 UTC
11
2018-06-06 08:51:55.747 UTC
2018-06-06 08:51:55.747 UTC
null
314,166
null
1,448,378
null
1
8
ruby-on-rails|jquery|renderpartial
29,876
<p>You can do that with javascript like:</p> <pre><code>&lt;%= link_to "Delete", delete_content_path, :remote =&gt; true %&gt; </code></pre> <p>The action in your corresponding controller then will be this:</p> <p><strong>My Controller:</strong></p> <pre><code>def delete_content respond_to do |format| format.js end end </code></pre> <p>Then you can create the <code>delete_content.js.erb</code> inside your correct directory of the link and there you put the following code:</p> <p><strong>delete_content.js.erb</strong></p> <pre><code>$('#div_id').html("&lt;%= render :partial =&gt; 'my_partial' %&gt;"); </code></pre> <p>Then in your view:</p> <p><strong>delete_content.html.erb</strong></p> <pre><code>&lt;div id = "div_id"&gt; #this div is html div that will render your partial &lt;/div&gt; </code></pre> <p>Don't forget to put your partial <strong>_my_partial.html.erb</strong> in the same folder.</p>
24,736,427
How to get Date from a resultSet
<p>I have a problem when getting a Date object from a ResultSet. In database it has a value (for example 2014-08-01) and after getting it from resultSet, it has another value (2014-08-31). I know that ResultSet's getDate method returns java.sql.Date, but I tried a few solutions, such as:<br/><br/> <code>Date date=new java.util.Date(resultSet.getDate(3).getTime());</code><br/><br/> or<br/><br/> <code>Date date=resultSet.getTimestamp();</code> <br/><br/> but the problem was the same. If I try<br/><br/> <code>Date date=resultSet.getDate();</code><br/><br/> It throws a NullPointerException.</p> <p>Can anybody explain this?</p>
24,737,131
2
5
null
2014-07-14 12:20:43.893 UTC
2
2014-07-14 13:08:35.957 UTC
null
null
null
null
3,836,820
null
1
3
java|mysql|sql|jdbc
47,105
<p>In your case you were not providing the columnName of the Date field to be retrieved.</p> <p>This should do the job</p> <pre><code> while (rs.next()) { java.sql.Time dbSqlTime = rs.getTime("columnName"); java.sql.Date dbSqlDate = rs.getDate("columnName"); java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("columnName"); java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime()); java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime()); System.out.println(dbSqlTimeConverted); System.out.println(dbSqlDateConverted); } </code></pre> <p>iterate over the <code>ResultSetObject</code> get the Date from the <code>ResultSetObject</code> which is <code>java.sql.Date</code> then convert it to <code>java.util.Date</code></p>
55,563,598
Why is this code using strlen heavily 6.5x slower with GCC optimizations enabled?
<p>I wanted to benchmark <code>glibc</code>'s <code>strlen</code> function for some reason and found out it apparently performs <em>much</em> slower with optimizations enabled in GCC and I have no idea why.</p> <p>Here's my code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;time.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char *s = calloc(1 &lt;&lt; 20, 1); memset(s, 65, 1000000); clock_t start = clock(); for (int i = 0; i &lt; 128; ++i) { s[strlen(s)] = 'A'; } clock_t end = clock(); printf("%lld\n", (long long)(end - start)); return 0; } </code></pre> <p>On my machine it outputs:</p> <pre><code>$ gcc test.c &amp;&amp; ./a.out 13336 $ gcc -O1 test.c &amp;&amp; ./a.out 199004 $ gcc -O2 test.c &amp;&amp; ./a.out 83415 $ gcc -O3 test.c &amp;&amp; ./a.out 83415 </code></pre> <p>Somehow, enabling optimizations causes it to execute longer.</p>
55,563,916
2
10
null
2019-04-07 20:54:34.727 UTC
11
2022-05-31 08:21:36.43 UTC
2021-03-12 08:01:31.497 UTC
null
224,132
null
4,924,866
null
1
70
c|performance|gcc|glibc
5,508
<p>Testing your code on <a href="https://godbolt.org/z/Ej4woo" rel="nofollow noreferrer">Godbolt's Compiler Explorer</a> provides this explanation:</p> <ul> <li>at <code>-O0</code> or without optimisations, the generated code calls the C library function <code>strlen</code>;</li> <li>at <code>-O1</code> the generated code uses a simple inline expansion using a <code>rep scasb</code> instruction;</li> <li>at <code>-O2</code> and above, the generated code uses a more elaborate inline expansion.</li> </ul> <p>Benchmarking your code repeatedly shows substantial variations from one run to another, but increasing the number of iterations shows that:</p> <ul> <li>the <code>-O1</code> code is much slower than the C library implementation: <code>32240</code> vs <code>3090</code></li> <li>the <code>-O2</code> code is faster than the <code>-O1</code> but still substantially slower than the C library code: <code>8570</code> vs <code>3090</code>.</li> </ul> <p>This behavior is specific to <code>gcc</code> and the GNU libc. The same test on OS/X with <code>clang</code> and Apple's Libc does not show significant differences, which is not a surprise as Godbolt shows that <code>clang</code> generates a call to the C library <code>strlen</code> at all optimisation levels.</p> <p>This could be considered a bug in gcc/glibc but more extensive benchmarking might show that the overhead of calling <code>strlen</code> has a more important impact than the lack of performance of the inline code for small strings. The strings in your benchmark are uncommonly large, so focusing the benchmark on ultra-long strings might not give meaningful results.</p> <p>I improved this benchmark and tested various string lengths. It appears from the benchmarks on linux with gcc (Debian 4.7.2-5) 4.7.2 running on an Intel(R) Core(TM) i3-2100 CPU @ 3.10GHz that the inline code generated by <code>-O1</code> is always slower, by as much as a factor of <strong>10</strong> for moderately long strings, while <code>-O2</code> is only slightly faster than the libc <code>strlen</code> for very short strings and half as fast for longer strings. From this data, the GNU C library version of <code>strlen</code> is quite efficient for most string lengths, at least on my specific hardware. Also keeping in mind that cacheing has a major impact on benchmark measurements.</p> <p>Here is the updated code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; void benchmark(int repeat, int minlen, int maxlen) { char *s = malloc(maxlen + 1); memset(s, 'A', minlen); long long bytes = 0, calls = 0; clock_t clk = clock(); for (int n = 0; n &lt; repeat; n++) { for (int i = minlen; i &lt; maxlen; ++i) { bytes += i + 1; calls += 1; s[i] = '\0'; s[strlen(s)] = 'A'; } } clk = clock() - clk; free(s); double avglen = (minlen + maxlen - 1) / 2.0; double ns = (double)clk * 1e9 / CLOCKS_PER_SEC; printf(&quot;average length %7.0f -&gt; avg time: %7.3f ns/byte, %7.3f ns/call\n&quot;, avglen, ns / bytes, ns / calls); } int main() { benchmark(10000000, 0, 1); benchmark(1000000, 0, 10); benchmark(1000000, 5, 15); benchmark(100000, 0, 100); benchmark(100000, 50, 150); benchmark(10000, 0, 1000); benchmark(10000, 500, 1500); benchmark(1000, 0, 10000); benchmark(1000, 5000, 15000); benchmark(100, 1000000 - 50, 1000000 + 50); return 0; } </code></pre> <p>Here is the output:</p> <pre> chqrlie> gcc -std=c99 -O0 benchstrlen.c && ./a.out average length 0 -> avg time: 14.000 ns/byte, 14.000 ns/call average length 4 -> avg time: 2.364 ns/byte, 13.000 ns/call average length 10 -> avg time: 1.238 ns/byte, 13.000 ns/call average length 50 -> avg time: 0.317 ns/byte, 16.000 ns/call average length 100 -> avg time: 0.169 ns/byte, 17.000 ns/call average length 500 -> avg time: 0.074 ns/byte, 37.000 ns/call average length 1000 -> avg time: 0.068 ns/byte, 68.000 ns/call average length 5000 -> avg time: 0.064 ns/byte, 318.000 ns/call average length 10000 -> avg time: 0.062 ns/byte, 622.000 ns/call average length 1000000 -> avg time: 0.062 ns/byte, 62000.000 ns/call chqrlie> gcc -std=c99 -O1 benchstrlen.c && ./a.out average length 0 -> avg time: 20.000 ns/byte, 20.000 ns/call average length 4 -> avg time: 3.818 ns/byte, 21.000 ns/call average length 10 -> avg time: 2.190 ns/byte, 23.000 ns/call average length 50 -> avg time: 0.990 ns/byte, 50.000 ns/call average length 100 -> avg time: 0.816 ns/byte, 82.000 ns/call average length 500 -> avg time: 0.679 ns/byte, 340.000 ns/call average length 1000 -> avg time: 0.664 ns/byte, 664.000 ns/call average length 5000 -> avg time: 0.651 ns/byte, 3254.000 ns/call average length 10000 -> avg time: 0.649 ns/byte, 6491.000 ns/call average length 1000000 -> avg time: 0.648 ns/byte, 648000.000 ns/call chqrlie> gcc -std=c99 -O2 benchstrlen.c && ./a.out average length 0 -> avg time: 10.000 ns/byte, 10.000 ns/call average length 4 -> avg time: 2.000 ns/byte, 11.000 ns/call average length 10 -> avg time: 1.048 ns/byte, 11.000 ns/call average length 50 -> avg time: 0.337 ns/byte, 17.000 ns/call average length 100 -> avg time: 0.299 ns/byte, 30.000 ns/call average length 500 -> avg time: 0.202 ns/byte, 101.000 ns/call average length 1000 -> avg time: 0.188 ns/byte, 188.000 ns/call average length 5000 -> avg time: 0.174 ns/byte, 868.000 ns/call average length 10000 -> avg time: 0.172 ns/byte, 1716.000 ns/call average length 1000000 -> avg time: 0.172 ns/byte, 172000.000 ns/call </pre>
17,247,189
Spring @RequestBody containing a list of different types (but same interface)
<p>Let's say that I have a domain class :</p> <pre><code> public class Zoo{ private List&lt;Animal&gt; animals; .... </code></pre> <p>where an Animal is an interface with different implementations (Cat,Dog). Let's say that I want to be able to save a Zoo object :</p> <pre><code> @RequestMapping(value = "/zoo", method = RequestMethod.POST) public @ResponseBody void save(@RequestBody Zoo zoo) { .... </code></pre> <p>and I want to send a json - something like :</p> <pre><code> { animals:[ {type:'Cat', whiskers-length:'3'}, {type:'Dog', name:'Fancy'} ] } </code></pre> <p>How can I tell spring MVC to map animal to Cat type when type=='Cat' and to map it to a Dog class when type=='Dog'?</p>
17,247,382
2
1
null
2013-06-22 04:02:09.073 UTC
9
2019-02-17 11:21:47.96 UTC
null
null
null
null
1,936,950
null
1
28
java|json|spring|spring-mvc
15,139
<p>You should use the Jackson annotations <a href="http://jackson.codehaus.org/1.9.0/javadoc/org/codehaus/jackson/annotate/JsonTypeInfo.html" rel="noreferrer"><code>@JsonTypeInfo</code></a> and <a href="http://jackson.codehaus.org/1.5.2/javadoc/org/codehaus/jackson/annotate/JsonSubTypes.html" rel="noreferrer"><code>@JsonSubTypes</code></a> to achieve polymorphic json. The annotations go on the <code>Animal</code> base class.</p> <pre><code>@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({@JsonSubTypes.Type(value = Dog.class, name = "Dog"), @JsonSubTypes.Type(value = Cat.class, name = "Cat")}) public abstract class Animal { } </code></pre>
17,199,113
psycopg2 leaking memory after large query
<p>I'm running a large query in a python script against my postgres database using psycopg2 (I upgraded to version 2.5). After the query is finished, I close the cursor and connection, and even run gc, but the process still consumes a ton of memory (7.3gb to be exact). Am I missing a cleanup step?</p> <pre><code>import psycopg2 conn = psycopg2.connect("dbname='dbname' user='user' host='host'") cursor = conn.cursor() cursor.execute("""large query""") rows = cursor.fetchall() del rows cursor.close() conn.close() import gc gc.collect() </code></pre>
27,940,340
3
0
null
2013-06-19 18:55:55.513 UTC
15
2016-01-30 14:46:07.64 UTC
null
null
null
null
1,026,542
null
1
32
python|postgresql|psycopg2
18,825
<p>I ran into a similar problem and after a couple of hours of blood, sweat and tears, found the answer simply requires the addition of one parameter.</p> <p>Instead of</p> <pre><code>cursor = conn.cursor() </code></pre> <p>write</p> <pre><code>cursor = conn.cursor(name="my_cursor_name") </code></pre> <p>or simpler yet </p> <pre><code>cursor = conn.cursor("my_cursor_name") </code></pre> <p>The details are found at <a href="http://initd.org/psycopg/docs/usage.html#server-side-cursors">http://initd.org/psycopg/docs/usage.html#server-side-cursors</a></p> <p>I found the instructions a little confusing in that I though I'd need to rewrite my SQL to include "DECLARE my_cursor_name ...." and then a "FETCH count 2000 FROM my_cursor_name" but it turns out psycopg does that all for you under the hood if you simply overwrite the "name=None" default parameter when creating a cursor.</p> <p>The suggestion above of using fetchone or fetchmany doesn't resolve the problem since, if you leave the name parameter unset, psycopg will by default attempt to load the entire query into ram. The only other thing you may need to to (besides declaring a name parameter) is change the cursor.itersize attribute from the default 2000 to say 1000 if you still have too little memory.</p>
17,274,329
svn 1.7.8 database is locked, cannot release
<p>when I run: </p> <pre><code>svn cleanup </code></pre> <p>I get the error message:</p> <pre><code>svn: E200033: database is locked, executing statement 'RELEASE s0' </code></pre> <p>or any other command to change DB, e.g. <code>commit</code>, <code>update</code> etc.</p> <p>This is on linux server, the directory is nfs. </p> <p>I can checkout another version and copy my changes, but it is a hassle and I think this error will come back. </p> <p>how do I fix this on a working directory, and is there a way to prevent it. </p> <p>p.s. there are no processes currently running, maybe eclipse crashed in the middle of some action. </p>
17,346,612
14
4
null
2013-06-24 11:25:56.637 UTC
19
2020-09-15 08:55:22.107 UTC
2013-06-24 12:05:13.937 UTC
null
398,670
null
21,274
null
1
56
svn
70,982
<p>This helped me solve the problem (subversion 1.7.10):</p> <pre><code>$ cd /my/repository/.svn $ mv wc.db wc.db.old $ sqlite3 wc.db.old sqlite&gt; .backup main wc.db sqlite&gt; .exit </code></pre> <p>After making sure it works, you can remove wc.db.old.</p> <p>See also: <a href="http://technosophos.com/content/sqlite-database-locked-error-and-unlocking-database" rel="noreferrer">http://technosophos.com/content/sqlite-database-locked-error-and-unlocking-database</a></p>
30,689,526
How to call python script from NodeJs
<p>I need to call this python script in NodeJs.</p> <p><strong>Read.py</strong></p> <pre><code>#!/usr/bin/env python # -*- coding: utf8 -*- import RPi.GPIO as GPIO import MFRC522 import signal continue_reading = True # Capture SIGINT for cleanup when the script is aborted def end_read(signal,frame): global continue_reading print "Ctrl+C captured, ending read." continue_reading = False GPIO.cleanup() # Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 MIFAREReader = MFRC522.MFRC522() # Welcome message print "Welcome to the MFRC522 data read example" print "Press Ctrl-C to stop." # This loop keeps checking for chips. If one is near it will get the UID and authenticate while continue_reading: # Scan for cards (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) # If a card is found if status == MIFAREReader.MI_OK: # Get the UID of the card (status,uid) = MIFAREReader.MFRC522_Anticoll() # If we have the UID, continue if status == MIFAREReader.MI_OK: # Print UID print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]) # This is the default key for authentication key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] # Select the scanned tag MIFAREReader.MFRC522_SelectTag(uid) # Authenticate status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid) # Check if authenticated if status == MIFAREReader.MI_OK: MIFAREReader.MFRC522_Read(8) MIFAREReader.MFRC522_StopCrypto1() else: print "Authentication error" </code></pre> <p>I used python-shell, here is the NodeJs code for that</p> <p><strong>Test.js</strong></p> <pre><code>var PythonShell = require('python-shell'); var options = { scriptPath: '/home/pi/gpio-admin/MFRC522-python/' }; var pyshell = new PythonShell('Read.py',options); pyshell.on('message', function (message) { console.log(message); }); </code></pre> <p>But when I ran this code I didn't see anything in Node side. I think problem occurs when python script comes to this level. </p> <pre><code> (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) </code></pre> <p>Because I just ran with while loop which has only print statement then it works. After that I tried another way to achieve this. But I got same problem which I have with above.Here is another method</p> <p><strong>AltTest.js</strong> </p> <pre><code>var python = require('child_process').spawn( 'python', // second argument is array of parameters, e.g.: ["/home/pi/gpio-admin/MFRC522-python/Read.py"] ); var output = ""; python.stdout.on('data', function(){ output += data ; console.log(data); }); python.on('close', function(code){ console.log("Here you are there..."); }); </code></pre> <p>Any help would be appreciated </p>
30,689,597
6
2
null
2015-06-07 02:34:35.04 UTC
13
2021-06-19 10:13:35.013 UTC
null
null
null
null
1,574,779
null
1
17
javascript|python|node.js|python-2.7|raspberry-pi
62,416
<p>There are multiple ways of doing this. </p> <ul> <li>first way is by doing <code>npm install python-shell</code> </li> </ul> <p>and here's the code</p> <pre><code>var PythonShell = require('python-shell'); //you can use error handling to see if there are any errors PythonShell.run('my_script.py', options, function (err, results) { //your code </code></pre> <p>you can send a message to python shell using <code>pyshell.send('hello');</code></p> <p>you can find the API reference here- <a href="https://github.com/extrabacon/python-shell" rel="noreferrer">https://github.com/extrabacon/python-shell</a></p> <ul> <li><p>second way - another package you can refer to is node python , you have to do <code>npm install node-python</code></p></li> <li><p>third way - you can refer to this question where you can find an example of using a child process- <a href="https://stackoverflow.com/questions/20972788/how-to-invoke-external-scripts-programs-from-node-js">How to invoke external scripts/programs from node.js</a></p></li> </ul> <p>a few more references - <a href="https://www.npmjs.com/package/python" rel="noreferrer">https://www.npmjs.com/package/python</a></p> <p>if you want to use service-oriented architecture - <a href="http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/" rel="noreferrer">http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/</a></p>
18,290,863
Right approach to building SAAS in Laravel 4
<p>Ok, so about a year ago I wrote a web app that helps organize appointments for my dads company. He now "couldn't do business without it". I have decided that I want to build a SAAS subscription model out of it and open it up to the public.</p> <p>It's currently built on codeigniter and php which I do not think is a good fit for a SAAS version. I am planning on rebuiling it from scratch in laravel 4 and using stripe as a payment gateway.</p> <p>My concern is how best to handle the database / application structure for more than one client. Currently, it just serves the one business and is very un-abstract and is specific to my dads companies needs. I need it to be able to handle different data depending on what the business who uses it does.</p> <p>I have looked into multi-tenancy but i'm not sure this is right for this. I am thinking that a 'gmail' style approach would be better. One app / domain that after login the user will see their customised dashboard and only their data.</p> <p>Before I get stuck in with the coding I need to work out how best to handle multiple 'accounts' on the one database. I do not want to create a table for each user, nor a database for each user.</p> <p>I guess my question is can anybody point me in the right direction for how best to handle a monthly payment subscription in Laravel? It's not so much the code that I'm stuggling with, rather what exactly I would need to build to handle charging the customer each month and denying them access if billing failed etc.</p> <p>Thanks</p>
18,293,859
2
0
null
2013-08-17 16:14:37.33 UTC
13
2013-08-18 16:06:10.903 UTC
2013-08-17 16:22:44.177 UTC
null
1,317,935
user1157393
null
null
1
14
database|laravel|laravel-4|saas|stripe-payments
5,349
<p>You are in for a lot of reading and a ton of work!</p> <p>First of all, let's completely ignore the billing aspect of this for now — at the end of the day that portion of the application is really fairly trivial. Take a page out of <a href="http://37signals.com/rework">37signals <em>Rework</em></a> (page 93 and 94) and launch your product with a 30 day free trial before you even begin implementing it (you should know how to implement it by then).</p> <p>Second, why do you think that "gmail" doesn't use multi-tenancy, URI structure tells nothing about the underlying database structure. I'm fairly confident they aren't cloning a database schema for every one of their customers. Therefore you've probably answered your own question — <strong>you want to implement multi-tenancy</strong>.</p> <p>You're going to want to abstract your database (and application architecture), and honestly there is no better resource to help you on your way to doing that than Taylor Otwell's (creator of Laravel) book <a href="https://leanpub.com/laravel"><em>Laravel: From Apprentice To Artisan</em></a>. His book is not for beginners, and by the time you're done reading it you should probably be able to answer this question for yourself.</p> <p>You are not going to be creating a table or a database for each user, you aren't even going to be creating one for each organization. Instead you'll be creating abstract database structure in code, which will pull your users data out of the database.</p> <p>Think about checking for permission to access an organization as another layer of user authentication. On every request you'll be checking to see if that user can access a particular organization. You'll likely also check to ensure that organization is still active (did it expire because they didn't pay?) this will again happen on every request and likely with a <a href="http://laravel.com/docs/routing#route-filters">filter within laravel</a>.</p> <p>This really leads to the next very important factor of developing a SaaS application.</p> <p>I don't know about you, but I'm paranoid, and I couldn't sleep well at night if I wasn't sure that user number <code>4506</code> couldn't see the data of an organization that he doesn't belong to. The only really good way to ensure this is through unit testing, which I'd highly suggest learning if you haven't already.</p> <p>The best way to do this within Laravel 4 is to read Jeffrey Way's book <a href="https://leanpub.com/laravel-testing-decoded"><em>Laravel Testing Decoded</em></a>. This book is extremely advanced, but still easy to understand if you have a good grasp of the fundamentals.</p> <p>Last but not least, the number one thing is get involved in the community — the easiest way I'd suggest doing that is idling on the <a href="http://laravel.io/irc">#laravel IRC channel</a> (freenode). Ask some questions, maybe answer some questions, everyone in the channel is very nice and responsive.</p> <p>You are definitely in for an adventure, don't be afraid to ask questions and make mistakes. Good luck.</p>
12,550,184
Throw a format exception C#
<p>I'm trying to throw a format exception in the instance someone tries to enter a non-integer character when prompted for their age. </p> <pre><code> Console.WriteLine("Your age:"); age = Int32.Parse(Console.ReadLine()); </code></pre> <p>I'm unfamiliar with C# language and could use help in writing a try catch block for this instance. </p> <p>Thanks very much. </p>
12,550,197
4
4
null
2012-09-23 06:19:08.937 UTC
0
2021-09-16 16:28:42.81 UTC
null
null
null
null
1,513,637
null
1
5
c#|try-catch|formatexception
76,548
<p>That code will already throw an <code>FormatException</code>. If you mean you want to <em>catch</em> it, you could write:</p> <pre><code>Console.WriteLine("Your age:"); string line = Console.ReadLine(); try { age = Int32.Parse(line); } catch (FormatException) { Console.WriteLine("{0} is not an integer", line); // Return? Loop round? Whatever. } </code></pre> <p>However, it would be <em>better</em> to use <code>int.TryParse</code>:</p> <pre><code>Console.WriteLine("Your age:"); string line = Console.ReadLine(); if (!int.TryParse(line, out age)) { Console.WriteLine("{0} is not an integer", line); // Whatever } </code></pre> <p>This avoids an exception for the fairly unexceptional case of user error.</p>
32,062,894
Take advantage of ARM unaligned memory access while writing clean C code
<p>It used to be that ARM processors were unable to properly handle unaligned memory access (ARMv5 and below). Something like <code>u32 var32 = *(u32*)ptr;</code> would just fail (raise exception) if <code>ptr</code> was not properly aligned on 4-bytes.</p> <p>Writing such a statement would work fine for x86/x64 though, since these CPU have always handled such situation very efficiently. But according to C standard, this is not a "proper" way to write it. <code>u32</code> is apparently equivalent to a structure of 4 bytes which <em>must</em> be aligned on 4 bytes.</p> <p>A proper way to achieve the same result while keeping the orthodoxy correctness <em>and</em> ensuring full compatibility with any cpu is : </p> <pre><code>u32 read32(const void* ptr) { u32 result; memcpy(&amp;result, ptr, 4); return result; } </code></pre> <p>This one is correct, will generate proper code for any cpu able or not to read at unaligned positions. Even better, on x86/x64, it's properly optimized to a single read operation, hence has the same performance as the first statement. It's portable, safe, and fast. Who can ask more ?</p> <p>Well, problem is, on ARM, we are not so lucky.</p> <p>Writing the <code>memcpy</code> version is indeed safe, but seems to result in systematic cautious operations, which are very slow for ARMv6 and ARMv7 (basically, any smartphone).</p> <p>In a performance oriented application which heavily relies on read operations, the difference between the 1st and 2nd version could be measured : it stands at <strong>> 5x</strong> at <code>gcc -O2</code> settings. This is way too much to be ignored.</p> <p>Trying to find a way to use ARMv6/v7 capabilities, I've looked for guidance on a few example codes around. Unfortunatley, they seem to select the first statement (direct <code>u32</code> access), which is not supposed to be correct.</p> <p>That's not all : new GCC versions are now trying to implement auto-vectorization. On x64, that means SSE/AVX, on ARMv7 that means NEON. ARMv7 also supports some new "Load Multiple" (LDM) and "Store Multiple" (STM) opcodes, which <em>require</em> pointer to be aligned.</p> <p>What does that mean ? Well, the compiler is free to use these advanced instructions, even if they were not specifically called from the C code (no intrinsic). To take such decision, it uses the fact the an <code>u32* pointer</code> is supposed to be aligned on 4 bytes. If it's not, then all bets are off : undefined behavior, crashes.</p> <p>What that means is that even on CPU which support unaligned memory access, it's now dangerous to use direct <code>u32</code> access, as it can lead to buggy code generation at high optimization settings (<code>-O3</code>).</p> <p>So now, this is a dilemna : how to access the native performance of ARMv6/v7 on unaligned memory access <em>without</em> writing the incorrect version <code>u32</code> access ?</p> <p>PS : I've also tried <code>__packed()</code> instructions, and from a performance perspective, they seem to work exactly the same as the <code>memcpy</code> method.</p> <p><em>[Edit] :</em> Thanks for the excellent elements received so far.</p> <p>Looking at the generated assembly, I could confirm @Notlikethat finding that <code>memcpy</code> version does indeed generate proper <code>ldr</code> opcode (unaligned load). However, I also found that the generated assembly uselessly invokes <code>str</code> (command). So the complete operation is now an unaligned load, an aligned store, and then a final aligned load. That's a lot more work than necessary.</p> <p>Answering @haneefmubarak, yes the code is properly inlined. And no, <code>memcpy</code> is very far from providing the best possible speed, since forcing the code to accept direct <code>u32</code> access translates into huge performance gains. So some better possibility must exist.</p> <p>A big thank to @artless_noise. The link to godbolt service is unvaluable. I've never been able to see so clearly the equivalence between a C source code and its assembly representation. This is highly inspiring.</p> <p>I completed one of @artless examples, and it gives the following :</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;memory.h&gt; typedef unsigned int u32; u32 reada32(const void* ptr) { return *(const u32*) ptr; } u32 readu32(const void* ptr) { u32 result; memcpy(&amp;result, ptr, 4); return result; } </code></pre> <p>once compiled using ARM GCC 4.8.2 at -O3 or -O2 :</p> <pre><code>reada32(void const*): ldr r0, [r0] bx lr readu32(void const*): ldr r0, [r0] @ unaligned sub sp, sp, #8 str r0, [sp, #4] @ unaligned ldr r0, [sp, #4] add sp, sp, #8 bx lr </code></pre> <p>Quite telling ....</p>
32,095,106
2
19
null
2015-08-18 03:09:44.17 UTC
14
2017-03-26 20:06:48.263 UTC
2015-08-18 19:04:23.727 UTC
null
646,947
null
646,947
null
1
33
c|arm|memory-alignment
12,864
<p>OK, the situation is more confusing than one would like. So, in an effort to clarify, here are the findings on this journey : </p> <h2><em>accessing unaligned memory</em></h2> <ol> <li>The only portable C standard solution to access unaligned memory is the <code>memcpy</code> one. I was hoping to get another one through this question, but apparently it's the only one found so far.</li> </ol> <p>Example code :</p> <pre><code>u32 read32(const void* ptr) { u32 value; memcpy(&amp;value, ptr, sizeof(value)); return value; } </code></pre> <p>This solution is safe in all circumstances. It also compiles into a trivial <code>load register</code> operation on x86 target using GCC.</p> <p>However, on ARM target using GCC, it translates into a way too large and useless assembly sequence, which bogs down performance.</p> <p>Using Clang on ARM target, <code>memcpy</code> works fine (see @notlikethat comment below). It would be easy to blame GCC at large, but it's not that simple : the <code>memcpy</code> solution works fine on GCC with x86/x64, PPC and ARM64 targets. Lastly, trying another compiler, icc13, the memcpy version is surprisingly heavier on x86/x64 (4 instructions, while one should be enough). And that's just the combinations I could test so far.</p> <p>I have to thank godbolt's project to make such statements <a href="https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXOUQCMB0AFgHwBQoksiqAtgjQPYBOAnkWRiwA4KIBmSGGDQgA5mF5JwGQQGYATAG5SpTj35JMTGBBlIA%2BvoCGGDEzwwMCQ0gAUtw1yMQA1r0MBKD0gDeg4WIScEi4ikgAvoIwCsrR8khMCEZwcbYQDMIyAG4MIHAAVEhcZt5%2BiRgwTGB2aRmYUQr5HsVMHgC0xKERKnEJSXBGCrWZSDl5hS2lfRVVSPnD9XFNRWZh4T0KfclD6SNjBSutSKR%2BpEjnfaIgmAhMcvGJaDBQGGFnF3Q0EFwstgBkj2eGAANIdQQAWDxvC7TSrVQEvN7hIAAA%22%2C%22compiler%22%3A%22armhfg482%22%2C%22options%22%3A%22-O3%22%7D%5D%7D" rel="noreferrer">easy to observe</a>.</p> <ol start="2"> <li>The second solution is to use <code>__packed</code> structures. This solution is not C standard, and entirely depends on compiler's extension. As a consequence, the way to write it depends on the compiler, and sometimes on its version. This is a mess for maintenance of portable code.</li> </ol> <p>That being said, in most circumstances, it leads to better code generation than <code>memcpy</code>. In most circumstances only ...</p> <p>For example, regarding the above cases where <code>memcpy</code> solution does not work, here are the findings :</p> <ul> <li>on x86 with ICC : <code>__packed</code> solution works</li> <li>on ARMv7 with GCC : <code>__packed</code> solution works</li> <li><p>on ARMv6 with GCC : does not work. Assembly looks even uglier than <code>memcpy</code>.</p> <ol start="3"> <li>The last solution is to use direct <code>u32</code> access to unaligned memory positions. This solution used to work for decades on x86 cpus, but is not recommended, as it violates some C standard principles : compiler is authorized to consider this statement as a guarantee that data is properly aligned, leading to buggy code generation.</li> </ol></li> </ul> <p>Unfortunately, in at least one case, it is the only solution able to extract performance from target. Namely for GCC on ARMv6.</p> <p>Do not use this solution for ARMv7 though : GCC can generate instructions which are reserved for aligned memory accesses, namely <code>LDM</code> (Load Multiple), leading to crash.</p> <p>Even on x86/x64, it becomes dangerous to write your code this way nowadays, as the new generation compilers may try to auto-vectorize some compatible loops, generating SSE/AVX code <em>based on the assumption that these memory positions are properly aligned</em>, crashing the program.</p> <p>As a recap, here are the results summarized as a table, using the convention : memcpy > packed > direct.</p> <pre><code>| compiler | x86/x64 | ARMv7 | ARMv6 | ARM64 | PPC | |-----------|---------|--------|--------|--------|--------| | GCC 4.8 | memcpy | packed | direct | memcpy | memcpy | | clang 3.6 | memcpy | memcpy | memcpy | memcpy | ? | | icc 13 | packed | N/A | N/A | N/A | N/A | </code></pre>
5,583,401
Serialize datetime to JSON
<p>How do I get DateTimeField from the Mysql database in Django in JSON format? I got an error when I executed the code <code>Date.time cannot be serialized in json</code> (data holds a lot of values):</p> <pre class="lang-py prettyprint-override"><code>data = json.dumps(data) </code></pre> <p>But this was fixed by adding</p> <pre class="lang-py prettyprint-override"><code>ALL_data = serializers.serialize(&quot;json&quot;, data, ensure_ascii=False) </code></pre> <p>But now I get <code>'str' object has no attribute '_meta'</code>.</p>
5,781,657
3
0
null
2011-04-07 15:14:48.85 UTC
9
2021-09-25 22:20:09.193 UTC
2021-09-25 22:20:09.193 UTC
null
11,573,842
null
532,312
null
1
25
python|django
29,250
<p><a href="https://docs.djangoproject.com/en/stable/topics/serialization/#djangojsonencoder" rel="noreferrer"><strong>DjangoJSONEncoder</strong></a> solved my problem.</p> <pre><code>import json from django.core.serializers.json import DjangoJSONEncoder data = json.dumps(data, cls=DjangoJSONEncoder) </code></pre>
5,385,039
Naming convention to differentiate partial views from normal views
<p>Is there any unofficial standard naming convention for partial views? I've seen someone suggested prefixing with "_", others postfixing with "Partial", I know the question is subjective, but since there is no official guideline, I'd like to know what the majority here uses for naming their partial views. Perhaps the most voted answer WILL become the standard.</p> <p>Update: I'm using ASP.NET MVC 3 with Razor as the view engine, in previous versions you didn't need a convention because you had the .ascx extension</p>
5,398,840
3
6
null
2011-03-21 23:39:23.207 UTC
4
2011-03-22 22:52:36.307 UTC
2011-03-22 02:14:33.157 UTC
null
8,411
null
8,411
null
1
45
asp.net-mvc|naming-conventions|razor
14,279
<p>If you look at WebMatrix, the convention is to prefix Razor files that are not meant to be served directly with a leading underscore. That includes partials and layout pages. Then if you look at <a href="http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/" rel="noreferrer">MvcScaffolding</a>, you can see that the default templates generate files using the same naming convention.</p> <p>Read <a href="https://stackoverflow.com/questions/4576548/why-does-razor-layout-cshtml-have-a-leading-underscore-in-file-name/4577799#4577799">this</a> for an explanation as to why that convention might be used.</p>
4,854,148
PHP & MySql check if table is empty
<p>I'm a bit of a noob- and I'm having a hard time...</p> <p>I need a bit of of code that searches a db table to find the row that matches the $id variable. There's a field in that table 'description' that I need to grab. If it's null, I need to show one message, if not another. Here's the code I have (I know I need to add the mysqli escape string, just doing this real quick from memory):</p> <pre><code>$query = "SELECT description FROM posts WHERE id = $id"; $result = mysqli_query($dbc, $query); $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ; if(!$row){ echo "&lt;p&gt;'No description'&lt;/p&gt;"; } else { echo '&lt;p&gt;' . $row['description'] . '&lt;/p&gt;'; } </code></pre>
4,854,174
4
4
null
2011-01-31 17:42:40.42 UTC
2
2012-03-31 13:11:19.38 UTC
2011-01-31 17:53:58.26 UTC
null
300,897
null
517,593
null
1
6
php|mysql|if-statement
50,741
<p><code>mysqli_fetch_array</code> will fetch a row regardless of if the columns in that row are null. You want to be checking if <code>$row['description']</code> is set instead of if <code>$row</code> is set:</p> <pre><code>$query = "SELECT description FROM posts WHERE id = $id"; $result = mysqli_query($dbc, $query); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); if(isset($row['description'])) { echo "&lt;p&gt;No description&lt;/p&gt;"; } else { echo '&lt;p&gt;' . $row['description'] . '&lt;/p&gt;'; } </code></pre> <p><strong>EDIT:</strong> Or, as an alternative, you can <em>not fetch rows from the database where description is NULL:</em></p> <pre><code>$query = "SELECT description FROM posts WHERE id = $id AND description IS NOT NULL LIMIT 1"; $result = mysqli_query($dbc, $query); $row = mysqli_fetch_array($result, MYSQLI_ASSOC); if(! $row) { echo "&lt;p&gt;No description&lt;/p&gt;"; } else { echo '&lt;p&gt;' . $row['description'] . '&lt;/p&gt;'; } </code></pre> <p><strong>Now</strong> you'd check to see if you were able to grab a row or not.</p>
9,244,824
How to remove &quot; from my Json in javascript?
<p>I am trying to inject json into my backbone.js app. My json has <code>&amp;quot;</code> for every quote.</p> <p>Is there a way for me to remove this? <br>I've provided a sample below:</p> <pre><code>[{&amp;quot;Id&amp;quot;:1,&amp;quot;Name&amp;quot;:&amp;quot;Name}] </code></pre>
9,244,845
9
3
null
2012-02-11 23:03:53.873 UTC
15
2021-10-24 13:11:37.12 UTC
2012-02-11 23:06:10.087 UTC
null
138,475
null
1,074,003
null
1
102
javascript
146,377
<p>Presumably you have it in a variable and are using <code>JSON.parse(data);</code>. In which case, use:</p> <pre><code>JSON.parse(data.replace(/&amp;quot;/g,'"')); </code></pre> <p>You might want to fix your JSON-writing script though, because <code>&amp;quot;</code> is not valid in a JSON object.</p>
18,223,402
How to start GUI from command line in Android-x86
<p>I managed to get Android-x86 running in VMware player, but if I need to go to the command line by pressing Alt+F1 I cannot go back to the GUI. How do I restart the GUI from the command line?</p>
18,225,031
4
0
null
2013-08-14 04:46:26.593 UTC
9
2022-04-04 15:09:36.953 UTC
2019-04-20 11:52:24.947 UTC
null
472,495
null
1,693,203
null
1
28
android|android-x86
101,627
<p>To go back to GUI try use Alt+F7</p>
19,929,186
Combobox null in if statement
<p>I am trying to code an if statement where if a certain combobox is null, then it runs a certain part of code if it has data in it then it runs another. I wrote up this:</p> <pre><code>Private Sub ProjectAddSetDateAutoBtn_Click() If ProjectAddAllDueDateAutoCmBx = Null Then 'Code1 Msgbox("ComboBox Is Null") Else 'Code2 Msgbox("ComboBox Has Data") End If End Sub </code></pre> <p>I leave the combobox with no data, and then it doesn't run the code in the first part of the if or the code in the 2nd part of it either! If I enter data into the box, it runs the 2nd part of the if statement perfectly. There are no errors, I am quite stumped on this. Do ComboBoxes have their own "Null"? Is there a problem with this if statement?</p>
19,929,496
5
3
null
2013-11-12 12:27:53.593 UTC
1
2013-11-12 13:40:18.803 UTC
2013-11-12 12:32:57.003 UTC
null
2,915,607
null
2,915,607
null
1
13
ms-access|vba|ms-access-2013
66,678
<p><a href="https://stackoverflow.com/a/13869017/77335">Nothing is ever equal to Null, not even another Null</a>.</p> <p>Use <a href="http://office.microsoft.com/en-us/access-help/isnull-function-HA001228867.aspx" rel="noreferrer">IsNull()</a> to check whether the combo box is Null.</p> <pre class="lang-vb prettyprint-override"><code>'If ProjectAddAllDueDateAutoCmBx = Null Then If IsNull(ProjectAddAllDueDateAutoCmBx) = True Then </code></pre>
20,310,209
How to perform Stream functions on an Iterable?
<p>In Java 8, the <code>Stream</code> class does not have any method to wrap a an <code>Iterable</code>.</p> <p>Instead, I am obtaining the <code>Spliterator</code> from the <code>Iterable</code> and then obtaining a <code>Stream</code> from <code>StreamSupport</code> like this:</p> <pre><code>boolean parallel = true; StreamSupport.stream(spliterator(), parallel) .filter(Row::isEmpty) .collect(Collectors.toList()) .forEach(this::deleteRow); </code></pre> <p>Is there some other way of generating <code>Stream</code> operations on an <code>Iterable</code> that I am missing?</p>
22,870,302
3
3
null
2013-12-01 08:24:18.89 UTC
5
2015-02-17 16:41:51.64 UTC
2015-02-17 16:41:51.64 UTC
null
1,441,122
null
1,584,255
null
1
32
java|java-8|java-stream|iterable|spliterator
14,265
<p>My similar question got marked as duplicate, but here is the helper methods I've used to avoid some of the boilerplate:</p> <pre><code>public static &lt;T&gt; Stream&lt;T&gt; stream(Iterable&lt;T&gt; in) { return StreamSupport.stream(in.spliterator(), false); } public static &lt;T&gt; Stream&lt;T&gt; parallelStream(Iterable&lt;T&gt; in) { return StreamSupport.stream(in.spliterator(), true); } </code></pre>
14,931,510
Android - Gesture Detection (Swipe up/down) on particular view
<p>I am trying to implement the OnGestureListener in Android. <br/>I have three TextViews in my layout. <br/>What i am trying to achieve is to set Gesture Listener for two of the textViews .<br/> Here is the <strong>layout</strong> - <br/></p> <pre><code> &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;TextView android:id="@+id/tvOne" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginBottom="10dp" android:layout_marginTop="5dp" android:gravity="center" android:text="One" /&gt; &lt;TextView android:id="@+id/tvTwo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/tvOne" android:layout_centerHorizontal="true" android:layout_marginBottom="10dp" android:layout_marginTop="5dp" android:gravity="center" android:text="Two" /&gt; &lt;TextView android:id="@+id/tvThree" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/tvTwo" android:layout_centerHorizontal="true" android:layout_marginBottom="10dp" android:layout_marginTop="5dp" android:gravity="center" android:text="Three" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>And here is the <strong>activity</strong></p> <pre><code> import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; public class TimeActivity extends Activity implements OnGestureListener { GestureDetector gestureScanner; @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wheelview); gestureScanner = new GestureDetector(this); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub return gestureScanner.onTouchEvent(event); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub Log.i("Test", "On Fling"); return true; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } } </code></pre> <p>At present Fling for all the three textviews is getting called .<br/> Is there any way through which i can set the <strong>Gesture Listener for some particular views in the layout</strong>.<br/> Any help will be highly appreciated.</p>
14,931,627
3
0
null
2013-02-18 07:42:22.037 UTC
5
2020-03-05 08:26:51.6 UTC
2020-03-05 08:26:51.6 UTC
null
3,891,036
null
1,997,711
null
1
28
android|swipe|gesture-recognition|onfling
52,262
<p>Do this in your <code>onCreate</code> method.</p> <pre><code>findViewById(R.id.tvOne).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event){ return gestureScanner.onTouchEvent(event); } }); </code></pre>
14,993,855
Android ADB device offline, can't issue commands
<p>I can't connect to my device anymore using <a href="http://en.wikipedia.org/wiki/Android_Debug_Bridge" rel="noreferrer">ADB</a> through the command line or in <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a>.</p> <p>Running the command</p> <pre><code>adb devices </code></pre> <p>returns the device name, but it says it's offline.</p> <p>Things I've tried.</p> <ol> <li>Toggled Android debugging mode</li> <li>Reinstalled the Google USB driver</li> <li>Restored the OS to a previously working backup (<a href="http://en.wikipedia.org/wiki/CyanogenMod" rel="noreferrer">CyanogenMod</a>)</li> <li>Swapped the USB cord</li> <li>Rebooted the phone/computer multiple times</li> <li>Updated the Android SDK</li> </ol> <p>I really don't have any clue what's going on. Anything else you think I can try, I'm all ears.</p> <p><strong>To be clear, if you're having this same issue the problem is probably an out-of-date SDK. As of 4.2.2 there is a security feature that requires you to confirm the RSA fingerprint of the connecting device. Open the SDK manager and update the tools! Then reboot.</strong></p>
15,000,565
66
13
2014-01-10 08:07:56.2 UTC
2013-02-21 03:01:29.557 UTC
64
2022-06-16 22:52:07.617 UTC
2014-02-20 14:21:07.53 UTC
null
63,550
null
461,631
null
1
361
android|adb|android-2.2-froyo
834,083
<p>I just got the same problem today after my <a href="https://en.wikipedia.org/wiki/Nexus_7_%282013_version%29">Nexus 7</a> and <a href="https://en.wikipedia.org/wiki/Galaxy_Nexus">Galaxy Nexus</a> were updated to Android 4.2.2.</p> <p>The thing that fixed it for me was to upgrade the SDK platform-tools to r16.0.1. For me, this version was not displayed in my SDK Manager, so I pulled it down from <a href="http://dl.google.com/android/repository/platform-tools_r16.0.1-windows.zip">http://dl.google.com/android/repository/platform-tools_r16.0.1-windows.zip</a> directly.</p> <p>You then need to rename the <code>platform-tools</code> directory and unzip it to <code>android-sdk-windows/platform-tools</code>. Using the SDK Manager, I had also updated to the latest sdk-tools before this.</p> <p>If your whole Eclipse and <a href="http://developer.android.com/guide/developing/tools/adt.html">ADT</a> are ancient, you may need to update them as well, but I didn't need to.</p> <p>Note: you may need to run SDK Manager twice (once to update itself) before you will see the latest packages.</p>
43,669,773
Angular 2: formGroup expects a FormGroup instance. Please pass one in
<p>I am creating a form in Angular 2. My goal is to get data from the API and pass it into the form for editing purposes. However, I am running into this error:</p> <blockquote> <p>EXCEPTION: Uncaught (in promise): Error: Error in ./EditPatientComponent class EditPatientComponent - inline template:1:10 caused by: formGroup expects a FormGroup instance. Please pass one in.</p> </blockquote> <p>Here is the current code with the error.</p> <p><strong>html</strong></p> <pre><code>&lt;section class="CreatePatient"&gt; &lt;form [formGroup]="patientForm" (ngSubmit)="onSubmit()"&gt; &lt;div class="row"&gt; &lt;div class="form-group col-12 col-lg-3"&gt; &lt;label for="firstName"&gt;First Name&lt;/label&gt; &lt;input formControlName="firstName" type="text" class="form-control" id="firstName" &gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-12 col-lg-2"&gt; &lt;button type="submit" name="submit" class="btn btn-block btn-primary"&gt;Save&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/section&gt; </code></pre> <p><strong>ts</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; import { PatientService } from './patient.service'; import { Patient } from './patient'; @Component({ templateUrl: 'editpatient.component.html' }) export class EditPatientComponent implements OnInit { errorMessage: string; id: string; editMode = true; private patientForm: FormGroup; private patient: Patient; constructor( private patientService: PatientService, private router: Router, private activatedRoute: ActivatedRoute, private formBuilder: FormBuilder) { console.log("routes"); console.log(activatedRoute.snapshot.url[1].path); } ngOnInit() { this.getPatient(); } getPatient() { this.patientService.getPatient(this.activatedRoute.snapshot.url[1].path) .subscribe( patient =&gt; { this.id = this.activatedRoute.snapshot.url[1].path; this.patient = patient; this.initForm(); }, error =&gt; this.errorMessage = &lt;any&gt;error); } onSubmit(form){ console.log(this.patientForm); // Post the API }; initForm() { let patientFirstName = ''; if (this.editMode) { console.log(this.patient.firstName); console.log(this.patient.lastName); console.log(this.patient.participantUuid); patientFirstName = this.patient.firstName; } this.patientForm = new FormGroup({ 'firstName': new FormControl(patientFirstName) }) }; } </code></pre> <p>Any help/pointing me in the right direction would be great! Thanks!</p>
43,669,848
5
3
null
2017-04-27 23:55:36.387 UTC
10
2020-12-21 09:31:30.597 UTC
null
null
null
null
5,711,574
null
1
60
forms|angular
107,148
<p>Your <code>patientForm</code> is <code>undefined</code> until the <code>patient</code> in the subscription is populated. As such, you're trying to bind to a value that doesn't exist in the template at the time the template is parsed.</p> <p>Add an <code>*ngIf</code> to render the form only when patient is truthy, or the form group is instantiated:</p> <pre><code>&lt;section class="CreatePatient"&gt; &lt;form *ngIf="patient" [formGroup]="patientForm" (ngSubmit)="onSubmit()"&gt; &lt;div class="row"&gt; &lt;div class="form-group col-12 col-lg-3"&gt; &lt;label for="firstName"&gt;First Name&lt;/label&gt; &lt;input formControlName="firstName" type="text" class="form-control" id="firstName" &gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-12 col-lg-2"&gt; &lt;button type="submit" name="submit" class="btn btn-block btn-primary"&gt;Save&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/section&gt; </code></pre> <p>When the patient is populated in the subscription, the <code>patientForm</code> instance will exist and the binding will work. It's a common "gotcha" when dealing with async values.</p> <p>Forms don't always have starting values, so you can also check for the existence of the form itself:</p> <pre><code>&lt;form *ngIf="patientForm" [formGroup]="patientForm" (ngSubmit)="onSubmit()"&gt; </code></pre> <p>The important part is that the form isn't rendered until its instantiated.</p>
28,256,923
Import cycle not allowed
<p>I have a problem with</p> <blockquote> <p>import cycle not allowed</p> </blockquote> <p>It appears when I am trying to test my controller. Here is the output:</p> <pre><code>can't load package: import cycle not allowed package project/controllers/account imports project/controllers/base imports project/components/mux imports project/controllers/account import cycle not allowed package project/controllers/account imports project/controllers/base imports project/components/mux imports project/controllers/account import cycle not allowed package project/controllers/account imports project/controllers/base imports project/components/mux imports project/controllers/routes imports project/controllers/base </code></pre> <p>How do I read or understand this error? Where is the dependency wrong?</p>
28,258,647
8
2
null
2015-01-31 21:50:08.067 UTC
33
2022-09-02 06:18:32.323 UTC
2021-06-08 13:03:22.83 UTC
null
321,731
null
1,743,843
null
1
204
go
220,645
<p>Here is an illustration of your first import cycle problem.</p> <pre><code> project/controllers/account ^ \ / \ / \ / \/ project/components/mux &lt;--- project/controllers/base </code></pre> <p>As you can see with my bad ASCII chart, you are creating an import cycle when <code>project/components/mux</code> imports <code>project/controllers/account</code>. Since Go does not support circular dependencies you get the <code>import cycle not allowed</code> error during compile time.</p>
7,958,816
How to get multiple rows into one line as a string?
<p>I have two tables "one to many":</p> <p>Table1</p> <pre><code>ID Name 1 Abe 2 David 3 Orly </code></pre> <p>Table2</p> <pre><code>ID email 1 a@zz.com 1 ab@zz.com 1 abe@zz.com 2 dav@zz.com 2 d@zz.com 3 orly@zz.com 3 o@zz.com </code></pre> <p>I need an output like this:</p> <pre><code>1 Abe a@zz.com, ab@zz.com, abe@zz.com 2 David dav@zz.com, d@zz.com 3 Orly orly@zz.com, o@zz.com </code></pre> <p>I know this won't work, because the inner SELECT is not a single string:</p> <pre><code>SELECT ID, Name, (SELECT email FROM Table2 WHERE Table2.ID = Table1.ID) AS emails FROM Table1 </code></pre> <p>I tried to apply:</p> <pre><code>DECLARE @emails VARCHAR(999) SELECT [ID],[Name], (SELECT @emails = COALESCE(@emails + ', ', '') + [email] FROM Table2) AS 'emails' FROM Table1 </code></pre> <p>but with no luck.</p> <p>How should this be solved?</p> <p>Thanks.</p>
7,959,662
2
3
null
2011-10-31 19:41:31.277 UTC
9
2013-05-28 08:32:28.01 UTC
2011-11-01 06:56:58.217 UTC
null
1,010,730
null
1,010,730
null
1
14
sql|sql-server
39,445
<p>One of the neatest ways to achieve this is to combine For XML Path and STUFF as follows:</p> <pre><code>SELECT ID, Name, Emails = STUFF(( SELECT ', ' + Email FROM Table2 WHERE Table2.ID = Table1.ID FOR XML PATH ('')),1,2,'') FROM Table1 </code></pre>
19,397,873
UIImagePickerController bug
<p>I think I found a bug in latest iOS 7 by running an app with Base SDK set to iOS 6.1 (possibly even lower versions too, haven't tested that out yet)</p> <p>I have this image in my photo library: <a href="https://i.imgur.com/7KUIGLt.jpg" rel="noreferrer">http://i.imgur.com/7KUIGLt.jpg</a></p> <p>I present a UIImagePickerController via:</p> <pre><code>UIImagePickerController *vc = [[UIImagePickerController alloc] init]; vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; vc.delegate = self; vc.allowsEditing = YES; [self presentViewController:vc animated:YES completion:nil]; </code></pre> <p>I save the chosen image to my desktop (I am running this on simulator, but this works on device too)</p> <pre><code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage* outputImage = [info objectForKey:UIImagePickerControllerEditedImage]; if (outputImage == nil) { outputImage = [info objectForKey:UIImagePickerControllerOriginalImage]; } NSData *d = UIImagePNGRepresentation(outputImage); [d writeToFile:@"/Users/Admin/Desktop/test.png" atomically:YES]; [self dismissViewControllerAnimated:YES completion:nil]; } </code></pre> <p>This is the resulting image: <img src="https://i.stack.imgur.com/d3Q9c.png" alt="enter image description here"></p> <p>Notice the big black bar to the right. What's causing this?</p> <p>To reproduce this, you need:</p> <ul> <li>iOS 7</li> <li>App with Base SDK set to 6.1 (maybe even lower SDKs too, i haven't tried yet)</li> <li>iPhone 5/5c/5s</li> <li>Only happens to pictures that were taken with iPhone 5/5c/5s camera (you can use the original image I linked above for testing)</li> </ul> <p><strong>NOTE:</strong> Just to be clear, the black bar is part of the actual image. The image you see there is not a screenshot of a UIImageView, but the actual image saved to disk and uploaded here...</p>
19,479,635
4
9
null
2013-10-16 07:49:48.013 UTC
8
2014-05-18 09:34:18.923 UTC
2013-12-18 08:18:41.53 UTC
null
1,578,927
null
903,643
null
1
25
ios|objective-c|cocoa-touch|ios7|uiimagepickercontroller
7,363
<p>Your question is "What's causing this?" So I'll focus on that instead of giving a workaround. This is definitely a bug in iOS 7 dealing with edited images in lower base SDKs. We can also rule out that XCode 5 &amp; Base SDK 6.1 causing this because I'm getting the same issue with XCode 4.6.3 &amp; 6.1 SDK running on iOS 7 Simulator.</p> <p>The source of the problem is that the CropRect values that are calculated by the SDK are wrong. If you'll print out the <code>info</code> <code>NSDictionary</code> from <code>imagePickerController:didFinishPickingMediaWithInfo</code> you'll see that:</p> <p>iOS 7 running any SDK lower than 7 we'll get: </p> <blockquote> <p>UIImagePickerControllerCropRect = "NSRect: {<strong>{154, 495}</strong>, {1705, 1705}}";</p> </blockquote> <p>While running iOS 6 or 5 with their SDK will give us: </p> <blockquote> <p>UIImagePickerControllerCropRect = "NSRect: {{<strong>0, 149</strong>}, {1704, 1705}}";</p> </blockquote> <p>You're probably saying, hmm, those y values are changing between SDKs too. Well, yea, if you'll slide your pic all the way down and select it you'll also get a black bar at the bottom of the picture. </p> <p><img src="https://i.stack.imgur.com/RuWdD.png" alt="enter image description here"></p> <p><strong>Suggested Solutions:</strong> </p> <ol> <li><p><a href="https://developer.apple.com/bug-reporting/" rel="nofollow noreferrer"><strike>File a bug report to Apple here </strike></a>...Did that! </p></li> <li><p>Don't use <code>UIImagePickerControllerEditedImage</code> and take the original picture instead.</p></li> <li><p>Calculate and do the cropping your self.</p></li> <li><p>Use a 3rd party cropping library such as <a href="https://github.com/kishikawakatsumi/PEPhotoCropEditor" rel="nofollow noreferrer">PEPhotoCropEditor</a> or <a href="https://github.com/ardalahmet/SSPhotoCropperViewController" rel="nofollow noreferrer">SSPhotoCropperViewController</a></p></li> </ol> <hr> <p>Edit - very simple solution added by fan of the answer!</p> <p>Amazingly, it can be this simple and elegant to crop it yourself:</p> <pre><code>{ // There is a bug in iOS. When using ALBUM, you must crop it yourself: fromAlbum = [info objectForKey:UIImagePickerControllerOriginalImage]; fromAlbum = [fromAlbum fixOrientation]; CGRect crop = [[info valueForKey:@"UIImagePickerControllerCropRect"] CGRectValue]; fromAlbum = [self ordinaryCrop:fromAlbum toRect:crop]; } </code></pre> <p>Here's the whole routine ordinaryCrop:toRect:</p> <pre><code>-(UIImage *)ordinaryCrop:(UIImage *)imageToCrop toRect:(CGRect)cropRect { CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], cropRect); UIImage *cropped = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return cropped; } </code></pre> <p>Now as Jesse points out, it is critical to rotate the image properly. This absolutely incredible piece of code by Anomie does the job:</p> <p><a href="https://stackoverflow.com/questions/5427656/ios-uiimagepickercontroller-result-image-orientation-after-upload/5427890#5427890">iOS UIImagePickerController result image orientation after upload</a></p> <p>Fixing UIImage orientation .. UIImage+fixOrientation.h</p> <p>It's that simple, hope it helps someone. Thanks again for the priceless answers here.</p>
8,613,535
Does Java have 'Debug' and 'Release' build mode like C#?
<p>In C#, we have 2 modes to build projects : <code>Debug</code> and <code>Release</code>, I wonder if Java has the same thing. I am using IntelliJ IDEA as Java IDE and so far I haven't seen anywhere to configure a build mode like in VS IDE.</p>
8,613,589
3
3
null
2011-12-23 07:53:35.623 UTC
12
2011-12-25 10:34:44.077 UTC
null
null
null
null
458,773
null
1
47
c#|java|.net|debugging|release
25,638
<pre><code>javac -g Generate all debugging info -g:none Generate no debugging info -g:{lines,vars,source} Generate only some debugging info </code></pre> <p>You can choose to include debug symbols in the compiled classes (this is the default) or to not do so. There is not much benefit to not doing that. The jar files will be <a href="https://stackoverflow.com/questions/218033/is-there-a-performance-difference-between-javac-debug-on-and-off">a little smaller</a>, but the performance benefit is minimal (if any). Without these symbols you no longer get line numbers in stack traces. You also have the option to include <a href="https://stackoverflow.com/questions/5746894/javac-with-debugging-information-option-gvars-output-example">additional symbols with local variable names</a> (by default there are only source file names and line numbers).</p> <pre><code>java -ea[:&lt;packagename&gt;...|:&lt;classname&gt;] -enableassertions[:&lt;packagename&gt;...|:&lt;classname&gt;] enable assertions </code></pre> <p>You can also enable assertions at run-time (default is off), which is sometimes useful during development and testing. This does have a performance impact (if the code in question did indeed make use of assertions, which I think is <a href="https://stackoverflow.com/questions/298909/java-assertions-underused">uncommon</a>).</p> <p>Regardless of any of these settings, the JVM always allows you to attach a debugger.</p> <p>What Java does not have is conditional compilation where completely different code would be compiled based on some external setting. The closest you can get is something like <code>public static final boolean DEBUG_BUILD = true;</code> somewhere in your code and use that in if statements. This will actually make the compiler exclude code that becomes unreachable, but you have to set this constant in the source code.</p>
8,537,516
How to use an user variables in MySQL LIKE clause?
<p>I am trying to setup a few simple SQL scripts to help with some short term DB administration. As such, I'm setting up variables to try to make it easier to reuse these scripts.</p> <p>The problem I'm having is specifically with the LIKE clause.</p> <pre><code>SET @email = 'test@test.com'; SELECT email from `user` WHERE email LIKE '%@email%'; </code></pre> <p>So I want to have it finding results based on the email SET in the variable. The query works if I manually enter the email into the LIKE clause.</p> <p>How can I get the LIKE clause to work with the user variable?</p> <p>UPDATE: @dems's answer works for this simple case, but I'm having trouble with a more complex query.</p> <pre><code>SET @email = 'test@test.com'; SELECT project.projectno, project.projectname, login.username, CONCAT(login.firstname, ' ', login.lastname), projectuser.title FROM projectuser INNER JOIN login ON projectuser.uid = login.uid LEFT JOIN project ON projectuser.pid = project.pid WHERE login.username LIKE CONCAT ('%', @email, '%') </code></pre> <p>Gives me the error "FUNCTION mydb.CONCAT does not exist"</p> <p>The query works without the CONCAT():</p> <pre><code>SET @email = 'test@test.com'; SELECT project.projectno, project.projectname, login.username, CONCAT(login.firstname, ' ', login.lastname), projectuser.title FROM projectuser INNER JOIN login ON projectuser.uid = login.uid LEFT JOIN project ON projectuser.pid = project.pid WHERE login.username LIKE @email </code></pre>
8,537,547
7
4
null
2011-12-16 16:59:26.957 UTC
11
2022-01-30 06:45:24.777 UTC
2011-12-20 17:37:03.467 UTC
null
962,289
null
962,289
null
1
59
mysql|sql|database
93,642
<pre><code>SET @email = 'test@test.com'; SELECT email from `user` WHERE email LIKE CONCAT('%', @email, '%'); </code></pre>
31,098,831
EXC_BAD_ACCESS tapping uisearchbar three times
<p>I am trying to implement a search bar in a UICollectionView as a UICollectionViewReusableView</p> <p>This way I am not using a UISearchController but I am changing the datasource of the collectionview</p> <p>In my custom layout I am adding the searchbar this way:</p> <pre><code>override func prepareLayout() { super.prepareLayout() var searchBarAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: TeacherSearchbarIdentifier, withIndexPath: NSIndexPath(forItem: 0, inSection: 0)) searchBarAttributes.frame = CGRectMake(0, 0, collectionViewContentSize().width, 44) searchBarAttributes.zIndex = 100 miscAttributes.append(searchBarAttributes) } override func layoutAttributesForElementsInRect(rect: CGRect) -&gt; [AnyObject]? { var attributes = [UICollectionViewLayoutAttributes]() for (idx, attr) in enumerate(miscAttributes) { if CGRectIntersection(rect, attr.frame) != CGRectNull { attributes.append(attr) } } return attributes } </code></pre> <p>I am setting the delegate like this:</p> <pre><code>func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -&gt; UICollectionReusableView { var view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kind, forIndexPath: indexPath) as! UICollectionReusableView if kind == TeacherSearchbarIdentifier { controller.searchBar = (view as! TeacherSearchView).searchBar return view } } </code></pre> <p>The variable <code>controller</code> is the UICollectionViewController which implements the <code>UISearchBarDelegate</code> Protocol</p> <p>The delegate is set in didSet of the searchBar variable. These are my delegates:</p> <pre><code>override func scrollViewDidScroll(scrollView: UIScrollView) { self.view.endEditing(true) } func searchBarShouldBeginEditing(searchBar: UISearchBar) -&gt; Bool { searchBar.setShowsCancelButton(true, animated: true) return true } func searchBarShouldEndEditing(searchBar: UISearchBar) -&gt; Bool { searchBar.setShowsCancelButton(false, animated: true) searchBar.resignFirstResponder() return true } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) searchBar.resignFirstResponder() } </code></pre> <p><strong>Now my problem!</strong></p> <p>When I am tapping on the search bar, the keyboard appears. If I press the cancel button or scroll, it dissappears. Just as I want it to. This also works a second time.</p> <p><strong>BUT!</strong></p> <p>If I do this a third time, I get a EXC_BAD_ACCESS:</p> <p><img src="https://i.stack.imgur.com/hKeOP.png" alt="EXC_BAD_ACCESS (code=1, address=0x14ac0beb8)"></p> <p>I tried turning on Enabling Zombie Objects, but no information was provided. I also tried profiling for Zombie Objects, it just crashes without any noticeable information.</p> <p>Please help me on how I can resolve this error, or give me further debugging instructions. </p> <p>EDIT 1:</p> <p>Here is the output from <code>bt all</code> in the lldb debugger:</p> <pre><code> * thread #1: tid = 0x228fc, 0x000000019502fbd0 libobjc.A.dylib`objc_msgSend + 16, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1cda8beb8) frame #0: 0x000000019502fbd0 libobjc.A.dylib`objc_msgSend + 16 frame #1: 0x000000018328b2f4 CoreFoundation`-[__NSDictionaryM objectForKey:] + 84 frame #2: 0x00000001884a21b8 UIKit`-[UICollectionView _visibleViewDictForElementCategory:elementKind:] + 96 frame #3: 0x0000000187ff6644 UIKit`-[UICollectionView _indexPathForView:ofType:] + 160 frame #4: 0x000000018849c3dc UIKit`-[UICollectionView _setIsAncestorOfFirstResponder:] + 792 frame #5: 0x0000000187ed9418 UIKit`+[UIView(Internal) _setIsResponderAncestorOfFirstResponder:startingAtFirstResponder:] + 164 frame #6: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #7: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #8: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #9: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #10: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #11: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #12: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #13: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #14: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #15: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #16: 0x0000000187ed925c UIKit`-[UIResponder(Static) _setFirstResponder:] + 56 frame #17: 0x0000000187f1b194 UIKit`-[UITextField _becomeFirstResponder] + 60 frame #18: 0x000000018800f300 UIKit`-[UISearchBarTextField _becomeFirstResponder] + 108 frame #19: 0x0000000187e9ad28 UIKit`-[UIResponder becomeFirstResponder] + 392 frame #20: 0x0000000187e9b0ac UIKit`-[UIView(Hierarchy) becomeFirstResponder] + 124 frame #21: 0x0000000187f19de4 UIKit`-[UITextField becomeFirstResponder] + 68 frame #22: 0x0000000187fc9fc4 UIKit`-[UITextInteractionAssistant(UITextInteractionAssistant_Internal) setFirstResponderIfNecessary] + 200 frame #23: 0x0000000187fc962c UIKit`-[UITextInteractionAssistant(UITextInteractionAssistant_Internal) oneFingerTap:] + 1736 frame #24: 0x0000000187faf070 UIKit`_UIGestureRecognizerSendActions + 276 frame #25: 0x0000000187e486b4 UIKit`-[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 580 frame #26: 0x00000001882b938c UIKit`___UIGestureRecognizerUpdate_block_invoke662 + 60 frame #27: 0x0000000187e0c418 UIKit`_UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 292 frame #28: 0x0000000187e0a7c4 UIKit`_UIGestureRecognizerUpdate + 2504 frame #29: 0x0000000187e4682c UIKit`-[UIWindow _sendGesturesForEvent:] + 1044 frame #30: 0x0000000187e45ee4 UIKit`-[UIWindow sendEvent:] + 660 frame #31: 0x0000000187e19120 UIKit`-[UIApplication sendEvent:] + 264 frame #32: 0x00000001880ba2b8 UIKit`_UIApplicationHandleEventFromQueueEvent + 15424 frame #33: 0x0000000187e17634 UIKit`_UIApplicationHandleEventQueue + 1716 frame #34: 0x0000000183358240 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24 frame #35: 0x00000001833574e4 CoreFoundation`__CFRunLoopDoSources0 + 264 frame #36: 0x0000000183355594 CoreFoundation`__CFRunLoopRun + 712 frame #37: 0x00000001832812d4 CoreFoundation`CFRunLoopRunSpecific + 396 frame #38: 0x000000018ccdf6fc GraphicsServices`GSEventRunModal + 168 frame #39: 0x0000000187e7ef40 UIKit`UIApplicationMain + 1488 * frame #40: 0x00000001000f0798 My-Project`main + 164 at AppDelegate.swift:14 frame #41: 0x00000001956c6a08 libdyld.dylib`start + 4 thread #2: tid = 0x22939, 0x00000001957c4c24 libsystem_kernel.dylib`kevent64 + 8, queue = 'com.apple.libdispatch-manager' frame #0: 0x00000001957c4c24 libsystem_kernel.dylib`kevent64 + 8 frame #1: 0x000000010083a588 libdispatch.dylib`_dispatch_mgr_invoke + 276 frame #2: 0x000000010082b09c libdispatch.dylib`_dispatch_mgr_thread + 52 thread #8: tid = 0x229d9, 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #0: 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #1: 0x00000001958792dc libsystem_pthread.dylib`_pthread_wqthread + 992 thread #7: tid = 0x229da, 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #0: 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #1: 0x00000001958792dc libsystem_pthread.dylib`_pthread_wqthread + 992 thread #9: tid = 0x229df, 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #0: 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #1: 0x00000001958792dc libsystem_pthread.dylib`_pthread_wqthread + 992 thread #10: tid = 0x229e1, 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #0: 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #1: 0x00000001958792dc libsystem_pthread.dylib`_pthread_wqthread + 992 thread #11: tid = 0x229e2, 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #0: 0x00000001957dfc78 libsystem_kernel.dylib`__workq_kernreturn + 8 frame #1: 0x00000001958792dc libsystem_pthread.dylib`_pthread_wqthread + 992 thread #12: tid = 0x229e3, 0x00000001957c4e0c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.apple.NSURLConnectionLoader' frame #0: 0x00000001957c4e0c libsystem_kernel.dylib`mach_msg_trap + 8 frame #1: 0x00000001957c4c88 libsystem_kernel.dylib`mach_msg + 72 frame #2: 0x0000000183357724 CoreFoundation`__CFRunLoopServiceMachPort + 200 frame #3: 0x0000000183355678 CoreFoundation`__CFRunLoopRun + 940 frame #4: 0x00000001832812d4 CoreFoundation`CFRunLoopRunSpecific + 396 frame #5: 0x0000000182d5e594 CFNetwork`+[NSURLConnection(Loader) _resourceLoadLoop:] + 440 frame #6: 0x00000001842a1db8 Foundation`__NSThread__main__ + 1072 frame #7: 0x000000019587bdc8 libsystem_pthread.dylib`_pthread_body + 164 frame #8: 0x000000019587bd24 libsystem_pthread.dylib`_pthread_start + 160 thread #13: tid = 0x229e6, 0x00000001957df498 libsystem_kernel.dylib`__select + 8, name = 'com.apple.CFSocket.private' frame #0: 0x00000001957df498 libsystem_kernel.dylib`__select + 8 frame #1: 0x000000018335d128 CoreFoundation`__CFSocketManager + 672 frame #2: 0x000000019587bdc8 libsystem_pthread.dylib`_pthread_body + 164 frame #3: 0x000000019587bd24 libsystem_pthread.dylib`_pthread_start + 160 </code></pre> <p>EDIT 2: I created a standalone project which produces this error. Just run the project and tap/cancel the searchbar a few times.</p> <p><a href="http://techprimate.com/CollectionViewResponderCrash.zip" rel="nofollow noreferrer">Download Project</a></p> <p>Video: </p> <p><img src="https://i.stack.imgur.com/fF15V.gif" alt="Short gif showing crash"></p> <p>Bugreport: <a href="http://openradar.appspot.com/21673802" rel="nofollow noreferrer">rdar://problem/21673802</a></p>
36,830,488
2
29
null
2015-06-28 10:37:17.023 UTC
5
2016-04-25 00:32:06.92 UTC
2015-09-30 18:26:14.017 UTC
null
3,515,302
null
3,515,302
null
1
32
ios|swift|exc-bad-access|uiresponder
1,428
<p>I came up with a workaround for this in iOS 8. I discovered that the crash only occurred if the <code>kind</code> string of my supplementary view was a Swift string. There was no crash when I used an Objective-C string bridged to Swift. I tried the obvious idea of creating a <code>NSString</code> explicitly in Swift and even tried creating a <code>CFString</code> in Swift and bridging that. However, neither of those efforts were successful.</p> <p>To easily verify this, try changing <code>TeacherSearchbarIdentifier</code> to an Objective-C string from UIKit like <code>UICollectionElementKindSectionHeader</code>.</p> <p>A more rigorous workaround would involve creating Objective-C strings for your use case and exposing those to Swift. As an example:</p> <pre class="lang-c prettyprint-override"><code>// MyElementKinds.h @import Foundation; FOUNDATION_EXPORT NSString *const TeacherSearchbarIdentifier; </code></pre> <pre class="lang-c prettyprint-override"><code>// MyElementKinds.m #import "MyElementKinds.h" NSString *const TeacherSearchbarIdentifier = @"TeacherSearchbarIdentifier"; </code></pre>
5,169,471
Is there an "after submit" jQuery option?
<p>I have a form that uploads a file and targets an iframe on the page. When the user clicks submit, I want the file contents to "clear" out.</p> <p>I tried this</p> <pre><code>$('#imageaddform').submit(function(){ $('#imagefile').val(''); }); </code></pre> <p>But it clears the form before the submit, so nothing is ever uploaded.</p> <p>Is how do I clear after submit?</p>
5,169,572
4
2
null
2011-03-02 15:12:33.403 UTC
7
2018-09-25 14:32:50.51 UTC
2018-09-25 14:32:50.51 UTC
null
814,702
null
456,782
null
1
48
javascript|jquery|forms|form-submit
87,621
<p>If you have no other handlers bound, you could do something like this:</p> <pre><code>$('#imageaddform').submit(function(e) { e.preventDefault(); // don't submit multiple times this.submit(); // use the native submit method of the form element $('#imagefile').val(''); // blank the input }); </code></pre>
5,483,423
How to write unicode strings into a file?
<p>I am using python 2.6.5 I want to write some japanese characters to a file. I am getting this error &amp; I don't know how to change the encoding.</p> <pre><code>Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) [GCC 4.3.4 20090804 (release) 1] on cygwin &gt;&gt;&gt; s = u'\u5E73\u621015' &gt;&gt;&gt; with open("yop", "wb") as f: ... f.write( s + "\n" ); ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) &gt;&gt;&gt; type( s ) &lt;type 'unicode'&gt; </code></pre>
5,483,534
4
0
null
2011-03-30 07:48:40.393 UTC
21
2015-03-09 03:59:33.033 UTC
null
null
null
null
450,278
null
1
54
python|unicode
77,623
<p>you're going to have to 'encode' the unicode string.</p> <pre><code>s = u'\u5E73\u621015' with open("yop", "wb") as f: f.write(s.encode("UTF-8")) </code></pre> <p>try this out for a bit of a friendly look at unicode and python: <a href="http://farmdev.com/talks/unicode/" rel="noreferrer">http://farmdev.com/talks/unicode/</a></p>
5,453,708
Android how to use Environment.getExternalStorageDirectory()
<p>How can i use <code>Environment.getExternalStorageDirectory()</code> to read a a stored image from the SD card or is there a better way to do it?</p>
5,453,753
4
0
null
2011-03-28 01:06:36.84 UTC
31
2020-06-16 19:36:52.333 UTC
2011-06-08 11:58:30.727 UTC
null
55,093
null
650,269
null
1
58
android|sd-card
184,948
<pre><code>Environment.getExternalStorageDirectory().getAbsolutePath() </code></pre> <p>Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.</p> <p>Here's a simple example for writing a file:</p> <pre><code>String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); String fileName = "myFile.txt"; // Not sure if the / is on the path or not File f = new File(baseDir + File.separator + fileName); f.write(...); f.flush(); f.close(); </code></pre> <p>Edit:</p> <p>Oops - you wanted an example for reading ...</p> <pre><code>String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); String fileName = "myFile.txt"; // Not sure if the / is on the path or not File f = new File(baseDir + File.Separator + fileName); FileInputStream fiStream = new FileInputStream(f); byte[] bytes; // You might not get the whole file, lookup File I/O examples for Java fiStream.read(bytes); fiStream.close(); </code></pre>
4,920,072
keytool -genkey error: Keystore file does not exist
<p>I try to create a new self certified keystore file</p> <p>The command I use is:</p> <pre><code>keytool -genkey -selfcert -dname "cn=My Name, ou=Orga unit" -alias selfcertified -keypass somepass -keystore keystore.jks -storepass anotherpass -validity 365 </code></pre> <p>but I always get this annoying error:</p> <pre><code>keytool error: java.lang.Exception: Keystore file does not exist: keystore.jks </code></pre> <p>I do not understand why I'm getting this error. The command above should create a new keystore, so why is it complaining about a non existing store?</p>
4,920,659
5
0
null
2011-02-07 10:14:19.973 UTC
7
2019-10-21 11:22:10.083 UTC
2016-01-18 12:35:42.113 UTC
null
3,885,376
null
606,235
null
1
16
java|certificate|keystore|keytool
88,673
<p>Generating a key pair (and a new keystore) has to be done as a separate operation to creating a self-signed certificate for that key.</p> <p>i.e.</p> <pre><code>keytool -genkey -alias myKey -keystore store.jks keytool -selfcert -alias myKey -keystore store.jks </code></pre>
5,490,025
C# reflection and finding all references
<p>Given a DLL file, I'd like to be able to find all the calls to a method within that DLL file. How can I do this?</p> <p>Essentially, how can I do programmatically what Visual Studio already does?</p> <p>I don't want to use a tool like <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="noreferrer">.NET Reflector</a> to do this, but reflection is fine and probably necessary.</p>
5,490,526
6
3
null
2011-03-30 17:44:32.23 UTC
20
2022-05-31 13:44:45.867 UTC
2013-09-17 19:12:56.09 UTC
null
63,550
null
420,667
null
1
41
c#|reflection|reference|reflector
35,355
<p>To find out where a method <code>MyClass.Foo()</code> is used, you have to analyse all classes of all assemblies that have a reference to the assembly that contains <code>MyClass</code>. I wrote a simple proof of concept of how this code can look like. In my example I used <a href="http://evain.net/blog/articles/2009/04/30/reflection-based-cil-reader" rel="nofollow noreferrer">this library</a> (it's just <a href="https://web.archive.org/web/20090504094118/http://gist.github.com/104001" rel="nofollow noreferrer">a single .cs file</a>) written by Jb Evain:</p> <p>I wrote a little test class to analyse:</p> <pre><code>public class TestClass { public void Test() { Console.WriteLine(&quot;Test&quot;); Console.Write(10); DateTime date = DateTime.Now; Console.WriteLine(date); } } </code></pre> <p>And I wrote this code to print out all the methods used within <code>TestClass.Test()</code>:</p> <pre><code>MethodBase methodBase = typeof(TestClass).GetMethod(&quot;Test&quot;); var instructions = MethodBodyReader.GetInstructions(methodBase); foreach (Instruction instruction in instructions) { MethodInfo methodInfo = instruction.Operand as MethodInfo; if(methodInfo != null) { Type type = methodInfo.DeclaringType; ParameterInfo[] parameters = methodInfo.GetParameters(); Console.WriteLine(&quot;{0}.{1}({2});&quot;, type.FullName, methodInfo.Name, String.Join(&quot;, &quot;, parameters.Select(p =&gt; p.ParameterType.FullName + &quot; &quot; + p.Name).ToArray()) ); } } </code></pre> <p>It gave me the following output:</p> <pre><code>System.Console.WriteLine(System.String value); System.Console.Write(System.Int32 value); System.DateTime.get_Now(); System.Console.WriteLine(System.Object value); </code></pre> <p>This example is obviously far from complete, because it doesn't handle ref and out parameters, and it doesn't handle generic arguments. I am sure that forgot about other details as well. It just shows that it can be done.</p>
4,897,149
How to convert Session Variable to Integer Type in C#
<p>I am using C#</p> <p>I am trying to check whether my login attempt is not more than 3, I mean with the below condition:</p> <pre><code>if (((int)Session["LoginAttempt"]) != 3) { } </code></pre> <p>In Login failed condition I am doing increment like below:</p> <pre><code>Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1; </code></pre> <p>But it is giving me this error: <strong>"Object reference not set to an instance of an object."</strong></p> <p>Suggestions please!</p>
4,897,343
8
0
null
2011-02-04 10:51:58.747 UTC
2
2019-10-09 14:15:17.977 UTC
2019-10-09 14:15:17.977 UTC
null
436,341
null
30,394
null
1
13
c#
63,784
<p>Sorry Guys,</p> <p>I just changed the integer converting code from</p> <pre><code>((int) Session["LoginAttempt"]) </code></pre> <p>to</p> <pre><code>Convert.ToInt32(Session["LoginAttempt"]) + 1; </code></pre> <p>and now it is working fine for me, please suggest incase of any issues in it.</p> <p>Thanks!</p>