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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,690,814 | How to increment an object property value if it exists, else set the initial value? | <p>How might I add check to see if a key already exists, and if does, increment the value, and if it doesn't exist, then set the initial value?</p>
<p>Something like this pseudo-code:</p>
<pre><code>var dict = {};
var new_item = "Bill"
If new_item not in dict:
dict[new_item] = 1
else:
dict[new_item] += 1
</code></pre> | 18,690,820 | 7 | 4 | null | 2013-09-09 02:41:29.29 UTC | 15 | 2022-03-27 06:55:40.94 UTC | 2019-09-25 07:24:42.497 UTC | null | 875,915 | null | 1,813,867 | null | 1 | 46 | javascript | 25,174 | <pre><code>dict[key] = (dict[key] || 0) + 1;
</code></pre> |
18,686,469 | Sharing audio file | <p>I'm trying to make a button for sharing an audio file. This is not working. First I tried to send the file right from my raw folder without copying it to the card of the phone. That didn't solve my problem. The second thing I tried, is saving the file to the phone and then share it. The part that saves the file to the phone works now, but when I try to share the audio file to another device all the compatible apps crash (Whatsapp, Gmail, etc).</p>
<p>This is my code:</p>
<pre><code> String sharePath = Environment.getExternalStorageDirectory().getPath()
+ "/Soundboard/Ringtones/custom_ringtone.ogg";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, sharePath);
startActivity(Intent.createChooser(share, "Share Sound File"));
</code></pre>
<p>By the way, the audio file is a .ogg file. I hope that those apps work with that type of files. If not I should convert it to .mp3. </p>
<p>Thanks in advance!</p> | 18,687,297 | 9 | 0 | null | 2013-09-08 17:16:45.507 UTC | 8 | 2021-10-06 16:09:44.17 UTC | 2015-04-30 14:38:33.973 UTC | user2629955 | null | null | 2,254,797 | null | 1 | 12 | android|audio|share | 25,542 | <p>Oké, found out what I did wrong. For people who have the same problem, this is how I solved it:</p>
<p>I forgot to parse the String to an uri. Thats the only line of code I had to add. <code>Uri uri = Uri.parse(sharePath);</code></p>
<p>Here is the full rest:</p>
<pre><code> String sharePath = Environment.getExternalStorageDirectory().getPath()
+ "/Soundboard/Ringtones/custom_ringtone.ogg";
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
</code></pre>
<p>Also do not forget to add permission <code>WRITE_EXTERNAL_STORAGE</code> otherwise you'll get an error while running your application.</p> |
15,106,690 | How does ampersand in the return type of a function declaration work? | <p>In this piece of code, why f() is declared as "double & f(..."? What does it mean and how does it work? I don't even know what to google to find the answer to my question. Please help.</p>
<pre><code>double a = 1, b = 2;
double & f (double & d) {
d = 4;
return b;
}
</code></pre>
<p>I know ampersand sign means the address of a variable or a function, but I don't see why it would make sense to write it when you are declaring a function.</p> | 15,106,932 | 3 | 4 | null | 2013-02-27 07:48:09.843 UTC | 9 | 2013-02-27 08:06:58.487 UTC | 2013-02-27 08:00:32.407 UTC | null | 228,632 | null | 228,632 | null | 1 | 27 | c++|function|function-declaration | 22,372 | <p>When the <code>&</code> operator is used in a declaration form, preceded by a type it doesn't mean "the address of" but a "reference to" which is essentially an automatically dereferenced pointer with disabled pointer arithmetic.</p>
<p>There are no references in C, so if you want to pass or return by reference, you had to pass a const pointer and dereference it to access the pointed to value. C++ added references to make this concept easier, to prevent accidental walking off the address with pointer arithmetic, and to save the need to dereference the pointer. This makes working with it much easier and resulting in cleaner and more readable syntax.</p> |
15,003,518 | Confused by the difference between let and let* in Scheme | <p>Can anyone explain the difference simply? I don't think I understand the concept from the textbooks/sites I have consulted.</p> | 15,003,605 | 2 | 3 | null | 2013-02-21 13:30:01.893 UTC | 8 | 2019-05-20 06:20:31.447 UTC | null | null | null | null | 2,095,626 | null | 1 | 29 | scheme|let | 11,384 | <p>If you use <code>let</code>, you can't reference <em>other</em> bindings which appear in the same <code>let</code> expression. </p>
<p>For example, this won't work:</p>
<pre><code>(let ((x 10)
(y (+ x 6))) ; error! unbound identifier: x
y)
</code></pre>
<p>But if you use <code>let*</code>, it is possible to refer to <em>previous</em> bindings which appear in the same <code>let*</code> expression:</p>
<pre><code>(let* ((x 10)
(y (+ x 6))) ; works fine
y)
=> 16
</code></pre>
<p>It's all <a href="http://docs.racket-lang.org/reference/let.html" rel="noreferrer">here</a> in the documentation.</p> |
8,548,141 | Can a website know if I am running a userscript? | <p>Can, for example, Facebook.com run a version control script on my browser and find out if I am running altered HTML code with the use of a script?</p>
<p>Could that be done with a script that can read the HTML code in the cache and produce some kind of hash tag that is sent back to the server and compared with the code that was sent to the client? </p> | 8,548,311 | 2 | 3 | null | 2011-12-17 21:46:55.887 UTC | 19 | 2017-12-23 17:51:51.077 UTC | 2017-12-23 17:51:51.077 UTC | null | 331,508 | null | 1,069,986 | null | 1 | 22 | javascript|facebook|greasemonkey|userscripts|tampermonkey | 13,450 | <p>Yes, in theory, a site can deduce the presence of scripts in various situations.</p>
<p>This is not foolproof and usually is way too much trouble for the negligible "threat" to the site. (Then again, some webmasters can be obsessive-paranoids about such things. ;) )</p>
<p>Some methods, depending on what the script does (in no particular order):</p>
<ol>
<li><p>Gaming or auction sites can monitor the timing (speed and regularity) of "bid" clicks.</p></li>
<li><p>A site can AJAX-back the count of say, <code><script></code> nodes, looking for extras.</p></li>
<li><p>Similarly, a site can AJAX-back any or all of the content of a page and compare that to expected values.</p></li>
<li><p>Extra AJAX calls, or AJAX calls that don't meet hidden requirements can be noted (and allowed to appear to succeed).</p></li>
<li><p>If the script uses <code>unsafeWindow</code> in just the right (wrong) way, <a href="http://wiki.greasespot.net/UnsafeWindow" rel="noreferrer">a page can detect that and even hijack (slightly) elevated privileges</a>.</p></li>
<li><p>"Clicks" that were not preceded by mouseover events can be detected. I've actually seen this used in the wild.</p></li>
<li><p><a href="http://help.dottoro.com/ljoljvsn.php" rel="noreferrer">A page's javascript can often detect script-generated clicks (etc.)</a> as being different than user generated ones. (Thanks, <a href="https://stackoverflow.com/users/946789/c69">c69</a>, for the reminder.)</p></li>
</ol>
<p>Ultimately, the advantage is to the userscript writer, however. Any counter-measures that a webpage takes can be detected and thwarted on the user end. Even custom, required plugins or required hardware dongles can be subverted by skilled and motivated users.</p> |
8,746,860 | how to handle 'double opacity' of two overlapping divs | <p>I have two divs, both with 0.6 opacity. I need them to overlap but retain their opacity and not create a new combined opacity level. I can't use an image. </p>
<p>EDIT -- The little circle is supposed to have a canvas element in it. Not sure if pseudo-elements would be the best solution.</p>
<p>Is there anyway to do this with CSS, or should I just use canvas?</p>
<p>example -</p>
<p><a href="http://dabblet.com/gist/1566209">http://dabblet.com/gist/1566209</a></p>
<p>HTML:</p>
<pre><code><div id="foo">
<div id="bar">
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>/**
* Double Opacity
*/
body{background:green;}
#foo{
height:150px;
width:250px;
background:rgba(0, 0, 0, 0.6);
position:absolute;
left:40%;
top:20%;
}
#bar{
height:40px;
width:40px;
background:rgba(0, 0, 0, 0.6);
border-radius:40px;
position:absolute;
top:-15px;
left:-15px;
}
</code></pre> | 8,747,361 | 5 | 5 | null | 2012-01-05 17:28:27.36 UTC | 10 | 2020-03-29 01:27:22.797 UTC | 2015-05-01 16:20:20.03 UTC | null | 1,811,992 | null | 607,306 | null | 1 | 35 | css|opacity|css-shapes | 24,398 | <hr />
<p><strong>SUMMARY:</strong></p>
<hr />
<p>Depending on what is needed it can be tricky but the basic approach is pretty straight forward.</p>
<hr />
<p>This approach is a little different from my first thought... but this has the same result.</p>
<ol>
<li>I made a black/transparent pattern for the circle and set it to
<code>:before</code>.</li>
<li>The circle is then transformed <code>rotate(180deg)</code> and moved to fit on
the corner of the <code><div></code>.</li>
<li>Then I set the <code>opacity</code> of that circle to <code>0.6</code>.</li>
<li>The <code><div></code> itself is not affected by the <code>opacity</code>.</li>
<li>Next I added the <code>:after</code> element and put an image as <code>background</code>
(you can control this via js if needed)</li>
<li>I added some effects to the image (<code>border-radius</code>, <code>box-shadow</code>,
<code>border</code>) to show how easily and independent this element can be
controlled.</li>
<li>I used a lighter background and set the <code>opacity</code> to <code>0.3</code> to show
the result</li>
</ol>
<p>HERE'S THE FIDDLE: <a href="http://jsfiddle.net/pixelass/nPjQh/4/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/4/</a></p>
<p><strong>Look at this version for some crazy results:</strong> <a href="http://jsfiddle.net/pixelass/nPjQh/5/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/5/</a></p>
<p>each of these examples only use a single <code>div</code> element</p>
<p>Basic rules. (these rules "could" be used to create a dynamic behavior with js)</p>
<p>position = absolute;</p>
<p>top = circleHeight / -2;</p>
<p>left = circleHeight / -2; //(left = top)</p>
<p>rotation = 180deg;</p>
<p>opacity = valueAofBackground;</p>
<p>bgColor = valueRGBofBackground;</p>
<pre><code>#inner {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
z-index: -1;
background-color: rgba(0, 0, 0, 0.3);
padding:20px;
border-radius: 20px;
border-top-left-radius: 0;
}
#inner:before {
content: "";
background-image: -webkit-linear-gradient(transparent 50%, rgb(0, 0, 0) 50%, rgb(0, 0, 0)),
-webkit-linear-gradient(0deg, transparent 50%, rgb(0, 0, 0) 50%, rgb(0, 0, 0));
height: 40px;
width: 40px;
border-radius: 40px;
position: absolute;
top: -20px;
left: -20px;
-webkit-transform: rotateZ(180deg);
opacity:0.3;
}
#inner:after {
content: "";
background: url('http://lorempixel.com/10/10/sports/1/') no-repeat;
background-position:0;
height: 10px;
width: 10px;
border-radius: 10px;
position: absolute;
top: -6px;
left: -6px;
-webkit-box-shadow: 0 0 10px rgb(255,255,255);
border: 1px rgb(255,255,255) solid;
}
</code></pre>
<hr />
<p><strong>Better explanaition</strong></p>
<hr />
<p>Original commented version
<a href="http://jsfiddle.net/pixelass/nPjQh/10/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/10/</a></p>
<p>see the comments in the code below</p>
<pre><code>#inner {
background: rgba(0,0,0,0.5) /*this is the full color-code of the div (with alpha)*/
}
#inner:before {
/*the solid color of the circle = rgbValue of the div*/
background-image: -webkit-linear-gradient(transparent 50%, rgb(0, 0, 0) 50%, rgb(0, 0, 0)),
-webkit-linear-gradient(0deg, transparent 50%, rgb(0, 0, 0) 50%, rgb(0, 0, 0));
/*opacity of the circle = alpha of the div*/
opacity: 0.5;
}
</code></pre>
<p>This example has a full transparent <code>div</code> ...the circle is a "pacman"- shape: <a href="http://jsfiddle.net/pixelass/nPjQh/14/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/14/</a></p>
<p><img src="https://i.stack.imgur.com/w37jj.png" alt="pacman shaped circle" /></p>
<hr />
<p><strong>Managing the offset of the circle</strong></p>
<hr />
<p>Look at these examples that handle the offset of the circle (<strong>NOT USING PSEUDEO-ELEMENTS</strong>)</p>
<p>1:1 copy of the OP's code (15px offset): <a href="http://jsfiddle.net/pixelass/nPjQh/12/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/12/</a></p>
<p>With a lot smaller offset (5px): <a href="http://jsfiddle.net/pixelass/nPjQh/13/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/13/</a></p>
<p>(the content has the same opacity as the circle)</p>
<p><strong>How does the offset work?</strong></p>
<p>Control the <code>background-size</code> vs. the <code>top</code> and <code>left</code></p>
<p><strong>Rules</strong>:</p>
<p>top = left;</p>
<p>background-size = elementHeight * 2 + top * 2;</p>
<p>Look at the flower (it is also only one <code><div></code> with pseudo-elements)
the <code>background-size</code> is bigger than the circle. which creates the green leaves on the bottom</p>
<p><a href="http://jsfiddle.net/pixelass/nPjQh/15/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/15/</a></p>
<p><img src="https://i.stack.imgur.com/b3QXA.png" alt="one div makes a flower" /></p>
<hr />
<p><strong>CURRENT PROBLEM</strong></p>
<hr />
<p>See this fiddle: <a href="http://jsfiddle.net/pixelass/nPjQh/16/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/16/</a></p>
<p>If not using another layer as seen in the examples at the top of the post the content will be transparent. So if you only need an image inside the circle the above examples will work fine.</p>
<p><img src="https://i.stack.imgur.com/DrwbU.png" alt="conent is transparent" /></p>
<p><strong>HOW TO SOLVE THIS ISSUE</strong></p>
<p>If you need a canvas or another div inside the circle you would have to put the circle on the div and layer the needed div over the circle</p>
<p>See this fiddle: <a href="http://jsfiddle.net/pixelass/nPjQh/17/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/17/</a></p>
<p>change around a little and it will work fine. GET THE CODE FROM THE FIDDLE</p>
<p><img src="https://i.stack.imgur.com/Qv5Ip.png" alt="correcting the opacity issue" /></p>
<hr />
<p><strong>Different shape /advanced Styling</strong></p>
<hr />
<p>If you use a different shape with flat sides, you could even put a border around the sum of the two divs.. or even add a box shadow</p>
<p>still using the simple markup of....</p>
<pre><code><div id="foo">
<div id="bar">
</div>
</div>
</code></pre>
<p>See the fiddle for the box-shadow: <a href="http://jsfiddle.net/pixelass/nPjQh/21/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/21/</a></p>
<p><img src="https://i.stack.imgur.com/C0PKz.png" alt="adding a box-shadow" /></p>
<hr />
<p><strong>Apply a border to the circle</strong></p>
<hr />
<p>Using <code>-webkit-mask-image</code> we could add a border to the circle.
<a href="http://jsfiddle.net/pixelass/nPjQh/24/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/24/</a></p>
<p><img src="https://i.stack.imgur.com/NPPxJ.png" alt="border on round element" /></p>
<hr />
<p><strong>More examples:</strong></p>
<hr />
<p><strong>Four circles around the div</strong></p>
<p><a href="http://jsfiddle.net/pixelass/nPjQh/25/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/25/</a></p>
<p>Markup:</p>
<pre><code><div id="foo">
<div id="bar1"></div>
<div id="bar2"></div>
<div id="bar3"></div>
<div id="bar4"></div>
</div>
</code></pre>
<p><img src="https://i.stack.imgur.com/LjAjH.png" alt="4 circles" /></p>
<p><strong>Using this technique to make a tooltip</strong></p>
<p><a href="http://jsfiddle.net/pixelass/nPjQh/31/" rel="noreferrer">http://jsfiddle.net/pixelass/nPjQh/31/</a></p>
<p>Markup:</p>
<pre><code><div id="foo">
<div id="bar"></div>
I am a pure css tooltip with a semi-transparent background and a black border. <br/>
My width is static an my height is dynamic...
</div>
</code></pre>
<p><img src="https://i.stack.imgur.com/k95JN.png" alt="css tooltip" /></p> |
8,931,328 | How do I add my new User Control to the Toolbox or a new Winform? | <p>I have an existing library (not a Winforms application) that supplies some Winforms to a bona-fide Windows application. Within this library, I would like to create a User Control to group some controls together. To accomplish this, I <strong>right-clicked, Add, User Control</strong> and dragged some controls onto the new User Control. </p>
<p>So far, so good. The User Control even has the requisite User Control icon. But dragging the new User Control from the Solution Explorer to a new blank Winform does not work (I get a circle with a line through it), and dragging it over to the Toolbox doesn't work either (even though I get a + sign when I drag it over the Toolbox).</p>
<p>Is there some sort of XML magic or something else I'm missing to make this work?</p>
<hr>
<p><strong>Note:</strong> I had some problems with Visual Studio 2008 that I managed to fix by following the workarounds that can be found <a href="http://connect.microsoft.com/VisualStudio/feedback/details/363321/choose-items-in-toolbox-causes-visual-studio-2008-sp1-to-crash">here</a>. I am now able to get User Controls I added to my existing project into the toolbox by simply rebuilding the project.</p> | 8,931,414 | 4 | 5 | null | 2012-01-19 18:29:36.03 UTC | 11 | 2020-02-21 19:39:58.277 UTC | 2015-02-12 16:13:22.15 UTC | null | 102,937 | null | 102,937 | null | 1 | 74 | c#|winforms|visual-studio-2008|user-controls | 137,864 | <p>Assuming I understand what you mean:</p>
<ol>
<li><p>If your <code>UserControl</code> is in a library you can add this to you Toolbox using </p>
<p>Toolbox -> right click -> <em>Choose Items</em> -> <kbd>Browse</kbd></p>
<p>Select your assembly with the <code>UserControl</code>.</p></li>
<li><p>If the <code>UserControl</code> is part of your project you only need to build the entire solution. After that, your <code>UserControl</code> should appear in the toolbox.</p></li>
</ol>
<p><strong>In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.</strong></p>
<p><img src="https://i.stack.imgur.com/tZgLt.png" alt="Enter image description here"></p> |
4,894,120 | What does "for(;;)" mean? | <p>In C/C++, what does the following mean?</p>
<pre><code>for(;;){
...
}
</code></pre> | 4,894,126 | 5 | 6 | null | 2011-02-04 02:56:48.967 UTC | 9 | 2022-08-16 06:33:01.383 UTC | 2018-09-08 19:49:15.867 UTC | null | 2,947,502 | null | 394,103 | null | 1 | 37 | c++|c|syntax|for-loop | 64,946 | <p>It's an infinite loop, equivalent to <code>while(true)</code>. When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).</p> |
5,382,712 | Bash: How to tokenize a string variable? | <p>If I have a string variable who's value is <code>"john is 17 years old"</code> how do I tokenize this using spaces as the delimeter? Would I use <code>awk</code>?</p> | 5,382,824 | 5 | 0 | null | 2011-03-21 19:41:10.963 UTC | 11 | 2018-12-21 09:36:48.587 UTC | null | null | null | null | 172,350 | null | 1 | 51 | linux|bash | 96,732 | <p>Use the shell's automatic tokenization of unquoted variables:</p>
<pre><code>$ string="john is 17 years old"
$ for word in $string; do echo "$word"; done
john
is
17
years
old
</code></pre>
<p>If you want to change the delimiter you can set the <code>$IFS</code> variable, which stands for internal field separator. The default value of <code>$IFS</code> is <code>" \t\n"</code> (space, tab, newline).</p>
<pre><code>$ string="john_is_17_years_old"
$ (IFS='_'; for word in $string; do echo "$word"; done)
john
is
17
years
old
</code></pre>
<p>(Note that in this second example I added parentheses around the second line. This creates a sub-shell so that the change to <code>$IFS</code> doesn't persist. You generally don't want to permanently change <code>$IFS</code> as it can wreak havoc on unsuspecting shell commands.)</p> |
5,058,843 | what is cgi programming | <p>What is exactly meant by CGI programming . If I am writing a cgi program in 'C' ,</p>
<p>in that context , what does the 'cgi' mean ?</p>
<p>Is the servelt environment is an abstraction of classical cgi programming ?</p> | 5,058,873 | 6 | 1 | null | 2011-02-20 17:57:56.237 UTC | 7 | 2018-05-10 12:06:49.727 UTC | null | null | null | null | 478,395 | null | 1 | 25 | cgi | 40,505 | <p>Abbreviation of Common Gateway Interface, a specification for transferring information between a World Wide Web server and a CGI program. A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program could be written in any programming language, including C, Perl, Java, or Visual Basic.
CGI programs are the most common way for Web servers to interact dynamically with users. Many HTML pages that contain forms, for example, use a CGI program to process the form's data once it's submitted. Another increasingly common way to provide dynamic feedback for Web users is to include scripts or programs that run on the user's machine rather than the Web server. These programs can be Java applets, Java scripts, or ActiveX controls. These technologies are known collectively as client-side solutions, while the use of CGI is a server-side solution because the processing occurs on the Web server.</p> |
5,155,333 | Remove index.php From URL - Codeigniter 2 | <p>I am having trouble removing index.php from my URLs in Codeigniter. I've made a few websites with Codeigniter 1.7 and the .htaccess code I used doesn't work in 2.</p>
<p>I have tried using </p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code></pre>
<p>and </p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ ./index.php/$1 [L]
</IfModule>
</code></pre>
<p>I've also tried it without RewriteBase / in.</p>
<p>I have changed the $config['uri_protocol'] to REQUEST_URI and QUERY_STRING and nothing.</p>
<p>I have set $config['index_page'] = "";</p>
<p>The file structure is 192.168.0.130/(site)/ so it must be going back to the root of the server and can't find the index.php file.</p>
<p>All of the controllers I have made can be reached by putting 192.168.0.130/(site)/index.php/testcontroller</p>
<p>Thank you.</p>
<p>Apologies if this has been asked before - I have looked and tried what I could see.</p>
<p>Edit:</p>
<p>I should also add that I changed the default folders to be </p>
<p>application</p>
<p>CI-2.0</p>
<p>index.php</p>
<p>and changed the paths in index.php to be correct. </p> | 5,156,116 | 7 | 7 | null | 2011-03-01 13:46:24.09 UTC | 8 | 2017-03-14 14:07:59.457 UTC | 2011-03-01 14:00:22.43 UTC | null | 442,326 | null | 442,326 | null | 1 | 30 | php|.htaccess|codeigniter | 42,157 | <p>Try the first code block you posted, but instead of /index.php try using /(site)/index.php (obv replacing (site) with whatever your site folder is named).</p> |
4,938,723 | What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)? | <p>What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)?</p>
<p>Currently (I have done nothing special to handle unix signals), my PyQt application ignores SIGINT (Ctrl+C). I want it to behave nicely and quit when it is killed. How should I do that?</p> | 4,939,113 | 8 | 5 | null | 2011-02-08 21:33:12.257 UTC | 20 | 2021-01-20 02:28:16.76 UTC | 2011-02-08 21:40:33.66 UTC | null | 164,171 | null | 164,171 | null | 1 | 79 | python|linux|qt|pyqt|signals | 48,792 | <blockquote>
<p><a href="http://docs.python.org/library/signal.html" rel="noreferrer">17.4. signal — Set handlers for asynchronous events</a></p>
<p>Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time.</p>
</blockquote>
<p>That means Python cannot handle signals while the Qt event loop is running. Only when the Python interpreter run (when the QApplication quits, or when a Python function is called from Qt) the signal handler will be called.</p>
<p>A solution is to use a QTimer to let the interpreter run from time to time.</p>
<p>Note that, in the code below, if there are no open windows, the application will quit after the message box regardless of the user's choice because QApplication.quitOnLastWindowClosed() == True. This behaviour can be changed.</p>
<pre><code>import signal
import sys
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QApplication, QMessageBox
# Your code here
def sigint_handler(*args):
"""Handler for the SIGINT signal."""
sys.stderr.write('\r')
if QMessageBox.question(None, '', "Are you sure you want to quit?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No) == QMessageBox.Yes:
QApplication.quit()
if __name__ == "__main__":
signal.signal(signal.SIGINT, sigint_handler)
app = QApplication(sys.argv)
timer = QTimer()
timer.start(500) # You may change this if you wish.
timer.timeout.connect(lambda: None) # Let the interpreter run each 500 ms.
# Your code here.
sys.exit(app.exec_())
</code></pre>
<p>Another possible solution, <a href="https://stackoverflow.com/a/6072360/286655">as pointed by LinearOrbit</a>, is <code>signal.signal(signal.SIGINT, signal.SIG_DFL)</code>, but it doesn't allow custom handlers.</p> |
5,334,353 | When should I use composite design pattern? | <p>I don't understand <strong>when I should use composite design pattern</strong>.
<em>What kinds of benefits will I get from this design pattern?</em>
I visited <a href="http://www.dofactory.com" rel="noreferrer">this website</a> but it only tells me about the structure of the design pattern and not the scenarios in which it is used.
I hope that it will be beneficial to the programmers like me who are starting to learn design pattern.</p> | 5,338,862 | 11 | 4 | null | 2011-03-17 02:48:34.077 UTC | 27 | 2022-01-29 19:57:44.9 UTC | 2016-10-06 21:41:57.013 UTC | null | 4,446,493 | null | 631,733 | null | 1 | 69 | design-patterns|composite | 47,004 | <p>Quoting from <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns</a>,</p>
<blockquote>
<p>Use the Composite pattern when</p>
<ul>
<li>you want to represent part-whole hierarchies of objects.</li>
<li>you want clients to be able to ignore the difference between
compositions of objects and
individual objects. Clients will
treat all objects in the composite
structure uniformly.</li>
</ul>
</blockquote>
<p>A common usage is the one used as a motivating example in the book, a display system of graphic windows which can contain other windows and graphic elements such as images, text. The composite can be composed at run-time, and the client code can manipulate all the elements without concern for which type it is for common operations such as drawing.</p> |
5,163,785 | How do I get the last character of a string? | <p>How do I get the last character of a string?</p>
<pre><code>public class Main {
public static void main(String[] args) {
String s = "test string";
//char lastChar = ???
}
}
</code></pre> | 5,163,852 | 11 | 3 | null | 2011-03-02 05:34:16.49 UTC | 25 | 2021-11-09 05:12:38.233 UTC | 2020-08-05 09:15:29.283 UTC | user10539074 | null | null | 516,805 | null | 1 | 228 | java|string|substring | 708,465 | <p>The code:</p>
<pre><code>public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
</code></pre>
<p>The output of <code>java Test abcdef</code>:</p>
<pre><code>last character: f
</code></pre> |
16,661,231 | Get value of a select element with ajax | <p>I'm trying to get a value of a select element, but is returning <code>Array()</code></p>
<p>This is my html:</p>
<pre><code><select name="data[Attorney][empresa]" id="AttorneyEmpresa">
<option value="">Selecione</option>
<option value="3">Sotreq</option>
</select>
</code></pre>
<p>And my Jquery:</p>
<pre><code>$(document).ready(function() {
$("#AttorneyEmpresa").change(function(){
$.ajax({
type: 'POST',
data: $('#AttorneyEmpresa').val()
});
});
});
</code></pre>
<p>What's wrong?</p> | 16,661,259 | 3 | 2 | null | 2013-05-21 02:28:03.1 UTC | 2 | 2013-05-21 02:42:45.673 UTC | 2013-05-21 02:42:45.673 UTC | user1823761 | null | null | 1,785,897 | null | 1 | 4 | jquery|ajax | 65,502 | <p>Try this</p>
<pre><code>$(document).ready(function() {
$("#AttorneyEmpresa").change(function(){
$.ajax({
type: 'POST',
data: {keyname:$('#AttorneyEmpresa option:selected').val()}
});
});
});
</code></pre>
<p><a href="http://jsfiddle.net/a5gkq/" rel="noreferrer">DEMO</a></p> |
12,227,689 | Function within Function in R | <p>Can you please explain to me why the code complains saying that <code>Samdat</code> is not found?</p>
<p>I am trying to switch between models, so I declared a function that contains these specific models and I just need to call this function as one of the argument in the <code>get.f</code> function where the resampling will change the structure for each design matrix in the model. The code complains that <code>Samdat</code> is not found when it is found.</p>
<p>Also, is there a way I can make the conditional statement <code>if(Model == M1())</code> instead of having to create another argument <code>M</code> to set <code>if(M==1)</code>?</p>
<p>Here is my code:</p>
<pre><code>dat <- cbind(Y=rnorm(20),rnorm(20),runif(20),rexp(20),rnorm(20),runif(20), rexp(20),rnorm(20),runif(20),rexp(20))
nam <- paste("v",1:9,sep="")
colnames(dat) <- c("Y",nam)
M1 <- function(){
a1 = cbind(Samdat[,c(2:5,7,9)])
b1 = cbind(Samdat[,c(2:4,6,8,7)])
c1 = b1+a1
list(a1=a1,b1=b1,c1=c1)}
M2 <- function(){
a1= cbind(Samdat[,c(2:5,7,9)])+2
b1= cbind(Samdat[,c(2:4,6,8,7)])+2
c1 = a1+b1
list(a1=a1,b1=b1,c1=c1)}
M3 <- function(){
a1= cbind(Samdat[,c(2:5,7,9)])+8
b1= cbind(Samdat[,c(2:4,6,8,7)])+8
c1 = a1+b1
list(a1=a1,b1=b1,c1=c1)}
#################################################################
get.f <- function(asim,Model,M){
sse <-c()
for(i in 1:asim){
set.seed(i)
Samdat <- dat[sample(1:nrow(dat),nrow(dat),replace=T),]
Y <- Samdat[,1]
if(M==1){
a2 <- Model$a1
b2 <- Model$b1
c2 <- Model$c1
s<- a2+b2+c2
fit <- lm(Y~s)
cof <- sum(summary(fit)$coef[,1])
coff <-Model$cof
sse <-c(sse,coff)
}
else if(M==2){
a2 <- Model$a1
b2 <- Model$b1
c2 <- Model$c1
s<- c2+12
fit <- lm(Y~s)
cof <- sum(summary(fit)$coef[,1])
coff <-Model$cof
sse <-c(sse,coff)
}
else {
a2 <- Model$a1
b2 <- Model$b1
c2 <- Model$c1
s<- c2+a2
fit <- lm(Y~s)
cof <- sum(summary(fit)$coef[,1])
coff <- Model$cof
sse <-c(sse,coff)
}
}
return(sse)
}
get.f(10,Model=M1(),M=1)
get.f(10,Model=M2(),M=2)
get.f(10,Model=M3(),M=3)
</code></pre> | 12,229,142 | 2 | 4 | null | 2012-09-01 12:25:58.363 UTC | 4 | 2012-09-01 20:27:51.763 UTC | 2012-09-01 20:12:25.423 UTC | null | 1,287,593 | null | 1,640,457 | null | 1 | 8 | r | 47,765 | <p>When you call</p>
<pre><code>get.f(10, Model=M1(), M=1)
</code></pre>
<p>your <code>M1</code> function is immediately called. It dies because inside the body of <code>M1</code> you are using <code>Samdat</code> which is only defined later, in the body of <code>get.f</code>.</p>
<p>Somehow, you need to call <code>M1</code> <em>after</em> <code>Samdat</code> is defined. One way of doing that is to make <code>M1</code> (the function) an argument to <code>get.f</code> and call the function from inside <code>get.f</code>:</p>
<pre><code>get.f <- function(asim, Model.fun, M) {
...
Sambat <- ...
Model <- Model.fun()
...
}
get.f(10, Model.fun = M1, M=1)
</code></pre>
<p>Also, in general, it is bad programming to use global variables, i.e., make your function use variables that are defined outside their scope. Instead, it is recommended that everything a function uses be passed as input arguments. You have two such cases in your code: <code>M1</code> (<code>M2</code>, and <code>M3</code>) use <code>Samdat</code> and <code>get.f</code> uses <code>dat</code>. They should be arguments to your functions. Here is a nicer version of your code. I have not fixed everything, so you'll have to do a little more to get it to work:</p>
<pre><code>M1 <- function(sampled.data) {
a1 <- sampled.data[, c("v1", "v2", "v3", "v4", "v6", "v8")]
b1 <- sampled.data[, c("v1", "v2", "v3", "v5", "v7", "v6")]
c1 <- a1 + b1
list(a1 = a1, b1 = b1, c1 = c1)
}
get.f <- function(dat, asim, Model.fun, offset, M) {
sse <- c()
for(i in 1:asim){
set.seed(i)
Samdat <- dat[sample(1:nrow(dat), nrow(dat), replace = TRUE), ]
Y <- Samdat[, "Y"]
Model <- Model.fun(sampled.data = Samdat)
a2 <- Model$a1
b2 <- Model$b1
c2 <- Model$c1
s <- switch(M, a2 + b2 + c2, c2 + 12, c2 + a2)
fit <- lm(Y ~ s)
cof <- sum(summary(fit)$coef[,1])
coff <- Model$cof # there is a problem here...
sse <- c(sse, coff) # this is not efficient
}
return(sse)
}
dat <- cbind(Y = rnorm(20), v1 = rnorm(20), v2 = runif(20), v3 = rexp(20),
v4 = rnorm(20), v5 = runif(20), v6 = rexp(20),
v7 = rnorm(20), v8 = runif(20), v9 = rexp(20))
get.f(dat, 10, Model.fun = M1, M = 1)
</code></pre>
<p>One last thing that jumps out: if the definition of <code>s</code> (what I gathered under <code>switch()</code> is related to the <code>Model</code> you use, then consider merging the definitions of <code>Model</code> and <code>s</code> together: add <code>s</code> to the list output of your <code>M1</code>, <code>M2</code>, <code>M3</code> functions so that <code>s</code> can just be defined as <code>s <- Model$s</code>, and you can then drop the <code>M</code> input to <code>get.f</code>.</p> |
12,191,029 | Running two independent tasks simultaneously using threads | <p>I've studied lots of tutorials on threads in java but I'm unable to find my answer. </p>
<p>My question is: how to run two independent threads simultaneously? </p>
<p>My case is: I have two tasks; </p>
<ol>
<li>save some data to the database</li>
<li>send a push notification on a mobile device. </li>
</ol>
<p>Since these two tasks are independent I want to execute them simultaneously. </p>
<p>I tried using a thread pool with two threads but the problem is that the database tasks finishes quickly but it takes some time to send a push notification. </p>
<p>Consequently when one task is finished while the other is still pending, it throws an exception. </p>
<p>Also there is no problem in my code because it runs fine without using threads. </p>
<p>Thanks in advance</p> | 12,191,090 | 2 | 3 | null | 2012-08-30 06:26:48.833 UTC | 12 | 2018-02-12 10:40:50.55 UTC | 2012-08-30 06:28:29.013 UTC | null | 992,484 | null | 634,958 | null | 1 | 11 | java|multithreading|threadpool | 48,968 | <pre><code>new Thread(new Runnable() {
public void run() {
System.out.println("Look ma, no hands");
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("Look at me, look at me...");
}
}).start();
</code></pre>
<p>Works just fine...</p>
<p>I'd prefer the use of an <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html">ExecutorService</a> personally.</p>
<p><strong>UPDATED with ExecutorService example</strong></p>
<p>So I wrote this really quick example...</p>
<p>Basically it uses an <code>ExecutorService</code> to run a couple of simple tasks. As it stands, both task will run in parallel with each other (simultaneously)</p>
<pre><code>public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(new PathScanner());
service.submit(new Counter());
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
System.exit(0);
}
public static class PathScanner implements Callable<Object> {
@Override
public Object call() throws Exception {
scan(new File("C:/"), 0);
return null;
}
protected void scan(File path, int deepth) {
if (deepth < 15) {
System.out.println("Scanning " + path + " at a deepth of " + deepth);
File[] files = path.listFiles();
for (File file : files) {
if (file.isDirectory()) {
scan(file, ++deepth);
}
}
}
}
}
public static class Counter implements Callable<Object> {
@Override
public Object call() throws Exception {
for (int index = 0; index < 1000; index++) {
Thread.sleep(1);
System.out.println(index);
}
return null;
}
}
</code></pre>
<p>Run it...</p>
<p>Now change <code>ExecutorService service = Executors.newFixedThreadPool(2);</code> to <code>ExecutorService service = Executors.newFixedThreadPool(1);</code> and run it again. Did you see the difference?</p>
<p>This is the way to control the number of simultaneously threads that executor can use while processing it's queue.</p>
<p>Make up some more tasks and add them to the queue and see what you get.</p> |
12,195,225 | Step by step Google SSO (java)? | <p>I am lost in all my open browser tabs for Google single sign on :)</p>
<p>I already have an application which I would like to put on Google market place. And mandatory integration is Google SSO. I have built application on Struts2 with Spring. </p>
<p>So now I need some instructions how to make this integration. An example would be perfect. Or how to start, which technology to use, best approaches, anything similar... </p>
<p>Also, <strong>do I have to</strong> use Google App Engine for SSO integration or no? Honestly, I am confused :)</p>
<p><strong>EDIT</strong></p>
<p>I started here: <a href="http://developers.google.com/google-apps/marketplace/sso">developers.google.com/google-apps/marketplace/sso</a> Because I use Java, if you look at Getting started at the bottom, I wanted to use step2, but the link is dead. From there on I got stuck...</p>
<p>Links <a href="https://developers.google.com/google-apps/help/open-source#sso">here</a> are also dead.</p> | 12,607,695 | 2 | 4 | null | 2012-08-30 10:51:37.847 UTC | 10 | 2012-09-26 18:01:09.737 UTC | 2012-09-04 13:42:12.667 UTC | null | 180,335 | null | 180,335 | null | 1 | 13 | java|oauth-2.0|single-sign-on | 7,660 | <p>I made with Apache's HttpClient. This is my solution and works perfectly for me.</p>
<p>First point to authorization url:</p>
<p><code>https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&state=%2Fprofile&response_type=code&client_id=<YOUR_CLIENT_ID>&redirect_uri=<YOUR_CALLBACK_URL></code></p>
<p>Then get parameters back from your <code>redirect_uri</code> and build request body for getting <code>access_token</code>:</p>
<pre><code> String code = request.getParameter("code");
String foros = "code="+code +
"&client_id=<YOUR_CLIENT_ID>" +
"&client_secret=<YOUR_CLIENT_SECRET>" +
"&redirect_uri="+getText("google.auth.redirect.uri") +
"&grant_type=authorization_code";
</code></pre>
<p>Then with HttpClient make a POST and with simple JSON parser parse out the access token.</p>
<pre><code> HttpClient client = new HttpClient();
String url = "https://accounts.google.com/o/oauth2/token";
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
try {
post.setRequestEntity(new StringRequestEntity(foros, null, null));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String accessToken = null;
try {
client.executeMethod(post);
String resp = post.getResponseBodyAsString();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(resp);
JSONObject parsed = (JSONObject)obj;
accessToken = (String) parsed.get("access_token");
} catch (HttpException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
</code></pre>
<p>Now you have the access token and you can now access <strong>all</strong> of the Google API. For example, getting all the users info:</p>
<pre><code> GetMethod getUserInfo = new GetMethod("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+accessToken);
String googleId = null;
String email = null;
String name = null;
String firstName = null;
String lastName = null;
try {
client.executeMethod(getUserInfo);
String resp = getUserInfo.getResponseBodyAsString();
JSONParser jsonParser = new JSONParser();
Object obj = jsonParser.parse(resp);
JSONObject parsed = (JSONObject)obj;
googleId = (String) parsed.get("id");
email = (String) parsed.get("email");
name = (String) parsed.get("name");
firstName = (String) parsed.get("given_name");
lastName = (String) parsed.get("family_name");
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
throw new RuntimeException(e);
}
</code></pre>
<p>This data you can now save and use it for login to your application. </p> |
12,369,639 | Tomcat won't stop or restart | <p>I tried stopping tomcat. It failed with this message: </p>
<ul>
<li>Tomcat did not stop in time. PID file was not removed.</li>
</ul>
<p>I then tried again and got this:</p>
<ul>
<li>PID file (/opt/tomcat/work/catalina.pid) found but no matching
process was found. Stop aborted.</li>
</ul>
<p>I then tried starting tomcat in debug mode and got this:</p>
<ul>
<li>PID file (/opt/tomcat/work/catalina.pid) found. Is Tomcat still
running? Start aborted.</li>
</ul>
<p>I them deleted /opt/tomcat/work/catalina.pid and tried restarting and got this:</p>
<ul>
<li>$CATALINA_PID was set (/opt/tomcat/work/catalina.pid) but the
specified file does not exist. Is Tomcat running? Stop aborted.</li>
</ul>
<p>Anyone know how to get tomcat restarted?</p> | 12,369,918 | 15 | 3 | null | 2012-09-11 12:23:52.07 UTC | 11 | 2022-05-07 10:23:47.67 UTC | null | null | null | null | 999,353 | null | 1 | 29 | tomcat|catalina | 143,612 | <p>It seems Tomcat was actually stopped. I started it and it started fine. Thanks all.</p> |
12,316,365 | How can I display a holo-themed activity circle? | <p>I've tried to show an indeterminate activity circle like this one:</p>
<p><img src="https://i.stack.imgur.com/SuGXK.png" alt="enter image description here"></p>
<p>Here's the layout code:</p>
<pre><code><ProgressBar
android:id="@+id/progress"
style="@style/GenericProgressIndicator"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:visibility="gone" />
</code></pre>
<p>Here's the styling code:</p>
<pre><code><style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Large">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:indeterminate">true</item>
</style>
</code></pre>
<p>My circle doesn't look anything like the Holo themed circle that you see in the Gmail App or the Play app. What am I doing wrong? How can I get the nice Holo animated activity circle?</p> | 12,318,820 | 3 | 0 | null | 2012-09-07 10:32:04.59 UTC | 12 | 2014-05-07 09:33:31.463 UTC | 2014-05-07 09:33:31.463 UTC | null | 304,151 | null | 304,151 | null | 1 | 35 | java|android|android-progressbar | 20,615 | <p>This really wasn't documented anywhere and I found it through some random article. Adding this styling attribute does the trick:</p>
<pre><code>style="?android:attr/progressBarStyleLarge"
</code></pre>
<p>The only reference to this on the developer documentation is <a href="http://developer.android.com/reference/android/R.attr.html#progressBarStyleLarge" rel="noreferrer">here</a>.</p> |
12,639,030 | Get the list of stored procedures created and / or modified on a particular date? | <p>I want to find which stored procedure I've created and also I want to find which stored procedure I've modified in my SQL Server on a particular date like 27 september 2012 (27/09/2012).</p>
<p>Is there any query which will list these procedures that are created and also modified on this date?</p> | 12,639,068 | 5 | 0 | null | 2012-09-28 11:20:34.42 UTC | 7 | 2016-11-04 10:09:58.66 UTC | 2015-02-12 18:44:47.757 UTC | null | 2,686,013 | null | 777,702 | null | 1 | 47 | sql|sql-server|sql-server-2008|sql-server-2005 | 147,459 | <p>You can try this query in any given SQL Server database:</p>
<pre><code>SELECT
name,
create_date,
modify_date
FROM sys.procedures
WHERE create_date = '20120927'
</code></pre>
<p>which lists out the name, the creation and the last modification date - unfortunately, it doesn't record <strong>who</strong> created and/or modified the stored procedure in question.</p> |
12,496,959 | Summing values in a List | <p>I'm trying to write a scala function which will recursively sum the values in a list. Here is what I have so far : </p>
<pre><code> def sum(xs: List[Int]): Int = {
val num = List(xs.head)
if(!xs.isEmpty) {
sum(xs.tail)
}
0
}
</code></pre>
<p>I dont know how to sum the individual Int values as part of the function. I am considering defining a new function within the function sum and have using a local variable which sums values as List is beuing iterated upon. But this seems like an imperative approach. Is there an alternative method ?</p> | 12,497,010 | 12 | 4 | null | 2012-09-19 14:33:49.557 UTC | 13 | 2020-04-08 13:42:04.613 UTC | 2012-09-19 17:33:45.157 UTC | null | 298,389 | null | 701,254 | null | 1 | 54 | scala | 97,931 | <p>Here's the the "standard" recursive approach:</p>
<pre><code>def sum(xs: List[Int]): Int = {
xs match {
case x :: tail => x + sum(tail) // if there is an element, add it to the sum of the tail
case Nil => 0 // if there are no elements, then the sum is 0
}
}
</code></pre>
<p>And, here's a tail-recursive function. It will be more efficient than a non-tail-recursive function because the compiler turns it into a while loop that doesn't require pushing a new frame on the stack for every recursive call:</p>
<pre><code>def sum(xs: List[Int]): Int = {
@tailrec
def inner(xs: List[Int], accum: Int): Int = {
xs match {
case x :: tail => inner(tail, accum + x)
case Nil => accum
}
}
inner(xs, 0)
}
</code></pre> |
19,031,861 | PendingIntent not opening Activity in Android 4.3 | <p>In my <code>Service</code>, I open up a notification on normal run, using this code:</p>
<pre><code>private final static NOTIFICATION_ID = 412434;
private void startNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
builder.setSmallIcon(R.drawable.notification);
builder.setContentTitle("Running");
final Intent intent = new Intent(this, MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setOngoing(true);
builder.setAutoCancel(false);
notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
</code></pre>
<p>The <code>PendingIntent</code> is to open the <code>MainActivity</code> when the Notification is tapped. This works perfectly fine on all my test devices, using Android 2.3.3, 2.3.5 and Android 4.1.</p>
<p>It does not work, however on my Nexus 7 (Android 4.3), this doesn't work at all. Nothing happens when I tap on the Notification.</p>
<p>Did something change in the way these are put together that I missed?</p> | 19,166,954 | 2 | 5 | null | 2013-09-26 15:04:08.667 UTC | 10 | 2018-08-21 12:51:13.493 UTC | null | null | null | null | 471,436 | null | 1 | 32 | android|android-intent|android-notifications | 11,480 | <p>There seems to be an issue on some 4.3 devices. It can be resolved by providing a non 0 value to the <code>requestCode</code> parameter.</p>
<p>Example:</p>
<pre><code>PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
</code></pre> |
43,095,886 | How to initialize a struct from a json object | <p>HI i am new to swift any idea . How to initialize a struct from a json object . i could not figure out how can i do it .</p>
<blockquote>
<p>{
"user": {
"name": "cruskuaka",
"email": "[email protected]",
"phoneNo":"018833455"
},
"address": {
"house": "100",
"street": "B",
"town":
{
"town_id": "1",
"town_name": "Galway city center"
},
"city":
{
"city_id": "10",
"city_name": "Galway"
},
"address_id":"200",
"full_address":"100, B, Galway city center,Galway"
},
"delivery_instruction": "no call",
"delivery_method": "1"
} </p>
</blockquote>
<p><strong><em>Here all struct</em></strong> :</p>
<pre><code>struct Contact {
let user : User
let address : Address
let deliveryInstruction : String
let deliveryMethod : String
init(dictionary: [String: Any]) {
self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
self.address = Address(dictionary: dictionary["address"] as? [String:Any] ?? [:])
self.user = User(dictionary: dictionary["address"] as? [String:Any] ?? [:])
}
}
</code></pre>
<hr>
<pre><code>struct User {
let name : String
let email : String
let phoneNo : String
init(dictionary : [String:Any] ) {
self.name = dictionary["name"] as? String ?? ""
self.email = dictionary["email"] as? String ?? ""
self.phoneNo = dictionary["phoneNo"] as? String ?? ""
}
}
</code></pre>
<hr>
<pre><code>struct Address {
let city : City
let town : Town
let addressId : String
let fullAddress : String
let house : String
let street: String
init(dictionary : [String:Any] ) {
self.addressId = dictionary["address_id"] as? String ?? ""
self.fullAddress = dictionary["full_address"] as? String ?? ""
self.house = dictionary["house"] as? String ?? ""
self.street = dictionary["street"] as? String ?? ""
self.city = City(dictionary: dictionary["address"] as? [String:Any] ?? [:])
self.town = Town(dictionary: dictionary["address"] as? [String:Any] ?? [:])
}
}
</code></pre>
<hr>
<pre><code>struct City {
let cityId : String
let cityName : String
init(dictionary : [String:Any] ) {
self.cityId = dictionary["city_id"] as? String ?? ""
self.cityName = dictionary["city_name"] as? String ?? ""
}
}
</code></pre>
<hr>
<pre><code>struct Town {
let townId : String
let townName : String
init(dictionary : [String:Any]) {
self.townId = dictionary["town_id"] as? String ?? ""
self.townName = dictionary["town_name"] as? String ?? ""
}
}
</code></pre> | 43,121,890 | 1 | 10 | null | 2017-03-29 14:06:25.513 UTC | 9 | 2020-06-28 03:18:47.17 UTC | 2017-03-30 15:09:19.233 UTC | null | 2,303,865 | user7166107 | null | null | 1 | 8 | json|swift|swift3 | 8,036 | <p>edit/update: Swift 4 or later you can use Codable Protocol:</p>
<pre><code>struct Root: Codable {
let user: User
let address: Address
let deliveryInstruction, deliveryMethod: String
}
</code></pre>
<hr />
<pre><code>struct Address: Codable {
let house, street, addressId, fullAddress: String
let town: Town
let city: City
}
</code></pre>
<hr />
<pre><code>struct City: Codable {
let cityId, cityName: String
}
</code></pre>
<hr />
<pre><code>struct Town: Codable {
let townId, townName: String
}
</code></pre>
<hr />
<pre><code>struct User: Codable {
let name, email, phoneNo: String
}
</code></pre>
<hr />
<pre><code>extension Decodable {
init(data: Data, using decoder: JSONDecoder = .init()) throws {
self = try decoder.decode(Self.self, from: data)
}
init(json: String, using decoder: JSONDecoder = .init()) throws {
try self.init(data: Data(json.utf8), using: decoder)
}
}
</code></pre>
<p>Just don't forget to set the JSONDecoder property <code>keyDecodingStrategy</code> to <code>.convertFromSnakeCase</code>:</p>
<hr />
<pre><code>let json = """
{"user": {"name": "crst","email": "[email protected]","phoneNo":"018833455"},"address": {"house": "100","street": "B","town":{"town_id": "1","town_name": "Galway city center"},"city":{"city_id": "10","city_name": "Galway"},"address_id":"200", "full_address":"100, B, Galway city center,Galway" },"delivery_instruction": "no call","delivery_method": "1" }
"""
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let root = try decoder.decode(Root.self, from: Data(json.utf8))
print(root)
} catch {
print(error)
}
</code></pre>
<p>or simply:</p>
<pre><code>do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let root = try Root(json: json, using: decoder) // or Root(data: data, using: decoder)
print(root)
} catch {
print(error)
}
</code></pre>
<p>This will print</p>
<blockquote>
<p>Root(user: __lldb_expr_112.User(name: "cruskuaka", email:
"[email protected]", phoneNo: "018833455"), address:
__lldb_expr_112.Address(house: "100", street: "B", addressId: "200", fullAddress: "100, B, Galway city center,Galway", town:
__lldb_expr_112.Town(townId: "1", townName: "Galway city center"), city: __lldb_expr_112.City(cityId: "10", cityName: "Galway")),
deliveryInstruction: "no call", deliveryMethod: "1")</p>
</blockquote>
<hr />
<hr />
<p>Original Answer (before Codable protocol)</p>
<p>Swift 3</p>
<p>You have more than one error in your code, but you are in the right path. You are using the wrong key when initializing your user, city and town structs. I have also created two more initializers so you can initialize your struct with a dictionary, the json string or just its data:</p>
<pre><code>struct Contact: CustomStringConvertible {
let user: User
let address: Address
let deliveryInstruction: String
let deliveryMethod: String
// customize the description to your needs
var description: String { return "\(user.name) \(deliveryInstruction) \(deliveryMethod)" }
init(dictionary: [String: Any]) {
self.deliveryInstruction = dictionary["delivery_instruction"] as? String ?? ""
self.deliveryMethod = dictionary["delivery_method"] as? String ?? ""
self.address = Address(dictionary: dictionary["address"] as? [String: Any] ?? [:])
self.user = User(dictionary: dictionary["user"] as? [String: Any] ?? [:])
}
init?(data: Data) {
guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil }
self.init(dictionary: json)
}
init?(json: String) {
self.init(data: Data(json.utf8))
}
}
</code></pre>
<hr />
<pre><code>struct User: CustomStringConvertible {
let name: String
let email: String
let phone: String
let description: String
init(dictionary: [String: Any]) {
self.name = dictionary["name"] as? String ?? ""
self.email = dictionary["email"] as? String ?? ""
self.phone = dictionary["phoneNo"] as? String ?? ""
self.description = "name: \(name) - email: \(email) - phone: \(phone)"
}
}
</code></pre>
<hr />
<pre><code>struct Address: CustomStringConvertible {
let id: String
let street: String
let house: String
let city: City
let town: Town
let description: String
init(dictionary: [String: Any] ) {
self.id = dictionary["address_id"] as? String ?? ""
self.description = dictionary["full_address"] as? String ?? ""
self.house = dictionary["house"] as? String ?? ""
self.street = dictionary["street"] as? String ?? ""
self.city = City(dictionary: dictionary["city"] as? [String: Any] ?? [:])
self.town = Town(dictionary: dictionary["town"] as? [String: Any] ?? [:])
}
}
</code></pre>
<hr />
<pre><code>struct City: CustomStringConvertible {
let id: String
let name: String
// customize the description to your needs
var description: String { return name }
init(dictionary: [String: Any] ) {
self.id = dictionary["city_id"] as? String ?? ""
self.name = dictionary["city_name"] as? String ?? ""
}
}
</code></pre>
<hr />
<pre><code>struct Town: CustomStringConvertible {
let id: String
let name: String
// customize the description to your needs
var description: String { return name }
init(dictionary: [String: Any]) {
self.id = dictionary["town_id"] as? String ?? ""
self.name = dictionary["town_name"] as? String ?? ""
}
}
</code></pre>
<p>Testing the initialization from JSON:</p>
<pre><code>let contact = Contact(json: json) // crst no call 1
contact // crst no call 1
contact?.user // name: crst - email: [email protected] - phone: 018833455
contact?.user.name // "crst"
contact?.user.email // "[email protected]"
contact?.user.phone // "018833455"
contact?.address // 100, B, Galway city center,Galway
contact?.address.id // 200
contact?.address.street // B
contact?.address.town // Galway city center
contact?.address.city // Galway
contact?.deliveryInstruction // "no call"
contact?.deliveryMethod // 1
</code></pre> |
3,858,698 | How to read json response as name value pairs in JQuery | <p>I want to read json response as name and value pairs in my JQuery code. Here is my sample JSON response that I return from my java code:</p>
<pre><code>String jsonResponse = "{"name1":"value1", "name2:value2"};
</code></pre>
<p>in my JQuery, if I write <code>jsonResponse.name1</code>, I will get value as <code>"value1"</code>. Here is my JQuery code</p>
<pre><code>$.ajax({
type: 'POST',
dataType:'json',
url: 'http://localhost:8080/calculate',
data: request,
success: function(responseData) {
alert(responseData.name1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//TODO
}
});
</code></pre>
<p>Here I want to read <code>"name1"</code> from jsonResponse instead of hardcoding in JQuery. Something like looping throug the response getting each name and value. Any suggestions?</p> | 3,858,712 | 3 | 0 | null | 2010-10-04 20:03:11.203 UTC | 4 | 2013-10-22 11:41:59.717 UTC | null | null | null | null | 322,492 | null | 1 | 7 | json|jquery|getjson | 46,883 | <pre><code>success: function(responseData) {
for (var key in responseData) {
alert(responseData[key]);
}
}
</code></pre>
<p>It is important to note that the order in which the properties will be iterated is arbitrary and shouldn't be relied upon.</p> |
3,809,165 | Long-running computations in node.js | <p>I'm writing a game server in node.js, and some operations involve heavy computation on part of the server. I don't want to stop accepting connections while I run those computations -- how can I run them in the background when node.js doesn't support threads?</p> | 3,846,564 | 3 | 0 | null | 2010-09-28 01:55:06.837 UTC | 10 | 2010-10-06 21:42:02.04 UTC | null | null | null | null | 216,728 | null | 1 | 14 | multithreading|backgroundworker|node.js | 7,559 | <p>I can't vouch for either of these, personally, but if you're hell-bent on doing the work in-process, there have been a couple of independent implementations of the WebWorkers API for node, as listed on the node modules page:</p>
<ul><li>http://github.com/cramforce/node-worker</li>
<li>http://github.com/pgriess/node-webworker</li>
</ul>
<p>At first glance, the second looks more mature, and these would both allow you to essentially do threaded programming, but it's basically actor-model, so it's all done with message passing, and you can't have shared data structures or anything.</p>
<p>Also, for what it's worth, the node.js team intends to implement precisely this API natively, eventually, so these tools, even if they're not perfect, may be a decent stopgap.</p> |
3,881,209 | Keep absolute reference even when inserting rows in Excel 2007 | <p>I have a spreadsheet where I want cell formula to always look at a specific cell, even if rows or columns are inserted and the specific cell moves. Effectively, I always want to look at the 'top' cell of a table, even if new rows are inserted at the top of the table.</p>
<p>eg. Cell A2 has the formula[=$E$2]</p>
<p>Now I highlight row 1 and do Insert Row. The formula in A2 now says [=$E$3] but I want it to be looking at the new row 2.</p>
<p>The dollars will keep an absolute cell reference no matter what I do to the 'referencing' cell, but I want the cell reference to be absolute no matter what I do to the 'referenced' cell. If that makes sense!</p>
<p>Effectively, I have a 'table' in excel 2007 and I want to always reference the top row. The trouble is that rows are added to this table from the top so the top row keeps moving down to make room for a new top row.</p>
<p>--- Alistair.</p> | 3,886,284 | 3 | 0 | null | 2010-10-07 11:34:19.93 UTC | 1 | 2020-10-25 22:33:38.553 UTC | 2015-06-27 18:00:11.047 UTC | null | 9,117 | null | 41,013 | null | 1 | 14 | excel|reference | 65,982 | <p>Try <code>=indirect("F2")</code>. This will work if you know that the top-right cell of the table is always going to be <code>$F$2</code>.</p> |
3,735,836 | How can I install Perl modules without root privileges? | <p>I am on a Linux machine where I have no root privileges. I want to install some packages through CPAN into my home directory so that when I run Perl, it will be able to see it.</p>
<p>I ran <code>cpan</code>, which asked for some coniguration options. It asked for some directory, which it suggested <code>~/perl</code> "for non-root users". Still, when I try to install a package, it fails at the <code>make install</code> step, because I don't have write access to <code>/usr/lib/perl5/whatever</code>.</p>
<p>How can I configure CPAN so that I can install packages into my home directory?</p> | 3,735,909 | 3 | 3 | null | 2010-09-17 13:45:42.583 UTC | 20 | 2022-05-11 00:43:22.65 UTC | 2022-05-11 00:43:22.65 UTC | null | 2,766,176 | null | 294,813 | null | 1 | 43 | perl|module|cpan | 38,307 | <p>See <a href="http://search.cpan.org/perldoc/local::lib#The_bootstrapping_technique" rel="noreferrer">local::lib</a>.</p>
<p>Once you have it installed, you can do:</p>
<blockquote>
<p><code>perl -MCPAN -Mlocal::lib -e 'CPAN::install(LWP)'</code></p>
</blockquote> |
3,360,160 | How do I create an COM visible class in C#? | <p>I using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2010" rel="nofollow noreferrer">Visual Studio 2010</a> (.NET 4). I need to create a <a href="http://en.wikipedia.org/wiki/Component_Object_Model" rel="nofollow noreferrer">COM</a> object (in C#) and have no idea how to get started (what type of project to use,etc.)</p> | 3,362,624 | 3 | 4 | null | 2010-07-29 07:04:33.95 UTC | 35 | 2022-07-05 11:02:54.097 UTC | 2019-01-21 19:00:47.94 UTC | null | 3,195,477 | null | 405,349 | null | 1 | 48 | visual-studio-2010|c#-4.0|com | 92,558 | <p>OK I found the solution and I'll write it here for the common good.</p>
<ol>
<li>Start VS2010 as administrator.</li>
<li>Open a class library project (exmaple - MyProject).</li>
<li>Add a new interface to the project (see example below).</li>
<li>Add a <code>using System.Runtime.InteropServices;</code> to the file</li>
<li>Add the attributes InterfaceType, Guid to the interface.</li>
<li>You can generate a Guid using Tools->Generate GUID (option 4).</li>
<li>Add a class that implement the interface.</li>
<li>Add the attributes ClassInterface, Guid, ProgId to the interface.<br/>
ProgId convention is {namespace}.{class}</li>
<li>Under the Properties folder in the project in the AssemblyInfo file set ComVisible to true.</li>
<li>In the project properties menu, in the build tab mark "Register for COM interop"</li>
<li>Build the project</li>
</ol>
<p>now you can use your COM object by using it's ProgID.</p>
<p>example:
the C# code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Launcher
{
[InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")]
public interface ILauncher
{
void launch();
}
[ClassInterface(ClassInterfaceType.None), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYY"), ProgId("Launcher.Launcher")]
public class Launcher : ILauncher
{
private string path = null;
public void launch()
{
Console.WriteLine("I launch scripts for a living.");
}
}
}
</code></pre>
<p>and VBScript using the COM:</p>
<code>
set obj = createObject("PSLauncher.PSLauncher")
obj.launch()
</code>
<p>and the output will be:</p>
<p>I launch scripts for a living</p> |
22,944,063 | How do I add 1 hour to datetime SQL column data? | <p>I used this part of a query to create a table column for the date and time a row is added:</p>
<p><code>order_date datetime NOT NULL DEFAULT GETDATE()</code></p>
<p>and whenever a new row is created, the data for <code>order_date</code> is set to something like this:</p>
<p><code>Apr 8 2014 9:52AM</code></p>
<p>For some reason, when a row is created and the <code>order_date</code> column data is set, the hour is set 1 hour back. For example, the above column data for <code>Apr 8 2014 9:52AM</code> was set at 10:52AM. </p>
<p>Is there a way to set it 1 hour ahead so that it is correct with my current time?</p>
<p>Thank you for any help. All help is greatly appreciated.</p> | 22,944,217 | 2 | 6 | null | 2014-04-08 17:23:47.533 UTC | 2 | 2017-08-09 11:17:39.643 UTC | 2017-08-09 11:17:39.643 UTC | null | 2,004,562 | null | 2,888,761 | null | 1 | 11 | sql|sql-server|datetime|getdate|hour | 72,658 | <p>You should consider using <a href="http://msdn.microsoft.com/en-us/library/bb630289.aspx" rel="nofollow">DATETIMEOFFSET</a> as your daatype instead of DATETIME. </p>
<blockquote>
<p>Defines a date that is combined with a time of a day that has time
zone awareness and is based on a 24-hour clock.</p>
</blockquote>
<p>You can use it with <a href="http://technet.microsoft.com/en-us/library/bb677334.aspx" rel="nofollow">SYSDATETIMEOFFSET(</a>).</p>
<pre><code>Returns a datetimeoffset(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is included.
</code></pre>
<p>Example:</p>
<pre><code> CREATE TABLE DateTest (id INT, order_date DATETIMEOFFSET NOT NULL DEFAULT SYSDATETIMEOFFSET())
INSERT INTO DateTest (id) VALUES (1)
SELECT * FROM DateTest
</code></pre> |
22,725,537 | Using Java 8's Optional with Stream::flatMap | <p>The new Java 8 stream framework and friends make for some very concise Java code, but I have come across a seemingly-simple situation that is tricky to do concisely.</p>
<p>Consider a <code>List<Thing> things</code> and method <code>Optional<Other> resolve(Thing thing)</code>. I want to map the <code>Thing</code>s to <code>Optional<Other></code>s and get the first <code>Other</code>.</p>
<p>The obvious solution would be to use <code>things.stream().flatMap(this::resolve).findFirst()</code>, but <code>flatMap</code> requires that you return a stream, and <code>Optional</code> doesn't have a <code>stream()</code> method (or is it a <code>Collection</code> or provide a method to convert it to or view it as a <code>Collection</code>).</p>
<p>The best I can come up with is this:</p>
<pre><code>things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
</code></pre>
<p>But that seems awfully long-winded for what seems like a very common case.</p>
<p>Anyone have a better idea?</p> | 22,726,869 | 12 | 7 | null | 2014-03-29 00:42:01.5 UTC | 50 | 2022-05-17 06:59:48.06 UTC | 2022-05-17 06:59:48.06 UTC | null | 452,775 | null | 966,104 | null | 1 | 290 | java|lambda|java-8|java-stream | 218,604 | <h2>Java 9</h2>
<p><a href="https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream--" rel="noreferrer"><code>Optional.stream</code></a> has been added to JDK 9. This enables you to do the following, without the need of any helper method:</p>
<pre><code>Optional<Other> result =
things.stream()
.map(this::resolve)
.flatMap(Optional::stream)
.findFirst();
</code></pre>
<h2>Java 8</h2>
<p>Yes, this was a small hole in the API, in that it's somewhat inconvenient to turn an <code>Optional<T></code> into a zero-or-one length <code>Stream<T></code>. You could do this:</p>
<pre><code>Optional<Other> result =
things.stream()
.map(this::resolve)
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.findFirst();
</code></pre>
<p>Having the ternary operator inside the <code>flatMap</code> is a bit cumbersome, though, so it might be better to write a little helper function to do this:</p>
<pre><code>/**
* Turns an Optional<T> into a Stream<T> of length zero or one depending upon
* whether a value is present.
*/
static <T> Stream<T> streamopt(Optional<T> opt) {
if (opt.isPresent())
return Stream.of(opt.get());
else
return Stream.empty();
}
Optional<Other> result =
things.stream()
.flatMap(t -> streamopt(resolve(t)))
.findFirst();
</code></pre>
<p>Here, I've inlined the call to <code>resolve()</code> instead of having a separate <code>map()</code> operation, but this is a matter of taste.</p> |
22,566,307 | Javascript's equivalent of destruct in object model | <p>Since I've dealt in the past with javascript's funky "object model", I assume there is no such thing as a destructor. My searches were mildly unsuccessful, so you guys are my last hope. How do you execute stuff upon instance destruction?</p> | 22,566,518 | 4 | 11 | null | 2014-03-21 18:05:09.873 UTC | 3 | 2021-03-10 17:48:14.283 UTC | 2020-05-18 18:05:09.38 UTC | null | 2,415,293 | null | 2,415,293 | null | 1 | 50 | javascript|destructor | 66,918 | <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects" rel="noreferrer">MDN</a> is a nice resource for JS.
No, there is nothing like calling a function when an object ceases.</p> |
26,081,543 | How to tell at runtime whether an iOS app is running through a TestFlight Beta install | <p>Is it possible to detect at runtime that an application has been installed through TestFlight Beta (submitted through iTunes Connect) vs the App Store? You can submit a single app bundle and have it available through both. Is there an API that can detect which way it was installed? Or does the receipt contain information that allows this to be determined?</p> | 26,113,597 | 6 | 5 | null | 2014-09-28 04:12:11.497 UTC | 63 | 2022-04-04 18:14:22.983 UTC | 2014-09-30 05:48:58.823 UTC | null | 236,264 | null | 236,264 | null | 1 | 161 | ios|testflight | 34,089 | <p>For an application installed through TestFlight Beta the receipt file is named <code>StoreKit/sandboxReceipt</code> vs the usual <code>StoreKit/receipt</code>. Using <code>[NSBundle appStoreReceiptURL]</code> you can look for sandboxReceipt at the end of the URL.</p>
<pre><code>NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSString *receiptURLString = [receiptURL path];
BOOL isRunningTestFlightBeta = ([receiptURLString rangeOfString:@"sandboxReceipt"].location != NSNotFound);
</code></pre>
<p>Note that <code>sandboxReceipt</code> is also the name of the receipt file when running builds locally and for builds run in the simulator.</p>
<p>Swift Version:</p>
<pre class="lang-swift prettyprint-override"><code>let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
</code></pre> |
21,938,932 | How do I convert a numpy array into a pandas dataframe? | <p>I would like to have the 3 columns of a numpy array</p>
<pre><code>px[:,:,0]
px[:,:,1]
px[:,:,0]
</code></pre>
<p>into a pandas Dataframe.</p>
<p>Should I use?</p>
<pre><code>df = pd.DataFrame(px, columns=['R', 'G', 'B'])
</code></pre>
<p>Thank you</p>
<p>Hugo</p> | 21,940,107 | 1 | 6 | null | 2014-02-21 15:49:07.6 UTC | 6 | 2014-02-21 16:41:56.587 UTC | null | null | null | null | 678,321 | null | 1 | 16 | python|numpy|pandas | 57,186 | <p>You need to reshape your array first, try this:</p>
<pre><code>px2 = px.reshape((-1,3))
df = pd.DataFrame({'R':px2[:,0],'G':px2[:,1],'B':px2[:,2]})
</code></pre> |
11,013,237 | How to maximize and minimize a div | <p>How to maximize and minimize a div? Can I resize div according to as need?</p> | 11,013,402 | 1 | 4 | null | 2012-06-13 10:46:16.417 UTC | 4 | 2022-08-31 10:49:40.58 UTC | 2022-08-31 10:49:40.58 UTC | null | 4,370,109 | null | 1,453,372 | null | 1 | 9 | javascript|html | 47,575 | <p>I think you need something like this</p>
<p><a href="http://jsfiddle.net/miqdad/Qy6Sj/1/">http://jsfiddle.net/miqdad/Qy6Sj/1/</a></p>
<p>You can view the code in jsfiddle here is the code what I have done created a div with another div inside as title bar and content box</p>
<p><strong>html</strong></p>
<pre><code><div id="widnow">
<div id="title_bar">
<div id="button">-</div>
</div>
<div id="box">
</div>
</div>
</code></pre>
<p><strong>css</strong></p>
<pre><code>#widnow{
width:400px;
border:solid 1px;
}
#title_bar{
background: #FEFEFE;
height: 25px;
width: 100%;
}
#button{
border:solid 1px;
width: 25px;
height: 23px;
float:right;
cursor:pointer;
}
#box{
height: 250px;
background: #DFDFDF;
}
</code></pre>
<p><strong>jquery</strong></p>
<pre><code>$("#button").click(function(){
if($(this).html() == "-"){
$(this).html("+");
}
else{
$(this).html("-");
}
$("#box").slideToggle();
});
</code></pre> |
11,144,916 | Eclipse console shows:'Failed to push selection: Read-only file system'when i try to push a file | <p>I am trying to push a file to the SD Card but its showing error in console 'failed to push selection: Read-only file system'.I am using DDMS perspective in Eclipse.I generated sdcard using mksdcard command.</p> | 14,293,973 | 7 | 0 | null | 2012-06-21 18:57:11.213 UTC | 5 | 2014-11-04 15:07:53.48 UTC | 2013-11-08 17:23:36.267 UTC | null | 1,190,809 | null | 1,190,809 | null | 1 | 30 | android|eclipse|mobile|sd-card | 37,123 | <p>Just go to</p>
<p><code>C:\Documents and Settings\<adminstrator>\.android\avd</code></p>
<p>take <code>'properties'</code> of your avd folder (there is a folder for each of the avd's)</p>
<p>uncheck <code>'Read only'</code> -> OK</p>
<p>This was the only thing that worked for me.</p>
<p>P.S: Some of these folders might be hidden.</p> |
11,376,304 | Right way to write JSON deserializer in Spring or extend it | <p>I am trying to write a custom JSON deserializer in Spring. I want to use default serializer for most part of fields and use a custom deserializer for few properties. Is it possible?
I am trying this way because, most part of properties are values, so for these I can let Jackson use default deserializer; but few properties are references, so in the custom deserializer I have to query a database for reference name and get reference value from database.</p>
<p>I'll show some code if needed.</p> | 11,377,362 | 4 | 2 | null | 2012-07-07 15:36:20.747 UTC | 20 | 2021-09-22 13:37:37.23 UTC | 2017-03-10 17:15:57.143 UTC | null | 5,557,885 | null | 41,977 | null | 1 | 63 | java|json|spring|jackson|deserialization | 129,252 | <p>I've searched a lot and the best way I've found so far is on this <a href="https://www.sghill.net/how-do-i-write-a-jackson-json-serializer-deserializer.html" rel="noreferrer">article</a>:</p>
<p><strong>Class to serialize</strong></p>
<pre><code>package net.sghill.example;
import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
</code></pre>
<p><strong>Deserializer class</strong></p>
<pre><code>package net.sghill.example;
import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
public class UserDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
}
}
</code></pre>
<p>Edit:
Alternatively you can look at <a href="http://www.baeldung.com/jackson-deserialization" rel="noreferrer">this article</a> which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.</p> |
12,911,628 | Getting error : WebSphere MQ reason code 2538? | <p>I have WebSphere MQ and WebSphere Message Broker installed on Linux and when I execute <code>mqsicreateexecutiongroup</code> I get an error saying: </p>
<blockquote>
<p>BIP1046E: Unable to connect with the queue manager (Could not connect to queue manager 'NSPZPAI1' (MQ reason code 2538)). </p>
</blockquote>
<p>When I search for this reason code I understand that it is a <em>host not available error</em>.<br>
Can somebody please tell me how to resolve this error? </p>
<p>When I run a <code>runmqlsr</code> command I always end up in a hang. Can somebody tell me how to start a listener? </p> | 12,915,613 | 2 | 0 | null | 2012-10-16 09:34:11.407 UTC | 1 | 2012-10-16 13:43:55.243 UTC | 2012-10-16 13:13:33.407 UTC | null | 214,668 | null | 1,746,125 | null | 1 | 7 | ibm-mq|messagebroker | 57,406 | <p>Don't start the listener by hand or script. If you have a modern queue manager, define a listener object like so:</p>
<pre><code>DEF LISTENER(LISTENER.1414) TRPTYPE(TCP) +
CONTROL(QMGR) PORT(1414) +
REPLACE
START LISTENER(LISTENER.1414)
</code></pre>
<p>The attribute <code>CONTROL(QMGR)</code> tells the QMgr to start the listener automatically when the QMgr is started and to kill the listener when the QMgr is shut down. This ensures that the listener will always be started when the QMgr comes up, even if the QMgr is started manually instead of from the usual boot script. Because the listener is a child process of the QMgr it will <em>always</em> come down with the QMgr so you don't need to worry about orphaned listeners preventing connections after a QMgr restart.</p>
<p>Once the listener is defined, you can also use <code>START LISTENER</code> or <code>STOP LISTENER</code> MQSC commands to manually start and stop it independently of the QMgr. In the example above, I've manually started the listener rather than reboot the QMgr. Either would work but the <code>START</code> command is less intrusive.</p> |
12,901,734 | what is the advantage of Singleton Design Pattern | <p>every one know how to write code for Singleton Design Pattern.say for example</p>
<pre><code>public class Singleton
{
// Private static object can access only inside the Emp class.
private static Singleton instance;
// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}
// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
</code></pre>
<p>it is very clear that when we create a instance of any class many time the memory is allocated for each instance but in case of Singleton design pattern a single instance give the service for all calls.</p>
<p>1) i am bit confuse and really do nor realize that what are the reasons...that when one should go for Singleton Design Pattern. only for saving some memory or any other benefit out there.</p>
<p>2) suppose any single program can have many classes then which classes should follow the Singleton Design Pattern? what is the advantage of Singleton Design Pattern?</p>
<p>3 in real life apps when should one make any classes following Singleton Design Pattern?
thanks</p>
<h2>Here is thread safe singleton</h2>
<pre><code>public sealed class MultiThreadSingleton
{
private static volatile MultiThreadSingleton instance;
private static object syncRoot = new Object();
private MultiThreadSingleton()
{
}
public static MultiThreadSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MultiThreadSingleton();
}
}
}
return instance;
}
}
}
</code></pre> | 12,901,802 | 8 | 6 | null | 2012-10-15 18:27:16.267 UTC | 4 | 2021-08-15 08:19:28.43 UTC | 2012-10-16 05:21:50.86 UTC | null | 783,681 | null | 508,127 | null | 1 | 11 | c#|oop | 41,207 | <p>To assure only one and same instance of object every time.</p>
<p>Take a scenario, say for a Company application, there is only one CEO. If you want to create or access CEO object, you should return the same CEO object every time.</p>
<p>One more, after logging into an application, current user must return same object every time.</p> |
12,836,270 | MySQL trigger before Insert value Checking | <p>I have a table <code>staff</code> with <code>office</code> column. Currently the <code>office</code> column do not accept NULL values. The application persisting onto this table has a bug which meant that, when the staff has not been assigned an office, it tries inserting a NULL value onto the table.</p>
<p>I have been asked to used a trigger to intercept the insert onto the <code>Staff</code> table and check if the <code>office</code> value is NULL and replace it with value <code>N/A</code>. </p>
<p>Below is my attempt so far, but do have <code>error</code> in attempt to implement. Any Ideas on how to resolve this.</p>
<pre><code>CREATE TRIGGER staffOfficeNullReplacerTrigger BEFORE INSERT ON Staff
FOR EACH ROW BEGIN
IF (NEW.office IS NULL)
INSERT INTO Staff SET office="N/A";
END IF
END;
</code></pre>
<p><strong>The error:</strong></p>
<blockquote>
<p>MySQL Database Error: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'INSERT INTO Staff SET office="N/A"; END'</p>
</blockquote> | 12,837,521 | 3 | 1 | null | 2012-10-11 09:21:11.5 UTC | 4 | 2015-09-02 14:22:44.783 UTC | null | null | null | null | 340,390 | null | 1 | 16 | mysql|triggers | 51,964 | <p>First, alter the table to allow NULLs:</p>
<pre><code>ALTER TABLE Staff MODIFY office CHAR(40) DEFAULT "N/A";
</code></pre>
<p>(Change <code>CHAR(40)</code> to whatever is appropriate.) Then you could use as your trigger:</p>
<pre><code>CREATE TRIGGER staffOfficeNullReplacerTrigger
BEFORE INSERT
ON Staff
FOR EACH ROW BEGIN
IF (NEW.office IS NULL) THEN
SET NEW.office = "N/A";
END IF
</code></pre> |
12,694,162 | Windows authentication failing in IIS 7.5 | <p>I'm building a simple internal application for my company, and it requires Windows Authentication for security. All other authentication modes are disabled. I'm stuck in a situation where internet explorer prompts for credentials 3 times, then fails with this error:</p>
<blockquote>
<p>Not Authorized</p>
<p>HTTP Error 401. The requested resource requires user authentication.</p>
</blockquote>
<p>I then created a bare-bones website to test this out. I created a new site in IIS, put it on its own port (:8111, chosen at random), put one static "default.htm" file in there, disabled anonymous authentication, then enabled windows authentication. Everything else was left at default settings. The port number was assigned because we have multiple sites on this machine all sharing the same IP.</p>
<p>Here are a few scenarios:</p>
<ul>
<li><p>Browsing from the web server itself, to http://<strong>localhost</strong>:8111/ works
fine</p></li>
<li><p>Browsing from another computer, to http://<strong>ServerIPaddress</strong>:8111/
works fine</p></li>
<li><p>Browsing from another computer, to http://<strong>ServerName</strong>:8111/ FAILS
(asks for credentials 3 times, then gives 401 error)</p></li>
</ul>
<p>I've been searching online and trying to find a solution with no luck thus far. Either I haven't found it, or I don't understand well enough what I'm reading. Any help would be greatly appreciated.</p> | 12,695,809 | 5 | 0 | null | 2012-10-02 16:14:11.63 UTC | 10 | 2015-07-15 18:55:47.077 UTC | null | null | null | null | 641,985 | null | 1 | 25 | iis-7|windows-server-2008|windows-authentication | 49,432 | <p>Just worked out the solution with the help of a coworker after 2 days of fighting with this issue. Here is what he wrote:</p>
<blockquote>
<p>There are 2 providers for Windows Authentication (Negotiate and NTLM).
When setting the Website Authentication to Windows Authentication,
while Windows Authentication is highlighted, click on the Providers
link on the right pane or IIS Manager and move NTLM to the top. By
default Negotiate is on top which is why you are getting an
authentication prompt.</p>
</blockquote> |
12,745,186 | Passing parameters to a JDBC PreparedStatement | <p>I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of <code>firstName</code>, <code>lastName</code> and <code>userID</code> fields. Now I want to select a specific row on the database through my parameter of my constructor.</p>
<pre class="lang-java prettyprint-override"><code>import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class Validation {
private PreparedStatement statement;
private Connection con;
private String x, y;
public Validation(String userID) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
statement = con.prepareStatement(
"SELECT * from employee WHERE userID = " + "''" + userID);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
x = rs.getString(1);
System.out.print(x);
System.out.print(" ");
y = rs.getString(2);
System.out.println(y);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
</code></pre>
<p>But it doesn't seem work.</p> | 12,745,238 | 5 | 1 | null | 2012-10-05 11:21:49.63 UTC | 7 | 2020-08-19 10:47:23.467 UTC | 2020-08-19 10:47:23.467 UTC | null | 452,775 | null | 1,708,134 | null | 1 | 29 | java|mysql|jdbc | 142,247 | <p>You should use the <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setString%28int,%20java.lang.String%29" rel="noreferrer"><code>setString()</code></a> method to set the <code>userID</code>. This both ensures that the statement is formatted properly, and prevents <code>SQL injection</code>: </p>
<pre><code>statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
</code></pre>
<p>There is a nice tutorial on how to use <code>PreparedStatement</code>s properly in <a href="http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html" rel="noreferrer">the Java Tutorials</a>.</p> |
12,903,069 | Simple rails rake task refuse to run with error "Don't know how to build task", why? | <p>I have this simple rake task which refuses to run. I just don't see why it looks correct. Who can pinpoint me to the probably very simple mistake I made? Thank you!</p>
<p><strong>/lib/tasks/reindex.rb:</strong></p>
<pre><code>namespace :db do
desc "Tire reindex profiles"
task :reindex => :environment do
system "cd #{Rails.root} && rake environment tire:import CLASS='Profile' FORCE=true"
end
end
</code></pre>
<p><strong>The error:</strong></p>
<pre><code>rake db:reindex
rake aborted!
Don't know how to build task 'db:reindex'
</code></pre> | 12,903,234 | 5 | 0 | null | 2012-10-15 19:57:55.157 UTC | 3 | 2019-02-18 15:26:14.09 UTC | 2016-02-15 08:23:32.927 UTC | null | 1,052,068 | null | 355,281 | null | 1 | 49 | ruby-on-rails|rake|rake-task | 51,371 | <p>Rename your file to <code>reindex.rake</code> and it should work.</p>
<p>Related: <a href="https://stackoverflow.com/questions/5334520/dont-know-how-to-build-task-dbpopulate">How to build task 'db:populate'</a></p> |
12,777,751 | HTML required readonly input in form | <p>I'm making a form. And on one <code>input</code> tag is an <code>OnClick</code> event handler, which is opening a popup, where you can choose some stuff, and then it autofills the <code>input</code> tag.</p>
<p>That input tag is also <code>readonly</code>, so only right data will be entered.</p>
<p>This is the code of the <code>input</code> tag:</p>
<pre><code><input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
</code></pre>
<p>But the <code>required</code> attribute isn't working in Chrome. But the field is required.</p>
<p>Does anybody know how I can make it work?</p> | 25,694,734 | 13 | 4 | null | 2012-10-08 08:17:46.47 UTC | 13 | 2021-02-17 06:20:10.897 UTC | 2012-10-08 08:46:26.83 UTC | null | 1,419,007 | null | 1,175,881 | null | 1 | 57 | forms|html|google-chrome|readonly|required-field | 79,015 | <p>I had same requirement as yours and I figured out an easy way to do this.
If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jQuery this way:</p>
<p><strong>IMPROVED</strong></p>
<p>form the suggestions in comments</p>
<pre><code><input type="text" class="readonly" autocomplete="off" required />
<script>
$(".readonly").on('keydown paste focus mousedown', function(e){
if(e.keyCode != 9) // ignore tab
e.preventDefault();
});
</script>
</code></pre>
<p>Credits: @Ed Bayiates, @Anton Shchyrov, @appel, @Edhrendal, @Peter Lenjo</p>
<p><strong>ORIGINAL</strong></p>
<pre><code><input type="text" class="readonly" required />
<script>
$(".readonly").keydown(function(e){
e.preventDefault();
});
</script>
</code></pre> |
16,823,790 | Android Studio don't know where is Java | <p>I am getting this error:</p>
<blockquote>
<p>Cannot run program "/usr/lib/jvm/java-1.7.0-openjdk-i386/bin/java" (in directory "/home/sergiy/.AndroidStudioPreview/system/compile-server"): error=2, No such file or directory</p>
</blockquote>
<p>This happens after i remove all JDK (Open and other). Some time before I installed Oracle JDK from official site. So, new folder of JDK named jdk1.7.0.</p>
<pre><code>JAVA_HOME=/usr/lib/jvm/jdk1.7.0
JDK_HOME=/usr/lib/jvm/jdk1.7.0
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) Server VM (build 23.21-b01, mixed mode)
</code></pre>
<p>Android studio starts without any errors. I think that a must rename path to JDK in Android studio? But how?</p> | 16,824,891 | 2 | 5 | null | 2013-05-29 21:06:37.897 UTC | 2 | 2015-12-13 13:12:16.84 UTC | 2015-06-28 13:34:04.207 UTC | null | 472,495 | null | 1,589,840 | null | 1 | 30 | java|android|ubuntu|android-studio | 46,901 | <p>All done! I find it in File->Other Settings->Default Project Structure->SDKs. There I change JDK home path.</p> |
16,945,519 | When to use RedirectToAction and where to use RedirectToRouteResult? | <h2><strong>Question</strong></h2>
<p>In which context, I can use <code>RedirectToAction</code> and where to use <code>RedirectToRouteResult</code> ?</p>
<p>I have two Action Methods like below.</p>
<h2><strong>Approach - 1</strong></h2>
<pre><code>public class ActionResultTypesController : Controller
{
public ActionResult Content()
{
return new RedirectToRouteResult(new RouteValueDictionary(
new { action = "Fileresult", controller = "ActionResultTypes" }));
}
public ActionResult Fileresult()
{
return View();
}
}
</code></pre>
<h2><strong>Approach - 2</strong></h2>
<p>I could write the same code like below as well. The only difference is that this time I used <code>RedirectToAction</code> in place of <code>RedirectToRouteResult</code></p>
<pre><code>public class ActionResultTypesController : Controller
{
public ActionResult Content()
{
return RedirectToAction("Fileresult", "ActionResultTypes");
}
public ActionResult Fileresult()
{
return View();
}
}
</code></pre>
<h2><strong>Both piece of code have common Resultant</strong></h2> | 16,948,815 | 3 | 1 | null | 2013-06-05 16:46:56.073 UTC | 7 | 2015-02-03 10:28:59.57 UTC | 2013-06-15 13:19:16.757 UTC | null | 727,208 | null | 2,445,839 | null | 1 | 38 | asp.net-mvc|asp.net-mvc-4 | 46,758 | <p>There isn't much difference between the two when using within the controller like you have in your example. </p>
<p>They both ultimately achieve the same goal. However, RedirectToRouteResult() is mostly used in an action filter type scenario <a href="https://stackoverflow.com/questions/5904976/how-do-i-redirect-user-to-another-controller-action-from-an-asp-mvc-3-action-fil">seen here.</a> It's a little less friendly on the eyes when just using in your actions on controllers.</p>
<p>Both can achieve the same goal. The questions you need to ask yourself in most scenarios are really:</p>
<ol>
<li>Do I need the permanent redirect flag when using RedirectToRouteResult()?</li>
<li>Do I want to write the extra code when using RedirectToRouteResult()?</li>
</ol>
<p>If your answer is no or I don't know,
</p>
<pre><code>RedirectToAction("Action", "Controller", new { parameter = value });
</code></pre>
<p>is probably your best bet!</p>
<p><strong>EDIT:</strong></p>
<p>Here's some light on what <code>RedirectToRouteResult</code> is.</p>
<p><a href="http://books.google.com/books?id=ZscWT8HzDVAC&pg=PT494&lpg=PT494&dq=RedirectToRouteResult.Permanent?&source=bl&ots=GrFt5tRIn0&sig=j_z_oH_GoB9_PDUGT4teVUYL-ag&hl=en&sa=X&ei=qaawUcfMLMa9yAHcyoGYCQ&ved=0CFkQ6AEwBQ" rel="noreferrer">Reference to some MVC Redirects.</a></p>
<p>In this you will notice that <code>RedirectToRouteResult</code> is not something that you would normally call to return in an action. It is used as a return type for multiple <code>RedirectToRoute</code> calls. For instance, there are 2 calls you will see in that book. <code>RedirectToRoute</code> and <code>RedirectToRoutePermanent</code>. </p>
<p>They both return <code>RedirectToRouteResult</code> except, <code>RedirectToRoutePermanent</code> returns the result with the permanent redirect bool <code>true</code>. This returns a <code>HTTP 301 status code</code>.</p>
<p>Hope this helps!</p> |
17,120,513 | PhpStorm debugger not stopping at BreakPoints; keeps waiting for xdebug _SESSION_ | <p><a href="https://stackoverflow.com/questions/17130931/phpstorm-webmatrix-iisexpress-xdebug-remote-port-which-ports-to-put">Updated question : PhpStorm | WebMatrix (IISExpress) | Xdebug.remote_port | — Which Port(s) to put where?</a></p>
<hr>
<p>I'm running localhost web server on my Windows machine with WebMatrix and IISExpress. I've installed PHP and Xdebug in it and they both are working.</p>
<p>I have a local WordPress install.</p>
<p>I'm now trying to get PhpStorm to debug it using Xdebug.</p>
<p>When I run PhpStorm it launches the web app in the browser with relevant debugging parameters in the browser.</p>
<p><strong>IDE KEY is matching</strong></p>
<p><img src="https://i.stack.imgur.com/ozmI5.png" alt="ide"></p>
<p><code>xdebug.remote_port</code> is configured correctly. (Later I found that this is wrong, but not erroneous. It should be port 9000)</p>
<p><img src="https://i.stack.imgur.com/Wijaa.png" alt="xdebug.remote_port"> </p>
<p>But it seems Xdebug never gets to communicate with PhpStorm. PhpStorm keeps listening, and the execution runs completely without stopping at any break-points.</p>
<p><img src="https://i.stack.imgur.com/NIyi8.png" alt="PhpStorm">
<img src="https://i.stack.imgur.com/58WCC.png" alt="PhpStorm"></p> | 28,309,951 | 16 | 14 | null | 2013-06-15 05:31:49.87 UTC | 12 | 2022-01-19 10:00:21.693 UTC | 2017-05-23 12:34:19.983 UTC | null | -1 | null | 1,266,650 | null | 1 | 50 | php|xdebug|phpstorm | 44,367 | <p>There was a syntax error in <code>php.ini</code>. There were extra <code>"</code>quotes<code>"</code> and <code>;</code>colons<code>;</code>.</p>
<p><img src="https://i.stack.imgur.com/Wijaa.png" alt="xdebug.remote_port"></p> |
17,046,518 | Comment out text in R Markdown (Rmd file) | <p>In an R Markdown (<code>.Rmd</code>) file, how do you comment out unused text? I'm not referring to the text in the R code chunk, but the general texts, like <strong>%</strong> in <strong>LaTex</strong> for example.</p> | 17,047,124 | 4 | 1 | null | 2013-06-11 14:24:00.243 UTC | 18 | 2021-05-13 07:57:50.04 UTC | 2018-10-11 08:53:25.443 UTC | null | 1,981,275 | null | 2,474,891 | null | 1 | 137 | r-markdown|knitr | 92,181 | <p>I think you should be able to use regular html comments:</p>
<pre><code><!-- regular html comment -->
</code></pre>
<p>Does this work for you?</p> |
62,815,733 | Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. How to refactor and reduce the complexity | <p>how to reduce the complexity of the given piece of code? I am getting this error in Sonarqube---> Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.</p>
<pre><code>this.deviceDetails = this.data && {...this.data.deviceInfo} || {};
if (this.data && this.data.deviceInfo) {
this.getSessionInfo();
// tslint:disable-next-line: no-shadowed-variable
const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
this.deviceDetails = {
name: device.name || '',
manufacturer: device.manufacturer || '',
deviceType: device.deviceType || '',
model: device.model || '',
description: device.description || '',
managerId: device.deviceManager && device.deviceManager.managerId || null,
locationId: device.location && device.location.locationId || null,
active: device.active,
connectionType: connectionType || null,
driver_id: driver && driver.driverId || null,
ipAddress: ipAddress || '',
port: String(port) || '',
connectionStatus: active,
};
this.oldDeviceDetails = {...this.deviceDetails};
this.deviceLocation = device.location && device.location.locationId || null;
} else {
</code></pre> | 62,867,219 | 3 | 1 | null | 2020-07-09 13:15:12.807 UTC | 2 | 2022-09-01 16:54:50.313 UTC | 2022-06-04 06:09:10.273 UTC | null | 201,303 | null | 8,118,685 | null | 1 | 12 | javascript|angular|sonarqube|karma-jasmine|sonarlint | 76,007 | <p><strong>A little information on how cognitive complexity works and why you should keep it low</strong></p>
<p>First of all it is important to understand how "<em>Cognitive Complexity</em>" works as compared to "<em>Cyclomatic Complexity</em>". Cognitive complexity takes into account the complexity perceived by the human brain. This is why it does not simply indicate the number of conditional paths (simplified the number of conditionals plus 1 for the return statement).</p>
<p>The <strong>cognitive complexity</strong> metric also <strong>considers nested conditions</strong> (e.g. an if inside an if, inside an if statement) which makes it even harder to read and understand the code from a human's perspective.</p>
<p>The following sample from the SonarQube documentation (<a href="https://www.sonarsource.com/docs/CognitiveComplexity.pdf" rel="nofollow noreferrer">https://www.sonarsource.com/docs/CognitiveComplexity.pdf</a>) outlines what I'm trying to explain:</p>
<pre><code>if (someVariableX > 3) { // +1
if (someVariableY < 3) { // +2, nesting = 1
if (someVariableZ === 8) { // +3, nesting = 2
someResult = someVariableX + someVariableY - someVariableZ;
}
}
}
</code></pre>
<p>So be aware that binary operations add to the complexity but nested conditions even add an extra score of plus 1 for each nested condition. Here the cognitive complexity would be 6, while the cyclomatic complexity would only be 4 (one for each conditional and one for the return path);</p>
<p>If you make your code more readable for a human, e.g. by extracting methods from lines that contain conditionals you achieve both, better readability and less complexity.</p>
<p>Although the code you provided does not have nested conditionals I think it is important to first understand how cyclomatic and cognitive complexity calculation works and why it is a good idea to keep it low.</p>
<p><strong>[TL;DR] A possible approach to refactor your code into a less complex and better readable version</strong></p>
<p>Let's first look how the complexity calcuation is done for your code as outlined by the comments:</p>
<pre><code>this.deviceDetails = this.data && { ...this.data.deviceInfo } || {}; // +2
if (this.data && this.data.deviceInfo) { // +1 for the if condition, +1 for the binary operator
this.getSessionInfo();
const { device, driver, ipAddress, port, active, connectionType } =
this.data.deviceInfo;
this.deviceDetails = {
name: device.name || '', // +1 for the binary operator
manufacturer: device.manufacturer || '', // +1 for the binary operator
deviceType: device.deviceType || '', // +1 for the binary operator
model: device.model || '', // +1 for the binary operator
description: device.description || '', // +1 for the binary operator
managerId: device.deviceManager && device.deviceManager.managerId || null, // +2 for the varying binary operators
locationId: device.location && device.location.locationId || null, // +2 for the varying binary operator
active: device.active,
connectionType: connectionType || null, // +1 for the binary operator
driver_id: driver && driver.driverId || null, // +2 for the varying binary operator
ipAddress: ipAddress || '', // +1 for the binary operator
port: String(port) || '', // +1 for the binary operator
connectionStatus: active,
};
this.oldDeviceDetails = { ...this.deviceDetails };
this.deviceLocation = device.location && device.location.locationId || null; // +2 for the varying binary operator
} else { // +1 for the else path
// some statement
}
</code></pre>
<p>So assuming my math is correct, this sums up to the cognitive complexity of 21 as reported by SonarQube.</p>
<p>The following code sample shows how your code can be refactored to a version which should <strong>lower the cognitive complexity down to 12</strong>. (Please be aware that this is just a manual calculation.)</p>
<p>It can be done by applying <em>simple refactorings</em> such as <em><strong>extract method</strong></em> and/or move method (see also Martin Fowler, <a href="https://refactoring.com/catalog/extractFunction.html" rel="nofollow noreferrer">https://refactoring.com/catalog/extractFunction.html</a>).</p>
<pre><code>this.deviceDetails = getDeviceInfo();
if (deviceInfoAvailable()) { // +1 for the if statement
this.getSessionInfo();
// tslint:disable-next-line: no-shadowed-variable
const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
this.deviceDetails = {
name: getInfoItem(device.name),
manufacturer: getInfoItem(device.manufacturer),
deviceType: getInfoItem(device.deviceType),
model: getInfoItem(device.model),
description: getInfoItem(device.description),
managerId: getManagerId(device),
locationId: getDeviceLocation(device),
active: device.active,
connectionType: getInfoItem(connectionType, null),
driver_id: getDriverId(driver),
ipAddress: getInfoItem(ipAddress),
port: getInfoItem(port),
connectionStatus: active,
};
this.oldDeviceDetails = { ...this.deviceDetails };
this.deviceLocation = getDeviceLocation(device);
} else { // +1 for the else
// some statement
}
function getDeviceInfo()
{
return this.data && { ...this.data.deviceInfo } || {}; // +2
}
function getDriverId(driver) {
return driver && driver.driverId || null; // +2 for the binary operators
}
function getDeviceLocation(device) {
return device.location && device.location.locationId || null; // +2 for the binary operators
}
function getManagerId(device) {
return device.deviceManager && device.deviceManager.managerId || null; // +2 for the binary operators
}
function deviceInfoAvailable() {
return this.data && this.data.deviceInfo; // +1 for the binary operator
}
function getInfoItem(infoItem, defaultValue = '') {
return infoItem || defaultValue; // +1 for the binary operator
}
</code></pre>
<p>With the simple extract method refactorings <strong>lots of duplications</strong> (see getInfoItem() function) <strong>got eliminated</strong> as well which <em>makes it easy to reduce the complexity and increase the readability</em>.</p>
<p>To be honest, I would even go some steps further and restructure your code even more so that the logic for checking for empty items and setting a default value (here an empty string) when providing the device details is done by the device class or a device details class itself to have better cohesion of the data and the logic that operates on that data. But as I don't know the rest of the code this inital refactoring should get you one step further to better readability and less complexity.</p>
<p><em><strong>Note</strong></em>: We could even go one step further and perform a so called <em><a href="https://refactoring.guru/replace-nested-conditional-with-guard-clauses" rel="nofollow noreferrer">Replace Nested Conditional with Guard Clauses</a></em> refactoring (sometimes also referred to as "<em>early return</em>" or "<em>invert if statement</em>).</p>
<p>This could result in the code shown below and further reduce the cognitive complexity by one due to the <em><strong>elimination of the else statement</strong></em>, resulting in a final cognitive complexity of <strong>11</strong>. The extracted functions are the same and therefore not listed again here...</p>
<pre><code>this.deviceDetails = getDeviceInfo();
if (deviceInfoAvailable()) { // +1 for the if statement
// some statement
return; // return the same way as in the eliminated else clause
}
this.getSessionInfo();
const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
this.deviceDetails = {
name: getInfoItem(device.name),
manufacturer: getInfoItem(device.manufacturer),
deviceType: getInfoItem(device.deviceType),
model: getInfoItem(device.model),
description: getInfoItem(device.description),
managerId: getManagerId(device),
locationId: getDeviceLocation(device),
active: device.active,
connectionType: getInfoItem(connectionType, null),
driver_id: getDriverId(driver),
ipAddress: getInfoItem(ipAddress),
port: getInfoItem(port),
connectionStatus: active,
};
this.oldDeviceDetails = { ...this.deviceDetails };
this.deviceLocation = getDeviceLocation(device);
</code></pre> |
10,202,427 | SELECT MySQL rows where today's date is between two DATE columns | <p>How can I get the rows in a table where today's date is between (inclusive) two DATE columns of that row?
For example, take these two columns of a table:</p>
<p><img src="https://i.stack.imgur.com/vVe8M.png" alt="enter image description here"></p>
<p>How could I get the first and second rows on the 10th of April, or the 3rd row on the 25th (inclusive, like I said)?</p>
<p>Any help would be greatly appreciated. Thanks in advance!</p> | 10,202,530 | 4 | 2 | null | 2012-04-18 03:36:58.29 UTC | 6 | 2020-11-09 08:38:53.607 UTC | null | null | null | null | 492,025 | null | 1 | 18 | mysql|select | 49,170 | <p>You will find a lot of people using between operator, but I prefer using a simple AND operator. </p>
<p>I do that because although the between operator IS inclusive, simple dates (2012-04-10) can be counted as being midnight, and will thus not be inclusive.</p>
<p>So this should work just fine and will always include the boundaries of the date range:</p>
<pre><code>SELECT * FROM table WHERE from_date <= '2012-04-10' AND to_date >= '2012-04-10'
</code></pre> |
9,989,414 | How to create a String with carriage returns? | <p>For a JUnit test I need a String which consists of multiple lines. But all I get is a single lined String. I tried the following:</p>
<pre><code> String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
</code></pre>
<p>I also tried <code>\n\r</code> instead of <code>\n</code>. System.getProperty("line.separator") doesn't work too. it produces a <code>\n</code> in String and no carriage return. So how can I solve that?</p> | 9,989,790 | 6 | 4 | null | 2012-04-03 08:08:02.647 UTC | 4 | 2016-03-22 20:06:28.42 UTC | null | null | null | null | 319,773 | null | 1 | 21 | java|string | 138,708 | <p>Thanks for your answers. I missed that my data is stored in a <code>List<String></code> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.</p> |
9,752,760 | Slide Toggle for Android | <p>Anyone know of any open source implementation of a slide toggle for android. The default android toggle(<a href="http://developer.android.com/reference/android/widget/ToggleButton.html" rel="noreferrer">ToggleButton</a>) is not pretty. I am looking for anything similar to iOS. I should be able to implement one from scratch. But if anything similar is already available, then i can build on it.</p>
<p>Thanks in advance to the wonderful stackoverflow community.</p>
<p><strong>Edit1:</strong>
What I meant by iOS Slide Toggle is UISwitch</p>
<p><img src="https://i.stack.imgur.com/FQYQ6.png" alt="ios Toggle Button"></p>
<p><br>
<br>
<strong>Edit2:</strong> Just want to summarize the answer. Commonsware provided the clue. I ended up back porting the <em>Switch</em> code from 4.0 to2.2.2. Thanks to the open-sourced code, back porting was not very difficult. The code is hosted on git hub. <a href="http://github.com/pellucide/Android-Switch-Demo-pre-4.0/tree/master/" rel="noreferrer">http://github.com/pellucide/Android-Switch-Demo-pre-4.0/tree/master/</a> <br></p>
<p>A screenshot from that project <br>
<img src="https://raw.github.com/pellucide/Android-Switch-Demo-pre-4.0/master/android-switch-demo/Screenshot.png" alt="Screen shot"></p> | 9,752,821 | 4 | 7 | null | 2012-03-17 18:45:38.557 UTC | 12 | 2021-08-14 21:17:32.233 UTC | 2012-10-09 04:46:15.193 UTC | null | 892,771 | null | 892,771 | null | 1 | 30 | android | 48,031 | <p>iOS does not seem to have a "slide toggle", at least under that name, based on a Google search. And, you did not provide an image (or a link to an image) of what you want.</p>
<p>Android 4.0 added a <a href="http://developer.android.com/reference/android/widget/Switch.html" rel="noreferrer"><code>Switch</code></a> that you might be able to backport to earlier versions. You will see samples of it in the API Demos app on your emulator:</p>
<p><img src="https://i.stack.imgur.com/cNNWp.png" alt="enter image description here"></p> |
9,914,816 | What is an example of the simplest possible Socket.io example? | <p>So, I have been trying to understand Socket.io lately, but I am not a supergreat programmer, and almost every example I can find on the web (believe me I have looked for hours and hours), has extra stuff that complicates things. A lot of the examples do a bunch of things that confuse me, or connect to some weird database, or use coffeescript or tons of JS libraries that clutter things up.</p>
<p>I'd love to see a basic, functioning example where the server just sends a message to the client every 10 seconds, saying what time it is, and the client writes that data to the page or throws up an alert, something very simple. Then I can figure things out from there, add stuff I need like db connections, etc. And yes I have checked the examples on the socket.io site and they don't work for me, and I don't understand what they do.</p> | 9,916,153 | 5 | 2 | null | 2012-03-28 20:03:53.31 UTC | 70 | 2020-01-27 14:06:53.887 UTC | null | null | null | null | 276,399 | null | 1 | 124 | node.js|socket.io | 174,538 | <p><strong>Edit:</strong> I feel it's better for anyone to consult the excellent <a href="http://socket.io/get-started/chat/" rel="noreferrer">chat example</a> on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.</p>
<p>Just because I feel nice today:</p>
<h1>index.html</h1>
<pre><code><!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
</code></pre>
<h1>app.js</h1>
<pre><code>var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);
</code></pre> |
11,528,845 | How do I style the alert box with CSS? | <p>-- Update --i have read a lot on the subject tried a few scripts and needed help to find out what you can or cant do. Community answered it all and the following is a good starting point. (answers here extracted from community below, thank you)</p>
<ol>
<li><p>YOU CAN NOT OVERIDE DEFAULT STYLE OF ALERT. It is produced by your client (eg. chrome firefox etc)</p></li>
<li><p>you can use jquery instead. Instead of using a script like:</p>
<p>function check_domain_input() {
var domain_val = document.getElementsByName('domain');
if (domain_val[0].value.length > 0) {
return true;
}
alert('Please enter a domain name to search for.');
return false;
}</p></li>
</ol>
<p>which makes the client (firefox chrome etc) produce an alert box.</p>
<p>2b. You tell the code if somethings needs to happen on a event load jquery alertbox which you can make pretty: (Answered by Jonathan Payne and created by Jonathan Payne. Thank you)</p>
<pre><code><link rel="stylesheet" href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" type="text/css" media="all" />
<div onclick="check_domain_input()">Click</div>
<div id="dialog" title="Attention!" style="display:none">
Please enter a domain name to search for.
</div>
<script>
function check_domain_input()
{
$( "#dialog" ).dialog(); // Shows the new alert box.
var domain_val = document.getElementsByName('domain');
if (domain_val[0].value.length > 0)
{
return true;
}
$( "#dialog" ).dialog();
return false;
}
</script>
</code></pre>
<p>Check out the jsFiddle here: <a href="http://jsfiddle.net/8cypx/12/" rel="nofollow">http://jsfiddle.net/8cypx/12/</a></p> | 11,528,905 | 5 | 5 | null | 2012-07-17 18:43:20.327 UTC | 2 | 2020-12-30 12:05:44.05 UTC | 2012-07-17 21:46:00.17 UTC | null | 1,460,917 | null | 1,460,917 | null | 1 | 7 | jquery|css | 49,009 | <p>Try <code>jQuery UI</code> located here: <a href="http://jqueryui.com/demos/dialog/" rel="noreferrer">http://jqueryui.com/demos/dialog/</a></p>
<p>They have a theme roller where you can style the dialog and modal boxes.</p>
<p>-- EDIT --</p>
<p>Answering your second question.</p>
<p>Check out the jsFiddle here: <a href="http://jsfiddle.net/8cypx/12/" rel="noreferrer">http://jsfiddle.net/8cypx/12/</a></p>
<pre><code><link rel="stylesheet" href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" type="text/css" media="all" />
<div onclick="check_domain_input()">Click</div>
<div id="dialog" title="Attention!" style="display:none">
Please enter a domain name to search for.
</div>
<script>
function check_domain_input()
{
$( "#dialog" ).dialog(); // Shows the new alert box.
var domain_val = document.getElementsByName('domain');
if (domain_val[0].value.length > 0)
{
return true;
}
$( "#dialog" ).dialog();
return false;
}
</script>
</code></pre>
<p></p> |
11,871,120 | Java time since the epoch | <p>In Java, how can I print out the time since the epoch given in seconds and nanoseconds in the following format :</p>
<pre><code>java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
</code></pre>
<p>My input is:</p>
<pre><code>long mnSeconds;
long mnNanoseconds;
</code></pre>
<p>Where the total of the two is the elapsed time since the epoch <code>1970-01-01 00:00:00.0</code>.</p> | 11,871,217 | 6 | 1 | null | 2012-08-08 18:46:50.68 UTC | 1 | 2019-05-26 20:55:30.067 UTC | 2016-07-24 05:50:39.31 UTC | null | 1,276,636 | null | 1,585,643 | null | 1 | 15 | java|time|simpledateformat|epoch | 58,308 | <p>You can do this</p>
<pre><code>public static String format(long mnSeconds, long mnNanoseconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.");
return sdf.format(new Date(mnSeconds*1000))
+ String.format("%09d", mnNanoseconds);
}
</code></pre>
<p>e.g.</p>
<pre><code>2012-08-08 19:52:21.123456789
</code></pre>
<hr>
<p>if you don't really need any more than milliseconds you can do</p>
<pre><code>public static String format(long mnSeconds, long mnNanoseconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return sdf.format(new Date(mnSeconds*1000 + mnNanoseconds/1000000));
}
</code></pre> |
11,713,306 | How can I remove children in jQuery? | <p>In the following example</p>
<p><a href="http://jsfiddle.net/pDsGF/" rel="noreferrer">http://jsfiddle.net/pDsGF/</a></p>
<p>I want to remove just class 'child' from class 'parent'. I have tried</p>
<p><code>.remove($('parent').children('child'))</code></p>
<p>But it doesn't work</p> | 11,713,330 | 5 | 1 | null | 2012-07-29 21:56:29.513 UTC | 2 | 2017-11-23 14:00:07.997 UTC | null | null | null | null | 1,011,816 | null | 1 | 19 | jquery | 59,947 | <p>You need periods to get elements by class, for one. For two, that syntax isn't correct.</p>
<pre><code>$('.parent .child').remove();
</code></pre>
<p><a href="http://jsfiddle.net/pDsGF/4/">Here's a demo.</a></p> |
11,475,970 | Recover sa password | <p>I have a computer which was used by another employee.</p>
<p>SQL Server 2008 R2 was installed but I don't know the 'sa' password.</p>
<p>When I try to alter the login, it gives below error.</p>
<blockquote>
<p>Cannot alter the login 'sa', because it does not exist or you do not have permission.</p>
</blockquote>
<p>When I try to restore a database, it gives a different permission error.</p>
<p>(When I enter the Security --> Logins --> sa --> Properties
windows authentication is disabled.)</p>
<p>Can I change it?</p>
<p>P.S: Password is not "password" :)</p> | 11,476,059 | 2 | 1 | null | 2012-07-13 18:09:30.33 UTC | 8 | 2021-12-28 02:27:09.337 UTC | 2012-07-13 18:18:15.137 UTC | null | 61,305 | null | 1,514,165 | null | 1 | 37 | sql|sql-server-2008-r2 | 151,265 | <p>The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).</p>
<p>If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:</p>
<ul>
<li><a href="https://web.archive.org/web/20191007012923/https://blogs.msdn.microsoft.com/raulga/2007/07/13/disaster-recovery-what-to-do-when-the-sa-account-password-is-lost-in-sql-server-2005/" rel="nofollow noreferrer">Disaster Recovery: What to do when the SA account password is lost in SQL Server 2005</a></li>
<li><a href="https://stackoverflow.com/questions/196150/is-there-a-way-i-can-retrieve-sa-password-in-sql-server-2005">Is there a way I can retrieve sa password in sql server 2005</a></li>
<li><a href="http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/" rel="nofollow noreferrer">How to recover SA password on Microsoft SQL Server 2008 R2</a></li>
</ul>
<p>Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.</p>
<p>You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).</p>
<p>As an aside, the login properties for <code>sa</code> would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.</p>
<p>I wrote a tip on using <a href="http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx" rel="nofollow noreferrer">PSExec</a> to connect to an instance using the <code>NT AUTHORITY\SYSTEM</code> account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):</p>
<ul>
<li><a href="http://www.mssqltips.com/sqlservertip/2682/recover-access-to-a-sql-server-instance/?utm_source=AaronBertrand" rel="nofollow noreferrer">Recover access to a SQL Server instance</a></li>
<li><a href="https://www.mssqltips.com/sqlservertip/4672/more-on-recovering-access-to-a-sql-server-instance/?utm_source=AaronBertrand" rel="nofollow noreferrer">More on Recovering Access to a SQL Server Instance</a></li>
</ul>
<p>And some other resources:</p>
<ul>
<li><p><a href="https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out" rel="nofollow noreferrer">Connect to SQL Server When System Administrators Are Locked Out</a></p>
</li>
<li><p><a href="https://www.0xsql.com/2012/01/12/leveraging-service-sids-to-logon-to-sql-server-2012-2014-and-new-2016-instances-with-sysadmin-privileges/" rel="nofollow noreferrer">Leveraging Service SIDs to Logon to SQL Server Instances with Sysadmin Privileges</a></p>
</li>
</ul> |
11,601,692 | MySQL/Amazon RDS error: "you do not have SUPER privileges..." | <p>I'm attempting to copy my mysql database from an Amazon EC2 to an RDS:</p>
<p>I successfully did a <code>mysqldump</code> of my database into my root folder using this:</p>
<pre><code>root@ip-xx-xx-xx-xx:~# mysqldump my_database -u my_username -p > my_database.sql
</code></pre>
<p>Then I tried to transfer this .sql file to my new RDS database:</p>
<pre><code>root@ip-xx-xx-xx-xx:~# mysql my_database -u my_username -p -h
my_new_database.xxxxxxxxx.us-east-1.rds.amazonaws.com < my_database.sql
</code></pre>
<p>Unfortunately, I get following error message:</p>
<pre><code>You do not have the SUPER privilege and binary logging is enabled
(you *might* want to use the less safe log_bin_trust_function_creators variable)
</code></pre>
<p>I tried to <code>GRANT SUPER..</code> in a variety of ways but I'm getting errors when I try to do that too. Typing <code>mysql > FLUSH privileges;</code> doesn't work either. </p>
<p>I'm a mysql beginner so sorry for such an easy question. Thoughts?</p> | 11,603,568 | 8 | 2 | null | 2012-07-22 15:49:44.71 UTC | 31 | 2022-04-08 15:28:06.263 UTC | 2020-06-15 02:10:16.7 UTC | null | 6,632,744 | null | 702,275 | null | 1 | 122 | mysql|amazon-ec2|amazon-web-services|amazon-rds|sql-grant | 122,086 | <p>Per <a href="http://getasysadmin.com/2011/06/amazon-rds-super-privileges/">http://getasysadmin.com/2011/06/amazon-rds-super-privileges/</a>, you need to set <code>log_bin_trust_function_creators</code> to 1 in <a href="https://console.aws.amazon.com/rds/">AWS console</a>, to load your dump file without errors.</p>
<p>If you want to ignore these errors, and load the rest of the dump file, you can use the <code>-f</code> option:</p>
<pre><code>mysql -f my_database -u my_username -p -h
my_new_database.xxxxxxxxx.us-east-1.rds.amazonaws.com < my_database.sql
</code></pre>
<p>The <code>-f</code> will report errors, but will continue processing the remainder of the dump file.</p> |
11,599,666 | Get the value of checked checkbox? | <p>So I've got code that looks like this:</p>
<pre><code><input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
</code></pre>
<p>I just need Javascript to get the value of whatever checkbox is currently checked.</p>
<p><strong>EDIT</strong>: To add, there will only be ONE checked box.</p> | 11,599,728 | 13 | 4 | null | 2012-07-22 10:54:07.68 UTC | 59 | 2021-11-10 03:58:18.543 UTC | 2015-07-24 00:50:04.837 UTC | null | 2,498,017 | null | 1,195,812 | null | 1 | 244 | javascript|checkbox | 1,096,924 | <p><em>For modern browsers</em>:</p>
<pre><code>var checkedValue = document.querySelector('.messageCheckbox:checked').value;
</code></pre>
<p><em>By using <code>jQuery</code></em>:</p>
<pre><code>var checkedValue = $('.messageCheckbox:checked').val();
</code></pre>
<p><em>Pure javascript without <code>jQuery</code></em>:</p>
<pre><code>var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
</code></pre> |
20,094,276 | IE11 is missing User Agent Style for main element (display: block;) | <p>Apparantly IE11 doesn't have a User Agent Style for <code><main></code> and therefor no <code>display: block;</code> on it. <strong>Why is there no User Agent Style?</strong> Is this a bug or on purpose?</p>
<p>Adding <code>display: block;</code> to the main element is enough, tho.</p> | 20,095,764 | 1 | 5 | null | 2013-11-20 11:09:10.59 UTC | 2 | 2014-01-03 13:55:05.5 UTC | 2014-01-03 13:55:05.5 UTC | null | 2,036,825 | null | 2,036,825 | null | 1 | 29 | html|internet-explorer|user-agent|internet-explorer-11 | 8,113 | <p>The <code>main</code> element is indeed not fully supported by IE11. Adding <code>main { display: block; }</code> to your CSS is the best solution for IE9+. You don't need to make conditional comments - since <code>display: block;</code> is the default behavior for <code>main</code> elements, it won't mess up anything.</p> |
20,224,446 | How to view and edit cacerts file? | <p>Using RAD 8.5 with WAS 8.5 runtime, I am getting an exception on my console:</p>
<p><code>The keystore located at "C:\IBM\Websphere85\jdk\jre\lib\security\cacerts" failed to load due to the following error: DerInputStream.getLength(): lengthTag=109, too big..</code></p>
<p>After searching for the error I got this <strong><a href="http://blog.webspheretools.com/2011/12/25/common-ssl-certificate-errors/" rel="noreferrer">link</a></strong> which suggests to edit the file and remove blank lines/extra characters.</p>
<p>How do I edit the file? I am on windows environment and the file seems to be base64 encoded.</p> | 20,483,171 | 2 | 6 | null | 2013-11-26 17:53:42.49 UTC | 4 | 2021-05-12 07:15:29.077 UTC | 2015-11-24 23:28:59.607 UTC | null | 1,505,120 | null | 1,054,245 | null | 1 | 15 | java|keystore|websphere-8|ibm-rad | 71,174 | <p>Here's a way to actually solve this problem without the need to view or edit the file.</p>
<blockquote>
<p>The default keyStore type is JKS and the WSKeyStore class assumes it to be a PKCS12 file which throws the above error. So we need to convert the cacerts file to .p12 format.</p>
</blockquote>
<p>Using the keytool utility from command line I executed:</p>
<pre><code>C:\IBM\WebSphere85\AppServer\java\bin>keytool -importkeystore ^
-srckeystore C:\IBM\WebSphere85\AppServer\java\jre\lib\security\cacerts ^
-destkeystore C:\IBM\WebSphere85\AppServer\java\jre\lib\security\cacerts.p12 ^
-srcstoretype JKS -deststoretype PKCS12 -srcstorepass changeit -deststorepass changeit -noprompt
</code></pre>
<p>which gave me a <code>cacerts.p12</code> file which could be easily read by the above class.</p>
<p><strong>References</strong>: </p>
<ul>
<li><a href="http://www-01.ibm.com/support/docview.wss?uid=swg21303472" rel="nofollow noreferrer">IBM Error</a></li>
<li><a href="https://stackoverflow.com/questions/2846828/converting-jks-to-p12">Stackoverflow: convert .jks to .p12</a></li>
</ul> |
3,800,458 | Quickly getting the color of some pixels on the screen in Python on Windows 7 | <p>I need to get the color of some pixels on the screen or from the active window, and I need to do so <em><strong>quickly</strong></em>. I've tried using win32gui and ctypes/windll, but they're much too slow. Each of these programs gets the color of 100 pixels:</p>
<pre><code>import win32gui
import time
time.clock()
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x , y)
print(time.clock())
</code></pre>
<p>and</p>
<pre><code>from ctypes import windll
import time
time.clock()
hdc = windll.user32.GetDC(0)
for y in range(0, 100, 10):
for x in range(0, 100, 10):
color = windll.gdi32.GetPixel(hdc, x, y)
print(time.clock())
</code></pre>
<p>Each of these takes about 1.75 seconds. I need a program like this to take less than 0.1 seconds. What's making it so slow?</p>
<p>I'm working with Python 3.x and Windows 7. If your solution requires I use Python 2.x, please link me to an article showing how to have Python 3.x and 2.x both installed. I looked, but couldn't figure out how to do this.</p> | 3,803,344 | 4 | 0 | null | 2010-09-27 00:40:04.897 UTC | 14 | 2021-02-07 15:30:49.467 UTC | 2021-02-07 15:30:49.467 UTC | null | 5,267,751 | null | 319,821 | null | 1 | 17 | python|windows-7|colors|screen|pixel | 80,800 | <p>I had this same exact problem, and solved it (<a href="https://stackoverflow.com/questions/3742731/java-how-to-draw-constantly-changing-graphics">in Java</a>, <a href="https://stackoverflow.com/questions/3743897/how-to-draw-constantly-changing-graphics">in C#</a>). The main idea behind the solution is GetPixel from screen is slow, and you can't fix that. But as you need some pixels, you can get a bunch of them all at once.</p>
<p>The time that it took to get 64 pixels was 98 times faster.</p> |
3,375,789 | Plus (+) in MVC Argument causes 404 on IIS 7.0 | <p>I have an MVC route that is giving me hell on a staging server running IIS. I am running Visual Studio 2010's development server locally.</p>
<p>Here is a sample URL that actually works on my dev box:</p>
<pre><code>Root/CPUBoards/Full+Size
Results
Server Error404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
</code></pre>
<p>Here is the complete behaviour I am seeing.</p>
<p>Localhost:</p>
<pre><code>Root/CPUBoards/Full Size - Resolves
Root/CPUBoards/Full%20Size - Resolves
Root/CPUBoards/Full+Size - Resolves
</code></pre>
<p>Staging Server with IIS 7.0:</p>
<pre><code>Root/CPUBoards/Full Size - Resolves
Root/CPUBoards/Full%20Size - Resolves
Root/CPUBoards/Full+Size - 404 Not Found Error.
</code></pre>
<p>Any ideas? I need to work with the encoded version for several reasons... won't waste your time with them.</p>
<p>HttpUtility.UrlEncode("Full Size") returns the version with the plus sing... Full+Size. This works on my dev box, but not on the staging server. I would prefer to just get it working on the server, since I already have everything else tested and working locally, but I have no idea where to start looking on the server configuration to get it to behave the same way.</p>
<p>Thanks!</p> | 3,375,847 | 4 | 1 | null | 2010-07-30 22:20:34.45 UTC | 7 | 2020-04-28 13:56:17.957 UTC | 2010-07-30 22:24:20.91 UTC | null | 18,936 | null | 406,732 | null | 1 | 29 | asp.net-mvc-2|arguments|asp.net-mvc-routing | 6,126 | <p><code>+</code> only has the special meaning of being a space in <code>application/x-www-form-urlencoded</code> data such as the query string part of a URL.</p>
<p>In other parts of the URL like path components, <code>+</code> literally means a plus sign. So resolving <code>Full+Size</code> to the unencoded name <code>Full Size</code> should not work anywhere.</p>
<p>The only correct form of a space in a path component is <code>%20</code>. (It still works when you type an actual space because the browser spots the error and corrects it for you.) <code>%20</code> also works in form-URL-encoded data as well, so it's generally safest to always use that.</p>
<p>Sadly <code>HttpUtility.UrlEncode</code> is misleadingly-named. It produces <code>+</code> in its output instead of <code>%20</code>, so it's really a form-URL-encoder and not a standard URL-encoder. Unfortunately I don't know of an ASP.NET function to “really URL-encode” strings for use in a path, so all I can recommend is doing a string replace of <code>+</code> to <code>%20</code> after encoding.</p>
<p>Alternatively, avoid using spaces in path parts, eg. by replacing them with <code>-</code>. It's common to ‘slug’ titles being inserted to URLs, reducing them to simple alphanumerics and ‘safe’ punctuation, to avoid filling the URL with ugly <code>%nn</code> sequences.</p> |
3,658,527 | Where/what level should logging code go? | <p>I'm wondering where logging code should go. For example, should my repository log it's own errors? Or should I log all errors from the UI/controller? Are there any general deisgn principles about this, or does anyone have link to a good article or somesuch.</p> | 3,659,000 | 5 | 0 | null | 2010-09-07 12:11:10.107 UTC | 10 | 2010-10-13 16:57:59.893 UTC | 2010-10-13 16:57:59.893 UTC | null | 265,143 | null | 207,752 | null | 1 | 18 | design-patterns|language-agnostic|logging|exception-handling | 3,722 | <p>Logging and tracing is (IMO) a fine art, knowing what to log and where takes experience.</p>
<p>I've found that the best (worst?) way of learning the art of logging is by experiencing the pain of attempting to diagnose issues with shoddy logging!</p>
<p>All I can offer you is some points of advice:</p>
<h2>Think about how the log message will be used.</h2>
<p>The <strong>key</strong> to good logging is to think about how the log message will be <em>used</em> if there is a problem, conversely the worst thing about poor logging is that you will only ever realise it when you have a problem and you don't have enough information!</p>
<p>Always think about <strong>what the log message says to the person who is reading it</strong>, for example:</p>
<ul>
<li>Has a windows API call failed? If so then you probably need to log the <code>HRESULT</code> and the <code>GetLastError</code> result (if there is one) for it to be of much use.</li>
<li>Couldn't find an entry in a collection? Without the name of the entry that wasn't found there really isn't much anyone can deduce - it would also be handy to know the count of the collection so that you can tell if the collection is empty.</li>
</ul>
<p>A common mistake is to not think about what information is required when logging, however you should also think carefully about <em>when</em> a message will be logged - if a message is logged frequently under normal operation then at best it's usefulness is questionable and at worst that log message can be misleading.</p>
<p>Also, make sure you can identify what logged a message. If all you can see in a log is a string which appears in your code base many times (or worse still not at all!) then you are going to need to deduction and cunning to figuring out where that log message came from (and without knowing where a message comes from, you have little hope in understanding it)</p>
<ul>
<li>In multi threaded / multi processor applications always log the thread id and the process id.</li>
<li>If you have a request id of any sort, log that too.</li>
<li>If you believe that you are going to spend any reasonable length of time looking at log files then you should strongly consider shipping whatever pdb etc... files are needed in order to see source files and line numbers.</li>
</ul>
<h2>Logging is only used when there is a problem</h2>
<p>Don't confuse <em>logging</em> with <em>error handling</em>. Error handling is the act of responding to and resolving that error, (e.g. displaying a message to the user), logs are (generally) only used when something has gone wrong and the reason is unclear.</p>
<p>For example: If a use attempts to open a file that doe not exist then if the error is correctly handled (by telling the user that the file couldn't be found) then there should be no need to log that error.</p>
<p>(The possible exception might be if you wanted statistics on how frequently that error happened or something - this comes back to thinking about how the logging will be used.)</p>
<p>In general correctly handling an error is preferable to logging, however good error handling is even more difficult than good logging - these are the cases where the extra information offered in logs is needed.</p>
<p>You also shouldn't confuse <em>logging</em> with <em>auditing</em> (although in many systems the two overlap).</p>
<h2>More is better!</h2>
<p>The only way you can log too much is if:</p>
<ul>
<li>You run out of storage space.</li>
<li>You significantly affect the performance of your app.</li>
<li>You get swamped with logs that you can't easily process in the case of an error.</li>
<li><del>You log profanities directed at your boss.</del></li>
</ul>
<p>Logging exists purely to diagnose the cause of problems (don't confuse logging with auditing) - if you don't have any problems then nobody is going to look at your logs, and no harm is done! Until you have a problem that is, in which case you need as much information as you can get.</p>
<p>If you are in doubt on whether or not to log something, then log it.</p>
<h2>Only log exceptions once.</h2>
<p>Having stated the above, I feel the need to clarify the logging of exceptions.</p>
<p>In general you should only log an exception once (at the point where it is handled). Don't be tempted to log an exception that you later throw to the caller "just in case" the caller doesn't log the exception properly - all that happens is that you end up with the same exception being logged many times as it passed from tier to tier (I've seen it happen and it makes it difficult to see how many errors actually occurred).</p>
<p>It is the callers responsibility to log an error - the only possible exception might be passing between system boundaries (e.g. web services), where it's not possible to transport across all of the error detail.</p>
<h2>Log whatever is relevant, wherever it is relevant to log it.</h2>
<p>For example, if you are writing a server based application then your log files need to be on the server, where the sysadmins can read them - if however there is potential for errors to occur on the client (e.g. in JavaScript), then your logging code needs to be in JavaScript. The solution? Your JavaScript logging needs to submit itself to the server (ala <a href="http://log4js.berlios.de/" rel="noreferrer">log4js</a>)</p>
<p>Don't worry about where you <em>should</em> and <strong>shouldn't</strong> put logging - just put it wherever it is needed.</p> |
3,982,663 | Falsey values in JavaScript | <p>I had an interesting interview question today that stumped me a little. I was asked about falsey values. So undefined, NaN, null, 0, and an empty string all evaluate to false. What is the reason this is useful to know in JavaScript? The only thing I can think of is instead of having to do this:</p>
<pre><code>if (mystring === '' || mystring === undefined) { }
</code></pre>
<p>I can do this:</p>
<pre><code>if (!mystring)
</code></pre>
<p>Is this the only useful application?</p> | 3,982,928 | 6 | 5 | null | 2010-10-20 21:55:05.533 UTC | 7 | 2015-04-15 07:08:49.15 UTC | 2015-04-10 19:18:16.667 UTC | null | 63,550 | null | 392,572 | null | 1 | 28 | javascript | 29,945 | <p>One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.</p>
<p>Suppose you want to test for the availability of a new property; when this property <em>can</em> actually have a value of <code>0</code> or <code>""</code>, you can't simply check for its availability using</p>
<pre><code>if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
</code></pre>
<p>In this case, you <strong>must</strong> check for it being really present or not:</p>
<pre><code>if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
</code></pre>
<p>Also be aware that <code>NaN</code> isn't equal to anything, even not to itself (<code>NaN != NaN</code>).</p> |
3,695,340 | Java "NoSuchMethodError" | <p>I'm getting: </p>
<pre><code>NoSuchMethodError: com.foo.SomeService.doSmth()Z
</code></pre>
<p>Am I understanding correctly that this <code>'Z'</code> means that return type of doSmth() method is boolean? If true, then that kind of method really does not exist because this method returns some Collection. But on the other hand if I call this method, I'm not assigning its return value to any variable. I just call this method like this:</p>
<pre><code>service.doSmth();
</code></pre>
<p>Any ideas why this error occurs? All necessary JAR files exist and all other methods from this class seems to exist. </p> | 3,695,376 | 7 | 3 | null | 2010-09-12 15:19:18.087 UTC | null | 2015-11-10 15:35:45.957 UTC | 2014-02-08 12:03:43.183 UTC | null | 1,693,859 | null | 223,610 | null | 1 | 28 | java|nosuchmethoderror | 50,434 | <p>Looks like method exists in classpath during compilation, but not during running of your application.</p>
<p>I don't think return type is a problem. If it was, it wouldn't compile. Compiler throws error when method call is ambiguous, and it is when two methods differ only by return type.</p> |
3,788,605 | #if DEBUG vs. Conditional("DEBUG") | <p>Which is better to use, and why, on a large project:</p>
<pre><code>#if DEBUG
public void SetPrivateValue(int value)
{ ... }
#endif
</code></pre>
<p>or</p>
<pre><code>[System.Diagnostics.Conditional("DEBUG")]
public void SetPrivateValue(int value)
{ ... }
</code></pre> | 3,788,719 | 8 | 7 | null | 2010-09-24 15:34:08.48 UTC | 150 | 2019-11-22 11:05:01.54 UTC | 2016-12-28 10:28:58.087 UTC | null | 3,926,461 | null | 100,988 | null | 1 | 481 | c#|debugging|preprocessor|debug-symbols | 324,616 | <p>It really depends on what you're going for:</p>
<ul>
<li><code>#if DEBUG</code>: The code in here won't even reach the IL on release.</li>
<li><code>[Conditional("DEBUG")]</code>: This code will reach the IL, however <em>calls</em> to the method will be omitted unless DEBUG is set when the caller is compiled.</li>
</ul>
<p>Personally I use both depending on the situation:</p>
<p><b>Conditional("DEBUG") Example:</b> I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.</p>
<pre><code>[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
GetType(), propertyName));
}
</code></pre>
<p>You really don't want to create a function using <code>#if DEBUG</code> unless you are willing to wrap every call to that function with the same <code>#if DEBUG</code>:</p>
<pre><code>#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething(); //This works, but looks FUGLY
#endif
}
</code></pre>
<p>versus:</p>
<pre><code>[Conditional("DEBUG")]
public void DoSomething() { }
public void Foo()
{
DoSomething(); //Code compiles and is cleaner, DoSomething always
//exists, however this is only called during DEBUG.
}
</code></pre>
<hr>
<p><b>#if DEBUG example:</b> I use this when trying to setup different bindings for WCF communication.</p>
<pre><code>#if DEBUG
public const String ENDPOINT = "Localhost";
#else
public const String ENDPOINT = "BasicHttpBinding";
#endif
</code></pre>
<p>In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.</p>
<hr>
<p>Update: I am updating this answer to clarify an important and tricky point. If you choose to use the <code>ConditionalAttribute</code>, keep in mind that calls are omitted during compilation, and <strong>not runtime</strong>. That is:</p>
<p>MyLibrary.dll</p>
<pre><code>[Conditional("DEBUG")]
public void A()
{
Console.WriteLine("A");
B();
}
[Conditional("DEBUG")]
public void B()
{
Console.WriteLine("B");
}
</code></pre>
<p>When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to <code>B()</code> from within <code>A()</code> omitted, even if a call to <code>A()</code> is included because DEBUG is defined in the calling assembly.</p> |
7,784,067 | Compare date without time | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion">How to compare two Dates without the time portion?</a> </p>
</blockquote>
<p>How to compare date without time in java ?</p>
<pre><code>Date currentDate = new Date();// get current date
Date eventDate = tempAppointments.get(i).mStartDate;
int dateMargin = currentDate.compareTo(eventDate);
</code></pre>
<p>this code compares time and date !</p> | 7,784,110 | 4 | 3 | null | 2011-10-16 11:53:16.743 UTC | 4 | 2021-09-03 21:21:03.267 UTC | 2017-05-23 12:09:52.997 UTC | null | -1 | null | 508,377 | null | 1 | 12 | java|time | 49,439 | <p>Try compare dates changing to 00:00:00 its time (as this function do):</p>
<pre><code>public static Date getZeroTimeDate(Date fecha) {
Date res = fecha;
Calendar calendar = Calendar.getInstance();
calendar.setTime( fecha );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
res = calendar.getTime();
return res;
}
Date currentDate = new Date();// get current date
Date eventDate = tempAppointments.get(i).mStartDate;
int dateMargin = getZeroTimeDate(currentDate).compareTo(getZeroTimeDate(eventDate));
</code></pre> |
8,285,040 | Reference as class member initialization | <p>I want to initialize a property of a class that holds a reference to another class by passing such a reference as a parameter to the constructor. However I receive an error: </p>
<p>“'TaxSquare::bank' must be initialized in constructor base/member initializer list”.
What is wrong in the following code of the classes? </p>
<pre><code>#ifndef TAXSQUARE_H
#define TAXSQUARE_H
#include "Square.h"
class Bank;
class TaxSquare : public Square
{
public:
TaxSquare(int, int, Bank&);
virtual void process();
private:
int taxAmount;
Bank& bank;
};
#endif
</code></pre>
<pre><code>#include <iostream>
#include "TaxSquare.h"
#include "Player.h"
#include "Bank.h"
using namespace std;
TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID)
{
taxAmount = amount;
bank = theBank;
}
</code></pre>
<pre><code>#ifndef BANK_H
#define BANK_H
class Bank
{
public:
Bank(int, int, int);
void getMoney(int);
void giveMoney(int);
void grantHouse();
void grantHotel();
private:
int sumMoney;
int numOfHouses;
int numOfHotels;
};
#endif
</code></pre> | 8,285,051 | 4 | 0 | null | 2011-11-27 10:51:00.887 UTC | 10 | 2014-11-25 18:49:02.937 UTC | 2011-11-27 10:53:46.963 UTC | null | 635,608 | null | 954,724 | null | 1 | 24 | c++|constructor|reference | 33,946 | <p>You are attempting to assign to <code>bank</code>, not initialize it:</p>
<pre><code>TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID)
{
// These are assignments
taxAmount = amount;
bank = theBank;
}
</code></pre>
<p><code>bank</code> is a reference, and therefore it must be initialized. You do so by putting it in the initializer list:</p>
<pre><code>TaxSquare::TaxSquare(int anID, int amount, Bank& theBank)
: Square(anID), taxAmount(amount), bank(theBank)
{}
</code></pre> |
7,709,022 | Is it ever useful to use Python's input over raw_input? | <p>I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous <code>input</code> function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to <code>eval</code> behind it.</p>
<p>So my question is, why does the <code>input</code> function call <code>eval</code>, and what would this ever be useful for that it wouldn't be safer to do with <code>raw_input</code>? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.</p>
<p><a href="http://docs.python.org/library/functions.html#input" rel="noreferrer">Python 2.x input function documentation</a></p> | 7,710,959 | 4 | 2 | null | 2011-10-10 05:57:31.93 UTC | 3 | 2018-10-09 13:33:41.263 UTC | 2011-10-10 06:03:18.803 UTC | null | 497,043 | null | 698,732 | null | 1 | 32 | python|user-input|python-2.x | 5,050 | <p>Is it ever useful to use Python 2's input over raw_input?</p>
<p><strong>No.</strong></p>
<hr>
<p><code>input()</code> evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, <a href="http://docs.python.org/library/functions.html#__import__" rel="noreferrer"><code>__import__</code></a>, and the <code>if/else</code> operators, literally anything Python can do can be achieved with a single expression. Malicious users can use <code>input()</code> to remove files (<code>__import__('os').remove('precious_file')</code>), monkeypatch the rest of the program (<code>setattr(__import__('__main__'), 'function', lambda:42)</code>), ... anything.</p>
<p>A normal user won't need to use all the advanced functionality. If you don't need expressions, use <code>ast.literal_eval(raw_input())</code> – the <a href="http://docs.python.org/library/ast.html#ast.literal_eval" rel="noreferrer"><code>literal_eval</code></a> function is safe.</p>
<p>If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.</p>
<p>If you're absolutely sure you know what you're doing, say <code>eval(raw_input())</code>. The <code>eval</code> screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.</p>
<hr>
<p><code>input()</code> was one of the old design mistakes that Python 3 is solving.</p> |
8,288,859 | How do you remove the _<scala-version> postfix from artifacts built+published with simple-build-tool? | <p>I'm building a few Java-only projects using simple-build-tool. When I publish the artifacts from the projects using, say, sbt publish-local then the resulting artifacts have the Scala version appended to their name. With a Scala project this would make sense, but since these are Java only projects it doesn't. How would I disable this postfixing of the Scala version? Or can I?</p>
<p>For reference I'm using sbt 0.11.1, Scala 2.9.1 and a .sbt file for build configuration (though moving to a full project config would be no problem).</p> | 8,291,387 | 4 | 0 | null | 2011-11-27 20:42:10.543 UTC | 12 | 2017-07-14 15:04:54.34 UTC | null | null | null | null | 2,719 | null | 1 | 67 | scala|sbt | 14,162 | <p>After looking around how Artifact.artifactName is implemented and ultimately used it seems that the way to turn this off is to specify false for the crossPath setting. This is documented in one of the quick configuration examples on the xsbt wiki.</p>
<p><a href="http://www.scala-sbt.org/release/docs/Examples/Quick-Configuration-Examples" rel="noreferrer">http://www.scala-sbt.org/release/docs/Examples/Quick-Configuration-Examples</a></p>
<pre><code>// disable using the Scala version in output paths and artifacts
crossPaths := false
</code></pre> |
8,212,373 | Firefox Web Console Disabled? | <p>How come I get this message from Firefox Web Console </p>
<blockquote>
<p>The Web Console logging API (console.log, console.info, console.warn, console.error) has been disabled by a script on this page</p>
</blockquote>
<p>The same webpage can print messages in Chrome Console but not Firefox. I opened the same webpage in another computers' Firefox (don't know what version) Web Console can print messages. My Firefox version is the latest, 8.0.</p> | 8,212,837 | 4 | 2 | null | 2011-11-21 13:12:24.797 UTC | 17 | 2016-05-23 14:45:49.32 UTC | 2011-11-21 13:19:27.927 UTC | null | 519,413 | null | 150,254 | null | 1 | 133 | javascript|html|firefox | 58,040 | <p>This happens when the page itself defines a global variable called <code>console</code>, for example. If the page is browser-sniffing to decide whether to define it, the behavior could differ in different browsers.</p>
<p>In the case of Firefox it also happens when Firebug is installed and its console is enabled, since that overrides the default <code>window.console</code>.</p> |
8,348,144 | How to convert .jar or .class to .dex file? | <p>I'm going to edit the Opera Mini v6.5 server because it is blocked in our country.</p>
<p>Now I have unpacked the <code>.apk</code> file extracted <code>classes.Dex</code> then converted it via <code>dex2jar.bat</code>, now modified the server.</p>
<p>My problem is I want to repack the <code>.jar</code> or <code>.class</code> to <code>classes.Dex</code>. How do I do it?</p> | 14,101,543 | 5 | 0 | null | 2011-12-01 20:53:43.303 UTC | 10 | 2022-03-26 21:23:09.293 UTC | 2022-03-26 21:23:09.293 UTC | null | 1,076,264 | null | 1,076,264 | null | 1 | 19 | java|android|dex|dx | 53,818 | <p>Here is a solution that was helpful in my case... </p>
<p>Suppose .jar file sits in "c:\temp\in.jar". In command prompt window cd to ..\android-sdk\platform-tools.
To get .apk execute: </p>
<pre><code>dx --dex --output="c:\temp\app.apk" "c:\temp\in.jar"
</code></pre>
<p>To get .dex file execute:</p>
<pre><code>dx --dex --output="c:\temp\dx.dex" "c:\temp\in.jar"
</code></pre> |
8,103,971 | "Sort Lines in Selection" for Xcode 4 | <p>I like Textmate's "Sort Lines in Selection" feature a lot. Is there something similar for Xcode 4? If not, what would be the best way to integrate such a feature (a plugin, Applescript, ...)?</p> | 8,104,750 | 5 | 0 | null | 2011-11-12 10:49:08.157 UTC | 9 | 2021-01-29 10:54:57.787 UTC | 2012-12-09 16:25:07.903 UTC | null | 353,652 | null | 353,652 | null | 1 | 20 | xcode|sorting|plugins|applescript|textmate | 4,900 | <p>You can do this with Automator:</p>
<ul>
<li>Start Automator and select either:<br>"Service" for macOS 10.7 or<br>"New Document" followed by "Quick Action" for macOS 11</li>
<li>Find and drag "Run Shell Script" into the workflow panel</li>
<li>Select "Output replaces selected text"</li>
<li>Type <code>sort -f</code> into the "Run Shell Script" textfield</li>
<li>Save</li>
</ul>
<p>Now you can sort lines in any textfield. Select some text and right-click or Control click and select the service you just created.</p>
<p><a href="https://i.stack.imgur.com/SRKUm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SRKUm.png" alt="Automator screenshot" /></a></p> |
8,292,256 | Get Number of Rows returned by ResultSet in Java | <p>I have used a <code>ResultSet</code> that returns certain number of rows. My code is something like this:</p>
<pre><code>ResultSet res = getData();
if(!res.next())
{
System.out.println("No Data Found");
}
while(res.next())
{
// code to display the data in the table.
}
</code></pre>
<p>Is there any method to check the number of rows returned by the <code>ResultSet</code>? Or do I have to write my own?</p> | 8,292,323 | 14 | 1 | null | 2011-11-28 06:33:01.98 UTC | 23 | 2020-03-06 11:36:06.84 UTC | 2014-07-25 19:44:51.757 UTC | null | 445,131 | null | 871,307 | null | 1 | 75 | java|resultset | 273,577 | <p>You could use a <code>do ... while</code> loop instead of a <code>while</code> loop, so that <code>rs.next()</code> is called after the loop is executed, like this:</p>
<pre><code>if (!rs.next()) { //if rs.next() returns false
//then there are no rows.
System.out.println("No records found");
}
else {
do {
// Get data from the current row and use it
} while (rs.next());
}
</code></pre>
<p>Or count the rows yourself as you're getting them:</p>
<pre><code>int count = 0;
while (rs.next()) {
++count;
// Get data from the current row and use it
}
if (count == 0) {
System.out.println("No records found");
}
</code></pre> |
4,591,763 | Find paths in a binary search tree summing to a target value | <p>Given a binary search tree and a target value, find all the paths (if there exists more than one) which sum up to the target value. It can be any path in the tree. It doesn't have to be from the root.</p>
<p>For example, in the following binary search tree:</p>
<pre><code> 2
/ \
1 3
</code></pre>
<p>when the sum should be 6, the path <code>1 -> 2 -> 3</code> should be printed.</p> | 4,592,412 | 3 | 3 | null | 2011-01-04 08:30:30.103 UTC | 18 | 2015-11-07 07:21:47.767 UTC | 2012-09-16 19:56:36.737 UTC | null | 387,076 | null | 547,198 | null | 1 | 18 | algorithm|data-structures|binary-tree | 13,019 | <p>Traverse through the tree from the root and do a post-order gathering of all path sums. Use a hashtable to store the possible paths rooted at a node and going down-only. We can construct all paths going through a node from itself and its childrens' paths.</p>
<p>Here is psuedo-code that implements the above, but stores only the sums and not the actual paths. For the paths themselves, you need to store the end node in the hashtable (we know where it starts, and there's only one path between two nodes in a tree).</p>
<pre><code>function findsum(tree, target)
# Traverse the children
if tree->left
findsum(tree.left, target)
if tree->right
findsum(tree.right, target)
# Single node forms a valid path
tree.sums = {tree.value}
# Add this node to sums of children
if tree.left
for left_sum in tree.left.sums
tree.sums.add(left_sum + tree.value)
if tree.right
for right_sum in tree.right.sums
tree.sums.add(right_sum + tree.value)
# Have we formed the sum?
if target in tree.sums
we have a path
# Can we form the sum going through this node and both children?
if tree.left and tree.right
for left_sum in tree.left.sums
if target - left_sum in tree.right.sums
we have a path
# We no longer need children sums, free their memory
if tree.left
delete tree.left.sums
if tree.right
delete tree.right.sums
</code></pre>
<p>This doesn't use the fact that the tree is a search tree, so it can be applied to any binary tree.</p>
<p>For large trees, the size of the hashtable will grow out of hand. If there are only positive values, it could be more efficient to use an array indexed by the sum.</p> |
4,799,816 | Return row of every n'th record | <p>How can I return every <em>nth</em> record from a sub query based on a numerical parameter that I supply?</p>
<p>For example, I may have the following query:</p>
<pre><code>SELECT
Id,
Key
FROM DataTable
WHERE CustomerId = 1234
ORDER BY Key
</code></pre>
<p><strong>e.g.</strong> </p>
<p>The subquery result may look like the following:</p>
<pre><code>Row Id Key
1 1 A3231
2 43 C1212
3 243 E1232
4 765 G1232
5 2432 E2325
...
90 3193 F2312
</code></pre>
<p>If I pass in the number 30, and the sub query result set contained 90 records, I would recieve the <em>30th</em>, <em>60th</em>, and <em>90th</em> row.</p>
<p>If I pass in the number 40, and the result set contained 90 records, I would recieve the <em>40th</em> and <em>80th</em> row.</p>
<p><em>As a side note, for background information, this is being used to capture the key/id of every nth record for a paging control.</em></p> | 4,799,880 | 3 | 2 | null | 2011-01-25 22:59:52.62 UTC | 5 | 2022-04-28 11:11:02.42 UTC | 2011-01-25 23:08:17.073 UTC | null | 225,239 | null | 225,239 | null | 1 | 50 | tsql|sql-server-2008 | 64,034 | <p>This is where <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="noreferrer"><code>ROW_NUMBER</code></a> can help. It requires an order-by clause but this is okay because an order-by is present (and required to guarantee a particular order).</p>
<pre><code>SELECT t.id, t.key
FROM
(
SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
FROM datatable
) AS t
WHERE t.rownum % 30 = 0 -- or % 40 etc
ORDER BY t.key
</code></pre> |
4,797,166 | Set default value of a password input so it can be read | <p>I want to have a password field which says "Password" in it before a user enters their password (so they know what the field is)</p>
<p>I'd rather just use Javascript, importing jQuery for this alone seems wasteful, but I have no idea how to. The images explain quite clearly:</p>
<p><em>What it looks like:</em></p>
<p><img src="https://i.stack.imgur.com/E8mnp.gif" alt="enter image description here"></p>
<p><em>What I want it to look like:</em></p>
<p><img src="https://i.stack.imgur.com/LnY61.gif" alt="enter image description here"></p>
<p>It's only a very simple website and the most basic of logins (has no validation etc)</p>
<p>Any ideas?</p>
<pre><code><input id="username" name="username" class="input_text" type="text" value="Username" />
<input id="password" name="password" class="input_text" type="password" value="Password" />
</code></pre> | 4,797,210 | 5 | 1 | null | 2011-01-25 18:04:40.98 UTC | 0 | 2015-06-19 22:35:58.003 UTC | null | null | null | null | 311,074 | null | 1 | 8 | javascript|html|forms | 42,090 | <p>Change your <code>password</code> input to be a simple input type <code>text</code>. Then, with JavaScript (or JQuery) on focus event, change it to be a input type <code>password</code>.</p>
<p>Here is a little untested sample with plain JavaScript (no JQUERY):</p>
<pre><code><html>
<head>
<script type="text/javascript">
function makeItPassword()
{
document.getElementById("passcontainer")
.innerHTML = "<input id=\"password\" name=\"password\" type=\"password\"/>";
document.getElementById("password").focus();
}
</script>
</head>
<body>
<form>
<span id="passcontainer">
<input onfocus="return makeItPassword()" name="password" type="text" value="Type Password" />
</span>
</form>
</body>
</html>
</code></pre> |
4,709,655 | how to output every line in a file python | <pre><code> if data.find('!masters') != -1:
f = open('masters.txt')
lines = f.readline()
for line in lines:
print lines
sck.send('PRIVMSG ' + chan + " " + str(lines) + '\r\n')
f.close()
</code></pre>
<p>masters.txt has a list of nicknames, how can I print every line from the file at once?. The code I have only prints the first nickname. Your help will be appreciate it. Thanks.</p> | 4,709,680 | 5 | 3 | null | 2011-01-17 03:03:34.807 UTC | 3 | 2017-02-02 10:04:49.247 UTC | 2011-01-17 03:55:50.213 UTC | null | 355,230 | null | 365,015 | null | 1 | 15 | python|file|input | 122,494 | <p>Firstly, as @l33tnerd said, <code>f.close</code> should be outside the for loop.</p>
<p>Secondly, you are only calling <code>readline</code> once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:</p>
<pre><code> if data.find('!masters') != -1:
f = open('masters.txt')
for line in f:
print line,
sck.send('PRIVMSG ' + chan + " " + line)
f.close()
</code></pre>
<p>Finally, you were referring to the variable <code>lines</code> inside the loop; I assume you meant to refer to <code>line</code>.</p>
<p>Edit: Oh and you need to indent the contents of the <code>if</code> statement.</p> |
4,100,486 | Java: create a list of HashMaps | <p>I tried to create a list of maps. In the following code, I'm expecting to get </p>
<pre><code>[{start=1,text=ye}, {start=2,text=no}]
</code></pre>
<p>however, I only got</p>
<pre><code>[{start=2,text=no}, {start=2,text=no}]
</code></pre>
<p>How to avoid overriding the first map? Here is my code: </p>
<pre><code>HashMap mMap = new HashMap();
ArrayList list = new ArrayList();
list.add(new HashMap());
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
System.out.println("Final result: " + list );
</code></pre>
<p>thanks!</p>
<p>==========================</p>
<p>As a learner of Java who came from a procedure language background (SAS), I spent quite a few hours learning and experimenting ArrayList, LinkedList, Map, LinkedMap, etc--- I coldn't get it to work. And I don't understand why with my limited knowledge. Now, these following answers are all excellent! They explained very important data structure in Java, at least for me.</p>
<p>THANK YOU ALL!!!!</p> | 4,100,507 | 6 | 0 | null | 2010-11-04 19:29:54.12 UTC | 4 | 2019-08-21 07:53:56.23 UTC | 2010-11-04 19:43:38.627 UTC | null | 311,884 | null | 311,884 | null | 1 | 13 | java|arraylist | 106,448 | <p>You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:</p>
<pre><code>HashMap mMap = new HashMap();
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap = new HashMap(); // create a new one!
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
</code></pre>
<p>also, you can remove the <code>list.add(new HashMap());</code> as that adds an empty map to your list that is never populated.</p> |
4,069,028 | Write string to output stream | <p>I have several output listeners that are implementing <code>OutputStream</code>.
It can be either a <code>PrintStream</code> writing to stdout or to a File, or it can be writing to memory or any other output destination; therefore, I specified <code>OutputStream</code> as (an) argument in the method.</p>
<p>Now, I have received the <code>String</code>. What is the best way to write to streams here?</p>
<p>Should I just use <code>Writer.write(message.getBytes())</code>? I can give it bytes, but if the destination stream is a character stream then will it convert automatically?</p>
<p>Do I need to use some bridge streams here instead?</p> | 4,069,104 | 6 | 1 | null | 2010-11-01 12:54:15.9 UTC | 30 | 2021-03-16 14:59:12.953 UTC | 2021-03-16 14:59:12.953 UTC | null | 40,342 | null | 232,666 | null | 1 | 156 | java|io|stream|outputstream | 389,424 | <p>Streams (<code>InputStream</code> and <code>OutputStream</code>) transfer <em>binary</em> data. If you want to write a string to a stream, you must first convert it to bytes, or in other words <em>encode</em> it. You can do that manually (as you suggest) using the <code>String.getBytes(Charset)</code> method, but you should avoid the <code>String.getBytes()</code> method, because that uses the default encoding of the JVM, which can't be reliably predicted in a portable way.</p>
<p>The usual way to write character data to a stream, though, is to wrap the stream in a <a href="http://download.oracle.com/javase/8/docs/api/java/io/Writer.html" rel="noreferrer"><code>Writer</code></a>, (often a <a href="http://download.oracle.com/javase/8/docs/api/java/io/PrintWriter.html" rel="noreferrer"><code>PrintWriter</code></a>), that does the conversion for you when you call its <a href="http://download.oracle.com/javase/8/docs/api/java/io/Writer.html#write(java.lang.String)" rel="noreferrer"><code>write(String)</code></a> (or <a href="http://download.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#print(java.lang.String)" rel="noreferrer"><code>print(String)</code></a>) method. The corresponding wrapper for InputStreams is a <a href="http://download.oracle.com/javase/8/docs/api/java/io/Reader.html" rel="noreferrer">Reader</a>.</p>
<p><code>PrintStream</code> is a special <code>OutputStream</code> implementation in the sense that it also contain methods that automatically encode strings (it uses a writer internally). But it is still a stream. You can safely wrap your stream with a writer no matter if it is a <code>PrintStream</code> or some other stream implementation. There is no danger of double encoding.</p>
<p>Example of PrintWriter with OutputStream:</p>
<pre><code>try (PrintWriter p = new PrintWriter(new FileOutputStream("output-text.txt", true))) {
p.println("Hello");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
</code></pre> |
4,781,014 | Unordered List (<ul>) default indent | <p>Can anyone tell me why an unordered list has a default indent/padding applied to it? Can this be solved with a CSS Browser Reset?</p> | 4,781,061 | 8 | 1 | null | 2011-01-24 10:38:47.187 UTC | 4 | 2018-05-30 16:31:08.013 UTC | null | null | null | null | 478,144 | null | 1 | 32 | html|css | 116,685 | <p>It has a default indent/padding so that the bullets will not end up outside the list itself.</p>
<p>A CSS reset might or might not contain rules to reset the list, that would depend on which one you use.</p> |
4,573,483 | Netbeans Shortcut to Open File | <p>I remember seeing someone use a shortcut in NetBeans to open a dialog similar to phpStrom that can open files based on class names or is it file name. whats that?</p>
<p><img src="https://imgur.com/ShYAX.jpg" alt=""></p> | 4,573,532 | 10 | 5 | null | 2011-01-01 07:44:17.597 UTC | 15 | 2020-04-19 12:50:43.003 UTC | 2011-01-01 10:28:37.8 UTC | null | 30,453 | null | 292,291 | null | 1 | 46 | netbeans|keyboard-shortcuts|screenshot|openfiledialog|classname | 61,011 | <p><em>Updated</em></p>
<p>I'm fairly certain you are referring to the "Quick File Chooser" plugin. As someone else points out, though, there are several other candidates. I list them below...</p>
<p><strong><em>The Quick File Chooser Plugin</em></strong>:</p>
<p>By default <kbd>CTRL</kbd>-<kbd>SHIFT</kbd>-<kbd>O</kbd> opens the <em>Open Project</em> dialog, and once the plugin is installed, you will get the dialog pictured here automatically: </p>
<p><img src="https://i.stack.imgur.com/Heh2b.jpg" alt="Quick File Chooser - Open Project Dialog"></p>
<p>(The Quick File Chooser plugin replaces the default open project dialog with its own.)</p>
<p>When opening a file with the Quick File Chooser plugin, you see this:</p>
<p><img src="https://i.stack.imgur.com/vb7G3.jpg" alt="Quick File Chooser - Open File Dialog"></p>
<p>I did not find that the plugin was able to open based on a class name.</p>
<p>Quick File Chooser is available through the <a href="http://plugins.netbeans.org/plugin/16203/quick-file-chooser" rel="noreferrer">NetBeans Plugin Portal</a>. You can also install it directly from within NetBeans versions 7.1 and 7.3 if you have the "Plugin Portal" Update Center configured. (See the bottom of this answer for instructions.)</p>
<p><strong><em>NetBeans Core (no plugin)</em></strong></p>
<p>By default <kbd>CTRL</kbd>-<kbd>SHIFT</kbd>-<kbd>O</kbd> opens the <em>Open Project</em> dialog, and <em>without</em> the QFC plugin, you will get the default dialog:</p>
<p><img src="https://i.stack.imgur.com/KqMPN.png" alt="default Open Project dialog (Windows)"></p>
<p>The default <em>Open File</em> dialog is this:</p>
<p><img src="https://i.stack.imgur.com/tsOXF.png" alt="default Open File dialog (Windows)"></p>
<p>The <em>Open File</em> dialog does not have a keyboard shortcut by default, but you can easily add it:</p>
<ul>
<li>Click on <em>Tools</em>, then <em>Options</em>, then on the <em>Keymap</em> icon in the tool bar of the dialog.</li>
<li>In <em>Search:</em> type <em>"Open Fi"</em> and you should see <em>"Open File..."</em> in the <em>Actions</em> list.</li>
<li>Double click on the <em>Shortcut</em> box for that entry, and select an appropriate shortcut (either by pressing the key combination, or by selecting it from the drop-down).</li>
<li>Click <em>OK</em>.</li>
</ul>
<p><em>The Go To... Dialogs</em>:</p>
<p>The <em>Go To...</em> dialogs are provided by core NetBeans, and are available even if the QFC plugin is installed (the QFC plugin does not override them).</p>
<p>The <em>Go To File</em> dialog is <kbd>ALT</kbd>-<kbd>SHIFT</kbd>-<kbd>O</kbd>. </p>
<p><img src="https://i.stack.imgur.com/gJdqf.jpg" alt="alt text"></p>
<p><em>Go To Type</em>: <kbd>CTRL</kbd>-<kbd>O</kbd>, appears to list classes, variables, and all sorts of stuff.</p>
<p><img src="https://i.stack.imgur.com/gxHsR.jpg" alt="alt text"></p>
<p><em>Go To Symbol</em>: <kbd>CTRL</kbd>-<kbd>ALT</kbd>-<kbd>SHIFT</kbd>-<kbd>O</kbd></p>
<p><img src="https://i.stack.imgur.com/1pqeD.jpg" alt="alt text"></p>
<p>For PHP projects, <em>Go To Type</em> and <em>Go To Symbol</em> appear to list the same set. As mentioned, all of these are available on the <em>Navigate</em> menu.</p>
<p><strong>Installing Quick File Chooser from the Plugin Portal Update Center</strong></p>
<p>In NetBeans:</p>
<ul>
<li>Click on <em>Tools</em>, then <em>Plugins</em></li>
<li>Go to the <em>Settings</em> tab</li>
<li>Ensure that the <em>"Plugin Portal"</em> is listed in <em>Configuration of Update Centers</em> and checked as <em>Active</em>. If it is not listed, click <em>Add</em>, give it an appropriate name, and the URL is <a href="http://plugins.netbeans.org/nbpluginportal/updates/7.3/catalog.xml.gz" rel="noreferrer">http://plugins.netbeans.org/nbpluginportal/updates/7.3/catalog.xml.gz</a> for versions 7.3.x. (In the URL replace the "7.3" with, e.g., "7.2" or "7.1" if you are using an older version of NetBeans.)</li>
<li>Click on the <em>Available Plugins</em> tab.</li>
<li>Click on <em>Reload Catalog</em> just to be sure you have the latest contents.</li>
<li>In <em>Search:</em> type <em>"Quick"</em>. That should be enough to get it listed by itself (or at least on a short list).</li>
<li>Click on the check box under the <em>Install</em> column, and then click on the <em>Install</em> button down below.</li>
</ul> |
4,054,662 | Displaying soft keyboard whenever AlertDialog.Builder object is opened | <p>My code for opening an input dialog reads as follows:</p>
<pre><code>final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Dialog Title");
alert.setMessage("Request information");
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.edittextautotextlayout, null);
final EditText inputBox = (EditText) textEntryView.findViewById(R.id.my_et_layout);
alert.setView(inputBox);
</code></pre>
<p>This works fine except that I have to tap the text entry line before the soft keyboard appears.</p>
<p>Following the advice given <a href="https://stackoverflow.com/questions/2403632/android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext">here</a> I have tried inserting:</p>
<pre><code>inputBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
alert.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
</code></pre>
<p>but Eclipse objects that "the method getWindow() is not defined for the type AlertDialog.Builder".</p>
<p>It seems that the setOnFocusChangeListener code works for an AlertDialog object but not an AlertDialog.Builder. How should I modify my code to make the soft keyboard appear automatcially.</p> | 4,115,170 | 14 | 0 | null | 2010-10-29 18:12:13.707 UTC | 7 | 2019-04-14 02:33:11.32 UTC | 2017-05-23 10:30:01.317 UTC | null | -1 | null | 250,845 | null | 1 | 35 | android|keyboard|android-edittext|android-alertdialog | 32,918 | <p>With the encouragement of Mur Votema (see his answer above) I have answered my question by building a custom dialog based on the Dialog class. Unlike an alert based on AlertDialog.Builder such a custom dialog does accept the getWindow().setSoftInputMode(...) command and therefore allows the soft keyboard to be displayed automatically.</p>
<p>For guidance on building a custom dialog I found <a href="http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application" rel="noreferrer">this web page</a> and <a href="http://blog.androgames.net/10/custom-android-dialog/" rel="noreferrer">this</a> especially helpful.</p> |
14,639,561 | Set colspan/rowspan for a cell | <p>I have a table and I want to change <code>colspan</code>/<code>rowspan</code> property of a cell on runtime. Here is an example:</p>
<pre><code><html>
<head>
<script type="text/javascript">
function setColSpan() {
document.getElementById('myTable').rows[0].cells[0].colSpan = 2
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<form>
<input type="button" onclick="setColSpan()" value="Change colspan">
</form>
</body>
</html>
</code></pre>
<p>My problem is that the cells shift. Am I supposed to remove the cells over which the cell in question spans?</p>
<p>I can I do without removing?</p>
<p>I want to implement a simple spreadsheet. For now I managed to be able to select a rectangular range of cells and show a menu with a "Merge selected cells" option. I would like to be able to "unmerge" cells, so it would be good to span cells without having to remove other cells.</p> | 14,639,696 | 2 | 2 | null | 2013-02-01 04:07:09.28 UTC | 2 | 2018-02-24 20:07:49.737 UTC | 2018-02-24 20:07:49.737 UTC | null | 4,370,109 | null | 248,296 | null | 1 | 13 | javascript|html|html-table | 62,209 | <p>I think you need to delete the cell. Check with following code. What i did was removed the entire row and added new row with new column span</p>
<pre><code>function setColSpan() {
var table = document.getElementById('myTable');
table.deleteRow(0);
var row = table.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML= "cell 1"
cell.colSpan = 2
}
</code></pre> |
14,660,938 | How can I get phone serial number (IMEI) | <p>I want to get phone serial number by programming to registration configuration of my application and number of users and phones that my app has been installed on them.</p>
<p>Can I get that?</p>
<p>and can I get phone model that my app has been installed on them?</p> | 14,661,104 | 5 | 3 | null | 2013-02-02 10:27:10.5 UTC | 5 | 2014-06-10 19:17:44.677 UTC | 2014-06-10 19:17:44.677 UTC | null | 881,229 | null | 1,793,650 | null | 1 | 17 | android | 107,167 | <p>pls refer this
<a href="https://stackoverflow.com/a/1972404/951045">https://stackoverflow.com/a/1972404/951045</a></p>
<pre><code> TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mngr.getDeviceId();
</code></pre>
<p>add <code>READ_PHONE_STATE</code> permission to <code>AndroidManifest.xml</code></p> |
14,577,568 | Is there a user-friendly Log4Net log files viewer? | <p>Is there any third party tool that can recognize Log4Net log file structure and show it in a user friendly way by providing search functionalities etc?</p> | 14,577,621 | 5 | 2 | null | 2013-01-29 07:17:16.453 UTC | 9 | 2019-05-03 14:06:30.693 UTC | 2013-09-11 15:20:23.607 UTC | null | 133 | null | 136,141 | null | 1 | 35 | .net|log4net | 41,273 | <p>Try <a href="https://sourceforge.net/projects/gamutlogviewer/" rel="noreferrer">GamutLogViewer</a>.</p>
<blockquote>
<p>GamutLogViewer© is log file, logfile, viewer that works with Log4J, Log4Net, NLog, and user defined formats including ColdFusion. It supports filtering, searching, highlighting and many other useful features. This is a Windows application.</p>
</blockquote> |
14,607,640 | Rotating a Vector in 3D Space | <p>I am making an android project in opengl es that uses accelerometer to calculate change in specific axes and my aim is to rotate my spacecraft-like object's movement vector. The problem is that i can't understand the math behind rotation matrices. Default movement vector is 0,1,0 , means +y, so the object looks upward in the beginning. and i am trying to rotate its movement vector so i can move the object where it points. I can gather rotation changes in phone. x-axis : rotate[0], y-axis : rotate[1], z-axis : rotate[2]. How can i rotate my movement vector using rotation matrix ?</p> | 14,609,567 | 2 | 1 | null | 2013-01-30 15:31:42.387 UTC | 61 | 2022-08-22 05:01:42.997 UTC | 2014-12-26 05:02:08.173 UTC | null | 183,120 | null | 1,248,401 | null | 1 | 70 | math|vector|3d|rotation|linear-algebra | 239,569 | <p>If you want to rotate a vector you should construct what is known as a <a href="http://en.wikipedia.org/wiki/Rotation_matrix" rel="nofollow noreferrer">rotation matrix</a>.</p>
<h1>Rotation in 2D</h1>
<p>Say you want to rotate a vector or a point by θ, then <a href="http://en.wikipedia.org/wiki/Polar_coordinates" rel="nofollow noreferrer">trigonometry</a> states that the new coordinates are</p>
<pre><code> x' = x cos θ − y sin θ
y' = x sin θ + y cos θ
</code></pre>
<p>To demo this, let's take the <a href="https://en.wikipedia.org/wiki/Cartesian_coordinate_system" rel="nofollow noreferrer">cardinal axes</a> X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider</p>
<pre><code> Unit vector along X axis = <1, 0>
x' = 1 cos 90 − 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ⟹ Y-axis
</code></pre>
<p>When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like <a href="https://en.wikipedia.org/wiki/Rotation_(mathematics)" rel="nofollow noreferrer">rotation</a>, <a href="https://en.wikipedia.org/wiki/Scaling_(geometry)" rel="nofollow noreferrer">scale</a> and <a href="https://en.wikipedia.org/wiki/Translation_(geometry)" rel="nofollow noreferrer">translation</a> (moving) can be combined and performed in a single step, using <a href="https://en.wikipedia.org/wiki/Affine_transformation" rel="nofollow noreferrer">one common method</a>. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is</p>
<pre><code> |cos θ −sin θ| |x| = |x cos θ − y sin θ| = |x'|
|sin θ cos θ| |y| |x sin θ + y cos θ| |y'|
</code></pre>
<h1>Rotation in 3D</h1>
<p>In 3D we need to account for the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be</p>
<pre><code> |cos θ −sin θ 0| |x| |x cos θ − y sin θ| |x'|
|sin θ cos θ 0| |y| = |x sin θ + y cos θ| = |y'|
| 0 0 1| |z| | z | |z'|
</code></pre>
<p>around the Y-axis would be</p>
<pre><code> | cos θ 0 sin θ| |x| | x cos θ + z sin θ| |x'|
| 0 1 0| |y| = | y | = |y'|
|−sin θ 0 cos θ| |z| |−x sin θ + z cos θ| |z'|
</code></pre>
<p>around the X-axis would be</p>
<pre><code> |1 0 0| |x| | x | |x'|
|0 cos θ −sin θ| |y| = |y cos θ − z sin θ| = |y'|
|0 sin θ cos θ| |z| |y sin θ + z cos θ| |z'|
</code></pre>
<p><strong>Note 1</strong>: axis around which rotation is done has no sine or cosine elements in the matrix.</p>
<p><strong>Note 2:</strong> This method of performing rotations follows the <a href="http://en.wikipedia.org/wiki/Euler_angles" rel="nofollow noreferrer">Euler angle</a> rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as <a href="http://en.wikipedia.org/wiki/Gimbal_lock" rel="nofollow noreferrer">Gimbal lock</a>. People resort to <a href="http://en.wikipedia.org/wiki/Quaternion" rel="nofollow noreferrer">Quaternion</a>s in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.</p>
<p>I hope this clarifies basic rotation.</p>
<h1>Rotation and Revolution</h1>
<p>The aforementioned matrices rotate an object at a distance r = √(x² + y²) from the origin along a circle of radius r; lookup <a href="http://en.wikipedia.org/wiki/Polar_coordinate_system" rel="nofollow noreferrer">polar coordinates</a> to know why. This rotation will be with respect to the world space origin a.k.a <em>revolution</em> or <em>orbiting</em>. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. Instead you'd</p>
<ol>
<li>Translate the object to world origin
<ul>
<li>Object's origin would align with world's, making r = 0</li>
</ul>
</li>
<li>Rotate with one (or more) aforementioned rotation matrices</li>
<li>Translate object back again to its previous (original) location.</li>
</ol>
<p>The order in which the transforms are applied <a href="http://www.glprogramming.com/red/chapter03.html#name2" rel="nofollow noreferrer">matters</a>.</p>
<h1>Composition/Concatenation of Transforms</h1>
<p>Since matrices can represent not just rotation but also translation, scale, etc. all three operations in <em>Rotation and Revolution</em> section can be written as matrices. When they are multiplied we get a single matrix which does all three operations in order. The resultant matrix when multiplied with the points of an object will rotate the object around <em>its</em> axis (in its local space). Combining multiple transforms together is called <em>concatenation</em> or <em>composition</em>.</p>
<p>I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found <a href="http://www.youtube.com/watch?v=heVndBwDffI" rel="nofollow noreferrer">this lecture video</a> to be a very good resource. Another resource is <a href="http://github.com/legends2k/2d-transforms-101/#2d-transforms-101" rel="nofollow noreferrer">this tutorial on transformations</a> that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).</p>
<h1>Rotation around Arbitrary Vector</h1>
<p>A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The <a href="https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula" rel="nofollow noreferrer">Rodrigues' formula</a> (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using <a href="http://en.wikipedia.org/wiki/Quaternion" rel="nofollow noreferrer">Quaternion</a>s, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact <em>and</em> fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See <a href="https://www.3dgep.com/understanding-quaternions/" rel="nofollow noreferrer">Understanding Quaternions</a> for a decent primer on quaternions.</p> |
2,878,447 | Tutorial: Simple WCF XML-RPC client | <p><strong>Update: I have provided complete code example in answer below.</strong></p>
<p>I have built my own little custom XML-RPC server, and since I'd like to keep things simple, on both server and client side, what I would like to accomplish is to create a simplest possible client (in C# preferably) using WCF.</p>
<p>Let's say that Contract for service exposed via XML-RPC is as follows:</p>
<pre><code>[ServiceContract]
public interface IContract
{
[OperationContract(Action="Ping")]
string Ping(); // server returns back string "Pong"
[OperationContract(Action="Echo")]
string Echo(string message); // server echoes back whatever message is
}
</code></pre>
<p>So, there are two example methods, one without any arguments, and another with simple string argument, both returning strings (just for sake of example). Service is exposed via http.</p>
<p>Aaand, what's next? :)</p> | 2,881,059 | 2 | 0 | null | 2010-05-20 22:54:10.143 UTC | 11 | 2016-02-03 17:16:00.733 UTC | 2013-08-15 14:45:22.66 UTC | user1228 | null | null | 267,491 | null | 1 | 14 | c#|wcf|client|xml-rpc | 30,293 | <p>Inspired by Doobi's answer, I looked up some more info (examples) on the subject, and came up with the following findings.</p>
<p>Steps to create simple WCF XML-RPC client:</p>
<ol>
<li>Download XML-RPC for WCF from this page: <a href="http://vasters.com/clemensv/PermaLink,guid,679ca50b-c907-4831-81c4-369ef7b85839.aspx" rel="noreferrer">http://vasters.com/clemensv/PermaLink,guid,679ca50b-c907-4831-81c4-369ef7b85839.aspx</a> (download link is at the top of page)</li>
<li>Create an empty project which targets <strong>.NET 4.0 Full</strong> framework (or else System.ServiceModel.Web won't be available later on)</li>
<li>Add <strong>Microsoft.Samples.XmlRpc</strong> project from the archive to your project</li>
<li>Add reference to Microsoft.Samples.XmlRpc project</li>
<li>Add references to System.ServiceModel and System.ServiceModel.Web</li>
</ol>
<p><strong>Example code</strong></p>
<pre><code>using System;
using System.ServiceModel;
using Microsoft.Samples.XmlRpc;
namespace ConsoleApplication1
{
// describe your service's interface here
[ServiceContract]
public interface IServiceContract
{
[OperationContract(Action="Hello")]
string Hello(string name);
}
class Program
{
static void Main(string[] args)
{
ChannelFactory<IServiceContract> cf = new ChannelFactory<IServiceContract>(
new WebHttpBinding(), "http://www.example.com/xmlrpc");
cf.Endpoint.Behaviors.Add(new XmlRpcEndpointBehavior());
IServiceContract client = cf.CreateChannel();
// you can now call methods from your remote service
string answer = client.Hello("World");
}
}
}
</code></pre>
<p><strong>Example request/response messages</strong></p>
<p><em>Request XML</em></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<methodCall>
<methodName>Hello</methodName>
<params>
<param>
<value>
<string>World</string>
</value>
</param>
</params>
</methodCall>
</code></pre>
<p><em>Response XML</em></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<params>
<param>
<value>
<string>Hello, World!</string>
</value>
</param>
</params>
</methodResponse>
</code></pre> |
1,457,131 | PHP PDO prepared statements | <p>I was told today that I should really be using PDO and prepared statements in my application. Whilst I understand the benefits, I am struggling to understand how I implement them into my workflow. Aside from the fact that it makes code much cleaner, should I have a specific database class which houses all my prepared statements or should I create one each time I want to run a query? I'm finding it very hard to understand when I should use a standard PDO query and when I should use a prepared statement. Any examples, tips or tutorial links would be greatly appreciated.</p> | 1,457,157 | 1 | 0 | null | 2009-09-21 22:01:50.777 UTC | 6 | 2022-05-10 12:06:05.68 UTC | 2012-09-03 21:13:07.583 UTC | null | 569,101 | null | 170,488 | null | 1 | 38 | php|mysql|pdo | 48,648 | <p>There are two great examples on the <a href="https://www.php.net/manual/en/pdo.prepare.php" rel="nofollow noreferrer">pdo::prepare()</a> documentation.</p>
<p>I have included them here and simplified them a bit.</p>
<p>This one uses <code>?</code> parameters. <code>$dbh</code> is basically a PDO object. And what you are doing is putting the values <code>150</code> and <code>'red'</code> into the first and second question mark respectively.</p>
<pre><code>/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
</code></pre>
<p>This one uses named parameters and is a bit more complex.</p>
<pre><code>/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql);
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
</code></pre> |
21,876,286 | Download CSV file via Rest | <p>Using OpenCSV, I can successfully create a CSV file on disc, but what I really need is to allow users download the CSV with a download button, I don't need to save on disk, just download. Any ideas? </p>
<pre><code>@GET
@Path("/downloadCsv")
public Object downloadCsv() {
CSVWriter writer;
FileWriter wr;
//Or should I use outputstream here?
wr= new FileWriter("MyFile.csv");
writer = new CSVWriter(wr,',');
for (Asset elem: assets) {
writer.writeNext(elem.toStringArray());
}
writer.close();
}
</code></pre>
<p>EDIT: I do NOT want to save/read file on disc EVER</p> | 21,876,743 | 3 | 0 | null | 2014-02-19 09:33:16.823 UTC | 6 | 2019-01-29 12:48:58.997 UTC | 2014-02-19 10:17:02.737 UTC | null | 379,028 | null | 379,028 | null | 1 | 7 | java|rest|csv|opencsv | 49,002 | <p>To force "save as", you need to set the content disposition HTTP header in the response. It should look like this:</p>
<pre><code>Content-Disposition: attachment; filename="whatever.csv"
</code></pre>
<p>It looks like you're using JAX-RS. This <a href="https://stackoverflow.com/questions/4621748/how-to-set-response-header-in-jax-rs-so-that-user-sees-download-popup-for-excel">question</a> shows how to set the header. You can either write the CSV to the HTTP response stream and set the header there or return a <code>Response</code> object like so:</p>
<pre><code>return Response.ok(myCsvText).header("Content-Disposition", "attachment; filename=" + fileName).build();
</code></pre>
<p>You do not need to write to a <code>File</code> object in the middle of this process so can avoid writing to disk.</p> |
40,272,600 | Is there a DynamoDB max partition size of 10GB for a single partition key value? | <p>I've read lots of DynamoDB docs on designing partition keys and sort keys, but I think I must be missing something fundamental.</p>
<p>If you have a bad partition key design, what happens when the data for a SINGLE partition key value exceeds 10GB?</p>
<p>The 'Understand Partition Behaviour' section states:</p>
<p>"A single partition can hold approximately 10 GB of data"</p>
<p>How can it partition a single partition key?</p>
<p><a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.Partitions" rel="noreferrer">http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.Partitions</a></p>
<p>The docs also talk about limits with a local secondary index being limited to 10GB of data after which you start getting errors.</p>
<p>"The maximum size of any item collection is 10 GB. This limit does not apply to tables without local secondary indexes; only tables that have one or more local secondary indexes are affected."</p>
<p><a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html#LSI.ItemCollections" rel="noreferrer">http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html#LSI.ItemCollections</a></p>
<p>That I can understand. So does it have some other magic for partitioning the data for a single partition key if it exceeds 10GB. Or does it just keep growing that partition? And what are the implications of that for your key design?</p>
<p>The background to the question is that I've seen lots of examples of using something like a TenantId as a partition key in a multi-tentant environment. But that seems limiting if a specific TenantId could have more than 10 GB of data.</p>
<p>I must be missing something?</p> | 40,277,185 | 1 | 0 | null | 2016-10-26 21:44:24.91 UTC | 10 | 2022-04-17 07:07:38.28 UTC | null | null | null | null | 364,098 | null | 1 | 36 | amazon-web-services|amazon-dynamodb|primary-key-design | 10,598 | <p><em>TL;DR</em> - items can be split even if they have the same partition key value by including the range key value into the partitioning function.</p>
<hr>
<p>The long version:</p>
<p>This is a very good question, and it is addressed in the documentation <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.Partitions" rel="noreferrer">here</a> and <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.Partitions.html" rel="noreferrer">here</a>. As the documentation states, items in a DynamoDB table are partitioned based on their partition key value (which used to be called <em>hash key</em>) into one or multiple partitions, using a h<a href="https://en.wikipedia.org/wiki/Hash_function" rel="noreferrer">ashing function</a>. The number of partitions is derived based on the maximum desired total throughput, as well as the distribution of items in the key space. In other words, if the partition key is chosen such that it distributes items uniformly across the partition key space, the partitions end up having approximately the same number of items each. This number of items in each partition is approximately equal to the total number of items in the table divided by the number of partitions.</p>
<p>The documentation also states that each partition is limited to about 10GB of space. And that once the sum of the sizes of all items stored in any partition grows beyond 10GB, DynamoDB will start a background process that will automatically and transparently split such partitions in half - resulting in two new partitions. Once again, if the items are distributed uniformly, this is great because each new sub-partition will end up holding roughly half the items in the original partition.</p>
<p>An important aspect to splitting is that the throughput of the split-partitions will each be half of the throughput that would have been available for the original partition.</p>
<p>So far we've covered the happy case.</p>
<p>On the flip side it is possible to have one, or a few, partition key values that correspond to a very large number of items. This can usually happen if the table schema uses a sort key and several items hash to the same partition key. In such case, it is possible that a single partition key could be responsible for items that together take up more than 10 GB. And this will result in a split. In this case DynamoDB will still create two new partitions but instead of using only the partition key to decide which sub-partition should an item be stored in, it will also use the sort key.</p>
<p><strong>Example</strong></p>
<p>Without loss of generality and to make things easier to reason about, imagine that there is a table where partition keys are letters (A-Z), and numbers are used as sort keys.</p>
<p>Imaging that the table has about 9 partitions, so letters A,B,C would be stored in partition 1, letters D,E,F would be in partition 2, etc.</p>
<p>In the diagram below, the partition boundaries are marked <code>h(A0)</code>, <code>h(D0)</code> etc. to show that, for instance, the items stored in the first partition are the items who's partition key hashes to a value between <code>h(A0)</code> and <code>h(D0)</code> - the <code>0</code> is intentional, and comes in handy next. </p>
<pre><code>[ h(A0) ]--------[ h(D0) ]---------[ h(G0) ]-------[ h(J0) ]-------[ h(M0) ]- ..
| A B C | E F | G I | J K L |
| 1 1 1 | 1 1 | 1 1 | 1 1 1 |
| 2 2 2 | 2 2 | 2 | 2 |
| 3 3 | 3 | 3 | |
.. .. .. .. ..
| 100 | 500 | | |
+-----------------+----------------+---------------+---------------+-- ..
</code></pre>
<p>Notice that for most partition key values, there are between 1 and 3 items in the table, but there are two partition key values: <code>D</code> and <code>F</code> that are not looking too good. <code>D</code> has 100 items while <code>F</code> has 500 items.</p>
<p>If items with a partition key value of <code>F</code> keep getting added, eventually the partition <code>[h(D0)-h(G0))</code> will split. To make it possible to split the items that have the same hash key, the range key values will have to be used, so we'll end up with the following situation:</p>
<pre><code>..[ h(D0) ]------------/ [ h(F500) ] / ----------[ h(G0) ]- ..
| E F | F |
| 1 1 | 501 |
| 2 2 | 502 |
| 3 | 503 |
.. .. ..
| 500 | 1000 |
.. ---+-----------------------+---------------------+--- ..
</code></pre>
<p>The original partition <code>[h(D0)-h(G0))</code> was split into <code>[h(D0)-h(F500))</code> and <code>[h(F500)-h(G0))</code></p>
<p>I hope this helps to visualize that items are generally mapped to partitions based on a hash value obtained by applying a hashing function to their partition key value, but if need be, the value being hashed can include the partition key + a sort key value as well. </p> |
38,564,080 | Remove Event Listener On Unmount React | <p>I had higher order component in react like this:</p>
<pre><code>export default function (InnerComponent) {
class InfiniteScrolling extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
window.addEventListener('scroll', this.onScroll.bind(this), false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll.bind(this), false);
}
onScroll() {
if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 50)) {
const { scrollFunc } = this.props;
scrollFunc();
}
}
render() {
return <InnerComponent {...this.props} />;
}
}
InfiniteScrolling.propTypes = {
scrollFunc: PropTypes.func.isRequired
};
return InfiniteScrolling;
}
</code></pre>
<p>After unmounting the component which are been wrapped via <code>InfiniteScrolling</code>, they where still throwing the error like (when I did scrolling):</p>
<blockquote>
<p>Warning: setState(...): Can only update a mounted or mounting
component. This usually means you called setState() on an unmounted
component. This is a no-op. Please check the code for the undefined
component.</p>
</blockquote>
<p>Even though I did remove the <code>scroll</code> event on my component unmount. It didn't work. </p>
<p>But when I changed the code to like this:</p>
<pre><code>constructor(props){
super(props);
this.onScroll = this.onScroll.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll, false);
}
</code></pre>
<p>everything seems to be working fine, without any issues. </p>
<p>I feel they are exactly the same thing, but the second one works fine while the first one was throwing up the error in the console as mentioned before!</p> | 38,564,123 | 4 | 0 | null | 2016-07-25 09:26:38.57 UTC | 12 | 2020-11-23 14:35:35.593 UTC | null | null | null | null | 576,682 | null | 1 | 56 | javascript|reactjs | 82,745 | <p><code>.bind</code> always creates a new function so you need to do like below, so it adds and removes the same function.</p>
<pre><code> constructor(props){
super(props);
this.onScroll = this.onScroll.bind(this); //bind function once
}
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
// you need to unbind the same listener that was binded.
window.removeEventListener('scroll', this.onScroll, false);
}
</code></pre> |
38,649,501 | Labeling boxplot in seaborn with median value | <p>How can I label each boxplot in a seaborn plot with the median value?</p>
<p>E.g.</p>
<pre><code>import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)
</code></pre>
<p>How do I label each boxplot with the median or average value?</p> | 38,649,932 | 3 | 0 | null | 2016-07-29 02:13:10.457 UTC | 10 | 2022-05-06 05:44:44.477 UTC | null | null | null | null | 308,827 | null | 1 | 33 | python|matplotlib|seaborn | 54,329 | <p>I love when people include sample datasets!</p>
<pre><code>import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
box_plot = sns.boxplot(x="day",y="total_bill",data=tips)
medians = tips.groupby(['day'])['total_bill'].median()
vertical_offset = tips['total_bill'].median() * 0.05 # offset from median for display
for xtick in box_plot.get_xticks():
box_plot.text(xtick,medians[xtick] + vertical_offset,medians[xtick],
horizontalalignment='center',size='x-small',color='w',weight='semibold')
</code></pre>
<p><a href="https://i.stack.imgur.com/dIGlL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dIGlL.png" alt="enter image description here"></a></p> |
31,605,932 | How to make a owl carousel with arrows instead of next previous | <p>Yesterday I presented a website to a customer. I always use Owl carousel since it's responsive. The client, however, hated the previous, next words, and wanted to change them to arrows. </p>
<p>So hence I updated my script. js file. It was very easy to do and I wanted to share it. </p>
<pre><code>$(document).ready(function(){
$('.owl-carousel').owlCarousel({
nav:true,
responsive:{
...
})
$( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
$( ".owl-next").html('<i class="fa fa-chevron-right"></i>');
});
</code></pre>
<p>Well there you have it. You can always add more styling. (First time I use an answer to your own question hope this is the right place/way)</p> | 31,605,933 | 6 | 0 | null | 2015-07-24 08:41:50.707 UTC | 10 | 2020-04-26 15:33:00.917 UTC | 2020-04-26 15:33:00.917 UTC | null | 1,979,115 | null | 3,806,549 | null | 1 | 29 | javascript|jquery|carousel | 204,576 | <p>This is how you do it in your <code>$(document).ready()</code> function with FontAwesome Icons:</p>
<pre><code> $( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
$( ".owl-next").html('<i class="fa fa-chevron-right"></i>');
</code></pre> |
35,315,726 | Plotly: How to display charts in Spyder? | <p>Since November 2015, plotly is Open-Source and available for python. <a href="https://plot.ly/javascript/open-source-announcement/" rel="noreferrer">https://plot.ly/javascript/open-source-announcement/</a></p>
<p>When trying to do some plots offline, these work in iPython Notebook (version 4.0.4)
But if I try to run them in Spyder (version 2.3.8), i just get the following output:</p>
<pre><code><IPython.core.display.HTML object>
<IPython.core.display.HTML object>
</code></pre>
<p>There's something wrong in my code or the iPython Terminal of Spyder still doesn't support this?</p>
<p>Here goes the example code (taken from <a href="https://www.reddit.com/r/IPython/comments/3tibc8/tip_on_how_to_run_plotly_examples_in_offline_mode/" rel="noreferrer">https://www.reddit.com/r/IPython/comments/3tibc8/tip_on_how_to_run_plotly_examples_in_offline_mode/</a>)</p>
<pre><code>from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
trace0 = Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers',
marker=dict(
size=[40, 60, 80, 100],
)
)
data = [trace0]
layout = Layout(
showlegend=False,
height=600,
width=600,
)
fig = dict( data=data, layout=layout )
iplot(fig)
</code></pre> | 35,393,328 | 2 | 0 | null | 2016-02-10 12:46:51.4 UTC | 6 | 2021-11-16 06:30:20.017 UTC | 2021-10-25 09:30:37.29 UTC | null | 3,437,787 | null | 5,235,265 | null | 1 | 25 | python|python-2.7|plotly|spyder|plotly-python | 51,746 | <p>importing plot instead iplot (and changing the last line from iplot(fig) to plot(fig) resolved the problem, at least in python 3: </p>
<pre><code>from plotly.offline import download_plotlyjs, init_notebook_mode, plot
from plotly.graph_objs import *
init_notebook_mode()
trace0 = Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers',
marker=dict(
size=[40, 60, 80, 100],
)
)
data = [trace0]
layout = Layout(
showlegend=False,
height=600,
width=600,
)
fig = dict( data=data, layout=layout )
plot(fig)
</code></pre>
<p>But instead you could do the following, which is slightly easier:</p>
<pre><code>import plotly
import plotly.graph_objs
plotly.offline.plot({
"data": [
plotly.graph_objs.Scatter( x=[1, 2, 3, 4],
y=[10, 11, 12, 13], mode='markers',
marker=dict(
size=[40, 60, 80, 100]))],
"layout": plotly.graph_objs.Layout(showlegend=False,
height=600,
width=600,
)
})
</code></pre> |
28,008,775 | How do I get the current x and y position so that I can use GCRectMake? | <p>I have this code inside an animation:</p>
<pre><code>image.frame = CGRectMake(x: x, y: y, width, height)
</code></pre>
<p>I need to get the x and y coordinates of an image. I found this Objective-C code:</p>
<pre><code>CGPoint origin = imageView.frame.origin;
</code></pre>
<p>Once I find the x and y position of the image, I will need to transform it. I will use something like:</p>
<pre><code>image.frame = CGRectMake(x-50, y-50, width+500, height+500)
</code></pre>
<p>...so that I can move the image around the screen. How do I find the original x and y positions?</p> | 28,008,868 | 1 | 0 | null | 2015-01-18 10:41:59.97 UTC | 8 | 2018-06-01 10:40:39.697 UTC | 2016-06-08 05:22:52.447 UTC | null | 1,135,714 | null | 1,135,714 | null | 1 | 32 | ios|swift|cgrectmake | 82,787 | <p>Do you mean you want this?</p>
<pre><code>var frm: CGRect = imageView.frame
frm.origin.x = frm.origin.x - 50
frm.origin.y = frm.origin.y - 50
frm.size.width = frm.size.width + 500
frm.size.height = frm.size.height + 500
imageView.frame = frm
</code></pre> |
40,420,240 | Grouped Bar graph Pandas | <p>I have a table in a pandas <code>DataFrame</code> named <code>df</code>:</p>
<pre><code>+--- -----+------------+-------------+----------+------------+-----------+
|avg_views| avg_orders | max_views |max_orders| min_views |min_orders |
+---------+------------+-------------+----------+------------+-----------+
| 23 | 123 | 135 | 500 | 3 | 1 |
+---------+------------+-------------+----------+------------+-----------+
</code></pre>
<p>What I am looking for now is to plot a grouped bar graph which shows me
(avg, max, min) of views and orders in one single bar chart.</p>
<p>i.e on x axis there would be Views and orders separated by a distance
and 3 bars of (avg, max, min) for views and similarly for orders.</p>
<p>I have attached a sample bar graph image, just to know how the bar graph should look.</p>
<p><a href="https://i.stack.imgur.com/M2Tdy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M2Tdy.png" alt="just sample: green color should be for avg, yellow for max and pin"></a>
Green color should be for avg, yellow for max and pink for avg.</p>
<p>I took the following code from <a href="https://stackoverflow.com/questions/11597785/setting-spacing-between-grouped-bar-plots-in-matplotlib">setting spacing between grouped bar plots in matplotlib</a> but it is not working for me:</p>
<pre><code>plt.figure(figsize=(13, 7), dpi=300)
groups = [[23, 135, 3], [123, 500, 1]]
group_labels = ['views', 'orders']
num_items = len(group_labels)
ind = np.arange(num_items)
margin = 0.05
width = (1. - 2. * margin) / num_items
s = plt.subplot(1, 1, 1)
for num, vals in enumerate(groups):
print 'plotting: ', vals
# The position of the xdata must be calculated for each of the two data
# series.
xdata = ind + margin + (num * width)
# Removing the "align=center" feature will left align graphs, which is
# what this method of calculating positions assumes.
gene_rects = plt.bar(xdata, vals, width)
s.set_xticks(ind + 0.5)
s.set_xticklabels(group_labels)
</code></pre>
<blockquote>
<p>plotting: [23, 135, 3]
...
ValueError: shape mismatch: objects cannot be broadcast to a single shape</p>
</blockquote> | 40,421,601 | 2 | 3 | null | 2016-11-04 10:22:55.38 UTC | 8 | 2021-09-12 17:51:07.343 UTC | 2021-09-12 17:51:07.343 UTC | null | 7,758,804 | null | 6,803,114 | null | 1 | 25 | python|pandas|matplotlib | 65,135 | <p>Using pandas:</p>
<pre><code>import pandas as pd
groups = [[23,135,3], [123,500,1]]
group_labels = ['views', 'orders']
# Convert data to pandas DataFrame.
df = pd.DataFrame(groups, index=group_labels).T
# Plot.
pd.concat(
[df.mean().rename('average'), df.min().rename('min'),
df.max().rename('max')],
axis=1).plot.bar()
</code></pre>
<p><a href="https://i.stack.imgur.com/4WzbH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4WzbH.png" alt="Result plot"></a></p> |
50,824,617 | Angular Material table Sizing/Scroll | <p>I have an Angular Material table with many columns. It is wider than the screen. When I scroll, the table rows extend past the edge of the table container.</p>
<p>See this StackBlitz project. <a href="https://stackblitz.com/edit/angular-r6xdgk" rel="noreferrer">https://stackblitz.com/edit/angular-r6xdgk</a> Use the scrollbar at the bottom and you will see the strange formatting.</p>
<p>Thanks in advance for any help!</p> | 50,824,892 | 4 | 0 | null | 2018-06-12 19:37:37.26 UTC | 4 | 2021-06-21 12:27:22.197 UTC | null | null | null | null | 6,019,611 | null | 1 | 17 | angular|angular-material | 66,882 | <p>Add </p>
<pre><code>.example-container {
overflow-x: scroll;
}
</code></pre>
<p>To the app.component.css to fix the top bar.
The bottom will need a similar styling. You can't use width:100% because it is technically outside the table. So it can not pick up the width automatically.</p> |
20,909,118 | The remote server returned an error: (415) Unsupported Media Type | <p>I try to upload a text file from <strong>WPF RESTful client to ASP .NET MVC WebAPI 2 website</strong>.</p>
<p><strong>Client code</strong></p>
<pre><code>HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:22678/api/Account/UploadFile?fileName=test.txt&description=MyDesc1");
request.Method = WebRequestMethods.Http.Post;
request.Headers.Add("Authorization", "Bearer " + tokenModel.ExternalAccessToken);
request.ContentType = "text/plain";
request.MediaType = "text/plain";
byte[] fileToSend = File.ReadAllBytes(@"E:\test.txt");
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
</code></pre>
<p><strong>WebAPI 2 code</strong></p>
<pre><code>[HttpPost]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UploadFile")]
public void UploadFile(string fileName, string description, Stream fileContents)
{
byte[] buffer = new byte[32768];
MemoryStream ms = new MemoryStream();
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileContents.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
ms.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
var data = ms.ToArray() ;
ms.Close();
Debug.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead);
}
</code></pre>
<p>So.. Under the client code I am facing that exception</p>
<blockquote>
<p>The remote server returned an error: (415) Unsupported Media Type.</p>
</blockquote>
<p>Any clue what do I am missing?</p> | 20,909,515 | 2 | 0 | null | 2014-01-03 17:14:42.343 UTC | 2 | 2014-01-03 18:00:06.133 UTC | null | null | null | null | 196,919 | null | 1 | 7 | c#|asp.net-web-api|httpwebrequest|media-type | 58,186 | <p>+1 on what Radim has mentioned above...As per your action Web API model binding notices that the parameter <code>fileContents</code> is a complex type and by default assumes to read the request body content using the formatters. (note that since <code>fileName</code> and <code>description</code> parameters are of <code>string</code> type, they are expected to come from uri by default).</p>
<p>You can do something like the following to prevent model binding to take place:</p>
<pre><code>[HttpPost]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UploadFile")]
public async Task UploadFile(string fileName, string description)
{
byte[] fileContents = await Request.Content.ReadAsByteArrayAsync();
....
}
</code></pre>
<p>BTW, what do you plan to do with this <code>fileContents</code>? are you trying to create a local file? if yes, there is a better way to handle this.</p>
<p><strong>Update based on your last comment</strong>:</p>
<p>A quick example of what you could do</p>
<pre><code>[HttpPost]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UploadFile")]
public async Task UploadFile(string fileName, string description)
{
Stream requestStream = await Request.Content.ReadAsStreamAsync();
//TODO: Following are some cases you might need to handle
//1. if there is already a file with the same name in the folder
//2. by default, request content is buffered and so if large files are uploaded
// then the request buffer policy needs to be changed to be non-buffered to imporve memory usage
//3. if exception happens while copying contents to a file
using(FileStream fileStream = File.Create(@"C:\UploadedFiles\" + fileName))
{
await requestStream.CopyToAsync(fileStream);
}
// you need not close the request stream as Web API would take care of it
}
</code></pre> |