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,789,627
How to change the timeout on a .NET WebClient object
<p>I am trying to download a client's data to my local machine (programatically) and their webserver is very, very slow which is causing a timeout in my <code>WebClient</code> object.</p> <p>Here is my code:</p> <pre><code>WebClient webClient = new WebClient(); webClient.Encoding = Encoding.UTF8; webClient.DownloadFile(downloadUrl, downloadFile); </code></pre> <p>Is there a way to set an infinite timeout on this object? Or if not can anyone help me with an example on an alternate way to do this?</p> <p>The URL works fine in a browser - it just takes about 3 minutes to show.</p>
6,994,391
12
1
null
2009-11-24 11:59:58.95 UTC
34
2021-12-13 12:40:00.7 UTC
null
null
null
null
147,731
null
1
252
c#|.net|file|download|webclient
214,548
<p>You can extend the timeout: inherit the original WebClient class and override the webrequest getter to set your own timeout, like in the following example.</p> <p>MyWebClient was a private class in my case:</p> <pre><code>private class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri uri) { WebRequest w = base.GetWebRequest(uri); w.Timeout = 20 * 60 * 1000; return w; } } </code></pre>
2,214,575
Passing arguments to "make run"
<p>I use Makefiles.</p> <p>I have a target called <code>run</code> which runs the build target. Simplified, it looks like the following:</p> <pre><code>prog: .... ... run: prog ./prog </code></pre> <p>Is there any way to pass arguments? So that</p> <pre><code>make run asdf --&gt; ./prog asdf make run the dog kicked the cat --&gt; ./prog the dog kicked the cat </code></pre>
2,214,593
14
1
null
2010-02-06 20:16:13.343 UTC
106
2022-09-01 16:55:07.407 UTC
2021-11-18 20:24:15.303 UTC
null
832,230
null
247,265
null
1
469
makefile
344,658
<p>I don't know a way to do what you want exactly, but a workaround might be:</p> <pre><code>run: ./prog ./prog $(ARGS) </code></pre> <p>Then:</p> <pre><code>make ARGS="asdf" run # or make run ARGS="asdf" </code></pre>
1,408,417
Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?
<p>I know that PHP is compiled to byte code before it is run on the server, and then that byte code can be cached so that the whole script doesn't have to be re-interpreted with every web access.</p> <p>But can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?</p>
1,408,499
14
5
null
2009-09-11 00:23:28.577 UTC
99
2021-06-03 14:51:36.03 UTC
2019-07-15 03:02:58.94 UTC
null
63,550
null
84,478
null
1
239
php|bytecode
257,145
<p>After this question was asked, Facebook launched <strong>HipHop for PHP</strong> which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.</p> <p>Beyond that, googling <code>PHP compiler</code> turns up a number of 3rd party solutions.</p> <p><a href="https://www.peachpie.io/" rel="noreferrer">PeachPie</a></p> <ul> <li><a href="https://github.com/peachpiecompiler/peachpie" rel="noreferrer">PeachPie GitHub</a></li> <li>compiles PHP to .NET and .NET Core</li> <li>can be compiled into self-contained binary file</li> <li>runs on Mac, Linux, Windows, Windows Core, ARM, ...</li> </ul> <p><a href="http://v4.php-compiler.net/" rel="noreferrer">Phalanger</a></p> <ul> <li><a href="https://github.com/devsense/phalanger/" rel="noreferrer">GitHub</a> (download), <a href="http://en.wikipedia.org/wiki/Phalanger_%28compiler%29" rel="noreferrer">Wikipedia</a></li> <li>compiles to .NET (CIL) looks discontinued from July 2017 and doesn't seem to support PHP 7. </li> </ul> <p><a href="https://github.com/pbiggar/phc" rel="noreferrer">phc</a></p> <ul> <li>compiles to native binaries</li> <li>not very active now (February 2014) – last version in 2011, last change in summer 2013</li> </ul> <p><a href="http://www.roadsend.com/" rel="noreferrer">Roadsend PHP Compiler</a></p> <ul> <li><a href="https://github.com/weyrick/roadsend-php" rel="noreferrer">GitHub</a>, <a href="https://github.com/weyrick/roadsend-php-raven" rel="noreferrer">GitHub of a rewrite</a></li> <li>free, open source implementation of PHP with compiler</li> <li>compiles to native binaries (Windows, Linux)</li> <li><a href="http://roadsend-php.blogspot.cz/2010/08/current-status.html" rel="noreferrer">discontinued since 2010 till contributors found</a> – website down, stays on GitHub where last change is from early 2012</li> </ul> <p><a href="http://www.php.net/manual/en/book.bcompiler.php" rel="noreferrer">bcompiler</a></p> <ul> <li>PECL extension of PHP</li> <li>experimental</li> <li>compiles to PHP bytecode, but can wrap it in Windows binary that loads PHP interpreter (see <a href="http://www.php.net/manual/en/function.bcompiler-write-exe-footer.php" rel="noreferrer"><code>bcompiler_write_exe_footer()</code> manual</a>)</li> <li>looks discontinued now (February 2014) – last change in 2011</li> </ul> <p><a href="http://www.projectzero.org/" rel="noreferrer">Project Zero</a></p> <ul> <li><a href="http://en.wikipedia.org/wiki/Project_Zero" rel="noreferrer">Wikipedia</a>, <a href="http://www.ibm.com/developerworks/ibm/zero/" rel="noreferrer">IBM</a></li> <li>incubator of changes for <a href="https://www.ibm.com/developerworks/websphere/zones/smash/" rel="noreferrer">WebSphere sMash</a></li> <li>supported by IBM</li> <li>compiles to Java bytecode</li> <li>looks discontinued now (February 2014) – website down, looks like big hype in 2008 and 2009</li> </ul> <p><a href="http://www.bambalam.se/bamcompile/" rel="noreferrer">Bambalam</a></p> <ul> <li>compiles to stand-alone Windows binaries</li> <li>the binaries contain bytecode and a launcher</li> <li>looks discontinued now (February 2014) – last change in 2006</li> </ul> <p><a href="http://sourceforge.net/projects/binaryphp/" rel="noreferrer">BinaryPHP</a></p> <ul> <li>compiles to C++</li> <li>looks discontinued now (February 2014) – last change in 2003</li> </ul>
8,517,304
What is the difference for sample/resample/scale/resize/adaptive-resize/thumbnail operators in ImageMagick convert?
<p>I found multiple ways to change the resolution of an image using <code>convert</code>:</p> <pre><code>-sample -resample -scale -resize -adaptive-resize -thumbnail </code></pre> <p>What's the difference of those?</p> <p>If I need to make various size large picture thumbnail with fixed aspect ratio (cropping needed) -- what's my best choice?</p>
13,078,621
1
2
null
2011-12-15 08:43:57.393 UTC
44
2021-08-23 03:10:58.08 UTC
2015-07-15 20:20:59.15 UTC
null
359,307
null
41,948
null
1
94
imagemagick|thumbnails
34,619
<p><strong>resize</strong></p> <blockquote> <p><strong><code>-resize 400x300+20+30</code></strong> (like the <code>-scale</code> and <code>-sample</code> examples below) converts an input to an output image which has the pixel dimensions of <code>400x300</code>. It also shifts the output by 20 pixels to the right and by 30 pixels to the bottom. Additionally, there are a few more differences to <code>-scale</code>:</p> </blockquote> <ul> <li><p><code>-resize</code> does support an additional setting of <code>-filter</code> (which should occur on the commandline <em>before</em> using <code>-resize</code>!).</p> </li> <li><p><code>-filter</code> determines the exact algorithm to be used for the colors of added pixels in the case of magnification, or for the colors to be used for the remaining pixels when some of their neighbors are removed in case of minification.</p> </li> <li><p>For a list of supported filters, simply run <code>convert -list filter</code>.</p> </li> <li><p><code>-filter point -resize 400x300</code> creates exactly the same result as <code>-sample 400x300</code> does, but it runs still a bit slower.</p> </li> <li><p>If not set alongside (before) <code>-resize</code>, the conversion will silently default to <code>-filter Lanczos</code> which is slower, but which generates a much better quality (because it takes into account the colors of all surrounding pixels for any newly added ones) than <code>-filter point</code> produces (which uses the <em>nearest neighbor</em> rule to determine the color of a newly added pixels).</p> </li> </ul> <p><strong>sample</strong></p> <blockquote> <p><strong><code>-sample 400x300</code></strong> converts an input image to an output images which has the pixel dimensions of <code>400x300</code>. However, there are a few very important differences to <code>-resize</code>:</p> </blockquote> <ul> <li><p><code>-sample</code> does not support the additional setting of <code>-filter</code>; if set anyway, then <code>-filter</code> is simply ignored.</p> </li> <li><p>When magnifying (because the input image size may be smaller than <code>400x300</code>), pixels are replicated in blocks.</p> </li> <li><p>When minifying (because the input image size may be larger than <code>400x300</code>), pixels are sub-sampled with a very simple algorithm: some rows and columns are simply skipped over.</p> </li> <li><p>The <em>geometry</em> argument to <code>-sample</code> doesn't support any <em>offset</em> part (unlike <code>-resize</code>, which respects <em>offset</em> directives for the output).</p> </li> <li><p>The output will never have more (different) colors than the input image had; it may have fewer colors though.</p> </li> <li><p>Therefore <code>-sample</code> is very fast (faster than <code>-resize</code>) -- but output quality is (usually) worse: you can easily get extreme <a href="http://www.imagemagick.org/Usage/filter/#blocking" rel="noreferrer">blocking</a> and <a href="http://www.imagemagick.org/Usage/filter/#aliasing" rel="noreferrer">aliasing</a> effects in the resulting output.</p> </li> <li><p>One important feature of <code>-sample</code> is that the new image will not contain any new colors, though some colors from the original image may disappear.</p> </li> </ul> <p><strong>resample</strong></p> <blockquote> <p><strong><code>-resample</code></strong> uses as parameter the desired <code>XxY</code> <em><strong>resolution</strong></em>, not not the <code>XxY</code> pixel <em><strong>geometry</strong></em> of the target image. The purpose of this operator is to preserve the <em>rendered</em> size of an image: Assume your image measures 4 inches by 3 inches on a device that renders it at 300 DPI. Then asking for a <code>-resample 72</code> or <code>-resample 72x72</code> will resize the image so that it measures (again) 4 inches by 3 inches on a 72 DPI device.</p> </blockquote> <ul> <li><p>This operation works only for such images which already have a desired resolution stored in their metadata (not all image formats do support the concept of an image resolution -- JPEG, PNG and TIFF do).</p> </li> <li><p>If the source image is in a format where internal support for an image resolution is missing, then the (assumed) original resolution of the image must be specified via <code>-density</code> on the command line <em>prior</em> to specifying the <code>-resample</code> resolution.</p> </li> </ul> <p><strong>scale</strong></p> <blockquote> <p><strong><code>-scale 400x300</code></strong> produces the equivalent result (but is faster, because it avoids all the filter processing) as does using <code>-filter box -resize 400x300</code>. It also completely ignores any current <code>-filter</code> setting.</p> </blockquote> <ul> <li><p>When minifying, it changes the image size simply by replacing pixel colors by averaging the respective input pixel colors together.</p> </li> <li><p>When magnifying, it simply replicates the respective input pixels for the required additional pixels.</p> </li> </ul> <p><strong>adaptive-resize</strong></p> <blockquote> <p><strong><code>-adaptive-resize 400x300</code></strong> does not support (or does ignore, if set) the <em>offset</em> part of a <em>geometry</em> parameter and also ignores the <code>-gravity</code> setting if present.</p> </blockquote> <ul> <li>It uses by default <a href="http://web.archive.org/web/20170813055734/http://www.cs.bath.ac.uk/%7Epjw/Q3D/forum-ddt.pdf" rel="noreferrer"><em>data-dependent triangulation</em></a> when resizing (unless the resize method is overridden by additionally specifying <code>-filter [something]</code>).</li> </ul> <p><strong>thumbnail</strong></p> <blockquote> <p><strong><code>-thumbnail</code></strong> works just like <code>-resize</code> does, with a few differences:</p> </blockquote> <ul> <li><p>It is optimized for speed.</p> </li> <li><p>It also removes any embedded color profiles to reduce the filesize of the thumbnails.</p> </li> </ul> <hr /> <p>The following answer shows a few (illustrated!) examples of the <code>-resize</code> directive. Each illustration shows a different result, depending on the 'fine details' of the exact resize method:</p> <ul> <li><a href="https://stackoverflow.com/a/11721339/359307"><strong>ImageMagick crop command not giving perfect result</strong></a></li> </ul>
6,478,364
How do you set percentage in Google Visualization Chart API?
<p>How do you set the vertical axis to display percent such as 25%, 50%, 75%, 100%?</p>
6,486,856
3
0
null
2011-06-25 14:27:27.85 UTC
2
2021-05-31 16:50:07.91 UTC
2019-02-27 15:39:30.313 UTC
null
759,866
null
336,920
null
1
23
api|charts|google-visualization|number-formatting
43,926
<p><pre><code>chart.draw(data, {vAxis: {format:'#%'} } ); </pre></code></p> <p>To get comma for thousands, use <code>{format:'#,###%'}</code>.</p> <p>See <a href="http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html" rel="noreferrer">http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html</a></p>
6,476,763
Rails 3 route appends _index to route name
<p>I am migrating a Rails 2.3.8 version to Rails 3.0 and so ive rewritten my routes file. When i list the routes using <code>rake routes</code>, i see some route names have <code>_index</code> appended to them. I cant figure out why this is.</p> <p>Relevant routes:</p> <p>Rails 2.3.8:</p> <pre><code>map.namespace "tracker", :path_prefix =&gt; "" do |planner| planner.resources :planner, :collection =&gt; {:step1 =&gt; :get, :add =&gt; :get, :unsubscribe =&gt; [:get, :post] } end </code></pre> <p>Rails 3.0 route:</p> <pre><code>namespace "tracker", :path =&gt; "" do resources :planner do collection do get :step1 get :add get :unsubscribe post :unsubscribe end end end </code></pre> <p>Output from <code>rake routes</code></p> <p>Rails 2.3.8</p> <pre><code>step1_tracker_planner GET /planner/step1(.:format) add_tracker_planner GET /planner/add(.:format) unsubscribe_tracker_planner GET /planner/unsubscribe(.:format) POST /planner/unsubscribe(.:format) </code></pre> <p>Rails 3.0</p> <pre><code>step1_tracker_planner_index GET /planner/step1(.:format) add_tracker_planner_index GET /planner/add(.:format) unsubscribe_tracker_planner_index GET /planner/unsubscribe(.:format) POST /planner/unsubscribe(.:format) </code></pre> <p>Any ideas as to why this <code>_index</code> is being added would be much appreciated.</p>
6,477,540
3
0
null
2011-06-25 08:38:36.053 UTC
4
2015-11-13 00:58:06.573 UTC
2011-06-25 09:06:32.967 UTC
null
285,614
null
285,614
null
1
34
ruby-on-rails|ruby-on-rails-3|routes
6,832
<p>It is because your resource is named <code>:planner</code> instead of <code>:planners</code> that Rails decided to add the _index to any collection nested underneath. My guess it is there for readability.</p> <p>The action named in the collection normally translates to a verb, so I can see why this makes sense. Take the typical photos resource example given in the routing docs:</p> <pre><code>resources :photos do collection do get 'search' end end search_photos GET /photos/search(.:format) </code></pre> <p>But if instead we called the resources 'photo'...</p> <pre><code>resources :photo do collection do get 'search' end end search_photo_index GET /photo/search(.:format) </code></pre> <p>In the first case, you search the "photos", and in the second case you search the "photo index".</p>
15,596,020
Permission denied when opening localhost
<p>I had recently installed Apache, PHP and MySQL in Ubuntu. And copied the files I created to the <code>var/www</code> directory. But when I open <code>http://localhost</code> it is showing</p> <blockquote> <p>Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0</p> <p>Fatal error: Unknown: Failed opening required '/var/www/index.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0</p> </blockquote> <p>How can I run my project normally? It was working fine in windows.</p>
15,596,084
2
5
null
2013-03-24 07:04:35.987 UTC
1
2013-03-30 04:15:58.303 UTC
2013-03-30 04:15:58.303 UTC
null
13,295
null
2,140,143
null
1
9
php|ubuntu|permissions|localhost
41,439
<p>According to this article, you need to give read/execute permissions to Owner, Group, and Everyone.</p> <p>Set permissions on the problem file to 777. Note, you should avoid doing this on a server that's accessible from the internet. </p> <p><a href="http://webomania.wordpress.com/2007/03/12/permission-denied-in-unknown-on-line-0/">http://webomania.wordpress.com/2007/03/12/permission-denied-in-unknown-on-line-0/</a></p>
18,803,354
ending "+" prompt in R
<p>I'm fairly new to R and I made a type-o while entering some code and now instead of getting the ">" prompt I get a "+" prompt. I appear to be stuck in some kind of function that is looking for input, but I can't seem to get out of it. I figure that there must be a better way to fix this problem then closing R and rerunning my script but I haven't been able to find anything on google (likely because I don't know the right search terms). </p> <p>Thanks for your help, sorry it's a trivial question</p> <p>The code I entered was as follows: </p> <pre><code>&gt; fit = lm(x~`y) + fit = lm(x~y) + fit + summary(fit) + + + end + ; + break + ) + + + + 
 
 + 
 + quit() + + quit + break() + abline(b0hat,b1hat) + return(null) + </code></pre>
18,803,911
5
2
null
2013-09-14 15:31:20.197 UTC
9
2022-09-17 09:49:18.437 UTC
2013-10-02 01:36:21.12 UTC
null
636,656
null
2,779,461
null
1
74
r|r-faq
106,627
<p>It depends on how you’re running R.</p> <p>In the terminal, the “normal” way is <kbd>Control</kbd>+<kbd>C</kbd> – the “cancel” key combination.</p> <p>In the graphical R application and in RStudio, it’s <kbd>Escape</kbd>.</p>
19,042,894
Periodic iOS background location updates
<p>I'm writing an application that requires background location updates with <strong>high accuracy and low frequency</strong>. The solution seems to be a background NSTimer task that starts the location manager's updates, which then immediately shuts down. This question has been asked before:</p> <p><a href="https://stackoverflow.com/questions/6347503/how-do-i-get-a-background-location-update-every-n-minutes-in-my-ios-application">How do I get a background location update every n minutes in my iOS application?</a></p> <p><a href="https://stackoverflow.com/questions/10235203/getting-user-location-every-n-minutes-after-app-goes-to-background?rq=1">Getting user location every n minutes after app goes to background</a></p> <p><a href="https://stackoverflow.com/questions/13377750/ios-not-the-typical-background-location-tracking-timer-issue">iOS Not the typical background location tracking timer issue</a></p> <p><a href="https://stackoverflow.com/questions/15650139/ios-long-running-background-timer-with-location-background-mode">iOS long-running background timer with &quot;location&quot; background mode</a></p> <p><a href="https://stackoverflow.com/questions/10706265/ios-full-time-background-service-based-on-location-tracking">iOS full-time background-service based on location tracking</a></p> <p>but I have yet to get a <strong>minimum example</strong> working. After trying every permutation of the above accepted answers, I put together a starting point. Entering background:</p> <pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application { self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ NSLog(@"ending background task"); [[UIApplication sharedApplication] endBackgroundTask:self.bgTask]; self.bgTask = UIBackgroundTaskInvalid; }]; self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES]; } </code></pre> <p>and the delegate method:</p> <pre><code>- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"%@", newLocation); NSLog(@"background time: %f", [UIApplication sharedApplication].backgroundTimeRemaining); [self.locationManager stopUpdatingLocation]; } </code></pre> <p>The current behavior is that the <code>backgroundTimeRemaining</code> decrements from 180 seconds to zero (while logging location), and then the expiration handler executes and no further location updates are generated. How do I modify the above code in order to receive <strong>periodic location updates in the background indefinitely</strong>?</p> <p><strong>Update</strong>: I'm targeting iOS 7 and there appears to be some evidence that background tasks behave differently:</p> <p><a href="https://stackoverflow.com/questions/18901583/start-location-manager-in-ios-7-from-background-task">Start Location Manager in iOS 7 from background task</a></p>
19,085,518
9
3
null
2013-09-27 04:44:30.337 UTC
91
2019-08-24 22:23:37.353 UTC
2018-09-10 21:38:07.02 UTC
null
5,175,709
null
1,601,957
null
1
93
ios|objective-c|core-location|background-task|ios-background-mode
97,398
<p>It seems that <code>stopUpdatingLocation</code> is what triggers the background watchdog timer, so I replaced it in <code>didUpdateLocation</code> with:</p> <pre><code>[self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers]; [self.locationManager setDistanceFilter:99999]; </code></pre> <p>which appears to effectively power down the GPS. The selector for the background <code>NSTimer</code> then becomes:</p> <pre><code>- (void) changeAccuracy { [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; [self.locationManager setDistanceFilter:kCLDistanceFilterNone]; } </code></pre> <p>All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the <code>locationManager</code> hasn't been stopped, <code>backgroundTimeRemaining</code> stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant <code>kCLLocationAccuracyBest</code> in the background) to ~2% per hour on my device.</p>
40,050,397
Deep-Learning Nan loss reasons
<p>Perhaps too general a question, but can anyone explain what would cause a Convolutional Neural Network to diverge?</p> <p>Specifics:</p> <p>I am using Tensorflow's iris_training model with some of my own data and keep getting</p> <blockquote> <p>ERROR:tensorflow:Model diverged with loss = NaN.</p> <p>Traceback...</p> <p>tensorflow.contrib.learn.python.learn.monitors.NanLossDuringTrainingError: NaN loss during training.</p> </blockquote> <p>Traceback originated with line:</p> <pre><code> tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[300, 300, 300], #optimizer=tf.train.ProximalAdagradOptimizer(learning_rate=0.001, l1_regularization_strength=0.00001), n_classes=11, model_dir=&quot;/tmp/iris_model&quot;) </code></pre> <p>I've tried adjusting the optimizer, using a zero for learning rate, and using no optimizer. Any insights into network layers, data size, etc is appreciated.</p>
40,434,284
13
4
null
2016-10-14 19:07:18.273 UTC
57
2022-06-12 13:08:30.77 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
5,031,496
null
1
134
python|tensorflow|machine-learning|keras|theano
188,819
<p>There are lots of things I have seen make a model diverge.</p> <ol> <li><p>Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity. </p></li> <li><p>I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue.</p></li> <li><p>Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier.</p></li> <li><p>You may have an issue with the input data. Try calling <code>assert not np.any(np.isnan(x))</code> on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255].</p></li> <li><p>The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below).</p></li> </ol>
5,283,090
Clean solution (project) structure with EF, Repositories, Entities
<p>I like to keep the structure of the project as clean as possible. Sample:</p> <pre><code>--BlogApp.sln --BlogApp.Data BlogModel.edmx (the EF mappings) Post.cs (I end up having partial classes in here with attributes) --BlogApp.Domain --Entities Post.cs (I would like to have my POCOs here with all its additional logic) --Repositories PostsRepository.cs --BlogApp.Ui (standard MVC structure) </code></pre> <p>I end up with mess when using EF as my ORM. Could anybody suggest some "clean" way to structure the project? Or maybe you could suggest some standard project structure that is most commonly used.</p>
5,283,973
2
4
null
2011-03-12 14:29:26.347 UTC
9
2011-03-12 16:59:55.19 UTC
2011-03-12 15:44:31.367 UTC
null
67,392
null
420,555
null
1
10
asp.net-mvc|entity-framework|projects-and-solutions|project-structure
10,426
<p>My preferred structure is:</p> <blockquote> <pre><code>Solution -- Common - Shared features used accross all layers - You can also place interfaces for repositories and uow here -- Entities - shared among DataAccess, Business (and UI in small projects) - T4 template + partial classes + custom enums - partial classes can contain methods with domain logic =&gt; domain objects -- DataAccess - all EF dependent code here - EDMX or code first mapping - Repositories - UnitOfWork -- Business - not every project needs this assembly - Business services - Logic like workflows - DTOs exposed to UI -- UI - Controllers - Views - ViewModels </code></pre> </blockquote>
5,223,763
How to FTP in Ruby without first saving the text file
<p>Since Heroku does not allow saving dynamic files to disk, I've run into a dilemma that I am hoping you can help me overcome. I have a text file that I can create in RAM. The problem is that I cannot find a gem or function that would allow me to stream the file to another FTP server. The Net/FTP gem I am using requires that I save the file to disk first. Any suggestions?</p> <pre><code>ftp = Net::FTP.new(domain) ftp.passive = true ftp.login(username, password) ftp.chdir(path_on_server) ftp.puttextfile(path_to_web_file) ftp.close </code></pre> <p>The ftp.puttextfile function is what is requiring a physical file to exist.</p>
7,589,083
2
0
null
2011-03-07 18:47:42.85 UTC
9
2015-03-29 00:09:23.143 UTC
2011-03-07 20:23:16.153 UTC
null
405,017
null
307,308
null
1
12
ruby|ftp|heroku
7,661
<p><a href="http://ruby-doc.org/stdlib/libdoc/stringio/rdoc/classes/StringIO.html#M003790" rel="noreferrer">StringIO.new</a> provides an object that acts like an opened file. It's easy to create a method like <a href="http://ruby-doc.org/stdlib/libdoc/net/ftp/rdoc/classes/Net/FTP.html#M001277" rel="noreferrer">puttextfile</a>, by using StringIO object instead of file.</p> <pre><code>require 'net/ftp' require 'stringio' class Net::FTP def puttextcontent(content, remotefile, &amp;block) f = StringIO.new(content) begin storlines("STOR " + remotefile, f, &amp;block) ensure f.close end end end file_content = &lt;&lt;filecontent &lt;html&gt; &lt;head&gt;&lt;title&gt;Hello!&lt;/title&gt;&lt;/head&gt; &lt;body&gt;Hello.&lt;/body&gt; &lt;/html&gt; filecontent ftp = Net::FTP.new(domain) ftp.passive = true ftp.login(username, password) ftp.chdir(path_on_server) ftp.puttextcontent(file_content, path_to_web_file) ftp.close </code></pre>
5,237,611
itertools.cycle().next()?
<p>Well, I was using <code>itertools.cycle().next()</code> method with Python 2.6.6, but now that I updated to 3.2 I noticed that <code>itertools.cycle()</code> object has no method <code>next()</code>.</p> <p>I used it to cycle a string in the <code>spin()</code>method of a <code>Spinner</code> class. So if we cycle the tuple <code>('|', '/', '-', '\\', '|', '/', '-')</code>, it'll print: <code>|</code>, <code>/</code>, <code>-</code>, <code>\</code> , <code>|</code>, <code>/</code>, <code>-</code>, <code>|</code>, <code>/</code> and so on...</p> <p>I've searched the release notes of Python 3.0, 3.1 and 3.2 and didn't noticed any change on this. When this have changed? Is there any simple alternative to achieve the same functionality as before?</p> <p>Thank you in advance.</p>
5,237,664
2
1
null
2011-03-08 20:00:50.64 UTC
6
2014-05-19 07:26:54.247 UTC
null
null
null
null
222,758
null
1
48
python-3.x|cycle|next|itertools
31,708
<p><code>iter.next()</code> was removed in python 3. Use <code>next(iter)</code> instead. So in your example change <code>itertools.cycle().next()</code> to <code>next(itertools.cycle())</code></p> <p>There is a <a href="http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#next" rel="noreferrer">good example here</a> along with various other porting to python 3 tips. It also compares various other <code>next()</code> idioms in python 2.x vs python 3.x</p>
369,438
Smooth spectrum for Mandelbrot Set rendering
<p>I'm currently writing a program to generate really enormous (65536x65536 pixels and above) Mandelbrot images, and I'd like to devise a spectrum and coloring scheme that does them justice. The <a href="http://en.wikipedia.org/wiki/File:Mandel_zoom_00_mandelbrot_set.jpg" rel="noreferrer">wikipedia featured mandelbrot image</a> seems like an excellent example, especially how the palette remains varied at all zoom levels of the sequence. I'm not sure if it's rotating the palette or doing some other trick to achieve this, though.</p> <p>I'm familiar with the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring" rel="noreferrer">smooth coloring algorithm</a> for the mandelbrot set, so I can avoid banding, but I still need a way to assign colors to output values from this algorithm.</p> <p>The images I'm generating are pyramidal (eg, a series of images, each of which has half the dimensions of the previous one), so I can use a rotating palette of some sort, as long as the change in the palette between subsequent zoom levels isn't too obvious.</p>
374,216
7
0
null
2008-12-15 19:26:33.75 UTC
24
2019-04-04 17:42:56.41 UTC
null
null
null
Arachnid
12,030
null
1
37
algorithm|colors|fractals|mandelbrot
35,887
<p>My eventual solution was to create a nice looking (and fairly large) palette and store it as a constant array in the source, then interpolate between indexes in it using the smooth coloring algorithm. The palette wraps (and is designed to be continuous), but this doesn't appear to matter much.</p>
870,173
Is there a limit on number of open files in Windows
<p>I'm opening lots of files with fopen() in VC++ but after a while it fails.</p> <p>Is there a limit to the number of files you can open simultaneously?</p>
870,224
7
3
null
2009-05-15 18:31:08.3 UTC
9
2017-10-25 09:14:32.393 UTC
null
null
null
null
73,869
null
1
44
c++|windows
76,882
<p>The C run-time libraries have a 512 limit for the number of files that can be open at any one time. Attempting to open more than the maximum number of file descriptors or file streams causes program failure. Use <code>_setmaxstdio</code> to change this number. More information about this can be read <a href="http://msdn.microsoft.com/en-us/library/kdfaxaay(vs.71).aspx" rel="noreferrer">here</a></p> <p>Also you may have to check if your version of windows supports the upper limit you are trying to set with <code>_setmaxstdio</code>. For more information on <code>_setmaxstdio</code> check <a href="http://msdn.microsoft.com/en-us/library/6e3b887c(vs.71).aspx" rel="noreferrer">here</a></p> <p>Information on the subject corresponding to VS 2015 can be found <a href="https://msdn.microsoft.com/en-us/library/kdfaxaay(v=vs.140).aspx" rel="noreferrer">here</a></p>
1,218,034
HTML anchor link with no scroll or jump
<p>I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.</p> <p>Simulated sample code:</p> <pre><code>&lt;a href="#button1" id="button1"&gt;button 1&lt;/a&gt; &lt;a href="#button2" id="button2"&gt;button 2&lt;/a&gt; &lt;a href="#" id="reset"&gt;Home&lt;/a&gt; </code></pre> <p>So if you were to click on the "button 1" link, the url could be <a href="http://example.com/foo.php#button1" rel="noreferrer">http://example.com/foo.php#button1</a></p> <p>Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.</p>
1,218,038
8
4
null
2009-08-02 02:40:28.457 UTC
9
2021-04-13 20:54:13.023 UTC
null
null
null
null
49,411
null
1
29
javascript|html|xhtml|scroll|anchor
52,544
<p>I'm probably missing something, but why not just give them different IDs?</p> <pre><code>&lt;a href="#button1" id="button-1"&gt;button 1&lt;/a&gt; &lt;a href="#button2" id="button-2"&gt;button 2&lt;/a&gt; &lt;a href="#" id="reset"&gt;Home&lt;/a&gt; </code></pre> <p>Or whatever convention you'd prefer.</p>
226,693
Python Disk-Based Dictionary
<p>I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a <code>dict</code> which will page parts of itself out to disk when it runs out of room? Obviously it will be slower than an in-memory dict, and it will probably end up eating my hard drive space, but this could apply to other problems that are not so futile.</p> <p>I realized that a disk-based dictionary is pretty much a database, so I manually implemented one using sqlite3, but I didn't do it in any smart way and had it look up every element in the DB one at a time... it was about 300x slower.</p> <p>Is the smartest way to just create my own set of dicts, keeping only one in memory at a time, and paging them out in some efficient manner?</p>
226,796
8
0
null
2008-10-22 17:00:11.053 UTC
18
2022-01-01 08:43:05.11 UTC
null
null
null
Claudiu
15,055
null
1
44
python|database|dictionary|disk-based
18,085
<p>Hash-on-disk is generally addressed with Berkeley DB or something similar - several options are listed in the <a href="http://docs.python.org/library/persistence.html" rel="noreferrer">Python Data Persistence documentation</a>. You can front it with an in-memory cache, but I'd test against native performance first; with operating system caching in place it might come out about the same.</p>
510,216
Can you make the settings in Settings.bundle default even if you don't open the Settings App
<p>I have an iPhone application with a settings.bundle that handles various settings for my application. I can set default values in my root.plist file (using the DefaultValue property), but these only get used the first time the user opens the settings app. Is there any way to get these values written out when your application installs? I know I can just write code that checks for the first launch of my app and then write them out, but then they are in two different places.</p> <p>Here is an entry from my root.plist as an example:</p> <pre><code>&lt;dict&gt; &lt;key&gt;Type&lt;/key&gt; &lt;string&gt;PSToggleSwitchSpecifier&lt;/string&gt; &lt;key&gt;Title&lt;/key&gt; &lt;string&gt;Open To Top Location&lt;/string&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;open_top_location&lt;/string&gt; &lt;key&gt;DefaultValue&lt;/key&gt; &lt;string&gt;YES&lt;/string&gt; &lt;key&gt;TrueValue&lt;/key&gt; &lt;string&gt;YES&lt;/string&gt; &lt;key&gt;FalseValue&lt;/key&gt; &lt;string&gt;NO&lt;/string&gt; &lt;/dict&gt; </code></pre> <p>The end result should be that if I ask for 'open_to_top_location' I get a YES, instead of it not being there at all until the first time the user opens the Settings app.</p> <p>Any ideas?</p>
510,329
8
0
null
2009-02-04 05:51:15.597 UTC
48
2016-11-21 09:36:05.64 UTC
null
null
null
rustyshelf
6,044
null
1
58
iphone|cocoa-touch
30,148
<p>If I understood you correctly, you want to avoid having default values specified twice (once as "DefaultValue" keys in your Settings.bundle/Root.plist file, and once in your app initialization code) so you do not have to keep them in sync.</p> <p>Since Settings.bundle is stored within the app bundle itself, you can just read the default values given there. I put together some sample code that looks at the Settings bundle and reads the default values for every key there. Note that this does not write out the default keys; if they don't exist, you'll need to read and register them at every launch (feel free to change this). I've only done some cursory tests, so make sure it works for you in all cases.</p> <pre><code>- (void)applicationDidFinishLaunching:(UIApplication *)application { NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"]; NSLog(@"name before is %@", name); // Note: this will not work for boolean values as noted by bpapa below. // If you use booleans, you should use objectForKey above and check for null if(!name) { [self registerDefaultsFromSettingsBundle]; name = [[NSUserDefaults standardUserDefaults] stringForKey:@"name"]; } NSLog(@"name after is %@", name); } - (void)registerDefaultsFromSettingsBundle { NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"]; if(!settingsBundle) { NSLog(@"Could not find Settings.bundle"); return; } NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]]; NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"]; NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]]; for(NSDictionary *prefSpecification in preferences) { NSString *key = [prefSpecification objectForKey:@"Key"]; if(key &amp;&amp; [[prefSpecification allKeys] containsObject:@"DefaultValue"]) { [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key]; } } [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister]; [defaultsToRegister release]; } </code></pre>
1,026,220
How to find out next character alphabetically?
<p>How we can find out the next character of the entered one. For example, if I entered the character "b" then how do I get the answer "c"?</p>
1,026,271
9
2
null
2009-06-22 09:15:20.85 UTC
3
2019-12-11 15:47:07.11 UTC
2009-09-04 09:23:54.81 UTC
null
124,875
null
124,875
null
1
39
c#|char
56,798
<p>Try this:</p> <pre><code>char letter = 'c'; if (letter == 'z') nextChar = 'a'; else if (letter == 'Z') nextChar = 'A'; else nextChar = (char)(((int)letter) + 1); </code></pre> <p>This way you have no trouble when the char is the last of the alphabet.</p>
1,237,778
How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?
<p>I have a time interval that spans years and I want all the time components from year down to seconds.</p> <p>My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on.</p> <p>That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method.</p> <p>Is there?</p> <p>I integrated Alex's 2nd method into my code.</p> <p>It's in a method called by a UIDatePicker in my interface.</p> <pre><code>NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &amp;year, &amp;month, &amp;day, &amp;hour, &amp;minute, &amp;sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); </code></pre> <p>When I set the date picker to a date 1 year and 1 day in the past, I get:</p> <blockquote> <p>1 years 1 months 1 days 16 hours 0 minutes 20 seconds</p> </blockquote> <p>which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount.</p> <p><strong>Update</strong>: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?</p>
1,386,746
9
3
null
2009-08-06 09:08:48.853 UTC
29
2016-10-19 12:52:37.213 UTC
2010-02-02 03:13:17.363 UTC
null
30,461
null
23,973
null
1
55
iphone|cocoa|time|nstimeinterval
48,645
<p><strong>Brief Description</strong></p> <ol> <li><p>Just another approach to complete the answer of JBRWilkinson but adding some code. It can also offers a solution to Alex Reynolds's comment. </p></li> <li><p>Use NSCalendar method:</p> <ul> <li><p><code>(NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts</code></p></li> <li><p>"Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". (From the API documentation). </p></li> </ul></li> <li><p>Create 2 NSDate whose difference is the NSTimeInterval you want to break down. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval, just apply the dates to the NSCalendar method).</p></li> <li><p>Get your quotes from NSDateComponents</p></li> </ol> <p><strong>Sample Code</strong></p> <pre><code>// The time interval NSTimeInterval theTimeInterval = ...; // Get the system calendar NSCalendar *sysCalendar = [NSCalendar currentCalendar]; // Create the NSDates NSDate *date1 = [[NSDate alloc] init]; NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; // Get conversion to months, days, hours, minutes NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit; NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0]; NSLog(@"Break down: %i min : %i hours : %i days : %i months", [breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]); </code></pre>
485,175
Is it safe to check floating point values for equality to 0?
<p>I know you can't rely on equality between double or decimal type values normally, but I'm wondering if 0 is a special case.</p> <p>While I can understand imprecisions between 0.00000000000001 and 0.00000000000002, 0 itself seems pretty hard to mess up since it's just nothing. If you're imprecise on nothing, it's not nothing anymore.</p> <p>But I don't know much about this topic so it's not for me to say.</p> <pre><code>double x = 0.0; return (x == 0.0) ? true : false; </code></pre> <p>Will that always return true?</p>
485,741
9
3
null
2009-01-27 20:50:14.62 UTC
26
2021-02-26 14:36:38.7 UTC
2016-02-21 12:38:22.657 UTC
null
96,780
PhoenixRedeemer
47,544
null
1
108
c#|.net|floating-point|precision|zero
81,652
<p>It is <strong>safe</strong> to expect that the comparison will return <code>true</code> if and only if the double variable has a value of exactly <code>0.0</code> (which in your original code snippet is, of course, the case). This is consistent with the semantics of the <code>==</code> operator. <code>a == b</code> means "<code>a</code> is equal to <code>b</code>".</p> <p>It is <strong>not safe</strong> (because it is <strong>not correct</strong>) to expect that the result of some calculation will be zero in double (or more generally, floating point) arithmetics whenever the result of the same calculation in pure Mathematics is zero. This is because when calculations come into the ground, floating point precision error appears - a concept which does not exist in Real number arithmetics in Mathematics.</p>
427,151
Algorithms for Simulating Fluid Flow
<p>I've got a game idea that requires some semi-realistic simulation of a fluid flowing around various objects. Think of a pool of mercury on an irregular surface that is being tilted in various directions.</p> <p>This is for a game, so 100% physical realism is not necessary. What is most important is that the calculations can be done in real time on a device with the horsepower of an iPhone.</p> <p>I'm thinking that some sort of cellular automaton or particle system is the way to go, but I don't know where to start.</p> <p>Any suggestions?</p>
427,157
10
0
2009-01-09 15:43:30.027 UTC
2009-01-09 05:20:11.853 UTC
11
2021-06-04 09:13:35.37 UTC
2009-01-09 15:46:40.723 UTC
nemo
20,774
Kristopher Johnson
1,175
null
1
15
algorithm|simulation|cellular-automata
12,900
<p>This is not my area of research but I believe this is considered the canonical work:</p> <p>Fluid Simulation for Computer Graphics</p> <p><a href="https://www.routledge.com/Fluid-Simulation-for-Computer-Graphics/Bridson/p/book/9781482232837" rel="nofollow noreferrer">https://www.routledge.com/Fluid-Simulation-for-Computer-Graphics/Bridson/p/book/9781482232837</a></p> <p>Also, look at the Berkeley Animation and Modeling Group</p> <p><a href="https://web.archive.org/web/20090116020253/http://www.cs.berkeley.edu/b-cam/" rel="nofollow noreferrer">https://web.archive.org/web/20090116020253/http://www.cs.berkeley.edu/b-cam/</a></p> <p>I also recommend a tool like Google Scholar or Citeseer and persue the scholarly literature.</p>
210,635
Teacher time schedule algorithm
<p>This is a problem I've had on my mind for a long time. Being the son of a teacher and a programmer, it occurred to me early on... but I still haven't found a solution for it.</p> <p>So this is the problem. One needs to create a time schedule for a school, using some constraints. These are generally divided in two categories:</p> <p><strong>Sanity Checks</strong> </p> <ul> <li>A teacher cannot teach two classes at the same time</li> <li>A student cannot follow two lessons at the same time</li> <li>Some teachers must have at least one day off during the week</li> <li>All the days of the week should be covered by the time table</li> <li>Subject X must have exactly so-and-so hours each week</li> <li>...</li> </ul> <p><strong>Preferences</strong> </p> <ul> <li>Each teacher's schedule should be as compact as possible (i.e. the teacher should work all hours for the day in a row with no pauses if possible)</li> <li>Teachers that have days off should be able to express a preference on which day</li> <li>Teachers that work part-time should be able to express a preference whether to work in the beginning or the end of the school day.</li> <li>...</li> </ul> <p>Now, after a few years of not finding a solution (and learning a thing or two in the meanwhile...), I realized that this smells like a NP-hard problem.</p> <p>Is it proven as NP-hard? </p> <p>Does anyone have an idea on how to crack this thing?</p> <p>Looking at <a href="https://stackoverflow.com/questions/184195/seating-plan-software-recommendations-does-such-a-beast-even-exist">this</a> question made me think about this problem, and whether genetic algorithms would be usable in this case. However it would be pretty hard to mutate possibilities while maintaining the sanity check rules. Also it's not clear to me how to distinguish incompatible requirements.</p> <hr> <p>A small addendum to better specify the problem. This is applied to Italian school style classrooms where all students are associated in different classes (for example: year 1 section A) and the teachers move between classes. All students of the same class have the same schedule, and have no choice over which lessons to attend.</p>
210,700
10
1
null
2008-10-16 23:27:33.18 UTC
26
2016-05-30 15:47:28.423 UTC
2017-05-23 11:53:38.5 UTC
Sklivvz
-1
Sklivvz
7,028
null
1
30
algorithm|scheduling|np-hard
20,747
<p>I am one of the developer that works on the scheduler part of a student information system. During our original approach of the scheduling problem, we researched genetic algorithms to solve constraint satisfaction problems, and even though we were successful initially, we realized that there was a less complicated solution to the problem (after attending a school scheduling workshop)</p> <p>Our current implementation works great, and uses brute force with smart heuristics to get a valid schedule in a short amount of time. The master schedule (assignment of the classes to the teachers) is first built, taking in consideration all the constraints that each teacher has while minimizing the possibility of conflicts for the students (based of their course requests). The students are then scheduled in the classes using the same method.</p> <p>Doing this allows you to have the machine build a master schedule first, and then have a human tweak it if needed. </p> <p>The scheduler current implementation is written in perl, but other options we visited early on were Prolog and CLIPS (expert system) </p>
132,867
I have a gem installed but require 'gemname' does not work. Why?
<p>The question I'm really asking is why require does not take the name of the gem. Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!?</p> <p>As an example if I have <code>memcache-client</code> installed then I have to require it using</p> <pre><code>require 'rubygems' require 'memcache' </code></pre>
132,970
11
0
null
2008-09-25 12:01:13.993 UTC
9
2020-06-10 01:05:54.393 UTC
null
null
null
mloughran
18,751
null
1
63
ruby|rubygems
71,410
<p>There is no standard for what the file you need to include is. However there are some commonly followed conventions that you can can follow try and make use of:</p> <ul> <li>Often the file is called the same name as the gem. So <code>require mygem</code> will work. </li> <li>Often the file is the only .rb file in the lib subdirectory of the gem, So if you can get the name of the gem (maybe you are itterating through vendor/gems in a pre 2.1 rails project), then you can inspect <code>#{gemname}/lib</code> for .rb files, and if there is only one, its a pretty good bet that is the one to require</li> </ul> <p>If all of that works, then all you can do is look into the gem's directory (which you can find by running <code>gem environment | grep INSTALLATION | awk '{print $4}'</code> and looking in the lib directory, You will probably need to read the files and hope there is a comment explaining what to do</p>
526,255
Probability distribution in Python
<p>I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to be chosen than a less unlikely (a more likely) object. I am wondering if you would have any suggestions, preferably an existing python module that I could use, else I will need to make it myself.</p> <p>I have checked out the random module; it does not seem to provide this.</p> <p>I have to make such choices many millions of times for 1000 different sets of objects each containing 2,455 objects. Each set will exchange objects among each other so the random chooser needs to be dynamic. With 1000 sets of 2,433 objects, that is 2,433 million objects; low memory consumption is crucial. And since these choices are not the bulk of the algorithm, I need this process to be quite fast; CPU-time is limited.</p> <p>Thx </p> <p>Update:</p> <p>Ok, I tried to consider your suggestions wisely, but time is so limited... </p> <p>I looked at the binary search tree approach and it seems too risky (complex and complicated). The other suggestions all resemble the ActiveState recipe. I took it and modified it a little in the hope of making more efficient:</p> <pre><code>def windex(dict, sum, max): '''an attempt to make a random.choose() function that makes weighted choices accepts a dictionary with the item_key and certainty_value as a pair like: &gt;&gt;&gt; x = [('one', 20), ('two', 2), ('three', 50)], the maximum certainty value (max) and the sum of all certainties.''' n = random.uniform(0, 1) sum = max*len(list)-sum for key, certainty in dict.iteritems(): weight = float(max-certainty)/sum if n &lt; weight: break n = n - weight return key </code></pre> <p>I am hoping to get an efficiency gain from dynamically maintaining the sum of certainties and the maximum certainty. Any further suggestions are welcome. You guys saves me so much time and effort, while increasing my effectiveness, it is crazy. Thx! Thx! Thx!</p> <p>Update2:</p> <p>I decided to make it more efficient by letting it choose more choices at once. This will result in an acceptable loss in precision in my algo for it is dynamic in nature. Anyway, here is what I have now:</p> <pre><code>def weightedChoices(dict, sum, max, choices=10): '''an attempt to make a random.choose() function that makes weighted choices accepts a dictionary with the item_key and certainty_value as a pair like: &gt;&gt;&gt; x = [('one', 20), ('two', 2), ('three', 50)], the maximum certainty value (max) and the sum of all certainties.''' list = [random.uniform(0, 1) for i in range(choices)] (n, list) = relavate(list.sort()) keys = [] sum = max*len(list)-sum for key, certainty in dict.iteritems(): weight = float(max-certainty)/sum if n &lt; weight: keys.append(key) if list: (n, list) = relavate(list) else: break n = n - weight return keys def relavate(list): min = list[0] new = [l - min for l in list[1:]] return (min, new) </code></pre> <p>I haven't tried it out yet. If you have any comments/suggestions, please do not hesitate. Thx!</p> <p>Update3:</p> <p>I have been working all day on a task-tailored version of Rex Logan's answer. Instead of a 2 arrays of objects and weights, it is actually a special dictionary class; which makes things quite complex since Rex's code generates a random index... I also coded a test case that kind of resembles what will happen in my algo (but I can't really know until I try!). The basic principle is: the more a key is randomly generated often, the more unlikely it will be generated again: </p> <pre><code>import random, time import psyco psyco.full() class ProbDict(): """ Modified version of Rex Logans RandomObject class. The more a key is randomly chosen, the more unlikely it will further be randomly chosen. """ def __init__(self,keys_weights_values={}): self._kw=keys_weights_values self._keys=self._kw.keys() self._len=len(self._keys) self._findSeniors() self._effort = 0.15 self._fails = 0 def __iter__(self): return self.next() def __getitem__(self, key): return self._kw[key] def __setitem__(self, key, value): self.append(key, value) def __len__(self): return self._len def next(self): key=self._key() while key: yield key key = self._key() def __contains__(self, key): return key in self._kw def items(self): return self._kw.items() def pop(self, key): try: (w, value) = self._kw.pop(key) self._len -=1 if w == self._seniorW: self._seniors -= 1 if not self._seniors: #costly but unlikely: self._findSeniors() return [w, value] except KeyError: return None def popitem(self): return self.pop(self._key()) def values(self): values = [] for key in self._keys: try: values.append(self._kw[key][1]) except KeyError: pass return values def weights(self): weights = [] for key in self._keys: try: weights.append(self._kw[key][0]) except KeyError: pass return weights def keys(self, imperfect=False): if imperfect: return self._keys return self._kw.keys() def append(self, key, value=None): if key not in self._kw: self._len +=1 self._kw[key] = [0, value] self._keys.append(key) else: self._kw[key][1]=value def _key(self): for i in range(int(self._effort*self._len)): ri=random.randint(0,self._len-1) #choose a random object rx=random.uniform(0,self._seniorW) rkey = self._keys[ri] try: w = self._kw[rkey][0] if rx &gt;= w: # test to see if that is the value we want w += 1 self._warnSeniors(w) self._kw[rkey][0] = w return rkey except KeyError: self._keys.pop(ri) # if you do not find one after 100 tries then just get a random one self._fails += 1 #for confirming effectiveness only for key in self._keys: if key in self._kw: w = self._kw[key][0] + 1 self._warnSeniors(w) self._kw[key][0] = w return key return None def _findSeniors(self): '''this function finds the seniors, counts them and assess their age. It is costly but unlikely.''' seniorW = 0 seniors = 0 for w in self._kw.itervalues(): if w &gt;= seniorW: if w == seniorW: seniors += 1 else: seniorsW = w seniors = 1 self._seniors = seniors self._seniorW = seniorW def _warnSeniors(self, w): #a weight can only be incremented...good if w &gt;= self._seniorW: if w == self._seniorW: self._seniors+=1 else: self._seniors = 1 self._seniorW = w def test(): #test code iterations = 200000 size = 2500 nextkey = size pd = ProbDict(dict([(i,[0,i]) for i in xrange(size)])) start = time.clock() for i in xrange(iterations): key=pd._key() w=pd[key][0] if random.randint(0,1+pd._seniorW-w): #the heavier the object, the more unlikely it will be removed pd.pop(key) probAppend = float(500+(size-len(pd)))/1000 if random.uniform(0,1) &lt; probAppend: nextkey+=1 pd.append(nextkey) print (time.clock()-start)*1000/iterations, "msecs / iteration with", pd._fails, "failures /", iterations, "iterations" weights = pd.weights() weights.sort() print "avg weight:", float(sum(weights))/pd._len, max(weights), pd._seniorW, pd._seniors, len(pd), len(weights) print weights test() </code></pre> <p>Any comments are still welcome. @Darius: your binary trees are too complex and complicated for me; and I do not think its leafs can be removed efficiently... Thx all</p>
526,300
12
12
2009-02-09 01:00:32.423 UTC
2009-02-08 19:52:22.713 UTC
23
2014-01-19 00:25:27.99 UTC
2009-02-10 15:56:55.267 UTC
Nicholas Leonard
49,985
Nicholas Leonard
49,985
null
1
21
python|algorithm|random|distribution|probability
20,787
<p><a href="http://code.activestate.com/recipes/117241/" rel="noreferrer">This activestate recipe</a> gives an easy-to-follow approach, specifically the version in the comments that doesn't require you to pre-normalize your weights:</p> <pre><code>import random def weighted_choice(items): """items is a list of tuples in the form (item, weight)""" weight_total = sum((item[1] for item in items)) n = random.uniform(0, weight_total) for item, weight in items: if n &lt; weight: return item n = n - weight return item </code></pre> <p>This will be slow if you have a large list of items. A binary search would probably be better in that case... but would also be more complicated to write, for little gain if you have a small sample size. <a href="http://code.activestate.com/recipes/498229/" rel="noreferrer">Here's an example of the binary search approach in python</a> if you want to follow that route.</p> <p>(I'd recommend doing some quick performance testing of both methods on your dataset. The performance of different approaches to this sort of algorithm is often a bit unintuitive.)</p> <hr> <p><strong>Edit:</strong> I took my own advice, since I was curious, and did a few tests.</p> <p>I compared four approaches:</p> <p><em>The weighted_choice function above.</em></p> <p><em>A binary-search choice function like so:</em></p> <pre><code>def weighted_choice_bisect(items): added_weights = [] last_sum = 0 for item, weight in items: last_sum += weight added_weights.append(last_sum) return items[bisect.bisect(added_weights, random.random() * last_sum)][0] </code></pre> <p><em>A compiling version of 1:</em></p> <pre><code>def weighted_choice_compile(items): """returns a function that fetches a random item from items items is a list of tuples in the form (item, weight)""" weight_total = sum((item[1] for item in items)) def choice(uniform = random.uniform): n = uniform(0, weight_total) for item, weight in items: if n &lt; weight: return item n = n - weight return item return choice </code></pre> <p><em>A compiling version of 2:</em></p> <pre><code>def weighted_choice_bisect_compile(items): """Returns a function that makes a weighted random choice from items.""" added_weights = [] last_sum = 0 for item, weight in items: last_sum += weight added_weights.append(last_sum) def choice(rnd=random.random, bis=bisect.bisect): return items[bis(added_weights, rnd() * last_sum)][0] return choice </code></pre> <p>I then built a big list of choices like so:</p> <pre><code>choices = [(random.choice("abcdefg"), random.uniform(0,50)) for i in xrange(2500)] </code></pre> <p>And an excessively simple profiling function:</p> <pre><code>def profiler(f, n, *args, **kwargs): start = time.time() for i in xrange(n): f(*args, **kwargs) return time.time() - start </code></pre> <p><strong>The results:</strong></p> <p>(Seconds taken for 1,000 calls to the function.)</p> <ul> <li>Simple uncompiled: 0.918624162674</li> <li>Binary uncompiled: 1.01497793198</li> <li>Simple compiled: 0.287325024605</li> <li>Binary compiled: 0.00327413797379</li> </ul> <p>The "compiled" results include the average time taken to compile the choice function once. (I timed 1,000 compiles, then divided that time by 1,000, and added the result to the choice function time.)</p> <p>So: if you have a list of items+weights which change very rarely, the binary compiled method is <em>by far</em> the fastest.</p>
576,775
As a programmer how would you explain imaginary numbers?
<p>As a programmer I think it is my job to be good at math but I am having trouble getting my head round imaginary numbers. I have tried google and <a href="http://en.wikipedia.org/wiki/Imaginary_number" rel="noreferrer">wikipedia</a> with no luck so I am hoping a programmer can explain in to me, give me an example of a number squared that is &lt;= 0, some example usage etc...</p>
576,800
13
0
null
2009-02-23 07:16:18.627 UTC
9
2015-03-11 21:47:14.183 UTC
2013-01-17 07:07:41.373 UTC
David Segonds
225,647
Ctrl Alt D-1337
36,157
null
1
18
math|complex-numbers
5,310
<p>I guess this <a href="http://betterexplained.com/articles/a-visual-intuitive-guide-to-imaginary-numbers/" rel="nofollow noreferrer">blog entry</a> is one good explanation:</p> <p>The key word is <strong>rotation</strong> (as opposed to <strong><em>direction</em></strong> for negative numbers, which are as stranger as imaginary number when you think of them: <em>less than nothing</em> ?)</p> <p><img src="https://betterexplained.com/wp-content/uploads/complex/imaginary_cycle.png" alt="alt text"></p> <p>Like negative numbers modeling flipping, <strong>imaginary numbers can model anything that rotates between two dimensions “X” and “Y”</strong>. Or anything with a cyclic, circular relationship</p>
180,947
Base64 decode snippet in C++
<p>Is there a freely available Base64 decoding code snippet in C++?</p>
180,949
13
3
null
2008-10-08 00:25:26.463 UTC
43
2022-01-19 05:00:53.637 UTC
2021-01-09 16:46:23.643 UTC
null
63,550
null
19,104
null
1
94
c++|base64
199,010
<p>See <em><a href="http://www.adp-gmbh.ch/cpp/common/base64.html" rel="noreferrer">Encoding and decoding base 64 with C++</a></em>.</p> <p>Here is the implementation from that page:</p> <pre><code>/* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger [email protected] */ static const std::string base64_chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot; &quot;abcdefghijklmnopqrstuvwxyz&quot; &quot;0123456789+/&quot;; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2; char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4); char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6); char_array_4[3] = char_array_3[2] &amp; 0x3f; for(i = 0; (i &lt;4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j &lt; 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2; char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4); char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6); char_array_4[3] = char_array_3[2] &amp; 0x3f; for (j = 0; (j &lt; i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ &lt; 3)) ret += '='; } return ret; } std::string base64_decode(std::string const&amp; encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- &amp;&amp; ( encoded_string[in_] != '=') &amp;&amp; is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i &lt;4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4); char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2); char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3]; for (i = 0; (i &lt; 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j &lt;4; j++) char_array_4[j] = 0; for (j = 0; j &lt;4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] &lt;&lt; 2) + ((char_array_4[1] &amp; 0x30) &gt;&gt; 4); char_array_3[1] = ((char_array_4[1] &amp; 0xf) &lt;&lt; 4) + ((char_array_4[2] &amp; 0x3c) &gt;&gt; 2); char_array_3[2] = ((char_array_4[2] &amp; 0x3) &lt;&lt; 6) + char_array_4[3]; for (j = 0; (j &lt; i - 1); j++) ret += char_array_3[j]; } return ret; } </code></pre>
652,770
Delete with Join in MySQL
<p>Here is the script to create my tables: </p> <pre><code>CREATE TABLE clients ( client_i INT(11), PRIMARY KEY (client_id) ); CREATE TABLE projects ( project_id INT(11) UNSIGNED, client_id INT(11) UNSIGNED, PRIMARY KEY (project_id) ); CREATE TABLE posts ( post_id INT(11) UNSIGNED, project_id INT(11) UNSIGNED, PRIMARY KEY (post_id) ); </code></pre> <p>In my PHP code, when deleting a client, I want to delete all projects posts:</p> <pre><code>DELETE FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id; </code></pre> <p>The posts table does not have a foreign key <code>client_id</code>, only <code>project_id</code>. I want to delete the posts in projects that have the passed <code>client_id</code>.</p> <p>This is not working right now because no posts are deleted.</p>
4,192,849
14
5
null
2009-03-17 01:44:05.523 UTC
115
2020-10-27 10:14:23.037 UTC
2018-10-26 14:07:35.047 UTC
null
8,810,495
brioblue
74,980
null
1
564
mysql
372,098
<p>You just need to specify that you want to delete the entries from the <code>posts</code> table:</p> <pre><code>DELETE posts FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id </code></pre> <p>EDIT: For more information you can see <a href="https://stackoverflow.com/a/29204958/214545">this alternative answer</a></p>
249,357
Are there any CSS standards that I should follow while writing my first stylesheet?
<p>I am currently working on my first website. I have no idea where to start on the CSS page, or if there are any standards that I should be following.</p> <p>I would appreciate any links or first-hand advise.</p>
249,387
17
0
null
2008-10-30 05:34:42.283 UTC
14
2014-09-18 09:44:45.667 UTC
null
null
null
jjnguy
2,598
null
1
15
css
2,708
<p>An error that beginners make quite often:</p> <p>CSS is semantic as well. Try to express concepts, not formats. Contrived example:</p> <h3>Wrong:</h3> <pre><code>div.red { color: red; } </code></pre> <p>as opposed to:</p> <h3>Good:</h3> <pre><code>div.error { color: red; } </code></pre> <p>CSS should be the formatting companion for the concepts you use on your web site, so they should be reflected in it. You will be much more flexible this way.</p>
126,445
Any way to remove IEs black border around submit button in active forms?
<p>I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border:</p> <pre><code>input.button { background: #eee; border: 1px solid #ccc; } </code></pre> <p>This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7. </p> <p>Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action.</p> <p>If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.</p>
126,517
18
0
null
2008-09-24 10:46:10.39 UTC
22
2014-12-23 10:58:41.243 UTC
null
null
null
Magnar
1,123
null
1
40
css|internet-explorer
65,424
<p>Well this works here:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; span.button { background: #eee; border: 1px solid #ccc; } span.button input { background:none; border:0; margin:0; padding:0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;span class="button"&gt;&lt;input type="button" name="..." value="Button"/&gt;&lt;/span&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1,073,384
What strategies have you used to improve build times on large projects?
<p>I once worked on a C++ project that took about an hour and a half for a full rebuild. Small edit, build, test cycles took about 5 to 10 minutes. It was an unproductive nightmare.</p> <p>What is the worst build times you ever had to handle? </p> <p>What strategies have you used to improve build times on large projects?</p> <p><strong>Update:</strong></p> <p>How much do you think the language used is to blame for the problem? I think C++ is prone to massive dependencies on large projects, which often means even simple changes to the source code can result in a massive rebuild. Which language do you think copes with large project dependency issues best?</p>
1,073,434
20
2
null
2009-07-02 09:26:09.29 UTC
11
2014-05-26 07:02:50.773 UTC
2011-12-19 18:43:16.317 UTC
null
105,971
null
4,012
null
1
24
c++|compiler-construction|build-process|build-automation
5,403
<ol> <li>Forward declaration</li> <li>pimpl idiom</li> <li>Precompiled headers</li> <li>Parallel compilation (e.g. MPCL add-in for Visual Studio).</li> <li>Distributed compilation (e.g. Incredibuild for Visual Studio).</li> <li>Incremental build</li> <li>Split build in several "projects" so not compile all the code if not needed.</li> </ol> <p><em>[Later Edit]</em> 8. Buy faster machines.</p>
196,017
Unique (non-repeating) random numbers in O(1)?
<p>I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is this possible?</p>
196,065
22
7
null
2008-10-12 20:34:22.297 UTC
117
2019-11-02 09:44:16.297 UTC
2015-07-16 18:08:47.61 UTC
Pete Kirkham
1,711,796
dicroce
3,886
null
1
188
algorithm|math|random|language-agnostic
109,105
<p>Initialize an array of 1001 integers with the values 0-1000 and set a variable, max, to the current max index of the array (starting with 1000). Pick a random number, r, between 0 and max, swap the number at the position r with the number at position max and return the number now at position max. Decrement max by 1 and continue. When max is 0, set max back to the size of the array - 1 and start again without the need to reinitialize the array.</p> <p><strong>Update:</strong> Although I came up with this method on my own when I answered the question, after some research I realize this is a modified version of <a href="http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="noreferrer">Fisher-Yates</a> known as Durstenfeld-Fisher-Yates or Knuth-Fisher-Yates. Since the description may be a little difficult to follow, I have provided an example below (using 11 elements instead of 1001):</p> <p>Array starts off with 11 elements initialized to array[n] = n, max starts off at 10:</p> <pre><code>+--+--+--+--+--+--+--+--+--+--+--+ | 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10| +--+--+--+--+--+--+--+--+--+--+--+ ^ max </code></pre> <p>At each iteration, a random number r is selected between 0 and max, array[r] and array[max] are swapped, the new array[max] is returned, and max is decremented:</p> <pre><code>max = 10, r = 3 +--------------------+ v v +--+--+--+--+--+--+--+--+--+--+--+ | 0| 1| 2|10| 4| 5| 6| 7| 8| 9| 3| +--+--+--+--+--+--+--+--+--+--+--+ max = 9, r = 7 +-----+ v v +--+--+--+--+--+--+--+--+--+--+--+ | 0| 1| 2|10| 4| 5| 6| 9| 8| 7: 3| +--+--+--+--+--+--+--+--+--+--+--+ max = 8, r = 1 +--------------------+ v v +--+--+--+--+--+--+--+--+--+--+--+ | 0| 8| 2|10| 4| 5| 6| 9| 1: 7| 3| +--+--+--+--+--+--+--+--+--+--+--+ max = 7, r = 5 +-----+ v v +--+--+--+--+--+--+--+--+--+--+--+ | 0| 8| 2|10| 4| 9| 6| 5: 1| 7| 3| +--+--+--+--+--+--+--+--+--+--+--+ ... </code></pre> <p>After 11 iterations, all numbers in the array have been selected, max == 0, and the array elements are shuffled:</p> <pre><code>+--+--+--+--+--+--+--+--+--+--+--+ | 4|10| 8| 6| 2| 0| 9| 5| 1| 7| 3| +--+--+--+--+--+--+--+--+--+--+--+ </code></pre> <p>At this point, max can be reset to 10 and the process can continue.</p>
895,371
Why is Bubble Sort implementation looping forever?
<p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p> <p>This is my attempt in Python:</p> <pre><code>mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True while unsorted: for element in range(0,length): unsorted = False if badList[element] &gt; badList[element + 1]: hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold print badList else: unsorted = True print bubble(mylist) </code></pre> <p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p> <p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p> <p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
902,736
28
16
null
2009-05-21 21:47:24.853 UTC
26
2022-04-06 15:24:11.58 UTC
2022-04-06 15:24:11.58 UTC
null
8,372,853
null
2,592
null
1
131
python|algorithm|sorting|bubble-sort
112,947
<p>To explain why your script isn't working right now, I'll rename the variable <code>unsorted</code> to <code>sorted</code>.</p> <p>At first, your list isn't yet sorted. Of course, we set <code>sorted</code> to <code>False</code>.</p> <p>As soon as we start the <code>while</code> loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set <code>sorted</code> back to <code>False</code>. <code>sorted</code> will remain <code>True</code> <em>only if there were no elements in the wrong order</em>.</p> <pre><code>sorted = False # We haven't started sorting yet while not sorted: sorted = True # Assume the list is now sorted for element in range(0, length): if badList[element] &gt; badList[element + 1]: sorted = False # We found two elements in the wrong order hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold # We went through the whole list. At this point, if there were no elements # in the wrong order, sorted is still True. Otherwise, it's false, and the # while loop executes again. </code></pre> <p>There are also minor little issues that would help the code be more efficient or readable.</p> <ul> <li><p>In the <code>for</code> loop, you use the variable <code>element</code>. Technically, <code>element</code> is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like <code>i</code> for "index".</p> <pre><code>for i in range(0, length): </code></pre></li> <li><p>The <code>range</code> command can also take just one argument (named <code>stop</code>). In that case, you get a list of all the integers from 0 to that argument.</p> <pre><code>for i in range(length): </code></pre></li> <li><p>The <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer" title="Style Guide for Python Code">Python Style Guide</a> recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles.</p> <pre><code>def bubble(bad_list): </code></pre></li> <li><p>To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, <code>(badList[i+1], badList[i])</code> is <code>(3, 5)</code>) and then gets assigned to the two variables on the left hand side (<code>(badList[i], badList[i+1])</code>).</p> <pre><code>bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] </code></pre></li> </ul> <p>Put it all together, and you get this:</p> <pre><code>my_list = [12, 5, 13, 8, 9, 65] def bubble(bad_list): length = len(bad_list) - 1 sorted = False while not sorted: sorted = True for i in range(length): if bad_list[i] &gt; bad_list[i+1]: sorted = False bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] bubble(my_list) print my_list </code></pre> <p>(I removed your print statement too, by the way.)</p>
34,722,862
How to remove time part from Date?
<p>I have a date <code>'12/12/1955 12:00:00 AM'</code> stored in a hidden column. I want to display the date without the time.</p> <p>How do I do this?</p>
34,722,927
8
8
null
2016-01-11 13:34:05.62 UTC
6
2022-09-16 11:49:43.42 UTC
2022-03-14 18:41:38.82 UTC
null
3,345,644
null
3,913,690
null
1
103
javascript
211,191
<p>Split it by <code>space</code> and take first part like below. Hope this will help you.</p> <pre><code>var d = '12/12/1955 12:00:00 AM'; d = d.split(' ')[0]; console.log(d); </code></pre>
7,002,477
SQL Server default date time stamp?
<p>I have a field that when something is inserted I want it to get the current Date &amp; Time and insert this into the database. Is there a way to get the date &amp; time, and set it as the default value? </p> <p>Currently the default value is: (getdate()) Which sets only the date. How do I also set the time? </p>
7,002,513
5
5
null
2011-08-09 20:25:27.353 UTC
1
2014-03-24 08:36:02.197 UTC
2011-08-09 20:28:25.897 UTC
null
280,598
null
494,901
null
1
16
sql|sql-server
66,730
<p><code>GETDATE()</code> is a date and time in SQL Server.</p> <p>Run <code>SELECT GETDATE()</code> to verify this.</p> <p>What is the datatype of your field? If it's <code>DATE</code> then it will not hold time values as well.</p>
6,736,023
Which browsers (and versions) support the Canvas.toBlob method?
<p>I'm working on a minimalist image creation project and I need to have the ability to create images within the browser that are in-turn used on a server. So far, the <code>Canvas.toDataUrl()</code> method has met our needs, but I just learned of the <code>Canvas.toBlob()</code> method which would be much more convenient.</p> <p>It appears that the <code>toBlob()</code> method is new to the specification by a few months (I can't find any direct reference to when it was added.)</p> <p>What browsers support <code>toBlob</code> and more importantly which versions of those browsers included the integration of the method? Additionally, is support for this feature "buggy" or in development for any major browsers?</p> <p><strong>UPDATE</strong></p> <p>I asked this question nearly 8 year ago. I had tabled my previous mentioned project, waiting for any updates on the status of the <code>canvas.toBlob()</code> method. From what I can gather on the web, implementation of <code>toBlob()</code> appears to be trickling into use across some browsers.</p> <p>I ask once again, how ubiquitous is the <code>canvas.toBlob()</code> method amongst browsers that have begun integrating the HTML5 canvas object and which versions of those browsers were the first to integrate this support?</p>
56,499,809
5
3
null
2011-07-18 16:22:02.31 UTC
2
2019-09-16 19:03:02.493 UTC
2019-06-12 15:29:06.15 UTC
null
469,319
null
469,319
null
1
38
html|html5-canvas
19,358
<p>It's been nearly 8 years since I first asked this question. Considering that I still get a trickle-in of upvotes and this question is often at the top of Google Searches, I figured I'd give an update to the state of <code>Canvas.toBlob(...)</code> and it's implementation.</p> <p>The following table:</p> <pre><code> | | Version Support | Version | for 'Quality' Browser | Implemented | Parameter -------------------+-------------+----------------- Android Webview) | 50 | 50 Chrome (Desktop) | 50 | 50 Chrome (Mobile) | 50 | Unsupported Edge (Desktop) | Unsupported | Unsupported Edge (Mobile) | Unsupported | Unsupported Firefox (Desktop) | 19 | 25 Firefox (Mobile) | 4 | 25 Internet Explorer* | 10 | Unsupported Opera (Desktop) | 37 | Yes Opera (Mobile) | 37 | Unsupported Safari (Desktop) | 11 | Unsupported Safari (Mobile) | 11 | Unsupported Samsung Internet | 5.0 | Unsupported * Internet Explore implements "msToBlob" rather than the "toBlob" function signature. </code></pre> <p>(Source: <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob</a>)</p>
6,449,345
How to show a Horizontal Android Indeterminate Progress Bar
<p>How to show an indeterminate horizontal progress bar in android? The animation of the progress bar should start from 0 to 100 and then go back from 100 to 0 continuously. I am not looking for the wheel progress bar.</p>
6,450,417
5
2
null
2011-06-23 04:29:47.933 UTC
9
2018-10-03 13:09:46.04 UTC
2018-01-25 09:38:31.907 UTC
null
2,598,247
null
608,209
null
1
50
android|android-progressbar
90,030
<p>I already knew that <code>setIndeterminate</code> will give an infinite horizontal progress bar. But it will be similar to the loading wheel, except that it will be horizontal. If you see my question I was looking for horizontal bar which starts from 0 and goes all the way to 100 (a gradual increase). If you want to achieve this in Android, you must use your progress bar as below: </p> <pre><code> &lt;ProgressBar android:id="@+id/progress_horizontal" android:indeterminateOnly="false" android:indeterminateDrawable="@drawable/progress_indeterminate_horizontal" android:progressDrawable="@drawable/progress_horizontal" android:minHeight="24dip" android:maxHeight="24dip" android:layout_width="fill_parent" android:layout_height="wrap_content"/&gt; </code></pre> <p>As I wanted to change the background of my progress bar, I changed the ProgressDrawable and IndeterminateDrawable. The original drawables are located under <code>frameworks/base/core/res/res/drawable</code>. Copy them to your project and change the color according to your needs.</p> <p>Create a thread which updates the progress count and does a <code>Thread.Sleep</code>. Then it sends the message to the Handler which will update the progress bar in UI thread.</p>
6,583,746
Matching Kinect Audio with Video
<p>I have a project dealing with video conferencing using the Kinect (or, more likely, four of them). Right now, my company uses these stupidly expensive cameras for our VTC rooms. The hope is, using a couple Kinects linked together, we can reduce the costs. The plan is to have four/five of them covering a 180 degree arc so the Kinects can see the entire room/table (still a lot cheaper than our current cameras!). The applications would choose a video stream coming from a Kinect based on who at the table is talking. Plan is fine in theory, but I've run into a snag. </p> <p>As far as I can tell, there is no way to tell which microphone array corresponds to Kinect Runtime object. I can get an object representing each Kinect using:</p> <pre><code>Device device = new Device(); Runtime[] kinects = new Runtime[device.Count]; for( int i = 0; i &lt; kinects.Length; i ++ ) kinects[i] = new Runtime(i); </code></pre> <p>And every microphone array using:</p> <pre><code>var source = new KinectAudioSource(); IEnumerable&lt;AudioDeviceInfo&gt; devices = source.FindCaptureDevices(); foreach( AudioDeviceInfo in device in devices) { KinectAudioSource devSpecificSource = new KinectAudioSource(); devSpecificSource.MicrophoneIndex = (short)device.DeviceIndex; } </code></pre> <p>but I cannot find any way to know that Runtime A corresponds to KinectAudioSource B. This isn't a huge problem for the two Kinects I'm using (I'll just guess which is which, and switch them if they're wrong), but when we get up to four or five Kinects, I don't want to need to do any kind of calibration every time the application runs. I've considered assuming that the Runtime and KinectAudioSource objects will be in the same order (Runtime index 0 corresponds to the first AudioDeviceInfo in devices), but that seems risky.</p> <p>So, the question: is there any way to match a Runtime object with its KinectAudioSource? If not, is it guaranteed that they will be in the correct order so I can match Runtime 0 with the first KinectAudioSource microphone index in devices?</p> <p><strong>UPDATE:</strong> Finally slammed my face against WPF's single thread apartment requirement and the Kinect audio's multiple thread apartment requirement enough to get the two to behave together. Problem is, as far as I can tell, the order of the Kinect Runtime objects and KinectAudioSources do <em>not</em> line up. I'm in a rather loud lab (I'm one of.. maybe 40 interns in the room), so it's hard to test, but I'm fairly certain that the order is switched for the two Kinects I have plugged in. I have two Runtime objects and two KinectAudioSource objects. When the first KinectAudioSource reports that a sound is coming from directly in front of it, I'm actually standing in front of the Kinect associated with the second Runtime object. So there's no guarantee that the orders of the two will line up. So now, to repeat the question: how do I match up the KinectAudioSource object with the Nui.Runtime object? Right now, I only have two Kinects hooked up, but since the goal is four or five.. I need a concrete way to do this.</p> <p><strong>UPDATE 2:</strong> Brought the two Kinects I have at work back home to play with. Three Kinects, one computer. Fun stuff (it was actually a pain to get them all installed at once, and one of the video feeds doesn't seem to be working, so I'm back to 2 for now). musefan's answer got me hoping that I had missed something in the AudioDeviceInfo objects that would shed some light on this problem, but no luck. I found an interesting looking field in Runtime objects called NuiCamera.UniqueDeviceName, but I can't find any link between that and anything in AudioDeviceInfo.</p> <p>Output from those fields, in the hopes Sherlock Holmes sees the thread and notices a connection: </p> <pre><code>Console.WriteLine("Nui{0}: {1}", i, nuis[i].NuiCamera.UniqueDeviceName); //Nui0: USB\VID_0409&amp;PID_005A\6&amp;1F9D61BF&amp;0&amp;4 //Nui1: USB\VID_0409&amp;PID_005A\6&amp;356AC357&amp;0&amp;3 Console.WriteLine("AudioDeviceInfo{0}: {1}, {2}, {3}", audios.IndexOf(audio), device.DeviceID, device.DeviceIndex, device.DeviceName); //AudioDeviceInfo0: {0.0.1.00000000}.{1945437e-2d55-45e5-82ba-fc3021441b17}, 0, Microphone Array (Kinect USB Audio) //AudioDeviceInfo1: {0.0.1.00000000}.{6002e98f-2429-459a-8e82-9810330a8e25}, 1, Microphone Array (2- Kinect USB Audio) </code></pre> <p><strong>UPDATE 3:</strong> I'm not looking for calibration techniques. I'm looking for a way to match the Kinect camera with its microphone array within the application at runtime, with no previous set up required. Please stop posting possible calibration techniques. The entire point of posting the question was to find a way to avoid needing the user to do set up.</p> <p><strong>UPDATE 4:</strong> WMI definitely seems like the way to go. Unfortunately, I haven't had a lot of time to work on it, as I've been struggling just to get 3 Kinects to play nice with each other. Something about USB hubs not being able to handle the bandwidth? I've informed my boss that there doesn't seem to be any easy way to connect 3+ Kinects to a regular computer and not blue screen. I might still try to work on this in my free time, but as far as work goes.. it's pretty much a dead end.</p> <p>Thanks for the answers guys, sorry I couldn't post a working solution.</p>
6,674,061
6
4
null
2011-07-05 13:52:14.67 UTC
8
2011-07-15 13:10:50.177 UTC
2011-07-15 13:10:50.177 UTC
null
610,634
null
610,634
null
1
28
c#|kinect
2,496
<p>The API provided by Microsoft Research doesn't actually provide this capability. Kinect is essentially multiple cameras, and a microphone array with each sensor having a unique driver stack so there is no linkage to the physical hardware device. The best way to achieve this would be to use the Windows API instead, by way of WMI and take the device ID's you get for the NUI camera, and microphones, and use WMI to find which USB bus they are attachted to (as each Kinect sensor has to be on its own bus) then you'll know which device matches what. This will be an expensive operation, so I would recommend you do this on start-up, or detection of the devices and keep the information persisted until a time you know the hardware configuration changes, or the application is reset. Using WMI through .NET is pretty well documented, but here is one article that specifically talks about USB devices through WMI/.NET: <a href="http://www.developerfusion.com/article/84338/making-usb-c-friendly/" rel="noreferrer">http://www.developerfusion.com/article/84338/making-usb-c-friendly/</a>. </p>
6,928,374
Example of the Scala aggregate function
<p>I have been looking and I cannot find an example or discussion of the <code>aggregate</code> function in Scala that I can understand. It seems pretty powerful.</p> <p>Can this function be used to reduce the values of tuples to make a multimap-type collection? For example:</p> <pre><code>val list = Seq(("one", "i"), ("two", "2"), ("two", "ii"), ("one", "1"), ("four", "iv")) </code></pre> <p>After applying aggregate:</p> <pre><code>Seq(("one" -&gt; Seq("i","1")), ("two" -&gt; Seq("2", "ii")), ("four" -&gt; Seq("iv")) </code></pre> <p>Also, can you give example of parameters <code>z</code>, <code>segop</code>, and <code>combop</code>? I'm unclear on what these parameters do.</p>
6,932,050
7
0
null
2011-08-03 14:47:30.347 UTC
28
2019-04-21 17:35:42.807 UTC
2016-08-12 21:43:27.533 UTC
null
442,945
null
235,820
null
1
36
scala|aggregate-functions
40,583
<p>The aggregate function does not do that (except that it is a very general function, and it could be used to do that). You want <code>groupBy</code>. Close to at least. As you start with a <code>Seq[(String, String)]</code>, and you group by taking the first item in the tuple (which is <code>(String, String) =&gt; String)</code>, it would return a <code>Map[String, Seq[(String, String)]</code>). You then have to discard the first parameter in the Seq[String, String)] values. </p> <p>So</p> <pre><code>list.groupBy(_._1).mapValues(_.map(_._2)) </code></pre> <p>There you get a <code>Map[String, Seq[(String, String)]</code>. If you want a <code>Seq</code> instead of <code>Map</code>, call <code>toSeq</code> on the result. I don't think you have a guarantee on the order in the resulting Seq though</p> <hr> <p>Aggregate is a more difficult function. </p> <p>Consider first reduceLeft and reduceRight. Let <code>as</code> be a non empty sequence <code>as = Seq(a1, ... an)</code> of elements of type <code>A</code>, and <code>f: (A,A) =&gt; A</code> be some way to combine two elements of type <code>A</code> into one. I will note it as a binary operator <code>@</code>, <code>a1 @ a2</code> rather than <code>f(a1, a2)</code>. <code>as.reduceLeft(@)</code> will compute <code>(((a1 @ a2) @ a3)... @ an)</code>. <code>reduceRight</code> will put the parentheses the other way, <code>(a1 @ (a2 @... @ an))))</code>. If <code>@</code> happens to be associative, one does not care about the parentheses. One could compute it as <code>(a1 @... @ ap) @ (ap+1 @...@an)</code> (there would be parantheses inside the 2 big parantheses too, but let's not care about that). Then one could do the two parts in parallel, while the nested bracketing in reduceLeft or reduceRight force a fully sequential computation. But parallel computation is only possible when <code>@</code> is known to be associative, and the reduceLeft method cannot know that. </p> <p>Still, there could be method <code>reduce</code>, whose caller would be responsible for ensuring that the operation is associative. Then <code>reduce</code> would order the calls as it sees fit, possibly doing them in parallel. Indeed, there is such a method. </p> <p>There is a limitation with the various reduce methods however. The elements of the Seq can only be combined to a result of the same type: <code>@</code> has to be <code>(A,A) =&gt; A</code>. But one could have the more general problem of combining them into a <code>B</code>. One starts with a value <code>b</code> of type <code>B</code>, and combine it with every elements of the sequence. The operator <code>@</code> is <code>(B,A) =&gt; B</code>, and one computes <code>(((b @ a1) @ a2) ... @ an)</code>. <code>foldLeft</code> does that. <code>foldRight</code> does the same thing but starting with <code>an</code>. There, the <code>@</code> operation has no chance to be associative. When one writes <code>b @ a1 @ a2</code>, it must mean <code>(b @ a1) @ a2</code>, as <code>(a1 @ a2)</code> would be ill-typed. So foldLeft and foldRight have to be sequential. </p> <p>Suppose however, that each <code>A</code> can be turned into a <code>B</code>, let's write it with <code>!</code>, <code>a!</code> is of type <code>B</code>. Suppose moreover that there is a <code>+</code> operation <code>(B,B) =&gt; B</code>, and that <code>@</code> is such that <code>b @ a</code> is in fact <code>b + a!</code>. Rather than combining elements with @, one could first transform all of them to B with <code>!</code>, then combine them with <code>+</code>. That would be <code>as.map(!).reduceLeft(+)</code>. And if <code>+</code> is associative, then that can be done with reduce, and not be sequential: as.map(!).reduce(+). There could be an hypothetical method as.associativeFold(b, !, +). </p> <p>Aggregate is very close to that. It may be however, that there is a more efficient way to implement <code>b@a</code> than <code>b+a!</code> For instance, if type <code>B</code> is <code>List[A]</code>, and b@a is a::b, then <code>a!</code> will be <code>a::Nil</code>, and <code>b1 + b2</code> will be <code>b2 ::: b1</code>. a::b is way better than (a::Nil):::b. To benefit from associativity, but still use <code>@</code>, one first splits <code>b + a1! + ... + an!</code>, into <code>(b + a1! + ap!) + (ap+1! + ..+ an!)</code>, then go back to using <code>@</code> with <code>(b @ a1 @ an) + (ap+1! @ @ an)</code>. One still needs the ! on ap+1, because one must start with some b. And the + is still necessary too, appearing between the parantheses. To do that, <code>as.associativeFold(!, +)</code> could be changed to <code>as.optimizedAssociativeFold(b, !, @, +)</code>.</p> <p>Back to <code>+</code>. <code>+</code> is associative, or equivalently, <code>(B, +)</code> is a semigroup. In practice, most of the semigroups used in programming happen to be monoids too, i.e they contain a neutral element <code>z</code> (for <em>zero</em>) in B, so that for each <code>b</code>, <code>z + b</code> = <code>b + z</code> = <code>b</code>. In that case, the <code>!</code> operation that make sense is likely to be be <code>a! = z @ a</code>. Moreover, as z is a neutral element <code>b @ a1 ..@ an = (b + z) @ a1 @ an</code> which is <code>b + (z + a1 @ an)</code>. So is is always possible to start the aggregation with z. If <code>b</code> is wanted instead, you do <code>b + result</code> at the end. With all those hypotheses, we can do a<code>s.aggregate(z, @, +)</code>. That is what <code>aggregate</code> does. <code>@</code> is the <code>seqop</code> argument (applied in a <em>sequence</em> <code>z @ a1 @ a2 @ ap</code>), and <code>+</code> is <code>combop</code> (applied to already partially <em>combined</em> results, as in <code>(z + a1@...@ap) + (z + ap+1@...@an)</code>). </p> <p>To sum it up, <code>as.aggregate(z)(seqop, combop)</code> computes the same thing as <code>as.foldLeft(z)( seqop)</code> provided that</p> <ul> <li><code>(B, combop, z)</code> is a monoid</li> <li><code>seqop(b,a) = combop(b, seqop(z,a))</code></li> </ul> <p>aggregate implementation may use the associativity of combop to group the computations as it likes (not swapping elements however, + has not to be commutative, ::: is not). It may run them in parallel. </p> <p>Finally, solving the initial problem using <code>aggregate</code> is left as an exercise to the reader. A hint: implement using <code>foldLeft</code>, then find <code>z</code> and <code>combo</code> that will satisfy the conditions stated above. </p>
6,929,662
How do I abort image <img> load requests without using window.stop()
<p>I have a very long page that dynamically loads images as users scroll through.</p> <p>However, if a user quickly scrolls away from a certain part of the page, I don't want the images to continue loading in that now out-of-view part of the page.</p> <p>There are lots of other requests happening on the page simultaneously apart from image loading, so a blunt window.stop() firing on the scroll event is not acceptable.</p> <p>I have tried removing &amp; clearing the img src attributes for images that are no longer in view, however, since the request was already started, the image continues to load.</p> <p>Remember that the image src was filled in as the user briefly scrolled past that part of the page. Once past though, I couldn't get that image from stop loading without using window.stop(). Clearing src didn't work. (Chrome &amp; FF)</p> <p>Similar posts I found that get close, but don't seem to solve this problem:</p> <ul> <li><a href="https://stackoverflow.com/questions/1339901/stop-loading-of-images-with-javascript-lazyload">Stop loading of images with javascript (lazyload)?</a></li> <li><a href="https://stackoverflow.com/questions/930237/javascript-cancel-stop-image-requests">Javascript: Cancel/Stop Image Requests</a> </li> <li><a href="https://stackoverflow.com/questions/5278304/how-to-cancel-an-image-from-loading">How to cancel an image from loading</a></li> </ul>
6,974,878
7
3
null
2011-08-03 16:13:06.697 UTC
16
2017-06-01 23:10:36.557 UTC
2017-05-23 12:00:24.427 UTC
null
-1
null
793,472
null
1
48
javascript|jquery|html|ajax|image
27,229
<p>What you are trying to do is the wrong approach, as mentioned by <a href="https://stackoverflow.com/users/380487/nrabinowitz">nrabinowitz</a>. You can't just "cancel" the loading process of an image (setting the <code>src</code> attribute to an empty string is <a href="http://www.nczonline.net/blog/2009/11/30/empty-image-src-can-destroy-your-site/" rel="nofollow noreferrer">not a good idea</a>). In fact, even if you could, doing so would only make things worst, as your server would continually send data that would get cancelled, increasing it's load factor and slow it down. Also, consider this:</p> <ol> <li>if your user scroll frenetically up and down the page, he/she will expect some loading delays.</li> <li>having a timeout delay (ex: 200 ms) before starting to load a portion of the page is pretty acceptable, and how many times will one stop and jump after 200 ms interval on your page? Even it it happens, it comes back to point 1</li> <li>how big are your images? Even a slow server can serve about a few tens of 3Kb thunbnails per second. If your site has bigger images, consider using low and hi resolution images with some components like <a href="http://leandrovieira.com/projects/jquery/lightbox/" rel="nofollow noreferrer">lightBox</a></li> </ol> <p>Often, computer problems are simply design problems.</p> <p>** <strong>EDIT</strong> **</p> <p>Here's an idea :</p> <ol> <li><p>your page should display <code>DIV</code> containers with the width and height of the expected image size (use CSS to style). Inside of each <code>DIV</code>, add an link. For example :</p> <pre><code>&lt;div class="img-wrapper thumbnail"&gt; &lt;a href="http://www.domain.com/path/to/image"&gt;Loading...&lt;/a&gt; &lt;/div&gt; </code></pre></li> <li><p>Add this Javascript (untested, the idea is self describing)</p> <pre><code>$(function() { var imgStack; var loadTimeout; $(window).scroll(function() { imgStack = null; if (loadTimeout) clearTimeout(loadTimeout); loadTimeout = setTimeout(function() { // get all links visible in the view port // should be an array or jQuery object imgStack = ... loadNextImage(); }, 200); // 200 ms delay }); function loadNextImage() { if (imgStack &amp;&amp; imgStack.length) { var nextLink = $(imgStack.pop()); // get next image element $('&lt;img /&gt;').attr('src', nextLink.attr('href')) .appendTo(nextLink.parent()) .load(function() { loadNextImage(); }); // remove link from container (so we don't precess it twice) nextLink.remove(); } }; }); </code></pre></li> </ol>
38,442,901
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
<p>I am getting this kind of error, how to fix it.</p> <pre><code>Error:Unable to load class 'org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection'. Possible causes for this unexpected error Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync project (requires network)The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build processes (requires restart)Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes. </code></pre>
42,622,353
40
2
null
2016-07-18 17:41:54.393 UTC
31
2021-05-06 13:42:26.277 UTC
2016-07-22 13:31:45.3 UTC
null
2,741,598
null
4,693,397
null
1
111
android|gradle|gradle-plugin
204,057
<p>I updated my Android Studio to 2.3 and it asked me to update my gradle plugin to 3.3 that created issues with my running projects. I've gone through all the Stack solutions and nothing worked for me except this workaround: <strong>I changed my distribution url in gradle-wrapper.properties with this one.</strong></p> <pre><code>distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip </code></pre> <p>(permanent link list here : <a href="https://services.gradle.org/distributions/" rel="noreferrer">https://services.gradle.org/distributions/</a>)</p> <p>My project is up and running.It just asked me to update to <strong>gradle build tools 25.0.0</strong> which I did so. Everything is fine now :)</p> <ol> <li>Go to the project section and select gradle scripts menu.</li> <li>Under script, menu select gradle -wrapper.properties</li> <li>Then replace the distributionUrl=https://services.gradle.org/distributions/gradle-2.2-all.zip with "distributionUrl=https://services.gradle.org/distributions/gradle-3.4.1-all.zip"</li> </ol> <p><a href="https://i.stack.imgur.com/5Ow8f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5Ow8f.png" alt="enter image description here"></a> note: <strong>distributions gradle will change depended upon the version of the android studio.</strong> </p>
15,675,689
How to upload a file to Google Drive
<p>So im trying to upload a text file to my google drive from an android app I am creating. I learned how to upload a picture from the Google tutorial. Also, I will be using the strings from my app in the text file. Potentially, I want to make it a spreadsheet. Any help?</p>
15,676,970
2
0
null
2013-03-28 06:38:44.96 UTC
10
2021-06-25 21:26:28.917 UTC
2013-03-28 08:00:41.587 UTC
null
2,178,759
null
2,178,759
null
1
14
android|google-drive-api
46,316
<p>Read <a href="https://developers.google.com/drive/quickstart-android" rel="noreferrer">Quick Start</a> on Google Android site. </p> <p>When you are done with all the authentication process, go for <a href="https://developers.google.com/drive/manage-uploads" rel="noreferrer">How to upload file to Google Drive</a>.</p> <p><strong>Edit</strong></p> <p>Reference Links</p> <ul> <li><a href="https://code.google.com/p/google-drive-sdk-samples/" rel="noreferrer">https://code.google.com/p/google-drive-sdk-samples/</a></li> <li><a href="https://stackoverflow.com/questions/12164024/android-open-and-save-files-to-from-google-drive-sdk">Android Open and Save files to/from Google Drive SDK</a></li> <li><a href="http://mavenrepo.google-api-java-client.googlecode.com/hg/com/google/apis/google-api-services-drive/v2-rev9-1.8.0-beta/" rel="noreferrer">http://mavenrepo.google-api-java-client.googlecode.com/hg/com/google/apis/google-api-services-drive/v2-rev9-1.8.0-beta/</a></li> </ul>
15,962,745
Draw a semicircle in the background of a View
<p>I am trying to create a TextView whose background is a half circle. I create a oval using a ShapeDrawable. I tried to create a semicircle by using ScaleDrawable to double the size vertical size of the oval and clip it. However, the ScaleDrawable has no effect. Why not? What is the best way to draw a semicircle in the background of a View?</p> <p><strong>res/layout/activity_main.xml</strong></p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;TextView android:id="@+id/main_view" android:background="@drawable/semicircle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:gravity="center_horizontal" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>res/drawable/semicircle.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;scale xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/circle" android:scaleGravity="top|clip_vertical" android:scaleHeight="200%" android:scaleWidth="100%" &gt; &lt;/scale&gt; </code></pre> <p><strong>res/drawable/circle.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" &lt;solid android:color="#444" /&gt; &lt;/shape&gt; </code></pre> <p><strong>src/.../MainActivity.java</strong></p> <pre><code>//... public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); findViewById(R.id.main_view).getBackground().setLevel(10000); } //... </code></pre>
15,963,620
5
1
null
2013-04-12 03:51:32.773 UTC
14
2021-05-25 15:47:39.6 UTC
2013-04-12 03:59:40.193 UTC
null
766,900
null
766,900
null
1
19
android
38,741
<p>You can implement you own Drawable. But that cannot be inflated from XML. You need to set the drawable from code using View.setBackgroundDrawable();</p> <p>See my sample implementation to draw a semi circle using drawable.</p> <pre><code>public class SemiCircleDrawable extends Drawable { private Paint paint; private RectF rectF; private int color; private Direction angle; public enum Direction { LEFT, RIGHT, TOP, BOTTOM } public SemiCircleDrawable() { this(Color.BLUE, Direction.LEFT); } public SemiCircleDrawable(int color, Direction angle) { this.color = color; this.angle = angle; paint = new Paint(); paint.setColor(color); paint.setStyle(Style.FILL); paint.setAntiAlias(true); rectF = new RectF(); } public int getColor() { return color; } /** * A 32bit color not a color resources. * @param color */ public void setColor(int color) { this.color = color; paint.setColor(color); } @Override public void draw(Canvas canvas) { canvas.save(); Rect bounds = getBounds(); if(angle == Direction.LEFT || angle == Direction.RIGHT) { canvas.scale(2, 1); if(angle == Direction.RIGHT) { canvas.translate(-(bounds.right / 2), 0); } } else { canvas.scale(1, 2); if(angle == Direction.BOTTOM) { canvas.translate(0, -(bounds.bottom / 2)); } } rectF.set(bounds); if(angle == Direction.LEFT) canvas.drawArc(rectF, 90, 180, true, paint); else if(angle == Direction.TOP) canvas.drawArc(rectF, -180, 180, true, paint); else if(angle == Direction.RIGHT) canvas.drawArc(rectF, 270, 180, true, paint); else if(angle == Direction.BOTTOM) canvas.drawArc(rectF, 0, 180, true, paint); canvas.restore() } @Override public void setAlpha(int alpha) { // Has no effect } @Override public void setColorFilter(ColorFilter cf) { // Has no effect } @Override public int getOpacity() { // Not Implemented return PixelFormat.UNKNOWN; } } </code></pre>
15,952,812
Multiple command parameters wpf button object
<p>How can I send multiple parameters from <code>Button</code> in <code>WPF</code>? I am able to send single parameter which is value of <code>TextBox</code> properly. Here is the code.</p> <p><code>XAML</code></p> <pre><code>&lt;TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="133,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /&gt; &lt;Button Content="Button" Grid.Row="1" Height="23" Command="{Binding Path=CommandClick}" CommandParameter="{Binding Text,ElementName=textBox1}" HorizontalAlignment="Left" Margin="133,62,0,0" Name="button1" VerticalAlignment="Top" Width="75" /&gt; </code></pre> <p><code>Code behind</code></p> <pre><code>public ICommand CommandClick { get; set; } this.CommandClick = new DelegateCommand&lt;object&gt;(AddAccount); private void AddAccount(object obj) { //custom logic } </code></pre>
15,952,864
2
4
null
2013-04-11 15:27:37.463 UTC
6
2017-11-13 07:45:51.503 UTC
2013-07-06 16:30:28.023 UTC
null
2,176,945
null
945,175
null
1
20
c#|wpf|button|mvvm|icommand
42,270
<blockquote> <p>How can i send multiple parameters from button in wpf. </p> </blockquote> <p>You can only send one parameter as the <code>CommandParameter</code>.</p> <p>A better solution is typically to just bind the <code>TextBox</code> and other controls to multiple properties in your ViewModel. The command would then have access to all of those properties (since it's in the same class), with no need for a command parameter at all.</p>
15,907,079
CSS3 Transition - Fade out effect
<p>I am trying to implement the "fade out" effect in pure CSS. Here is the <a href="http://jsfiddle.net/dYBD2/" rel="noreferrer">fiddle</a>. I did look into a couple of solutions online, however, after reading the <a href="http://www.w3schools.com/css3/css3_animations.asp" rel="noreferrer">documentation online</a>, I am trying to figure out why the slide animation would not work. Any pointers?</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-css lang-css prettyprint-override"><code>.dummy-wrap { animation: slideup 2s; -moz-animation: slideup 2s; -webkit-animation: slideup 2s; -o-animation: slideup 2s; } .success-wrap { width: 75px; min-height: 20px; clear: both; margin-top: 10px; } .successfully-saved { color: #FFFFFF; font-size: 20px; padding: 15px 40px; margin-bottom: 20px; text-align: center; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background-color: #00b953; } @keyframes slideup { 0% {top: 0px;} 75% {top: 0px;} 100% {top: -20px;} } @-moz-keyframes slideup { 0% {top: 0px;} 75% {top: 0px;} 100% {top: -20px;} } @-webkit-keyframes slideup { 0% {top: 0px;} 75% {top: 0px;} 100% {top: -20px;} } @-o-keyframes slideup { 0% {top: 0px;} 75% {top: 0px;} 100% {top: -20px;} }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="dummy-wrap"&gt; &lt;div class="success-wrap successfully-saved"&gt;Saved&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
16,611,735
8
0
null
2013-04-09 16:10:52.48 UTC
36
2022-02-02 07:58:49.637 UTC
2020-05-20 06:24:54.577 UTC
null
6,904,888
user2246087
null
null
1
126
css|css-transitions
472,975
<p>You can use transitions instead:</p> <pre><code>.successfully-saved.hide-opacity{ opacity: 0; } .successfully-saved { color: #FFFFFF; text-align: center; -webkit-transition: opacity 3s ease-in-out; -moz-transition: opacity 3s ease-in-out; -ms-transition: opacity 3s ease-in-out; -o-transition: opacity 3s ease-in-out; opacity: 1; } </code></pre>
36,233,477
Implementing an interface with two abstract methods by a lambda expression
<p>In Java 8 the <strong><em>lambda expression</em></strong> is introduced to help with the reduction of boilerplate code. If the interface has only one method it works fine. If it consists of multiple methods, then none of the methods work. How can I handle multiple methods? </p> <p>We may go for the following example</p> <pre><code>public interface I1() { void show1(); void show2(); } </code></pre> <p>Then what will be the structure of the main function to define the methods in the main itself?</p>
36,233,545
4
6
null
2016-03-26 09:03:47.573 UTC
8
2018-12-06 14:10:54.013 UTC
2017-03-01 03:33:27.063 UTC
null
4,539,511
null
4,999,323
null
1
32
java|lambda|java-8|functional-interface
13,650
<p>Lambda expressions are only usable with functional interface as said by Eran but if you really need multiple methods within the interfaces, you may change the modifiers to <code>default</code> or <code>static</code> and override them within the classes that implement them if necessary.</p> <pre><code>public class Test { public static void main(String[] args) { I1 i1 = () -&gt; System.out.println(); // NOT LEGAL I2 i2 = () -&gt; System.out.println(); // TOTALLY LEGAL I3 i3 = () -&gt; System.out.println(); // TOTALLY LEGAL } } interface I1 { void show1(); void show2(); } interface I2 { void show1(); default void show2() {} } interface I3 { void show1(); static void show2 () {} } </code></pre> <hr> <h2>Inheritance</h2> <p>You shouldn't forget the inherited methods.</p> <p>Here, <code>I2</code> inherits <code>show1</code> and <code>show2</code> and thus can not be a functional interface.</p> <pre><code>public class Test { public static void main(String[] args) { I1 i1 = () -&gt; System.out.println(); // NOT LEGAL BUT WE SAW IT EARLIER I2 i2 = () -&gt; System.out.println(); // NOT LEGAL } } interface I1 { void show1(); void show2(); } interface I2 extends I1 { void show3(); } </code></pre> <hr> <h2>Annotation</h2> <p>To make sure your interface is a functional interface, you may add the following annotation <code>@FunctionalInterface</code></p> <pre><code>@FunctionalInterface &lt;------- COMPILATION ERROR : Invalid '@FunctionalInterface' annotation; I1 is not a functional interface interface I1 { void show1(); void show2(); } @FunctionalInterface interface I2 { void show3(); } </code></pre>
50,298,114
Django 2 - How to register a user using email confirmation and CBVs?
<p>This question specifically aims for a Django 2.0 answer as the <code>registration</code> module isn't available (yet) for it.</p> <p><em>More, this might seem to broad, but I often found myself in situations where I can't use any 3rd party module because ... oh well..policies. I'm sure many did. And I know that looking and putting together information taken from here or django docs was a headache.</em></p> <hr /> <h3>Workflow:</h3> <p>Let's suppose we need the following flow:</p> <ol> <li>The user goes to the sign-up page and fills in the following fields: <code>first_name</code>, <code>last_name</code> and <code>email</code> (the email will be used as the username).</li> <li>The user submits the form and receives a confirmation email with an URL containing a unique token.</li> <li>When the user clicks on the received link, he's redirected to a page where he'll set his password. When done, he's logged in to the dashboard page.</li> </ol> <p><em>Extra-info: The user will later log in by using his email (which is actually his username) and password.</em></p> <hr /> <h3>Specific question:</h3> <ul> <li>How will the models/views (using CBVs)/forms/urls look like?</li> </ul>
50,330,016
3
4
null
2018-05-11 18:20:28.563 UTC
16
2020-08-20 23:18:41.133 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,316,077
null
1
21
python|django|authentication
14,286
<h2>The User Model</h2> <p>First, you will need to create a custom <code>User</code> model and a custom <code>UserManager</code> to remove the <code>username</code> field and use <code>email</code> instead.</p> <p>In <code>models.py</code> the <code>UserManager</code> should look like this:</p> <pre><code>from django.contrib.auth.models import BaseUserManager class MyUserManager(BaseUserManager): &quot;&quot;&quot; A custom user manager to deal with emails as unique identifiers for auth instead of usernames. The default that's used is &quot;UserManager&quot; &quot;&quot;&quot; def _create_user(self, email, password, **extra_fields): &quot;&quot;&quot; Creates and saves a User with the given email and password. &quot;&quot;&quot; if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) </code></pre> <p>And the <code>User</code> model:</p> <pre><code>from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) USERNAME_FIELD = 'email' objects = MyUserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email </code></pre> <p>And finally in <code>settings.py</code>:</p> <pre><code>AUTH_USER_MODEL = 'your_app_name.User' </code></pre> <hr /> <h2>The Token Generator</h2> <p>Second part is to create a token generator for the email confirmation url. We can inherit the built-in <code>PasswordResetTokenGenerator</code> to make it easier.</p> <p>Create <code>tokens.py</code>:</p> <pre><code>from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() </code></pre> <hr /> <h2>The Signup Form</h2> <p>Then you should create a registration form to use in our views. Best way is to inherit the built-in Django's <code>UserCreationForm</code> and to remove the <code>username</code> and <code>password</code> fields from it and then add an <code>email</code> field. <code>forms.py</code>:</p> <pre><code>from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('email', 'first_name', 'last_name') </code></pre> <hr /> <h2>The Signup View</h2> <p>In the sign up you should make the user inactive <code>user.is_active = False</code> with no password <code>set_unusable_password()</code> until the user complete the activation. Also, we are going to construct an activation URL and email it to the user after completing the registration.</p> <p>in <code>views.py</code>:</p> <pre><code>from django.views import View from django.http import HttpResponse from django.shortcuts import render from .forms import SignupForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from .tokens import account_activation_token from django.core.mail import EmailMessage class Signup(View): def get(self, request): form = SignupForm() return render(request, 'signup.html', {'form': form}) def post(self, request): form = SignupForm(request.POST) if form.is_valid(): # Create an inactive user with no password: user = form.save(commit=False) user.is_active = False user.set_unusable_password() user.save() # Send an email to the user with the token: mail_subject = 'Activate your account.' current_site = get_current_site(request) uid = urlsafe_base64_encode(force_bytes(user.pk)) token = account_activation_token.make_token(user) activation_link = &quot;{0}/?uid={1}&amp;token{2}&quot;.format(current_site, uid, token) message = &quot;Hello {0},\n {1}&quot;.format(user.username, activation_link) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') </code></pre> <p>And of course, don't forget to create a template for you signup view.</p> <hr /> <h2>The Activation View</h2> <p>Then you should create a view for the user to activate his account using the URL we created in the sign up view. We will also use the built-in Django's <code>SetPasswordForm</code> to allow users to set their passwords.</p> <p>In <code>views.py</code>:</p> <pre><code>from django.contrib.auth import get_user_model, login, update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from .tokens import account_activation_token User = get_user_model() class Activate(View): def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): # activate user and login: user.is_active = True user.save() login(request, user) form = PasswordChangeForm(request.user) return render(request, 'activation.html', {'form': form}) else: return HttpResponse('Activation link is invalid!') def post(self, request): form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important, to update the session with the new password return HttpResponse('Password changed successfully') </code></pre> <p>Again, don't forget to create a template for your activation view.</p> <hr /> <h2>The URLs</h2> <p>Finally, in <code>urls.py</code>:</p> <pre><code>from . import views from django.urls import path urlpatterns = [ ... path('signup/', views.signup.as_view(), name='signup'), path('activate/&lt;str:uid&gt;/&lt;str:token&gt;', views.activate.as_view(), name='activate'), ] </code></pre> <hr /> <p>P.S. Honestly, I didn't get a chance to test all this parts together yet but don't hesitate to ask if any problem happened.</p>
25,127,468
Android: Placing ImageView on overlap between layouts
<p>I am trying to place an <code>ImageView</code> on the overlap point between two layouts. In the picture below, my goal would be to place the <code>ImageView</code> where the white square is. <b>NOTE: The overlap point will not necessarily be centered vertically as shown below</b></p> <p><img src="https://i.stack.imgur.com/ofS7G.jpg" alt="enter image description here"></p> <p>Is this possible in XML?</p> <p>My only guess right now is to do this in the actual code itself.</p> <p>EDIT 8/3/2016: For reference, I think <code>ConstraintLayouts</code> may be the best future solution for these types of problems <a href="http://tools.android.com/tech-docs/layout-editor" rel="noreferrer">http://tools.android.com/tech-docs/layout-editor</a></p>
25,143,739
4
6
null
2014-08-04 21:01:39.383 UTC
8
2022-01-14 16:19:32.673 UTC
2016-08-03 17:43:34.547 UTC
null
3,019,655
null
3,019,655
null
1
15
android|android-layout|android-xml
19,239
<p>This will do what you want, with either an image of fixed height, or calculated programatically.</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;RelativeLayout android:id="@+id/layoutTop" android:layout_width="match_parent" android:layout_height="200dp" &gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout android:id="@+id/layoutBottom" android:layout_width="match_parent" android:layout_height="0dp" android:layout_alignParentBottom="true" android:layout_below="@id/layoutTop" &gt; &lt;/RelativeLayout&gt; &lt;ImageView android:id="@+id/overlapImage" android:layout_width="wrap_content" android:layout_height="40dp" android:layout_above="@id/layoutBottom" android:layout_centerHorizontal="true" android:layout_marginBottom="-20dp" &lt;!-- This should be always half the height, can also be calculated and added programtically --&gt; android:adjustViewBounds="true" android:src="@drawable/ic_launcher" /&gt; &lt;/RelativeLayout&gt; </code></pre>
37,876,288
Is there a one-liner to unpack tuple/pair into references?
<p>I frequently write snippets like</p> <pre><code>int x,y,z; tie(x,y,z) = g[19]; </code></pre> <p>where, for instance, <code>g</code> was declared earlier</p> <pre><code>vector&lt;tuple&lt;int,int,int&gt;&gt; g(100); </code></pre> <p>Problem is, maybe later I actually want <code>x</code> and <code>y</code> to point to the internals of <code>g</code> by reference, and the refactoring is ugly, e.g.</p> <pre><code>int &amp;x = get&lt;0&gt;(g[19]); int &amp;y = get&lt;1&gt;(g[19]); int &amp;z = get&lt;2&gt;(g[19]); </code></pre> <p>or sometimes even worse, for instance if the access is a more complex expression</p> <pre><code>tuple&lt;int,int,int&gt; &amp;p = g[19]; // if the rhs was actually more complicated int &amp;x = get&lt;0&gt;(p); int &amp;y = get&lt;1&gt;(p); int &amp;z = get&lt;2&gt;(p); </code></pre> <p>Is there a better refactoring, more in the style of the assignment to tie(..)? </p> <p>The difficulty as I understand it is that references insist on being initialized <a href="http://en.cppreference.com/w/cpp/language/reference_initialization">exactly at their declaration</a>. So, in possibly other words, is there a way to use <code>tie</code>-like syntax for multiple variable <em>initialization</em> in c++ (this would also make the earlier non reference usage cleaner)?</p>
45,866,028
3
6
null
2016-06-17 08:06:23.867 UTC
7
2018-08-20 23:28:39.087 UTC
null
null
null
null
6,478,097
null
1
46
c++
19,845
<p>Fortunately, C++17 has a solution for exactly this problem, the <a href="http://en.cppreference.com/w/cpp/language/structured_binding" rel="noreferrer">structured binding declaration</a>. Even the non-reference interface can be improved.</p> <pre><code>auto[x, y, z] = g[i]; </code></pre> <p>The above line declares x, y,z and initializes them with the values of <code>g[i]</code>. Not only is it cleaner, but it could be more efficient for types that are expensive to construct.</p> <p>To get references to the members of <code>g[i]</code>, one can write</p> <pre><code>auto&amp; [x, y, z] = g[i]; </code></pre>
37,714,152
How to select range of columns in a dataframe based on their name and not their indexes?
<p>In a pandas dataframe created like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(10, size=(6, 6)), columns=['c' + str(i) for i in range(6)], index=["r" + str(i) for i in range(6)]) </code></pre> <p>which could look as follows:</p> <pre><code> c0 c1 c2 c3 c4 c5 r0 2 7 3 3 2 8 r1 6 9 6 7 9 1 r2 4 0 9 8 4 2 r3 9 0 4 3 5 4 r4 7 6 8 8 0 8 r5 0 6 1 8 2 2 </code></pre> <p>I can easily select certain rows and/or a range of columns using <code>.loc</code>:</p> <pre><code>print df.loc[['r1', 'r5'], 'c1':'c4'] </code></pre> <p>That would return:</p> <pre><code> c1 c2 c3 c4 r1 9 6 7 9 r5 6 1 8 2 </code></pre> <p>So, particular rows/columns I can select in a list, a range of rows/columns using a colon.</p> <p>How would one do this in R? <a href="https://stackoverflow.com/questions/10085806/extracting-specific-columns-from-a-data-frame">Here</a> and <a href="https://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame">here</a> one always has to specify the desired range of columns by their index but one cannot - or at least I did not find it - access those by name. To give an example:</p> <pre><code>df &lt;- data.frame(c1=1:6, c2=2:7, c3=3:8, c4=4:9, c5=5:10, c6=6:11) rownames(df) &lt;- c('r1', 'r2', 'r3', 'r4', 'r5', 'r6') </code></pre> <p>The command</p> <pre><code>df[c('r1', 'r5'),'c1':'c4'] </code></pre> <p>does not work and throws an error. The only thing that worked for me is</p> <pre><code>df[c('r1', 'r5'), 1:4] </code></pre> <p>which returns</p> <pre><code> c1 c2 c3 c4 r1 1 2 3 4 r5 5 6 7 8 </code></pre> <p>But how would I select the columns by their name and not by their index (which might be important when I drop certain columns throughout the analysis)? In this particular case I could of course use <code>grep</code> but how about columns that have arbitrary names?</p> <p>So I don't want to use </p> <pre><code>df[c('r1', 'r5'),c('c1','c2', 'c3', 'c4')] </code></pre> <p>but an actual slice.</p> <p>EDIT:</p> <p>A follow-up question can be found <a href="https://stackoverflow.com/questions/37715085/how-to-slice-a-dataframe-by-selecting-a-range-of-columns-and-rows-based-on-names">here</a>.</p>
37,714,216
5
7
null
2016-06-08 22:45:40.797 UTC
1
2017-04-25 22:12:01.53 UTC
2017-05-23 12:17:56.673 UTC
null
-1
null
1,534,017
null
1
5
r|dataframe|subset|code-conversion
39,657
<p>It looks like you can accomplish this with a <code>subset</code>:</p> <pre><code>&gt; df &lt;- data.frame(c1=1:6, c2=2:7, c3=3:8, c4=4:9, c5=5:10, c6=6:11) &gt; rownames(df) &lt;- c('r1', 'r2', 'r3', 'r4', 'r5', 'r6') &gt; subset(df, select=c1:c4) c1 c2 c3 c4 r1 1 2 3 4 r2 2 3 4 5 r3 3 4 5 6 r4 4 5 6 7 r5 5 6 7 8 r6 6 7 8 9 &gt; subset(df, select=c1:c2) c1 c2 r1 1 2 r2 2 3 r3 3 4 r4 4 5 r5 5 6 r6 6 7 </code></pre> <p>If you want to subset by row name range, this hack would do:</p> <pre><code>&gt; gRI &lt;- function(df, rName) {which(match(rNames, rName) == 1)} &gt; df[gRI(df,"r2"):gRI(df,"r4"),] c1 c2 c3 c4 c5 c6 r2 2 3 4 5 6 7 r3 3 4 5 6 7 8 r4 4 5 6 7 8 9 </code></pre>
38,009,060
Is List<?> the common parent of List<Integer> and List<Number>?
<p>From <a href="https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html">this Oracle tutorial</a>,</p> <blockquote> <p>Although <code>Integer</code> is a subtype of <code>Number</code>, <code>List&lt;Integer&gt;</code> is not a subtype of <code>List&lt;Number&gt;</code> and, in fact, these two types are not related.</p> <p>The common parent of <code>List&lt;Number&gt;</code> and <code>List&lt;Integer&gt;</code> is <code>List&lt;?&gt;</code>.</p> </blockquote> <p>My question is about the second sentence. <strong>How can we say that <code>List&lt;?&gt;</code> is the common parent of <code>List&lt;Number&gt;</code> and <code>List&lt;Integer&gt;</code>?</strong></p> <p><code>?</code> stands for an unknown type, which could be <em>any</em> reference type. Even if I say that <code>?</code> would be <code>Object</code> here, <code>Object</code> being the common parent of <code>Integer</code> and <code>Number</code> does NOT mean that <code>List&lt;Object&gt;</code> becomes a common parent of <code>List&lt;Integer&gt;</code> and <code>List&lt;Number&gt;</code>.</p>
38,009,294
5
14
null
2016-06-24 08:40:15.47 UTC
10
2016-06-29 12:08:37.86 UTC
2016-06-24 23:44:48.647 UTC
null
63,550
null
3,395,512
null
1
42
java|generics|inheritance|polymorphism
3,111
<p>The context you need to understand is not of <code>Integer</code> or <code>Number</code> but it's the <strong><code>List</code></strong>. Let's suppose you were the one creating the <code>List</code> class then how would you create the class so it will only support a specific type of class. </p> <p>Yes, that <code>List</code> class won't use Object as its type but instead use a wild card <code>?</code>.</p> <p>As <a href="http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html">documentation of WildCards</a> say </p> <blockquote> <p>So what is the supertype of all kinds of collections? It's written <code>Collection&lt;?&gt;</code> (pronounced "collection of unknown")</p> </blockquote> <p>Same thing can be said for List.</p> <blockquote> <p>So what is the supertype of all kinds of Lists? It's written <code>List&lt;?&gt;</code> (pronounced "List of unknown")</p> </blockquote>
35,452,178
What can `__init__` do that `__new__` cannot?
<p>In Python, <code>__new__</code> is used to initialize immutable types and <code>__init__</code> typically initializes mutable types. If <code>__init__</code> were removed from the language, what could no longer be done (easily)?</p> <p>For example,</p> <pre><code>class A: def __init__(self, *, x, **kwargs): super().__init__(**kwargs) self.x = x class B(A): def __init__(self, y=2, **kwargs): super().__init__(**kwargs) self.y = y </code></pre> <p>Could be rewritten using <code>__new__</code> like this:</p> <pre><code>class A_N: def __new__(cls, *, x, **kwargs): obj = super().__new__(cls, **kwargs) obj.x = x return obj class B_N(A_N): def __new__(cls, y=2, **kwargs): obj = super().__new__(cls, **kwargs) obj.y = y return obj </code></pre> <hr> <p>Clarification for scope of question: This is not a question about how <code>__init__</code> and <code>__new__</code> are used or what is the difference between them. This is a question about what would happen if <code>__init__</code> were removed from the language. Would anything break? Would anything become a lot harder or impossible to do?</p>
35,452,516
3
9
null
2016-02-17 09:09:05.063 UTC
4
2020-05-09 02:41:57.213 UTC
2016-02-17 09:40:51.827 UTC
null
99,989
null
99,989
null
1
30
python|initialization
3,091
<p>Everything you can do in <code>__init__</code> can also be done in <code>__new__</code>.</p> <p>Then, why use <code>__init__</code>?<br> Because you don't have to store instance in variable (<code>obj</code> in your example code), and later bother returning it. You can focus on what you realy want to do &ndash; initializing mutable object.</p>
22,666,828
No "pull" in Git Gui?
<p>How can I make a pull using Git GUI tool? It seems there is no pull command anywhere.</p> <p>Is there an equivalent menu option using Git GUI?</p> <p>Any help will be appreciated.</p>
22,666,879
3
2
null
2014-03-26 16:07:52.203 UTC
23
2022-06-06 06:51:45.397 UTC
2014-03-26 16:16:38.13 UTC
null
261,122
null
2,848,629
null
1
132
git-pull|git-gui
98,758
<p>Well, I found this useful forum post: <a href="https://web.archive.org/web/20200211180001/http://git.661346.n2.nabble.com/No-quot-pull-quot-in-git-gui-td1121058.html" rel="noreferrer">https://web.archive.org/web/20200211180001/http://git.661346.n2.nabble.com/No-quot-pull-quot-in-git-gui-td1121058.html</a></p> <p>A fetch and merge should be done.</p> <p>It seems you need to go to &quot;Remote&quot; menu, then &quot;Fetch from&quot; option , in my case origin, and then go to &quot;Merge Menu&quot; and then &quot;Local Merge...&quot;.</p>
13,579,632
Android: Date (year,month,day)
<p>I want to get the date as a <em>year, month ,day</em> without hours or minutes or any thing else, and I don't want to get the year alone and the month and the day each by its self. Because as a full date I need it to comparison with another date </p> <p>such as today <code>28.11.2012</code> and to compare it to <code>11.12.2011</code> as if today minus <code>11.12.2011</code> more than 280 day I want to execute some code</p>
13,579,719
5
5
null
2012-11-27 07:53:43.92 UTC
null
2020-04-23 15:56:36.503 UTC
2012-11-28 07:08:29.117 UTC
null
1,838,457
null
1,838,457
null
1
9
android|date|calendar|gettime
42,169
<p>you can use <code>SimpleDateFormat</code>.</p> <p>The basics for getting the current date </p> <pre><code>DateFormat df = new SimpleDateFormat("MMM d, yyyy"); String now = df.format(new Date()); </code></pre> <p>or</p> <pre><code>DateFormat df = new SimpleDateFormat("MM/dd/yy"); String now = df.format(new Date()); </code></pre> <p><strong>EDITED :</strong> First of All you have the date in String Formate. you have to Convert into date Formate. try below code to do that. you have apply same for both the String <strong>strThatDay</strong> &amp; <strong>strTodaDay</strong> you will get Calender Object for both.</p> <pre><code>String strThatDay = "2012/11/27"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); Date d = null; try { d = formatter.parse(strThatDay);//catch exception } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar thatDay = Calendar.getInstance(); thatDay.setTime(d); </code></pre> <p>after that try below code to get Day from two Date :</p> <pre><code>long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis long days = diff / (24 * 60 * 60 * 1000); </code></pre> <p>try it out. Hope it will help you.</p>
13,458,992
Angle between two Vectors 2D
<p>I'm trying to compute the angle between two vectors. I tried this, but it always returns zero:</p> <pre><code>public double GetAngle(Vector2 a, Vector2 b) { double angle = Math.Atan2(b.Y, b.X) - Math.Atan2(a.Y, a.X); return angle; } GetAngle(new Vector2(1,1), new Vector2(50,50)); </code></pre> <p><a href="https://i.stack.imgur.com/sVPA2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sVPA2.png" alt="Vectors" /></a><a href="https://i.stack.imgur.com/77Mf3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/77Mf3.png" alt="The angle I need" /></a></p>
13,459,068
9
5
null
2012-11-19 17:27:20.637 UTC
5
2022-08-24 19:27:48.267 UTC
2022-04-11 09:24:29.537 UTC
null
4,298,200
null
1,697,953
null
1
15
c#|vector|xna
56,560
<p>You should take a look at the documentation of <code>atan2</code> (<a href="http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx" rel="noreferrer">here</a>).</p> <p>What you're looking of is finding the difference between B (your upper left vector) and A (your bottom right vector), then pass this as a parameter to <code>atan2</code></p> <pre><code>return Math.Atan2(b.Y - a.Y, b.X - a.X); </code></pre> <p>What your code currently does is find the angle of the vector <code>b</code> in reference to <code>0,0</code> and subtract the angle of the vector <code>a</code> in reference to <code>0,0</code>.</p> <p>The reason you always get 0 is because <code>1,1</code> and <code>50,50</code> are on the same line that crosses <code>0,0</code> (both calls return something approx. <code>0.785398</code>), so subtracting them will result in <code>0</code></p>
13,784,434
How to use OpenSSL's SHA256 functions
<p>I'm writing a program to get myself acquainted with OpenSSL, libncurses, and UDP networking. I decided to work with OpenSSL's SHA256 to become familiar with industry encryption standards, but I'm having issues with getting it working. I've isolated the error to the linking of OpenSSL with the compiled program. I'm working on Ubuntu 12.10, 64 bit. I have the package libssl-dev installed.</p> <p>Take, for instance, the C++ main.cpp:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;iomanip&gt; using namespace std; #include &lt;openssl/sha.h&gt; string sha256(const string str) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&amp;sha256); SHA256_Update(&amp;sha256, str.c_str(), str.size()); SHA256_Final(hash, &amp;sha256); stringstream ss; for(int i = 0; i &lt; SHA256_DIGEST_LENGTH; i++) { ss &lt;&lt; hex &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; (int)hash[i]; } return ss.str(); } int main() { cout &lt;&lt; sha256("test") &lt;&lt; endl; cout &lt;&lt; sha256("test2") &lt;&lt; endl; return 0; } </code></pre> <p>I'm using the SHA256() function found <a href="https://stackoverflow.com/questions/2262386/generate-sha256-with-openssl-and-c">here</a> as a wrapper for OpenSSL's SHA256 functionality.</p> <p>When I attempt to compile with the following g++ arguments, I receive the following error:</p> <pre><code>millinon@myhost:~/Programming/sha256$ g++ -lssl -lcrypto -o main main.cpp /tmp/ccYqwPUC.o: In function `sha256(std::string)': main.cpp:(.text+0x38): undefined reference to `SHA256_Init' main.cpp:(.text+0x71): undefined reference to `SHA256_Update' main.cpp:(.text+0x87): undefined reference to `SHA256_Final' collect2: error: ld returned 1 exit status </code></pre> <p>So, GCC clearly recognizes OpenSSL's defined functions and types, but ld is failing to find the function symbols referred to in sha.h.</p> <p>Do I need to manually point to a specific shared object or directory?</p> <p>Thanks!</p>
13,784,484
2
0
null
2012-12-09 03:47:05.427 UTC
5
2017-10-09 02:23:09.133 UTC
2017-10-09 02:23:09.133 UTC
null
608,639
null
1,633,848
null
1
16
c++|gcc|openssl|sha256
41,271
<p>You make a very common beginners mistake... Putting the libraries you link with in the wrong place on the command line when you build.</p> <p>Dependencies are reversed on the command line, so something that depends on something else should actually be put <em>before</em> what it depends on on the command line.</p> <p>In your example, you have a source file <code>main.cpp</code> that depends on some set of libraries, then the source file should be before the libraries it depend on:</p> <pre><code>$ g++ -o main main.cpp -lssl -lcrypto </code></pre> <p>To be safe, always put libraries <em>last</em>, after any source or object files listed on the command line.</p>
13,320,011
Bootstrap modal dismiss if user click anywhere else..how to prevent this?
<p>I am using Twitter's Bootstrap modal.</p> <p>The modal is dismissed whenever the user clicks anywhere else on the screen except the modal.</p> <p>Is there a way I can prevent this, so the user has to click the Close button to dismiss the modal?</p> <p>Best,</p>
13,320,021
3
2
null
2012-11-10 06:48:45.02 UTC
5
2017-05-18 18:18:09.273 UTC
2012-11-10 06:59:19.867 UTC
null
1,725,145
null
1,260,138
null
1
44
javascript|jquery|css|twitter-bootstrap
29,615
<p>you can pass these options:</p> <pre><code>{ keyboard: false, backdrop: 'static' } </code></pre>
13,698,978
Git - undoing git rm
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2125710/how-to-revert-a-git-rm-r">How to revert a “git rm -r .”?</a> </p> </blockquote> <p>Git SOS here. I worked 10 hours on a project without committing (I know, I know) and then I git added too many files, so I tried using git rm and accidentally deleted EVERYTHING. Is there hope for me? :(((</p>
13,699,072
1
0
null
2012-12-04 08:46:21.78 UTC
22
2019-10-15 09:00:16.853 UTC
2017-05-23 10:31:13.547 UTC
null
-1
null
1,436,111
null
1
97
git|git-rm
80,091
<p>If you already commited changes, then:</p> <pre><code>git reset (--hard) HEAD~1 </code></pre> <p>If not then:</p> <pre><code>git reset git ls-files -d -z | xargs -0 git checkout -- </code></pre>
13,246,211
How to get stage from controller during initialization?
<p>I want to handle stage events (i.e. hiding) from my controller class. So all I have to do is to add a listener like this:</p> <pre><code>((Stage) myPane.getScene().getWindow()).setOn*whatIwant*(...); </code></pre> <p>But the problem is that initialization starts right after this code:</p> <pre><code>Parent root = FXMLLoader.load(getClass().getResource(&quot;MyGui.fxml&quot;)); </code></pre> <p>And before this code:</p> <pre><code>Scene scene = new Scene(root); stage.setScene(scene); </code></pre> <p>Thus <code>getScene</code> returns null.</p> <p>The only workaround I found by myself is to add a listener to <code>myPane.sceneProperty</code>, and when it becomes not null I get scene, add to it's <code>windowProperty</code> my listener handling which I finally retrieve stage. And it all ends with setting desired listeners to stage events.</p> <p>I think there are too many listeners.</p> <p>Is it the only way to solve my problem?</p>
13,247,005
7
0
null
2012-11-06 07:18:36.13 UTC
23
2022-04-10 12:31:48.113 UTC
2022-04-10 12:31:48.113 UTC
null
452,775
null
1,711,975
null
1
99
javafx|initialization|javafx-2|javafx-8|stage
168,602
<p>You can get the instance of the controller from the <code>FXMLLoader</code> after initialization via <code>getController()</code>, but you need to instantiate an <code>FXMLLoader</code> instead of using the static methods then. </p> <p>I'd pass the stage after calling <code>load()</code> directly to the controller afterwards:</p> <pre><code>FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml")); Parent root = (Parent)loader.load(); MyController controller = (MyController)loader.getController(); controller.setStageAndSetupListeners(stage); // or what you want to do </code></pre>
13,483,430
How to make rounded percentages add up to 100%
<p>Consider the four percentages below, represented as <code>float</code> numbers:</p> <pre><code> 13.626332% 47.989636% 9.596008% 28.788024% ----------- 100.000000% </code></pre> <p>I need to represent these percentages as whole numbers. If I simply use <code>Math.round()</code>, I end up with a total of 101%. </p> <pre><code>14 + 48 + 10 + 29 = 101 </code></pre> <p>If I use <code>parseInt()</code>, I end up with a total of 97%. </p> <pre><code>13 + 47 + 9 + 28 = 97 </code></pre> <p>What's a good algorithm to represent any number of percentages as whole numbers while still maintaining a total of 100%?</p> <hr> <p><strong>Edit</strong>: After reading some of the comments and answers, there are clearly many ways to go about solving this.</p> <p>In my mind, to remain true to the numbers, the "right" result is the one that minimizes the overall error, defined by how much error rounding would introduce relative to the actual value:</p> <pre><code> value rounded error decision ---------------------------------------------------- 13.626332 14 2.7% round up (14) 47.989636 48 0.0% round up (48) 9.596008 10 4.0% don't round up (9) 28.788024 29 2.7% round up (29) </code></pre> <p>In case of a tie (3.33, 3.33, 3.33) an arbitrary decision can be made (e.g. 3, 4, 3).</p>
13,485,888
22
10
null
2012-11-20 22:38:55.757 UTC
102
2021-11-04 03:21:15.773 UTC
2017-06-03 15:41:43.807 UTC
user6547518
null
null
25,842
null
1
251
algorithm|math|rounding|percentage
135,533
<p>Since none of the answers here seem to solve it properly, here's my semi-obfuscated version using <a href="http://underscorejs.org/" rel="noreferrer">underscorejs</a>:</p> <pre class="lang-js prettyprint-override"><code>function foo(l, target) { var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0); return _.chain(l). sortBy(function(x) { return Math.round(x) - x }). map(function(x, i) { return Math.round(x) + (off &gt; i) - (i &gt;= (l.length + off)) }). value(); } foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // =&gt; [48, 29, 14, 9] foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // =&gt; [17, 17, 17, 17, 16, 16] foo([33.333, 33.333, 33.333], 100) // =&gt; [34, 33, 33] foo([33.3, 33.3, 33.3, 0.1], 100) // =&gt; [34, 33, 33, 0] </code></pre>
51,973,856
How is the smooth dice loss differentiable?
<p>I am training a U-Net in keras by minimizing the <code>dice_loss</code> function that is popularly used for this problem: <a href="https://github.com/keras-team/keras/issues/3611" rel="noreferrer">adapted from here</a> and <a href="https://gist.github.com/wassname/7793e2058c5c9dacb5212c0ac0b18a8a" rel="noreferrer">here</a></p> <pre><code>def dsc(y_true, y_pred): smooth = 1. y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) score = (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) return score def dice_loss(y_true, y_pred): return (1 - dsc(y_true, y_pred)) </code></pre> <p>This implementation is different from the <a href="https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient" rel="noreferrer">traditional dice loss</a> because it has a smoothing term to make it "differentiable". I just don't understand how adding the <code>smooth</code> term instead of something like <code>1e-7</code> in the denominator makes it better because it actually changes the loss values. I have checked this by using a trained unet model on a test set with a regular <code>dice</code> implementation as follows: </p> <pre><code>def dice(im1,im2): im1 = np.asarray(im1).astype(np.bool) im2 = np.asarray(im2).astype(np.bool) intersection = np.logical_and(im1, im2) return np.float(2. * intersection.sum()) / (im1.sum() + im2.sum() + 1e-7)) </code></pre> <p>Can someone explain why the smooth dice loss is conventionally used?</p>
51,979,012
1
4
null
2018-08-22 19:27:16.41 UTC
8
2022-04-26 10:22:14.637 UTC
2021-12-05 12:35:42.893 UTC
null
1,714,410
null
7,892,871
null
1
11
tensorflow|image-processing|keras|image-segmentation|semantic-segmentation
5,235
<p>Adding <code>smooth</code> to the loss does not make it differentiable. What makes it differentiable is</p> <ol> <li>Relaxing the threshold on the prediction: You do not cast <code>y_pred</code> to <code>np.bool</code>, but leave it as a <em>continuous</em> value between 0 and 1</li> <li>You do not use set operations as <code>np.logical_and</code>, but rather use the element-wise product to approximate the non-differenetiable intersection operation.</li> </ol> <p>You only add <code>smooth</code> to avoid division by zero when both <code>y_pred</code> and <code>y_true</code> do not contain any foreground pixels.</p>
20,365,334
php - syntax error, unexpected T_DOUBLE_ARROW
<p>how i can rid of this error??</p> <pre><code>Parse error: syntax error, unexpected T_DOUBLE_ARROW in /var/www/core/restvt.api.php on line 35 </code></pre> <p>PHP Code :</p> <pre><code> $datax = Array(); foreach ($inis as $key =&gt; $data){ if ($data=="mem"){ $str = number_format($ARRAY[(array_search($data.':',$ARRAY)+2)]/1024,0,',','.')." MB [ ".number_format(($ARRAY[(array_search($data.':',$ARRAY)+2)]/$ARRAY[(array_search($data.':',$ARRAY)+1)])*100,0,',','.')." % ]"; array_push($datax, "mem"=&gt;$str); //error here, why? }else{ array_push($datax,$data=&gt;$ARRAY[(array_search($data.':',$ARRAY)+1)]); } } $jsonr = json_encode($datax); </code></pre> <p>thx alot for your help...</p>
20,365,479
2
2
null
2013-12-04 01:50:50.833 UTC
null
2016-10-17 19:46:53.943 UTC
2013-12-04 02:00:57.647 UTC
null
3,051,384
null
3,051,384
null
1
15
php|syntax
77,554
<p>I <strong>hate</strong> seeing people use array_push - I know it's legal. In this case, you can't <strong>push</strong> a <code>key =&gt; value</code> to your array, just do this instead:</p> <pre><code>$datax['mem'] = $str; </code></pre> <p>Manual: <a href="http://php.net/manual/en/function.array-push.php" rel="noreferrer">http://php.net/manual/en/function.array-push.php</a></p> <blockquote> <p>edit</p> </blockquote> <p>If you insist on using the <code>array_push</code> type method, you'll need to create a new array with your new key value pair then use <code>array_merge</code> to join them:</p> <pre><code>$new_data = array('mem' =&gt; $str); $datax = array_merge($datax, $new_data); </code></pre>
3,877,006
where can I find mysql.data.dll for c#
<p>All I keep on finding are source files for compiling the project myself (which keeps on failing).</p> <p>Any ideas please?</p> <p>Thank You!</p>
3,877,080
2
4
null
2010-10-06 21:22:17.643 UTC
1
2015-05-07 06:15:41.677 UTC
null
null
null
null
126,015
null
1
14
c#|mysql
77,472
<p><a href="http://dev.mysql.com/downloads/connector/net/" rel="noreferrer">Here is where you can download the latest MySql .NET driver for ADO.NET.</a> </p> <p>Enjoy!</p>
3,552,223
ASP.NET - AppDomain.CurrentDomain.GetAssemblies() - Assemblies missing after AppDomain restart
<p>I have a Bootstrapper that looks through all Assemblies in an ASP.NET MVC application to find types that implement an <code>IBootstrapperTask</code> interface, and then registers them with an IOC Contrainer. The idea is that you can literaly place your IBootstrapperTasks anywhere, and organise your Projects how you please.</p> <p>Code for Bootstrapper:</p> <pre><code>public class Bootstrapper { static Bootstrapper() { Type bootStrapperType = typeof(IBootstrapperTask); IList&lt;Assembly&gt; assemblies = AppDomain.CurrentDomain.GetAssemblies(); List&lt;Type&gt; tasks = new List&lt;Type&gt;(); foreach (Assembly assembly in assemblies) { var types = from t in assembly.GetTypes() where bootStrapperType.IsAssignableFrom(t) &amp;&amp; !t.IsInterface &amp;&amp; !t.IsAbstract select t; tasks.AddRange(types); } foreach (Type task in tasks) { if (!IocHelper.Container().Kernel.HasComponent(task.FullName)) { IocHelper.Container().AddComponentLifeStyle( task.FullName, task, LifestyleType.Transient); } } } public static void Run() { // Get all registered IBootstrapperTasks, call Execute() method } } </code></pre> <p>After a full build, <code>AppDomain.CurrentDomain.GetAssemblies()</code> returns all Assemblies in my solution (including all the GAC one's but that doesn't bother me).</p> <p>However, if the AppDomain is restarted, or I 'bounce' the Web.Config file (adding a space and saving), the static constructor is run again but when <code>AppDomain.CurrentDomain.GetAssemblies()</code> is called, <strong>most of the Assemblies are missing</strong>, including the one containing my IBootstrapperTask types.</p> <p>How do I get around this problem? I guess I could System.IO the /bin directory and load all the DLLs in there manually, but would rather avoid this if possible, or is that the only way? Am I taking the right general approach to this?</p> <p>This is an ASP.NET MVC 2.0 application running on .NET 4.0, I get this problem with the built-in Visual Studio 2010 Cassini web server, and with IIS7.0 in Integrated Pipeline Mode on Windows Server 2008.</p> <hr> <p><strong>Edit:</strong> I just came across this SO post <a href="https://stackoverflow.com/questions/2477787/difference-between-appdomain-getassemblies-and-buildmanager-getreferencedassembli">Difference between AppDomain.GetAssemblies and BuildManager.GetReferencedAssemblies</a> which says the AppDomain only loads the Assemblies as they're needed (eg. when a method/class from that Assembly is first called). I guess that would explain why the Assemblies are missing on <code>AppDomain.CurrentDomain.GetAssemblies()</code> as the Bootstrapper is run very early on.</p> <p>I noticed if I placed a call to 'something' from the missing Assembly before the Bootstrapper eg:</p> <pre><code>public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { MyApp.MissingAssembly.SomeClass someClass = new MyApp.MissingAssembly.SomeClass(); Bootstrapper.Run(); } } </code></pre> <p>...it seems to fix the problem, but it is a bit of a hack.</p>
3,704,939
2
1
null
2010-08-23 22:34:30.137 UTC
12
2014-06-09 15:31:34.493 UTC
2017-05-23 12:17:14.827 UTC
null
-1
null
143,253
null
1
32
c#|asp.net|asp.net-mvc|reflection|assemblies
13,463
<p>I looked through the ASP.NET MVC 2.0 source code and looked up how <code>AreaRegistration.RegisterAllAreas();</code> is implemented. This line is usually put into the Global.asax Application_Start() method and internally it scans all Assemblies for types that implement the AreaRegistration abstract type. This is kinda the behaviour I'm after.</p> <p>It appears RegisterAllAreas() makes a call to <code>BuildManager.GetReferencedAssemblies()</code>, well if it's good enough for MVC then it's good enough for me :-)</p> <p>I've done some experimentation and BuildManager.GetReferencedAssemblies() will even pick up adhoc, random DLL's dropped into the /bin folder, even with no references to any projects in the Visual Studio solution. So it appears far more reliable than <code>AppDomain.Current.GetAssemblies()</code>.</p> <p>I've rewritten my Assembly locator code to the following:</p> <pre><code>using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Compilation; public static class AssemblyLocator { private static readonly ReadOnlyCollection&lt;Assembly&gt; AllAssemblies; private static readonly ReadOnlyCollection&lt;Assembly&gt; BinAssemblies; static AssemblyLocator() { AllAssemblies = new ReadOnlyCollection&lt;Assembly&gt;( BuildManager.GetReferencedAssemblies().Cast&lt;Assembly&gt;().ToList()); IList&lt;Assembly&gt; binAssemblies = new List&lt;Assembly&gt;(); string binFolder = HttpRuntime.AppDomainAppPath + "bin\\"; IList&lt;string&gt; dllFiles = Directory.GetFiles(binFolder, "*.dll", SearchOption.TopDirectoryOnly).ToList(); foreach (string dllFile in dllFiles) { AssemblyName assemblyName = AssemblyName.GetAssemblyName(dllFile); Assembly locatedAssembly = AllAssemblies.FirstOrDefault(a =&gt; AssemblyName.ReferenceMatchesDefinition( a.GetName(), assemblyName)); if (locatedAssembly != null) { binAssemblies.Add(locatedAssembly); } } BinAssemblies = new ReadOnlyCollection&lt;Assembly&gt;(binAssemblies); } public static ReadOnlyCollection&lt;Assembly&gt; GetAssemblies() { return AllAssemblies; } public static ReadOnlyCollection&lt;Assembly&gt; GetBinFolderAssemblies() { return BinAssemblies; } } </code></pre>
3,875,195
Google Chrome > Textboxes > Yellow border when active..?
<p>Ive been modifying a form today, and testing it in Chrome. I noticed that on selecting a textbox, with border: 0 or none, it still puts a yellow border around it. Does anyone know of a way to get rid of this border? I usually wouldnt be that bothered but it looks really horrible with the colour scheme I am using.</p> <p>Thanks in advance.</p> <p>Regards,</p> <p>Richard</p> <p>PS I have tried using !important too, in case something else is setting the border to yellow in the CSS.</p>
3,875,216
2
3
null
2010-10-06 17:19:43.273 UTC
11
2014-03-13 00:39:12.847 UTC
null
null
null
null
297,683
null
1
43
css|google-chrome|input|textbox|border
42,683
<p>This is caused by an <a href="http://www.w3.org/TR/CSS2/ui.html#dynamic-outlines" rel="noreferrer">outline</a>, not a border. The specific style you see is defined in the user agent (browser) stylesheet.</p> <p>I agree that Chrome's large, highlighted outline looks bad in many cases, although it does make it obvious which field is active.</p> <hr> <p><strong>As of early 2014, the highlight is now blue (instead of yellow) and the highlight effect is smaller. The following instructions are still valid for modifying this style.</strong></p> <hr> <h2>Removing the Outline</h2> <p>You can set <code>outline: none;</code> on any element to remove the highlight completely.</p> <pre><code>input[type="text"], input[type="password"] { outline: none; } </code></pre> <p>This potentially (likely) reduces accessibility/usability. There is even <a href="http://outlinenone.com/" rel="noreferrer">a website dedicated</a> to the dangers of completely removing the outline.</p> <h2>Styling the Outline</h2> <p>A better alternative is to style the outline so that it is still visible but less obnoxious. See <a href="https://developer.mozilla.org/en-US/docs/CSS/outline" rel="noreferrer">https://developer.mozilla.org/en-US/docs/CSS/outline</a></p> <p><strong>Demo:</strong> <a href="http://jsfiddle.net/G28Gd/2/" rel="noreferrer">http://jsfiddle.net/G28Gd/2/</a></p> <pre><code>INPUT[type="text"]:focus, INPUT[type="number"]:focus, INPUT[type="email"]:focus, INPUT[type="search"]:focus, INPUT[type="password"]:focus, INPUT[type="range"]:focus { outline: 1px solid #0033dd; }​ </code></pre> <h2>User Expectations</h2> <blockquote> <p>At times, style sheet authors may want to create outlines around visual objects such as buttons, active form fields, image maps, etc., to make them stand out.</p> </blockquote> <p>In theory, the outline may be used for cosmetic purposes though I've never found a practical use other than indicating focus. However, it's best to only show a focus-like outline when an element is actually focused. In other words, don't make an element look focused when it is not.</p> <p>Remember that HTML anchors can also receive focus and that their outline can also be styled. This can be a useful cue to the user.</p> <h2>Visual Rendering</h2> <blockquote> <p>The outline created with the outline properties is drawn "over" a box, i.e., the outline is always on top, and does not influence the position or size of the box, or of any other boxes. Therefore, displaying or suppressing outlines does not cause reflow or overflow.</p> </blockquote> <p>An outline may be applied to any element (again, make sure to not confuse the user).</p> <p>Unlike borders, they do not impact the position or size of the box. This is important, for example, when showing that an anchor has focus; if you added a border to the anchor, the whole box would visibly shift by the size of the border (<a href="http://jsfiddle.net/KaP6K/" rel="noreferrer">try it</a>). By comparison, an outline will not shift the box. </p> <p>One downside of this box-independence is that the outline doesn't always render precisely where you would expect. <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element" rel="noreferrer">Replaced elements</a> may render in ways (now, or in the future) that might not look good with a particular highlight style. <code>&lt;input type="range"&gt;</code> is a good candidate for seeing this behavior.</p> <p><img src="https://i.stack.imgur.com/GUcYD.png" alt="enter image description here"></p> <p><sub>This outline is functional, but not very pretty or even aligned correctly (Chrome 26-29).</sub></p> <hr> <p><s>Button elements do not currently (Chrome 21) look correct with an outline specified (try it and see - the outline does not follow the edge of the button).</s></p> <p><sub>Outlines now appear to be correctly aligned with the edges of a button as of Chrome 26.</sub></p>
3,826,580
What rules does software version numbering follow?
<p>I have been developing some software and want to give it version numbers.</p> <p>How do I do this? </p> <p>How is it that some software gets two versions like 1.3v1.1</p> <p>or some have 3 numbers - 4.0.1 </p> <p>What is the method behind all this?</p> <p>Thanks.</p>
3,826,643
2
0
null
2010-09-29 23:18:33.49 UTC
72
2016-06-14 21:32:28.563 UTC
null
null
null
null
52,256
null
1
129
version-control
131,721
<p>The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:</p> <ul> <li>Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.</li> <li>Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.</li> <li>Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.</li> </ul> <p>Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.</p> <p>There are many variants to versioning. It all boils down to personal preference.</p> <p>For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.</p>
45,493,948
Error: The truth value of a Series is ambiguous - Python pandas
<p>I know this question has been asked before, however, when I am trying to do an <code>if</code> statement and I am getting an error. I looked at this <a href="https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o">link</a> , but did not help much in my case. My <code>dfs</code> is a list of DataFrames. </p> <p>I am trying the following,</p> <pre><code>for i in dfs: if (i['var1'] &lt; 3.000): print(i) </code></pre> <p>Gives the following error:</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p><strong>AND</strong> I tried the following and getting the same error.</p> <pre><code>for i,j in enumerate(dfs): if (j['var1'] &lt; 3.000): print(i) </code></pre> <p>My <code>var1</code> data type is <code>float32</code>. I am not using any other <code>logical</code> operators and <code>&amp;</code> or <code>|</code>. In the above link it seemed to be because of using logical operators. Why do I get <code>ValueError</code>?</p>
45,494,393
3
14
null
2017-08-03 20:26:39.563 UTC
5
2020-05-16 11:01:55.697 UTC
2018-09-02 12:27:08.273 UTC
null
6,605,349
null
6,626,093
null
1
16
python|pandas|logic
69,573
<p>Here is a small demo, which shows why this is happenning:</p> <pre><code>In [131]: df = pd.DataFrame(np.random.randint(0,20,(5,2)), columns=list('AB')) In [132]: df Out[132]: A B 0 3 11 1 0 16 2 16 1 3 2 11 4 18 15 In [133]: res = df['A'] &gt; 10 In [134]: res Out[134]: 0 False 1 False 2 True 3 False 4 True Name: A, dtype: bool </code></pre> <p>when we try to check whether such Series is <code>True</code> - Pandas doesn't know what to do:</p> <pre><code>In [135]: if res: ...: print(df) ...: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ... skipped ... ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>Workarounds:</p> <p>we can decide how to treat Series of boolean values - for example <code>if</code> should return <code>True</code> if <strong>all</strong> values are <code>True</code>:</p> <pre><code>In [136]: res.all() Out[136]: False </code></pre> <p>or when <strong>at least one</strong> value is True:</p> <pre><code>In [137]: res.any() Out[137]: True In [138]: if res.any(): ...: print(df) ...: A B 0 3 11 1 0 16 2 16 1 3 2 11 4 18 15 </code></pre>
29,473,830
Image in tooltip using bootstrap?
<pre><code>&lt;button title="Tooltip on right" data-placement="right" data-toggle="tooltip" class="btn btn-default mrs" type="button"&gt;Tooltip on right&lt;/button&gt; &lt;script&gt; $(function () { $('[data-toggle=tooltip]').tooltip(); }); &lt;/script&gt; </code></pre> <p>This works fine but I'd like to include an image and some text inside the tooltip. I tried to use data-content="some stuff" but it shows nothing.</p>
29,474,000
1
3
null
2015-04-06 15:02:56.83 UTC
3
2015-04-06 15:12:22.777 UTC
2015-04-06 15:03:50.257 UTC
null
616,443
null
3,916,237
null
1
22
javascript|jquery|twitter-bootstrap|frontend
63,175
<p>You have to pass in the html option to when you initialize .tooltip. e.g. </p> <pre><code>&lt;div class="cart"&gt; &lt;a data-toggle="tooltip" title="&lt;img src='http://getbootstrap.com/apple-touch-icon.png' /&gt;"&gt; &lt;i class="icon-shopping-cart"&gt;&lt;/i&gt; &lt;/a&gt; </code></pre> <h2> </h2> <pre><code>$('a[data-toggle="tooltip"]').tooltip({ animated: 'fade', placement: 'bottom', html: true }); </code></pre> <p>See the example <a href="http://jsfiddle.net/joshvito/v4p24ak8/1/">fiddle</a></p>
16,462,163
Java - How to access an ArrayList of another class?
<p>Hello I'm a beginner in Java and this is my question: I have this first class with the following variables:</p> <pre><code>import java.util.ArrayList; public class numbers { private int number1 = 50; private int number2 = 100; } </code></pre> <p>And I have this class too:</p> <pre><code>import java.util.ArrayList; public class test { private numbers number; } </code></pre> <p>My question here is: I want to store the number1 &amp; number2 variables into an ArrayList, then access this ArrayList from class test. How can I do that?</p>
16,462,257
5
3
null
2013-05-09 12:48:41.287 UTC
13
2019-03-18 08:35:54.553 UTC
2013-05-09 14:53:48.677 UTC
null
1,622,894
null
2,304,521
null
1
19
java|arraylist
157,932
<pre><code>import java.util.ArrayList; public class numbers { private int number1 = 50; private int number2 = 100; private List&lt;Integer&gt; list; public numbers() { list = new ArrayList&lt;Integer&gt;(); list.add(number1); list.add(number2); } public List&lt;Integer&gt; getList() { return list; } } </code></pre> <p>And the test class:</p> <pre><code>import java.util.ArrayList; public class test { private numbers number; //example public test() { number = new numbers(); List&lt;Integer&gt; list = number.getList(); //hurray ! } } </code></pre> <p></p>
16,492,940
How to install and run lessc on top of node.js and Windows?
<p>Hi I am learning LESS and I would like to install lessc on my Windows 7.</p> <p>Following this tutorial <a href="http://verekia.com/less-css/dont-read-less-css-tutorial-highly-addictive">http://verekia.com/less-css/dont-read-less-css-tutorial-highly-addictive</a></p> <p>The first step is I dowloaded and installed node.js (node-v0.10.5-x64.msi).</p> <p>Then in a console, I ran</p> <pre><code>npm install less -g </code></pre> <p>I got the following: </p> <pre><code>npm http GET https://registry.npmjs.org/less npm http 304 https://registry.npmjs.org/less npm http GET https://registry.npmjs.org/ycssmin npm http 304 https://registry.npmjs.org/ycssmin C:\Users\Me\AppData\Roaming\npm\lessc -&gt; C:\Users\Me\AppData\Roaming\npm\node_modules\less\bin\lessc [email protected] C:\Users\Me\AppData\Roaming\npm\node_modules\less +-- [email protected] </code></pre> <p>Then I ran the following in the same console:</p> <pre><code>lessc style.less &gt; style.css </code></pre> <p>But I got </p> <blockquote> <p>'lessc' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>I am not sure where I got wrong. I googled but it seems there is too much stuff, not sure which one is right. Did many tests without any success.</p> <p>Could someone tell me how to do it or give me a pointer to some place with detailed and latest install info for Windows?</p>
16,493,186
9
1
null
2013-05-11 01:42:14.863 UTC
3
2019-06-16 23:03:30.66 UTC
2013-08-29 21:56:43.167 UTC
null
404,623
null
997,474
null
1
19
windows|node.js|less
38,384
<p>In a console, run the following:</p> <pre><code>node C:\Users\Me\AppData\Roaming\npm\node_modules\less\bin\lessc style.less &gt; style.css </code></pre> <p><code>style.less</code> must be in the console's directory.</p>
16,549,137
How to get the style value using attr
<p>My HTML CODE HERE:</p> <pre><code> &lt;i id="bgcolor" style="background-color: rgb(255, 146, 180)"&gt;&lt;/i&gt; </code></pre> <p>I want to get the background-color value using jquery attr. What i tried is below:</p> <pre><code>$("#bgcolor").mouseleave(function(){ var bodyColor = $(this).attr("style"); $("body").css(bodyColor); }); </code></pre> <p>But this output is:</p> <pre><code>background-color: rgb(255, 146, 180); </code></pre> <p>And now that I've added it to my css it will not work. How can I achieve this task?</p> <p><img src="https://i.stack.imgur.com/doK2P.png" alt="enter image description here"></p>
16,549,201
5
2
null
2013-05-14 17:18:47.1 UTC
2
2020-01-31 22:32:08.507 UTC
2020-01-31 22:32:08.507 UTC
null
2,912,011
null
2,373,354
null
1
20
jquery|html|css|attr
58,658
<p>Check out the documentation for .css: <a href="http://api.jquery.com/css/" rel="noreferrer">http://api.jquery.com/css/</a></p> <pre><code>var bodyColor = $(this).css("backgroundColor"); </code></pre>
16,077,341
How to reset all default styles of the HTML5 button element
<h2>Scenario</h2> <p>I use the <code>&lt;button&gt;</code> element which appeares just as plain text with an "+" on right end. <br/>On click a div element expands and reveals some information. I think the button element is semanticaley correct to represent such a ... button ... trigger.</p> <h2>Problem</h2> <p>So I have mixed some buttons and h2 elements and I have got a visual problem. After resetting all <strong>default user agent style's</strong> I expect that every element I introduce to the document looks plain and unstyled.</p> <p>But the button element does not look that plain. It has an text, slightly, text indention. <br /><br /></p> <h2>Example</h2> <p><img src="https://i.stack.imgur.com/RY67y.jpg" alt="First, three elements are &lt;h2&gt;&lt;button&gt;TEXT&lt;/button&gt;&lt;/h2&gt; and the two from above are just &lt;h2&gt;TEXT&lt;/h2&gt;"></p> <p>First, three elements are <code>&lt;h2&gt;&lt;button&gt;text node&lt;/button&gt;&lt;/h2&gt;</code> and the two from above are just <code>&lt;h2&gt;text node&lt;/h2&gt;</code></p> <h2>CSS</h2> <pre><code>* { /*Reset's every elements apperance*/ background: none repeat scroll 0 0 transparent; border: medium none; border-spacing: 0; color: #26589F; font-family: 'PT Sans Narrow',sans-serif; font-size: 16px; font-weight: normal; line-height: 1.42rem; list-style: none outside none; margin: 0; padding: 0; text-align: left; text-decoration: none; text-indent: 0; } </code></pre> <h2>Other element's CSS</h2> <p>The other elements use background-image, text-transform:uppercase and that's it. In Firebug there are <strong>no</strong> paddings,margins,text-indents or other "soft" or "hard" properties which could mess things up. I played around with display settings but it does not "fix" anything or make it worse.</p> <h2>Question</h2> <p>Can anybody explain why, even after resetting the default styles, there is this visual failure on the <code>&lt;button&gt;</code> element?</p>
16,077,726
1
0
null
2013-04-18 07:50:15.3 UTC
5
2014-11-12 04:57:17.98 UTC
null
null
null
null
497,060
null
1
23
css|html|button|default|user-agent
59,035
<pre><code>button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } </code></pre> <p>add this one also in css it will solve your problem.</p>
16,164,044
What is the correct way to silently close InputStream in finally block without losing the original exception?
<p>I am wondering if the below code closes InputStream in finally block correctly</p> <pre><code>InputStream is = new FileInputStream("test"); try { for(;;) { int b = is.read(); ... } } finally { try { is.close(); } catch(IOException e) { } } </code></pre> <p>If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?</p>
16,164,100
9
2
null
2013-04-23 08:01:30.047 UTC
null
2020-01-14 09:48:20.383 UTC
null
null
null
null
1,831,293
null
1
30
java
28,681
<p>The exception from is.close() will be suppressed and the exception from is.read() will be the one that propagates up.</p>
12,864,999
Sending and Receiving UDP packets
<p>The following code sends a packet on port 15000:</p> <pre><code>int port = 15000; UdpClient udp = new UdpClient(); //udp.EnableBroadcast = true; //This was suggested in a now deleted answer IPEndPoint groupEP = new IPEndPoint(IPAddress.Broadcast, port); string str4 = "I want to receive this!"; byte[] sendBytes4 = Encoding.ASCII.GetBytes(str4); udp.Send(sendBytes4, sendBytes4.Length, groupEP); udp.Close(); </code></pre> <p>However, it's kind of useless if I can't then receive it on another computer. All I need is to send a command to another computer on the LAN, and for it to receive it and do something.</p> <p>Without using a Pcap library, is there any way I can accomplish this? The computer my program is communicating with is Windows XP 32-bit, and the sending computer is Windows 7 64-bit, if it makes a difference. I've looked into various <code>net send</code> commands, but I can't figure them out.</p> <p>I also have access to the computer (the XP one)'s local IP, by being able to physically type 'ipconfig' on it.</p> <p><strong>EDIT:</strong> Here's the Receive function I'm using, copied from somewhere:</p> <pre><code>public void ReceiveBroadcast(int port) { Debug.WriteLine("Trying to receive..."); UdpClient client = null; try { client = new UdpClient(port); } catch (Exception ex) { Debug.WriteLine(ex.Message); } IPEndPoint server = new IPEndPoint(IPAddress.Broadcast, port); byte[] packet = client.Receive(ref server); Debug.WriteLine(Encoding.ASCII.GetString(packet)); } </code></pre> <p>I'm calling <code>ReceiveBroadcast(15000)</code> but there's no output at all.</p>
12,867,005
1
7
null
2012-10-12 18:26:45.203 UTC
3
2017-12-20 13:23:00.157 UTC
2012-10-12 19:42:56.743 UTC
null
1,742,063
null
1,742,063
null
1
5
c#|udp|message|broadcast|packet
64,104
<p>Here is the <code>simple</code> version of Server and Client to send/receive UDP packets</p> <p><strong>Server</strong></p> <pre><code>IPEndPoint ServerEndPoint= new IPEndPoint(IPAddress.Any,9050); Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); WinSocket.Bind(ServerEndPoint); Console.Write("Waiting for client"); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0) EndPoint Remote = (EndPoint)(sender); int recv = WinSocket.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); </code></pre> <p><strong>Client</strong></p> <pre><code>IPEndPoint RemoteEndPoint= new IPEndPoint( IPAddress.Parse("ServerHostName"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, RemoteEndPoint); </code></pre>
15,374,969
Determining if a string contains a word
<p>In Python, what is the syntax for a statement that, given the following context:</p> <pre><code>words = 'blue yellow' </code></pre> <p>would be an if statement that checks to see if <code>words</code> contains the word "blue"? I.e.,</p> <pre><code>if words ??? 'blue': print 'yes' elif words ??? 'blue': print 'no' </code></pre> <p>In English, "If words contain blue, then say yes. Otherwise, print no."</p>
15,374,983
4
4
null
2013-03-13 00:37:51.817 UTC
4
2013-03-13 01:11:42.847 UTC
2013-03-13 00:52:31.447 UTC
null
722,332
null
2,157,472
null
1
6
python|if-statement
57,775
<pre><code>words = 'blue yellow' if 'blue' in words: print 'yes' else: print 'no' </code></pre> <h1>Edit</h1> <p>I just realized that <code>nightly blues</code> would contain <code>blue</code>, but not as a whole word. If this is not what you want, split the wordlist:</p> <pre><code>if 'blue' in words.split(): … </code></pre>
17,184,242
Command Prompt/Bat file - Create new folder named with today's date
<p>I use the following code to create a new folder that is named with todays date:</p> <pre><code>for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a mkdir c:\%date:/=% </code></pre> <p>Now the format is as follows:</p> <pre><code>20130619 </code></pre> <p>How do I change the format to?: </p> <pre><code>2013_06_19 </code></pre> <p>Thank you</p>
17,184,479
4
0
null
2013-06-19 06:25:13.62 UTC
3
2017-09-17 00:23:18.53 UTC
null
null
null
null
1,140,828
null
1
5
command-line|batch-file
53,072
<pre><code>for /f "tokens=1-3 delims=/" %%a in ("%date%") do md "%%a_%%b_%%c" </code></pre>
24,614,474
Pandas Merge on Name and Closest Date
<p>I am trying to merge two dataframes on both name and the closest date (WRT the left hand dataframe). In my research I found one similar question <a href="https://stackoverflow.com/questions/21201618/pandas-merge-match-the-nearest-time-stamp-the-series-of-timestamps">here</a> but it doesn't account for the name as well. From the above question it doesn't seem like there is a way to do this with merge but I can't see another way to do the two argument join that doesn't use the pandas merge function. </p> <p>Is there a way to do this with merge? And if not what would be the appropriate way to do this? </p> <p>I will post a copy of what I have tried but this was trying it with an exact merge on date which will not work. The most important line is the last one where I make the data3 dataframe.</p> <pre><code>data=pd.read_csv("edgar14Afacts.csv", parse_dates={"dater": [2]}, infer_datetime_format=True) data2=pd.read_csv("sdcmergersdata.csv", parse_dates={"dater": [17]}, infer_datetime_format=True) list(data2.columns.values) data2.rename(columns=lambda x: x.replace('\r\n', ''), inplace=True) data2.rename(columns=lambda x: x.replace('\n', ''), inplace=True) data2.rename(columns=lambda x: x.replace('\r', ''), inplace=True) data2=data2.rename(columns = {'Acquiror Name':'name'}) data2=data2.rename(columns = {'dater':'date'}) data=data.rename(columns = {'dater':'date'}) list(data2.columns.values) data["name"]=data['name'].map(str.lower) data2["name"]=data2['name'].map(str.lower) data2['date'].fillna(method='pad') data['namer1']=data['name'] data['dater1']=data['date'] data2['namer2']=data2['name'] data2['dater2']=data2['date'] print data.head() print data2.head() data['name'] = data['name'].map(lambda x: str(x)[:4]) data2['name'] = data2['name'].map(lambda x: str(x)[:4]) data3 = pd.merge(data, data2, how='left', on=['date','name']) data3.to_csv("check.csv") </code></pre>
25,962,323
3
6
null
2014-07-07 15:39:00.62 UTC
12
2018-07-18 14:25:35.84 UTC
2017-05-23 12:01:33.313 UTC
null
-1
null
3,314,282
null
1
18
python|date|pandas|merge
21,337
<p>I'd also love to see the final solution you came up with to know how it shook out in the end.</p> <p>One thing you can do to find the closest date might be something to calc the number of days between each date in the first DataFrame and the dates in the second DataFrame. Then you can use <code>np.argmin</code> to retrieve the date with the smallest time delta.</p> <p>For example:</p> <p><strong>Setup</strong></p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from pandas.io.parsers import StringIO </code></pre> <p><strong>Data</strong></p> <pre><code>a = """timepoint,measure 2014-01-01 00:00:00,78 2014-01-02 00:00:00,29 2014-01-03 00:00:00,5 2014-01-04 00:00:00,73 2014-01-05 00:00:00,40 2014-01-06 00:00:00,45 2014-01-07 00:00:00,48 2014-01-08 00:00:00,2 2014-01-09 00:00:00,96 2014-01-10 00:00:00,82 2014-01-11 00:00:00,61 2014-01-12 00:00:00,68 2014-01-13 00:00:00,8 2014-01-14 00:00:00,94 2014-01-15 00:00:00,16 2014-01-16 00:00:00,31 2014-01-17 00:00:00,10 2014-01-18 00:00:00,34 2014-01-19 00:00:00,27 2014-01-20 00:00:00,58 2014-01-21 00:00:00,90 2014-01-22 00:00:00,41 2014-01-23 00:00:00,97 2014-01-24 00:00:00,7 2014-01-25 00:00:00,86 2014-01-26 00:00:00,62 2014-01-27 00:00:00,91 2014-01-28 00:00:00,0 2014-01-29 00:00:00,73 2014-01-30 00:00:00,22 2014-01-31 00:00:00,43 2014-02-01 00:00:00,87 2014-02-02 00:00:00,56 2014-02-03 00:00:00,45 2014-02-04 00:00:00,25 2014-02-05 00:00:00,92 2014-02-06 00:00:00,83 2014-02-07 00:00:00,13 2014-02-08 00:00:00,50 2014-02-09 00:00:00,48 2014-02-10 00:00:00,78""" b = """timepoint,measure 2014-01-01 00:00:00,78 2014-01-08 00:00:00,29 2014-01-15 00:00:00,5 2014-01-22 00:00:00,73 2014-01-29 00:00:00,40 2014-02-05 00:00:00,45 2014-02-12 00:00:00,48 2014-02-19 00:00:00,2 2014-02-26 00:00:00,96 2014-03-05 00:00:00,82 2014-03-12 00:00:00,61 2014-03-19 00:00:00,68 2014-03-26 00:00:00,8 2014-04-02 00:00:00,94 """ </code></pre> <p><strong>look at data</strong></p> <pre><code>df1 = pd.read_csv(StringIO(a), parse_dates=['timepoint']) df1.head() timepoint measure 0 2014-01-01 78 1 2014-01-02 29 2 2014-01-03 5 3 2014-01-04 73 4 2014-01-05 40 df2 = pd.read_csv(StringIO(b), parse_dates=['timepoint']) df2.head() timepoint measure 0 2014-01-01 78 1 2014-01-08 29 2 2014-01-15 5 3 2014-01-22 73 4 2014-01-29 40 </code></pre> <p><strong>Func to find the closest date to a given date</strong></p> <pre><code>def find_closest_date(timepoint, time_series, add_time_delta_column=True): # takes a pd.Timestamp() instance and a pd.Series with dates in it # calcs the delta between `timepoint` and each date in `time_series` # returns the closest date and optionally the number of days in its time delta deltas = np.abs(time_series - timepoint) idx_closest_date = np.argmin(deltas) res = {"closest_date": time_series.ix[idx_closest_date]} idx = ['closest_date'] if add_time_delta_column: res["closest_delta"] = deltas[idx_closest_date] idx.append('closest_delta') return pd.Series(res, index=idx) df1[['closest', 'days_bt_x_and_y']] = df1.timepoint.apply( find_closest_date, args=[df2.timepoint]) df1.head(10) timepoint measure closest days_bt_x_and_y 0 2014-01-01 78 2014-01-01 0 days 1 2014-01-02 29 2014-01-01 1 days 2 2014-01-03 5 2014-01-01 2 days 3 2014-01-04 73 2014-01-01 3 days 4 2014-01-05 40 2014-01-08 3 days 5 2014-01-06 45 2014-01-08 2 days 6 2014-01-07 48 2014-01-08 1 days 7 2014-01-08 2 2014-01-08 0 days 8 2014-01-09 96 2014-01-08 1 days 9 2014-01-10 82 2014-01-08 2 days </code></pre> <p><strong>Merge the two DataFrames on the new <code>closest</code> date column</strong></p> <pre><code>df3 = pd.merge(df1, df2, left_on=['closest'], right_on=['timepoint']) colorder = [ 'timepoint_x', 'closest', 'timepoint_y', 'days_bt_x_and_y', 'measure_x', 'measure_y' ] df3 = df3.ix[:, colorder] df3 timepoint_x closest timepoint_y days_bt_x_and_y measure_x measure_y 0 2014-01-01 2014-01-01 2014-01-01 0 days 78 78 1 2014-01-02 2014-01-01 2014-01-01 1 days 29 78 2 2014-01-03 2014-01-01 2014-01-01 2 days 5 78 3 2014-01-04 2014-01-01 2014-01-01 3 days 73 78 4 2014-01-05 2014-01-08 2014-01-08 3 days 40 29 5 2014-01-06 2014-01-08 2014-01-08 2 days 45 29 6 2014-01-07 2014-01-08 2014-01-08 1 days 48 29 7 2014-01-08 2014-01-08 2014-01-08 0 days 2 29 8 2014-01-09 2014-01-08 2014-01-08 1 days 96 29 9 2014-01-10 2014-01-08 2014-01-08 2 days 82 29 10 2014-01-11 2014-01-08 2014-01-08 3 days 61 29 11 2014-01-12 2014-01-15 2014-01-15 3 days 68 5 12 2014-01-13 2014-01-15 2014-01-15 2 days 8 5 13 2014-01-14 2014-01-15 2014-01-15 1 days 94 5 14 2014-01-15 2014-01-15 2014-01-15 0 days 16 5 15 2014-01-16 2014-01-15 2014-01-15 1 days 31 5 16 2014-01-17 2014-01-15 2014-01-15 2 days 10 5 17 2014-01-18 2014-01-15 2014-01-15 3 days 34 5 18 2014-01-19 2014-01-22 2014-01-22 3 days 27 73 19 2014-01-20 2014-01-22 2014-01-22 2 days 58 73 20 2014-01-21 2014-01-22 2014-01-22 1 days 90 73 21 2014-01-22 2014-01-22 2014-01-22 0 days 41 73 22 2014-01-23 2014-01-22 2014-01-22 1 days 97 73 23 2014-01-24 2014-01-22 2014-01-22 2 days 7 73 24 2014-01-25 2014-01-22 2014-01-22 3 days 86 73 25 2014-01-26 2014-01-29 2014-01-29 3 days 62 40 26 2014-01-27 2014-01-29 2014-01-29 2 days 91 40 27 2014-01-28 2014-01-29 2014-01-29 1 days 0 40 28 2014-01-29 2014-01-29 2014-01-29 0 days 73 40 29 2014-01-30 2014-01-29 2014-01-29 1 days 22 40 30 2014-01-31 2014-01-29 2014-01-29 2 days 43 40 31 2014-02-01 2014-01-29 2014-01-29 3 days 87 40 32 2014-02-02 2014-02-05 2014-02-05 3 days 56 45 33 2014-02-03 2014-02-05 2014-02-05 2 days 45 45 34 2014-02-04 2014-02-05 2014-02-05 1 days 25 45 35 2014-02-05 2014-02-05 2014-02-05 0 days 92 45 36 2014-02-06 2014-02-05 2014-02-05 1 days 83 45 37 2014-02-07 2014-02-05 2014-02-05 2 days 13 45 38 2014-02-08 2014-02-05 2014-02-05 3 days 50 45 39 2014-02-09 2014-02-12 2014-02-12 3 days 48 48 40 2014-02-10 2014-02-12 2014-02-12 2 days 78 48 </code></pre>
21,983,097
Testflight: Cannot upload build, cannot download SDK
<p>I'm having difficulties with TestFlight today. I've tried to upload ipa for the new app but getting this error:</p> <blockquote> <p>Sorry, we are no longer accepting any new builds that use the TestFlight SDK. Please remove the SDK and re-upload. Learn More.</p> </blockquote> <p>Learn more just point to generic Help portal, not helpful. Thought the problem is with actual SDK (it's not latest version) but when I went to Dashboard/SDK, there is another error waiting for me: </p> <blockquote> <p>Sorry, the TestFlight SDK is no longer available for download for Team xxx.<br> If you require technical support, please contact [email protected]</p> </blockquote> <p>I've checked and I can only download SDK for one team, the rest of the teams is getting the same error.</p> <p>Any assistance appreciated.</p>
21,983,289
2
3
null
2014-02-24 09:02:36.447 UTC
4
2015-03-02 07:26:54.813 UTC
2014-11-17 18:28:29.347 UTC
null
1,192,479
null
211,765
null
1
35
ios|testflight
13,836
<p>I think this is related to the <a href="http://techcrunch.com/2014/02/21/rumor-testflight-owner-burstly-is-being-acquired-by-apple/" rel="noreferrer">Apple purchase of TestFlight</a>.</p> <p>My colleague told me that Android has also been disabled for TestFlight so it wouldn't surprise me if they have taken the whole thing down for maintenance (updating/permanently/moving it to ITC/etc...).</p>
21,891,218
Using $state methods with $stateChangeStart toState and fromState in Angular ui-router
<p>I'm writing a handler for <code>$stateChangeStart</code>:</p> <pre><code>var stateChangeStartHandler = function(e, toState, toParams, fromState, fromParams) { if (toState.includes('internal') &amp;&amp; !$cookies.MySession) { e.preventDefault(); // Some login stuff. } }; $rootScope.$on('$stateChangeStart', stateChangeStartHandler); </code></pre> <p><code>toState</code> does not have the includes method. Should I be doing something different, or is there a way to do what I'm trying to do?</p> <p>Also, when //some login stuff includes a <code>$state.go(...)</code>, I get an infinite loop. What might cause that?</p> <hr> <p>Here's a more complete example demonstrating what we eventually got to work:</p> <pre><code>angular.module('test', ['ui.router', 'ngCookies']) .config(['$stateProvider', '$cookiesProvider', function($stateProvider, $cookiesProvider) { $stateProvider .state('public', { abstract: true }) .state('public.login', { url: '/login' }) .state('tool', { abstract: true }) .state('tool.suggestions', { url: '/suggestions' }); }]) .run(['$state', '$cookies', '$rootScope', function($state, $cookies, $rootScope) { $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) { if (toState.name.indexOf('tool') &gt; -1 &amp;&amp; !$cookies.Session) { // If logged out and transitioning to a logged in page: e.preventDefault(); $state.go('public.login'); } else if (toState.name.indexOf('public') &gt; -1 &amp;&amp; $cookies.Session) { // If logged in and transitioning to a logged out page: e.preventDefault(); $state.go('tool.suggestions'); }; }); }); </code></pre> <p>I don't like using <code>indexOf</code> to search for a particular state in the <code>toState</code>. It feels naive. I'm not sure why <code>toState</code> and <code>fromState</code> couldn't be an instance of the <code>$state</code> service, or why the <code>$state</code> service couldn't accept a state configuration override in its methods.</p> <p>The infinite looping was caused by a mistake on our part. I don't love this, so I'm still looking for better answers.</p>
24,010,392
1
7
null
2014-02-19 20:05:15.827 UTC
19
2018-07-20 12:56:30.32 UTC
2016-10-25 14:06:30.377 UTC
null
3,146,716
null
1,032,590
null
1
36
angularjs|angular-ui-router
104,647
<h3>Suggestion 1</h3> <p>When you add an object to <code>$stateProvider.state</code> that object is then passed with the state. So you can add additional properties which you can read later on when needed.</p> <p><strong>Example route configuration</strong></p> <pre><code>$stateProvider .state('public', { abstract: true, module: 'public' }) .state('public.login', { url: '/login', module: 'public' }) .state('tool', { abstract: true, module: 'private' }) .state('tool.suggestions', { url: '/suggestions', module: 'private' }); </code></pre> <p>The <code>$stateChangeStart</code> event gives you acces to the <code>toState</code> and <code>fromState</code> objects. These state objects will contain the configuration properties.</p> <p><strong>Example check for the custom module property</strong></p> <pre><code>$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) { if (toState.module === 'private' &amp;&amp; !$cookies.Session) { // If logged out and transitioning to a logged in page: e.preventDefault(); $state.go('public.login'); } else if (toState.module === 'public' &amp;&amp; $cookies.Session) { // If logged in and transitioning to a logged out page: e.preventDefault(); $state.go('tool.suggestions'); }; }); </code></pre> <p>I didn't change the logic of the cookies because I think that is out of scope for your question.</p> <h3>Suggestion 2</h3> <p>You can create a Helper to get you this to work more modular.</p> <p><strong>Value <code>publicStates</code></strong></p> <pre><code>myApp.value('publicStates', function(){ return { module: 'public', routes: [{ name: 'login', config: { url: '/login' } }] }; }); </code></pre> <p><strong>Value <code>privateStates</code></strong></p> <pre><code>myApp.value('privateStates', function(){ return { module: 'private', routes: [{ name: 'suggestions', config: { url: '/suggestions' } }] }; }); </code></pre> <p><strong>The Helper</strong></p> <pre><code>myApp.provider('stateshelperConfig', function () { this.config = { // These are the properties we need to set // $stateProvider: undefined process: function (stateConfigs){ var module = stateConfigs.module; $stateProvider = this.$stateProvider; $stateProvider.state(module, { abstract: true, module: module }); angular.forEach(stateConfigs, function (route){ route.config.module = module; $stateProvider.state(module + route.name, route.config); }); } }; this.$get = function () { return { config: this.config }; }; }); </code></pre> <p>Now you can use the helper to add the state configuration to your state configuration.</p> <pre><code>myApp.config(['$stateProvider', '$urlRouterProvider', 'stateshelperConfigProvider', 'publicStates', 'privateStates', function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) { helper.config.$stateProvider = $stateProvider; helper.process(publicStates); helper.process(privateStates); }]); </code></pre> <p>This way you can abstract the repeated code, and come up with a more modular solution.</p> <p>Note: the code above isn't tested</p>
17,283,018
The call is ambiguous between single method i.e extension method
<p>I have an extension method like</p> <pre><code>public static class Extension { public static string GetTLD(this string str) { var host = new System.Uri(str).Host; int index = host.LastIndexOf('.'), last = 3; while (index &gt;= last - 3) { last = index; index = host.LastIndexOf('.', last - 1); } var domain = host.Substring(index + 1); return domain; } } </code></pre> <p>And I am calling this like</p> <pre><code>string domain = "." + _url.GetTLD(); </code></pre> <p>I am getting no error at building and clean build.<br> But I am getting <code>compilation error</code> at run time error saying</p> <blockquote> <p>The call is ambiguous between the following methods or properties: 'myIGNOU.Extension.GetTLD(string)' and 'myIGNOU.Extension.GetTLD(string)'</p> </blockquote> <p>I swear that I don't have this extension method placed any where else too in the project. Why I am getting this error only at run time..?</p> <p>But if I delete this method then I am getting error at build time not not at run time. Everything works fine without the code of this method.</p> <p><a href="https://www.dropbox.com/s/tndh2zqzim01bj4/Compilation%20Error.htm">Here is compilation error page</a></p>
17,285,002
6
18
null
2013-06-24 19:00:55.073 UTC
3
2017-10-24 12:08:20.373 UTC
2013-06-24 20:30:46.48 UTC
null
270,348
null
1,306,394
null
1
29
c#|asp.net|runtime-error|ambiguous
11,083
<p>This is not a real solution and I can't explain how did it work but it worked.</p> <p>I was trying everything in Project Properties, References, bin, obj but nothing helped me really. And I was just trying every option and chose 'Convert to Web Application' from the context menu. Although It was a Web Application itself before. It showed me a warning saying that <code>.designer.cs</code> files will be added to each aspx file and I just clicked OK.</p> <p>Everything remained same except <code>App_Code</code> folder (where all these classes were) was renamed to <code>Old App_Code</code> and I'd build the project. And now I am not getting compilation error at run time.</p> <p>I know App_Code folder are meant to Website Project and I was having no issue with this till this time in WAP. But I just realize I should not have App_Code folder in WAP as it is discussed here in a <a href="http://p2p.wrox.com/book-beginning-asp-net-3-5-c-vb-book-isbn-978-0-470-18759-3/73539-app_code-folder-web-application-project.html#post237879">wrox forum (1st point)</a>. Author has said here that</p> <blockquote> <p>App_Code is not supported in a WAP. The App_Code folder is compiled at <em>run-time</em>; all code in a WAP is compiled at compile / development time. So, when you add an App_Code folder to a WAP. you end up with duplicate code; for example, a class defined in App_Code will also show up in the wap DLL. The fix is easy: just name the folder something else like Classes or CodeFiles.</p> </blockquote> <p>I have tried it renaming too before conversion but that time it did not work.</p>
17,178,907
How to get a permanent user token for writes using the Trello API?
<p>I'm trying to write an app that updates my Trello cards with the API. How do I get a permanent user token for the app to write to my Trello board?</p> <p>Thanks</p>
17,301,115
3
0
null
2013-06-18 21:04:21.397 UTC
17
2017-03-14 10:24:04.463 UTC
null
null
null
null
233,798
null
1
34
trello
13,818
<p>You can do this in one of 2 ways -</p> <p>Direct the user to the below address. This will direct the user to a page that has a token that she can copy and paste back to you. The important bit is that you ask for <code>expiration = never</code> and <code>scope = read,write</code></p> <pre><code>https://trello.com/1/authorize?key=substitutewithyourapplicationkey&amp;scope=read%2Cwrite&amp;name=My+Application&amp;expiration=never&amp;response_type=token </code></pre> <p>Or use OAuth (harder) to automate the request for an access token. Read more in the <a href="https://trello.com/docs/gettingstarted/index.html#getting-a-token-from-a-user">documentation</a>.</p> <p>Once you have the token, you can make any API call you'd like. </p>
17,505,835
How do I set up the hosts file for multiple domains/hosts with the same IP?
<p>As you surely know you can map host names to IP addresses with the "hosts" file. This is very useful especially when you are developing as you can change localhost for project1.</p> <p>That part is clear, but unfortunately I can't figure out how to set this up to open multiple projects with the same IP. I've tried a few things without success such as: </p> <pre><code>127.0.0.1/projects/project1 project1 127.0.0.1/projects/project2 project2 </code></pre> <p>I checked some related questions but I couldn't find an answer. So, can I accomplish what I'm trying to do somehow? Any suggestions?</p>
17,893,591
3
0
null
2013-07-06 18:25:11.633 UTC
15
2022-09-15 07:49:27.263 UTC
2019-07-24 17:22:41.673 UTC
null
964,243
null
736,086
null
1
50
hosts|web-development-server
103,855
<p>I got this resolved thanks to Google and the collaborators, @jvilhena and @DRC. Here's how I did it:</p> <p>If you are using Windows and XAMPP as in my case the first step is to set up the 'hosts' file. If you are using Windows it's likely that you will find it in C:\Windows\System32\drivers\etc\hosts. You can use any text editor to edit it.</p> <p>You can set up as many host names as you like all pointing to your localhost, with the IP, 127.0.0.1.</p> <p>For example:</p> <pre><code> 127.0.0.1 local.project1 127.0.0.1 local.project2 127.0.0.1 youcanuseany.name.here </code></pre> <p>The second step was to deal with the Apache file httpd-vhosts.conf. Again, I'm using Windows and XAMPP. It's likely this file will be in C:\xampp\apache\conf\extra\httpd-vhosts.conf.</p> <p>You don't have to but I like to keep my project folders in my htdocs folder @ C:\xampp\htdocs.</p> <p>For each project that you create a "host name" for, you should add the following to your httpd-vhosts.conf file:</p> <pre><code>&lt;VirtualHost *&gt; DocumentRoot "C:\xampp\htdocs\projectx" ServerName youcanuseany.name.here &lt;Directory "C:\xampp\htdocs\projectx"&gt; Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>One more example just for the sake of it :)</p> <pre><code>&lt;VirtualHost *&gt; DocumentRoot "C:\xampp\htdocs\project1" ServerName local.project1 &lt;Directory "C:\xampp\htdocs\project1"&gt; Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>Now you can type <code>local.project1</code> and <code>youcanuseany.name.here</code> in your browser and it should open your project as if you were typing <code>localhost/project1</code> and <code>localhost/projectX</code>. I hope this helps.</p>
18,647,611
Posting JSON data to API using CURL
<p>When I'm posting <code>json</code> data to API using <code>curl</code> - I'm not getting any output. I would like to send email invitation to recipient. </p> <pre><code>$url_send ="http://api.address.com/SendInvitation?"; $str_data = json_encode($data); function sendPostData ($url, $post) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); return curl_exec($ch); } </code></pre> <p>And here is <code>JSON</code> <code>$str_data</code></p> <pre><code>[ { "authorizedKey" : "abbad35c5c01-xxxx-xxx", "senderEmail" : "[email protected]", "recipientEmail" : "[email protected]", "comment" : "Invitation", "forceDebitCard" : "false" } ] </code></pre> <p>And calling function:</p> <pre><code>$response = sendPostData($url_send, $str_data); </code></pre> <p>This is the API: <a href="https://api.payquicker.com/Help/Api/POST-api-SendInvitation" rel="noreferrer">https://api.payquicker.com/Help/Api/POST-api-SendInvitation</a></p>
18,648,053
3
0
null
2013-09-05 23:36:36.303 UTC
2
2018-09-12 15:57:13.337 UTC
2014-07-14 09:22:00.313 UTC
null
542,420
null
2,729,422
null
1
12
php|json|api|curl
77,320
<p>Try adding <code>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);</code><br> And changing <code>http_build_query($post)</code> to <code>$post</code></p> <p>The implementation:</p> <pre><code>&lt;?php $data = array( "authorizedKey" =&gt; "abbad35c5c01-xxxx-xxx", "senderEmail" =&gt; "[email protected]", "recipientEmail" =&gt; "[email protected]", "comment" =&gt; "Invitation", "forceDebitCard" =&gt; "false" ); $url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx"; $str_data = json_encode($data); function sendPostData($url, $post){ $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS,$post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec($ch); curl_close($ch); // Seems like good practice return $result; } echo " " . sendPostData($url_send, $str_data); ?&gt; </code></pre> <p>The response I get is:</p> <pre><code>{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"} </code></pre> <p>But maybe it will work with valid data....</p> <p><strong>Edit:</strong> For posting xml, it's the same as on their site, except in a string:</p> <pre><code>$xml = ' &lt;SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models"&gt; &lt;authorizedKey&gt;80c587b9-caa9-4e56-8750-a34b17dba0a2&lt;/authorizedKey&gt; &lt;comment&gt;sample string 4&lt;/comment&gt; &lt;forceDebitCard&gt;true&lt;/forceDebitCard&gt; &lt;recipientEmail&gt;sample string 3&lt;/recipientEmail&gt; &lt;senderEmail&gt;sample string 2&lt;/senderEmail&gt; &lt;/SendInvitationRequest&gt;'; </code></pre> <p>Then:</p> <pre><code>sendPostData($url_send, $xml) </code></pre>
9,796,101
Exchange - listing mailboxes in an OU with their mailbox size
<p>I'm trying to display all the mailboxes and their sizes for all our users in our Departed OU. I seem to be very close but my command seems to be adding some padding to the results.</p> <pre><code>[PS] C:\Windows\system32&gt;dsquery user "ou=Departed,ou=Staff,dc=COMPANY,dc=local" -limit 4 | dsget user -samid | Get-MailboxStatistics | ft DisplayName, TotalItemSize, ItemCount </code></pre> <p>And the output:</p> <pre><code>Dsquery has reached the specified limit on number of results to display; use a different value for the -limit option to display more results.The specified mailbox " samid " doesn't exist. + CategoryInfo : NotSpecified: (0:Int32) [Get-MailboxStatistics], ManagementObjectNotFoundException + FullyQualifiedErrorId : DD7D7CEA,Microsoft.Exchange.Management.MapiTasks.GetMailboxStatistics The specified mailbox " Eka.Tian " doesn't exist. + CategoryInfo : NotSpecified: (1:Int32) [Get-MailboxStatistics], ManagementObjectNotFoundException + FullyQualifiedErrorId : 7F701DFD,Microsoft.Exchange.Management.MapiTasks.GetMailboxStatistics </code></pre> <p>Obviously shouldnt work for the first result "samid" but "Eka.Tian" exists. Why is it adding all those spaces? Is there a way I could format the output from dsget user so it plays nice with Get-MailboxStatistics?</p>
9,796,371
2
0
null
2012-03-20 22:40:17.063 UTC
2
2019-01-25 10:34:55.07 UTC
null
null
null
null
1,273,286
null
1
3
powershell|exchange-server
103,260
<p>Why the dsquery?</p> <pre><code>get-mailbox -OrganizationalUnit "ou=Departed,ou=Staff,dc=COMPANY,dc=local" -resultsize unlimited | get-mailboxstatistics | ft DisplayName,TotalItemSize,Itemcount </code></pre>
23,401,652
fatal: The current branch master has no upstream branch
<p>I'm trying to push one of my projects to github, and I keep getting this error:</p> <pre><code>peeplesoft@jane3:~/846156 (master) $ git push fatal: The current branch master has no upstream branch. To push the current branch and set the remote as upstream, use git push --set-upstream origin master </code></pre> <p>So I tried it and got this:</p> <pre><code>peeplesoft@jane3:~/846156 (master) $ git push --set-upstream origin master fatal: Authentication failed </code></pre> <p>Another stackoverflow thread suggested I try the following, with disappointing results.</p> <pre><code>peeplesoft@jane3:~/846156 (master) $ git push -u origin master fatal: Authentication failed </code></pre> <p>Then I tried this:</p> <pre><code>peeplesoft@jane3:~/846156 (master) $ git config remote.origin.push HEAD peeplesoft@jane3:~/846156 (master) $ git push fatal: Authentication failed </code></pre> <p>Any hints?</p>
23,402,125
31
7
null
2014-05-01 03:38:33.823 UTC
98
2022-09-21 06:53:39.03 UTC
2015-01-05 02:44:14.237 UTC
null
31,671
null
1,524,361
null
1
372
git|github
945,488
<p>You fixed the push, but, independently of that push issue (which I explained in "<a href="https://stackoverflow.com/a/17096880/6309">Why do I need to explicitly push a new branch?</a>": <code>git push -u origin master</code> or <code>git push -u origin --all</code>), you need now to resolve the authentication issue.</p> <p>That depends on your url (ssh as in '<code>[email protected]/yourRepo</code>, or https as in <code>https://github.com/You/YourRepo</code>)</p> <p>For https url:</p> <p>If your account is protected by the <a href="https://github.com/blog/1614-two-factor-authentication" rel="noreferrer">two-factor authentication</a>, your regular password won't work (for https url), <a href="https://superuser.com/a/647862/141">as explained here</a> <a href="https://stackoverflow.com/a/21027728/6309">or here</a>. </p> <p>Same problem if your password contains special character (as in <a href="https://stackoverflow.com/a/22512390/6309">this answer</a>)</p> <p>If https doesn't work (because you don't want to generate a secondary key, a PAT: personal Access Token), then you can switch to ssh, <a href="https://stackoverflow.com/a/17671315/6309">as I have shown here</a>.</p> <hr> <p>As noted by <a href="https://stackoverflow.com/users/985454/qwerty">qwerty</a> in the comments, you can automatically create the branch of same name on the remote with:</p> <pre><code>git push -u origin head </code></pre> <p>Why?</p> <ul> <li>HEAD (see your <code>.git\HEAD</code> file) has the refspec of the currently checked out branch (for example: <code>ref: refs/heads/master</code>)</li> <li>the default <a href="https://git-scm.com/docs/git-config#Documentation/git-config.txt-pushdefault" rel="noreferrer">push policy</a> is <strong><a href="https://stackoverflow.com/a/6547682/6309">simple</a></strong></li> </ul> <p>Since the refpec used for this push is head: (no destination), a missing <code>:&lt;dst&gt;</code> means to update the same ref as the <code>&lt;src&gt;</code> (head, which is a branch).</p> <p>That won't work if <a href="https://stackoverflow.com/a/3965714/6309">HEAD is detached</a> though.</p>
5,502,688
Using Markov chains (or something similar) to produce an IRC-bot
<p>I tried google and found little that I could understand.</p> <p>I understand <a href="http://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">Markov chains</a> to a very basic level: It's a mathematical model that only depends on previous input to change states..so sort of a FSM with weighted random chances instead of different criteria?</p> <p>I've heard that you can use them to generate semi-intelligent nonsense, given sentences of existing words to use as a dictionary of kinds. </p> <p>I can't think of search terms to find this, so can anyone link me or explain how I could produce something that gives a semi-intelligent answer? (if you asked it about pie, it would not start going on about the vietnam war it had heard about)</p> <p>I plan on:</p> <ul> <li>Having this bot idle in IRC channels for a bit</li> <li>Strip any usernames out of the string and store as sentences or whatever</li> <li>Over time, use this as the basis for the above.</li> </ul>
5,502,971
3
0
null
2011-03-31 15:54:46.017 UTC
15
2011-06-16 11:42:40.12 UTC
2011-03-31 16:22:59.563 UTC
null
166,749
null
407,879
null
1
20
artificial-intelligence|nlp|markov-chains
8,164
<p>Yes, a Markov chain is a finite-state machine with probabilistic state transitions. To generate random text with a simple, first-order Markov chain:</p> <ol> <li>Collect bigram (adjacent word pair) statistics from a corpus (collection of text).</li> <li>Make a markov chain with one state per word. Reserve a special state for end-of-text.</li> <li>The probability of jumping from state/word <em>x</em> to <em>y</em> is the probability of the words <em>y</em> immediately following <em>x</em>, estimated from relative bigram frequencies in the training corpus.</li> <li>Start with a random word <em>x</em> (perhaps determined by how often that word occurs as the first word of a sentence in the corpus). Then pick a state/word <em>y</em> to jump to randomly, taking into account the probability of <em>y</em> following <em>x</em> (the state transition probability). Repeat until you hit end-of-text.</li> </ol> <p>If you want to get something semi-intelligent out of this, then your best shot is to train it on lots of carefully collected texts. The "lots" part makes it produce proper sentences (or plausible IRC speak) with high probability; the "carefully collected" part means you control what it talks about. Introducing higher-order Markov chains also helps in both areas, but takes more storage to store the necessary statistics. You may also look into things like statistical smoothing.</p> <p>However, having your IRC bot actually respond to what is said to it takes a <em>lot</em> more than Markov chains. It may be done by doing <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Document_classification" rel="noreferrer">text categorization</a> (aka topic spotting) on what is said, then picking a domain-specific Markov chain for text generation. Naïve Bayes is a popular model for topic spotting.</p> <p>Kernighan and Pike in <a href="http://cm.bell-labs.com/cm/cs/tpop/" rel="noreferrer"><em>The Practice of Programming</em></a> explore various implementation strategies for Markov chain algorithms. These, and natural language generation in general, is covered in great depth by Jurafsky and Martin, <a href="http://www.cs.colorado.edu/~martin/slp.html" rel="noreferrer"><em>Speech and Language Processing</em></a>.</p>
25,642,585
How to check if object is null or not except == null
<p>I want to make method that will check if the class instance is null or not.</p> <p>Simply I know that i can use <code>== null</code>, but I want to know that is there any other way that can be implemented to check if instance is null or not ?</p> <p>I have nearly <code>70-80</code> class instance. &amp; all that class extend same Class <code>BaseEntity</code>.</p> <p>at time of declaration I have declare each instance like :</p> <p>Entity1 instance1 = null;</p> <p>like so I have defined all <code>70 class instances</code>.</p> <p>when they will be used I am initializing them using new. but at end of my main <code>Entity Processor</code>, I have to store data of each Entity id it is initialized, so for that I ll have to check if instance is null or not ?</p> <p><code>All Entities extend</code> same class <code>BaseEntity</code> so I have made following method.</p> <p>I know only one method :</p> <pre><code>public boolean checkIfEntityNull(BaseEntity entity){ return entity != null ? true : false; } </code></pre> <p>if it returns <code>true</code> then I ll call it's <code>save method of repository to save data in DB</code> otherwise it ll not call save method.</p> <p>So any guidance on it guys.</p>
25,642,884
1
3
null
2014-09-03 10:58:35.083 UTC
5
2014-09-03 11:34:10.003 UTC
null
null
null
null
3,145,373
null
1
21
java|null
124,732
<p>The easiest way to check is <code>entity == null</code>. There is no shorter way to do that.</p> <p>Note that there is a method for this in the standard lib:</p> <p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-" rel="noreferrer">Objects.isNull(Object obj)</a></p> <p>And another one which is the opposite of the above one:</p> <p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#nonNull-java.lang.Object-" rel="noreferrer">Objects.nonNull(Object obj)</a></p> <p>And there is yet another one which can be used to force a value to be not <code>null</code>, it throws a <code>NullPointerException</code> otherwise:</p> <p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#requireNonNull-T-" rel="noreferrer"> T Objects.requireNonNull(T obj);</a></p> <p><strong>Note:</strong> The <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html" rel="noreferrer">Objects</a> class was added in Java 7, but the <code>isNull()</code> and <code>nonNull()</code> methods were added only in Java 8.</p>
25,802,786
Is there any way to recover recently deleted documents in MongoDB?
<p>I have removed some documents in my last query by mistake, Is there any way to rollback my last query mongo collection.</p> <p>Here it is my last query :</p> <pre><code> db.foo.remove({ "name" : "some_x_name"}) </code></pre> <p>Is there any rollback/undo option? Can I get my data back?</p>
25,809,807
2
3
null
2014-09-12 07:15:25.057 UTC
10
2020-01-20 05:28:24.657 UTC
2020-01-20 05:28:24.657 UTC
null
3,835,758
null
3,835,758
null
1
33
mongodb|rollback
81,051
<p>There is no rollback option (<a href="http://docs.mongodb.org/manual/core/replica-set-rollbacks/">rollback has a different meaning</a> in a MongoDB context), and strictly speaking there is no supported way to get these documents back - the precautions you can/should take are covered in the comments. With that said however, if you are running a replica set, even a single node replica set, then you have an <a href="http://docs.mongodb.org/manual/core/replica-set-oplog/#replica-set-oplog"><code>oplog</code></a>. With an <code>oplog</code> that covers when the documents were inserted, you may be able to recover them.</p> <p>The easiest way to illustrate this is with an example. I will use a simplified example with just 100 deleted documents that need to be restored. To go beyond this (huge number of documents, or perhaps you wish to only selectively restore etc.) you will either want to change the code to iterate over a cursor or write this using your language of choice outside the MongoDB shell. The basic logic remains the same.</p> <p>First, let's create our example collection <code>foo</code> in the database <code>dropTest</code>. We will insert 100 documents without a <code>name</code> field and 100 documents with an identical <code>name</code> field so that they can be mistakenly removed later:</p> <pre><code>use dropTest; for(i=0; i &lt; 100; i++){db.foo.insert({_id : i})}; for(i=100; i &lt; 200; i++){db.foo.insert({_id : i, name : "some_x_name"})}; </code></pre> <p>Now, let's simulate the accidental removal of our 100 <code>name</code> documents:</p> <pre><code>&gt; db.foo.remove({ "name" : "some_x_name"}) WriteResult({ "nRemoved" : 100 }) </code></pre> <p>Because we are running in a replica set, we still have a record of these documents in the <code>oplog</code> (being inserted) and thankfully those inserts have not (yet) fallen off the end of the <code>oplog</code> (the <code>oplog</code> is a <a href="http://docs.mongodb.org/manual/core/capped-collections/">capped collection</a> remember) . Let's see if we can find them:</p> <pre><code>use local; db.oplog.rs.find({op : "i", ns : "dropTest.foo", "o.name" : "some_x_name"}).count(); 100 </code></pre> <p>The count looks correct, we seem to have our documents still. I know from experience that the only piece of the <code>oplog</code> entry we will need here is the <code>o</code> field, so let's add a projection to only return that (output snipped for brevity, but you get the idea):</p> <pre><code>db.oplog.rs.find({op : "i", ns : "dropTest.foo", "o.name" : "some_x_name"}, {"o" : 1}); { "o" : { "_id" : 100, "name" : "some_x_name" } } { "o" : { "_id" : 101, "name" : "some_x_name" } } { "o" : { "_id" : 102, "name" : "some_x_name" } } { "o" : { "_id" : 103, "name" : "some_x_name" } } { "o" : { "_id" : 104, "name" : "some_x_name" } } </code></pre> <p>To re-insert those documents, we can just store them in an array, then iterate over the array and insert the relevant pieces. First, let's create our array:</p> <pre><code>var deletedDocs = db.oplog.rs.find({op : "i", ns : "dropTest.foo", "o.name" : "some_x_name"}, {"o" : 1}).toArray(); &gt; deletedDocs.length 100 </code></pre> <p>Next we remind ourselves that we only have 100 docs in the collection now, then loop over the 100 inserts, and finally revalidate our counts:</p> <pre><code>use dropTest; db.foo.count(); 100 // simple for loop to re-insert the relevant elements for (var i = 0; i &lt; deletedDocs.length; i++) { db.foo.insert({_id : deletedDocs[i].o._id, name : deletedDocs[i].o.name}); } // check total and name counts again db.foo.count(); 200 db.foo.count({name : "some_x_name"}) 100 </code></pre> <p>And there you have it, with some caveats:</p> <ul> <li>This is not meant to be a true restoration strategy, look at backups (MMS, other), delayed secondaries for that, as mentioned in the comments</li> <li>It's not going to be particularly quick to query the documents out of the oplog (any oplog query is a table scan) on a large busy system.</li> <li>The documents may age out of the oplog at any time (you can, of course, make a copy of the oplog for later use to give you more time)</li> <li>Depending on your workload you might have to de-dupe the results before re-inserting them</li> <li>Larger sets of documents will be too large for an array as demonstrated, so you will need to iterate over a cursor instead</li> <li>The format of the <code>oplog</code> is considered internal and may change at any time (without notice), so use at your own risk</li> </ul>
9,136,674
Verify a method call using Moq
<p>I am fairly new to unit testing in C# and learning to use Moq. Below is the class that I am trying to test.</p> <pre><code>class MyClass { SomeClass someClass; public MyClass(SomeClass someClass) { this.someClass = someClass; } public void MyMethod(string method) { method = "test" someClass.DoSomething(method); } } class Someclass { public DoSomething(string method) { // do something... } } </code></pre> <p>Below is my TestClass:</p> <pre><code>class MyClassTest { [TestMethod()] public void MyMethodTest() { string action="test"; Mock&lt;SomeClass&gt; mockSomeClass = new Mock&lt;SomeClass&gt;(); mockSomeClass.SetUp(a =&gt; a.DoSomething(action)); MyClass myClass = new MyClass(mockSomeClass.Object); myClass.MyMethod(action); mockSomeClass.Verify(v =&gt; v.DoSomething(It.IsAny&lt;string&gt;())); } } </code></pre> <p>I get the following exception:</p> <pre><code>Expected invocation on the mock at least once, but was never performed No setups configured. No invocations performed.. </code></pre> <p>I just want to verify if the method "MyMethod" is being called or not. Am I missing something?</p>
9,136,721
1
5
null
2012-02-03 23:01:32.34 UTC
24
2019-11-24 10:43:40.777 UTC
2019-11-24 10:43:40.777 UTC
null
4,551,041
null
591,410
null
1
214
c#|testing|methods|moq
283,596
<p>You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.</p> <p>You should be doing something more like this:</p> <pre><code>class MyClassTest { [TestMethod] public void MyMethodTest() { string action = "test"; Mock&lt;SomeClass&gt; mockSomeClass = new Mock&lt;SomeClass&gt;(); mockSomeClass.Setup(mock =&gt; mock.DoSomething()); MyClass myClass = new MyClass(mockSomeClass.Object); myClass.MyMethod(action); // Explicitly verify each expectation... mockSomeClass.Verify(mock =&gt; mock.DoSomething(), Times.Once()); // ...or verify everything. // mockSomeClass.VerifyAll(); } } </code></pre> <p>In other words, you are verifying that calling <code>MyClass#MyMethod</code>, your class will definitely call <code>SomeClass#DoSomething</code> once in that process. Note that you don't need the <code>Times</code> argument; I was just demonstrating its value.</p>
18,588,927
Elasticsearch 503 error when checking server status
<p>I've been using elasticsearch as a search engine for my Rails application, however it stopped working properly due to a reason i can't understand. When making a curl request to elasticsearch server i get a 503 error.</p> <pre><code>curl -XGET http://localhost:9200 { "ok" : true, "status" : 503, "name" : "Killpower", "version" : { "number" : "0.90.3", "build_hash" : "5c38d6076448b899d758f29443329571e2522410", "build_timestamp" : "2013-08-06T13:18:31Z", "build_snapshot" : false, "lucene_version" : "4.4" }, "tagline" : "You Know, for Search" } </code></pre> <p>I've tried to solve the problem with reloading elasticsearch service and installing a new version without any success.</p> <p>Here is what I found in logs</p> <pre><code>[2013-09-03 12:31:45,320][INFO ][node ] [Killpower] version[0.90.3], pid[4222], build[5c38d60/2013-08-06T13:18:31Z] [2013-09-03 12:31:45,321][INFO ][node ] [Killpower] initializing ... [2013-09-03 12:31:45,327][INFO ][plugins ] [Killpower] loaded [], sites [] [2013-09-03 12:31:47,248][INFO ][node ] [Killpower] initialized [2013-09-03 12:31:47,248][INFO ][node ] [Killpower] starting ... [2013-09-03 12:31:47,313][INFO ][transport ] [Killpower] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/172.20.46.32:9300]} [2013-09-03 12:31:51,443][INFO ][discovery.zen ] [Killpower] master_left [[Amphibion][IMB4uACSTyOx3MO2u-FsWg][inet[/fe80:0:0:0:52e5:49ff:fec2:9718%2:9300]]], reason [do not exists on master, act as master failure] [2013-09-03 12:31:51,446][INFO ][discovery ] [Killpower] elasticsearch/iavpGrMtRHmWLHMTNpscGQ [2013-09-03 12:31:51,483][INFO ][http ] [Killpower] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/172.20.46.32:9200]} [2013-09-03 12:31:51,484][INFO ][node ] [Killpower] started [2013-09-03 12:31:54,712][WARN ][transport.netty ] [Killpower] exception caught on transport layer [[id: 0xa929f24d, /127.0.0.1:50456 =&gt; /127.0.0.1:9300]], closing connection </code></pre> <p>After that also follows a long java stacktrace. How can i fix the problem?</p>
21,629,814
4
1
null
2013-09-03 09:40:48.493 UTC
4
2020-08-27 09:00:45.653 UTC
null
null
null
null
1,022,108
null
1
28
search|curl|full-text-search|elasticsearch|tire
54,724
<p>There could be another instance in your local network with elasticsearch server up and running. Since shards in elasticsearch are working from the box and enabled by default there could be a conflict of master node. Please review your elasticsearch.log file. If there is something like </p> <pre><code>{"error":"MasterNotDiscoveredException[waited for [30s]]","status":503} </code></pre> <p>You should go to your config file <code>/etc/elasticsearch/elasticsearch.yml</code> and add this line:</p> <pre><code>discovery.zen.ping.multicast.enabled: false </code></pre>
18,544,359
How to read user input into a variable in Bash?
<p>I'm trying to create a script that simplifies the process of creating a new user on an iOS device. Here are the steps broken down:</p> <pre class="lang-bash prettyprint-override"><code>fullname=&quot;USER INPUT&quot; user=&quot;USER INPUT&quot; group=$user uid=1000 gid=1000 home=/var/$user echo &quot;$group:*:$gid:$user&quot; &gt;&gt; /private/etc/group echo &quot;$user::$uid:$gid::0:0:$fullname:$home:/bin/sh&quot; &gt;&gt; /private/etc/master.passwd passwd $user mkdir $home chown $user:$group $home </code></pre> <p>As you can see, some fields require input. How can I request input for a variable in the script?</p>
18,546,416
5
0
null
2013-08-31 04:03:08.007 UTC
40
2022-08-07 11:07:49.293 UTC
2022-08-07 11:04:09.283 UTC
null
775,954
null
2,602,638
null
1
162
bash|shell
220,330
<p>Use <a href="https://wiki.bash-hackers.org/commands/builtin/read" rel="noreferrer"><code>read -p</code></a>:</p> <pre><code># fullname=&quot;USER INPUT&quot; read -p &quot;Enter fullname: &quot; fullname # user=&quot;USER INPUT&quot; read -p &quot;Enter user: &quot; user </code></pre> <p>If you like to get the user's confirmation:</p> <pre><code>read -p &quot;Continue? (Y/N): &quot; confirm &amp;&amp; [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1 </code></pre> <p>You should also quote your variables to prevent pathname expansion and word splitting with spaces:</p> <pre><code># passwd &quot;$user&quot; # mkdir &quot;$home&quot; # chown &quot;$user:$group&quot; &quot;$home&quot; </code></pre>
18,538,428
Loading a .json file into c# program
<p>I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a <code>.json</code> file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the <code>.xml</code> file converted and saved as a <code>.json</code>. I would rather not use a 3rd party library.</p>
18,538,469
6
5
null
2013-08-30 17:28:25.99 UTC
4
2020-04-16 02:18:21.023 UTC
2020-03-27 00:29:56.93 UTC
null
1,127,428
null
2,654,083
null
1
51
c#|json
217,499
<p>You <strong><em>really</em></strong> should use an established library, such as <a href="http://www.nuget.org/packages/NewtonSoft.Json/">Newtonsoft.Json</a> (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in <a href="http://msdn.microsoft.com/en-us/library/bb355316.aspx">JavascriptSerializer</a>.</p> <p>Here's a sample of reading JSON using Newtonsoft.Json:</p> <pre><code>JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json")); // read JSON directly from a file using (StreamReader file = File.OpenText(@"c:\videogames.json")) using (JsonTextReader reader = new JsonTextReader(file)) { JObject o2 = (JObject) JToken.ReadFrom(reader); } </code></pre>
18,580,066
How to Allow Remote Access to PostgreSQL database
<p>I have PostgreSQL 9.2 Installed in Windows 7 and I have windows XP installed in Virtual Machine, how do I connect these two databases and allow remote access to add/edit the database from both Systems ?</p>
18,580,598
8
1
null
2013-09-02 20:05:38.643 UTC
49
2022-02-08 10:08:58.957 UTC
null
null
null
null
2,355,951
null
1
100
windows|postgresql|virtual-machine
224,899
<p>In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:</p> <p>postgresql.conf<br> pg_hba.conf</p> <p>Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)</p> <p>First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:<br> open the file <code>postgresql.conf</code> (usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter<br></p> <pre><code>listen_addresses = '*' </code></pre> <p>Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.<br> For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the <code>pg_hba.conf</code> file:</p> <pre><code>host all all 192.168.56.1/24 md5 </code></pre> <p>this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.</p> <p>Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.</p>
18,344,569
setting ng-href in <tr> elements
<p>The following code makes the client.name an anchor on each client in clients. I am interested in having the entire <code>&lt;tr&gt;</code> element be that link however. <code>ng-href</code> does not work on the <code>&lt;tr&gt;</code> element.. what can I do so that the entire row is a single link instantiated by <code>ng-href</code>?</p> <pre><code>&lt;tr ng-repeat="client in clients"&gt; &lt;td&gt;&lt;a ng-href="#/user/{{client.tagid}}"&gt;{{client.firstname}}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{client.lastname}}&lt;/td&gt; &lt;td&gt;{{client.inumber}}&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>What I am looking to do is something like this.. which of course does not work..</p> <pre><code>&lt;a ng-href="#/user/{{client.tagid}}"&gt; &lt;tr ng-repeat="client in clients"&gt; &lt;td&gt;{{client.firstname}}&lt;/td&gt; &lt;td&gt;{{client.lastname}}&lt;/td&gt; &lt;td&gt;{{client.inumber}}&lt;/td&gt; &lt;/tr&gt; &lt;/a&gt; </code></pre> <p>OR</p> <pre><code>&lt;tr ng-repeat="client in clients" ng-href="#/user/{{client.tagid}}"&gt; &lt;td&gt;{{client.firstname}}&lt;/td&gt; &lt;td&gt;{{client.lastname}}&lt;/td&gt; &lt;td&gt;{{client.inumber}}&lt;/td&gt; &lt;/tr&gt; </code></pre>
18,344,639
9
2
null
2013-08-20 20:40:56.537 UTC
3
2021-07-17 19:09:49.837 UTC
null
null
null
null
759,466
null
1
19
angularjs
46,012
<p>You can use an <a href="http://docs.angularjs.org/api/ng.directive:ngClick" rel="noreferrer">ng-click</a> (instead of onClick) as Jason suggests as well.</p> <p>Something like:</p> <p><strong>HTML</strong></p> <pre><code>&lt;tr ng-repeat="client in clients" ng-click="showClient(client)"&gt; &lt;td&gt;&lt;a ng-href="#/user/{{client.tagid}}"&gt;{{client.firstname}}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{{client.lastname}}&lt;/td&gt; &lt;td&gt;{{client.inumber}}&lt;/td&gt; &lt;/tr&gt; </code></pre> <p><strong>Controller</strong></p> <pre><code>$scope.showClient = function(client) { $location.path('#/user/' + client.tagid); }; </code></pre> <p>And styling to make it show as an clickable element (wont work in IE7)</p> <p><strong>CSS</strong></p> <pre><code>tr { cursor: pointer; } // or [ng-click] { cursor: pointer; } </code></pre>
18,389,124
Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?
<p>I want to create a database which does not exist through JDBC. Unlike MySQL, PostgreSQL does not support <code>create if not exists</code> syntax. What is the best way to accomplish this?</p> <p>The application does not know if the database exists or not. It should check and if the database exists it should be used. So it makes sense to connect to the desired database and if connection fails due to non-existence of database it should create new database (by connecting to the default <code>postgres</code> database). I checked the error code returned by Postgres but I could not find any relevant code that species the same.</p> <p>Another method to achieve this would be to connect to the <code>postgres</code> database and check if the desired database exists and take action accordingly. The second one is a bit tedious to work out.</p> <p>Is there any way to achieve this functionality in Postgres?</p>
18,389,184
10
0
null
2013-08-22 19:21:08.99 UTC
39
2021-08-03 21:21:51.433 UTC
2013-09-16 18:24:11.217 UTC
null
939,860
null
1,317,240
null
1
191
sql|database|postgresql|jdbc|ddl
210,174
<h3>Restrictions</h3> <p>You can ask the system catalog <a href="https://www.postgresql.org/docs/current/catalog-pg-database.html" rel="noreferrer"><code>pg_database</code></a> - accessible from any database in the same database cluster. The tricky part is that <a href="https://www.postgresql.org/docs/current/sql-createdatabase.html" rel="noreferrer"><code>CREATE DATABASE</code></a> can only be executed as a single statement. <a href="https://www.postgresql.org/docs/current/sql-createdatabase.html#id-1.9.3.61.7" rel="noreferrer">The manual:</a></p> <blockquote> <p><code>CREATE DATABASE</code> cannot be executed inside a transaction block.</p> </blockquote> <p>So it cannot be run directly inside a function or <a href="https://www.postgresql.org/docs/current/sql-do.html" rel="noreferrer"><code>DO</code></a> statement, where it would be inside a transaction block implicitly. SQL procedures, introduced with Postgres 11, <a href="https://dba.stackexchange.com/a/194811/3684">cannot help with this either</a>.</p> <h3>Workaround from within psql</h3> <p>You can work around it from within psql by executing the DDL statement conditionally:</p> <pre><code>SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec </code></pre> <p><a href="https://www.postgresql.org/docs/current/app-psql.html" rel="noreferrer">The manual:</a></p> <blockquote> <p><code>\gexec</code></p> <p>Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.</p> </blockquote> <h3>Workaround from the shell</h3> <p>With <code>\gexec</code> you only need to call psql <em>once</em>:</p> <pre><code>echo &quot;SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec&quot; | psql </code></pre> <p>You may need more psql options for your connection; role, port, password, ... See:</p> <ul> <li><a href="https://stackoverflow.com/questions/15359348/run-batch-file-with-psql-command-without-password/15593100#15593100">Run batch file with psql command without password</a></li> </ul> <p>The same cannot be called with <code>psql -c &quot;SELECT ...\gexec&quot;</code> since <code>\gexec</code> is a psql meta‑command and the <code>-c</code> option expects a single <em>command</em> for which <a href="https://www.postgresql.org/docs/current/app-psql.html" rel="noreferrer">the manual states:</a></p> <blockquote> <p><em><strong><code>command</code></strong></em> must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a <code>-c</code> option.</p> </blockquote> <h3>Workaround from within Postgres transaction</h3> <p>You could use a <code>dblink</code> connection back to the current database, which runs outside of the transaction block. Effects can therefore also not be rolled back.</p> <p>Install the additional module dblink for this (once per database):</p> <ul> <li><a href="https://stackoverflow.com/questions/3862648/how-to-use-install-dblink-in-postgresql/13264961#13264961">How to use (install) dblink in PostgreSQL?</a></li> </ul> <p>Then:</p> <pre><code>DO $do$ BEGIN IF EXISTS (SELECT FROM pg_database WHERE datname = 'mydb') THEN RAISE NOTICE 'Database already exists'; -- optional ELSE PERFORM dblink_exec('dbname=' || current_database() -- current db , 'CREATE DATABASE mydb'); END IF; END $do$; </code></pre> <p>Again, you may need more psql options for the connection. See Ortwin's added answer:</p> <ul> <li><a href="https://stackoverflow.com/questions/18389124/simulate-create-database-if-not-exists-for-postgresql/36218838#36218838">Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?</a></li> </ul> <p>Detailed explanation for dblink:</p> <ul> <li><a href="https://stackoverflow.com/questions/1113277/how-do-i-do-large-non-blocking-updates-in-postgresql">How do I do large non-blocking updates in PostgreSQL?</a></li> </ul> <p>You can make this a function for repeated use.</p>
15,007,637
Deleting carriage returns caused by line reading
<p>I have a list:</p> <pre><code>Cat Dog Monkey Pig </code></pre> <p>I have a script:</p> <pre><code>import sys input_file = open('list.txt', 'r') for line in input_file: sys.stdout.write('"' + line + '",') </code></pre> <p>The output is:</p> <pre><code>"Cat ","Dog ","Monkey ","Pig", </code></pre> <p>I'd like:</p> <pre><code>"Cat","Dog","Monkey","Pig", </code></pre> <p>I can't get rid of the carriage return that occurs from processing the lines in the list. Bonus point for getting rid of the , at the end. Not sure how to just find and delete the last instance.</p>
15,007,662
3
0
null
2013-02-21 16:41:40.34 UTC
3
2013-02-21 16:50:32.937 UTC
null
null
null
null
1,721,444
null
1
26
python|python-2.7
74,995
<p><a href="http://docs.python.org/2/library/stdtypes.html#str.rstrip" rel="noreferrer">str.rstrip</a> or simply <a href="http://docs.python.org/2/library/stdtypes.html#str.strip" rel="noreferrer">str.strip</a> is the right tool to split carriage return (newline) from the data read from the file. Note str.strip will strip of whitespaces from either end. If you are only interested in stripping of newline, just use <code>strip('\n')</code></p> <p>Change the line</p> <pre><code> sys.stdout.write('"' + line + '",') </code></pre> <p>to</p> <pre><code>sys.stdout.write('"' + line.strip() + '",') </code></pre> <p>Note in your case, a more simplistic solution would had been</p> <pre><code>&gt;&gt;&gt; from itertools import imap &gt;&gt;&gt; with open("list.txt") as fin: print ','.join(imap(str.strip, fin)) Cat,Dog,Monkey,Pig </code></pre> <p>or Just using List COmprehension</p> <pre><code>&gt;&gt;&gt; with open("test.txt") as fin: print ','.join(e.strip('\n') for e in fin) Cat,Dog,Monkey,Pig </code></pre>
14,954,220
How to check if obtained homography matrix is good?
<p>This question was already <a href="https://stackoverflow.com/questions/11053099/how-can-you-tell-if-a-homography-matrix-is-acceptable-or-not">asked</a>, but I still don't get it. I obtain a homography matrix by calling <code>cv::findHomography</code> from a set of points. I need to check whether it's relevant or not.<br>The proposed method is to calculate maximum reprojection error for inliers and compare it with a threshold. But after such filtration I keep getting insane transformations with object bounding box transforming to almost a straight line or some strange non-convex quadrangle, with self-intersections etc.<br>What constraints can be used to check if the homography matrix itself is adequate?</p>
14,965,352
2
1
null
2013-02-19 09:37:27.51 UTC
19
2017-02-08 10:46:14.423 UTC
2017-05-23 10:30:49.723 UTC
null
-1
null
609,063
null
1
29
opencv|image-processing|computer-vision|homography|ransac
15,520
<p>Your question is mathematical. Given a matrix of 3x3 decide whether it represents a good rigid transformation. It is hard to define what is "good" but here are some clues that can help you</p> <ol> <li>Homography should preserve the direction of polygonal points. Design a simple test. points (0,0), (imwidth,0), (width,height), (0,height) represent a quadrilateral with clockwise arranged points. Apply homography on those points and see if they are still clockwise arranged if they become counter clockwise your homography is flipping (mirroring) the image which is sometimes still ok. But if your points are out of order than you have a "bad homography" </li> <li>The homography doesn't change the scale of the object too much. For example if you expect it to shrink or enlarge the image by a factor of up to X, just check this rule. Transform the 4 points (0,0), (imwidth,0), (width-1,height), (0,height) with homography and calculate the area of the quadrilateral (opencv method of calculating area of polygon) if the ratio of areas is too big (or too small), you probably have an error.</li> <li>Good homography is usually uses low values of perspectivity. Typically if the size of the image is ~1000x1000 pixels those values should be ~0.005-0.001. High perspectivity will cause enormous distortions which are probably an error. If you don't know where those values are located read my post: <a href="https://stackoverflow.com/questions/10667834/trying-to-understand-the-affine-transform/">trying to understand the Affine Transform</a> . It explains the affine transform math and the other 2 values are perspective parameters.</li> </ol> <p>I think that if you check the above 3 condition (condition 2 is the most important) you will be able to detect most of the problems. Good luck</p>
15,085,118
PrettyPrint python into a string, and not stdout
<p>I'd like to use prettyprint to print out a dictionary, but into a string and not to console. This string is to be passed on to other functions.</p> <p>I know I can use the "stream" parameter to specify a file instead of sys.out but I want a string.</p> <p>How do I do that?</p>
15,085,170
3
5
null
2013-02-26 09:09:15.513 UTC
4
2013-02-26 10:42:24.72 UTC
null
null
null
null
1,724,926
null
1
40
python
15,196
<p>Just use the <a href="http://docs.python.org/2/library/stringio.html" rel="nofollow"><code>StringIO</code> module</a>:</p> <pre><code>import StringIO output = StringIO.StringIO() </code></pre> <p>Now you may pass <code>output</code> as a stream to <code>prettyprint</code>.</p>
28,099,683
Algorithm for dependency resolution
<p>I'm in the process of writing a package manager, and for that I want the dependency resolution to be as powerful as possible.</p> <p>Each package has a list of versions, and each version contains the following information:</p> <ul> <li>A comparable ID</li> <li><strong>Dependencies</strong> (a list of packages and for each package a set of acceptable versions)</li> <li><strong>Conflicts</strong> (a list of packages and for each package a set of versions that cause issues together with this version)</li> <li><strong>Provides</strong> (a list of packages and for each package a set of versions that this package also provides/contains)</li> </ul> <p>For the current state I have a list of packages and their current versions.</p> <p>I now want to, given the list of available packages and the current state, be able to get a version for each package in a list of packages, taking the given constraints into account (dependencies, conflicting packages, packages provided by other packages) and get back a list of versions for each of these packages. Circular dependencies are possible.</p> <p>If no valid state can be reached, the versions of the existing packages may be changed, though this should only be done if necessary. Should it not be possible to reach a valid state as much information to the reason should be available (to tell the user "it could work if you remove X" etc.). </p> <p>If possible it should also be possible to "lock" packages to a specific version, in which case the version of the package may NOT be changed.</p> <p>What I'm trying to accomplish is very similar to what existing package managers already do, with the difference that not necessarily the latest version of a package needs to be used (an assumption which most package managers seem to do).</p> <p>The only idea I have so far is building a structure of all possible states, for all possible versions of the packages in question, and then removing invalid states. I really hope this is not the only solution, since it feels very "brute force"-ish. Staying under a few seconds for ~500 available packages with ~100 versions each, and ~150 installed packages would be a good goal (though the faster the better).</p> <p>I don't believe this is a language-specific question, but to better illustrate it, here is a bit of pseudecode:</p> <pre><code>struct Version integer id list&lt;Package, set&lt;integer&gt;&gt; dependencies list&lt;Package, set&lt;integer&gt;&gt; conflicts list&lt;Package, set&lt;integer&gt;&gt; provides struct Package string id list&lt;Version&gt; versions struct State map&lt;Package, Version&gt; packages map&lt;Package, boolean&gt; isVersionLocked State resolve(State initialState, list&lt;Package&gt; availablePackages, list&lt;Package&gt; newPackages) { // do stuff here } </code></pre> <p>(if you should have actual code or know about an existing implementation of something that does this (in any language, C++ preferred) feel free to mention it anyway)</p>
28,102,139
1
2
null
2015-01-22 22:17:02.93 UTC
17
2015-01-23 02:38:24.487 UTC
null
null
null
null
953,222
null
1
27
algorithm|dependency-management
12,461
<h2>It's NP-hard</h2> <p>Some bad news: This problem is NP-hard, so unless P=NP, there is no algorithm that can efficiently solve all instances of it. I'll prove this by showing how to convert, in polynomial time, any given instance of the NP-hard problem <a href="http://en.wikipedia.org/wiki/Boolean_satisfiability_problem#3-satisfiability">3SAT</a> into a dependency graph structure suitable for input to your problem, and how to turn the output of any dependency resolution algorithm on that problem back into a solution to the original 3SAT problem, again in polynomial time. The logic is basically that if there was some algorithm that could solve your dependency resolution problem in polynomial time, then it would also solve any 3SAT instance in polynomial time -- and since computer scientists have spent decades looking for such an algorithm without finding one, this is believed to be impossible.</p> <p>I'll assume in the following that at most one version of any package can be installed at any time. (This is equivalent to assuming that there are implicit conflicts between every pair of distinct versions of the same package.)</p> <p>First, let's formulate a slightly relaxed version of the dependency resolution problem in which we assume that no packages are already installed. All we want is an algorithm that, given a "target" package, either returns a set of package versions to install that (a) includes some version of the target package and (b) satisfies all dependency and conflict properties of every package in the set, or returns "IMPOSSIBLE" if no set of package versions will work. Clearly if this problem is NP-hard, then so is the more general problem in which we also specify a set of already-installed package versions that are not to be changed.</p> <h2>Constructing the instance</h2> <p>Suppose we are given a 3SAT instance containing n clauses and k variables. We will create 2 packages for each variable: one corresponding to the literal x_k, and one corresponding to the literal !x_k. The x_k package will have a conflict with the !x_k package, and vice versa, ensuring that at most one of these two packages will ever be installed by the package manager. All of these "literal" packages will have just a single version, and no dependencies.</p> <p>For each clause we will also create a single "parent" package, and 7 versions of a "child" package. Each parent package will be dependent on any of the 7 versions of its child package. Child packages correspond to ways of choosing at least one item from a set of 3 items, and will each have 3 dependencies on the corresponding literal packages. For example, a clause (p, !q, r) will have child package versions having dependencies on the literal packages (p, q, !r), (!p, !q, !r), (!p, q, r), (p, !q, !r), (p, q, r), (!p, !q, r), and (p, !q, r): the first 3 versions satisfy exactly one of the literals p, !q or r; the next 3 versions satisfy exactly 2; and the last satisfies all 3.</p> <p>Finally, we create a "root" package, which has all of the n parent clause packages as its dependencies. This will be the package that we ask the package manager to install.</p> <p>If we run the package manager on this set of 2k + 8n + 1 package versions, asking it to install the root package, it will either return "IMPOSSIBLE", or a list of package versions to install. In the former case, the 3SAT problem is unsatisfiable. In the latter case, we can extract values for the variables easily: if the literal package for x_k was installed, set x_k to <code>true</code>; if the literal package !x_k was installed, set x_k to <code>false</code>. (Note that there won't be any variables with neither literal package installed: each variable appears in at least one clause, and each clause produces 7 child package versions, at least one of which must be installed, and which will force installation of one of the two literals for that variable.)</p> <h2>Even some restrictions are hard</h2> <p>This construction doesn't make any use of pre-installed packages or "Provides" information, so the problem remains NP-hard even when those aren't permitted. More interestingly, given our assumption that at most one version of any package can be installed at a time, the problem remains NP-hard <em>even if we don't permit conflicts</em>: instead of making the literals x_k and !x_k separate packages with conflict clauses in each direction, we just make them two different versions of the same package!</p>
45,021,644
Is there way to determine why Azure App Service restarted?
<p>I have a bunch of websites running on a single instance of Azure App Service, and they're all set to Always On. They all suddenly restarted at the same time, causing everything to go slow for a few minutes as everything hit a cold request. </p> <p>I would expect this if the service had moved me to a new host, but that didn't happen -- I'm still on the same hostname. </p> <p>CPU and memory usage were normal at the time of the restart, and I didn't initiate any deployments or anything like that. I don't see an obvious reason for the restart.</p> <p>Is there any logging anywhere that I can see to figure out <em>why</em> they all restarted? Or is this just a normal thing that App Service does from time to time?</p>
45,242,214
2
9
null
2017-07-10 21:10:38.603 UTC
21
2022-04-02 10:45:58.11 UTC
null
null
null
null
32,187
null
1
40
azure|azure-web-app-service
15,213
<p>So, it seems the answer to this is &quot;no, you can't really know <em>why</em>, you can just infer that it <em>did</em>.&quot;</p> <p>I mean, you can add some Application Insights logging like</p> <pre><code> private void Application_End() { log.Warn($&quot;The application is shutting down because of '{HostingEnvironment.ShutdownReason}'.&quot;); TelemetryConfiguration.Active.TelemetryChannel.Flush(); // Server Channel flush is async, wait a little while and hope for the best Thread.Sleep(TimeSpan.FromSeconds(2)); } </code></pre> <p>and you will end up with <code>&quot;The application is shutting down because of 'ConfigurationChange'.&quot;</code> or <code>&quot;The application is shutting down because of 'HostingEnvironment'.&quot;</code>, but it doesn't really tell you what's going on at the host level.</p> <p>What I needed to accept is that App Service is going to restart things from time to time, and ask myself why I cared. App Service is supposed to be smart enough to wait for the application pool to be warmed up before sending requests to it (like overlapped recycling). Yet, my apps would sit there CPU-crunching for 1-2 minutes after a recycle.</p> <p>It took me a while to figure out, but the culprit was that all of my apps have a rewrite rule to redirect from HTTP to HTTPS. This does not work with the Application Initialization module: it sends a request to the root, and all it gets its a 301 redirect from the URL Rewrite module, and the ASP.NET pipeline isn't hit at all, the hard work wasn't actually done. App Service/IIS then thought the worker process was ready and then sends traffic to it. But the first &quot;real&quot; request actually follows the 301 redirect to the HTTPS URL, and bam! that user hits the pain of a cold start.</p> <p><a href="https://support.microsoft.com/en-us/help/2843964/application-initialization-module-fails-when-web-site-requires-ssl" rel="noreferrer">I added a rewrite rule described here</a> to exempt the Application Initialization module from needing HTTPS, so when it hits the root of the site, it will actually trigger the page load and thus the whole pipeline:</p> <pre><code>&lt;rewrite&gt; &lt;rules&gt; &lt;clear /&gt; &lt;rule name=&quot;Do not force HTTPS for application initialization&quot; enabled=&quot;true&quot; stopProcessing=&quot;true&quot;&gt; &lt;match url=&quot;(.*)&quot; /&gt; &lt;conditions&gt; &lt;add input=&quot;{HTTP_HOST}&quot; pattern=&quot;localhost&quot; /&gt; &lt;add input=&quot;{HTTP_USER_AGENT}&quot; pattern=&quot;Initialization&quot; /&gt; &lt;/conditions&gt; &lt;action type=&quot;Rewrite&quot; url=&quot;{URL}&quot; /&gt; &lt;/rule&gt; &lt;rule name=&quot;Force HTTPS&quot; enabled=&quot;true&quot; stopProcessing=&quot;true&quot;&gt; &lt;match url=&quot;(.*)&quot; ignoreCase=&quot;false&quot; /&gt; &lt;conditions&gt; &lt;add input=&quot;{HTTPS}&quot; pattern=&quot;off&quot; /&gt; &lt;/conditions&gt; &lt;action type=&quot;Redirect&quot; url=&quot;https://{HTTP_HOST}/{R:1}&quot; appendQueryString=&quot;true&quot; redirectType=&quot;Permanent&quot; /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; </code></pre> <p>It's one of many entries in a diary of moving old apps into Azure -- turns out there's a lot of things you can get away with when something's running on a traditional VM that seldom restarts, but it'll need some TLC to work out the kinks when migrating to our brave new world in the cloud....</p> <p>--</p> <p><strong>UPDATE 10/27/2017:</strong> Since this writing, Azure has added a new tool under &quot;Diagnose and solve problems&quot;. Click &quot;Web App Restarted&quot;, and it'll tell you the reason, usually because of storage latency or infrastructure upgrades. The above still stands though, in that when moving to Azure App Service, the best way forward is you really just have to coax your app into being comfortable with random restarts.</p> <p>--</p> <p><strong>UPDATE 2/11/2018:</strong> After migrating several legacy systems to a single instance of a medium App Service Plan (with plenty of CPU and memory overhead), I was having a vexing problem where my deployments from staging slots would go seamlessly, but whenever I'd get booted to a new host because of Azure infrastructure maintenance, everything would go haywire with downtime of 2-3 minutes. I was driving myself nuts trying to figure out why this was happening, because App Service is supposed to wait until it receives a successful response from your app before booting you to the new host.</p> <p>I was so frustrated by this that I was ready to classify App Service as enterprise garbage and go back to IaaS virtual machines.</p> <p>It turned out to be multiple issues, and I suspect others will come across them while porting their own beastly legacy ASP.NET apps to App Service, so I thought I'd run through them all here.</p> <p>The first thing to check is that you're actually doing real work in your <code>Application_Start</code>. For example, I'm using NHibernate, which while good at many things is quite a pig at loading its configuration, so I make sure to actually create the <code>SessionFactory</code> during <code>Application_Start</code> to make sure that the hard work is done.</p> <p>The second thing to check, as mentioned above, is that you don't have a rewrite rule for SSL that is interfering with App Service's warmup check. You can exclude the warmup checks from your rewrite rule as mentioned above. Or, in the time since I originally wrote that work around, App Service has added an <a href="https://blogs.msdn.microsoft.com/benjaminperkins/2017/11/30/how-to-make-an-azure-app-service-https-only/" rel="noreferrer">HTTPS Only</a> flag that allows you to do the HTTPS redirect at the load balancer instead of within your web.config file. Since it's handled at a layer of indirection above your application code, you don't have to think about it, so I would recommend the HTTPS Only flag as the way to go.</p> <p>The third thing to consider is whether or not you're using the <a href="https://docs.microsoft.com/en-us/azure/app-service/app-service-local-cache-overview" rel="noreferrer">App Service Local Cache Option</a>. In brief, this is an option where App Service will copy your app's files to the local storage of the instances that it's running on rather than off of a network share, and is a great option to enable if your app doesn't care if it loses changes written to the local filesystem. It speeds up I/O performance (which is important because, remember, <a href="https://stackoverflow.com/questions/36966505/azure-web-apps-are-really-slow">App Service runs on potatoes</a>) and eliminates restarts that are caused by any maintenance on network share. But, there is a specific subtlety regarding App Service's infrastructure upgrades that is poorly documented and you need to be aware of. Specifically, the Local Cache option is initiated in the background in a separate app domain after the first request, and then you're switched to the app domain when the local cache is ready. That means that App Service will hit a warmup request against your site, get a successful response, point traffic to that instance, but (whoops!) now Local Cache is grinding I/O in the background, and if you have a lot of sites on this instance, you've ground to a halt because App Service I/O is horrendous. If you don't know this is happening, it looks spooky in the logs because it's as if your app is starting up twice on the same instance (because it is). The solution is to follow this <a href="https://tech.jet.com/blog/2017/02-01-azure-web-apps/" rel="noreferrer">Jet blog post</a> and create an application initialization warmup page to monitors for the environment variable that tells you when the Local Cache is ready. This way, you can force App Service to delay booting you to the new instance until the Local Cache is fully prepped. Here's one that I use to make sure I can talk to the database, too:</p> <pre><code>public class WarmupHandler : IHttpHandler { public bool IsReusable { get { return false; } } public ISession Session { get; set; } public void ProcessRequest(HttpContext context) { if (context == null) { throw new ArgumentNullException(&quot;context&quot;); } var request = context.Request; var response = context.Response; var localCacheVariable = Environment.GetEnvironmentVariable(&quot;WEBSITE_LOCAL_CACHE_OPTION&quot;); var localCacheReadyVariable = Environment.GetEnvironmentVariable(&quot;WEBSITE_LOCALCACHE_READY&quot;); var databaseReady = true; try { using (var transaction = this.Session.BeginTransaction()) { var query = this.Session.QueryOver&lt;User&gt;() .Take(1) .SingleOrDefault&lt;User&gt;(); transaction.Commit(); } } catch { databaseReady = false; } var result = new { databaseReady, machineName = Environment.MachineName, localCacheEnabled = &quot;Always&quot;.Equals(localCacheVariable, StringComparison.OrdinalIgnoreCase), localCacheReady = &quot;True&quot;.Equals(localCacheReadyVariable, StringComparison.OrdinalIgnoreCase), }; response.ContentType = &quot;application/json&quot;; var warm = result.databaseReady &amp;&amp; (!result.localCacheEnabled || result.localCacheReady); response.StatusCode = warm ? (int)HttpStatusCode.OK : (int)HttpStatusCode.ServiceUnavailable; var serializer = new JsonSerializer(); serializer.Serialize(response.Output, result); } } </code></pre> <p>Also remember to map a route and add the application initialization your <code>web.config</code>:</p> <pre><code>&lt;applicationInitialization doAppInitAfterRestart=&quot;true&quot;&gt; &lt;add initializationPage=&quot;/warmup&quot; /&gt; &lt;/applicationInitialization&gt; </code></pre> <p>The fourth thing to consider is that sometimes App Service will restart your app for seemingly garbage reasons. It seems that setting the <code>fcnMode</code> property to <code>Disabled</code> can help; it prevents the runtime from restarting your app if someone diddles with configuration files or code on the server. If you're using staging slots and doing deployments that way, this shouldn't bother you. But if you expect to be able to FTP in and diddle with a file and see that change reflected in production, then don't use this option:</p> <pre><code> &lt;httpRuntime fcnMode=&quot;Disabled&quot; targetFramework=&quot;4.5&quot; /&gt; </code></pre> <p>The fifth thing to consider, <em>and this was primarily my problem all along</em>, is whether or not you are using staging slots with the <code>AlwaysOn</code> option enabled. The <code>AlwaysOn</code> option works by pinging your site every minute or so to make sure it's warm so that IIS doesn't spin it down. Inexplicably, <a href="https://social.msdn.microsoft.com/Forums/azure/en-US/f1a4664d-efba-4983-878b-9368a54a97f1/why-is-alwayson-not-a-slot-setting?forum=windowsazurewebsitespreview" rel="noreferrer">this isn't a sticky setting</a>, so you may have turned on <code>AlwaysOn</code> on both your production and staging slots so you don't have to mess with it every time. This causes a problem with App Service infrastructure upgrades when they boot you to a new host. Here's what happens: let's say you have 7 sites hosted on an instance, each with its own staging slot, everything with <code>AlwaysOn</code> enabled. App Service does the warmup and application initialization to your 7 production slots and dutifully waits for them to respond successfully before redirecting traffic over. <strong>But it doesn't do this for the staging slots.</strong> So it directs traffic over to the new instance, but then <code>AlwaysOn</code> kicks in 1-2 minutes later on the staging slots, so now you have 7 more sites starting up at the same time. Remember, <a href="https://stackoverflow.com/questions/36966505/azure-web-apps-are-really-slow">App Service runs on potatoes</a>, so all this additional I/O happening at the same time is going to destroy the performance of your production slots and will be perceived as downtime.</p> <p>The solution is to keep <code>AlwaysOn</code> off on your staging slots so you don't get nailed by this simultaneous I/O frenzy after an infrastructure update. If you are using a swap script via PowerShell, maintaining this &quot;Off in staging, On in production&quot; is surprisingly verbose to do:</p> <pre><code>Login-AzureRmAccount -SubscriptionId {{ YOUR_SUBSCRIPTION_ID }} $resourceGroupName = &quot;YOUR-RESOURCE-GROUP&quot; $appName = &quot;YOUR-APP-NAME&quot; $slotName = &quot;YOUR-SLOT-NAME-FOR-EXAMPLE-STAGING&quot; $props = @{ siteConfig = @{ alwaysOn = $true; } } Set-AzureRmResource ` -PropertyObject $props ` -ResourceType &quot;microsoft.web/sites/slots&quot; ` -ResourceGroupName $resourceGroupName ` -ResourceName &quot;$appName/$slotName&quot; ` -ApiVersion 2015-08-01 ` -Force Swap-AzureRmWebAppSlot ` -SourceSlotName $slotName ` -ResourceGroupName $resourceGroupName ` -Name $appName $props = @{ siteConfig = @{ alwaysOn = $false; } } Set-AzureRmResource ` -PropertyObject $props ` -ResourceType &quot;microsoft.web/sites/slots&quot; ` -ResourceGroupName $resourceGroupName ` -ResourceName &quot;$appName/$slotName&quot; ` -ApiVersion 2015-08-01 ` -Force </code></pre> <p>This script sets the staging slot to have <code>AlwaysOn</code> turned on, does the swap so that staging is now production, then sets the staging slot to have <code>AlwaysOn</code> turned off, so it doesn't blow things up after an infrastructure upgrade.</p> <p>Once you get this working, it is indeed nice to have a PaaS that handles security updates and hardware failures for you. But it's a little bit more difficult to achieve in practice than the marketing materials might suggest. Hope this helps someone.</p> <p>--</p> <p><strong>UPDATE 07/17/2020:</strong> In the blurb above, I talk about needing to diddle with &quot;AlwaysOn&quot; if you're using staging slots, as it would swap with the slots, and having it on all slots can cause performance issues. At some point that isn't clear to me, <a href="https://docs.microsoft.com/en-us/azure/app-service/deploy-staging-slots#what-happens-during-a-swap" rel="noreferrer">they seem to have fixed this so that &quot;AlwaysOn&quot; isn't swapped</a>. My script actually still does the diddling with AlwaysOn, but in effect it ends up being a no-op now. So the advice to keep AlwaysOn off for your staging slots still stands, but you shouldn't have to do this little juggle in a script anymore.</p>