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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,296,645 | Decrease bitrate on WAV file created with recorderjs | <p>I'm trying to use <a href="https://github.com/mattdiamond/Recorderjs">recorderjs</a> on an app engine site where users upload short audio recordings (say, 1 to a dozen seconds long). I've noticed that the WAV files I'm uploading are much larger than I expected. For example, I just created a recording that lasts roughly 9 seconds, and the uploaded blob is 1736769 bytes, which is > 1.5 megabytes.</p>
<p><strong>Question:</strong> </p>
<p>How do I modify the recorderjs code (or my own code -- maybe I'm using recorderjs incorrectly) so that my audio blobs have a lower bitrate? I'd like a 10 second recording to be safely under 1 MB.</p>
<p>My guess is that I would need to modify the encodeWAV function in <a href="https://github.com/mattdiamond/Recorderjs/blob/master/recorderWorker.js">here</a>, or maybe exportWAV, but I'm not sure how. Would it make sense to just drop every other element of the interleaved buffer in exportWAV? Is there a more intelligent way to do it? How does the bitrate of the exported WAV depend on properties of my computer (e.g. the sampling rate of my soundcard)?</p>
<p>I can add some details on my own code if it might be helpful.</p>
<p>Edit: if you'd like to see a live example, install google chrome beta and try <a href="http://webaudiodemos.appspot.com/AudioRecorder/index.html">this page</a>. On my computer, a recording 5-10 seconds long is over 1 MB.</p>
<p>Many thanks,</p>
<p>Adrian</p> | 16,320,400 | 3 | 1 | null | 2013-04-30 09:35:40.377 UTC | 10 | 2017-11-12 10:19:40.227 UTC | 2014-02-27 01:53:46.173 UTC | null | 1,091,386 | null | 610,668 | null | 1 | 12 | html|audio|wav|audio-recording|recorder.js | 12,219 | <p>You could try a couple of things. First off, I think you're on to something about "dropping every other element of the interleaved buffer" (converting the sound to mono).</p>
<p>For that you could choose to keep the left or the right channel. You could change the "interleave" function to be:</p>
<pre><code>function interleave(inputL, inputR){
return inputL; // or inputR
}
</code></pre>
<p>If you wanted to keep both channels, but "pan" them both center (to the single mono channel), you could do something like:</p>
<pre><code>function interleave(inputL, inputR){
var result = new Float32Array(inputL.length);
for (var i = 0; i < inputL.length; ++i)
result[i] = 0.5 * (inputL[i] + inputR[i]);
return result;
}
</code></pre>
<p>That being said, there are <strong>potentially</strong> a lot of other placed you would have to change the encoded audio from being denoted as stereo to mono. However, my guess is (and I haven't used recorder.js, so I don't know it's inner workings), line 113/114 in the recorderWorker could probably changed to 1.</p>
<p>My guess is that you could get away with just changing the two places mentioned here (the interleave function, and the place where channel-count is set [line 114]) because: interleave and encodeWAV are only called through the exportWAV function, so not touching how the original worker has been recorder audio (and it's been recording stereo) hopefully won't break it. We would in that case only be making changes to the audio that was stored.</p> |
16,331,423 | What's the Java regular expression for an only integer numbers string? | <p>I'm trying with <code>if (nuevo_precio.getText().matches("/^\\d+$/"))</code> but got not good results so far...</p> | 16,331,458 | 6 | 0 | null | 2013-05-02 06:08:46.98 UTC | 2 | 2019-05-15 09:43:32.75 UTC | null | null | null | null | 742,560 | null | 1 | 15 | java|regex | 100,580 | <p>In Java regex, you don't use delimiters <code>/</code>:</p>
<pre><code>nuevo_precio.getText().matches("^\\d+$")
</code></pre>
<p>Since <code>String.matches()</code> (or <code>Matcher.matcher()</code>) force the whole string to match against the pattern to return <code>true</code>, the <code>^</code> and <code>$</code> are actually redundant and can be removed without affecting the result. This is a bit different compared to JavaScript, PHP (PCRE) or Perl, where "match" means finding a substring in the target string that matches the pattern.</p>
<pre><code>nuevo_precio.getText().matches("\\d+") // Equivalent solution
</code></pre>
<p>It doesn't hurt to leave it there, though, since it signifies the intention and makes the regex more portable.</p>
<hr>
<p>To limit to <strong>exactly</strong> 4 digit numbers:</p>
<pre><code>"\\d{4}"
</code></pre> |
16,530,194 | Can OCMock run a block parameter? | <p>Assume a method signature such as the following:</p>
<pre><code>- (void)theMethod:(void(^)(BOOL completed))completionBlock;
</code></pre>
<p>I would like to mock this method signature to ensure the method is called, and just call the completion block. I see from other posts like <a href="https://stackoverflow.com/questions/10781787/stub-method-with-block-of-code-as-parameter-with-ocmock">this one</a> that I can mock the method call and accept any block, but not run the block. I also know there is a andDo method that I might be able to use, but I can't figure out how to pass a block in and run it. </p>
<p>Any ideas?</p>
<p>Thanks.</p> | 16,530,443 | 5 | 0 | null | 2013-05-13 20:02:40.66 UTC | 5 | 2016-09-29 08:44:06.097 UTC | 2017-05-23 11:54:39.93 UTC | null | -1 | null | 1,863,655 | null | 1 | 32 | ios|unit-testing|ocmock | 16,707 | <p>You can use <code>[[mock stub] andDo:]</code> like this to pass another block that gets called when your mocked method is called:</p>
<pre><code>void (^proxyBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
void (^passedBlock)( BOOL );
[invocation getArgument: &passedBlock atIndex: 2];
};
[[[mock stub] andDo: proxyBlock] theMethod:[OCMArg any]];
</code></pre>
<p>The block gets a <code>NSInvocation</code> instance from which you can query all the used arguments. Note that the first argument is at index 2 since you have self and _cmd at the indices 0 and 1.</p> |
41,890,549 | Tensorflow cannot open libcuda.so.1 | <p>I have a laptop with a GeForce 940 MX. I want to get Tensorflow up and running on the gpu. I installed everything from their tutorial page, now when I import Tensorflow, I get</p>
<pre><code>>>> import tensorflow as tf
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:119] Couldn't open CUDA library libcuda.so.1. LD_LIBRARY_PATH:
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:165] hostname: workLaptop
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:189] libcuda reported version is: Not found: was unable to find libcuda.so DSO loaded into this program
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:193] kernel reported version is: Permission denied: could not open driver version path for reading: /proc/driver/nvidia/version
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1092] LD_LIBRARY_PATH:
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1093] failed to find libcuda.so on this system: Failed precondition: could not dlopen DSO: libcuda.so.1; dlerror: libnvidia-fatbinaryloader.so.367.57: cannot open shared object file: No such file or directory
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcurand.so locally
>>>
</code></pre>
<p>after which I think it just switches to running on the cpu. </p>
<p>EDIT: After I nuked everything , started from scratch. Now I get this:</p>
<pre><code>>>> import tensorflow
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:119] Couldn't open CUDA library libcuda.so.1. LD_LIBRARY_PATH: :/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:165] hostname: workLaptop
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:189] libcuda reported version is: Not found: was unable to find libcuda.so DSO loaded into this program
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:193] kernel reported version is: Permission denied: could not open driver version path for reading: /proc/driver/nvidia/version
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1092] LD_LIBRARY_PATH: :/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1093] failed to find libcuda.so on this system: Failed precondition: could not dlopen DSO: libcuda.so.1; dlerror: libnvidia-fatbinaryloader.so.367.57: cannot open shared object file: No such file or directory
I tensorflow/stream_executor/dso_loader.cc:128] successfully opened CUDA library libcurand.so locally
</code></pre> | 42,405,657 | 3 | 10 | null | 2017-01-27 09:23:44.98 UTC | 5 | 2020-07-11 10:52:21.843 UTC | 2017-01-27 11:57:04.227 UTC | null | 5,016,028 | null | 5,016,028 | null | 1 | 20 | cuda|tensorflow|nvidia | 86,104 | <p>libcuda.so.1 is a symlink to a file that is specific to the version of your NVIDIA drivers. It may be pointing to the wrong version or it may not exist.</p>
<pre><code># See where the link is pointing.
ls /usr/lib/x86_64-linux-gnu/libcuda.so.1 -la
# My result:
# lrwxrwxrwx 1 root root 19 Feb 22 20:40 \
# /usr/lib/x86_64-linux-gnu/libcuda.so.1 -> ./libcuda.so.375.39
# Make sure it is pointing to the right version.
# Compare it with the installed NVIDIA driver.
nvidia-smi
# Replace libcuda.so.1 with a link to the correct version
cd /usr/lib/x86_64-linux-gnu
sudo ln -f -s libcuda.so.<yournvidia.version> libcuda.so.1
</code></pre>
<p>Now in the same way, make another symlink from libcuda.so.1 to a link of the same name in your <a href="http://docs.nvidia.com/cuda/cuda-installation-guide-linux/#environment-setup" rel="noreferrer">LD_LIBRARY_PATH directory</a>.</p>
<p>You may also find that you need to create a link to libcuda.so.1 in /usr/lib/x86_64-linux-gnu named libcuda.so</p> |
22,416,403 | Apache won't start in wamp | <p>I have been googling for the past few hours but I simply can't get my apache on wamp to start. My skype isn't running, and the test port 80 shows it isn't being used by anything. Before this happened, I was trying to add a new vhost, but now I have reverted back all of the files where I made changes. Anyway to debug why apache won't start?</p>
<p>Clicking on start/resume service for apache doesn't show any errors either.</p>
<p>Also just in case, I am running Win7 64bit</p> | 22,422,115 | 16 | 2 | null | 2014-03-14 21:52:36.323 UTC | 25 | 2022-07-03 18:43:20.407 UTC | null | null | null | null | 3,157,464 | null | 1 | 44 | windows|apache|wamp|wampserver | 131,572 | <p>If you have an issue in the httpd.conf or any files included by it there are a couple of ways to find out what the problem is</p>
<p>First look at your <code>Windows Event Viewer</code>. Click on the <code>Windows</code> link in the menu on the left, and then submenu <code>Applications</code>.
Look for messages from Apache with the red error icon.</p>
<p>Secondly, open a command window, then CD into \wamp\bin\apache\apache2.x.y\bin, replace x,y with your actual version.
Now you can run this command to get Apache(httpd) to vaidate the httpd.conf file.</p>
<pre><code>httpd.exe -t
</code></pre>
<p>This should give errors with line numbers related to the http.conf file.
It stops on the first error, so you will have to keep running it and fixing the error and then run it again until it gives the all OK message.</p> |
21,474,239 | css padding is not working in outlook | <p>I have following html in email template.</p>
<p>I am getting different view in MS Outlook and in gmail for the same.</p>
<pre><code><tr>
<td bgcolor="#7d9aaa" style="color: #fff; font-size:15px; font-family:Arial, Helvetica, sans-serif; padding: 12px 2px 12px 0px; ">
<span style="font-weight: bold;padding-right:150px;padding-left: 35px;">Order Confirmation </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span style="font-weight: bold;width:400px;"> Your Confirmation number is {{var order.increment_id}} </span></td>
</tr>
</code></pre>
<p><img src="https://i.stack.imgur.com/ZLuwg.png" alt="In gmail"></p>
<p><img src="https://i.stack.imgur.com/mwS74.png" alt="In outlook"></p>
<p>How to fix this?</p> | 21,528,238 | 15 | 3 | null | 2014-01-31 07:00:35.37 UTC | 20 | 2022-09-05 10:12:33.237 UTC | null | null | null | null | 1,616,003 | null | 1 | 78 | html|css|email|outlook|outlook-2010 | 195,835 | <p>I changed to following and it worked for me</p>
<pre><code><tr>
<td bgcolor="#7d9aaa" style="color: #fff; font-size:15px; font-family:Arial, Helvetica, sans-serif; padding: 12px 2px 12px 0px; ">
<table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0">
<td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>
<td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>
</table>
</td>
</tr>
</code></pre>
<p><em>Update based on Bsalex request what has actually changed.</em>
I replaced span tag</p>
<pre><code><span style="font-weight: bold;padding-right:150px;padding-left: 35px;">Order Confirmation </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span style="font-weight: bold;width:400px;"> Your Confirmation number is {{var order.increment_id}} </span>
</code></pre>
<p>with table and td tags as following </p>
<pre><code> <table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0">
<td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>
<td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>
</table>
</code></pre> |
21,856,025 | Getting an accurate execution time in C++ (micro seconds) | <p>I want to get an accurate execution time in micro seconds of my program implemented with C++.
I have tried to get the execution time with clock_t but it's not accurate.</p>
<p>(Note that micro-benchmarking is <em>hard</em>. An accurate timer is only a small part of what's necessary to get meaningful results for short timed regions. See <a href="https://stackoverflow.com/questions/60291987/idiomatic-way-of-performance-evaluation">Idiomatic way of performance evaluation?</a> for some more general caveats)</p> | 21,856,299 | 4 | 4 | null | 2014-02-18 13:57:44.42 UTC | 17 | 2022-05-09 03:11:47.007 UTC | 2020-08-24 22:11:45.727 UTC | null | 224,132 | null | 3,323,616 | null | 1 | 48 | c++|performance|benchmarking|timing|microbenchmark | 80,549 | <p>If you are using c++11 or later you could use <code>std::chrono::high_resolution_clock</code>.</p>
<p>A simple use case :</p>
<pre><code>auto start = std::chrono::high_resolution_clock::now();
...
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(
elapsed).count();
</code></pre>
<p>This solution has the advantage of being portable.</p>
<hr />
<p>Beware that <strong>micro-benchmarking is hard</strong>. It's very easy to measure the wrong thing (like your benchmark optimizing away), or to include page-faults in your timed region, or fail to account for CPU frequency idle vs. turbo.</p>
<p>See <a href="https://stackoverflow.com/questions/60291987/idiomatic-way-of-performance-evaluation">Idiomatic way of performance evaluation?</a> for some general tips, e.g. sanity check by testing the other one first and see if that changes which one appears faster.</p> |
17,350,939 | git-archive a subdirectory -- | <p>I'm using git-archive to archive a subdirectory in a git repo, like so:</p>
<pre><code>git archive -o ../subarchive.zip HEAD subdir/*
</code></pre>
<p>However the resulting archive maintains the subdir/ directory structure, i.e. the contents are:</p>
<pre><code>subdir/
whatever.js
morestuff.js
</code></pre>
<p>When I actually want whatever.js and morestuff.js at the root of the archive.</p>
<p>How do? Thanks.</p> | 17,351,814 | 1 | 0 | null | 2013-06-27 18:46:13.373 UTC | 8 | 2014-07-10 12:03:13.12 UTC | null | null | null | null | 417,681 | null | 1 | 32 | git|subdirectory|git-archive | 19,321 | <p>You can do that like this:</p>
<pre><code>git archive -o ../subarchive.zip HEAD:subdir
</code></pre>
<p>By the way, an easy way to play with the command and see what it will generate is if you use it in this form:</p>
<pre><code>git archive --format=tar HEAD:subdir | tar t
git archive --format=tar HEAD subdir | tar t
# ... and so on ...
</code></pre>
<p>Once you see what you're looking for, you can change the format and use the <code>-o</code> flag to actually create the archive.</p> |
17,295,549 | How to add a user defined column with a single value to a SQL query | <p>I currently have a SQL query that produces a table with around 10M rows. I would like to append this table with another column that has the same entry for all 10M rows. </p>
<p>As an example consider the following toy query</p>
<pre><code>SELECT PRODUCT_ID, ORDER_QUANTITY
FROM PRODUCT_TABLE
GROUP BY SALES_DAY
</code></pre>
<p>And say that is produces the following table</p>
<pre><code> PRODUCT_ID ORDER_QUANTITY`
1 10
2 12
3 14
</code></pre>
<p>How can I change this query so that it produces the following table, where every entry in USER_VALUE is 999.</p>
<pre><code> PRODUCT_ID ORDER_QUANTITY USER_VALUE
1 10 999
2 12 999
3 14 999
</code></pre>
<p>I realize that there may be several answers here... but I suppose that it would help to know the method that would be produce the table with the smallest file size (I assume this would require specifying the type of data beforehand).</p> | 17,295,582 | 3 | 0 | null | 2013-06-25 10:59:30.957 UTC | 11 | 2013-06-25 11:03:43.71 UTC | null | null | null | null | 568,249 | null | 1 | 32 | sql | 77,493 | <p>Like this:</p>
<pre><code>SELECT PRODUCT_ID, ORDER_QUANTITY, 999 as USER_VALUE
FROM PRODUCT_TABLE
GROUP BY SALES_DAY
</code></pre> |
17,267,329 | Converting unicode character to string format | <p>Does anyone know how to convert a unicode to a string in javascript. For instance:</p>
<p><code>\u2211 -> ∑</code>
<code>\u0032 -> 2</code>
<code>\u222B -> ∫</code></p>
<p>I basically want to be able to display the symbol in xhtml or html. Haven't decided which I will be using yet.</p> | 17,267,373 | 5 | 2 | null | 2013-06-24 02:41:53.983 UTC | 15 | 2020-03-26 09:22:35.38 UTC | null | null | null | null | 1,129,110 | null | 1 | 37 | javascript|unicode | 75,444 | <p>Just found a way:
<code>String.fromCharCode(parseInt(unicode,16))</code> returns the right symbol representation. The unicode here doesn't have the <code>\u</code> in front of it just the number.</p> |
17,263,967 | Codesign of Dropbox API fails in Xcode 4.6.3: "code object is not signed at all" | <p>I have an OS X app that's distributed through the Mac App Store, and recently updated to Xcode 4.6.3.</p>
<p>When I run my regular build now, I receive:</p>
<pre><code>Command /usr/bin/codesign failed with exit code 1:
/Users/Craig/Library/Developer/Xcode/DerivedData/Mac-dxcgahgplwpbjedqnembegifbowj/Build/Products/Debug/MyApp.app: code object is not signed at all
In subcomponent: /Users/Craig/Library/Developer/Xcode/DerivedData/Mac-dxcgahgplwpbjedqnembegifbowj/Build/Products/Debug/MyApp.app/Contents/Frameworks/DropboxOSX.framework
Command /usr/bin/codesign failed with exit code 1
</code></pre>
<p>I can't seem to discern any other changes in my project, so I can't tell if it's an issue related to the 4.6.3 update, or something else.</p>
<p>I have tried restarting Xcode, running a clean build, and cleaning the build folder.</p> | 17,396,143 | 6 | 1 | null | 2013-06-23 18:32:04.883 UTC | 24 | 2020-04-10 11:38:26.897 UTC | 2013-06-23 18:42:37.973 UTC | null | 88,111 | null | 88,111 | null | 1 | 76 | xcode|macos|dropbox|code-signing|mac-app-store | 31,424 | <p>I think I may have figured this one out. I've been running Xcode 4.6.3 on OS X Mavericks, under the impression that any build-specific tools were bundled in the Xcode application.</p>
<p>But, it seems <code>codesign</code> is in <code>/usr/bin</code>. Whether it's put there by one of the Xcode installers or comes with a vanilla system install, I'm not sure. But reading through the <code>man</code> page for <code>codesign</code>, I found this nifty option:</p>
<pre><code>--deep When signing a bundle, specifies that nested code content such as helpers, frameworks, and plug-ins, should be recursively signed
in turn. Beware that all signing options you specify will apply, in turn, to such nested content.
When verifying a bundle, specifies that any nested code content will be recursively verified as to its full content. By default,
verification of nested content is limited to a shallow investigation that may not detect changes to the nested code.
When displaying a signature, specifies that a list of directly nested code should be written to the display output. This lists only
code directly nested within the subject; anything nested indirectly will require recursive application of the codesign command.
</code></pre>
<p>And then I found this post (<a href="https://alpha.app.net/isaiah/post/6774960%29">https://alpha.app.net/isaiah/post/6774960</a>) from two weeks ago (~June 2013), which mentions (albeit second-handedly):</p>
<blockquote>
<p>@isaiah I asked a guy in the labs about it. He said codesign now
requires embedded frameworks to be signed separately before code
signing the app bundle as a whole.</p>
</blockquote>
<p>Manually re-running the <code>codesign</code> command that Xcode normally runs, while adding the <code>--deep</code> flag to the end, signs the application properly.</p>
<p>I'm not yet sure exactly what ramifications this manual signing has, or whether I can tweak the Xcode build to add the <code>--deep</code> flag automatically, but this seems to be the underlying issue. (<code>codesign</code> no longer automatically deeply signs your app bundle.)</p> |
30,342,873 | event.target is undefined in events | <p>How can one use <code>each</code> input values in <code>events</code>? Hope my below code will explain you well.</p>
<p>HTML:</p>
<pre><code><template name="UpdateAge">
{{#each Name}}
<div data-action="showPrompt">
<div>
Some content
</div>
<div>
<div>
Some content
</div>
</div>
<div>
Name : {{name}}
Age : <input type="text" name="age" value="{{age}}"/> //I need to access age values in event
</div>
</div>
{{/each}}
<template>
</code></pre>
<p>JS:</p>
<pre><code>Template.UpdateAge.events({
'click [data-action="showPrompt"]': function (event, template) {
console.log(event.target.age.value); // TypeError: event.target.age.value is undefined
}
});
</code></pre>
<p>I dont know whether my approach is good for passing parameter values to <code>events</code> so suggestions are welcome.</p> | 30,343,157 | 2 | 2 | null | 2015-05-20 07:20:14.84 UTC | 4 | 2016-12-29 11:43:47.503 UTC | 2016-12-29 11:43:47.503 UTC | null | 6,539,198 | null | 1,560,616 | null | 1 | 17 | javascript|meteor|handlebars.js|meteor-blaze|meteor-helper | 54,974 | <p>the notation you are using is valid only for form elements and when event.target IS a form element.</p>
<pre><code>event.target.age.value
</code></pre>
<p><a href="http://www.w3schools.com/jsref/event_target.asp" rel="noreferrer">event.target</a> is the element where the event occurred, <a href="http://www.w3schools.com/jsref/event_currenttarget.asp" rel="noreferrer">event.currentTarget</a> is the element which has attached the event handler</p>
<p>if you replace <code>div</code> with <code>form</code> and replace <code>target</code> with <code>currentTarget</code> then it will work</p>
<pre><code>event.currentTarget.age.value
</code></pre>
<p><a href="https://jsfiddle.net/597fym2d/" rel="noreferrer">here a fiddle</a> using your code</p> |
36,893,804 | What does ModelState.IsValid do? | <p>When I do a create method i bind my object in the parameter and then I check if <code>ModelState</code> is valid so I add to the database:</p>
<p>But when I need to change something before I add to the database (before I change it the <code>ModelState</code> couldn't be valid so I have to do it)
why the model state still non valid.</p>
<p>What does this function check exactly?</p>
<p>This is my example:</p>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) {
encaissement.Montant = Convert.ToDecimal(encaissement.Montant);
ViewBag.montant = encaissement.Montant;
if (ModelState.IsValid) {
db.Encaissements.Add(encaissement);
db.SaveChanges();
return RedirectToAction("Index", "Encaissement");
};
ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP");
return View(encaissement);
}
</code></pre> | 36,894,368 | 3 | 3 | null | 2016-04-27 15:08:44.3 UTC | 9 | 2022-03-24 10:10:00.433 UTC | 2022-03-24 10:10:00.433 UTC | null | 297,823 | null | 5,998,569 | null | 1 | 49 | c#|asp.net-mvc|modelstate | 114,071 | <p><code>ModelState.IsValid</code> indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.</p>
<p>In your example, the model that is being bound is of class type <code>Encaissement</code>. Validation rules are those specified on the model by the use of attributes, logic and errors added within the <code>IValidatableObject</code>'s <code>Validate()</code> method - or simply within the code of the action method.</p>
<p>The <code>IsValid</code> property will be true if the values were able to bind correctly to the model AND no validation rules were broken in the process.</p>
<p>Here's an example of how a validation attribute and <code>IValidatableObject</code> might be implemented on your model class:</p>
<pre><code>public class Encaissement : IValidatableObject
{
// A required attribute, validates that this value was submitted
[Required(ErrorMessage = "The Encaissment ID must be submitted")]
public int EncaissementID { get; set; }
public DateTime? DateEncaissement { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
// Validate the DateEncaissment
if (!this.DateEncaissement.HasValue)
{
results.Add(new ValidationResult("The DateEncaissement must be set", new string[] { "DateEncaissement" });
}
return results;
}
}
</code></pre>
<p>Here's an example of how the same validation rule may be applied within the action method of your example:</p>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) {
// Perform validation
if (!encaissement.DateEncaissement.HasValue)
{
this.ModelState.AddModelError("DateEncaissement", "The DateEncaissement must be set");
}
encaissement.Montant = Convert.ToDecimal(encaissement.Montant);
ViewBag.montant = encaissement.Montant;
if (ModelState.IsValid) {
db.Encaissements.Add(encaissement);
db.SaveChanges();
return RedirectToAction("Index", "Encaissement");
};
ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP");
return View(encaissement);
}
</code></pre>
<p>It's worth bearing in mind that the value types of the properties of your model will also be validated. For example, you can't assign a string value to an <code>int</code> property. If you do, it won't be bound and the error will be added to your <code>ModelState</code> too.</p>
<p>In your example, the <code>EncaissementID</code> value could not have a value of <code>"Hello"</code> posted to it, this would cause a model validation error to be added and <code>IsValid</code> will be false.</p>
<p>It is for any of the above reasons (and possibly more) that the <code>IsValid</code> bool value of the model state will be <code>false</code>.</p> |
26,092,155 | Just run single test instead of the whole suite? | <p>I have a test suite for a Go package that implements a dozen tests. Sometimes, one of the tests in the suite fails and I'd like to re-run that test individually to save time in debugging process. Is this possible or do I have to write a separate file for this every time?</p> | 26,092,203 | 6 | 2 | null | 2014-09-29 03:35:03.763 UTC | 11 | 2022-06-20 13:03:28.067 UTC | 2014-09-29 19:34:07.367 UTC | null | 2,371,861 | null | 172,265 | null | 1 | 93 | go | 81,897 | <p>Use the <code>go test -run</code> flag to run a specific test. The flag is documented in
the <a href="https://pkg.go.dev/cmd/go#hdr-Testing_flags" rel="noreferrer">testing flags section</a> of the <a href="http://golang.org/cmd/go/" rel="noreferrer">go tool</a> documentation:</p>
<pre><code>-run regexp
Run only those tests and examples matching the regular
expression.
</code></pre> |
31,922,386 | How to construct TypeScript object with HTML input values? | <p>This should be very basic but I am unable to get through it.</p>
<p>I have a class like: </p>
<pre><code>class MyObject {
value: number;
unit: string;
constructor(value: number, unit: string){
this.value = value;
this.unit = unit;
}
}
</code></pre>
<p>Then in HTML,</p>
<pre><code> <input id="myValue" type="number"></input>
<input id="myUnit" type="text"></input>
</code></pre>
<p>I want to create an Object of "MyObject" class using myValue and myUnit. How do I do that ?</p>
<p>Something like: </p>
<pre><code> var value = document.getElementById("myValue");
var unit = document.getElementById("myUnit");
myObject: MyObject = new MyObject(value, unit);
</code></pre>
<p>Unable to do it the above way. What's the way to go about with this ?</p> | 31,944,343 | 3 | 5 | null | 2015-08-10 14:35:11.957 UTC | 1 | 2016-11-23 08:39:39.07 UTC | null | null | null | null | 4,389,984 | null | 1 | 11 | typescript | 62,586 | <p>Here is the final answer which works in TypeScript (Reference for casting HTMLElement to HTMLInputElement: <a href="https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement">The property 'value' does not exist on value of type 'HTMLElement'</a> )</p>
<pre><code>var value = parseFloat((<HTMLInputElement>document.getElementById("myValue")).value);
var unit = (<HTMLInputElement>document.getElementById("myUnit")).value;
myObject: MyObject = new MyObject(value, unit);
</code></pre>
<p>It was important to cast HTMLElement to HTMLInputElement, otherwise 'value' property doesn't exist for HTMLElement in TypeScript and TypeScript compiler will show error. </p> |
5,116,352 | When we should use scala.util.DynamicVariable? | <p>When I read the source of scalatra, I found there are some code like:</p>
<pre><code>protected val _response = new DynamicVariable[HttpServletResponse](null)
protected val _request = new DynamicVariable[HttpServletRequest](null)
</code></pre>
<p>There is an interesting class named <code>DynamicVariable</code>. I've looked at the doc of this class, but I don't know when and why we should use it? It has a <code>withValue()</code> which is usually be used.</p>
<p>If we don't use it, then what code we should use instead, to solve the problem it solved?</p>
<p>(I'm new to scala, if you can provide some code, that will be great)</p> | 5,117,158 | 3 | 1 | null | 2011-02-25 10:54:01.22 UTC | 18 | 2015-05-11 10:17:28.603 UTC | 2011-11-19 23:54:14.063 UTC | null | 1,502,059 | null | 342,235 | null | 1 | 46 | scala|thread-local | 10,277 | <p><code>DynamicVariable</code> is an implementation of the loan and dynamic scope patterns. Use-case of <code>DynamicVariable</code> is pretty much similar to <code>ThreadLocal</code> in Java (as a matter of fact, <code>DynamicVariable</code> uses <code>InheritableThreadLocal</code> behind the scenes) - it's used, when you need to do a computation within an enclosed scope, where every thread has it's own copy of the variable's value:</p>
<pre><code>dynamicVariable.withValue(value){ valueInContext =>
// value used in the context
}
</code></pre>
<p>Given that <code>DynamicVariable</code> uses an inheritable <code>ThreadLocal</code>, value of the variable is passed to the threads spawned in the context:</p>
<pre><code>dynamicVariable.withValue(value){ valueInContext =>
spawn{
// value is passed to the spawned thread
}
}
</code></pre>
<p><code>DynamicVariable</code> (and <code>ThreadLocal</code>) is used in Scalatra for the same reason it's used in many other frameworks (Lift, Spring, Struts, etc.) - it's a non-intrusive way to store and pass around context(thread)-specific information. </p>
<p>Making <code>HttpServletResponse</code> and <code>HttpServletRequest</code> dynamic variables (and, thus, binding to a specific thread that processes request) is just the easiest way to obtain them anywhere in the code (not passing through method arguments or anyhow else explicitly).</p> |
4,912,690 | How to access at request attributes in JSP? | <p>Currently I use:</p>
<pre><code><%
final String message = (String) request.getAttribute ("Error_Message");
%>
</code></pre>
<p>and then</p>
<pre><code><%= message %>
</code></pre>
<p>However I wonder if the same can be done with EL or JSTL instead of using a scriptlet.</p> | 4,912,797 | 3 | 0 | null | 2011-02-06 10:18:01.75 UTC | 12 | 2019-11-14 14:08:46.05 UTC | null | null | null | null | 341,091 | null | 1 | 62 | jsp|jstl|el | 135,180 | <p>EL expression:</p>
<pre><code>${requestScope.Error_Message}
</code></pre>
<p>There are several implicit objects in JSP EL. See <a href="http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html" rel="noreferrer">Expression Language</a> under the <a href="https://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html#wp71043" rel="noreferrer">"Implicit Objects"</a> heading.</p> |
25,453,159 | Getting consistent normals from a 3D cubic bezier path | <p>I'm writing a BezierPath class that contains a list of BezierPoints. Each BezierPoint has a position, an inTangent and an outTangent:</p>
<p><img src="https://i.stack.imgur.com/YZxuj.png" alt="enter image description here"></p>
<p>BezierPath contains functions for getting linear positions and tangents from the path. My next step is to provide functionality for getting the normals from the path.</p>
<p>I'm aware that any given line in 3D is going to have an unlimited number of lines that are perpendicular, so there isn't going to be a set answer.</p>
<p>My aim is for the user to be able to specify normals (or a roll angle?) at each BezierPoint which I will interpolate between to get normals along the path. My problem is that I don't know how to choose a starting tangent (what should the default tangent be?).</p>
<p>My first attempt at getting the starting tangents is using the Unity3D method <a href="http://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html" rel="noreferrer">Quaternion.LookRotation</a>:</p>
<pre><code>Quaternion lookAt = Quaternion.LookRotation(tangent);
Vector3 normal = lookAt * Vector3.up;
Handles.DrawLine(position, position + normal * 10.0f);
</code></pre>
<p>This results in the following (green lines are tangents, blue are normals):</p>
<p><img src="https://i.stack.imgur.com/R37t2.png" alt="enter image description here"></p>
<p>For the most part this seems like a good base result, but it looks like there are sudden changes in certain orientations:</p>
<p><img src="https://i.stack.imgur.com/0MHW5.png" alt="enter image description here"></p>
<p><strong>So my question is:</strong> Is there a good way for getting consistent default normals for lines in 3D?</p>
<p>Thanks,
Ves</p> | 25,458,216 | 1 | 2 | null | 2014-08-22 18:10:57.26 UTC | 8 | 2019-12-24 16:43:39.227 UTC | null | null | null | null | 3,058,663 | null | 1 | 8 | 3d|unity3d|bezier|normals | 6,131 | <p>Getting the normal for a point on a Bezier curve is actually pretty straight forward, as normals are simply perpendicular to a function's tangent (oriented in the plane of the direction of travel for the curve), and the tangent function of a Bezier curve is actually just another Bezier curve, 1 order lower. Let's find the normal for a cubic Bezier curve. The regular function, with (a,b,c,d) being the curve coordinates in a single dimension:</p>
<pre><code>function computeBezier (t, a, b, c, d) {
return a * (1-t)³ + 3 * b * (1-t)² * t + 3 * c * (1-t) * t² + d * t³
}
</code></pre>
<p>Note that Bezier curves are symmetrical, the only difference between <code>t</code> vs <code>1-t</code> is which end of the curve represents "the start". Using <code>a * (1-t)³</code> means the curve starts at <code>a</code>. Using <code>a * t³</code> would make it start at <code>d</code> instead.</p>
<p>So let's define a quick curve with the following coordinates:</p>
<pre><code>a = (-100,100,0)
b = (200,-100,100)
c = (0,100,-500)
d = (-100,-100,100)
</code></pre>
<p><img src="https://i.stack.imgur.com/Xginn.jpg" alt="just a 3D curve"></p>
<p>In order to get the normal for this function, we first need the <a href="http://pomax.github.io/bezierinfo/#derivatives" rel="noreferrer">derivative</a>:</p>
<pre><code>function computeBezierDerivative (t,a,b,c,d) {
a = 3*(b−a)
b = 3*(c-b)
c = 3*(d-c)
return a * (1-t)² + 2 * b * (1-t) * t + c * t²
}
</code></pre>
<p>Done. Computing the derivative is stupidly simple (a fantastic property of Bezier curves).</p>
<p>Now, in order to get the normal, we need to take the normalised tangent vector at some value <code>t</code>, and rotate it by a quarter turn. We can turn it in quite a few directions, so a further restriction is that we want to turn it only in the plane that is defined by the tangent vector, and the tangent vector "right next to it", an infinitesimally small interval apart.</p>
<p>The tangent vector for any Bezier curve is formed simply by taking however-many-dimensions you have, and evaluating them separately, so for a 3D curve:</p>
<pre><code> | computeBezierDerivative(t, x values) | |x'|
Tangent(t) = | computeBezierDerivative(t, y values) | => |y'|
| computeBezierDerivative(t, z values) | |z'|
</code></pre>
<p>Again, quite simple to compute. To normalise this vector (or in fact any vector), we simply perform a vector division by its length:</p>
<pre><code> |x'|
NormalTangent(t) = |y'| divided by sqrt(x'² + y'² + z'²)
|z'|
</code></pre>
<p>So let's draw those in green:</p>
<p><img src="https://i.stack.imgur.com/URfl4.jpg" alt="our curve with tangents computed at many points"></p>
<p>The only trick is now to find the plane in which to rotate the tangent vector, to turn the tangent into a normal. We know we can use another t value arbitrarily close to the one we want, and turn that into a second tangent vector damn near on the same point, for finding the plane with arbitrary correctness, so we can do that:</p>
<p>Given an original point <code>f(t1)=p</code> we take a point <code>f(t2)=q</code> with <code>t2=t1+e</code>, where <em>e</em> is some small value like 0.001 -- this point <code>q</code> has a derivative <code>q' = pointDerivative(t2)</code>, and in order to make things easier for us, we move that tangent vector a tiny bit by <code>p-q</code> so that the two vectors both "start" at <code>p</code>. Pretty simple.</p>
<p>However, this is equivalent to computing the first and second derivative at <code>p</code>, and then forming the second vector by adding those two together, as the second derivative gives us the change of the tangent at a point, so adding the second derivative vector to the first derivative vector gets us two vectors in the plane at <code>p</code> without having to find an adjacent point. This can be useful in curves where there are discontinuities in the derivative, i.e. curves with cusps.</p>
<p>We now have two vectors, departing at the same coordinate: our real tangent, and the "next" point's tangent, which is so close it might as well be the same point. Thankfully, due to how Bezier curves work, this second tangent is <em>never</em> the same, but slightly different, and "slightly different" is all we need: If we have two normalised vectors, starting at the same point but pointing in different directions, we can find the axis over which we need to rotate one to get the other simply by taking the <a href="https://en.wikipedia.org/wiki/Cross_product" rel="noreferrer">cross product</a> between them, and thus we can find the plane that they both go through.</p>
<p>Order matters: we compute <strong>c = tangent₂ × tangent₁</strong>, because if we compute <strong>c = tangent₁ × tangent₂</strong> we'll be computing the rotation axis and resulting normals in the "wrong" direction. Correcting that is literally just a "take vector, multiply by -1" at the end, but why correct after the fact when we can get it right, here. Let's see those axes of rotation in blue:</p>
<p><img src="https://i.stack.imgur.com/B0Zul.jpg" alt="our curve with the cross-product axis added"></p>
<p>Now we have everything we need: in order to turn our normalised tangent vectors into normal vectors, all we have to do is rotate them about the axes we just found by a quarter turn. If we turn them one way, we get normals, if we turn them the other, we get backfacing normals.</p>
<p>For arbitrary rotation about an axis in 3D, <a href="https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle" rel="noreferrer">that job is perhaps laborious, but not difficult</a>, and the quarter turns are generally special in that they greatly simplify the maths: to rotate a point over our rotation axis <strong>c</strong>, the rotation matrix turns out to be:</p>
<pre><code> | c₁² c₁*c₂ - c₃ c₁*c₃ + c₂ |
R = | c₁*c₂ + c₃ c₂² c₂*c₃ - c₁ |
| c₁*c₃ - c₂ c₂*c₃ + c₁ c₃² |
</code></pre>
<p>Where the 1, 2 and 3 subscripts are really just the x, y, and z components of our vector. So that's still easy, and all that's left is to matrix-rotate our normalised tangent:</p>
<pre><code>n = R * Tangent "T"
</code></pre>
<p>Which is:</p>
<pre><code> | T₁ * R₁₁ + T₂ * R₁₂ + T₃ * R₁₃ | |nx|
n = | T₁ * R₂₁ + T₂ * R₂₂ + T₃ * R₂₃ | => |ny|
| T₁ * R₃₁ + T₂ * R₃₂ + T₃ * R₃₃ | |nz|
</code></pre>
<p>And we have the normal vector(s) we need. Perfect!</p>
<p><strong>Except we can do better</strong>: since we're not working with arbitrary angles but with right angles, there's a significant shortcut we can use. In the same way that the vector <strong>c</strong> was perpendicular to both tangents, our normal <strong>n</strong> is perpendicular to both <strong>c</strong> and the regular tangent, so we can use the cross product a second time to find the normal:</p>
<pre><code> |nx|
n = c × tangent₁ => |ny|
|nz|
</code></pre>
<p>This will give us exactly the same vector, with less work.</p>
<p><img src="https://i.stack.imgur.com/xmIHj.jpg" alt="Our curve with normals!"></p>
<p>And if we want internal normals, it's the same vector, just multiply by -1:</p>
<p><img src="https://i.stack.imgur.com/Orla8.jpg" alt="Our curve with inward normals"></p>
<p>Pretty easy once you know the tricks! And finally, because code is always useful <a href="https://gist.github.com/Pomax/5b6b2c091d7ed8d3f1de" rel="noreferrer">this gist</a> is the <a href="http://processing.org" rel="noreferrer">Processing</a> program I used to make sure I was telling the truth.</p>
<h1>What if the normals behave really weird?</h1>
<p>For example, what if we're using a 3D curve but it's planar (e.g. all <code>z</code> coordinates at 0)? Things suddenly do horrible things. For instance, let's look at a curve with coordinates (0,0,0), (-38,260,0), (-25,541,0), and (-15,821,0):</p>
<p><img src="https://i.stack.imgur.com/f2Uuj.png" alt="enter image description here"></p>
<p>Similarly, particularly curvy curves may yield rather twisting normals. Looking at a curve with coordinates (0,0,0), (-38,260,200), (-25,541,-200), and (-15,821,600):</p>
<p><img src="https://i.stack.imgur.com/IVjq2.png" alt="enter image description here"></p>
<p>In this case, we want normals that rotate and twist as little as possible, which can be found using a Rotation Minimising Frame algorithm, such as explained in section 4 or <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/12/Computation-of-rotation-minimizing-frames.pdf" rel="noreferrer">"Computation of Rotation Minimizing Frames" (Wenping Wang, Bert Jüttler, Dayue Zheng, and Yang Liu, 2008)</a>. </p>
<p>Implementing their 9 line algorithm takes a little more work in a normal programming language, such as Java/Processing:</p>
<pre class="lang-java prettyprint-override"><code>ArrayList<VectorFrame> getRMF(int steps) {
ArrayList<VectorFrame> frames = new ArrayList<VectorFrame>();
double c1, c2, step = 1.0/steps, t0, t1;
PointVector v1, v2, riL, tiL, riN, siN;
VectorFrame x0, x1;
// Start off with the standard tangent/axis/normal frame
// associated with the curve just prior the Bezier interval.
t0 = -step;
frames.add(getFrenetFrame(t0));
// start constructing RM frames
for (; t0 < 1.0; t0 += step) {
// start with the previous, known frame
x0 = frames.get(frames.size() - 1);
// get the next frame: we're going to throw away its axis and normal
t1 = t0 + step;
x1 = getFrenetFrame(t1);
// First we reflect x0's tangent and axis onto x1, through
// the plane of reflection at the point midway x0--x1
v1 = x1.o.minus(x0.o);
c1 = v1.dot(v1);
riL = x0.r.minus(v1.scale( 2/c1 * v1.dot(x0.r) ));
tiL = x0.t.minus(v1.scale( 2/c1 * v1.dot(x0.t) ));
// Then we reflection a second time, over a plane at x1
// so that the frame tangent is aligned with the curve tangent:
v2 = x1.t.minus(tiL);
c2 = v2.dot(v2);
riN = riL.minus(v2.scale( 2/c2 * v2.dot(riL) ));
siN = x1.t.cross(riN);
x1.n = siN;
x1.r = riN;
// we record that frame, and move on
frames.add(x1);
}
// and before we return, we throw away the very first frame,
// because it lies outside the Bezier interval.
frames.remove(0);
return frames;
}
</code></pre>
<p>Still, this works really well. With the note that the Frenet frame is the "standard" tangent/axis/normal frame:</p>
<pre class="lang-java prettyprint-override"><code>VectorFrame getFrenetFrame(double t) {
PointVector origin = get(t);
PointVector tangent = derivative.get(t).normalise();
PointVector normal = getNormal(t).normalise();
return new VectorFrame(origin, tangent, normal);
}
</code></pre>
<p>For our planar curve, we now see perfectly behaved normals:</p>
<p><img src="https://i.stack.imgur.com/rc4Wv.png" alt="enter image description here"></p>
<p>And in the non-planar curve, there is minimal rotation:</p>
<p><img src="https://i.stack.imgur.com/ynJep.png" alt="enter image description here"></p>
<p>And finally, these normals can be uniformly reoriented by rotating all vectors around their associated tangent vectors. </p> |
9,577,349 | Delete a row from a SQL Server table | <p>I'm trying to simply delete a full row from my SQL Server database table using a button event. So far none of my attempts have succeeded. This is what I'm trying to do:</p>
<pre><code>public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + IDNumber, con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
</code></pre>
<p>I keep receiving the error: </p>
<blockquote>
<p>A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
An error occurred: Operand type clash: text is incompatible with int</p>
</blockquote>
<p>All of the columns in the table are of <code>TEXT</code> type. Why cannot I compare the function argument of type <code>string</code> to the columns to find the match? (And then delete the row?)</p> | 9,578,107 | 8 | 3 | null | 2012-03-06 03:04:35.867 UTC | 2 | 2019-10-01 16:25:23.013 UTC | 2017-03-04 21:08:26.083 UTC | null | 4,370,109 | null | 1,157,509 | null | 1 | 8 | c#|sql-server|delete-row | 136,507 | <p>As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....</p>
<pre><code> public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
</code></pre> |
9,153,224 | How to limit file upload type file size in PHP? | <p>I have an upload form and am checking the file size and file type to limit the uploaded file to 2 megabytes and either .pdf, .jpg, .gif or .png file types. My goal is to have an alert message displayed to the user if they violate one of these rules.</p>
<p>There are four scenarios:</p>
<ol>
<li>Correct Size / Correct Type (working)</li>
<li>Correct Size / INCORRECT Type (working)</li>
<li>INCORRECT Size / Correct Type (<strong>not working</strong>)</li>
<li>INCORRECT Size / INCORRECT Type (<strong>not working</strong>)</li>
</ol>
<p>With my current code, it always displays the incorrect "type" message when the file size is greater than 2 megabytes (#4), even if the file type is correct (#3). </p>
<p>Any ideas why?</p>
<pre><code>if (isset ( $_FILES['uploaded_file'] ) ) {
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
if (($file_size > 2097152)){
$message = 'File too large. File must be less than 2 megabytes.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
elseif (
($file_type != "application/pdf") &&
($file_type != "image/jpeg") &&
($file_type != "image/jpg") &&
($file_type != "image/gif") &&
($file_type != "image/png")
){
$message = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
else {
store_uploaded_file($id);
}
}
</code></pre> | 9,153,419 | 5 | 4 | null | 2012-02-05 21:32:44.753 UTC | 18 | 2018-09-17 09:54:35.757 UTC | 2012-02-05 21:47:39.787 UTC | null | 284,908 | null | 284,908 | null | 1 | 24 | php|file|file-upload | 147,230 | <p>Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:</p>
<pre><code>if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
</code></pre>
<p>Look into the docs for <a href="http://php.net/manual/en/function.move-uploaded-file.php" rel="noreferrer"><code>move_uploaded_file()</code></a> (it's called move not store) for more.</p> |
18,574,699 | How to make a space between <i> tags (icons) in table? | <p>I have a classic HTML table. In one column I want to add 3 icons with links to edit for example users. I am using twitter-bootstrap and glyphsicons. How to make more space between icons???
I prefer to use CSS.</p>
<pre><code><td>
<a href='#'>
<i class='icon-ok'></i>
</a>
<a href='#'>
<i class='icon-pencil'></i>
</a>
<a href='#'>
<i class='icon-remove'></i>
</a>
</td>
</code></pre> | 18,574,745 | 6 | 3 | null | 2013-09-02 13:40:30.097 UTC | null | 2022-02-09 12:50:40.327 UTC | 2013-09-02 13:43:01.143 UTC | null | 189,056 | null | 2,718,553 | null | 1 | 4 | html|css|twitter-bootstrap | 41,605 | <p>Just apply a padding (or a margin, depending on the style you've used) between elements, e.g.</p>
<pre><code>td a + a {
padding-left: 3em;
}
</code></pre> |
20,007,610 | Bootstrap carousel multiple frames at once | <p>This is the effect I'm trying to achieve with Bootstrap 3 carousel</p>
<p><img src="https://i.stack.imgur.com/rID5S.png" alt="enter image description here"></p>
<p>Instead of just showing one frame at a time, it displays N frames slide by side. Then when you slide (or when it auto slides), it shifts the group of slides like it does.</p>
<p><strong>Can this be done</strong> with bootstrap 3's carousel? I'm hoping I won't have to go hunting for yet another jQuery plugin...</p> | 20,450,875 | 16 | 3 | null | 2013-11-15 18:00:57.21 UTC | 65 | 2021-12-19 18:36:51.433 UTC | 2018-02-10 10:09:45.617 UTC | null | 171,456 | null | 774,907 | null | 1 | 135 | jquery|twitter-bootstrap-3|jquery-plugins|carousel|bootstrap-4 | 493,926 | <blockquote>
<p>Can this be done with bootstrap 3's carousel? I'm hoping I won't have
to go hunting for yet another jQuery plugin</p>
</blockquote>
<p>As of 2013-12-08 the answer is no. The effect you are looking for is not possible using Bootstrap 3's generic carousel plugin. However, here's a simple jQuery plugin that seems to do exactly what you want <a href="http://sorgalla.com/jcarousel/" rel="noreferrer">http://sorgalla.com/jcarousel/</a></p> |
14,972,199 | How to create Splash screen with transparent background in JavaFX | <p>I am trying to create a splash screen like the example I've provded.
It seems that AnchorPane does not allow transparent background, I've tried setting the css of the <code>AnchorPane</code> to <code>-fx-background-color: rgba(255,0,255,0.1) ;</code> but the white background still shows up.</p>
<p>All I have in my fxml file is a AnchorPane with ImageView with contain the png image</p>
<p><img src="https://encrypted-tbn2.gstatic.com/images?q=tbn%3aANd9GcRgvz97Or6OruF9rfSSu3FW_SSeeCFn4ggD8DKZLWnVR3aUHZ_2lw" alt="Example"></p>
<p>I've looked everywhere but can't find any solution, any help would be appreciated. Thanks</p> | 14,973,758 | 2 | 0 | null | 2013-02-20 04:15:49.34 UTC | 19 | 2018-01-29 16:15:34.583 UTC | null | null | null | null | 1,840,759 | null | 1 | 23 | java|transparency|javafx-2|javafx|splash-screen | 32,560 | <p>Try this <a href="https://gist.github.com/jewelsea/1588531" rel="noreferrer">JavaFX splash sample</a> created for the Stackoverflow question: <a href="https://stackoverflow.com/questions/9997509/designing-a-splash-screen-java">Designing a splash screen (java)</a>. And a <a href="https://gist.github.com/jewelsea/2305098" rel="noreferrer">follow up sample</a> which also provides application initialization progress feedback. </p>
<p>JavaFX does offer the <a href="http://docs.oracle.com/javafx/2/deployment/preloaders.htm" rel="noreferrer">Preloader</a> interface for smooth transfer from splash to application, but the above samples don't make use of it.</p>
<p>The splash samples above also don't do the transparent effect, but this <a href="https://gist.github.com/jewelsea/1887631" rel="noreferrer">dialog sample</a> shows you how to do that and you can combine it with the previous splash samples to get the effect you want.</p>
<p>The transparent effect is created by:</p>
<ol>
<li><code>stage.initStyle(StageStyle.TRANSPARENT)</code>.</li>
<li><code>scene.setFill(Color.TRANSPARENT)</code>.</li>
<li>Ensuring your root node is not an opaque square rectangle.</li>
</ol>
<p>Which is all demonstrated in Sergey's sample.</p>
<p>Related question:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15126210/how-to-use-javafx-preloader-with-stand-alone-application-in-eclipse">How to use javaFX Preloader with stand-alone application in Eclipse?</a></li>
</ul>
<p><em>Update Apr 2016 based on additional questions</em></p>
<blockquote>
<p>the preloader image isnt in the foreground. I have tried stage.toFront(), but doesnt help.</p>
</blockquote>
<p>A new API was created in Java 8u20 <a href="https://docs.oracle.com/javase/8/javafx/api/javafx/stage/Stage.html#setAlwaysOnTop-boolean-" rel="noreferrer">stage.setAlwaysOnTop(true)</a>. I updated the <a href="https://gist.github.com/jewelsea/2305098" rel="noreferrer">linked sample</a> to use this on the initial splash screen, which helps aid in a smoother transition to the main screen.</p>
<p><em>For Java8+</em></p>
<p>For modena.css (the default JavaFX look and feel definition in Java 8), a slight shaded background was introduced for all controls (and also to panes if a control is loaded).</p>
<p>You can remove this by specifying that the default background is transparent. This can be done by adding the following line to your application's CSS file:</p>
<pre><code>.root { -fx-background-color: transparent; }
</code></pre>
<p>If you wish, you can use CSS style classes and rules or a setStyle call (as demonstrated in Sergey's answer) to ensure that the setting only applies to the root of your splash screen rather than all of your app screens.</p>
<p>See related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/34033119/how-to-make-transparent-scene-and-stage-in-javafx">how to make transparent scene and stage in javafx?</a></li>
</ul> |
15,300,073 | What is the default value of a member in an array? | <p>I instantiate an array like this:</p>
<pre><code>int array[] = new int[4];
</code></pre>
<p>What are the default values for those four members? Is it null, 0 or not exists?</p> | 15,300,089 | 4 | 2 | null | 2013-03-08 17:41:58.447 UTC | 1 | 2021-04-27 04:35:44.96 UTC | 2017-05-07 14:06:07.44 UTC | null | 63,550 | null | 1,933,169 | null | 1 | 36 | c#|arrays|default-value|member | 50,222 | <p>It's 0. It can't be null, as null isn't a valid <code>int</code> value.</p>
<p>From section 7.6.10.4 of the C# 5 specification:</p>
<blockquote>
<p>All elements of the new array instance are initialized to their default values (§5.2).</p>
</blockquote>
<p>And from section 5.2:</p>
<blockquote>
<p>The default value of a variable depends on the type of the variable and is determined as follows:</p>
<ul>
<li>For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).</li>
<li>For a variable of a reference-type, the default value is null.</li>
</ul>
<p>Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference.</p>
</blockquote>
<p>(As an implementation detail, there's some trickiness around the first bullet point. Although C# itself doesn't allow you to declare a parameterless constructor for value types, you <em>can</em> create your own parameterless constructors for value types in IL. I don't believe those constructors are called in array initialization, but they <em>will</em> be called in a <code>new X()</code> expression in C#. It's outside the realm of the C# spec though, really.)</p> |
15,395,479 | Why I've got no crontab entry on OS X when using vim? | <p>I would like to use cron on my Mac. I choose it over <code>launchd</code>, because I want to be able to use my new knowledge on Linux as well. However, I cannot seem to get the <code>crontab -e</code> command to work. It fires up vim, I enter my test job:</p>
<pre><code>0-59 * * * * mollerhoj3 echo "Hello World"
</code></pre>
<p>But after saving and quitting (<code>:wq</code>),</p>
<pre><code>crontab -l
</code></pre>
<p>says:</p>
<pre><code>No crontab for mollerhoj3
</code></pre>
<p>What am I doing wrong?</p> | 16,732,109 | 14 | 7 | null | 2013-03-13 20:10:20.877 UTC | 49 | 2022-08-20 16:31:17.24 UTC | 2015-03-26 20:28:54.123 UTC | null | 55,075 | null | 1,232,027 | null | 1 | 79 | macos|vim|cron | 123,794 | <p>Just follow these steps:</p>
<ol>
<li>In Terminal: <code>crontab -e</code>.</li>
<li>Press <kbd>i</kbd> to go into vim's insert mode.</li>
<li><p>Type your cron job, for example:</p>
<pre><code>30 * * * * /usr/bin/curl --silent --compressed http://example.com/crawlink.php
</code></pre></li>
<li><p>Press <kbd>Esc</kbd> to exit vim's insert mode.</p></li>
<li>Type <kbd>ZZ</kbd> to exit vim (must be capital letters). </li>
<li>You should see the following message: <code>crontab: installing new crontab</code>. You can verify the crontab file by using <code>crontab -l</code>.</li>
</ol>
<p>Note however that this might not work depending on the content of your <code>~/.vimrc</code> file.</p> |
43,504,068 | Create my own method for DataFrames (python) | <p>So I wanted to create a module for my own projects and wanted to use methods. For example I wanted to do:</p>
<pre><code>from mymodule import *
df = pd.DataFrame(np.random.randn(4,4))
df.mymethod()
</code></pre>
<p>Thing is it seems I can't use <code>.myfunc()</code> since I think I can only use methods for the classes I've created. A work around is making <code>mymethod</code> a function and making it use <code>pandas.Dataframes</code> as a variable:</p>
<pre><code>myfunc(df)
</code></pre>
<p>I don't really want to do this, is there anyway to implement the first one?</p> | 53,630,084 | 3 | 4 | null | 2017-04-19 19:04:00.983 UTC | 10 | 2020-06-06 00:23:08.42 UTC | 2017-04-19 19:19:23.403 UTC | null | 7,311,767 | null | 7,724,154 | null | 1 | 15 | python|pandas|methods|module | 7,644 | <p>Nice solution can be found in ffn package. What authors do:</p>
<pre><code>from pandas.core.base import PandasObject
def your_fun(df):
...
PandasObject.your_fun = your_fun
</code></pre>
<p>After that your manual function "your_fun" becomes a method of pandas.DataFrame object and you can do something like</p>
<pre><code>df.your_fun()
</code></pre>
<p>This method will be able to work with both DataFrame and Series objects</p> |
28,170,004 | How to do local port forwarding with iptables | <p>I have an application (server) listening on port 8080. I want to be able to forward port 80 to it, such that hitting <code>http://localhost</code> resolves my application (on <code>localhost:8080</code>).</p>
<p>This should be generalized for any port mapping (e.g. <code>80:8080</code> => <code>P_src:P_target</code>), and use best practices for modern *nix machines (e.g. Ubuntu).</p>
<p><strong>N.B. This is all done locally, so there is no need to accept connections from anyone but localhost.</strong></p> | 28,170,005 | 1 | 3 | null | 2015-01-27 11:59:18.61 UTC | 8 | 2015-12-13 10:52:10.22 UTC | null | null | null | null | 3,033,674 | null | 1 | 30 | iptables | 25,598 | <p>So after much searching around, I found the answer uses iptables, setting up a NAT, and using the built-ins PREROUTING and OUTPUT.</p>
<p>First, you must have port forwarding enabled:</p>
<p><code>echo "1" > /proc/sys/net/ipv4/ip_forward</code></p>
<p>Then you have to add the following rules to your iptables NAT table, using your own values for <code>${P_src}</code> and <code>${P_target}</code>:</p>
<pre><code>iptables -t nat -A PREROUTING -s 127.0.0.1 -p tcp --dport ${P_src} -j REDIRECT --to ${P_target}`
iptables -t nat -A OUTPUT -s 127.0.0.1 -p tcp --dport ${P_src} -j REDIRECT --to ${P_target}`
</code></pre>
<p>If you want to remove the rules, you simply need to use the <code>-D</code> switch instead of <code>-A</code> for each rule.</p>
<p>I build a nice little script for this that does adding and removing of mappings.</p>
<pre><code>#!/bin/bash
#
# API: ./forwardPorts.sh add|rm p1:p1' p2:p2' ...
#
# Results in the appending (-A) or deleting (-D) of iptable rule pairs that
# would otherwise facilitate port forwarding.
#
# E.g
# sudo iptables -t nat -A PREROUTING -s 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to 8080
# sudo iptables -t nat -A OUTPUT -s 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to 8080
#
if [[ $# -lt 2 ]]; then
echo "forwardPorts takes a state (i.e. add or rm) and any number port mappings (e.g. 80:8080)";
exit 1;
fi
case $1 in
add )
append_or_delete=A;;
rm )
append_or_delete=D;;
* )
echo "forwardPorts requires a state (i.e. add or rm) as it's first argument";
exit 1; ;;
esac
shift 1;
# Do a quick check to make sure all mappings are integers
# Many thanks to S.O. for clever string splitting:
# http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash
for map in "$@"
do
IFS=: read -a from_to_array <<< "$map"
if [[ ! ${from_to_array[0]} =~ ^-?[0-9]+$ ]] || [[ ! ${from_to_array[1]} =~ ^-?[0-9]+$ ]]; then
echo "forwardPorts port maps must go from an integer, to an integer (e.g. 443:4443)";
exit 1;
fi
mappings[${#mappings[@]}]=${map}
done
# We're shooting for transactional consistency. Only manipulate iptables if all
# the rules have a chance to succeed.
for map in "${mappings[@]}"
do
IFS=: read -a from_to_array <<< "$map"
from=${from_to_array[0]}
to=${from_to_array[1]}
sudo iptables -t nat -$append_or_delete PREROUTING -s 127.0.0.1 -p tcp --dport $from -j REDIRECT --to $to
sudo iptables -t nat -$append_or_delete OUTPUT -s 127.0.0.1 -p tcp --dport $from -j REDIRECT --to $to
done
exit 0;
</code></pre> |
48,422,199 | Laravel 5.5 Trying to get property 'id' of non-object | <p>I'm new on Laravel.I used Laravel version 5.5</p>
<p>If I try to login with postman.I got "Trying to get property 'id' of non-object" error.And error line is </p>
<pre><code> private $client;
public function __construct(){
$this->client = Client::find(1);
}
public function login(Request $request){
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
return $this->issueToken($request, 'password'); // this line has error
}
</code></pre>
<p>issueToken Function</p>
<pre><code>public function issueToken(Request $request, $grantType, $scope = ""){
$params = [
'grant_type' => $grantType,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => $scope
];
if($grantType !== 'social'){
$params['username'] = $request->username ?: $request->email;
}
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
</code></pre>
<p>I got same error on Register.But my user successfully registered with 500 error (Trying to get property 'id' of non-object) </p> | 48,422,378 | 4 | 5 | null | 2018-01-24 12:12:06.123 UTC | 1 | 2020-03-02 04:37:17.73 UTC | 2018-01-24 12:14:10.78 UTC | null | 7,846,137 | null | 7,846,137 | null | 1 | 5 | php|mysql|laravel|laravel-5 | 65,967 | <h3>The error is because <code>$this->client</code> is null when <code>find()</code> cannot find the record.</h3>
<p>You need to be sure if the record exists or not.</p>
<p><strong>Change:</strong></p>
<pre><code>$this->client = Client::find(1);
</code></pre>
<p><strong>To:</strong></p>
<pre><code>$this->client = Client::findOrFail(1);
</code></pre>
<p><strong>Documentation:</strong></p>
<p>From <a href="https://laravel.com/docs/eloquent" rel="nofollow noreferrer">Laravel Eloquent docs</a>,
this will throw a <code>404</code> error if no record with the specified id is found. </p> |
9,219,005 | Proportionally scale a div with CSS based on max-width (similar to img scaling) | <p>Is it possible to proportionally scale a <code>div</code> like an <code>img</code> using only CSS? Here is my first attempt: <a href="http://dabblet.com/gist/1783363">http://dabblet.com/gist/1783363</a></p>
<h1>Example</h1>
<pre><code>div {
max-width:100px;
max-height:50px;
}
img {
max-width:100px;
max-height:50px;
}
</code></pre>
<h2>Actual Result</h2>
<pre><code>Container: 200 x 100
Div: 100 x 50
Image: 100 x 50
Container: 50 x 100
Div: 50 x 50 // I want this to be 50x25, like the image
Image: 50 x 25
</code></pre> | 9,236,397 | 3 | 6 | null | 2012-02-09 21:23:13.08 UTC | 9 | 2017-06-02 05:49:50.967 UTC | 2012-02-14 19:10:13.54 UTC | null | 526,741 | null | 798,420 | null | 1 | 12 | image|html|css|scale | 30,524 | <p>Since vertical paddings set in percent are calculated out of <em>width</em> of an element we can make a div always be of a certain aspect ratio.</p>
<p>If we set <code>padding-top:50%; height:0</code>, the height of the div will always be half of its width.
And to make text appear inside such a container you need to make it <code>position:relative</code> and put another div inside it and position it absolutely 10px away from all four sides (the padding you set first).</p>
<p>See <a href="http://dabblet.com/gist/1794086" rel="noreferrer">my fork of your code</a>.</p> |
65,058,598 | NextJs CORS issue | <p>I have a Next.js app hosted on Vercel at <a href="http://www.example.com" rel="noreferrer">www.example.com</a>, which needs to communicate with a backend .NET Core Web API hosted on a different server at api.example.com.
The .NET core web api has been configured to allow CORS but my Next.js keeps complaining that data cannot be displayed when I use AXIOS to fetch data because the response lacks allow-cors headers:</p>
<blockquote>
<p>Access to XMLHttpRequest at 'https://api.example.com' from origin 'http://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource</p>
</blockquote>
<p>It works fine when I run it locally using <code>npm run dev</code>, but doesn't work when I build it and then run <code>npm run start</code></p>
<p>Does anyone know how to fix the cors issue in production?</p> | 65,058,898 | 8 | 3 | null | 2020-11-29 09:20:28.363 UTC | 5 | 2022-07-21 08:00:31.023 UTC | null | null | null | null | 4,200,709 | null | 1 | 30 | reactjs|cors|next.js | 95,235 | <p>I found a solution <a href="https://nextjs.org/docs/api-reference/next.config.js/rewrites" rel="noreferrer">here</a>:</p>
<p>Basically, I just need to add a next.config.js file in the root directory and add the following:</p>
<pre><code>// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
};
</code></pre> |
30,997,129 | In C++11 what should happen first: raw string expansion or macros? | <p>This code works in Visual C++ 2013 but not in gcc/clang:</p>
<pre><code>#if 0
R"foo(
#else
int dostuff () { return 23; }
// )foo";
#endif
dostuff();
</code></pre>
<p>Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?</p> | 30,997,287 | 2 | 7 | null | 2015-06-23 08:02:59.093 UTC | 1 | 2019-01-29 05:27:40.937 UTC | 2016-07-05 16:58:01.733 UTC | null | 4,370,109 | null | 360,270 | null | 1 | 45 | c++|c++11|c-preprocessor|rawstring | 2,841 | <p>[Update: Adrian McCarthy comments below saying MSVC++ 2017 fixes this]</p>
<p>GCC and clang are right, VC++ is wrong.</p>
<blockquote>
<p>2.2 Phases of translation [lex.phases]:</p>
<p>[...]</p>
<ol start="3">
<li><p>The source file is decomposed into <strong>preprocessing tokens (2.5)</strong> and sequences of white-space characters (including comments).</p>
</li>
<li><p><strong>Preprocessing directives</strong> are executed, [...]</p>
</li>
</ol>
</blockquote>
<p>And <em><strong>2.5 Preprocessing tokens [lex.pptoken]</strong></em> lists <em><code>string-literals</code></em> amongst the tokens.</p>
<p>Consequently, parsing is required to tokenise the string literal first, "consuming" the <code>#else</code> and <code>dostuff</code> function definition.</p> |
4,843,746 | Regular Expression to add double quotes around keys in JavaScript | <p>I am using jQuery's getJSON function to make a request and handle the JSON response. The problem is the response I get back is malformed and I can't change it. The response looks something like this:</p>
<pre><code>{
aNumber: 200,
someText: '\'hello\' world',
anObject: {
'foo': 'fooValue',
'bar': '10.0'
}
}
</code></pre>
<p>To be valid JSON, it should look like this:</p>
<pre><code>{
"aNumber": 200,
"someText": "'hello' world",
"anObject": {
"foo": "fooValue",
"bar": "10.0"
}
}
</code></pre>
<p>I would like to change the text returned to a valid JSON object. I've used the JavaScript replace function to turn the single quotes into double quotes and the escaped single quotes into single quotes, but now I am stuck on figuring out the best way to add quotes around the key values.</p>
<p>For example, how would I change <code>foo: "fooValue"</code> to <code>"foo":"fooValue"</code>? Is there a Regular Expression that can make this easy?</p>
<p>Thanks in advance!</p> | 4,843,766 | 5 | 1 | null | 2011-01-30 15:42:02.223 UTC | 9 | 2020-05-24 10:06:09.357 UTC | 2020-05-24 10:06:09.357 UTC | null | 6,904,888 | null | 338,658 | null | 1 | 12 | javascript|regex|json | 19,355 | <p><em>edit</em> — came back to point out, first and foremost, that this is not a problem that can be solved with a regular expression.</p>
<p>It's important to distinguish between JSON notation as a serialized form, and JavaScript object constant notation.</p>
<p>This:</p>
<pre><code>{ x: "hello" }
</code></pre>
<p>is a perfectly valid JavaScript value (an expression fragment), so that this:</p>
<pre><code>var y = { x: "hello" };
</code></pre>
<p>gives you exactly the same result as:</p>
<pre><code>var y = { "x": "hello" };
</code></pre>
<p>In other words, the value of "y" in either of those cases will be exactly the same. Completely, exactly the same, such that it would not be possible to ever tell which of those two constants was used to initialize "y".</p>
<p>Now, if what you want to do is translate a <strong>string</strong> containing JavaScript style "JSON shorthand" without quotes into valid JSON, the only thing to do is parse it and reconstruct the string with quotes around the property names. That is, you will have to either write your own "relaxed" JSON parser than can cope with unquoted identifiers as property names, or else find an off-the-shelf parser that can handle such relaxed syntax.</p>
<p>In your case, it looks like once you have the "relaxed" parser available, you're done; there shouldn't be any need for you to translate back. Thankfully, your "invalid" JSON response is completely interpretable by JavaScript itself, so if you trust the data source (and that's a <strong>big</strong> "if") you should be able to evaluate it with "eval()".</p> |
5,158,326 | Safest and Railsiest way in CanCan to do Guest, User, Admin permissions | <p>I'm relatively new to rails (3), and am building an application, using CanCan, where there are 3 tiers of users.</p>
<ul>
<li>Guest - unregistered visitor User</li>
<li>registered and logged in visitor</li>
<li>Admin - registered and logged in
visitor with admin flag</li>
</ul>
<p>My ability is bog-stock right now, copied from cancan docs, basically defining the guest role and the admin role</p>
<pre><code>class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # Guest user
if user.is_admin?
can :manage, :all
else
can :read, [Asana,Image,User,Video,Sequence]
end
end
end
</code></pre>
<p>I'm looking to add in the user role. Since I'm creating that throwaway user model, I thought about using new_record? to determine if the user is logged in or not. Something like:</p>
<pre><code>class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # Guest user
if !user.new_record? and user.is_admin?
can :manage, :all
elsif !user.new_record? and !user.is_admin?
can {registered user-y permissions}
else
can :read, [Asana,Image,User,Video,Sequence]
end
end
end
</code></pre>
<p>But, it just doesn't feel right. Seems kind of disassociated from, like, actual logged-in-ed-ness, and have concerns about whether its actually secure.</p>
<p>Looking for advice on a more elegant way to doing this.</p>
<p>Thanks!</p> | 5,417,527 | 5 | 2 | null | 2011-03-01 17:50:54.55 UTC | 16 | 2013-04-11 21:55:52.257 UTC | null | null | null | null | 267,404 | null | 1 | 13 | ruby-on-rails|ruby-on-rails-3|cancan | 4,734 | <p>Good question, I use a lower to higher permissions approach:</p>
<pre><code>class Ability
include CanCan::Ability
def initialize(user)
# Guest User
unless user
can :read, [Asana,Image,User,Video,Sequence]
else
# All registered users
can {registered user-y permissions}
# Admins
if user.is_admin?
can :manage, :all
end
end
end
end
</code></pre>
<p>This way if tomorrow you have other roles to integrate you can do it adding a case statement like so:</p>
<pre><code>class Ability
include CanCan::Ability
def initialize(user)
# Guest User
unless user
can :read, [Asana,Image,User,Video,Sequence]
else
# All registered users
can {registered user-y permissions}
# Different roles
case user.role
when 'admin'
can :manage, :all
when 'manager'
can :manage, [Video, Image, Sequence]
end
end
end
end
</code></pre> |
4,873,976 | How to commit only modified (and not new or deleted) files? | <p><code>git status</code> shows a bunch of files which were modified and some which were deleted. I want to first commit the modified files and then the deleted ones. I don't see any option in <code>git add</code> that enables me to do this. How can I do it?</p>
<p><strong>EDIT</strong>: As pointed out, <code>git add</code> wouldn't have staged the deleted files anyway, so <code>git add .</code> would do. But it has the side-effect of including files which weren't tracked, which I would also like to avoid. I have changed the title of the question accordingly.</p> | 12,000,642 | 6 | 0 | null | 2011-02-02 11:36:30.757 UTC | 24 | 2021-05-27 13:29:06.92 UTC | 2011-02-02 12:08:50.467 UTC | null | 106,281 | null | 106,281 | null | 1 | 69 | git|version-control | 107,172 | <p>The following command should do the trick:</p>
<pre><code>git commit -a
</code></pre>
<p>or</p>
<pre><code>git commit -am "commit message"
</code></pre>
<p>From the <a href="http://git-scm.com/book">Pro Git</a> book:</p>
<blockquote>
<p>Providing the -a option to the git commit command makes Git automatically stage every file that is already tracked before doing the commit</p>
</blockquote> |
4,848,611 | Rendering a template variable as HTML | <p>I use the 'messages' interface to pass messages to user like this:</p>
<pre><code>request.user.message_set.create(message=message)
</code></pre>
<p>I would like to include html in my <code>{{ message }}</code> variable and render it without escaping the markup in the template.</p> | 4,848,661 | 6 | 0 | null | 2011-01-31 07:40:00 UTC | 42 | 2020-02-05 22:57:16.08 UTC | 2014-10-03 17:11:28.39 UTC | user212218 | null | null | 356,875 | null | 1 | 229 | django|django-templates | 195,948 | <p>If you don't want the HTML to be escaped, look at the <code>safe</code> filter and the <code>autoescape</code> tag:</p>
<p><a href="http://docs.djangoproject.com/en/stable/ref/templates/builtins/#safe" rel="noreferrer"><code>safe</code></a>:</p>
<pre><code>{{ myhtml |safe }}
</code></pre>
<p><a href="http://docs.djangoproject.com/en/stable/ref/templates/builtins/#autoescape" rel="noreferrer"><code>autoescape</code></a>:</p>
<pre><code>{% autoescape off %}
{{ myhtml }}
{% endautoescape %}
</code></pre> |
5,241,369 | Word wrap a link so it doesn't overflow its parent div width | <p>I have this piece of code:</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>div#permalink_section {
width: 960px
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='permalink_section'>
<a href="here goes a very long link">here goes a very very long link</a>
</div></code></pre>
</div>
</div>
</p>
<p>The link text can be very long and it overflows the div when it's length does exceed the div width. Is there a way to force the link to break and go on the next line when its width exceeds the div width?</p> | 5,241,448 | 7 | 0 | null | 2011-03-09 04:36:47.563 UTC | 19 | 2019-09-03 16:16:51.227 UTC | 2019-04-18 15:02:54.263 UTC | null | 10,607,772 | null | 117,704 | null | 1 | 63 | html|css|width|word-wrap | 114,511 | <p>The following is a cross browser compatible solution:</p>
<blockquote>
<pre><code>#permalink_section
{
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</code></pre>
</blockquote>
<p>From <a href="https://stackoverflow.com/questions/3247358/how-do-i-wrap-text-with-no-whitespace-inside-a-td/5108367#5108367">How do I wrap text with no whitespace inside a <td>?</a></p>
<p>Check working example <a href="http://jsfiddle.net/5zsqP/1" rel="noreferrer">here</a>.</p> |
5,586,383 | How to diff one file to an arbitrary version in Git? | <p>How can I diff a file, say <code>pom.xml</code>, from the master branch to an arbitrary older version in Git?</p> | 5,586,435 | 14 | 0 | null | 2011-04-07 19:18:41.527 UTC | 85 | 2022-06-12 07:46:40.713 UTC | 2020-12-18 21:14:36.653 UTC | user456814 | 183,704 | null | 51,789 | null | 1 | 391 | git|diff|git-diff | 272,870 | <p>You can do:</p>
<pre><code>git diff master~20:pom.xml pom.xml
</code></pre>
<p>... to compare your current <code>pom.xml</code> to the one from <code>master</code> 20 revisions ago through the first parent. You can replace <code>master~20</code>, of course, with the object name (SHA1sum) of a commit or any of the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html#_specifying_revisions" rel="noreferrer">many other ways of specifying a revision</a>.</p>
<p>Note that this is actually comparing the old <code>pom.xml</code> to the version in your working tree, not the version committed in <code>master</code>. If you want that, then you can do the following instead:</p>
<pre><code>git diff master~20:pom.xml master:pom.xml
</code></pre> |
5,242,429 | What is the facade design pattern? | <p>Is <em>facade</em> a class which contains a lot of other classes? </p>
<p>What makes it a design pattern? To me, it is like a normal class. </p>
<p>Can you explain to me this <em>Facade</em> pattern?</p> | 5,242,476 | 20 | 5 | null | 2011-03-09 07:04:30.673 UTC | 51 | 2020-10-01 17:50:21.073 UTC | 2018-12-16 13:05:32.65 UTC | null | 3,924,118 | null | 631,733 | null | 1 | 199 | design-patterns|facade | 126,171 | <p>A design pattern is a common way of solving a recurring problem. Classes in all design patterns are just normal classes. What is important is how they are structured and how they work together to solve a given problem in the best possible way. </p>
<p>The <em>Facade</em> design pattern simplifies the interface to a complex system; because it is usually composed of all the classes which make up the subsystems of the complex system. </p>
<p>A Facade shields the user from the complex details of the system and provides them with a <code>simplified view</code> of it which is <code>easy to use</code>. It also <code>decouples</code> the code that uses the system from the details of the subsystems, making it easier to modify the system later.</p>
<p><a href="http://www.dofactory.com/Patterns/PatternFacade.aspx" rel="noreferrer">http://www.dofactory.com/Patterns/PatternFacade.aspx</a></p>
<p><a href="http://www.blackwasp.co.uk/Facade.aspx" rel="noreferrer">http://www.blackwasp.co.uk/Facade.aspx</a></p>
<p>Also, what is important while learning design patterns is to be able to recognize which pattern fits your given problem and then using it appropriately. It is a very common thing to misuse a pattern or trying to fit it to some problem just because you know it. Be aware of those pitfalls while learning\using design patterns.</p> |
4,945,128 | What is a good example of recursion other than generating a Fibonacci sequence? | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/105838/real-world-examples-of-recursion">Real-world examples of recursion</a><br>
<a href="https://stackoverflow.com/questions/126756/examples-of-recursive-functions">Examples of Recursive functions</a> </p>
</blockquote>
<p>I see that most programming language tutorial teach recursion by using a simple example which is how to generate fibonacci sequence, my question is, is there another good example other than generating fibonacci sequence to explain how recursion works?</p> | 4,945,152 | 23 | 9 | null | 2011-02-09 12:55:51.373 UTC | 13 | 2011-02-10 22:33:16.987 UTC | 2017-05-23 12:26:26.863 UTC | null | -1 | null | 286,041 | null | 1 | 26 | c++|algorithm|recursion|fibonacci | 15,584 | <p>The classic is the binary tree search:</p>
<pre><code>def findval (node,val):
if node == null:
return null
if node.val = val:
return node
if node.val > val:
return findval (node.left,val)
return findval (node.right,val)
findval (root,thing_to_find)
</code></pre>
<p>That may be a little more complex than a simple formula but it's the "bread and butter" use of recursion, and it illustrates the best places to use it, that where the recursion levels are minimised.</p>
<p>By that I mean: you <em>could</em> add two non-negative numbers with:</p>
<pre><code>def add (a,b):
if b == 0:
return a
return add (a+1,b-1)
</code></pre>
<p>but you'd find yourself running out of stack space pretty quickly for large numbers (unless the compiler optimised tail-end recursions of course, but you should probably ignore that for the level of teaching you're concerned with).</p> |
12,603,279 | Waiting For Process To Complete | <p>Is there any way to pause a process or wait unitl the process is complete before continuing onto the next line of code?</p>
<p>Here is my current process to zip all PDFs and then delete. Currently, its deleting files before the zipping is complete. Is there a way to pause/wait until the process is complete?</p>
<pre><code> Dim psInfo As New System.Diagnostics.ProcessStartInfo("C:\Program Files\7-Zip\7z.exe ", Arg1 + ZipFileName + PathToPDFs)
psInfo.WindowStyle = ProcessWindowStyle.Hidden
System.Diagnostics.Process.Start(psInfo)
'delete remaining pdfs
For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Temp\", FileIO.SearchOption.SearchAllSubDirectories, "*.pdf")
File.Delete(foundFile)
Next
</code></pre> | 12,603,341 | 3 | 0 | null | 2012-09-26 13:50:07.903 UTC | 2 | 2019-03-13 15:00:07.843 UTC | null | null | null | null | 1,221,294 | null | 1 | 6 | vb.net|visual-studio-2010|process | 46,842 | <p>You can use <code>process.WaitForExit</code> method</p>
<p>WaitForExit can make the current thread wait until the associated process to exit.</p>
<p>Link : <a href="http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.waitforexit(v=vs.80).aspx" rel="noreferrer">http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.waitforexit(v=vs.80).aspx</a></p> |
12,183,572 | How to use JavaScript to fill a form on another page | <p>I am trying to fill out the fields on a form through JavaScript. The problem is I only know how to execute JavaScript on the current page so I cannot redirect to the form and execute code from there. I'm hesitant to use this term, but the only phrase that comes to mind is cross-site script. The code I am attempting to execute is below.</p>
<pre><code><script language="javascript">
window.location = "http://www.pagewithaform.com";
loaded();
//checks to see if page is loaded. if not, checks after timeout.
function loaded()
{
if(window.onLoad)
{
//never executes on new page. the problem
setTitle();
}
else
{
setTimeout("loaded()",1000);
alert("new alert");
}
}
//sets field's value
function setTitle()
{
var title = prompt("Field Info","Default Value");
var form = document.form[0];
form.elements["fieldName"].value = title;
}
</script>
</code></pre>
<p>I'm not truly sure if this is possible. I'm also open to other ideas, such as PHP. Thanks.</p>
<p>EDIT: The second page is a SharePoint form. I cannot edit any of the code on the form. The goal is to write a script that pre-fills most of the fields because 90% of them are static.</p> | 12,183,659 | 4 | 5 | null | 2012-08-29 17:42:13.667 UTC | 12 | 2020-07-18 09:57:24.443 UTC | 2012-08-29 17:59:47.64 UTC | null | 1,096,496 | null | 1,096,496 | null | 1 | 10 | javascript|forms | 59,562 | <p>You're trying to maintain state between pages. Conventionally there are two ways to maintain state:</p>
<ul>
<li>Store state in cookies</li>
<li>Store state in the query string</li>
</ul>
<p>Either way your first page has to persist state (to either cookies or the query string) and the other page has to - separately - restore the state. You can't use the same script across both pages.</p>
<h1>Example: Using Cookies</h1>
<p>Using cookies, the first page would have to write all the form data you'll need on the next page to cookies:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With Cookies</title>
</head>
<body>
<div>
Setting cookies and redirecting...
</div>
<script>
// document.cookie is not a real string
document.cookie = 'form/title=My Name is Richard; expires=Tue, 29 Aug 2017 12:00:01 UTC'
document.cookie = 'form/text=I am demoing how to use cookies in JavaScript; expires=Tue, 29 Aug 2017 12:00:01 UT';
setTimeout(function(){
window.location = "./form-cookies.html";
}, 1000);
</script>
</body>
</html>
</code></pre>
<p>... and the second page would then read those cookies and populate the form fields with them:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With Cookies</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var COOKIES = {};
var cookieStr = document.cookie;
cookieStr.split(/; /).forEach(function(keyValuePair) { // not necessarily the best way to parse cookies
var cookieName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var cookieValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
COOKIES[cookieName] = cookieValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = COOKIES["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = COOKIES["form/text"];
</script>
</body>
</html>
</code></pre>
<h1>Example: Using the Query String</h1>
<p>In the case of using the Query String, the first page would just include the query string in the redirect URL, like so:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Query String</title>
</head>
<body>
<div>
Redirecting...
</div>
<script>
setTimeout(function(){
window.location = "./form-querystring.html?form/title=My Name is Richard&form/text=I am demoing how to use the query string in JavaScript";
}, 1000);
</script>
</body>
</html>
</code></pre>
<p>...while the form would then parse the query string (available in JavaScript via <code>window.location.search</code> - prepended with a <code>?</code>):</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Query String</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var GET = {};
var queryString = window.location.search.replace(/^\?/, '');
queryString.split(/\&/).forEach(function(keyValuePair) {
var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
GET[paramName] = paramValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = GET["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = GET["form/text"];
</script>
</body>
</html>
</code></pre>
<h1>Example: With a Fragment Identifier</h1>
<p>There's one more option: since state is being maintained strictly on the client side (not on th server side) you could put the information in a fragment identifier (the "hash" part of a URL).</p>
<p>The first script is very similar to the Query String example above: the redirect URL just includes the fragment identifier. I'm going to re-use query string formatting for convenience, but notice the <code>#</code> in the place where a <code>?</code> used to be:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Fragment Identifier</title>
</head>
<body>
<div>
Redirecting...
</div>
<script>
setTimeout(function(){
window.location = "./form-fragmentidentifier.html#form/title=My Name is Richard&form/text=I am demoing how to use the fragment identifier in JavaScript";
}, 1000);
</script>
</body>
</html>
</code></pre>
<p>... and then the form has to parse the fragment identifier etc:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Maintaining State With The Fragment Identifier</title>
</head>
<body>
<form id="myForm" action="submit.mumps.cgi" method="POST">
<input type="text" name="title" />
<textarea name="text"></textarea>
</form>
<script>
var HASH = {};
var hashString = window.location.hash.replace(/^#/, '');
hashString.split(/\&/).forEach(function(keyValuePair) {
var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
HASH[paramName] = paramValue;
});
document.getElementById("myForm").getElementsByTagName("input")[0].value = HASH["form/title"];
document.getElementById("myForm").getElementsByTagName("textarea")[0].value = HASH["form/text"];
</script>
</body>
</html>
</code></pre>
<h1>And if you can't edit the code for the form page</h1>
<p><a href="http://userscripts.org/scripts/show/39313" rel="noreferrer">Try a greasemonkey script.</a></p> |
12,627,746 | SQL - Is there an opposite but equivalent UNION function? | <p>Is there an opposite but equivalent UNION function for mysql?</p>
<p>I know it's possible to do this with a longer query but I'm curious on whether or not there's a function equivalent.</p>
<p>I have 2 select statements for 2 different tables</p>
<pre><code>select state, state_name, id, idname, phone, mobile, home from table1
select state, state_name, id, idname, phone, mobile, home from table2
</code></pre>
<p>And I need a query that pulls only from table1 and ONLY if idname, phone, mobile, home from table1 doesn't match with table2</p>
<p>For example: Table1 has</p>
<pre><code>AK | Alaska | 1 | row6 | 453 | 567 | 123
</code></pre>
<p>but Table 2 has:</p>
<pre><code>AK | Alaska | 1 | row6 | 453 | 567 | 123
AK | Alaska | 1 | row6 | NULL | 567 | 123
AK | Alaska | 1 | tttttt | 453 | 567 | 123
</code></pre>
<p>The query will display</p>
<pre><code>AK | Alaska | 1 | row6 | NULL | 567 | 123
AK | Alaska | 1 | tttttt | 453 | 567 | 123
</code></pre>
<p>will NOT display</p>
<pre><code>AK | Alaska | 1 | row6 | 453 | 567 | 123
</code></pre> | 12,627,787 | 2 | 0 | null | 2012-09-27 18:20:53.863 UTC | 4 | 2012-09-27 18:34:36.123 UTC | 2012-09-27 18:28:00.723 UTC | null | 981,310 | null | 981,310 | null | 1 | 18 | mysql|sql | 45,631 | <p>In standard SQL you can use the ANSI SQL <code>EXCEPT</code> operator which is an exact analogue of <code>UNION</code></p>
<pre><code>SELECT * FROM Table2
EXCEPT
SELECT * FROM Table1
</code></pre>
<p>There is also an <code>INTERSECT</code> <a href="http://en.wikipedia.org/wiki/Set_operations_%28SQL%29" rel="noreferrer">set operator</a> that would show rows that both sources have in common.</p>
<p>Unfortunately neither of these are supported in current versions of MySQL so you need to use one of these other 3 more verbose ways of achieving an anti semi join.</p>
<p><a href="http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/" rel="noreferrer">NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL</a></p> |
12,226,757 | Difference between double and Double in comparison | <p>I know that <code>Double</code> is a a wrapper class, and it wraps <code>double</code> number. Today, I have seen another main difference : </p>
<pre><code>double a = 1.0;
double b = 1.0;
Double c = 1.0;
Double d = 1.0;
System.out.println(a == b); // true
System.out.println(c == d); // false
</code></pre>
<p>So strange with me !!!</p>
<p>So, if we use <code>Double</code>, each time, we must do something like this :</p>
<pre><code>private static final double delta = 0.0001;
System.out.println(Math.abs(c-d) < delta);
</code></pre>
<p>I cannot explain why Double make directly comparison wrong. Please explain for me.</p> | 12,226,768 | 5 | 3 | null | 2012-09-01 09:58:12.933 UTC | 9 | 2020-01-30 14:49:51.513 UTC | 2020-01-30 14:09:53.35 UTC | null | 479,156 | null | 1,192,728 | null | 1 | 25 | java|double | 30,916 | <p><code>c</code> and <code>d</code> are technically two different objects and <code>==</code> operator compares only references. </p>
<pre><code>c.equals(d)
</code></pre>
<p>is better as it compares values, not references. But still not ideal. Comparing floating-point values directly should always take some error (epsilon) into account (<code>Math.abs(c - d) < epsilon</code>).</p>
<p>Note that:</p>
<pre><code>Integer c = 1;
Integer d = 1;
</code></pre>
<p>here comparison would yield <code>true</code>, but that's more complicated (<code>Integer</code> internal caching, described in <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)" rel="noreferrer">JavaDoc of <code>Integer.valueOf()</code></a>):</p>
<blockquote>
<p>This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.</p>
</blockquote>
<p>Why <code>valueOf()</code>? Because this method is implicitly used to implement autoboxing:</p>
<pre><code>Integer c = Integer.valueOf(1);
Integer d = Integer.valueOf(1);
</code></pre>
<h1>See also</h1>
<ul>
<li><a href="https://stackoverflow.com/questions/3130311">Weird Integer boxing in Java</a></li>
<li><a href="https://stackoverflow.com/questions/1514910">How to properly compare two Integers in Java?</a></li>
</ul> |
12,205,785 | Getting bundle file references / paths at app launch | <p>Suppose I have an arbitrary set of files included in the Main App Bundle. I would like to fetch the file URLs for those at launch and store them somewhere. Is this possible using <code>NSFileManager</code>? The documentation is unclear in that regard.</p>
<p>Note: I only need the file URLs, I do not need to access the actual files.</p> | 12,205,868 | 4 | 2 | null | 2012-08-30 21:27:34.907 UTC | 2 | 2018-03-17 10:25:21.663 UTC | null | null | null | null | 501,452 | null | 1 | 30 | ios|ios5|nsfilemanager|nsbundle | 46,303 | <p>You can get the URL of a file in the main bundle using</p>
<pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"SomeFile" ofType:@"jpeg"];
NSURL *url = [NSURL fileURLWithPath:path];
</code></pre>
<p>You can write this URL to, for example, a property list file in the Documents directory:</p>
<pre><code>NSString *docsDir = [NSSearchForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Files.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[url absoluteString] forKey:@"SomeFile.jpeg"];
[dict writeToFile:plistPath atomically:YES];
</code></pre>
<p>If you don't know the names of the files and you just want to list all the files in the bundle, use</p>
<pre><code>NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] bundlePath] error:NULL];
for (NSString *fileName in files) {
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
// do something with `url`
}
</code></pre> |
12,624,358 | Nginx not following symlinks | <p>I have installed nginx on Ubuntu 12.04. However, nginx does not seem to follow symlinks. I understand that there is a config change required for this but I am not able to find where to make the change. Any help appreciated.</p> | 12,624,697 | 3 | 1 | null | 2012-09-27 15:00:41.73 UTC | 9 | 2018-10-07 17:57:25.787 UTC | null | null | null | null | 1,299,738 | null | 1 | 40 | nginx|symlink | 106,279 | <p>Have a look at the following config option from <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#disable_symlinks" rel="noreferrer">nginx docs</a>:</p>
<blockquote>
<p>Syntax:</p>
<pre><code>disable_symlinks off;
disable_symlinks on |
if_not_owner [from=part];
</code></pre>
<p>Default: disable_symlinks off;</p>
<p>Context: http, server, location</p>
<p>This directive appeared in version 1.1.15. </p>
</blockquote> |
12,156,517 | Whats the difference between Paxos and W+R>=N in Cassandra? | <p>Dynamo-like databases (e.g. Cassandra) can enforce consistency by means of quorum, i.e. a number of synchronously written replicas (W) and a number of replicas to read (R) should be chosen in such a way that W+R>N where N is a replication factor. On the other hand, PAXOS-based systems like Zookeeper are also used as a consistent fault-tolerant storage.</p>
<p>What is the difference between these two approaches? Does PAXOS provide guarantees that are not provided by W+R>N schema? </p> | 12,165,463 | 5 | 1 | null | 2012-08-28 09:37:04.787 UTC | 23 | 2021-12-25 16:43:43.753 UTC | 2012-08-28 10:06:37.227 UTC | null | 1,128,016 | null | 1,128,016 | null | 1 | 41 | algorithm|synchronization|cassandra|apache-zookeeper|paxos | 10,702 | <p>Paxos is non-trivial to implement, and expensive enough that many systems using it use hints as well, or use it only for leader election, or something. However, it does provide guaranteed consistency in the presence of failures - subject of course to the limits of its particular failure model. </p>
<p>The first quorum based systems I saw assumed some sort of leader or transaction infrastructure that would ensure enough consistency that you could trust that the quorum mechanism worked. This infrastructure might well be Paxos-based.</p>
<p>Looking at descriptions such as <a href="https://cloudant.com/blog/dynamo-and-couchdb-clusters/" rel="noreferrer">https://cloudant.com/blog/dynamo-and-couchdb-clusters/</a>, it would appear that Dynamo is <em>not</em> based on an infrastructure that guarantees consistency for its quorum system - so is it being very clever or cutting corners? According to <a href="http://muratbuffalo.blogspot.co.uk/2010/11/dynamo-amazons-highly-available-key.html" rel="noreferrer">http://muratbuffalo.blogspot.co.uk/2010/11/dynamo-amazons-highly-available-key.html</a>, "The Dynamo system emphasizes availability to the extent of sacrificing consistency. The abstract reads "Dynamo sacrifices consistency under certain failure scenarios". Actually, later it becomes clear that Dynamo sacrifices consistency even in the absence of failures: Dynamo may become inconsistent in the presence of multiple concurrent write requests since the replicas may diverge due to multiple coordinators." (end quote)</p>
<p>So, it would appear that in the case of quorums as implemented in Dynamo, Paxos provides stronger reliability guarantees.</p> |
19,014,766 | How can I get input radio elements to horizontally align? | <p>I want these radio inputs to stretch across the screen, rather than one beneath the other:</p>
<p>HTML</p>
<pre><code><input type="radio" name="editList" value="always">Always
<br>
<input type="radio" name="editList" value="never">Never
<br>
<input type="radio" name="editList" value="costChange">Cost Change
</code></pre>
<p>CSS</p>
<pre><code>input[type="radio"] {
margin-left:10px;
}
</code></pre>
<p><a href="http://jsfiddle.net/clayshannon/8wRT3/13/">http://jsfiddle.net/clayshannon/8wRT3/13/</a></p>
<p>I've monkeyed around with the display properties, and googled, and bang (bung? binged?) for an answer, but haven't found one.</p> | 19,014,810 | 4 | 7 | null | 2013-09-25 20:37:39.837 UTC | 4 | 2019-02-27 12:04:19.917 UTC | null | null | null | null | 875,317 | null | 1 | 25 | html|css|input|radio-button | 133,839 | <p>In your case, you just need to remove the line breaks (<code><br></code> tags) between the elements - <code>input</code> elements are <code>inline-block</code> by default (in Chrome at least). <a href="http://jsfiddle.net/8wRT3/14/"><strong>(updated example)</strong></a>.</p>
<pre><code><input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
</code></pre>
<hr>
<p>I'd suggest using <code><label></code> elements, though. In doing so, clicking on the label will check the element too. Either associate the <code><label></code>'s <code>for</code> attribute with the <code><input></code>'s <code>id</code>: <a href="http://jsfiddle.net/9000o0bc/"><strong>(example)</strong></a></p>
<pre><code><input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>
<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>
<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>
</code></pre>
<p>..or wrap the <code><label></code> elements around the <code><input></code> elements directly: <a href="http://jsfiddle.net/zeLrkw05/"><strong>(example)</strong></a></p>
<pre><code><label>
<input type="radio" name="editList" value="always"/>Always
</label>
<label>
<input type="radio" name="editList" value="never"/>Never
</label>
<label>
<input type="radio" name="editList" value="costChange"/>Cost Change
</label>
</code></pre>
<p>You can also get fancy and use the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:checked"><code>:checked</code> pseudo class</a>.</p> |
3,223,112 | JavaEE6 DAO: Should it be @Stateless or @ApplicationScoped? | <p>I'm currently creating an EJB3 Data Access Class to handle all database operations in my Java EE 6-application. Now, since Java EE 6 provides the new <code>ApplicationScoped</code> annotation, I wonder what state my EJB should have, or if it should be stateless. </p>
<p>Would it be better to let the DAO be a <code>@Stateless</code> Session Bean, or an <code>@ApplicationScoped</code> Bean? What about <code>@Singleton</code>? What are the differences between these options related to a DAO? </p>
<p><strong>EDIT:</strong>
I'm using Glassfish 3.0.1 with the full Java EE 6 platform</p> | 3,224,607 | 3 | 0 | null | 2010-07-11 12:58:38.19 UTC | 12 | 2019-02-13 18:31:07.687 UTC | 2019-02-13 18:31:07.687 UTC | null | 702,479 | null | 319,905 | null | 1 | 23 | java|jakarta-ee|ejb|java-ee-6|ejb-3.1 | 18,609 | <blockquote>
<p>Whould it be better to let the DAO be a @Stateless Session Bean, or an @ApplicationScoped Bean? What about @Singleton? What are the differences between these options related to a DAO? </p>
</blockquote>
<p>I would NOT use Stateless Session Beans for DAOs:</p>
<ol>
<li><p>EJBs are pooled by the container so if you have N instances per pool and thousands of tables, you're just going to waste resources (not even to mention the cost at deploy time). </p></li>
<li><p>Implementing DAOs as SLSB would encourage EJB chaining which is not a good practice from a scalability point of view.</p></li>
<li><p>I would not tie the DAO layer to the EJB API.</p></li>
</ol>
<p>The <code>@Singleton</code> introduced in EJB 3.1 could make things a bit better but I would still not implement DAOs as EJBs. I would rather use CDI (and maybe a custom stereotype, see <a href="http://www.theserverside.com/news/2240016831/Part-3-of-dependency-injection-in-Java-EE-6" rel="noreferrer">this article</a> for example).</p>
<p>Or I wouldn't use DAOs at all. JPA's entity manager is an implementation of the <a href="http://www.corej2eepatterns.com/Patterns2ndEd/DomainStore.htm" rel="noreferrer">Domain Store</a> pattern and wrapping access to a Domain Store in a DAO doesn't add much value.</p> |
3,501,811 | What is the best open source pure java computer vision library? | <p>As a practical developer I would like to make a good algorithm for my specific task, built from blocks, like a 'boundary extraction', or 'gamma correction' and so on, but I don't want to implement the wheel, making all that stuff, so I wander - if there's any powerful CV library, like C++'s OpenCV?</p>
<p>Saying "the best", I mean library having following properties:</p>
<ul>
<li>Lot of different algorithms implemented</li>
<li>Extensibility - I can create new stuff in terms of the library</li>
<li>High performance</li>
<li>Thread safety</li>
</ul> | 3,504,072 | 3 | 2 | null | 2010-08-17 11:20:47.057 UTC | 9 | 2012-05-16 14:26:38.563 UTC | 2010-08-17 12:40:59.907 UTC | null | 255,667 | null | 255,667 | null | 1 | 26 | java|open-source|computer-vision | 27,441 | <p>Shaman,
I have been looking a long time for a image processing library comparable to opencv in Java. For the amount of automated tasks opencv performs there is nothing that comes close to it for the advanced machine vision type applications.</p>
<p>In terms of image processing though <a href="http://rsbweb.nih.gov/ij/" rel="noreferrer">imagej</a> has a large amount of preimplemented algorithms and plugins. I use this library all the time to preprocess things I need to send into opencvs machine vision utilities. This is also open source with easy ways of adding additional features through plugins or direct manipulations so I think it could meet most of your requirements.</p> |
20,857,120 | What is the proper way to stop a service running as foreground | <p>I am trying to stop a service which is running as foreground service.</p>
<p>The current issue is that when I call <code>stopService()</code> the notification still stays.</p>
<p>So in my solution I have added a receiver which I am registering to inside the <code>onCreate()</code></p>
<p>Inside the <code>onReceive()</code> method I call <code>stopforeground(true)</code> and it hides the notification.
And then <code>stopself()</code> to stop the service.</p>
<p>Inside the <code>onDestroy()</code> I unregistered the receiver.</p>
<p>Is there a more proper way to handle this? because stopService() simply doesn't work.</p>
<pre><code>@Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}
</code></pre> | 20,857,343 | 8 | 4 | null | 2013-12-31 12:04:32.697 UTC | 18 | 2022-05-28 11:56:12.843 UTC | 2017-07-27 04:01:28.557 UTC | null | 3,263,659 | null | 1,940,676 | null | 1 | 67 | android|foreground-service | 57,821 | <p>From your activity call <code>startService(intent)</code> and pass it some data that will represent a key to <strong>stop the service</strong>.</p>
<p>From your service call <code>stopForeground(true)</code> and then <code>stopSelf()</code> right after it. </p> |
26,338,387 | unexpected exception: java.lang.NoClassDefFoundError: org/apache/log4j/LogManager | <p>I'm developing a GWT application. It's using RPC to collect information from an internal system. It does so by using a library jar, lets call it alpha.jar. We are using this jar in many application so it works fine, and btw its built with ANT, outside eclipse.</p>
<p>Some classes in alpha.jar references LOG4J2 and also lots of other external jars, so <strong>when we run an application we pass a classpath to all those, and everything works out fine</strong>. Please note that this is not a simple beginners problem. The alpha.jar is working as it should, including calls to Log4J.</p>
<p>The problem:</p>
<p>In Eclipse, I have this GWT application project and also the Alpha.jar project (with source code of course). The server part needs to instatiate alpha objects and communicate to the alpha system.</p>
<p>When do this in GWT by adding a build-path-reference to the Alpha project, my GWT app runs fine.</p>
<p>When I instead of the project reference include (in war/WEB-INF/lib) the alpha.jar and runs the app, I get the error in the title the first time I instantiate a class from alpha.jar.</p>
<p>There are no peculiarities in how the alpha.jar is built, so basically it should be the same thing as the project in eclipse, right?</p>
<p>Note the following:</p>
<p>*) The alpha.jar's dependent jars are also in war/WEB-INF/lib. log4j2-core, log4j-api as well as a bunch of others (apache common for example)</p>
<p>*) If I remove the alpha.jar (and the code that calls it) and instead just add code that called LOG4J2, that code also works fine!</p>
<p>How come I get this weird error when using the JAR?? Note also the NoClassDefFoundError, its not the more common ClassNotFoundException. Pls see <a href="https://stackoverflow.com/questions/1457863/what-is-the-difference-between-noclassdeffounderror-and-classnotfoundexception">What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?</a></p>
<p>If you need more info let me know.</p> | 26,341,886 | 3 | 4 | null | 2014-10-13 10:58:20.103 UTC | 1 | 2018-12-12 12:14:47.593 UTC | 2017-05-23 12:16:28.64 UTC | null | -1 | null | 587,238 | null | 1 | 16 | java|eclipse|gwt|jar | 76,265 | <p><code>org.apache.log4j.LogManager</code> is a class from log4j 1.2 (not log4j2).</p>
<p>Therefore, one of your web app jars must be referencing it. The culprit should be visible in the stack trace.</p>
<p>Depending upon your circumstances, you may want to just add a log4j 1.2 jar to the web app as the two versions are completely independent of each other.</p> |
22,053,852 | How to install Matplotlib for anaconda 1.9.1 and Python 3.3.4? | <p>I am configuring Anaconda 1.9.1 together with Python 3.3.4 and I am unable to setup Matplotlib for anaconda environment when I try to add package using Pycharm. I also tried to install from Matplotlib.exe file which I downloaded from its website. I can not change the installation directory in that case. I would like to know that is there a way to tackle this issue. </p> | 22,072,896 | 3 | 8 | null | 2014-02-26 21:34:27.017 UTC | 1 | 2017-08-18 01:52:52.76 UTC | null | null | null | null | 1,551,892 | null | 1 | 3 | python|python-3.x|matplotlib | 45,258 | <p>If you're using anaconda, your default environment is Python 2.7. You need to create a new environment and install matplotlib in there.</p>
<p>In a command prompt, do the following (saying yes to the questions):</p>
<pre><code>conda create --name mpl33 python=3.3 matplotlib ipython-notebook
activate mpl33
ipython notebook
</code></pre>
<p>You should be able to import matplotlib when the notebook server comes up.</p>
<ul>
<li>The first command simultaneously creates the environment and install
the listed packages.</li>
<li>The second command activates the new environment by prepending its location to the system path</li>
<li>The third command just starts the ipython notebook so that you can test out everything</li>
</ul>
<p>I don't know how pycharm works, but my guess is that you'll have to tell it to look for the right python that you want to use. In this case it'll be something like: C:/Users//anaconda/envs/mpl33. In any case, the command prompt should display the path when you activate the environment.</p>
<p>Once you've activated your environment, you can install more packages like this:</p>
<pre><code>conda install pandas=0.12
conda install pyodbc statsmodels
</code></pre>
<p>You can specific version numbers of packages like the first command or simply accept the latest available version (default)</p> |
11,264,975 | How to pass a parameter from Batch (.bat) to VBScript (.vbs)? | <p>How can I pass a parameter from batch to vbscript? My batch script sends out an email at the end of the automated execution. For that it uses/calls my vbscript (email.vbs) that sends out the email with an actual log file (that has the results for that execution) attached.
All those log files are stored in specific folders such as: 201207(July, 2012), 201208(August, 2012) and so on....
I want to pass the folder name or part of (i am thinking about hard coding the 2012 part and get the month number from that parameter through my batch) it as a parameter to my email.vbs so that it can go look for the right folder to grab the right log file. Makes sense?</p>
<pre><code>ECHO Checking the log file for errors...
FINDSTR /C:"RC (return code) = 0" %workDir%\%filenm%_Log.txt && (ECHO Deployment was successful.
ECHO Email is sent out...
cscript //nologo success_mail_DEV.vbs %workDir% 'passing the directory param. here.
ECHO Press ENTER to exit...
GOTO offshore) || (ECHO Deployment was not successful. Errors were found!
ECHO Email is sent out...
ECHO Press ENTER to exit...
cscript //nologo fail_mail_DEV.vbs %workDir% 'and here
GOTO offshore)
</code></pre>
<p>This is part of what I have right now. It is checking for errors in the log file and calling that success/failed mail accordingly. Right now the location name/number is hardcoded in those 2 vbs mailing scripts that you see up there. I am sure there is a way to pass a parameter somewhere up there to the emailing vbscript. But, i don't know how to.</p>
<p>This is my mailing vbscript:</p>
<pre><code>Const ForReading = 1
Set args = WScript.Arguments
directory = args.Item(0) 'thought that workDir would come in here
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(&directory&"\filename.txt", ForReading)
fileName = objTextFile.ReadLine
Dim ToAddress
Dim FromAddress
Dim MessageSubject
Dim MyTime
Dim MessageBody
Dim MessageAttachment
Dim ol, ns, newMail
MyTime = Now
ToAddress = "[email protected]"
MessageSubject = "SUCCESS"
MessageBody = "It was successful"
MessageAttachment = &directory&"\"&fileName&"_Log.txt"
Set ol = WScript.CreateObject("Outlook.Application")
Set ns = ol.getNamespace("MAPI")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.Body = MessageBody & vbCrLf & MyTime
newMail.RecipIents.Add(ToAddress)
newMail.Attachments.Add(MessageAttachment)
newMail.Send
objTextFile.Close
</code></pre>
<p>But not working...</p>
<p>Thanks in advance!</p> | 11,348,036 | 3 | 0 | null | 2012-06-29 15:49:56.32 UTC | 4 | 2012-07-05 15:51:07.473 UTC | 2012-06-29 17:46:34.83 UTC | null | 1,459,606 | null | 1,459,606 | null | 1 | 6 | parameters|vbscript|batch-file | 48,090 | <p>Alright, I am updating that question I had. It's finally working, with all of your help, guys.
Thanks.
Here is how I called the vbscript and passed a parameter to it:</p>
<pre><code>cscript //nologo fail_mail.vbs something.sql 'something.sql is the param. that i'm passing.
</code></pre>
<p>Here is what my vbscript for mail looks like:</p>
<pre><code>Const ForReading = 1
Set args = WScript.Arguments
arg1 = args.Item(0) 'the parameter from batch comes in here to arg1
...
...
ToAddress = "[email protected]"
MessageSubject = "WORKED"
MessageBody = "Success"
MessageAttachment = ""&arg1&"" 'here those quotes are important. dk why.
Set ol = WScript.CreateObject("Outlook.Application")
Set ns = ol.getNamespace("MAPI")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject
newMail.Body = MessageBody & vbCrLf & MyTime
newMail.RecipIents.Add(ToAddress)
newMail.Attachments.Add(MessageAttachment)
newMail.Send
</code></pre>
<p>And it is working.
*One can pass more than one parameters using the same technique.</p> |
10,949,893 | VBA error 1004 - select method of range class failed | <p>First time poster, so if there is any formatting, or guidelines I failed to adhere to, please let me know so that I can fix it. </p>
<p>So I am basically asking the user for the file directory of the excel file, then I setup some variables (originally set at public as project variables, since these were being used and changed in other places). I have also added the lines to set these variables to nothing (just in case, I do not think that it should matter). I then set these variables to the excel file, workbook, and sheets that I want to access. </p>
<pre><code>Dim filepath as String
filePath = CStr(fileDialog) 'ask file dir, set to string
Dim sourceXL As Variant 'these three were orig project variables
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant
Set sourceXL = Nothing 'set to nothing in case...?
Set sourceBook = Nothing
Set sourceSheet = Nothing
Set sourceSheetSum = Nothing
Set sourceXL = Excel.Application 'set to the paths needed
Set sourceBook = sourceXL.Workbooks.Open(filePath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
Dim measName As Variant 'create variable to access later
Dim partName As Variant
sourceSheetSum.Range("C3").Select 'THIS IS THE PROBLEM LINE
measName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value
sourceSheetSum.Range("D3").Select
partName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value
</code></pre>
<p>So I created two different sheet variables 'sourceSheets' and 'sourceSheetsSum', the code works if i use 'sourceSheets', but error 1004 occurs if i use 'sourceSheetsSum'. I have also tried the code with the variable 'sourceSheet' removed completely, in case that was overriding 'sourceSheetSum' for some reason.</p>
<p>I am fairly confident that the excel workbook and sheets exist and are being called correctly, since I ran a quick bit of code to loop through all the sheets in the workbook and output the names, shown below.</p>
<pre><code>For j = 1 To sourceBook.Sheets.Count
Debug.Print (Sheets(j).name)
Next j
</code></pre>
<p>With the debug output of</p>
<blockquote>
<p>Measurements<br>
Analysis Summary<br>
Analysis Settings</p>
</blockquote>
<p>So, does anyone have any ideas what this error could mean, or how I can possibly go about finding more about what the error actually is?</p>
<p>EDIT:
So I decided to add a bit to the listing of the sheet names, not sure if it will help at all.</p>
<pre><code>For j = 1 To sourceBook.Sheets.Count
listSheet(j) = Sheets(j).name
Next j
Debug.Print (listSheet(2))
Set sourceSheetSum = sourceBook.Sheets(listSheet(2))
</code></pre>
<p>The debug prints Analysis Summary, so I know that the sheet exists in the workbook, and there should not be any issues with a 'typo' in the names. <br>
The code still has the same error at the same line though.</p>
<p>deusxmach1na: I think you wanted me to change </p>
<pre><code>Dim sourceXL As Variant
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant
Set sourceSheet = sourceBook.Sheets("Measurements")
</code></pre>
<p>To </p>
<pre><code>Dim sourceXL As Excel.Application
Dim sourceBook As Excel.Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceSheet = sourceBook.Worksheets("Measurements")
</code></pre>
<p>But this does not change the error, I remember I had it similar to that, and then changed it since I read that variant is like a catch all, not actually that solid on what variant is.</p> | 10,952,432 | 4 | 1 | null | 2012-06-08 13:34:07.377 UTC | 5 | 2014-11-20 15:58:34.733 UTC | 2018-07-09 18:41:45.953 UTC | null | -1 | null | 1,444,573 | null | 1 | 21 | vb.net|excel|excel-2010|powerpoint|vba | 131,609 | <p>You have to select the sheet before you can select the range.</p>
<p>I've simplified the example to isolate the problem. Try this:</p>
<pre><code>Option Explicit
Sub RangeError()
Dim sourceBook As Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet
Set sourceBook = ActiveWorkbook
Set sourceSheet = sourceBook.Sheets("Sheet1")
Set sourceSheetSum = sourceBook.Sheets("Sheet2")
sourceSheetSum.Select
sourceSheetSum.Range("C3").Select 'THIS IS THE PROBLEM LINE
End Sub
</code></pre>
<p>Replace Sheet1 and Sheet2 with your sheet names.</p>
<p><strong>IMPORTANT NOTE:</strong> Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.</p> |
10,995,254 | jenkins script console: list of available jenkins methods? | <p>I would like to use the jenkins script console some more.</p>
<p>Where do I have to look in order to find a list of available Objects/Methods that I can use via groovy? Is there something online? Should I browse the source on Github? Where would I start?</p>
<p>Like in this example, how would I have known that <code>hudson.model.Hudson.instance.pluginManager.plugins</code> exists and is ready to be called from the jenkins script console?</p>
<pre><code>println(hudson.model.Hudson.instance.pluginManager.plugins)
</code></pre>
<p>Thanks!</p> | 10,995,514 | 2 | 0 | null | 2012-06-12 10:55:33.223 UTC | 5 | 2013-07-18 21:30:52.157 UTC | 2013-07-18 21:30:52.157 UTC | null | 1,708,136 | null | 568,844 | null | 1 | 24 | groovy|jenkins | 38,379 | <p>You are looking for <a href="http://javadoc.jenkins-ci.org/" rel="noreferrer">Jenkins Main Module API</a>.</p>
<p>You may find <a href="https://stackoverflow.com/a/10781891/1178189">this answer</a> helpful in getting yourself on your way.</p> |
11,124,539 | How to acquire a lock by a key | <p>What is the best way to prevent concurrent update of one record in a key-value set without locking the entire set? Semantically, I'm looking for some kind of locking by a key (ideally, Java implementation, but not necessarily):</p>
<pre><code>interface LockByKey {
void lock(String key); // acquire an exclusive lock for a key
void unlock(String key); // release lock for a key
}
</code></pre>
<p>This lock is intended to synchronize an access to a remote store, so some synchronized Java collection is not an option.</p> | 11,125,602 | 6 | 3 | null | 2012-06-20 17:02:42.657 UTC | 15 | 2019-02-14 11:37:35.617 UTC | null | null | null | null | 1,128,016 | null | 1 | 37 | java|algorithm|synchronization|locking | 19,343 | <p>Guava has something like this being released in 13.0; you can get it out of HEAD if you like.</p>
<p><a href="https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/Striped.java" rel="noreferrer"><code>Striped<Lock></code></a> more or less allocates a specific number of locks, and then assigns strings to locks based on their hash code. The API looks more or less like</p>
<pre><code>Striped<Lock> locks = Striped.lock(stripes);
Lock l = locks.get(string);
l.lock();
try {
// do stuff
} finally {
l.unlock();
}
</code></pre>
<p>More or less, the controllable number of stripes lets you trade concurrency against memory usage, because allocating a full lock for each string key can get expensive; essentially, you only get lock contention when you get hash collisions, which are (predictably) rare.</p>
<p>(Disclosure: I contribute to Guava.)</p> |
11,077,425 | Finding distance between CLLocationCoordinate2D points | <p>I know from documentation we can find distance between two <code>CLLocation</code> points using the function, <code>distanceFromLocation:</code>. But my problem is I dont have CLLocation data type with me, I have the CLLocationCoordinate2D points. So how can I find distance between two CLLocationCoordinate2D points. I have seen the post <a href="https://stackoverflow.com/questions/3905896/distancefromlocation-calculate-distance-between-two-points">post</a> but not helpful for me. </p> | 11,077,442 | 8 | 3 | null | 2012-06-18 05:39:04.163 UTC | 4 | 2021-09-14 16:32:43.773 UTC | 2017-05-23 10:31:31.763 UTC | null | -1 | null | 818,514 | null | 1 | 45 | ios|iphone|core-location | 28,166 | <p>You should create an object of CLLocation using,</p>
<pre><code>- (id)initWithLatitude:(CLLocationDegrees)latitude
longitude:(CLLocationDegrees)longitude;
</code></pre>
<p>Then, you should be able to calculate the distance using</p>
<pre><code>[location1 distanceFromLocation:location2];
</code></pre> |
11,076,272 | It's not possible to lock a mongodb document. What if I need to? | <p>I know that I can't lock a single mongodb document, in fact there is no way to lock a collection either.</p>
<p>However, I've got this scenario, where I think I need some way to prevent more than one thread (or process, it's not important) from modifying a document. Here's my scenario.</p>
<p>I have a collection that contains object of type A. I have some code that retrieve a document of type A, add an element in an array that is a property of the document (<code>a.arr.add(new Thing()</code>) and then save back the document to mongodb. This code is parallel, multiple threads in my applications can do theses operations and for now there is no way to prevent to threads from doing theses operations in parallel on the same document. This is bad because one of the threads could overwrite the works of the other.</p>
<p>I do use the repository pattern to abstract the access to the mongodb collection, so I only have CRUDs operations at my disposition.</p>
<p>Now that I think about it, maybe it's a limitation of the repository pattern and not a limitation of mongodb that is causing me troubles. Anyway, how can I make this code "thread safe"? I guess there's a well known solution to this problem, but being new to mongodb and the repository pattern, I don't immediately sees it.</p>
<p>Thanks</p> | 31,036,136 | 13 | 0 | null | 2012-06-18 02:12:18.743 UTC | 10 | 2021-06-07 23:47:55.117 UTC | 2014-03-02 14:10:02.56 UTC | null | 5,861 | null | 5,861 | null | 1 | 48 | mongodb|repository-pattern | 44,751 | <p>Stumbled into this question while working on mongodb upgrades. Unlike at the time this question was asked, now mongodb supports document level locking out of the box.</p>
<p>From: <a href="http://docs.mongodb.org/manual/faq/concurrency/" rel="noreferrer">http://docs.mongodb.org/manual/faq/concurrency/</a></p>
<p>"How granular are locks in MongoDB?</p>
<p>Changed in version 3.0.</p>
<p>Beginning with version 3.0, MongoDB ships with the WiredTiger storage engine, which uses optimistic concurrency control for most read and write operations. WiredTiger uses only intent locks at the global, database and collection levels. When the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation."</p> |
11,012,527 | What does `kill -0 $pid` in a shell script do? | <p>Basically, what signal does '0' represent, because <a href="http://lxr.linux.no/linux+v2.6.16.60/include/asm-i386/signal.h#L34">here</a> I see SIGNAL numbers starting from 1. </p> | 11,012,755 | 6 | 2 | null | 2012-06-13 10:00:50.033 UTC | 32 | 2021-04-26 17:52:36.713 UTC | 2019-08-20 17:14:58.53 UTC | null | 124,486 | null | 1,237,287 | null | 1 | 149 | bash|shell|scripting|signals|kill | 63,121 | <p>sending the signal <code>0</code> to a given <code>PID</code> just checks if any process with the given <code>PID</code> is running and you have the permission to send a signal to it.</p>
<p>For more information see the following manpages:</p>
<em>kill(1)</em>
<pre><code>$ man 1 kill
...
If sig is 0, then no signal is sent, but error checking is still performed.
...
</code></pre>
<em>kill(2)</em>
<pre><code>$ man 2 kill
...
If sig is 0, then no signal is sent, but error checking is still performed; this
can be used to check for the existence of a process ID or process group ID.
...
</code></pre> |
12,657,389 | AngularJS load service then call controller and render | <p>My problem is that i need a service loaded before the controller get called and the template get rendered.
<a href="http://jsfiddle.net/g75XQ/2/" rel="noreferrer">http://jsfiddle.net/g75XQ/2/</a></p>
<p><strong>Html:</strong></p>
<pre><code><div ng-app="app" ng-controller="root">
<h3>Do not render this before user has loaded</h3>
{{user}}
</div>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>angular.module('app', []).
factory('user',function($timeout,$q){
var user = {};
$timeout(function(){//Simulate a request
user.name = "Jossi";
},1000);
return user;
}).
controller('root',function($scope,user){
alert("Do not alert before user has loaded");
$scope.user = user;
});
</code></pre>
<p></p> | 12,657,669 | 6 | 1 | null | 2012-09-29 23:25:57.657 UTC | 7 | 2017-02-08 16:39:55.327 UTC | 2012-09-30 00:19:34.55 UTC | null | 1,704,423 | null | 1,704,423 | null | 1 | 21 | javascript|synchronization|sync|angularjs | 38,031 | <p>You can defer init of angular app using <a href="https://docs.angularjs.org/guide/bootstrap#manual-initialization" rel="nofollow noreferrer">manual initialization</a>, instead of auto init with <code>ng-app</code> attribute.</p>
<pre><code>// define some service that has `$window` injected and read your data from it
angular.service('myService', ['$window', ($window) =>({
getData() {
return $window.myData;
}
}))
const callService = (cb) => {
$.ajax(...).success((data)=>{
window.myData = data;
cb(data)
})
}
// init angular app
angular.element(document).ready(function() {
callService(function (data) {
doSomething(data);
angular.bootstrap(document);
});
});
</code></pre>
<p>where <code>callService</code> is your function performing AJAX call and accepting success callback, which will init angular app.</p>
<p>Also check <code>ngCloak</code> directive, since it maybe everything you need.</p>
<p>Alternatively, when using <a href="https://docs.angularjs.org/api/ngRoute" rel="nofollow noreferrer">ngRoute</a> you can use <code>resolve</code> property, for that you can see @honkskillet answer</p> |
12,854,125 | How do I dump the struct into the byte array without reflection? | <p>I already found <a href="http://golang.org/pkg/encoding/binary/" rel="noreferrer">encoding/binary</a> package to deal with it, but it depended on <a href="http://golang.org/pkg/reflect/" rel="noreferrer">reflect</a> package so it didn't work with uncapitalized(that is, unexported) struct fields. However I spent a week to find that problem out, I still have a question: if struct fields should not be exported, how do I dump them easily into binary data?</p>
<p><strong>EDIT:</strong> Here's the example. If you capitalize the name of fields of <code>Data</code> struct, that works properly. But <code>Data</code> struct was intended to be an abstract type, so I don't want to export these fields.</p>
<pre class="lang-go prettyprint-override"><code>package main
import (
"fmt"
"encoding/binary"
"bytes"
)
type Data struct {
id int32
name [16]byte
}
func main() {
d := Data{Id: 1}
copy(d.Name[:], []byte("tree"))
buffer := new(bytes.Buffer)
binary.Write(buffer, binary.LittleEndian, d)
// d was written properly
fmt.Println(buffer.Bytes())
// try to read...
buffer = bytes.NewBuffer(buffer.Bytes())
var e = new(Data)
err := binary.Read(buffer, binary.LittleEndian, e)
fmt.Println(e, err)
}
</code></pre> | 12,854,659 | 1 | 8 | null | 2012-10-12 07:20:06.843 UTC | 10 | 2015-09-14 16:05:55.993 UTC | 2015-09-14 16:05:55.993 UTC | null | 13,860 | null | 676,818 | null | 1 | 23 | struct|binary|bytearray|go|structure | 16,602 | <p>Your best option would probably be to use the <a href="http://golang.org/pkg/encoding/gob" rel="noreferrer">gob package</a> and let your struct implement the <a href="http://golang.org/pkg/encoding/gob/#GobDecoder" rel="noreferrer">GobDecoder</a> and <a href="http://golang.org/pkg/encoding/gob/#GobEncoder" rel="noreferrer">GobEncoder</a> interfaces in order to serialize and deserialize private fields.</p>
<p>This would be safe, platform independent, and efficient. And you have to add those GobEncode and GobDecode functions only on structs with unexported fields, which means you don't clutter the rest of your code.</p>
<pre><code>func (d *Data) GobEncode() ([]byte, error) {
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
err := encoder.Encode(d.id)
if err!=nil {
return nil, err
}
err = encoder.Encode(d.name)
if err!=nil {
return nil, err
}
return w.Bytes(), nil
}
func (d *Data) GobDecode(buf []byte) error {
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
err := decoder.Decode(&d.id)
if err!=nil {
return err
}
return decoder.Decode(&d.name)
}
func main() {
d := Data{id: 7}
copy(d.name[:], []byte("tree"))
buffer := new(bytes.Buffer)
// writing
enc := gob.NewEncoder(buffer)
err := enc.Encode(d)
if err != nil {
log.Fatal("encode error:", err)
}
// reading
buffer = bytes.NewBuffer(buffer.Bytes())
e := new(Data)
dec := gob.NewDecoder(buffer)
err = dec.Decode(e)
fmt.Println(e, err)
}
</code></pre> |
13,037,654 | Subtract two dates in Java | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances">Calculating the Difference Between Two Java Date Instances</a> </p>
</blockquote>
<p>I know this might be a duplicate thread. But I am trying to figure out a way to compute the difference between two dates. From jquery the date string is in the format <code>'yyyy-mm-dd'</code>. I read this as a String and converted to java Date like this</p>
<pre><code>Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date2));
</code></pre>
<p>I want to compute the difference in the number of days between these two dates.</p>
<p><strong>Note:</strong> I cannot use third party API's as those need to reviewed.</p> | 13,038,018 | 3 | 8 | null | 2012-10-23 19:21:44.84 UTC | 6 | 2018-05-28 15:29:27.71 UTC | 2017-05-23 11:55:07.73 UTC | null | -1 | null | 525,146 | null | 1 | 31 | java|date | 148,894 | <p><strong>Edit 2018-05-28</strong>
I have changed the example to use Java 8's Time API:</p>
<pre><code>LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
</code></pre> |
30,537,330 | Is floating point precision mutable or invariant? | <p>I keep getting mixed answers of whether floating point numbers (i.e. <code>float</code>, <code>double</code>, or <code>long double</code>) have one and only one value of precision, or have a precision value which can vary.</p>
<p>One topic called <a href="https://stackoverflow.com/questions/5098558/float-vs-double-precision">float vs. double precision</a> seems to imply that floating point precision is an absolute.</p>
<p>However, another topic called <a href="https://stackoverflow.com/questions/2386772/difference-between-float-and-double">Difference between float and double</a> says,</p>
<blockquote>
<p><em>In general a double has <strong>15 to 16</strong> decimal digits of precision</em></p>
</blockquote>
<p>Another <a href="http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/" rel="nofollow noreferrer">source</a> says,</p>
<blockquote>
<p><em>Variables of type float typically have a precision of <strong>about</strong> 7 significant digits</em></p>
<p><em>Variables of type double typically have a precision of <strong>about</strong> 16 significant digits</em></p>
</blockquote>
<p>I don't like to refer to approximations like the above if I'm working with sensitive code that can break easily when my values are not exact. So let's set the record straight. Is floating point precision mutable or invariant, and why?</p> | 30,537,382 | 10 | 9 | null | 2015-05-29 19:11:03.1 UTC | 7 | 2015-08-28 03:00:52.553 UTC | 2017-05-23 12:16:31.86 UTC | null | -1 | null | 4,750,730 | null | 1 | 39 | binary|floating-point|decimal|floating-point-precision|significant-digits | 2,764 | <p>The precision is fixed, which is <strong>exactly 53 binary digits</strong> for double-precision (or 52 if we exclude the implicit leading 1). This comes out to <strong>about 15 decimal digits</strong>.</p>
<hr>
<p>The OP asked me to elaborate on why having exactly 53 binary digits means "about" 15 decimal digits.</p>
<p>To understand this intuitively, let's consider a less-precise floating-point format: instead of a 52-bit mantissa like double-precision numbers have, we're just going to use a 4-bit mantissa.</p>
<p>So, each number will look like: (-1)<sup>s</sup> × 2<sup>yyy</sup> × 1.xxxx (where <code>s</code> is the sign bit, <code>yyy</code> is the exponent, and <code>1.xxxx</code> is the normalised mantissa). For the immediate discussion, we'll focus only on the mantissa and not the sign or exponent.</p>
<p>Here's a table of what <code>1.xxxx</code> looks like for all <code>xxxx</code> values (all rounding is half-to-even, just like how the default floating-point rounding mode works):</p>
<pre class="lang-none prettyprint-override"><code> xxxx | 1.xxxx | value | 2dd | 3dd
--------+----------+----------+-------+--------
0000 | 1.0000 | 1.0 | 1.0 | 1.00
0001 | 1.0001 | 1.0625 | 1.1 | 1.06
0010 | 1.0010 | 1.125 | 1.1 | 1.12
0011 | 1.0011 | 1.1875 | 1.2 | 1.19
0100 | 1.0100 | 1.25 | 1.2 | 1.25
0101 | 1.0101 | 1.3125 | 1.3 | 1.31
0110 | 1.0110 | 1.375 | 1.4 | 1.38
0111 | 1.0111 | 1.4375 | 1.4 | 1.44
1000 | 1.1000 | 1.5 | 1.5 | 1.50
1001 | 1.1001 | 1.5625 | 1.6 | 1.56
1010 | 1.1010 | 1.625 | 1.6 | 1.62
1011 | 1.1011 | 1.6875 | 1.7 | 1.69
1100 | 1.1100 | 1.75 | 1.8 | 1.75
1101 | 1.1101 | 1.8125 | 1.8 | 1.81
1110 | 1.1110 | 1.875 | 1.9 | 1.88
1111 | 1.1111 | 1.9375 | 1.9 | 1.94
</code></pre>
<p>How many decimal digits do you say that provides? You could say 2, in that each value in the two-decimal-digit range is covered, albeit not uniquely; or you could say 3, which covers all unique values, but do not provide coverage for all values in the three-decimal-digit range.</p>
<p>For the sake of argument, we'll say it has 2 decimal digits: the decimal precision will be the number of digits where all values of those decimal digits could be represented.</p>
<hr>
<p>Okay, then, so what happens if we halve all the numbers (so we're using <code>yyy</code> = -1)?</p>
<pre class="lang-none prettyprint-override"><code> xxxx | 1.xxxx | value | 1dd | 2dd
--------+----------+-----------+-------+--------
0000 | 1.0000 | 0.5 | 0.5 | 0.50
0001 | 1.0001 | 0.53125 | 0.5 | 0.53
0010 | 1.0010 | 0.5625 | 0.6 | 0.56
0011 | 1.0011 | 0.59375 | 0.6 | 0.59
0100 | 1.0100 | 0.625 | 0.6 | 0.62
0101 | 1.0101 | 0.65625 | 0.7 | 0.66
0110 | 1.0110 | 0.6875 | 0.7 | 0.69
0111 | 1.0111 | 0.71875 | 0.7 | 0.72
1000 | 1.1000 | 0.75 | 0.8 | 0.75
1001 | 1.1001 | 0.78125 | 0.8 | 0.78
1010 | 1.1010 | 0.8125 | 0.8 | 0.81
1011 | 1.1011 | 0.84375 | 0.8 | 0.84
1100 | 1.1100 | 0.875 | 0.9 | 0.88
1101 | 1.1101 | 0.90625 | 0.9 | 0.91
1110 | 1.1110 | 0.9375 | 0.9 | 0.94
1111 | 1.1111 | 0.96875 | 1. | 0.97
</code></pre>
<p>By the same criteria as before, we're now dealing with 1 decimal digit. So you can see how, depending on the exponent, you can have more or less decimal digits, because <strong>binary and decimal floating-point numbers do not map cleanly to each other</strong>.</p>
<p>The same argument applies to double-precision floating point numbers (with the 52-bit mantissa), only in that case you're getting either 15 or 16 decimal digits depending on the exponent.</p> |
37,550,560 | Why is React Webpack production build showing Blank page? | <p>I'm building a react app, and at the moment <code>webpack-dev-server</code> works just fine( the <strong>hello world</strong> text shows up ), But webpack -p shows blank page. For the Production build The network tab under chrome dev tools, shows <code>index.html</code> and <code>index_bundle.js</code> to have size 0 B(see picture)<a href="https://i.stack.imgur.com/eei4z.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eei4z.jpg" alt="enter image description here"></a> But That is clearly not the case HTML file size is 227 B & <code>index_bundle.js</code> file size is 195Kb(see picture) <a href="https://i.stack.imgur.com/766rz.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/766rz.jpg" alt=""></a></p>
<p>Also Chrome Devtools Elements Tab shows the following(see picture)
<a href="https://i.stack.imgur.com/bdmHu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bdmHu.jpg" alt="enter image description here"></a></p>
<p>My webpack config file looks like this:<a href="https://i.stack.imgur.com/Rn1Yo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Rn1Yo.jpg" alt="enter image description here"></a></p> | 37,557,805 | 7 | 9 | null | 2016-05-31 16:02:43.54 UTC | 9 | 2020-06-26 08:21:51.54 UTC | 2017-07-19 01:37:38.057 UTC | null | 5,404,861 | null | 3,818,829 | null | 1 | 26 | javascript|web-applications|reactjs|webpack|redux | 23,599 | <p>I figured it out, I was using browserHistory without setting up a local server. If i changed it to hashHistory it worked. To test webpack production locally with react-router browser history i needed to do this Configure a Server:</p>
<p>Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /accounts/23 your web server will get a request to /accounts/23. You will need it to handle that URL and include your JavaScript application in the response.</p>
<p>An express app might look like this:</p>
<pre><code>const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// serve static assets normally
app.use(express.static(__dirname + '/public'))
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)
</code></pre>
<p>And just in case anyone is deploying to firebase using react-router with browser-history do this:</p>
<pre><code>{
"firebase": "<YOUR-FIREBASE-APP>",
"public": "<YOUR-PUBLIC-DIRECTORY>",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
</code></pre> |
16,813,118 | Extending Object.prototype with TypeScript | <p>I am currently working on a TypeScript API, which requires some additional features binding to the Object prototype (Object.prototype).</p>
<p>Consider the following code:</p>
<pre><code>class Foo {
}
interface Object {
GetFoo(): Foo;
GetFooAsString(): string;
}
//This is problematic...
Object.prototype.GetFoo = function() {
return new Foo();
// Note, this line is just for testing...I don't want my function to just return a blank instance of Foo!
}
//This is ok.
Object.prototype.GetFooAsString = function () {
return this.GetFoo().toString();
}
</code></pre>
<p>You might want to try this directly at the <a href="http://www.typescriptlang.org/Playground/#src=class%20Foo%20%7B%0A%0A%7D%0A%0Ainterface%20Object%20%7B%0A%20%20%20%20GetFoo%28%29%3a%20Foo;%0A%20%20%20%20GetFooAsString%28%29%3a%20string;%0A%7D%0A%0A//This%20is%20problematic...%0AObject.prototype.GetFoo%20=%20function%28%29%20%7B%0A%20%20%20%20return%20new%20Foo%28%29;%0A%20%20%20%20//%20Note,%20this%20line%20is%20just%20for%20testing...I%20don%27t%20want%20my%20function%20to%20just%20return%20a%20blank%20instance%20of%20Foo!%0A%7D%0A%0A//This%20is%20ok.%0AObject.prototype.GetFooAsString%20=%20function%20%28%29%20%7B%0A%20%20%20%20return%20this.GetFoo%28%29.toString%28%29;%0A%7D">Playground</a>.</p>
<p>As you can see, I have a class called <code>Foo</code> (not the actual object name I will be using). I have also extended the <code>Object</code> interface to include two new functions. Finally I have implemented the functions against the <code>prototype</code> (these work in pure JavaScript, it's just TypeScript that complains).</p>
<p>Where I have annotated "<em>//this is problematic...</em>" TypeScript highlights this with a red squiggly, and shows the following error:</p>
<pre><code>Cannot convert '() => Foo' to '{ (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; }': Call signatures of types '() => Foo' and '{ (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; (): Foo; }' are incompatible
() => Foo
</code></pre>
<p>Either this is just a TypeScript bug (I know it's still in development phase, so a lot of the bugs need ironing out, and I have illustrated some of these on CodePlex already), or, I'm missing something.</p>
<p>Why am I getting this issue?</p>
<p>If it's not a TypeScript bug, how can I fix this?</p> | 16,813,554 | 3 | 0 | null | 2013-05-29 11:51:22.557 UTC | 8 | 2017-05-02 22:59:16.283 UTC | 2013-05-29 12:05:22.217 UTC | null | 1,014,822 | null | 1,033,686 | null | 1 | 34 | javascript|object|interface|prototype|typescript | 68,102 | <p>This bug is fixed in TS 0.9.0 alpha as you can see below:
<img src="https://i.stack.imgur.com/L71ZB.png" alt="no error in Ts 0.9.0 alpha"></p>
<p>The playground is still running 0.8.3. </p>
<p>This basically happens because methods on some key interfaces ( Object, Number, String ) etc get cached as a performance optimization. </p>
<p>If you run this. The first time it loads you will not see that error. <a href="http://www.typescriptlang.org/Playground/#src=class%20Foo%20%7B%0A%0A%7D%0A%0Ainterface%20Object%20%7B%0A%20%20%20%20GetFoo%28%29:%20Foo;%0A%20%20%20%20GetFooAsString%28%29:%20string;%0A%7D%0A%0A//This%20is%20problematic...%0AObject.prototype.GetFoo%20=%20function%28%29%20%7B%0A%20%20%20%20return%20new%20Foo%28%29;%0A%20%20%20%20//%20Note,%20this%20line%20is%20just%20for%20testing...I%20don%27t%20want%20my%20function%20to%20just%20return%20a%20blank%20instance%20of%20Foo!%0A%7D%0A%0A//This%20is%20ok.%0AObject.prototype.GetFooAsString%20=%20function%20%28%29%20%7B%0A%20%20%20%20return%20this.GetFoo%28%29.toString%28%29;%0A%7D" rel="noreferrer">Try It</a>. </p>
<p>As soon as you make an edit to that code, the parser goes through the code again, and since it cached the old interface definition sees a duplicate function definition and then effectively blows up. The more edits you make to that file the more complicated the error statement will get. </p> |
17,116,114 | How to Troubleshoot Angular "10 $digest() iterations reached" Error | <blockquote>
<p>10 $digest() iterations reached. Aborting!</p>
</blockquote>
<p>There is a lot of supporting text in the sense of "Watchers fired in the last 5 iterations: ", etc., but a lot of this text is Javascript code from various functions. Are there rules of thumb for diagnosing this problem? Is it a problem that can ALWAYS be mitigated, or are there applications complex enough that this issue should be treated as just a warning?</p> | 17,129,274 | 13 | 0 | null | 2013-06-14 19:43:01.153 UTC | 24 | 2019-01-18 14:10:12.007 UTC | 2016-08-16 12:36:11.903 UTC | null | 546,730 | null | 253,263 | null | 1 | 95 | angularjs | 83,162 | <p>as Ven said, you are either returning different (not identical) objects on each <code>$digest</code> cycle, or you are altering the data too many times.</p>
<p><strong>The fastest solution to figure out which part of your app is causing this behavior is:</strong></p>
<ol>
<li>remove all suspicious HTML - basically remove all your html from the template, and check if there are no warnings</li>
<li>if there are no warnings - add small parts of the html you removed and check if the problem is back</li>
<li>repeat step 2 until you get a warning - you will figure out which part of your html is responsible for the problem </li>
<li>investigate further - the part from step 3 is responsible for either mutating the objects on the <code>$scope</code> or is returning non-identical objects on each <code>$digest</code> cycle.</li>
<li>if you still have <code>$digest</code> iteration warnings after step 1, than you are probably doing something very suspicious. Repeat the same steps for parent template/scope/controller</li>
</ol>
<p><strong>You also want to make sure you are not altering the input of your custom filters</strong></p>
<p>Keep in mind, that in JavaScript there are specific types of objects that don't behave like you would normally expect:</p>
<pre><code>new Boolean(true) === new Boolean(true) // false
new Date(0) == new Date(0) // false
new String('a') == new String('a') // false
new Number(1) == new Number(1) // false
[] == [] // false
new Array == new Array // false
({})==({}) // false
</code></pre> |
16,873,323 | JavaScript sleep/wait before continuing | <p>I have a JavaScript code that I need to add a sleep/wait function to. The code I am running is already in a function, eg:</p>
<pre><code>function myFunction(time)
{
alert('time starts now');
//code to make the program wait before continuing
alert('time is up')
}
</code></pre>
<p>I have heard that a possible solution might include</p>
<pre><code>setTimeout
</code></pre>
<p>but I am not sure how to use it in this case.</p>
<p>I can't use PHP, as my server does not support it, although using jQuery would be fine.</p> | 16,873,849 | 1 | 5 | null | 2013-06-01 13:40:38.48 UTC | 71 | 2020-06-20 15:51:02.96 UTC | 2015-08-01 20:52:24.513 UTC | null | 1,828,051 | null | 2,370,460 | null | 1 | 373 | javascript|jquery|delay|sleep|wait | 1,361,153 | <p>JS does not have a sleep function, it has <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout" rel="noreferrer"><strong>setTimeout()</strong></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval" rel="noreferrer"><strong>setInterval()</strong></a> functions.</p>
<p>If you can move the code that you need to run after the pause into the <code>setTimeout()</code> callback, you can do something like this:</p>
<pre><code>//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
</code></pre>
<p>see example here : <a href="http://jsfiddle.net/9LZQp/" rel="noreferrer">http://jsfiddle.net/9LZQp/</a></p>
<p>This won't halt the execution of your script, but due to the fact that <code>setTimeout()</code> is an asynchronous function, this code</p>
<pre><code>console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
</code></pre>
<p>will print this in the console:</p>
<pre><code>HELLO
DOG
THIS IS
</code></pre>
<p>(note that <strong>DOG</strong> is printed before <strong>THIS IS</strong>)</p>
<hr />
<p>You can use the following code to simulate a sleep for short periods of time:</p>
<pre><code>function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</code></pre>
<p>now, if you want to sleep for 1 second, just use:</p>
<pre><code>sleep(1000);
</code></pre>
<p>example: <a href="http://jsfiddle.net/HrJku/1/" rel="noreferrer">http://jsfiddle.net/HrJku/1/</a></p>
<p>please note that <strong>this code will keep your script busy for <em>n milliseconds</em>. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive</strong>. In other words this is almost always the wrong thing to do.</p> |
16,926,130 | Convert to binary and keep leading zeros | <p>I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:</p>
<p>Example:</p>
<pre><code>bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
</code></pre>
<p>Is there a way of doing this?</p> | 16,926,357 | 10 | 1 | null | 2013-06-04 19:41:19.523 UTC | 59 | 2022-08-23 11:37:31.077 UTC | 2021-05-31 02:19:40.4 UTC | null | 355,230 | null | 1,272,712 | null | 1 | 214 | python|binary|formatting|bitwise-operators | 241,383 | <p>Use the <a href="http://docs.python.org/2/library/functions.html#format" rel="noreferrer"><code>format()</code> function</a>:</p>
<pre><code>>>> format(14, '#010b')
'0b00001110'
</code></pre>
<p>The <code>format()</code> function simply formats the input following the <a href="http://docs.python.org/2/library/string.html#format-specification-mini-language" rel="noreferrer">Format Specification mini language</a>. The <code>#</code> makes the format include the <code>0b</code> prefix, and the <code>010</code> size formats the output to fit in 10 characters width, with <code>0</code> padding; 2 characters for the <code>0b</code> prefix, the other 8 for the binary digits.</p>
<p>This is the most compact and direct option.</p>
<p>If you are putting the result in a larger string, use an <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">formatted string literal</a> (3.6+) or use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="noreferrer"><code>str.format()</code></a> and put the second argument for the <code>format()</code> function after the colon of the placeholder <code>{:..}</code>:</p>
<pre><code>>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
</code></pre>
<p>As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using <code>format()</code>:</p>
<pre><code>>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
</code></pre>
<p>But I'd use that only if performance in a tight loop matters, as <code>format(...)</code> communicates the intent better.</p>
<p>If you did not want the <code>0b</code> prefix, simply drop the <code>#</code> and adjust the length of the field:</p>
<pre><code>>>> format(14, '08b')
'00001110'
</code></pre> |
25,546,022 | PHPStorm/Webstorm increase memory to more than 512MB | <p>I'm using <code>PHPStorm</code> under <code>Win7 64bit</code> with <code>64bit Java (latest version I guess)</code> and working currently on an insanely big and chaotic project. There are many classes containing <code>10k LOC</code> and more. Therefore my <code>PHPStorm</code> runs out of memory once in a while.</p>
<p>I get this nice <code>Out-of-Memory</code> dialog suggesting increasing my memory settings. I currently have set in my <code>PhpStorm.exe.vmoptions</code>:</p>
<pre><code>-server
-Xms128m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=64m
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+UseCodeCacheFlushing
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
</code></pre>
<p>The problem is: When I increase my memory to be used in this file I get the following error when starting the program:</p>
<blockquote>
<p>Failed to create JVM: Error code -4</p>
</blockquote>
<p>I Googled around but nobody seems to want the memory to be <strong>more</strong> than <code>512MB</code>.</p>
<p><strong>Does anybody know what I can do to use PHPStorm without any hassle again?</strong></p>
<p>Sure, I can reset the cache but this is not a permanent solution, right?</p>
<p>I read somewhere that adding this line to my <code>vmoptions</code> is a good idea, but I don't see any difference:</p>
<pre><code>-server
....
-XX:MinHeapFreeRatio=15
</code></pre> | 25,546,908 | 7 | 6 | null | 2014-08-28 10:02:03.043 UTC | 7 | 2021-07-13 01:26:18.513 UTC | 2016-05-27 22:58:57.397 UTC | null | 404,699 | null | 1,331,671 | null | 1 | 55 | jvm|out-of-memory|phpstorm|webstorm|windows-7-x64 | 65,186 | <p>Make sure that PhpStorm use 64-bit Java and not bundled one (which is 32-bit). You an check that in <code>Help | About</code>.</p>
<p>Generally speaking: with 64-bit Java you do not have to change that value as it works <strong>a bit</strong> differently compared to 32-bit one.</p>
<p><strong>1)</strong> PhpStorm comes with bundled x86 Java and it is the first one that it tries; only then it looks for other Java installations -- check <code>PhpStorm.bat</code> for details (what environment variables and in which order). By defining one of those environment variables (which will point to your 64-bit Java installation) you can tell PhpStorm to use instead of bundled one.</p>
<p><strong>2)</strong> PhpStorm <strong>v8</strong> (currently in EAP stage) comes with 64-bit specific files: you should use <code>PhpStorm64.exe</code> and not <code>PhpStorm.exe</code> (same for <code>.vmoptions</code> file -- it should be <code>PhpStorm64.exe.vmoptions</code>).</p>
<p>I'm not sure how PhpStorm v7 works with 64-bit Java -- have never tried it this way myself.</p>
<hr>
<p><strong>Selecting the JDK version the IDE will run under</strong></p>
<p><a href="https://intellij-support.jetbrains.com/entries/23455956-Selecting-the-JDK-version-the-IDE-will-run-under" rel="noreferrer">https://intellij-support.jetbrains.com/entries/23455956-Selecting-the-JDK-version-the-IDE-will-run-under</a></p> |
4,053,262 | How can I add multiple sources to an HTML5 audio tag, programmatically? | <p>A lot of examples demonstrate multiple source tags nested in the audio tag, as a method to overcome codec compatibility across different browsers. Something like this -</p>
<pre><code><audio controls="controls">
<source src="song.ogg" type="audio/ogg" />
<source src="song.mp3" type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
</code></pre>
<p>While with JavaScript, I'm also allowed to create an audio element like this -</p>
<pre><code>var new_audio = document.createElement("audio");
</code></pre>
<p>Where I can set its source by the <code>.src</code> property - <code>new_audio.src="....";</code></p>
<p>I failed to find how to add multiple sources in an audio element through JavaScript, something similar to source tags shown in the HTML snippet.</p>
<p>Do I manipulate the <code>new_audio</code> and add the <code><source...</code> tags inside it, just like one would manipulate any other DOM element? I'm doing this right now and it works, which is -</p>
<pre><code>new_audio.innerHTML = "<source src='audio/song.ogg' type='audio/ogg' />";
new_audio.play();
</code></pre>
<p>I wonder if there is a more appropriate way to do it?</p> | 4,053,467 | 2 | 0 | null | 2010-10-29 15:19:37.27 UTC | 8 | 2011-10-28 11:47:50.987 UTC | 2011-10-28 11:47:50.987 UTC | null | 8,655 | null | 8,786 | null | 1 | 37 | javascript|html|html5-audio | 27,487 | <p>Why add multiple files with JavaScript when you can just detect the types supported? I would suggest instead detecting the best type then just setting the <code>src</code>.</p>
<pre><code>var source= document.createElement('source');
if (audio.canPlayType('audio/mpeg;')) {
source.type= 'audio/mpeg';
source.src= 'audio/song.mp3';
} else {
source.type= 'audio/ogg';
source.src= 'audio/song.ogg';
}
audio.appendChild(source);
</code></pre>
<p>Add as many checks as you have file types.</p> |
26,815,738 | SVG use tag and ReactJS | <p>So normally to include most of my SVG icons that require simple styling, I do:</p>
<pre><code><svg>
<use xlink:href="/svg/svg-sprite#my-icon" />
</svg>
</code></pre>
<p>Now I have been playing with ReactJS as of late evaluating it as a possible component in my new front-end development stack however I noticed that in its list of supported tags/attributes, neither <code>use</code> or <code>xlink:href</code> are supported.</p>
<p>Is it possible to use svg sprites and load them in this way in ReactJS?</p> | 26,822,815 | 7 | 5 | null | 2014-11-08 09:44:17.503 UTC | 24 | 2022-08-31 15:31:36.82 UTC | null | null | null | null | 384,016 | null | 1 | 135 | svg|sprite|reactjs | 100,859 | <p><strong>Update september 2018</strong>: this solution is deprecated, read <a href="https://stackoverflow.com/questions/26815738/svg-use-tag-and-reactjs/26822815#32994814">Jon’s answer</a> instead.</p>
<p>--</p>
<p>React doesn’t support all SVG tags as you say, there is a list of supported tags <a href="http://facebook.github.io/react/docs/tags-and-attributes.html" rel="noreferrer">here</a>. They are working on wider support, f.ex in <a href="https://github.com/facebook/react/issues/1657" rel="noreferrer">this ticket</a>.</p>
<p>A common workaround is to inject HTML instead for non-supported tags, f.ex:</p>
<pre><code>render: function() {
var useTag = '<use xlink:href="/svg/svg-sprite#my-icon" />';
return <svg dangerouslySetInnerHTML={{__html: useTag }} />;
}
</code></pre> |
10,050,228 | C++ char array null terminator location | <p>I am a student learning C++, and I am trying to understand how null-terminated character arrays work. Suppose I define a char array like so:</p>
<pre><code>char* str1 = "hello world";
</code></pre>
<p>As expected, <code>strlen(str1)</code> is equal to 11, and it is null-terminated.</p>
<p>Where does C++ put the null terminator, if all 11 elements of the above char array are filled with the characters "hello world"? Is it actually allocating an array of length 12 instead of 11, with the 12th character being <code>'\0'</code>? <a href="http://www.cplusplus.com/doc/tutorial/ntcs/">CPlusPlus.com</a> seems to suggest that one of the 11 would need to be <code>'\0'</code>, unless it is indeed allocating 12.</p>
<p>Suppose I do the following:</p>
<pre><code>// Create a new char array
char* str2 = (char*) malloc( strlen(str1) );
// Copy the first one to the second one
strncpy( str2, str1, strlen(str1) );
// Output the second one
cout << "Str2: " << str2 << endl;
</code></pre>
<p>This outputs <code>Str2: hello worldatcomY╗°g♠↕</code>, which I assume is C++ reading the memory at the location pointed to by the pointer <code>char* str2</code> until it encounters what it interprets to be a null character.</p>
<p>However, if I then do this:</p>
<pre><code>// Null-terminate the second one
str2[strlen(str1)] = '\0';
// Output the second one again
cout << "Terminated Str2: " << str2 << endl;
</code></pre>
<p>It outputs <code>Terminated Str2: hello world</code> as expected.</p>
<p>But doesn't writing to <code>str2[11]</code> imply that we are writing outside of the allocated memory space of <code>str2</code>, since <code>str2[11]</code> is the 12th byte, but we only allocated 11 bytes? </p>
<p>Running this code does not seem to cause any compiler warnings or run-time errors. Is this safe to do in practice? Would it be better to use <code>malloc( strlen(str1) + 1 )</code> instead of <code>malloc( strlen(str1) )</code>?</p> | 10,050,258 | 6 | 2 | null | 2012-04-06 23:06:18.617 UTC | 5 | 2013-05-29 19:48:41.217 UTC | null | null | null | null | 1,307,032 | null | 1 | 21 | c++|arrays|char|null-terminated | 51,583 | <p>In the case of a string literal the compiler is actually reserving an extra <code>char</code> element for the <code>\0</code> element. </p>
<pre><code>// Create a new char array
char* str2 = (char*) malloc( strlen(str1) );
</code></pre>
<p>This is a common mistake new C programmers make. When allocating the storage for a <code>char*</code> you need to allocate the number of characters + 1 more to store the <code>\0</code>. Not allocating the extra storage here means this line is also illegal</p>
<pre><code>// Null-terminate the second one
str2[strlen(str1)] = '\0';
</code></pre>
<p>Here you're actually writing past the end of the memory you allocated. When allocating X elements the last legal byte you can access is the memory address offset by <code>X - 1</code>. Writing to the <code>X</code> element causes undefined behavior. It will often work but is a ticking time bomb. </p>
<p>The proper way to write this is as follows</p>
<pre><code>size_t size = strlen(str1) + sizeof(char);
char* str2 = (char*) malloc(size);
strncpy( str2, str1, size);
// Output the second one
cout << "Str2: " << str2 << endl;
</code></pre>
<p>In this example the <code>str2[size - 1] = '\0'</code> isn't actually needed. The <code>strncpy</code> function will fill all extra spaces with the null terminator. Here there are only <code>size - 1</code> elements in <code>str1</code> so the final element in the array is unneeded and will be filled with <code>\0</code></p> |
10,017,381 | How do I write a compareTo method which compares objects? | <p>I am learning about arrays, and basically I have an array that collects a last name, first name, and score.</p>
<p>I need to write a <code>compareTo</code> method that will compare the last name and then the first name so the list could be sorted alphabetically starting with the last names, and then if two people have the same last name then it will sort the first name.</p>
<p>I'm confused, because all of the information in my book is comparing numbers, not objects and Strings.</p>
<p>Here is what I have coded so far. I know it's wrong but it at least explains what I think I'm doing:</p>
<pre><code>public int compare(Object obj) // creating a method to compare
{
Student s = (Student) obj; // creating a student object
// I guess here I'm telling it to compare the last names?
int studentCompare = this.lastName.compareTo(s.getLastName());
if (studentCompare != 0)
return studentCompare;
else
{
if (this.getLastName() < s.getLastName())
return - 1;
if (this.getLastName() > s.getLastName())
return 1;
}
return 0;
}
</code></pre>
<p>I know the <code><</code> and <code>></code> symbols are wrong, but like I said my book only shows you how to use the <code>compareTo</code>.</p> | 10,017,406 | 9 | 1 | null | 2012-04-04 18:46:09.64 UTC | 12 | 2018-08-29 17:20:51.23 UTC | 2018-04-04 21:06:01.257 UTC | null | 2,891,664 | null | 1,009,070 | null | 1 | 29 | java|comparable|compareto | 164,619 | <p>This is the right way to compare strings:</p>
<pre><code>int studentCompare = this.lastName.compareTo(s.getLastName());
</code></pre>
<p>This won't even compile:</p>
<pre><code>if (this.getLastName() < s.getLastName())
</code></pre>
<p>Use
<code>if (this.getLastName().compareTo(s.getLastName()) < 0)</code> instead.</p>
<p>So to compare fist/last name order you need:</p>
<pre><code>int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;
</code></pre> |
28,201,164 | slow function call in V8 when using the same key for the functions in different objects | <p>Maybe not because the call is slow, but rather the lookup is; I'm not sure, but here is an example:</p>
<pre><code>var foo = {};
foo.fn = function() {};
var bar = {};
bar.fn = function() {};
console.time('t');
for (var i = 0; i < 100000000; i++) {
foo.fn();
}
console.timeEnd('t');
</code></pre>
<p>Tested on win8.1</p>
<ul>
<li>firefox 35.01: <strong>~240ms</strong></li>
<li>chrome 40.0.2214.93 (V8 3.30.33.15): <strong>~760ms</strong></li>
<li>msie 11: <strong>34 sec</strong></li>
<li>nodejs 0.10.21 (V8 3.14.5.9): <strong>~100ms</strong></li>
<li>iojs 1.0.4 (V8 4.1.0.12): <strong>~760ms</strong></li>
</ul>
<p>Now here is the interesting part, if i change <code>bar.fn</code> to <code>bar.somethingelse</code>:</p>
<ul>
<li>chrome 40.0.2214.93 (V8 3.30.33.15): <strong>~100ms</strong></li>
<li>nodejs 0.10.21 (V8 3.14.5.9): <strong>~100ms</strong></li>
<li>iojs 1.0.4 (V8 4.1.0.12): <strong>~100ms</strong></li>
</ul>
<p>Something went wrong in v8 lately? What causes this?</p> | 28,202,612 | 2 | 8 | null | 2015-01-28 19:52:35.703 UTC | 18 | 2015-02-02 02:14:17.433 UTC | 2015-02-02 02:14:17.433 UTC | null | 1,819,423 | null | 3,968,830 | null | 1 | 50 | javascript|node.js|performance|google-chrome|v8 | 2,194 | <p>First fundamentals.</p>
<p>V8 uses <em>hidden classes</em> connected with <em>transitions</em> to discover static structure in the fluffy shapeless JavaScript objects.</p>
<p>Hidden classes describe the structure of the object, transitions link hidden classes together describing which hidden class should be used if a certain action is performed on an object.</p>
<p>For example the code below would lead to the following chain of hidden classes:</p>
<pre class="lang-js prettyprint-override"><code>var o1 = {};
o1.x = 0;
o1.y = 1;
var o2 = {};
o2.x = 0;
o2.y = 0;
</code></pre>
<p><img src="https://i.stack.imgur.com/Ffr9E.png" alt="enter image description here"></p>
<p>This chain is created as you construct <code>o1</code>. When <code>o2</code> is constructed V8 simply follows established transitions.</p>
<p>Now when a property <code>fn</code> is used to store a function V8 tries to give this property a special treatment: instead of just declaring in the hidden class that object contains a property <code>fn</code> V8 <strong>puts function into the hidden class</strong>. </p>
<pre class="lang-js prettyprint-override"><code>var o = {};
o.fn = function fff() { };
</code></pre>
<p><img src="https://i.stack.imgur.com/YAsEV.png" alt="enter image description here"></p>
<p>Now there is an interesting consequence here: if you store different functions into the field with the same name V8 can no longer simply follow the transitions because the value of the function property does not match expected value:</p>
<pre class="lang-js prettyprint-override"><code>var o1 = {};
o1.fn = function fff() { };
var o2 = {};
o2.fn = function ggg() { };
</code></pre>
<p>When evaluating <code>o2.fn = ...</code> assignment V8 will see that there is a transition labeled <code>fn</code> but it leads to a hidden class that does not suitable: it contains <code>fff</code> in <code>fn</code> property, while we are trying to store <code>ggg</code>. Note: I have given function names only for simplicity - V8 does not internally use their names but their <em>identity</em>.</p>
<p>Because V8 is unable to follow this transition V8 will decide that its decision to promote function to the hidden class was incorrect and wasteful. The picture will change</p>
<p><img src="https://i.stack.imgur.com/f0Yzv.png" alt="enter image description here"> </p>
<p>V8 will create a new hidden class where <code>fn</code> is just a simple property and not a constant function property anymore. It will reroute the transition and also mark old transition target <em>deprecated</em>. Remember that <code>o1</code> is still using it. However next time code touches <code>o1</code> e.g. when a property is loaded from it - runtime will migrate <code>o1</code> off the deprecated hidden class. This is done to reduce polymorphism - we don't want <code>o1</code> and <code>o2</code> to have different hidden classes.</p>
<p>Why is it important to have functions on the hidden classes? Because this gives V8's optimizing compiler information it uses to <em>inline method calls</em>. It can only inline method call if call target is stored on the hidden class itself.</p>
<p>Now lets apply this knowledge to the example above.</p>
<p>Because there is a clash between transitions <code>bar.fn</code> and <code>foo.fn</code> become normal properties - with functions stored directly on those objects and V8 can't inline the call of <code>foo.fn</code> leading to a slower performance.</p>
<p>Could it inline the call before? <strong>Yes</strong>. Here is what changed: in older V8 <em>there was no deprecation mechanism</em> so even after we had a clash and rerouted <code>fn</code> transition, <code>foo</code> was not migrated to the hidden class where <code>fn</code> becomes a normal property. Instead <code>foo</code> still kept the hidden class where <code>fn</code> is a constant function property directly embedded into the hidden class allowing optimizing compiler to inline it.</p>
<p>If you try timing <code>bar.fn</code> on the older node you will see that it is slower:</p>
<pre class="lang-js prettyprint-override"><code>for (var i = 0; i < 100000000; i++) {
bar.fn(); // can't inline here
}
</code></pre>
<p>precisely because it uses hidden class that does not allow optimizing compiler to inline <code>bar.fn</code> call.</p>
<p>Now the last thing to notice here is that this benchmark does not measure the performance of a function call, but rather it measures if optimizing compiler can reduce this loop to an empty loop by inlining the call inside it. </p> |
8,047,217 | How can I use iCloud to synchronize a .zip file between my apps? | <p>Is it possible to upload a <code>.zip</code> file to <code>iCloud</code>, and then have it be synchronized across all of a user's iOS devices?<br>
If so, how would I go about doing this?<br>
If there is any File size limit, then also mention max. file size allowed.</p> | 10,069,242 | 3 | 0 | null | 2011-11-08 07:31:50.177 UTC | 16 | 2015-05-18 11:48:58.45 UTC | 2015-05-18 11:48:58.45 UTC | null | 1,070,692 | null | 605,996 | null | 1 | 6 | iphone|ios|zip|ios5|icloud | 10,189 | <p>This is how I synchronized zip files with iCloud .</p>
<p>Steps:</p>
<p>1) <a href="http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html" rel="noreferrer">http://transoceanic.blogspot.in/2011/07/compressuncompress-files-on.html</a>
. Refer this link to download zip api which is having code for zipping and unzipping folder. </p>
<p>2) Now all you need to play with NSData.</p>
<p>3) "MyDocument.h" file </p>
<pre><code>#import <UIKit/UIKit.h>
@interface MyDocument : UIDocument
@property (strong) NSData *zipDataContent;
@end
</code></pre>
<p>4)</p>
<pre><code>#import "MyDocument.h"
@implementation MyDocument
@synthesize zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
self.zipDataContent = [[NSData alloc] initWithBytes:[contents bytes] length:[contents length]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return self.zipDataContent;
}
@end
</code></pre>
<p>5) Now somewhere in your app you need to zip folder and sync with icloud. </p>
<pre><code>-(BOOL)zipFolder:(NSString *)toCompress zipFilePath:(NSString *)zipFilePath
{
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSArray *subpaths;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
zipFilePath = [documentsDirectory stringByAppendingPathComponent:zipFilePath];
//NSLog(@"%@",zipFilePath);
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
BOOL successCompressing = [za CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
-(IBAction) iCloudSyncing:(id)sender
{
//***** PARSE ZIP FILE : Pictures *****
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if([self zipFolder:@"Pictures" zipFilePath:@"iCloudPictures"])
NSLog(@"Picture Folder is zipped");
ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:@"iCloudPictures.zip"];
mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"iCloudPictures"];
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
// NSLog(@"%@ %@",zipFilePath,data);
mydoc.zipDataContent = data;
[mydoc saveToURL:[mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(@"PictureZip: Synced with icloud");
}
else
NSLog(@"PictureZip: Syncing FAILED with icloud");
}];
}
</code></pre>
<p>6) You can unzip data received from iCloud like this.</p>
<pre><code>- (void)loadData:(NSMetadataQuery *)queryData {
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:@"iCloudPictures"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(@"Pictures : Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFolder = [documentsDirectory stringByAppendingPathComponent:@"Pics.zip"];
[[NSFileManager defaultManager] createFileAtPath:zipFolder contents:file attributes:nil];
//NSLog(@"zipFilePath : %@",zipFolder);
NSString *outputFolder = [documentsDirectory stringByAppendingPathComponent:@"Pictures"];//iCloudPics
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile: zipFolder] ) {
if( [za UnzipFileTo:outputFolder overWrite:YES] != NO ) {
NSLog(@"Pics : unzip successfully");
}
[za UnzipCloseFile];
}
[za release];
NSError *err;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:outputFolder error:&err];
if (files == nil) {
NSLog(@"EMPTY Folder: %@",outputFolder);
}
// Add all sbzs to a list
for (NSString *file in files) {
//if ([file.pathExtension compare:@".jpeg" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSLog(@" Pictures %@",file);
// NSFileManager *fm = [NSFileManager defaultManager];
// NSDictionary *attributes = [fm fileAttributesAtPath:[NSString stringWithFormat:@"%@/%@",documentsDirectory,file] traverseLink:NO];
//
// NSNumber* fileSize = [attributes objectForKey:NSFileSize];
// int e = [fileSize intValue]; //Size in bytes
// NSLog(@"%@__%d",file,e);
}
}
else
{
NSLog(@"Pictures : failed to open from iCloud");
[self hideProcessingView];
}
}];
}
}
}
</code></pre> |
8,176,166 | invalid SHA1 signature file digest | <p>I have been trying to verify the Jar signing:</p>
<pre><code> jarsigner -verify -verbose -certs example.jar
</code></pre>
<p>I got the following problem:</p>
<pre><code>jarsigner: java.lang.SecurityException: invalid SHA1 signature file digest for o
rg/apache/log4j/net/DefaultEvaluator.class
</code></pre>
<p>I got some suggestions about using <code>-digestalg SHA-1</code> but I do not know where I should put this statement!</p>
<p>I hope you can help me to fix the problem.</p> | 8,186,648 | 3 | 0 | null | 2011-11-18 00:07:14.893 UTC | 5 | 2014-03-10 16:43:41.857 UTC | 2011-11-18 00:13:16.417 UTC | null | 634,025 | null | 1,046,657 | null | 1 | 22 | jnlp | 43,016 | <p>Here is the solution:</p>
<pre><code>jarsigner -keystore mykeystore -digestalg SHA1 jarfile alias
</code></pre>
<p>To verify: </p>
<pre><code>jarsigner -verify -verbose -certs jarfile
</code></pre> |
7,812,444 | How do I import an existing Java keystore (.jks) file into a Java installation? | <p>So, I am having trouble with LDAP. I have an integration test case that hopefully will work out, but it is currently running into LDAPS security issues with the SSL handshake.</p>
<p>I am able to connect to the LDAPS with Apache Directory Studio, and it has downloaded the keystore into a file "permanent.jks".</p>
<p>That's ok, but I want my integration test, which resides in Eclipse using a JRE, to be able to connect to the LDAP server using this keystore.</p>
<p>How can I take this keystore and import it into the JRE for its own use?</p> | 7,812,567 | 3 | 0 | null | 2011-10-18 19:17:09.473 UTC | 21 | 2016-03-23 10:18:55.8 UTC | null | null | null | null | 8,026 | null | 1 | 47 | java|keystore|jks | 161,151 | <p>Ok, so here was my process:</p>
<p><code>keytool -list -v -keystore permanent.jks</code> - got me the alias.</p>
<p><code>keytool -export -alias alias_name -file certificate_name -keystore permanent.jks</code> - got me the certificate to import.</p>
<p>Then I could import it with the keytool:</p>
<p><code>keytool -import -alias alias_name -file certificate_name -keystore keystore location</code></p>
<p>As @Christian Bongiorno says the alias can't already exist in your keystore.</p> |
12,027,092 | Detecting HTML5 video play/pause state with jQuery | <p>I'm building a jQuery slideshow which will feature an HTML5 video player on one of the slides. Is there any way to get the jQuery slideshow to pause from its otherwise automatically running state, when it detects that the video is playing, besides a "slideshow play/pause" button?</p> | 12,027,475 | 2 | 0 | null | 2012-08-19 14:05:06.617 UTC | 4 | 2013-01-31 09:18:22.993 UTC | null | null | null | null | 1,033,027 | null | 1 | 12 | jquery|html|video|html5-video|detect | 39,723 | <p>You can check if the video is paused used the <code>paused</code> property:</p>
<pre><code>$("#videoID").get(0).paused;
</code></pre>
<p>You can pause a video using the <code>pause()</code> method:</p>
<pre><code>$("#videoID").get(0).pause();
</code></pre>
<p>You can then resume the playback of the video using the <code>play()</code> method:</p>
<pre><code>$("#videoID").get(0).play();
</code></pre> |
11,577,522 | Call a url in javascript on click | <p>I have a javascript function. On-click will call this. Using <code>document.getElementById</code> I am getting certain parameters there. Using that parameters I need to build a url. ie, onclick will have to execute that url.</p>
<p>For example, in javascript,</p>
<pre><code>function remove()
{
var name=...;
var age = ...;
// url should be like http://something.jsp?name=name&age=age
}
</code></pre>
<p>In short I need to execute <code>http://something.jsp?name=name&age=age</code> this url on click </p>
<pre><code><input type="button" name="button" onclick="remove();" />
</code></pre> | 11,577,563 | 3 | 0 | null | 2012-07-20 10:28:31.573 UTC | 2 | 2017-12-05 10:46:56.847 UTC | 2017-12-05 10:46:56.847 UTC | null | 8,046,353 | null | 930,544 | null | 1 | 14 | javascript|jsp|url | 107,084 | <p>Use <a href="https://developer.mozilla.org/en/DOM/window.location" rel="noreferrer"><code>window.location</code></a>:</p>
<pre><code>function remove()
{
var name = ...;
var age = ...;
window.location = 'http://something.jsp?name=' + name + '&age=' + age;
}
</code></pre> |
11,803,496 | Dump sql file to ClearDB in Heroku | <p>I have a sql file that I want to be dumped into a MySQL database that I have in Heroku using the ClearDB addon. When dumping in local I do the following:</p>
<pre><code>mysql -u my_user -p mydatabasename < my_dump_file.sql
</code></pre>
<p>However, I don't have any clue on how to dump it to the Heroku MySQL database. All I know is this address:</p>
<pre><code>mysql://b5xxxxx7:[email protected]/heroku_xxxxxx?reconnect=true
</code></pre>
<p>But if I try to do:</p>
<pre><code>mysql://b5xxxxx7:[email protected]/heroku_xxxxxx?reconnect=true < my_dump_file.sql
</code></pre>
<p>I get <code>No such file or directory</code>.</p>
<p>How am I supposed to do it?</p> | 11,803,685 | 4 | 2 | null | 2012-08-03 21:24:02.503 UTC | 17 | 2020-12-13 07:38:54.61 UTC | 2014-03-03 22:22:35.047 UTC | null | 634,513 | null | 1,196,150 | null | 1 | 17 | mysql|ruby-on-rails|ruby|heroku | 15,227 | <p>You might be able to do something like this</p>
<pre><code>mysql --host=us-cdbr-east.cleardb.com --user=b5xxxxx7 --password=37d8faad --reconnect heroku_xxxxxx < my_dump_file.sql
</code></pre> |
11,880,917 | How can I add click-to-play to my HTML5 videos without interfering with native controls? | <p>I'm using the following code to add click-to-play functionality to HTML5 video:</p>
<pre><code>$('video').click(function() {
if ($(this).get(0).paused) {
$(this).get(0).play();
}
else {
$(this).get(0).pause();
}
});
</code></pre>
<p>It works okay except that it interferes with the browser's native controls: that is, it captures when a user clicks on the pause/play button, immediately reversing their selection and rendering the pause/play button ineffective.</p>
<p>Is there a way to select <em>just</em> the video part in the DOM, or failing that, a way to capture clicks to the <em>controls</em> part of the video container, so that I can ignore/reverse the click-to-play functionality when a user presses the pause/play button?</p> | 11,891,812 | 5 | 0 | null | 2012-08-09 09:59:49.183 UTC | 2 | 2014-10-03 06:33:32.983 UTC | null | null | null | user113292 | null | null | 1 | 19 | javascript|html5-video | 40,757 | <p>You could add a layer on top of the video that catches the click event. Then hide that layer while the video is playing.</p>
<p>The (simplified) markup:</p>
<pre class="lang-html prettyprint-override"><code><div id="container">
<div id="videocover">&nbsp;</div>
<video id="myvideo" />
</div>
</code></pre>
<p>The script:</p>
<pre class="lang-js prettyprint-override"><code>$("#videocover").click(function() {
var video = $("#myvideo").get(0);
video.play();
$(this).css("visibility", "hidden");
return false;
});
$("#myvideo").bind("pause ended", function() {
$("#videocover").css("visibility", "visible");
});
</code></pre>
<p>The CSS:</p>
<pre class="lang-css prettyprint-override"><code>#container {
position: relative;
}
/*
covers the whole container
the video itself will actually stretch
the container to the desired size
*/
#videocover {
position: absolute;
z-index: 1;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</code></pre> |
11,894,765 | Unable log in to the django admin page with a valid username and password | <p>I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages</p>
<p>This question is in the <a href="https://docs.djangoproject.com/en/dev/faq/admin/#i-can-t-log-in-when-i-enter-a-valid-username-and-password-it-just-brings-up-the-login-page-again-with-no-error-messages" rel="noreferrer">django FAQ</a>, but I've gone over the answers there and still can't get past the initial login screen.</p>
<p>I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.</p>
<p>I've confirmed that I'm registering the admin in the <code>admin.py</code> file, made sure to syncdb after adding <code>INSTALLED_APPS</code>.
When I enter the wrong password I <em>DO</em> get an error, so my admin user is being authenticated, just not proceeding to the admin page.</p>
<p>I've tried both setting <code>SESSION_COOKIE_DOMAIN</code> to the machine's IP and None. (Confirmed that the cookie domain shows as the machine's IP in chrome)</p>
<p>Also, checked that the user authenticates via the shell:</p>
<pre><code>>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True
</code></pre>
<p>Attempted login using IE8 and chrome canary, both results in the same return to the login screen.</p>
<p>Is there something else I'm missing????</p>
<p><strong>settings.py</strong></p>
<pre><code>...
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django.contrib.gis',
'myapp.main',
)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from django.conf.urls.defaults import * #@UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^bin/', include('myproject.main.urls')),
(r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
(r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
(r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
(r'^layers/$', "myproject.layer.views.get_layer_definitions"),
(r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
(r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
(r'^$', "myproject.layer.views.view_map"),
)
urlpatterns += staticfiles_urlpatterns()
</code></pre>
<p>Apache Version:</p>
<pre><code>Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured
</code></pre>
<p>Apache apache2/sites-available/default:</p>
<pre><code><VirtualHost *:80>
ServerAdmin ironman@localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
WSGIProcessGroup lbs
WSGIScriptAlias / /var/www/bin/apache/django.wsgi
Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
ServerAdmin ironman@localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
WSGIProcessGroup tilestache
WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>
</code></pre>
<p><strong>UPDATE</strong></p>
<p>The admin page does proceed when using the development server via <code>runserver</code> so it seems like a wsgi/apache issue. Still haven't figured it out yet.</p>
<p><strong>SOLUTION</strong></p>
<p>The problem was that I had the settings file <code>SESSION_ENGINE</code> value set to <code>'django.contrib.sessions.backends.cache'</code> <em>without</em> having the <code>CACHE_BACKEND</code> properly configured. </p>
<p>I've changed the SESSION_ENGINE to <code>'django.contrib.sessions.backends.db'</code> which resolved the issue.</p> | 12,110,570 | 23 | 17 | null | 2012-08-10 02:45:15.5 UTC | 18 | 2022-01-13 11:57:58.46 UTC | 2012-08-29 01:39:21.293 UTC | null | 24,718 | null | 24,718 | null | 1 | 72 | python|django|authentication|admin|mod-wsgi | 64,946 | <p>Steps to debug:</p>
<ul>
<li>Make sure that your Database is synced
<ul>
<li>Double check that you have a django_session table</li>
</ul></li>
<li>Try to authenticate
<ul>
<li>Do you see a record being created in the <code>django_session</code> table?</li>
</ul></li>
</ul>
<p>IF NOT</p>
<ul>
<li>remove non-standard settings
<ul>
<li>AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)</li>
<li>SESSION_EXPIRE_AT_BROWSER_CLOSE = True</li>
<li>SESSION_SAVE_EVERY_REQUEST = True</li>
<li>SESSION_COOKIE_AGE = 86400 # sec</li>
<li>SESSION_COOKIE_DOMAIN = None</li>
<li>SESSION_COOKIE_NAME = 'DSESSIONID'</li>
<li>SESSION_COOKIE_SECURE = False</li>
</ul></li>
<li>Make sure that your Database is synced
<ul>
<li>Double check that you have a <code>django_session</code> table</li>
</ul></li>
<li>Try to authenticate
<ul>
<li>Do you see a record being created in the <code>django_session</code> table?</li>
</ul></li>
</ul>
<p>Let me know if this turns up any useful debug.</p>
<p>Sample settings file: <a href="https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py" rel="noreferrer">https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py</a></p> |
3,780,870 | Using 'AsParallel()' / 'Parallel.ForEach()' guidelines? | <p>Looking for a little advice on leveraging <code>AsParallel()</code> or <code>Parallel.ForEach()</code> to speed this up.</p>
<p>See the method I've got (simplified/bastardized for this example) below.</p>
<p>It takes a list like "US, FR, APAC", where "APAC" is an alias for maybe 50 other "US, FR, JP, IT, GB" etc. countires. The method should take "US, FR, APAC", and convert it to a list of "US", "FR", plus all the countries that are in "APAC".</p>
<pre><code>private IEnumerable<string> Countries (string[] countriesAndAliases)
{
var countries = new List<string>();
foreach (var countryOrAlias in countriesAndAliases)
{
if (IsCountryNotAlias(countryOrAlias))
{
countries.Add(countryOrAlias);
}
else
{
foreach (var aliasCountry in AliasCountryLists[countryOrAlias])
{
countries.Add(aliasCountry);
}
}
}
return countries.Distinct();
}
</code></pre>
<p>Is making this parallelized as simple as changing it to what's below? Is there more nuance to using <code>AsParallel()</code> than this? Should I be using <code>Parallel.ForEach()</code> instead of <code>foreach</code>? What rules of thumb should I use when parallelizing <code>foreach</code> loops?</p>
<pre><code>private IEnumerable<string> Countries (string[] countriesAndAliases)
{
var countries = new List<string>();
foreach (var countryOrAlias in countriesAndAliases.AsParallel())
{
if (IsCountryNotAlias(countryOrAlias))
{
countries.Add(countryOrAlias);
}
else
{
foreach (var aliasCountry in AliasCountryLists[countryOrAlias].AsParallel())
{
countries.Add(aliasCountry);
}
}
}
return countries.Distinct();
}
</code></pre> | 3,780,946 | 4 | 1 | null | 2010-09-23 17:15:54.247 UTC | 13 | 2019-10-01 21:30:40.653 UTC | 2019-10-01 21:30:40.653 UTC | null | 3,258,851 | null | 454,541 | null | 1 | 48 | c#|.net|multithreading|parallel-processing | 51,210 | <p>Several points.</p>
<p>writing just <code>countriesAndAliases.AsParallel()</code> is useless. <code>AsParallel()</code> makes part of Linq query that comes after it execute in parallel. Part is empty, so no use at all.</p>
<p>generally you should repace <code>foreach</code> with <code>Parallel.ForEach()</code>. But beware of not thread safe code! You have it. You can't just wrap it into <code>foreach</code> because <code>List<T>.Add</code> is not thread safe itself.</p>
<p>so you should do like this (sorry, i didn't test, but it compiles):</p>
<pre><code> return countriesAndAliases
.AsParallel()
.SelectMany(s =>
IsCountryNotAlias(s)
? Enumerable.Repeat(s,1)
: AliasCountryLists[s]
).Distinct();
</code></pre>
<p><strong>Edit</strong>:</p>
<p>You must be sure about two more things:</p>
<ol>
<li><code>IsCountryNotAlias</code> must be thread safe. It would be even better if it is <a href="http://en.wikipedia.org/wiki/Pure_function" rel="noreferrer">pure function</a>.</li>
<li>No one will modify <code>AliasCountryLists</code> in a meanwhile, because dictionaries are not thread safe. Or use <a href="http://msdn.microsoft.com/en-us/library/dd287191.aspx" rel="noreferrer">ConcurrentDictionary</a> to be sure.</li>
</ol>
<p>Useful links that will help you:</p>
<p><a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en" rel="noreferrer">Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4</a></p>
<p><a href="http://download.microsoft.com/download/B/C/F/BCFD4868-1354-45E3-B71B-B851CD78733D/ParallelProgramsinNET4_CodingGuidelines.pdf" rel="noreferrer">Parallel Programming in .NET 4 Coding Guidelines</a></p>
<p><a href="http://download.microsoft.com/download/B/C/F/BCFD4868-1354-45E3-B71B-B851CD78733D/WhenToUseParallelForEachOrPLINQ.pdf" rel="noreferrer">When Should I Use Parallel.ForEach? When Should I Use PLINQ?</a></p>
<p><strong>PS</strong>: As you see new parallel features are not as obvious as they look (and feel).</p> |
3,839,809 | Detect iPhone/iPad purely by css | <p>I've been trying to detect an iPhone or iPad purely by stylesheet. I tried the solution provided <a href="http://iphone.wikidot.com/detection" rel="noreferrer">here</a> by using @media handheld, only screen and (max-device-width: 480px) {.</p>
<p>However, this doesnt seem to work. Any ideas?</p> | 3,839,892 | 5 | 1 | null | 2010-10-01 13:53:32.52 UTC | 39 | 2017-01-08 07:04:32.057 UTC | null | null | null | null | 188,363 | null | 1 | 47 | iphone|css|ipad | 106,383 | <p>This is how I handle iPhone (and similar) devices [not iPad]:</p>
<p>In my CSS file:</p>
<pre><code>@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
</code></pre>
<p>In the head of my HTML document:</p>
<pre><code><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
</code></pre> |
3,989,352 | What advantages does PHP have over ASP.NET? | <p>I have opened a large web project on elance for a social network. I got over 30 bids on my project and many of the providers recommended php even though they had .net knowledge. many have said that php with drupal has many advanteges over the .NET framework but did not say what they were. Its hard to believe that a scripting language has advantages over a compiled language. Am I missing something here.</p> | 3,989,422 | 6 | 2 | null | 2010-10-21 15:51:16.737 UTC | 5 | 2010-10-21 16:25:35.2 UTC | null | null | null | null | 184,773 | null | 1 | 26 | php|asp.net | 43,323 | <p>PHP will run on essentially any server, for free. That's a fairly compelling feature for many folks.</p>
<p>There are lots of pros and cons of both, and it certainly doesn't boil down to scripting vs. compiled (incidentally, opcode caches like APC and things like Facebook's HipHop even the score on that point).</p>
<p>I'd say if someone's recommending PHP over ASP.NET, they code primarily in PHP. If they're recommending ASP.NET over PHP, they code primarily in ASP.NET. There's probably not much more to it than that in the responses you're getting.</p> |
3,671,666 | Sharing a complex object between processes? | <p>I have a fairly complex Python object that I need to share between multiple processes. I launch these processes using <code>multiprocessing.Process</code>. When I share an object with <code>multiprocessing.Queue</code> and <code>multiprocessing.Pipe</code> in it, they are shared just fine. But when I try to share an object with other non-multiprocessing-module objects, it seems like Python forks these objects. Is that true?</p>
<p>I tried using multiprocessing.Value. But I'm not sure what the type should be? My object class is called MyClass. But when I try <code>multiprocess.Value(MyClass, instance)</code>, it fails with:</p>
<p><code>TypeError: this type has no size</code></p>
<p>Any idea what's going on?</p> | 3,697,322 | 6 | 1 | null | 2010-09-08 20:36:37.423 UTC | 31 | 2022-01-20 19:06:52.12 UTC | 2020-12-27 12:35:26.297 UTC | null | 355,230 | null | 413,065 | null | 1 | 64 | python|process|multiprocessing|sharing | 106,843 | <p>You can do this using Python's <code>multiprocessing</code> "<a href="https://docs.python.org/3/library/multiprocessing.html#managers" rel="noreferrer">Manager</a>" classes and a proxy class that you define. See <a href="http://docs.python.org/library/multiprocessing.html#proxy-objects" rel="noreferrer">Proxy Objects</a> in the Python docs.</p>
<p>What you want to do is define a proxy class for your custom object, and then share the object using a "Remote Manager" -- look at the examples in the same linked doc page in the "<a href="https://docs.python.org/3/library/multiprocessing.html#using-a-remote-manager" rel="noreferrer">Using a remote manager</a>" section where the docs show how to share a remote queue. You're going to be doing the same thing, but your call to <code>your_manager_instance.register()</code> will include your custom proxy class in its argument list.</p>
<p>In this manner, you're setting up a server to share the custom object with a custom proxy. Your clients need access to the server (again, see the excellent documentation examples of how to setup client/server access to a remote queue, but instead of sharing a <code>Queue</code>, you are sharing access to your specific class).</p> |
3,446,216 | What is the difference between single-quoted and double-quoted strings in PHP? | <p>I'm a little confused why I see some code in PHP with string placed in single quotes and sometimes in double quotes.</p>
<p>I just know in .NET, or the C language, if it is in a single quote, that means it is a character, not a string.</p> | 3,446,286 | 7 | 0 | null | 2010-08-10 05:12:56.133 UTC | 305 | 2022-03-10 06:31:42.007 UTC | 2019-09-02 13:57:58.653 UTC | null | 6,622,577 | null | 379,800 | null | 1 | 897 | php|string|syntax | 443,657 | <p><a href="https://php.net/manual/en/language.types.string.php" rel="noreferrer"><strong>PHP strings</strong></a> can be specified not just in <em>two</em> ways, but in <strong>four</strong> ways.</p>
<ol>
<li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single" rel="noreferrer"><strong>Single quoted strings</strong></a> will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash <code>\'</code>, and to display a back slash, you can escape it with another backslash <code>\\</code> (<strong>So yes, even single quoted strings are parsed</strong>).</li>
<li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double" rel="noreferrer"><strong>Double quote strings</strong></a> will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that <strong>you can use curly braces to isolate the name of the variable you want evaluated</strong>. For example let's say you have the variable <code>$type</code> and you want to <code>echo "The $types are"</code>. That will look for the variable <code>$types</code>. To get around this use <code>echo "The {$type}s are"</code> You can put the left brace before or after the dollar sign. Take a look at <a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing" rel="noreferrer">string parsing</a> to see how to use array variables and such.</li>
<li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc" rel="noreferrer"><strong>Heredoc</strong></a> string syntax works like double quoted strings. It starts with <code><<<</code>. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax. </li>
<li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc" rel="noreferrer"><strong>Nowdoc</strong></a> (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <code><<<</code> sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <code><<<'EOT'</code>. <strong>No parsing is done in nowdoc.</strong></li>
</ol>
<p><strong>Notes:</strong>
Single quotes inside of single quotes and double quotes inside of double quotes must be escaped:</p>
<pre><code>$string = 'He said "What\'s up?"';
$string = "He said \"What's up?\"";
</code></pre>
<p><strong>Speed:</strong><br>
I would not put too much weight on single quotes being faster than double quotes. They probably are faster in certain situations. Here's an article <a href="https://web.archive.org/web/20170703004051/https://www.phplens.com/lens/php-book/optimizing-debugging-php.php" rel="noreferrer">explaining one manner in which single and double quotes are essentially equally fast since PHP 4.3</a> (<code>Useless Optimizations</code> toward the bottom, section <code>C</code>). Also, this <a href="https://www.phpbench.com/" rel="noreferrer"><strong>benchmarks page</strong></a> has a single vs double quote comparison. Most of the comparisons are the same. There is one comparison where double quotes are slower than single quotes.</p> |
3,716,153 | How to remove returnurl from url? | <p>I want to remove "returnurl=/blabla" from address bar when a user want to access to a login required page. Because I'm trying to redirect the user to a static page after login to do some selections.</p>
<p>How can I do that?</p> | 3,716,672 | 11 | 0 | null | 2010-09-15 09:03:20.217 UTC | 11 | 2022-01-02 01:25:31.06 UTC | 2010-09-15 22:18:24.453 UTC | null | 321,946 | null | 4,215 | null | 1 | 39 | asp.net|asp.net-mvc|forms-authentication | 67,678 | <p>This is the nature of <strong>Forms Authentication</strong>. (which im guessing you're using).</p>
<p>That is, when you access a page which requires authentication, ASP.NET will redirect you to the login page, passing in the ReturnUrl as a parameter so you can be returned to the page you came from post-login.</p>
<p>To remove this functionality would break the semantics and design of Forms Authentication itself. (IMO)</p>
<p>My suggestion - if you dont need it, <strong>dont use it</strong>.</p>
<blockquote>
<p>I'm trying to redirect the user to a
static page after login to do some
selections.</p>
</blockquote>
<p>Piece of cake - after you've done your login, instead of doing <strong>FormsAuthentication.RedirectFromLoginPage</strong> (which uses that very ReturnUrl QueryString parameter), just use <strong>FormsAuthentication.SetAuthCookie</strong> and redirect wherever you want.</p> |
3,623,263 | Reverse iteration with an unsigned loop variable | <p>I've been discussing the use of size_t with colleagues. One issue that has come up is loops that decrement the loop variable until it reaches zero.</p>
<p>Consider the following code:</p>
<pre><code>for (size_t i = n-1; i >= 0; --i) { ... }
</code></pre>
<p>This causes an infinite loop due to unsigned integer wrap-around. What do you do in this case? It seems far to easy to write the above code and not realise that you've made a mistake.</p>
<p>Two suggestions from our team are to use one of the following styles:</p>
<pre><code>for (size_t i = n-1; i != -1 ; --i) { ... }
for (size_t i = n; i-- > 0 ; ) { ... }
</code></pre>
<p>But I do wonder what other options there are...</p> | 3,626,468 | 11 | 5 | null | 2010-09-02 01:37:14.407 UTC | 28 | 2020-10-31 16:38:29.307 UTC | 2020-10-31 14:19:30.177 UTC | null | 8,372,853 | null | 43,066 | null | 1 | 72 | c++|for-loop | 16,939 | <p>Personally I have come to like:</p>
<pre><code>for (size_t i = n; i --> 0 ;)
</code></pre>
<p>It has a) no funny <code>-1</code>, b) the condition check is mnemonic, c) it ends with a suitable smiley.</p> |
3,489,071 | In Python, when to use a Dictionary, List or Set? | <p>When should I use a dictionary, list or set?</p>
<p>Are there scenarios that are more suited for each data type?</p> | 3,489,100 | 13 | 0 | null | 2010-08-15 20:22:32.663 UTC | 176 | 2022-03-02 08:01:05.663 UTC | 2019-07-01 23:44:38.66 UTC | null | 42,223 | null | 39,677 | null | 1 | 334 | python|list|dictionary|data-structures|set | 212,017 | <p>A <code>list</code> keeps order, <code>dict</code> and <code>set</code> don't: when you care about order, therefore, you must use <code>list</code> (if your choice of containers is limited to these three, of course ;-) ).</p>
<p><code>dict</code> associates each key with a value, while <code>list</code> and <code>set</code> just contain values: very different use cases, obviously.</p>
<p><code>set</code> requires items to be hashable, <code>list</code> doesn't: if you have non-hashable items, therefore, you cannot use <code>set</code> and must instead use <code>list</code>.</p>
<p><code>set</code> forbids duplicates, <code>list</code> does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in <code>collections.Counter</code> -- you could build one as a <code>dict</code>, if for some weird reason you couldn't import <code>collections</code>, or, in pre-2.7 Python as a <code>collections.defaultdict(int)</code>, using the items as keys and the associated value as the count).</p>
<p>Checking for membership of a value in a <code>set</code> (or <code>dict</code>, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, <code>set</code> is better than <code>list</code>.</p> |
8,292,103 | Java Multi Threading - real world use cases | <p>I want to work on multi-threading, but my current project do not have such opportunities.Can someone please guide me where should I start.I need real time scenarios so that I can directly jump onto coding. I am reading side by side as well.</p>
<p>Can you please refer some websites for practicing.</p> | 8,292,517 | 6 | 4 | null | 2011-11-28 06:12:09.4 UTC | 14 | 2017-12-05 06:39:16.887 UTC | 2011-11-28 12:07:51.423 UTC | null | 432,886 | null | 432,886 | null | 1 | 17 | java|multithreading | 26,815 | <p>Google can transfer you to practicing tutorial websites (much better than I can). A nice real time scenario could include any of the following (may seem academic, but the skills are absolutely transferable to practice):</p>
<ol>
<li>Dining philosopher's problem.</li>
<li>Reader/Writer problem.</li>
<li>Consumer/Producer problem.</li>
</ol>
<p>Some more specific ones:</p>
<ol>
<li>Concurrent alpha-beta search (this is seriously tricky).</li>
<li>Any genetic algorithm can be implemented concurrently and since memory/storage are shared amongst threads, it can be quite challenging if done right (try the semi-transparent polygon drawing an image project. You can search google for that).</li>
<li>Concurrent database-access can be rather interesting. Sketch a scenario for yourself.</li>
<li>Have a look at <a href="http://projecteuler.net/" rel="noreferrer">http://projecteuler.net/</a> which includes a bunch of interesting problems. Many of the problems there can be implemented using threads.</li>
</ol>
<p>Enjoy. </p> |
7,889,765 | Remove all HTMLtags in a string (with the jquery text() function) | <p>is it possible to use the jquery text() function to remove all HTML in a string?</p>
<p><strong>String with HTML tags:</strong><br /><code>myContent = '<div id="test">Hello <span>world!</span></div>';</code></p>
<p><br />
<strong>The result must be:</strong><br /> <code>Hello world!</code></p> | 7,889,791 | 6 | 2 | null | 2011-10-25 13:11:06.23 UTC | 5 | 2019-06-28 13:57:44.743 UTC | null | null | null | null | 2,136,202 | null | 1 | 38 | jquery|string|text | 118,946 | <pre><code>var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
</code></pre>
<p>That results in hello world. Does that answer your question?</p>
<p><a href="http://jsfiddle.net/D2tEf/" rel="noreferrer">http://jsfiddle.net/D2tEf/</a> for an example</p> |
4,106,369 | How do I find the size of a 2D array? | <p>If I declare this array...</p>
<pre><code>string[,] a = {
{"0", "1", "2"},
{"0", "1", "2"},
{"0", "1", "2"},
{"0", "1", "2"},
};
</code></pre>
<p>Then I can measure the length with</p>
<pre><code>a.Length
</code></pre>
<p>which is 12. How do I measure the dimension of the arrays within? If I try...</p>
<pre><code>a[0].Length
</code></pre>
<p>I get <code>Wrong number of indices inside []; expected 2</code>. What gives?</p> | 4,106,425 | 3 | 4 | null | 2010-11-05 13:43:55.137 UTC | 10 | 2015-12-15 07:59:00.06 UTC | 2015-12-15 07:59:00.06 UTC | null | 3,970,411 | null | 974 | null | 1 | 88 | c#|.net|arrays|multidimensional-array | 88,437 | <p>You want the GetLength() method of your array:</p>
<pre><code>a.GetLength(0);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx">http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx</a></p> |
4,660,200 | How do I get the text from UITextField into an NSString? | <p>I've tried various methods, which all give me warnings. Such as <code>userName = [NSString stringWithFormat:@"%@", [yournamefield stringValue]];</code> which just gives me a warning of</p>
<blockquote>
<p>'UITextField' may not respond to '-stringValue'</p>
</blockquote>
<p>How do i do this?</p> | 4,660,232 | 4 | 2 | null | 2011-01-11 16:54:00.46 UTC | 3 | 2015-03-10 19:14:28.727 UTC | 2011-02-08 00:24:52.337 UTC | null | 106,435 | null | 561,395 | null | 1 | 16 | iphone|objective-c|cocoa-touch|nsstring|uitextfield | 49,361 | <p>Get the text inside the text field using the <code>text</code> property</p>
<pre><code>NSString *name = yourNameField.text;
</code></pre> |
4,206,363 | the functions (procedures) in MIPS | <p>I'm new in MIPS language and I don't understand how the functions (procedures) in the MIPS assembly language work. Here are but I will specify my problem :</p>
<ol>
<li><p>What does:</p>
<ul>
<li><code>jal</code></li>
<li><code>jr</code></li>
<li><code>$ra</code></li>
</ul>
<p>mean in mips language and the important thing</p></li>
<li>How can we use them when we want to create a function or (procedure)?</li>
</ol> | 4,214,232 | 4 | 1 | null | 2010-11-17 16:01:27.037 UTC | 8 | 2021-03-27 11:40:27.563 UTC | 2014-05-25 23:34:39.74 UTC | null | 2,456,263 | null | 510,976 | null | 1 | 19 | function|mips|procedure | 79,087 | <p>Firstly, you might want to check <a href="http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm" rel="noreferrer">this</a> quick MIPS reference. It really helped me. </p>
<p>Secondly, to explain <code>jal</code>, <code>jr</code> and <code>$ra</code>. What <code>jal <label></code> does is jump to the <code>label</code> label and store the <em>program counter</em> (think of it as the address of the current instruction) in the <code>$ra</code> register. Now, when you want to return from <code>label</code> to where you initially were, you just use <code>jr $ra</code>. </p>
<p>Here's an example:</p>
<pre><code>.text
main:
li $t0, 1
jal procedure # call procedure
li $v0, 10
syscall
procedure:
li $t0, 3
jr $ra # return
</code></pre>
<p>You will notice when running this in a SPIM emulator that the value left in <code>$t0</code> is 3, the one loaded in the so-called <em>procedure</em>.</p>
<p>Hope this helps.</p> |
4,719,346 | Redis master/slave replication - single point of failure? | <p>How does one upgrade to a newer version of Redis with zero downtime? Redis slaves are read-only, so it seems like you'd have to take down the master and your site would be read-only for 45 seconds or more while you waited for it to reload the DB.</p>
<p>Is there a way around this?</p> | 4,721,782 | 4 | 2 | null | 2011-01-18 00:20:29.557 UTC | 17 | 2014-04-25 10:04:03.96 UTC | 2011-01-18 00:48:06.343 UTC | null | 216,728 | null | 216,728 | null | 1 | 40 | redis|high-availability | 36,848 | <p>When taking the node offline, promote the slave to master using the SLAVEOF command, then when you bring it back online you set it up as a slave and it will copy all data from the online node.</p>
<p>You may also need to make sure your client can handle changed/missing master nodes appropriately.</p>
<p>If you want to get really fancy, you can set up your client to promote a slave if it detects an error writing to the master.</p> |
4,571,346 | How to encode URL to avoid special characters in Java? | <p>i need java code to encode URL to avoid special characters such as spaces and % and & ...etc</p> | 4,571,518 | 5 | 2 | null | 2010-12-31 17:12:34.487 UTC | 17 | 2018-01-27 10:13:41.63 UTC | 2018-01-27 10:13:41.63 UTC | null | 472,495 | null | 508,377 | null | 1 | 40 | java|url-encoding | 143,457 | <p>URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc2396" rel="nofollow noreferrer">RFC 2396</a> explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).</p>
<p>In Java, the correct way to build a URL is with the <a href="http://download.oracle.com/javase/6/docs/api/java/net/URI.html" rel="nofollow noreferrer"><code>URI</code></a> class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The <code>toASCIIString()</code> method gives you a properly-escaped and encoded string that you can send to a server. To <em>decode</em> a URL, construct a <code>URI</code> object using the single-string constructor and then use the accessor methods (such as <code>getPath()</code>) to retrieve the decoded components.</p>
<p>Don't use the <code>URLEncoder</code> class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's <em>not</em> correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a <code>URLEncoder</code>. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).</p> |
4,506,249 | How can I make Emacs Org-mode open links to sites in Google Chrome? | <p>Google Chrome is set as the default browser. However, it opens links in Firefox, which is undesired.</p>
<p>How can I make <a href="https://en.wikipedia.org/wiki/Org-mode" rel="nofollow noreferrer">Org-mode</a> to open links in Google Chrome?</p> | 4,506,458 | 7 | 0 | null | 2010-12-22 04:50:17.003 UTC | 16 | 2020-12-15 15:53:06.63 UTC | 2020-12-15 15:24:58.103 UTC | null | 63,550 | null | 397,649 | null | 1 | 46 | browser|emacs|google-chrome|org-mode | 19,355 | <p>Emacs 23.2 doesn't directly support Google Chrome, but it does support a "generic" browser, and something like this should work:</p>
<pre><code>(setq browse-url-browser-function 'browse-url-generic
browse-url-generic-program "chromium-browser")
</code></pre>
<p>You don't mention your OS, but if it's Windows or Mac, you can try:</p>
<pre><code>(setq browse-url-browser-function 'browse-url-default-windows-browser)
(setq browse-url-browser-function 'browse-url-default-macosx-browser)
</code></pre>
<p>And, if that doesn't work, there are other folks who have implemented <code>'browse-url-chrome</code>. Google turned up the following link:</p>
<ul>
<li><a href="http://code.ohloh.net/search?s=browse-url-chrome&browser=Default" rel="nofollow noreferrer">http://code.ohloh.net/search?s=browse-url-chrome&browser=Default</a></li>
</ul> |
4,212,149 | Init function in javascript and how it works | <p>I often see the following code:</p>
<pre><code>(function () {
// init part
})();
</code></pre>
<p>but I never could get my head around how it works. I find the last brackets especially confusing.
Could someone explain how it works in terms of Execution Contexts (EC) and Variable Objects (VO)?</p> | 4,212,281 | 7 | 2 | null | 2010-11-18 06:17:24.003 UTC | 35 | 2020-04-07 09:04:23.437 UTC | 2015-10-01 14:17:42.6 UTC | null | 1,766,230 | null | 244,569 | null | 1 | 57 | javascript | 132,137 | <p>That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a <a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">closure</a>.</p>
<p>Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to. </p>
<p>A demonstration:</p>
<pre><code>var x = 1; // global VO
(function(){
var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO
</code></pre>
<p>The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).</p> |
4,326,017 | Implementing Generic Interface in Java | <p>I have a Java generics question I was hoping someone could answer. Consider the following code:</p>
<pre><code>public interface Event{}
public class AddressChanged implements Event{}
public class AddressDiscarded implements Event{}
public interface Handles<T extends Event>{
public void handle(T event);
}
</code></pre>
<p>I want to implement this Handles interface like this: </p>
<pre><code>public class AddressHandler implements Handles<AddressChanged>, Handles<AddressDiscarded>{
public void handle(AddressChanged e){}
public void handle(AddressDiscarded e){}
}
</code></pre>
<p>But java doesn't allow implementing Handles twice using the Generic. I was able to accomplish this with C#, but cannot figure a workaround in java without using Reflection or instanceof and casting.</p>
<p>Is there a way in java to implement the Handles interface using both generic interfaces? Or perhaps another way to write the Handles interface so the end result can be accomplished?</p> | 4,326,066 | 8 | 0 | null | 2010-12-01 15:36:48.13 UTC | 9 | 2021-07-14 19:56:26.353 UTC | 2012-07-06 08:56:32.11 UTC | null | 322,283 | null | 425,319 | null | 1 | 30 | java|generics|cqrs | 44,754 | <p>You can't do that in Java. You can only implement one concrete realization of the same generic interface. I would do this instead:</p>
<pre><code>public class AddressHandler implements Handles<Event>{
public void handle(Event e){
if(e instanceof AddressDiscarded){
handleDiscarded(e);
} else if(e instanceof AddressChanged){
handleChanged(e);
}
}
public void handleDiscarded(AddressDiscarded e){}
public void handleChanged(AddressChanged e){}
}
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.