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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,987,060 | What is the meaning of id? | <p>I am (trying to) learn Objective-C and I keep coming across a phrase like:</p>
<pre><code>-(id) init;
</code></pre>
<p>And I understand <code>id</code> is an Objective C language keyword, but what does it mean to say "the compiler specifically treats <code>id</code> in terms of the pointer type conversion rules"?</p>
<p>Does <code>id</code> automatically designate the object to its right as a pointer?</p> | 7,987,169 | 5 | 3 | null | 2011-11-02 20:43:06.29 UTC | 23 | 2021-01-29 03:13:20.033 UTC | 2012-07-07 07:40:01.7 UTC | null | 603,977 | null | 997,365 | null | 1 | 111 | objective-c|types | 74,475 | <p><code>id</code> is a pointer to any type, but unlike <code>void *</code> it always points to an Objective-C object. For example, you can add anything of type <code>id</code> to an NSArray, but those objects must respond to <code>retain</code> and <code>release</code>.</p>
<p>The compiler is totally happy for you to implicitly cast any object to <code>id</code>, and for you to cast <code>id</code> to any object. This is unlike any other implicit casting in Objective-C, and is the basis for most container types in Cocoa.</p> |
8,202,053 | Socket.IO - require is not defined | <p>I'm trying to get socket.io working but now in Chrome I get the error:</p>
<p><strong>Uncaught ReferenceError: require is not defined</strong></p>
<p><strong>client.php:9Uncaught ReferenceError: io is not defined</strong></p>
<p>I changed the way to include the socket.io.js file because it dosnt exists somewher else:</p>
<pre><code><script src="/node_modules/socket.io/lib/socket.io.js"></script>
</code></pre>
<p>If I try </p>
<pre><code><script src="/socket.io/socket.io.js"></script>
</code></pre>
<p>I get: <strong>Failed to load resource: the server responded with a status of 404 (Not Found)</strong></p>
<p>This is on Ubuntu with the latest of everything</p>
<p>I'm using the server code from <a href="http://socket.io/" rel="noreferrer">http://socket.io/</a> to work with in the same folder like client.php and that works, named server.js, only modified port.</p> | 8,202,186 | 8 | 4 | null | 2011-11-20 14:10:55.447 UTC | 8 | 2014-02-17 19:08:06.553 UTC | 2011-11-22 14:57:14.013 UTC | null | 102,704 | null | 1,049,661 | null | 1 | 18 | html|node.js|socket.io | 30,260 | <p>If your script isn't coming from your webserver, this will not work:</p>
<pre><code><script src="/socket.io/socket.io.js"></script>
</code></pre>
<p>You have to explicitely state host and port:</p>
<pre><code><script src="http://localhost:<port>/socket.io/socket.io.js"></script>
</code></pre> |
8,041,703 | Remove White Background from an Image and Make It Transparent | <p>We're trying to do the following in Mathematica - <a href="https://stackoverflow.com/questions/7738437">RMagick remove white background from image and make it transparent</a>.</p>
<p>But with actual photos it ends up looking lousy (like having a halo around the image).</p>
<p>Here's what we've tried so far:</p>
<pre><code>unground0[img_] := With[{mask = ChanVeseBinarize[img, TargetColor->{1.,1.,1.}]},
Rasterize[SetAlphaChannel[img, ImageApply[1-#&, mask]], Background->None]]]
</code></pre>
<p>Here's an example of what that does.</p>
<p>Original image:</p>
<p><img src="https://i.stack.imgur.com/k7E1F.png" alt="original image"></p>
<p>Image with the white background replaced with no background (or, for demonstration purposes here, a pink background):</p>
<p><img src="https://i.stack.imgur.com/lbVKT.png" alt="image with transparent background -- actually a pink background here, to make the halo problem obvious"></p>
<p>Any ideas for getting rid of that halo? Tweaking things like LevelPenalty, I can only get the halo to go away at the expense of losing some of the image.</p>
<p>EDIT: So I can compare solutions for the bounty, please structure your solution like above, namely a self-contained function named unground-something that takes an image and returns an image with transparent background.</p> | 8,050,421 | 9 | 15 | null | 2011-11-07 19:48:16.963 UTC | 44 | 2021-11-05 21:29:52.93 UTC | 2019-10-17 23:26:40.583 UTC | null | 195,787 | null | 4,234 | null | 1 | 83 | image|image-processing|wolfram-mathematica|masking | 21,217 | <p>Perhaps, depending on the edge quality you need:</p>
<pre><code>img = Import@"http://i.stack.imgur.com/k7E1F.png";
mask = ChanVeseBinarize[img, TargetColor -> {1., 1., 1.}, "LengthPenalty" -> 10]
mask1 = Blur[Erosion[ColorNegate[mask], 2], 5]
Rasterize[SetAlphaChannel[img, mask1], Background -> None]
</code></pre>
<p><img src="https://i.stack.imgur.com/6pLo7.png" alt="enter image description here"></p>
<p><strong>Edit</strong></p>
<p><a href="http://www.antimoon.com/forum/t6720.htm" rel="noreferrer"><code>Stealing a bit from @Szabolcs</code></a></p>
<pre><code>img2 = Import@"http://i.stack.imgur.com/k7E1F.png";
(*key point:scale up image to smooth the edges*)
img = ImageResize[img2, 4 ImageDimensions[img2]];
mask = ChanVeseBinarize[img, TargetColor -> {1., 1., 1.}, "LengthPenalty" -> 10];
mask1 = Blur[Erosion[ColorNegate[mask], 8], 10];
f[col_] := Rasterize[SetAlphaChannel[img, mask1], Background -> col,
ImageSize -> ImageDimensions@img2]
GraphicsGrid[{{f@Red, f@Blue, f@Green}}]
</code></pre>
<p><a href="https://i.stack.imgur.com/anny7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/anny7.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/anny7.png" rel="noreferrer"><h3>Click to enlarge</h3></a></p>
<p><strong>Edit 2</strong></p>
<p>Just to get an idea of the extent of the <em>halo</em> and background imperfections in the image:</p>
<pre><code>img = Import@"http://i.stack.imgur.com/k7E1F.png";
Join[{img}, MapThread[Binarize, {ColorSeparate[img, "HSB"], {.01, .01, .99}}]]
</code></pre>
<p><img src="https://i.stack.imgur.com/8l2K0.png" alt="enter image description here"></p>
<pre><code>ColorNegate@ImageAdd[EntropyFilter[img, 1] // ImageAdjust, ColorNegate@img]
</code></pre>
<p><img src="https://i.stack.imgur.com/vVfuE.png" alt="enter image description here"></p> |
4,572,314 | Graphical user interface Tutorial in C | <p>I have a project in C language and the teacher ordered to make a Gui of project.
I can only use C or C++ for the GUI part.</p>
<p>Can anyone please suggest me Some easy open source Graphics Library Tutorial because this will be my first ever GUI.</p>
<p>thanks</p> | 4,572,322 | 3 | 1 | null | 2010-12-31 21:09:42.803 UTC | 21 | 2021-06-07 14:08:01.393 UTC | 2010-12-31 22:15:57.643 UTC | null | 301,832 | null | 534,408 | null | 1 | 23 | c|user-interface | 111,988 | <p>The two most usual choices are <a href="http://www.gtk.org/" rel="nofollow noreferrer">GTK+</a>, which has documentation links <a href="http://www.gtk.org/docs/" rel="nofollow noreferrer">here</a>, and is mostly used with C; or <a href="http://qt-project.org/" rel="nofollow noreferrer">Qt</a> which has documentation <a href="http://qt-project.org/doc/latest" rel="nofollow noreferrer">here</a> and is more used with C++.</p>
<p>I posted these two as you do not specify an operating system and these two are pretty cross-platform.</p> |
4,503,437 | Android HttpClient Doesn't Use System Proxy Settings | <p>When I create a <a href="http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html" rel="noreferrer">DefaultHttpClient</a> object and try to hit a webpage, the request isn't routed through the proxy I specified in Settings.</p>
<p>Looking through the API docs, I don't see anywhere where I can specify a proxy though Android does have a <a href="http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html" rel="noreferrer">Proxy</a> class that allows me to read the system's proxy settings.</p>
<p>Is there a way I can use the proxy settings in an HttpClient?</p> | 4,503,990 | 4 | 3 | null | 2010-12-21 20:09:50.067 UTC | 11 | 2015-09-25 14:25:28.23 UTC | null | null | null | null | 680 | null | 1 | 13 | android|proxy|httpclient | 19,811 | <p>Try:</p>
<pre><code>DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHost proxy = new HttpHost("someproxy", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
</code></pre>
<p>(culled from <a href="http://improve.ro/2010/10/proxy-settings-with-httpclient-and-spring/">here</a>)</p> |
4,718,071 | How can I run my python script from the terminal in Mac OS X without having to type the full path? | <p>I'm on Mac OS 10.6 Snow Leopard and I'm trying to add a directory to my PATH variable so I can run a tiny script I wrote by just typing: python alarm.py at the terminal prompt.</p>
<p>I put the path in my .profile file and it seems to show up when I echo $PATH, but python still can't find script the that I've put in that directory. </p>
<p>Here's the contents of my .profile file in my home directory:</p>
<pre><code>~ toby$ vim .profile
export PATH=/Users/tobylieven/Documents/my_scripts:$PATH
</code></pre>
<p>Here's the output of echo $PATH, where all seems well:</p>
<pre><code>~ toby$ echo $PATH
/Users/tobylieven/Documents/my_scripts:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
</code></pre>
<p>Here's the script I'm trying to run:</p>
<pre><code>~ toby$ ls /Users/tobylieven/Documents/my_scripts
-rwxrwxrwx@ 1 tobylieven staff 276 17 Jan 21:17 alarm.py
</code></pre>
<p>Here's the command I'm trying to use to run the script and the fail message I'm getting instead:</p>
<pre><code>~ toby$ python alarm.py
python: can't open file 'alarm.py': [Errno 2] No such file or directory
</code></pre>
<p>If anyone has an idea what I might be doing wrong, that'd be great.
Thanks a lot. </p> | 4,718,135 | 5 | 0 | null | 2011-01-17 21:25:23.43 UTC | 5 | 2019-05-21 23:34:41.723 UTC | null | null | null | null | 579,046 | null | 1 | 10 | python|macos|path|terminal | 47,677 | <p>PATH is only for executables, not for python scripts. Add the following to the beginning of your Python script:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>and run</p>
<pre><code>sudo chmod a+x /Users/tobylieven/Documents/my_scripts/alarm.py
</code></pre>
<p>Then, you can type just <code>alarm.py</code> to execute your program.</p> |
4,608,470 | Why dec 31 2010 returns 1 as week of year? | <p>For instance:</p>
<pre><code>Calendar c = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
c.setTime( sdf.parse("31/12/2010"));
out.println( c.get( Calendar.WEEK_OF_YEAR ) );
</code></pre>
<p>Prints 1</p>
<p>Same happens with Joda time. </p>
<p>:) </p> | 4,608,695 | 5 | 4 | null | 2011-01-05 19:43:19.65 UTC | 5 | 2018-05-25 18:38:57.887 UTC | 2011-01-06 10:02:27.3 UTC | null | 71,059 | null | 20,654 | null | 1 | 30 | java|calendar|jodatime|week-number | 22,500 | <p><strong>The definition of Week of Year is <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html" rel="noreferrer"><code>Locale</code></a> dependent.</strong></p>
<p>How it is defined in US is discused in the other posts. For example in Germany (<a href="https://de.wikipedia.org/wiki/DIN_1355-1" rel="noreferrer">DIN 1355-1</a> / <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a>): the first Week* of Year is the first week with 4 or more days in the new year.</p>
<p><em>*first day of week is Monday and last day of week is Sunday</em></p>
<p>And Java’s <code>Calendar</code> pays attention to the locale. For example:</p>
<pre><code>public static void main(String[] args) throws ParseException {
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date lastDec2010 = sdf.parse("31/12/2010");
Calendar calUs = Calendar.getInstance(Locale.US);
calUs.setTime(lastDec2010);
Calendar calDe = Calendar.getInstance(Locale.GERMAN);
calDe.setTime(lastDec2010);
System.out.println( "us: " + calUs.get( Calendar.WEEK_OF_YEAR ) );
System.out.println( "de: " + calDe.get( Calendar.WEEK_OF_YEAR ) );
}
</code></pre>
<p>prints:</p>
<pre><code>us: 1
de: 52
</code></pre>
<p><strong>ADDED</strong>
For the US (and I can think of that it is the same for Mexico) the 1. Week of Year is the week where the 1. January belongs to. -- So if 1. Januar is a Saturday, then the Friday before (31. Dec) belongs the same week, and in this case this day belongs to the 1. Week of Year 2011.</p> |
4,574,912 | CSS content generation before or after 'input' elements | <p>In Firefox 3 and Google Chrome 8.0 the following works as expected:</p>
<pre><code><style type="text/css">
span:before { content: 'span: '; }
</style>
<span>Test</span> <!-- produces: "span: Test" -->
</code></pre>
<p>But it doesn't when the element is <code><input></code>:</p>
<pre><code><style type="text/css">
input:before { content: 'input: '; }
</style>
<input type="text"></input> <!-- produces only the textbox; the generated content
is nowhere to be seen in both FF3 and Chrome 8 -->
</code></pre>
<p>Why is it not working like I expected?</p> | 4,574,946 | 5 | 4 | null | 2011-01-01 17:29:18.617 UTC | 27 | 2020-03-10 11:00:01.163 UTC | 2015-04-14 13:09:46.53 UTC | null | 800,457 | null | 180,581 | null | 1 | 221 | html|css | 256,376 | <p>With <code>:before</code> and <code>:after</code> you specify which content should be inserted before (or after) <strong>the content</strong> inside of that element. <code>input</code> elements have no content.</p>
<p>E.g. if you write <code><input type="text">Test</input></code> (which is wrong) the browser will correct this and put the text <em>after</em> the input element.</p>
<p>The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.</p>
<p>See the examples in the <a href="http://www.w3.org/TR/CSS2/generate.html#before-after-content" rel="noreferrer">specification</a>:</p>
<blockquote>
<p>For example, the following document fragment and style sheet:</p>
<pre><code><h2> Header </h2> h2 { display: run-in; }
<p> Text </p> p:before { display: block; content: 'Some'; }
</code></pre>
<p>...would render in exactly the same way as the following document fragment and style sheet:</p>
<pre><code><h2> Header </h2> h2 { display: run-in; }
<p><span>Some</span> Text </p> span { display: block }
</code></pre>
</blockquote>
<p>This is the same reason why it does not work for <code><br></code>, <code><img></code>, etc. (<code><textarea></code> seems to be special).</p> |
4,541,556 | Pushing an array into a vector | <p>I've a 2d array, say <code>A[2][3]={{1,2,3},{4,5,6}};</code> and I want to push it into a 2D vector(vector of vectors). I know you can use two <code>for loops</code> to push the elements one by on on to the first vector and then push that into the another vector which makes it 2d vector but I was wondering if there is any way in C++ to do this in a single loop. For example I want to do something like this:</p>
<pre><code>myvector.pushback(A[1]+3); // where 3 is the size or number of columns in the array.
</code></pre>
<p>I understand this is not a correct code but I put this just for understanding purpose. Thanks</p> | 4,541,707 | 8 | 0 | null | 2010-12-27 20:22:44.313 UTC | 3 | 2013-08-28 12:29:14.593 UTC | null | null | null | null | 419,074 | null | 1 | 7 | c++|vector | 41,632 | <p>The new C++0x standard defines <code>initializer_lists</code> which allows you to:</p>
<pre><code>vector<vector<int>> myvector = {{1,2,3},{4,5,6}};
</code></pre>
<p>gcc 4.3+ and some other compilers have partial C++0x support.
for gcc 4.3+ you could enable c++0x support by adding the flag <code>-std=c++0x</code></p>
<p>Its not the best way to have your static data represented like that. However, if your compiler vendor supports C++ tr1 then you could do:</p>
<pre><code>#include <tr1/array> // or #include <array>
...
typedef vector<vector<int> > vector2d;
vector2d myvector;
// initialize the vectors
myvector.push_back(vector<int>());
myvector.push_back(vector<int>());
typedef std::array<std::array<int, 3>, 2> array2d;
array2d array = {{1,2,3},{4,5,6}};
array2d::const_iterator ai = array.begin(), ae = array.end();
for (vector2d::iterator i = myvector.begin(), e = myvector.end()
; i != e && ai != ae
; i++, a++)
{
// reserve vector space
i->reserve(array.size());
// copy array content to vector
std::copy(ai.begin(), ai->end(), i->begin());
}
</code></pre> |
4,495,433 | UISlider with ProgressView combined | <p>Is there an apple-house-made way to get a UISlider with a ProgressView. This is used by many streaming applications e.g. native quicktimeplayer or youtube.
(Just to be sure: i'm only in the visualization interested)</p>
<p><img src="https://i.stack.imgur.com/8Nie9.png" alt="Slider with loader"></p>
<p>cheers Simon</p> | 4,576,320 | 9 | 1 | null | 2010-12-21 00:54:51.43 UTC | 40 | 2020-10-17 11:41:48.97 UTC | 2010-12-22 00:09:10.403 UTC | null | 330,658 | null | 330,658 | null | 1 | 38 | objective-c|ios4|streaming|uislider|uiprogressview | 25,989 | <p>Here's a simple version of what you're describing.</p>
<p><img src="https://i.stack.imgur.com/49eyY.png" alt="alt text"></p>
<p>It is "simple" in the sense that I didn't bother trying to add the shading and other subtleties. But it's easy to construct and you can tweak it to draw in a more subtle way if you like. For example, you could make your own image and use it as the slider's thumb.</p>
<p>This is actually a UISlider subclass lying on top of a UIView subclass (MyTherm) that draws the thermometer, plus two UILabels that draw the numbers. </p>
<p>The UISlider subclass eliminates the built-in track, so that the thermometer behind it shows through. But the UISlider's thumb (knob) is still draggable in the normal way, and you can set it to a custom image, get the Value Changed event when the user drags it, and so on. Here is the code for the UISlider subclass that eliminates its own track:</p>
<pre><code>- (CGRect)trackRectForBounds:(CGRect)bounds {
CGRect result = [super trackRectForBounds:bounds];
result.size.height = 0;
return result;
}
</code></pre>
<p>The thermometer is an instance of a custom UIView subclass, MyTherm. I instantiated it in the nib and unchecked its Opaque and gave it a background color of Clear Color. It has a <code>value</code> property so it knows how much to fill the thermometer. Here's its <code>drawRect:</code> code:</p>
<pre><code>- (void)drawRect:(CGRect)rect {
CGContextRef c = UIGraphicsGetCurrentContext();
[[UIColor whiteColor] set];
CGFloat ins = 2.0;
CGRect r = CGRectInset(self.bounds, ins, ins);
CGFloat radius = r.size.height / 2.0;
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, CGRectGetMaxX(r) - radius, ins);
CGPathAddArc(path, NULL, radius+ins, radius+ins, radius, -M_PI/2.0, M_PI/2.0, true);
CGPathAddArc(path, NULL, CGRectGetMaxX(r) - radius, radius+ins, radius, M_PI/2.0, -M_PI/2.0, true);
CGPathCloseSubpath(path);
CGContextAddPath(c, path);
CGContextSetLineWidth(c, 2);
CGContextStrokePath(c);
CGContextAddPath(c, path);
CGContextClip(c);
CGContextFillRect(c, CGRectMake(r.origin.x, r.origin.y, r.size.width * self.value, r.size.height));
}
</code></pre>
<p>To change the thermometer value, change the MyTherm instance's <code>value</code> to a number between 0 and 1, and tell it to redraw itself with <code>setNeedsDisplay</code>.</p> |
4,421,681 | How to count the number of arguments passed to a function that accepts a variable number of arguments? | <p>How to count the no of arguments passed to the function in following program:</p>
<pre><code>#include<stdio.h>
#include<stdarg.h>
void varfun(int i, ...);
int main(){
varfun(1, 2, 3, 4, 5, 6);
return 0;
}
void varfun(int n_args, ...){
va_list ap;
int i, t;
va_start(ap, n_args);
for(i=0;t = va_arg(ap, int);i++){
printf("%d", t);
}
va_end(ap);
}
</code></pre>
<p>This program's output over my gcc compiler under ubuntu 10.04: </p>
<pre><code>234561345138032514932134513792
</code></pre>
<p>so how to find how many no. of arguments actually passed to the function?</p> | 4,421,702 | 12 | 3 | null | 2010-12-12 12:40:16.16 UTC | 13 | 2021-09-03 10:51:16.527 UTC | 2010-12-12 12:43:29.253 UTC | null | 41,116 | null | 525,342 | null | 1 | 51 | c|variadic-functions | 61,946 | <p>You can't. You have to manage for the caller to indicate the number of arguments somehow. You can:</p>
<ul>
<li>Pass the number of arguments as the first variable</li>
<li>Require the last variable argument to be null, zero or whatever</li>
<li>Have the first argument describe what is expected (eg. the printf format string dictates what arguments should follow)</li>
</ul> |
4,179,708 | How to detect if the pressed key will produce a character inside an <input> text-box? | <p>I have a regular text-box: </p>
<pre><code><input type="text">
</code></pre>
<p>I use jQuery to handle key-related events: </p>
<pre><code>$("input:text").keydown(function() {
// keydown code
}).keypress(function() {
// keypress code
}).keyup(function() {
// keyup code
});
</code></pre>
<p>The user focuses on a text-box and presses various keys on his keyboard (the usual ones: letters, numbers, SHIFT, BACKSPACE, SPACE, ...). I need to detect when the user presses a key that is going to increase the length of the text-box value. For example, the "A" key will increase it, the "SHIFT" key wont. </p>
<p>I remember watching a lecture by PPK where he mentioned the difference between those two. It has something to do with the event - keydown vs. keypress - and possibly with the event properties - key, char, keyCode.</p>
<p><strong><em>Update!</em></strong> </p>
<p>I need to know this information within the keydown or keypress handlers. I cannot wait for the keyup event to occur. </p>
<p><strong><em>Why I need this:</em></strong> </p>
<p>I have a text-box which size dynamically changes based on the user input. You can have a look at this demo: <a href="http://vidasp.net/tinydemos/variable-size-text-box.html" rel="noreferrer">http://vidasp.net/tinydemos/variable-size-text-box.html</a> </p>
<p>In the demo, I have a keydown and keyup handler. The keyup handler adjusts the text-box size based on the input value. However, the keydown handler sets the size to be 1 character larger then the input value. The reason I do this is that if I didn't, then the character would overflow outside the text-box and only when the user would let go of the key, the text-box would expand. This looks weird. That's why I have to anticipate the new character - I enlarge the text-box on each keydown, ergo, before the character appears in the text-box. As you can see in the demo, this method looks great. </p>
<p>However, the problem are the BACKSPACE and ARROW keys - they will also expand the text-box on keydown, and only on keyup the text-box size will be corrected. </p>
<p><strong><em>A work-around:</em></strong> </p>
<p>A work-around would be to detect the BACKSPACE, SHIFT, and ARROW keys manually and act based on that: </p>
<pre><code>// keydown handler
function(e) {
var len = $(this).val().length;
if (e.keyCode === 37 || e.keyCode === 39 ||
e.keyCode === 16) { // ARROW LEFT or ARROW RIGHT or SHIFT key
return;
} else if (e.keyCode === 8) { // BACKSPACE key
$(this).attr("size", len <= 1 ? 1 : len - 1);
} else {
$(this).attr("size", len === 0 ? 1 : len + 1);
}
}
</code></pre>
<p>This works (and looks great) for BACKSPACE, SHIFT, ARROW LEFT and ARROW RIGHT. However, I would like to have a more robust solution.</p> | 4,180,715 | 16 | 4 | null | 2010-11-14 21:14:09.063 UTC | 11 | 2022-07-09 09:27:38.607 UTC | 2010-11-14 23:45:23.673 UTC | null | 425,275 | null | 425,275 | null | 1 | 53 | javascript|jquery|keyboard-events | 59,694 | <p>This I think will do the job, or if not is very close and will need only minor tweaking. The thing you have to remember is that you can't reliably tell anything at all about any character that may be typed in a <code>keydown</code> or <code>keyup</code> event: that all has to be done in a <code>keypress</code> handler. The definitive resource for key events is <a href="http://unixpapa.com/js/key.html" rel="noreferrer">http://unixpapa.com/js/key.html</a></p>
<p>You also need to consider pastes, which this code won't handle. You will need to have separate <code>paste</code> event handler (although this event isn't supported in Firefox < 3.0, Opera, and very old WebKit browsers). You'll need a timer in your paste handler since it's impossible in JavaScript to access the content that's about to be pasted.</p>
<pre><code>function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
<input type="text" onkeypress="alert(isCharacterKeyPress(event))">
</code></pre> |
4,374,185 | Regular Expression Match to test for a valid year | <p>Given a value I want to validate it to check if it is a valid year. My criteria is simple where the value should be an integer with <code>4</code> characters. I know this is not the best solution as it will not allow years before <code>1000</code> and will allow years such as <code>5000</code>. This criteria is adequate for my current scenario.</p>
<p>What I came up with is</p>
<p><code>\d{4}$</code></p>
<p>While this works it also allows negative values.</p>
<p>How do I ensure that only positive integers are allowed?</p> | 4,374,196 | 17 | 2 | null | 2010-12-07 07:13:22.27 UTC | 13 | 2022-05-02 20:50:47.183 UTC | 2017-02-25 13:17:18.377 UTC | null | 2,311,366 | null | 286,204 | null | 1 | 105 | regex|string|validation|string-matching | 178,060 | <p>You need to add a start anchor <code>^</code> as:</p>
<pre><code>^\d{4}$
</code></pre>
<p>Your regex <code>\d{4}$</code> will match strings <strong>that end with 4 digits</strong>. So input like <code>-1234</code> will be accepted.</p>
<p>By adding the start anchor you match only those strings that <strong>begin and end</strong> with 4 digits, which effectively means they must contain only 4 digits.</p> |
14,572,100 | How do I style all anchor tags inside a certain div? | <p>I can't figure out how to properly do this. I have the following CSS:</p>
<pre><code>#container > #main > #content > a {
color: #3B7315;
}
</code></pre>
<p>I'm using that to supposedly style all <code><a></code> tags in the <code>#content</code> div. The problem is, however, it doesn't seem to style <code><a></code> tags inside divs or nested lists, etc. It only styles the top-most tags such as the following:</p>
<pre><code><div id="content">
<a href="#">Lorem ipsum</a>
</div>
</code></pre>
<p>When I put the link inside another element, the styling is gone.</p>
<p>So how do I include the whole sub elements and make the style recursively apply itself from <code>#content</code> onwards? I think I'm looking for a wildcard value of sort?</p> | 14,572,116 | 4 | 1 | null | 2013-01-28 22:04:42.977 UTC | null | 2013-01-29 04:35:57.073 UTC | null | null | null | null | 1,023,230 | null | 1 | 16 | html|css | 41,843 | <p>You made it much more complicated than it needs to be:</p>
<pre><code>#content a {}
</code></pre> |
14,742,106 | Refreshing a UICollectionview | <p>Does anyone know how to reload/refresh a UICollectionView while the collection view is being displayed? Basically I'm looking for something similar to the standard reloadData method for a UITableview.</p> | 14,742,308 | 3 | 1 | null | 2013-02-07 01:33:57.903 UTC | 2 | 2018-06-27 11:19:01.293 UTC | 2016-01-28 18:50:34.233 UTC | null | 1,429,262 | null | 1,253,907 | null | 1 | 23 | ios|objective-c|uicollectionview|reloaddata | 41,064 | <p>You can just call:</p>
<pre><code>[self.myCollectionView reloadData];
</code></pre>
<p>Individual sections and items can also be reloaded:</p>
<pre><code>[self.myCollectionView reloadSections:indexSet];
[self.myCollectionView reloadItemsAtIndexPaths:arrayOfIndexPaths];
</code></pre> |
14,800,037 | Putting some indicator around the image in image move/resize/rotate operations | <p>I would like to Scale, Move, Resize Image. I would like to surround the image with Indicators which guide user what operation these indicators perform i.e. Moving, Rotating, Scaling.</p>
<p><img src="https://i.stack.imgur.com/3JwKd.jpg" alt="enter image description here"></p>
<p>I've tried</p>
<ul>
<li>Scaling - but it only crops down. No chance to increase length and height of image.</li>
<li>Rotate - achieved but via inserting manual degrees. That's not a good option in here.</li>
<li>Moving - as I'm achieving drag on Api < 11. So little bit of difficult. Still no hope in here.</li>
</ul>
<p>Is there any library which can do me simple image edit [Move, Scale, Rotate]?</p> | 14,960,140 | 8 | 1 | null | 2013-02-10 16:46:50.163 UTC | 15 | 2018-09-24 19:33:33.98 UTC | 2018-08-30 07:32:12.96 UTC | null | 472,495 | null | 1,543,541 | null | 1 | 28 | android|android-image|image-editing | 18,337 | <p><strong>Using Library : <a href="https://github.com/nimengbo/StickerView" rel="nofollow">StickerView</a></strong></p>
<p>Its a 3rd Party Library which gives exactly what i was looking for.</p>
<p><strong>WorkAround :</strong></p>
<p>Still these answer is half of what I've asked for in OP. Means It ain't surronded by some specific Indicator. I'm still searching how to wrap <code>ImageView</code> with indicators and use them for Translate & Resize.</p>
<p>Initilization of Variables inside <code>Activity</code> important for Translate & Resize <code>ImageView</code></p>
<pre><code>public static final int DRAG = 1;
public static final int NONE = 0;
private static final String TAG = "Touch";
public static final int ZOOM = 2;
public static PointF mid = new PointF();
public static int mode = 0;
float d = 0.0F;
Matrix savedMatrix = new Matrix();
Matrix matrix = new Matrix();
PointF start = new PointF();
</code></pre>
<hr>
<p>Setting <code>ImageView</code> to scaleType - <code>Matrix</code></p>
<pre><code>iv = new ImageView(this);
iv.setPadding(10, 10, 25, 25);
iv.setScaleType(ImageView.ScaleType.MATRIX);
iv.setOnTouchListener(t);
</code></pre>
<hr>
<p>Adding onTouch Listener to <code>ImageView</code> which uses </p>
<ul>
<li>1 Finger for Translate - Drag</li>
<li><p>2 Finger for Zoom - Resize {Pinch To Zoom}</p>
<pre><code>View.OnTouchListener t = new View.OnTouchListener()
{
public boolean onTouch(View paramView, MotionEvent event)
{
ImageView view = (ImageView)paramView;
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG" );
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM" );
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
}
else if (mode == ZOOM) {
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE" );
break;
}
view.setImageMatrix(matrix);
return true;
}
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
};
</code></pre></li>
</ul> |
14,896,533 | Git "NO-HEAD" statement | <p>I am using EGit plugin for Eclipse but whenever I add my project to Git, the plugin puts a "NO-HEAD" indication next to my project folder in Eclipse directory view. Am I doing something wrong ? What does this mean ?</p> | 14,897,092 | 1 | 0 | null | 2013-02-15 14:10:29.69 UTC | 8 | 2014-05-17 21:44:57.18 UTC | 2014-05-17 21:44:57.18 UTC | user456814 | null | null | 586,986 | null | 1 | 31 | git|egit | 47,132 | <p>It can simply mean that, until you make your first add and first commit, you have no branch (not even a <code>master</code> one), hence no <code>HEAD</code> referencing any branch.</p>
<p>See more in "<a href="https://stackoverflow.com/a/17096880/6309">Why do I need to explicitly push a new branch?</a>".</p> |
14,414,430 | Why 0 ** 0 equals 1 in python | <p>Why does <code>0 ** 0</code> equal <code>1</code> in Python? Shouldn't it throw an exception, like <code>0 / 0</code> does?</p> | 14,414,488 | 3 | 9 | null | 2013-01-19 12:37:07.33 UTC | 3 | 2019-08-31 22:41:53.563 UTC | 2013-01-19 12:39:53.91 UTC | null | 1,252,759 | null | 1,814,909 | null | 1 | 32 | python|math | 7,578 | <p>Wikipedia has interesting coverage of the <a href="https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero" rel="nofollow noreferrer">history and the differing points of view on</a> the value of <code>0 ** 0</code>:</p>
<blockquote>
<p>The debate has been going on at least since the early 19th century. At that time, most mathematicians agreed that <code>0 ** 0 = 1</code>, until in 1821 Cauchy listed <code>0 ** 0</code> along with expressions like <code>0⁄0</code> in a table of undefined forms. In the 1830s Libri published an unconvincing argument for <code>0 ** 0 = 1</code>, and Möbius sided with him...</p>
</blockquote>
<p>As applied to computers, <a href="http://en.wikipedia.org/wiki/IEEE_754-2008" rel="nofollow noreferrer">IEEE 754</a> recommends several functions for computing a power. It defines <code>pow(0, 0)</code> and <code>pown(0, 0)</code> as returning <code>1</code>, and <code>powr(0, 0)</code> as returning <code>NaN</code>.</p>
<p>Most programming languages follow the convention that <code>0 ** 0 == 1</code>. Python is no exception, both for integer and floating-point arguments.</p> |
14,802,128 | Tuple pairs, finding minimum using python | <p>I want to find the minimum of a list of tuples sorting by a given column. I have some data arranged as a list of 2-tuples for example.</p>
<pre><code>data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01),
(6, 0.5), (7, 0.2), (8, 0.6)]
</code></pre>
<p>How may I find the min of the dataset by the comparison of the second number in the tuples only?</p>
<p>i.e. </p>
<pre><code>data[0][1] = 7.57
data[1][1] = 2.1
</code></pre>
<p>min( data ) = <code>(5, 0.01)</code></p>
<p><code>min( data )</code> returns <code>(1, 7.57)</code>, which I accept is correct for the minimum of index 0, but I want minimum of index 1.</p> | 14,802,198 | 3 | 0 | null | 2013-02-10 20:13:55.337 UTC | 20 | 2020-09-14 15:26:37.373 UTC | 2017-09-24 02:24:35.287 UTC | null | 445,131 | null | 1,978,467 | null | 1 | 77 | python|tuples|min | 74,179 | <pre><code>In [2]: min(data, key = lambda t: t[1])
Out[2]: (5, 0.01)
</code></pre>
<p>or:</p>
<pre><code>In [3]: import operator
In [4]: min(data, key=operator.itemgetter(1))
Out[4]: (5, 0.01)
</code></pre> |
14,908,372 | How to suppress Update Links warning? | <p>I'm trying to write a script that opens many Excel files. I keep getting the prompt:</p>
<pre><code>This workbook contains links to other data sources.
</code></pre>
<p>I want to keep this message from appearing, so that my script can just automatically go through all the workbooks without me having to click <code>Don't Update</code> for each one. Currently I'm using the following:</p>
<pre><code>function getWorkbook(bkPath as string) as workbook
Application.EnableEvents=False
Application.DisplayAlerts=False
getWorkbook=Workbooks.Open(bkPath,updatelinks:=0,readonly:=false)
end function
</code></pre>
<p>However, the message is still appearing. How can I suppress it?</p>
<p>EDIT: It appears that this message is coming up for workbooks that have broken links; I wasn't seeing the <code>This workbook contains one or more links that cannot be updated</code> message because I'd set <code>DisplayAlerts</code> to false. The workbooks are linked to equivalent files in a folder on our Windows server, so when the matching file is deleted from that folder (which happens as part of our business flow), the link breaks. Is it possible to suppress the warning when the link is broken?</p>
<p>Also, I'm using Excel 2010.</p> | 14,913,783 | 9 | 6 | null | 2013-02-16 08:15:17.813 UTC | 42 | 2022-08-20 20:46:24.943 UTC | 2019-07-11 15:50:05.753 UTC | null | 11,615,632 | null | 619,177 | null | 1 | 124 | excel|vba | 371,208 | <p>I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:</p>
<pre><code>while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
</code></pre>
<p>So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.</p> |
14,602,540 | How to debug a maven goal with intellij idea? | <p>Can you debug a maven goal with Intellij IDEA? I know that I can right-click and run <em>Debug</em>. However, the maven plugin does not appear in my <em>External Libraries</em> list, so I can not go into the code and set a breakpoint. Thus, <em>Debug</em> runs through the goals without stopping, like <em>Run</em> does.</p>
<p>I am using OS X 10.8 and IDEA 12.0.2.</p>
<p><strong>EDIT: Goal</strong></p>
<p>I've written custom specRunner for <a href="https://github.com/searls/jasmine-maven-plugin" rel="noreferrer">https://github.com/searls/jasmine-maven-plugin</a> - However, $specs$ stays empty. So I try to see which files are actually loaded.</p> | 14,853,683 | 9 | 2 | null | 2013-01-30 11:08:23.077 UTC | 32 | 2021-10-01 08:53:25.19 UTC | 2017-11-10 13:24:41.98 UTC | null | 352,319 | null | 974,272 | null | 1 | 126 | intellij-idea | 105,158 | <p>Figured it out:</p>
<ol>
<li>from the command line, run maven goal with <code>mvnDebug</code> instead of <code>mvn</code>. E.g. <code>mvnDebug clean</code></li>
<li>Open the source of the maven plugin you want to debug in intelliJ and set a breakPoint</li>
<li>In IDEA, add a <code>Remote JVM Debug</code> Configuration.
<ol>
<li>Under Settings, set Transport: Socket, Debugger Mode: Attach, Host: localhost, Port: 8000 (default port of mvnDebug).</li>
</ol>
</li>
<li>Run the Configuration in Debug mode. It should connect to the waiting mvnDebug jvm.</li>
</ol> |
2,925,041 | How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map? | <p>I have a <code>Seq</code> containing objects of a class that looks like this:</p>
<pre><code>class A (val key: Int, ...)
</code></pre>
<p>Now I want to convert this <code>Seq</code> to a <code>Map</code>, using the <code>key</code> value of each object as the key, and the object itself as the value. So:</p>
<pre><code>val seq: Seq[A] = ...
val map: Map[Int, A] = ... // How to convert seq to map?
</code></pre>
<p>How can I does this efficiently and in an elegant way in Scala 2.8?</p> | 2,925,357 | 4 | 1 | null | 2010-05-27 21:22:25.48 UTC | 11 | 2021-04-01 13:55:12.557 UTC | 2010-12-15 22:38:37.847 UTC | null | 3,827 | null | 135,589 | null | 1 | 46 | scala|scala-2.8|scala-collections | 51,502 | <p>Map over your <code>Seq</code> and produce a sequence of tuples. Then use those tuples to create a <code>Map</code>. Works in all versions of Scala.</p>
<pre><code>val map = Map(seq map { a => a.key -> a }: _*)
</code></pre> |
2,912,144 | Alternatives to LIMIT and OFFSET for paging in Oracle | <p>I'm developing a web application and need to page ordered results. I normaly use LIMIT/OFFSET for this purpose.</p>
<p>Which is the best way to page ordered results in Oracle? I've seen some samples using rownum and subqueries. Is that the way? Could you give me a sample for translating this SQL to Oracle:</p>
<pre><code>SELECT fieldA,fieldB
FROM table
ORDER BY fieldA
OFFSET 5 LIMIT 14
</code></pre>
<p>(I'm using Oracle 10g, for what it's worth)</p>
<p>Thanks!</p>
<hr>
<p><strong>Answer:</strong>
Using the link provided below by karim79, this SQL would look like:</p>
<pre><code>SELECT * FROM (
SELECT rownum rnum, a.*
FROM(
SELECT fieldA,fieldB
FROM table
ORDER BY fieldA
) a
WHERE rownum <=5+14
)
WHERE rnum >=5
</code></pre> | 2,912,182 | 4 | 1 | null | 2010-05-26 10:41:45.26 UTC | 17 | 2020-03-16 16:08:48.213 UTC | 2020-03-16 16:08:48.213 UTC | null | 1,509,264 | null | 62,426 | null | 1 | 60 | sql|oracle|sql-limit | 107,985 | <p>You will need to use the <code>rownum</code> pseudocolumn to limit results. See here:</p>
<p><strike><a href="http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html" rel="noreferrer">http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html</a></strike></p>
<p><a href="http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html" rel="noreferrer">http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html</a></p> |
38,041,893 | JSON File - Java: editing/updating fields values | <p>I have some JSONObject(s) in my workflow, and the same JSONObjects are stored by writting them into a json file.</p>
<p>I would like an efficient way to update the json file, <strong>only fields where is needed</strong>, with the content of newer JSONObjects instances.</p>
<p>Eg:</p>
<p>On file I have</p>
<pre><code>ObjectOnFile = {key1:val1, key2:val2,...}
</code></pre>
<p>In memory I have </p>
<pre><code>ObjectInMemory = {key1:val1_newer, key2:val2_newer,...}
</code></pre>
<p>The update will be like: </p>
<pre><code> if (!(ObjectInMemory.get(key1).equals(ObjectOnFile.get(key1)))
// update file field value <--- how to?
</code></pre>
<p>In general I would like to update the value of every key where its content is newer (different).</p>
<p>Actually my code is:</p>
<pre><code>import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
Sting key = "key1"; //whatever
JSONObject jo = new JSONObject("{key1:\"val1\", key2:\"val2\"}");
JSONObject root = mapper.readValue(new File(json_file), JSONObject.class);
JSONObject val_newer = jo.getJSONObject(key);
JSONObject val_older = root.getJSObject(key);
if(!val_newer.equals(val_older)){
root.put(key,val_newer);
/*write back root to the json file...how? */
}
</code></pre> | 38,042,302 | 1 | 0 | null | 2016-06-26 18:40:53.987 UTC | 1 | 2019-12-03 10:13:33.557 UTC | 2019-04-04 05:49:05.55 UTC | null | 101,337 | null | 3,299,167 | null | 1 | 6 | java|json|mapping|editing | 54,500 | <p>Simply you can do like this:<br></p>
<pre><code>import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws JSONException, IOException
{
ObjectMapper mapper = new ObjectMapper();
String key = "key1"; //whatever
JSONObject jo = new JSONObject("{key1:\"val1\", key2:\"val2\"}");
//Read from file
JSONObject root = mapper.readValue(new File("json_file"), JSONObject.class);
String val_newer = jo.getString(key);
String val_older = root.getString(key);
//Compare values
if(!val_newer.equals(val_older))
{
//Update value in object
root.put(key,val_newer);
//Write into the file
try (FileWriter file = new FileWriter("json_file"))
{
file.write(root.toString());
System.out.println("Successfully updated json object to file...!!");
}
}
}
}
</code></pre> |
40,351,994 | Update frames button gone in Xcode 8.1 | <p>After updating to 8.1 (8B62) there is no longer a button for updating frames in a storyboard/xib, in the Resolve Auto Layout Issues shortcut in the bottom right corner of the Interface Builder. I heard talk about putting such a button on the new and fancy touch bar, but what does this mean to a mere mortal like myself? Do I have to start using the menu bar?</p>
<p>Now:
<a href="https://i.stack.imgur.com/h67yk.png"><img src="https://i.stack.imgur.com/h67yk.png" alt="enter image description here"></a></p>
<p>Before:</p>
<p><a href="https://i.stack.imgur.com/cQaE9.png"><img src="https://i.stack.imgur.com/cQaE9.png" alt="enter image description here"></a></p> | 40,352,058 | 1 | 0 | null | 2016-10-31 23:21:35.68 UTC | 2 | 2016-11-18 17:11:20.453 UTC | null | null | null | null | 1,373,572 | null | 1 | 29 | xcode|xcode8 | 9,274 | <p>Update frames is a separate option now and not inside the drop down. I am on Xcode Version 8.1 (8B62) and I can see the below button:</p>
<p><a href="https://i.stack.imgur.com/TQy5M.png"><img src="https://i.stack.imgur.com/TQy5M.png" alt="enter image description here"></a></p>
<p>It is enabled only if the control is misplaced</p> |
40,629,312 | Ionic 2: How to call a method when select value is changed | <p>I am new to Ionic 2, I read the Ionic 2 Documentation over and thought this code would work.
Its supposed to give back the current select value when it's changed and print it to console.</p>
<p>page.html</p>
<pre><code><ion-select #C ionChange="onChange(C.value)">
<ion-option value="a">A</ion-option>
<ion-option value="b">B</ion-option>
</ion-select>
</code></pre>
<p>page.ts</p>
<pre><code>public CValue:String;
onChange(CValue) {
console.log(CValue);
}
</code></pre>
<p>However the console isn't giving out anything related to this. Did I miss something in the binding?</p> | 40,629,730 | 5 | 0 | null | 2016-11-16 10:09:47.943 UTC | null | 2021-03-31 22:14:06.057 UTC | 2018-08-23 15:44:54.75 UTC | null | 3,915,438 | null | 6,709,376 | null | 1 | 17 | angular|typescript|ionic-framework|ionic2|ionic3 | 42,478 | <p>Instead of</p>
<pre><code><ion-select #C ionChange="onChange(C.value)">
...
</ion-select>
</code></pre>
<p>Since <code>ionChange</code> is an event (and not a simple attribute) you need to do it like this:</p>
<pre><code><ion-select #C (ionChange)="onChange(C.value)">
...
</ion-select>
</code></pre> |
38,775,661 | What is the difference between geoms and stats in ggplot2? | <p>Both geoms and stats can be used to make plots in the R package ggplot2, and they often give similar results (e.g., geom_area and stat_bin). They also often have slightly different arguments, e.g. in <a href="http://docs.ggplot2.org/current/geom_density_2d.html" rel="noreferrer">2-D density plots</a>:</p>
<pre><code>geom_density_2d(mapping = NULL, data = NULL, stat = "density2d",
position = "identity", ..., lineend = "butt", linejoin = "round",
linemitre = 1, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)
stat_density_2d(mapping = NULL, data = NULL, geom = "density_2d",
position = "identity", ..., contour = TRUE, n = 100, h = NULL, na.rm =
FALSE, show.legend = NA, inherit.aes = TRUE)
</code></pre>
<p>Are there any fundamental differences between the two types of objects?</p> | 38,775,879 | 3 | 0 | null | 2016-08-04 19:18:56.207 UTC | 15 | 2020-04-17 21:46:37.587 UTC | 2018-12-02 23:57:32.377 UTC | null | 3,163,618 | null | 6,585,945 | null | 1 | 18 | r|plot|ggplot2 | 10,924 | <p>geoms stand for "geometric objects." These are the core elements that you see on the plot, object like points, lines, areas, curves.</p>
<p>stats stand for "statistical transformations." These objects summarize the data in different ways such as counting observations, creating a loess line that best fits the data, or adding a confidence interval to the loess line.</p>
<p>As geoms are the "core" of the plot, these are required objects. On the other hand, stats are not required to produce a plot, but can greatly enhance the final plot.</p>
<p>As @eipi10 notes in the comments, these distinctions are somewhat conceptual as the majority of geoms undergo some statistical transformation prior to being plotted. These include <code>geom_bar</code>, <code>geom_smooth</code>, and <code>geom_quantile</code>. Some common exceptions where the data is presented in more or less "raw" form are <code>geom_point</code> and <code>geom_line</code> and the less commonly used <code>geom_rug</code>.</p> |
54,106,333 | How to divide two Int a get a BigDecimal in Kotlin? | <p>I want to divide two Integers and get a BigDecimal back in Kotlin.</p>
<p>E.g. 3/6 = 0.500000.</p>
<p>I've tried some solutions, like:</p>
<pre><code>val num = BigDecimal(3.div(6))
println("%.6f".format(num))
// The result is: 0.000000
</code></pre>
<p>but none of them solve my problem.</p> | 54,106,423 | 3 | 0 | null | 2019-01-09 08:56:37.753 UTC | null | 2022-09-23 14:00:55.713 UTC | 2022-09-23 14:00:55.713 UTC | null | 10,749,567 | null | 7,975,049 | null | 1 | 35 | kotlin|division|integer-division | 25,819 | <p><code>3</code> and <code>6</code> are both <code>Int</code>, and dividing one <code>Int</code> by another gives an <code>Int</code>: that's why you get back 0. To get a non-integer value you need to get the result of the division to be a non-integer value. One way to do this is convert the <code>Int</code> to something else before dividing it, e.g.:</p>
<pre><code>val num = 3.toDouble() / 6
</code></pre>
<p><code>num</code> will now be a <code>Double</code> with a value of <code>0.5</code>, which you can format as a string as you wish.</p> |
42,862,042 | How to import from the __init__.py in the same directory? | <p>Suppose I have a module <code>rules</code> with the following structure:</p>
<pre><code>rules
├── conditions.py
├── __init__.py
</code></pre>
<p>In the script <code>conditions.py</code>, I'd like to import a class called <code>RuleParserError</code> defined in <code>__init__.py</code>. However, I haven't been able to figure out how to do this. (Following <a href="https://stackoverflow.com/questions/22282316/python-how-to-import-from-an-init-py-file">Python: How to import from an __init__.py file?</a> I've tried</p>
<pre><code>from . import RuleParserError
</code></pre>
<p>but this leads to an <code>ImportError: cannot import name RuleParserError</code> when trying to run <code>conditions.py</code> as <code>__main__</code>).</p> | 42,862,399 | 3 | 0 | null | 2017-03-17 15:58:12.247 UTC | 10 | 2021-02-27 20:35:30.76 UTC | 2021-02-27 20:35:30.76 UTC | null | 11,573,842 | null | 995,862 | null | 1 | 26 | python | 23,608 | <p>I see 'import from parent module' as an anti-pattern in Python. Imports should be the other way around. Importing from modules's <code>__init__.py</code> is especially problematic. As you noticed, importing module <code>foo.bar</code> from <code>foo/bar.py</code> involves importing <code>foo/__init__.py</code> first, and you may end up with a circular dependency. Adding a <code>print("Importing", __name__)</code> to your init files helps see the sequence and understand the problem.</p>
<p>I'd suggest that you moved the code you want to import in <code>conditions.py</code> from <code>__init__.py</code> to a separate lower-level module, and just import some names from that module in <code>__init__.py</code> to expose it at higher level.</p>
<p>Let's suppose that you had some <code>class Bar</code> in your <code>__init__.py</code>. I'd reorganize it the following way.</p>
<p><code>__init__.py</code>:</p>
<pre><code>from bar import Bar # exposed at the higher level, as it used to be.
</code></pre>
<p><code>bar.py</code>:</p>
<pre><code>class Bar(object): ...
</code></pre>
<p><code>conditions.py</code>:</p>
<pre><code>from . import Bar # Now it works.
</code></pre>
<p>Ideally an <code>__init__.py</code> should contain nothing but imports from lower-level modules, or nothing at all.</p> |
52,080,991 | How to display percentage above grouped bar chart | <p>The following are the pandas dataframe and the bar chart generated from it:</p>
<pre><code>colors_list = ['#5cb85c','#5bc0de','#d9534f']
result.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None)
plt.legend(labels=result.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.yticks([])
</code></pre>
<p><img src="https://i.stack.imgur.com/ZGgve.jpg" alt="Dataframe">
<img src="https://i.stack.imgur.com/dQYmx.jpg" alt="Bar Chart"></p>
<p>I need to display the percentages of each interest category for the respective subject above their corresponding bar. I can create a list with the percentages, but I don't understand how to add it on top of the corresponding bar.</p> | 52,082,020 | 2 | 0 | null | 2018-08-29 15:18:53.74 UTC | 13 | 2022-08-05 17:31:44.863 UTC | 2022-08-05 17:31:44.863 UTC | null | 7,758,804 | null | 7,194,482 | null | 1 | 18 | python|pandas|matplotlib|bar-chart|plot-annotations | 72,477 | <p>Try adding the following <code>for</code> loop to your code:</p>
<pre><code>ax = result.plot(kind='bar', figsize=(15,4), width=0.8, color=colors_list, edgecolor=None)
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x, y = p.get_xy()
ax.annotate(f'{height}', (x + width/2, y + height*1.02), ha='center')
</code></pre>
<hr />
<h3>Explanation</h3>
<p>In general, you use <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.annotate.html" rel="noreferrer"><code>Axes.annotate</code></a> to add annotations to your plots.<br>
This method takes the <code>text</code> value of the annotation and the <code>xy</code> coords on which to place the annotation.</p>
<p>In a barplot, each "bar" is represented by a <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Rectangle.html" rel="noreferrer"><code>patch.Rectangle</code></a> and each of these rectangles has the attributes <code>width</code>, <code>height</code> and the <code>xy</code> coords of the lower left corner of the rectangle, all of which can be obtained with the methods <code>patch.get_width</code>, <code>patch.get_height</code> and <code>patch.get_xy</code> respectively.</p>
<p>Putting this all together, the solution is to loop through each patch in your <code>Axes</code>, and set the annotation text to be the <code>height</code> of that patch, with an appropriate <code>xy</code> position that's just above the centre of the patch - calculated from it's height, width and xy coords.</p>
<hr />
<p>For your specific need to annotate with the percentages, I would first normalize your <code>DataFrame</code> and plot that instead.</p>
<pre><code>colors_list = ['#5cb85c','#5bc0de','#d9534f']
# Normalize result
result_pct = result.div(result.sum(1), axis=0)
ax = result_pct.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None)
plt.legend(labels=result.columns,fontsize= 14)
plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16)
plt.xticks(fontsize=14)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.yticks([])
# Add this loop to add the annotations
for p in ax.patches:
width = p.get_width()
height = p.get_height()
x, y = p.get_xy()
ax.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')
</code></pre>
<p><a href="https://i.stack.imgur.com/c08fG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c08fG.png" alt="plot" /></a></p> |
52,376,287 | Positioning a Widget in the end of the Row widget | <p>I'm just stuck here. I've tried everything but nothing works for me. All I want is to position the <code>Icon</code> on the right of my <code>Row</code>.</p>
<p>Note: I've tried setting all widget inside the row into a <code>Align</code> Widget and handle the position of that Align widget, but nothing worked. The code below is retrieving this:</p>
<p><a href="https://i.stack.imgur.com/8xJ5f.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8xJ5f.jpg" alt="enter image description here" /></a></p>
<p>This arrow, should go to the end of the <code>Row</code> widget.
Here is my Code:</p>
<pre><code>Row(
mainAxisAlignment: MainAxisAlignment.start, //change here don't //worked
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin:
EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0, right: 12.0),
width: 15.0,
height: 15.0,
decoration: BoxDecoration(
color: task.color, borderRadius: BorderRadius.circular(40.0)),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
task.title,
style: TextStyle(
color: Colors.black,
fontSize: 19.0,
fontWeight: FontWeight.bold),
),
Text(
'Duration: ${task.date}',
style: TextStyle(color: Colors.black, fontSize: 14.0),
)
],
),
Icon(Icons.navigate_next, color: Colors.black) // This Icon
],
),
</code></pre> | 52,377,051 | 4 | 0 | null | 2018-09-17 22:04:44.95 UTC | 3 | 2021-12-21 19:43:55.493 UTC | 2020-08-01 09:55:24.67 UTC | null | 9,185,192 | null | 9,185,192 | null | 1 | 34 | dart|flutter|flutter-layout | 28,977 | <p>One solution is to use the Spacer widget to fill up the space</p>
<p><a href="https://docs.flutter.io/flutter/widgets/Spacer-class.html" rel="noreferrer">https://docs.flutter.io/flutter/widgets/Spacer-class.html</a></p>
<pre><code> Row(
mainAxisAlignment: MainAxisAlignment.start, //change here don't //worked
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin:
EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0, right: 12.0),
width: 15.0,
height: 15.0,
decoration: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(40.0)),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"task.title",
style: TextStyle(
color: Colors.black,
fontSize: 19.0,
fontWeight: FontWeight.bold),
),
Text(
'Duration: ${somenum}',
style: TextStyle(color: Colors.black, fontSize: 14.0),
)
],
),
new Spacer(), // I just added one line
Icon(Icons.navigate_next, color: Colors.black) // This Icon
],
),
</code></pre>
<p><a href="https://i.stack.imgur.com/ynSYL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ynSYL.png" alt="enter image description here" /></a></p>
<p>Here is what happens if you add it to the beginning of the Row.</p>
<p><a href="https://i.stack.imgur.com/3IaTy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3IaTy.png" alt="enter image description here" /></a></p> |
44,596,181 | Firebase cloud function deploy error | <p>irregularly my firebase deployment get stuck at this log: </p>
<pre><code>i functions: updating function [FUNCTION NAME]...
</code></pre>
<p>After canceling the deploy and retrying it throws the following error message: </p>
<pre><code>⚠ functions: failed to update function resetBadgeCount
⚠ functions: HTTP Error: 400, An operation on function [FUNCTION NAME]
in region us-central1 in project [PROJECT NAME] is already in progress.
Please try again later.
</code></pre>
<p>So it seams like that the deploy got stuck and kept in the pipeline blocking further deploys. After a while it let me deploy the functions normally again.
But is there an explanation for this? Or maybe even a word around?</p> | 44,804,932 | 9 | 0 | null | 2017-06-16 18:55:23.22 UTC | 7 | 2022-05-05 07:37:55.36 UTC | null | null | null | null | 6,410,733 | null | 1 | 44 | firebase|google-cloud-functions | 32,586 | <p>Go to <a href="https://console.cloud.google.com/functions/" rel="noreferrer">Google cloud functions console</a> and see if there is red exclamation mark against your function. Then select that particular function and try to delete. once it gets deleted from there, you can deploy again successfully. if it is showing spinner, then wait till it shows red mark. </p> |
26,097,513 | Android simple alert dialog | <p>I need to show a little text message to the users that clicks a button on my Android app, on IOS I just had to create an AlertView that it's simple to use but with Android i'm struggling because the solution seems x10 times harder. I saw that I need to use a DialogFragment but I can't understand how to make it work, can someone explain? Also, is my solution right or there is something easier to show a simple text message to users?</p> | 26,097,588 | 3 | 0 | null | 2014-09-29 10:16:36.47 UTC | 36 | 2021-10-01 07:10:51.4 UTC | null | null | null | null | 3,789,527 | null | 1 | 168 | android|dialog|android-alertdialog | 310,634 | <p>You would simply need to do this in your <code>onClick</code>:</p>
<pre><code>AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
</code></pre>
<p>I don't know from where you saw that you need DialogFragment for simply showing an alert.</p> |
28,182,569 | Get all indexes for a python list | <p>I can get the first index by doing:</p>
<pre><code>l = [1,2,3,1,1]
l.index(1) = 0
</code></pre>
<p>How would I get a list of all the indexes?</p>
<pre><code>l.indexes(1) = [0,3,4]
</code></pre>
<p>?</p> | 28,182,579 | 1 | 0 | null | 2015-01-28 00:23:30.763 UTC | 4 | 2015-01-28 00:24:31.433 UTC | null | null | null | null | 651,174 | null | 1 | 18 | python | 61,485 | <pre><code>>>> l = [1,2,3,1,1]
>>> [index for index, value in enumerate(l) if value == 1]
[0, 3, 4]
</code></pre> |
2,796,587 | How do I make a universal iPhone / iPad application that programmatically uses UISplitViewController and UINavigationController? | <p>I couldn't find a good answer anywhere to this. I am using a UINavigationController for my iPhone app, with everything is generated programmatically, nothing in Interface Builder. I am trying to port my app to iPad, using a UISplitViewController and my existing UINavigationController, but I am not sure where I should have the logic of my program separating the view controllers for iPhone or iPad.</p>
<p>Do I set up my main file to use a different app delegate or do I use the same app delegate and have the user interface conditionally set up within it? </p>
<p>Besides this, whenever I try to compile my app on the simulator it does not recognize the UISplitViewController or even the condition in which I check if the class exists.</p>
<p>Can please someone put me in the right direction, remembering that I am not using any xibs?</p> | 2,797,835 | 1 | 0 | null | 2010-05-09 04:28:27.17 UTC | 12 | 2011-12-21 17:44:01.79 UTC | 2010-05-09 14:03:02.313 UTC | null | 19,679 | null | 326,693 | null | 1 | 12 | iphone|cocoa-touch|ipad|uisplitviewcontroller | 8,391 | <p>If you want to see an example of a completely programmatic iPhone / iPad interface that uses a split view, you can download the source code of my application <a href="http://www.sunsetlakesoftware.com/molecules" rel="nofollow noreferrer">Molecules</a>.</p>
<p>Within that application, I use one application delegate, but I set up the interface differently depending on which user interface idiom is present (iPad or iPhone). For the iPhone, I instantiate a root view controller which manages the appropriate interface for that device. For the iPad, I first create a UISplitViewController and attach it to the root window, then create my iPad-specific root view controller and place it as the detail view of the split view controller (with a navigation controller that I use for item selection as the left-hand controller for the split view).</p>
<p>Again, I recommend looking at that application project to see how I set this up programmatically. The code's available under a BSD license, so you can copy and paste this into your own application if you'd like.</p>
<p>As far as the compilation errors you're getting, you will need to migrate your application target to be a universal application using the "Upgrade Current Target for iPad" menu option. Once that has completed, set your build SDK to 3.2. Go to your application's build settings and set its Deployment Target to the earliest OS you want to support with your application (with 3.0 being the farthest back you can go).</p>
<p><strike>Finally, you will need to weak-link UIKit. For how to do that, see my answer <a href="https://stackoverflow.com/questions/2618889/universal-iphone-ipad-application-debug-compilation-error-for-iphone-testing/2622027#2622027">here</a>.</strike> Weak linking of frameworks is no longer necessary if you are building using the iOS 4.2 or later SDK. Simply check for the presence of the appropriate classes at runtime by seeing if their <code>+class</code> method returns <code>nil</code>.</p> |
2,572,176 | How can I make the batch file wait until another batch file completes execution? | <p>How can I make a batch file wait until another batch file has finished?</p>
<p>For example, I have:</p>
<pre><code>echo hi >r.txt
echo some piece of code >>r.txt
start ar.bat
echo some piece of code >>ar.txt
</code></pre>
<p>I want the code after <code>start ar.bat</code> to execute only after <code>ar.bat</code> finishes executing. I tried without <code>start</code> and it works, but I want to run <code>ar.bat</code> in a separate window.</p>
<p>Is there any method to check whether <code>ar.bat</code> has finished?</p> | 2,572,178 | 1 | 0 | null | 2010-04-03 18:13:36.737 UTC | 1 | 2019-03-18 20:14:18.74 UTC | 2019-03-18 20:14:18.74 UTC | null | 5,250,453 | null | 71,713 | null | 1 | 26 | windows|batch-file|command-line|scripting | 58,332 | <p>Use <code>call ar.bat</code> to do it completely with batch file commands.</p>
<p>Use <code>start /wait ar.bat</code> to get another window and wait for it to complete.</p> |
2,746,899 | What is NetFx in the Windows SDK? | <p>What is NetFx, in the context of the Windows SDK? What differentiates NetFx tools from the tools in the regular SDK <code>bin</code> directory?</p>
<p>I noticed that the version of <code>sgen.exe</code> in <code>C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\</code> was built against .NET 2.0, but the version in <code>C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\</code> was built against .NET 4.0.</p>
<hr>
<p>Update: After a little more searching I found hints that NetFx is the "new" name for WinFx, which was originally a branding intended to convey ".NET with some extra stuff".</p>
<p><a href="http://blogs.msdn.com/ianm/archive/2006/04/19/578851.aspx" rel="noreferrer">http://blogs.msdn.com/ianm/archive/2006/04/19/578851.aspx</a></p>
<p><a href="http://channel9.msdn.com/posts/Duncanma/Jason-Zander-on-the-WinFX-to-NET-FX-30-rename/" rel="noreferrer">http://channel9.msdn.com/posts/Duncanma/Jason-Zander-on-the-WinFX-to-NET-FX-30-rename/</a></p>
<p>Is this right?</p> | 2,746,922 | 1 | 2 | null | 2010-04-30 18:50:03.113 UTC | 3 | 2021-09-07 12:16:29.507 UTC | 2017-07-17 19:24:24.68 UTC | null | 226,625 | null | 111,327 | null | 1 | 46 | .net|winapi | 50,725 | <p>NetFx is apparently just shorthand for "Microsoft .NET Framework."</p> |
21,311,386 | Using grep to help subset a data frame | <p>I am having trouble subsetting my data. I want the data subsetted on column x, where the first 3 characters begin G45.</p>
<p>My data frame:</p>
<pre><code>x <- c("G448", "G459", "G479", "G406")
y <- c(1:4)
My.Data <- data.frame (x,y)
</code></pre>
<p>I have tried:</p>
<pre><code>subset (My.Data, x=="G45*")
</code></pre>
<p>But I am unsure how to use wildcards. I have also tried grep() to find the indicies:</p>
<pre><code>grep ("G45*", My.Data$x)
</code></pre>
<p>but it returns all 4 rows, rather than just those beginning G45, probably also as I am unsure how to use wildcards.</p> | 21,311,458 | 2 | 0 | null | 2014-01-23 14:45:16.663 UTC | 16 | 2021-09-25 14:04:23.36 UTC | 2021-09-25 14:04:23.36 UTC | null | 107,625 | null | 2,535,316 | null | 1 | 34 | r|dataframe|subset | 117,102 | <p>It's pretty straightforward using <code>[</code> to extract:</p>
<p><code>grep</code> will give you the position in which it matched your search pattern (unless you use <code>value = TRUE</code>). </p>
<pre><code>grep("^G45", My.Data$x)
# [1] 2
</code></pre>
<p>Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with <code>[</code> (where you would use <code>My.Data[rows, cols]</code> to get specific rows and columns).</p>
<pre><code>My.Data[grep("^G45", My.Data$x), ]
# x y
# 2 G459 2
</code></pre>
<hr>
<p>The help-page for <code>subset</code> shows how you can use <code>grep</code> and <code>grepl</code> with <code>subset</code> if you prefer using this function over <code>[</code>. Here's an example.</p>
<pre><code>subset(My.Data, grepl("^G45", My.Data$x))
# x y
# 2 G459 2
</code></pre>
<hr>
<p>As of R 3.3, there's now also the <code>startsWith</code> function, which you can again use with <code>subset</code> (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using <code>substring</code> or <code>grepl</code>.</p>
<pre><code>subset(My.Data, startsWith(as.character(x), "G45"))
# x y
# 2 G459 2
</code></pre> |
47,925,751 | How to fill the height of the viewport with tailwind css | <p>I'm just trying out Tailwind CSS and want to know how to fill the height of the viewport.</p>
<p>Taking this example HTML from the docs</p>
<pre><code><div class="flex items-stretch bg-grey-lighter">
<div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">1</div>
<div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">2</div>
<div class="flex-1 text-grey-darker text-center bg-grey-light px-4 py-2 m-2">3</div>
</div>
</code></pre>
<p>How do I make it stretch to the bottom of the screen?</p> | 47,926,137 | 9 | 0 | null | 2017-12-21 13:11:03.833 UTC | 3 | 2022-04-11 11:01:16.297 UTC | 2018-01-24 13:27:19.857 UTC | null | 904,570 | null | 2,405,998 | null | 1 | 40 | css|flexbox|tailwind-css | 86,852 | <p>if you mean that the elements occupy all the height of the viewport, should work with</p>
<pre><code>height: 100vh;
</code></pre> |
47,916,751 | REST API that calls another REST API | <p>Is it proper programming practice/ software design to have a REST API call another REST API? If not what would be the recommended way of handling this scenario?</p> | 47,926,149 | 2 | 0 | null | 2017-12-21 01:41:56.443 UTC | 9 | 2017-12-21 13:36:02.977 UTC | null | null | null | null | 1,293,892 | null | 1 | 20 | rest|api|design-patterns | 24,175 | <p>If I understand your question correctly, then <strong>YES</strong>, it is extremely common.</p>
<p>You are describing the following, I presume:</p>
<blockquote>
<p>Client makes API call to Server-1, which in the process of servicing
this request, makes another request to API Server-2, takes the
response from Server-2, does some reformatting or data extraction, and
packages that up to respond back the the Client?</p>
</blockquote>
<p>This sort of thing happens all the time. The downside to it, is that unless the connection between Server-1 and Server-2 is very low latency (e.g. they are on the same network), and the bandwidth used is small, then the Client will have to wait quite a while for the response. Obviously there can be caching between the two back-end servers to help mitigate this.</p>
<p>It is pretty much the same as Server-1 making a SQL query to a database in order to answer the request.</p>
<p>An alternative interpretation of your question might be that the Client is asking Server-1 to queue an operation that Server-2 would pick up and execute asynchronously. This also is very common (it's how Google crawls your website, for instance). This scenario would have Server-1 respond to Client immediately without needing to wait for the results of the operation undertaken by Server-2. A message queue or database table is usually used as an intermediary between servers in this case.</p> |
47,624,777 | PyCharm: Anaconda installation is not found | <p>I had Anaconda on Windows 10 installed in C:\ProgramData\Anaconda3 before using PyCharm. Now PyCharm displays: "Anaconda installation is not found" when I try using a conda env.</p>
<p>I also added Anaconda to PATH.</p>
<p>Is there a way to show PyCharm where Anaconda is installed?</p> | 47,660,948 | 7 | 0 | null | 2017-12-04 00:16:06.623 UTC | 11 | 2019-09-05 14:43:19.46 UTC | 2017-12-11 23:52:36.423 UTC | null | 5,216,909 | null | 5,216,909 | null | 1 | 34 | windows|path|installation|pycharm|anaconda | 29,066 | <p>There is an open bug, currently PyCharm and IDEA both seem to detect Conda installation only from %HOMEPATH%/anaconda. <a href="https://youtrack.jetbrains.com/issue/PY-26923" rel="noreferrer">https://youtrack.jetbrains.com/issue/PY-26923</a></p>
<p>The easiest workaround is to create a symlink to $HOME/.anaconda</p>
<pre><code>mklink /D %HOMEDRIVE%%HOMEPATH%\anaconda C:\ProgramData\Anaconda3
</code></pre>
<p>Note that C:\ProgramData\Anaconda3 should be replaced with the path to your Anconda installation. If you selected to installed it for "Just Me" instead of "All Users", your default location will be </p>
<pre><code>C:\Users\<your_username>\AppData\Local\Continuum\anaconda3
</code></pre>
<p><strong>UPDATE:</strong> This issue is now fixed in IDEA and PyCharm since version 2018.1. You can specify a custom path under Python Interpreter or SDK settings in Conda Environment section.</p> |
41,769,882 | Pandas Dataframe to Code | <p>If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe.</p>
<p>e.g. </p>
<pre><code>In[1]: df
Out[1]:
income user
0 40000 Bob
1 50000 Jane
2 42000 Alice
In[2]: someFunToWriteDfCode(df)
Out[2]:
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
...: 'income': [40000, 50000, 42000]})
</code></pre> | 46,832,041 | 5 | 0 | null | 2017-01-20 18:09:56.237 UTC | 4 | 2022-07-22 11:16:15.4 UTC | 2017-01-20 18:21:28.81 UTC | null | 4,727,766 | null | 4,727,766 | null | 1 | 32 | python|pandas | 3,960 | <p>You could try to use the to_dict() method on DataFrame:</p>
<pre><code>print "df = pd.DataFrame( %s )" % (str(df.to_dict()))
</code></pre>
<p>If your data contains NaN's, you'll have to replace them with float('nan'):</p>
<pre><code>print "df = pd.DataFrame( %s )" % (str(df.to_dict()).replace(" nan"," float('nan')"))
</code></pre> |
24,581,610 | UI-Router - Change $state without rerender/reload of the page | <p>I've been looking at these pages (<a href="https://stackoverflow.com/questions/23585065/angularjs-ui-router-change-url-without-reloading-state">1</a>, <a href="https://stackoverflow.com/questions/23121695/change-url-of-angular-ui-router-without-reloading-page">2</a>, <a href="https://github.com/angular-ui/ui-router/issues/64" rel="noreferrer">3</a>). I basically want to change my <code>$state</code>, but I don't want the page to reload. </p>
<p>I am currently in the page <code>/schedules/2/4/2014</code>, and I want to go into edit mode when I click a button and have the URL become <code>/schedules/2/4/2014/edit</code>. </p>
<p>My <code>edit</code> state is simply <code>$scope.isEdit = true</code>, so there is no point of reloading the whole page. However, I do want the <code>$state</code> and/or <code>url</code> to change so that if the user refreshses the page, it starts in the edit mode.</p>
<p>What can I do?</p> | 24,597,985 | 3 | 0 | null | 2014-07-04 23:20:39.18 UTC | 18 | 2020-01-14 14:39:18.007 UTC | 2017-05-23 10:31:39.507 UTC | null | -1 | null | 834,045 | null | 1 | 37 | angularjs|angular-ui-router | 31,559 | <p>For this problem, you can just create a child state that has neither <code>templateUrl</code> nor <code>controller</code>, and advance between <code>states</code> normally:</p>
<pre><code>// UPDATED
$stateProvider
.state('schedules', {
url: "/schedules/:day/:month/:year",
templateUrl: 'schedules.html',
abstract: true, // make this abstract
controller: function($scope, $state, $stateParams) {
$scope.schedDate = moment($stateParams.year + '-' +
$stateParams.month + '-' +
$stateParams.day);
$scope.isEdit = false;
$scope.gotoEdit = function() {
$scope.isEdit = true;
$state.go('schedules.edit');
};
$scope.gotoView = function() {
$scope.isEdit = false;
$state.go('schedules.view');
};
},
resolve: {...}
})
.state('schedules.view', { // added view mode
url: "/view"
})
.state('schedules.edit', { // both children share controller above
url: "/edit"
});
</code></pre>
<p>An important <a href="https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#nested-states--views">concept</a> here is that, in <code>ui-router</code>, when the application is in a particular state—when a state is "active"—all of its ancestor states are implicitly active as well.</p>
<p>So, in this case, </p>
<ul>
<li>when your application advances from view mode to edit mode, its parent state <code>schedules</code> (along with its <code>templateUrl</code>, <code>controller</code> and even <code>resolve</code>) will still be retained.</li>
<li>since ancestor states are implicitly activated, even if the child state is being refreshed (or loaded directly from a bookmark), the page will still render correctly.</li>
</ul> |
23,610,476 | Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined | <p>I'm using fabric.js to draw some text on a canvas. I have a function to create a text label. I'd like to have labels run a function when they're selected. The syntax for this is <code>label.on('selected', functionToCall());</code> This works fine when I make the function an anonymous inner function, but when I break it out as a separate function, I get an Uncaught TypeError:</p>
<blockquote>
<p>Cannot read property 'hasOwnProperty' of undefined.</p>
</blockquote>
<p>What am I doing wrong?</p>
<p>Below is the code which doesn't work for me. Here's the <a href="http://jsfiddle.net/R2mMt/" rel="nofollow noreferrer">broken code</a> on jsfiddle, and a version set up with an <a href="http://jsfiddle.net/MUqL5/" rel="nofollow noreferrer">anonymous function</a> which works.</p>
<pre><code>"use strict";
var canvas = new fabric.Canvas('c', {selection: false}),
position = 50;
function onLabelSelection(theLabel) {
if (theLabel.hasOwnProperty('edge')) {
selectedEdge = theLabel.edge;
} else {
selectedEdge = null;
}
}
function createLabel() {
var label;
label = new fabric.Text('Hello World', {
left: position,
top: position
});
position += 50;
label.edge = null;
label.on('selected', onLabelSelection(this));
return label;
}
canvas.on('mouse:up', function() {
var newLabel = createLabel();
canvas.add(newLabel);
});
</code></pre> | 23,610,522 | 1 | 0 | null | 2014-05-12 13:32:16.177 UTC | 1 | 2021-04-27 20:20:30.483 UTC | 2021-04-27 20:20:30.483 UTC | null | 4,370,109 | null | 1,224,068 | null | 1 | 6 | javascript|dom-events|anonymous-function | 43,279 | <blockquote>
<p>The syntax for this is <code>label.on('selected', functionToCall())</code></p>
</blockquote>
<p>No. The syntax for event handlers is to <em>pass</em> the handler function, not to call it:</p>
<pre><code>label.on('selected', functionToCall);
</code></pre>
<p>You might want to try <code>label.on('selected', onLabelSelection.bind(this))</code> or - since <code>this</code> inside <code>createLablel</code> is apparently <code>undefined</code> - just <code>label.on('selected', onLabelSelection)</code>.</p> |
23,872,508 | BootStrap 3 container inside container-fluid | <p>Below is the Layout that I am working on using BootStrap3. I have setup example with limited layout for this question at <a href="http://jsfiddle.net/s7Rwj/4" rel="noreferrer">http://jsfiddle.net/s7Rwj/4</a></p>
<p><img src="https://i.stack.imgur.com/sZyTx.png" alt="WebSite Layout"></p>
<p>I am having hard time setting up my header. I am using container-fluid width so my Header's width is 100% however the ask is that out of three elements inside header one should stay to left and rest of the two should match left and right respectively of the below "container".</p>
<p>So far I have tried various layouts but below is the only one which is close to what I am looking for.</p>
<pre><code> <header class="container-fluid navbar-fixed-top">
<div class="row">
<div class="col-xs-12" style="background-color:aliceblue">
<div class="container">
<div class="row">
<div class="col-xs-6" style="background-color:violet">2</div>
<div class="col-xs-6 pull-right" style="background-color: lightblue">3</div>
</div>
</div>
<span style="position:absolute;top:0;left:0">
A quick brown fox jumps over the lazy dog.
</span>
</div>
</div>
</header>
</code></pre>
<p>However challenge with this layout is that since the span is using absolute position when the browser is re-sized the text overlaps the second element inside header. I have already tried providing explicit width to it but it didn't help.</p>
<p>If I don't use absolute position then the span and rest of the items are rendered in two different lines.</p>
<p>I am looking for advice on how to setup this header. </p>
<p>PS: I have added random background colors to div tag to understand where they are getting rendered. Feel free to ignore them. </p> | 25,742,158 | 3 | 0 | null | 2014-05-26 14:35:31.573 UTC | 15 | 2016-02-03 12:59:30.17 UTC | null | null | null | null | 1,718,305 | null | 1 | 37 | html|css|twitter-bootstrap-3 | 95,794 | <p>I think you're looking for difficulties where they are not.</p>
<p>You should avoid nesting containers (.container and .container-fluid) because they are not nestable due to their padding etc... <a href="http://getbootstrap.com/css/#overview-container">look at Bootstrap 3 Containers overview</a></p>
<p>Also, when you are nesting columns, all you need to do is to put a new row into one of your columns and put the nested columns right into it. <a href="http://getbootstrap.com/css/#grid-nesting">See Bootstrap 3 Grid system - nesting columns</a>, here's their example:</p>
<pre><code><div class="row">
<div class="col-sm-9">
Level 1: .col-sm-9
<div class="row">
<div class="col-xs-8 col-sm-6">
Level 2: .col-xs-8 .col-sm-6
</div>
<div class="col-xs-4 col-sm-6">
Level 2: .col-xs-4 .col-sm-6
</div>
</div>
</div>
</div>
</code></pre>
<p>The solution you're looking for with your layout is very simple. You don't necessarily need container-fluid in the header. Simply create a container for the center part above carousel and wrap it into a .wrap or any other class that you can style with width: 100%. Additionally, you can add some padding that container-fluid has. </p>
<pre><code><header class="wrap navbar-fixed-top">
<div class="container">
<div class="row">
<div class="col-xs-6" style="background-color: violet;">2</div>
<div class="col-xs-6 pull-right" style="background-color: lightblue;">3</div>
</div>
<span style="position:absolute;top:0;left:0">
A quick brown fox jumps over the lazy dog.
</span>
</div>
</header>
</code></pre>
<p>And somewhere in your CSS (I recommend style.less), you can style .wrap to 100% width, though it should be default width for every div without styles. </p>
<pre><code>.wrap {
width: 100%;
}
</code></pre>
<p>I know this question is a lil bit older but it doesn't matter. Hope I understood your question correctly.</p> |
52,505,923 | Error in bind_rows_(x, .id) : Argument 1 must have names | <p>Here is a code snippet:</p>
<pre><code>y <- purrr::map(1:2, ~ c(a=.x))
test1 <- dplyr::bind_rows(y)
test2 <- do.call(dplyr::bind_rows, y)
</code></pre>
<p>The first call to <code>bind_rows</code> (<code>test1</code>) generates the error</p>
<pre><code>Error in bind_rows_(x, .id) : Argument 1 must have names
</code></pre>
<p>Using <code>do.call</code> to invoke <code>bind_rows</code> (<code>test2</code>), on the other hand, works as expected:</p>
<pre><code>test2
# A tibble: 2 x 1
a
<int>
1 1
2 2
</code></pre>
<p>Why? This is using dplyr 0.7.6 and purrr 0.2.5. If I use <code>map_df</code> instead of <code>map</code>, it fails with the same error.</p>
<p>Note: It doesn't appear to me that this question is the same as <a href="https://stackoverflow.com/questions/48512461/error-in-bind-rows-x-id-argument-1-must-have-names-using-map-df-in-purrr">Error in bind_rows_(x, .id) : Argument 1 must have names using map_df in purrr</a>. </p>
<p>EDIT: The other way to address this issue is by explicitly creating a dataframe in the first place:</p>
<pre><code>y <- purrr::map(1:2, ~ data.frame(a=.x))
</code></pre>
<p><code>test1</code> and <code>test2</code> are now created with no errors and are identical. </p>
<p>Alternatively,this creates the <code>test2</code> data frame in one step:</p>
<pre><code>purrr::map_df(1:2, ~ data.frame(a=.x))
</code></pre> | 52,506,031 | 2 | 0 | null | 2018-09-25 20:06:22.147 UTC | 3 | 2021-09-04 21:47:24.08 UTC | 2018-09-26 23:22:37.333 UTC | null | 1,115,698 | null | 1,115,698 | null | 1 | 25 | r|dplyr|tidyverse | 41,926 | <p>From the documentation of <code>bind_rows</code>:</p>
<blockquote>
<p>Note that for historical reasons, lists containg vectors are always
treated as data frames. Thus their vectors are treated as columns
rather than rows, and their inner names are ignored</p>
</blockquote>
<p>Here, your <code>y</code> as constructed has only inner names - it is two unnamed list elements, each containing a length-one vector with the vector element named <code>a</code>. So this error seems to be expected.</p>
<p>If you name the list elements, you can see that it behaves as described, with the vectors treated as columns:</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
y <- map(1:2, ~ c(a=.x)) %>%
set_names(c("a", "b"))
bind_rows(y)
#> # A tibble: 1 x 2
#> a b
#> <int> <int>
#> 1 1 2
</code></pre>
<p>The difference with supplying <code>y</code> as arguments via <code>do.call</code> is that it's more like writing <code>bind_rows(c(a = 1), c(a = 2))</code>. This is not a list containing vectors, but separate vectors, so it binds by row as expected.</p> |
1,301,254 | How to get current method's name in Delphi 7? | <p>Is there any way to know the name of a method I'm currently in?</p>
<p>So that:</p>
<pre><code>procedure TMyObject.SomeMethod();
begin
Writeln('my name is: ' + <hocus pocus>);
end;
</code></pre>
<p>would produce this output:</p>
<p><code>my name is: SomeMethod</code></p> | 1,301,332 | 2 | 0 | null | 2009-08-19 16:57:07.003 UTC | 8 | 2020-07-16 08:59:13.49 UTC | null | null | null | null | 118,322 | null | 1 | 28 | delphi|delphi-7 | 11,200 | <p><a href="http://sourceforge.net/projects/jcl/" rel="noreferrer">JCL</a> is free and has functions for that. It does depend on how well a stack trace can be made and how much debug information is present.</p>
<p>JclDebug.pas</p>
<pre><code>function FileByLevel(const Level: Integer = 0): string;
function ModuleByLevel(const Level: Integer = 0): string;
function ProcByLevel(const Level: Integer = 0): string;
function LineByLevel(const Level: Integer = 0): Integer;
</code></pre> |
862,570 | How can I use the RelayCommand in wpf? | <p>How can I use the <code>RelayCommand</code> in wpf?</p> | 862,592 | 2 | 0 | null | 2009-05-14 10:16:17.843 UTC | 20 | 2013-05-03 21:13:08.693 UTC | 2011-07-29 22:19:10.1 UTC | null | 305,637 | null | 88,096 | null | 1 | 40 | c#|wpf|relaycommand | 64,523 | <p>Relay command doesn't exist in WPF, it is just a external class that raised to prominence after it was defined in <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030" rel="noreferrer">this MSDN article</a>. You need to write it yourself if you want to use it.</p>
<p>Otherwise you can you the Delegate command from the WPF toolkit <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14962" rel="noreferrer">here</a> which has a little bit of extra functionality over the RelayCommand code.</p>
<hr>
<p>Ah, the question changed while I was typing this answer. Assuming that you are using the RelayCommand as defined above you need to supply it with one or two delegates, one that returns a bool which determines whether the command is in a valid state to be run, and a second which returns nothing and actually runs the command. If you don't supply a "CanRun" delegate then the command will consider that it is always in a valid state. The code used in the article:</p>
<pre><code>RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
}
return _saveCommand;
}
}
</code></pre>
<p>Declares a RelayCommand that will call the Save() method when triggered and return the CanSave property as a test for validity. When this command is bound to a button in WPF the IsEnabled property of the Button will match the CanSave property of the ViewModel and when the button is clicked (assuming it is enabled) the Save() method will be called on the ViewModel.</p> |
720,647 | Hiding namespaces containing only internal types in a class library? | <p>I have a class library that has a couple of namespaces containing only internal types.</p>
<p>However, when using the class library in an application project, the namespaces shows up in intellisense, but of course they are empty. Is there any way for me to hide the namespaces completely when using intellisense in other projects?</p>
<p>I've tried to apply <code>EditorBrowsableAttribute</code> to all the internal classes as well, but what I'd like to do would be to apply that to the namespace, which is of course impossible.</p>
<p>Or is, if I care enough about this, the only option I have to just move the types into a namespace that contains public types?</p> | 9,348,101 | 2 | 1 | null | 2009-04-06 08:47:37.037 UTC | 4 | 2012-02-19 09:25:30.7 UTC | null | null | null | null | 267 | null | 1 | 48 | c#|namespaces|intellisense|hide|internal | 18,518 | <p>It depends on how you're referencing your class library:</p>
<ul>
<li>If you have the class library project contained within your solution and use a project reference, you'll always see that empty namespace via Intellisense.</li>
<li>If you're referencing a compiled dll of your class library, you won't see the namespace popping up in intellisense, provided it contains only internal members.</li>
</ul>
<p>Try this:</p>
<pre><code>namespace ClassLibrary1
{
namespace Internal
{
internal class InternalClass
{
public int internalStuff { get; set; }
}
}
namespace Public
{
public class PublicClass
{
public int publicStuff { get; set; }
}
}
}
</code></pre>
<p>If you reference this via a project reference, you'll see the empty namespace. If you reference a dll of it, you won't.</p> |
2,606,190 | Why are my basic Heroku apps taking two seconds to load? | <p>I created two very simple Heroku apps to test out the service, but it's often taking several seconds to load the page when I first visit them:</p>
<ul>
<li><a href="http://cropify.heroku.com/" rel="noreferrer">Cropify</a> - Basic Sinatra App (<a href="http://github.com/viatropos/cropify" rel="noreferrer">on github</a>)</li>
<li><a href="http://meetseesaw.com/" rel="noreferrer">Textile2HTML</a> - Even more basic Sinatra App (<a href="http://github.com/viatropos/seesaw/" rel="noreferrer">on github</a>)</li>
</ul>
<p>All I did was create a simple Sinatra app and deploy it. I haven't done anything to mess with or test the Heroku servers. What can I do to improve response time? It's very slow right now and I'm not sure where to start. The code for the projects are on github if that helps.</p> | 2,606,240 | 5 | 1 | null | 2010-04-09 09:12:01.257 UTC | 40 | 2020-10-16 08:28:48.81 UTC | 2012-05-30 19:07:30.57 UTC | null | 128,421 | null | 169,992 | null | 1 | 118 | ruby|performance|heroku | 69,487 | <ul>
<li>If your application is unused for a while it gets unloaded (from the server memory). </li>
<li>On the first hit it gets loaded and stays loaded until some time passes without anyone accessing it. </li>
</ul>
<p>This is done to save server resources. If no one uses your app why keep resources busy and not let someone who really needs use them ?<br>
If your app has a lot of continous traffic it will never be unloaded.</p>
<p>There is an <a href="https://devcenter.heroku.com/articles/dynos#dyno-sleeping" rel="noreferrer">official note</a> about this.</p> |
2,341,808 | How to get the absolute path for a given relative path programmatically in Linux? | <p>How to get the absolute path for a given relative path programmatically in Linux?</p>
<p>Incase of Windows we have the <code>_fullpath()</code> API. In other words, I mean what is analogous API to <code>_fullpath</code> of Windows in Linux?</p> | 2,341,847 | 7 | 1 | null | 2010-02-26 13:17:15.767 UTC | 10 | 2018-07-25 13:42:23.957 UTC | 2018-07-25 13:42:23.957 UTC | null | 8,012,646 | null | 236,222 | null | 1 | 27 | c|linux|relative-path|absolute-path | 66,431 | <p>As Paul mentioned, use <code><a href="http://man7.org/linux/man-pages/man3/realpath.3.html" rel="noreferrer">realpath()</a></code>. Please note though, that since many file systems in Linux support <a href="http://en.wikipedia.org/wiki/Hard_link" rel="noreferrer">hard links</a>, any given directory can have a number of different absolute paths.</p> |
3,134,573 | Reading/writing CSV/tab delimited files in c# | <p>I need to read from a CSV/Tab delimited file and write to such a file as well from .net.</p>
<p>The difficulty is that I don't know the structure of each file and need to write the cvs/tab file to a datatable, which the FileHelpers library doesn't seem to support.</p>
<p>I've already written it for Excel using OLEDB, but can't really see a way to write a tab file for this, so will go back to a library.</p>
<p>Can anyone help with suggestions?</p> | 3,134,626 | 8 | 0 | null | 2010-06-28 17:17:26.667 UTC | 3 | 2018-11-03 19:47:29.68 UTC | null | null | null | null | 56,861 | null | 1 | 13 | c#|csv | 58,724 | <p>I used this <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="noreferrer">CsvReader</a>, it is really great and well configurable. It behaves well with all kinds of escaping for strings and separators. The escaping in other quick and dirty implementations were poor, but this lib is really great at reading. With a few additional codelines you can also add a cache if you need to.</p>
<p>Writing is not supported but it rather trivial to implement yourself. Or inspire yourself from <a href="http://knab.ws/blog/index.php?/archives/3-CSV-file-parser-and-writer-in-C-Part-1.html" rel="noreferrer">this code</a>.</p> |
3,188,882 | Compile and run dynamic code, without generating EXE? | <p>I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.</p>
<p>Basically, the Main application, will have some stored code (code that will potentially be changed), and it will need to compile the code, and execute it. without creating any files. </p>
<p>creating the files, running the program, and then deleting the files is not an option. the compiled code will need to be ran from memory.</p>
<p>code examples, or pointers, or pretty much anything is welcome :)</p> | 3,188,953 | 8 | 0 | null | 2010-07-06 17:57:02.737 UTC | 19 | 2015-01-12 09:10:53.903 UTC | null | null | null | null | 184,746 | null | 1 | 22 | c#|runtime-compilation | 24,555 | <pre><code>using (Microsoft.CSharp.CSharpCodeProvider foo =
new Microsoft.CSharp.CSharpCodeProvider())
{
var res = foo.CompileAssemblyFromSource(
new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true
},
"public class FooClass { public string Execute() { return \"output!\";}}"
);
var type = res.CompiledAssembly.GetType("FooClass");
var obj = Activator.CreateInstance(type);
var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
}
</code></pre>
<p>This compiles a simple class from the source code string included, then instantiates the class and reflectively invokes a function on it.</p> |
2,579,373 | Saving any file to in the database, just convert it to a byte array? | <p>Is converting a file to a byte array the best way to save ANY file format to disk or database var binary column?</p>
<p>So if someone wants to save a .gif or .doc/.docx or .pdf file, can I just convert it to a bytearray UFT8 and save it to the db as a stream of bytes?</p> | 2,579,467 | 8 | 1 | null | 2010-04-05 15:58:33.227 UTC | 61 | 2021-11-27 06:54:51.147 UTC | null | null | null | null | 39,677 | null | 1 | 76 | c#|file-io|byte | 242,867 | <p>Since it's not mentioned what database you mean I'm assuming SQL Server. Below solution works for both 2005 and 2008.</p>
<p>You have to create table with <code>VARBINARY(MAX)</code> as one of the columns. In my example I've created Table <code>Raporty</code> with column <code>RaportPlik</code> being <code>VARBINARY(MAX)</code> column.</p>
<p><strong>Method to put <code>file</code> into database from <code>drive</code></strong>:</p>
<pre><code>public static void databaseFilePut(string varFilePath) {
byte[] file;
using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read)) {
using (var reader = new BinaryReader(stream)) {
file = reader.ReadBytes((int) stream.Length);
}
}
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
}
</code></pre>
<p><strong>This method is to get <code>file</code> from database and save it on <code>drive</code></strong>:</p>
<pre><code>public static void databaseFileRead(string varID, string varPathToNewLocation) {
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("@varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
using (var fs = new FileStream(varPathToNewLocation, FileMode.Create, FileAccess.Write))
fs.Write(blob, 0, blob.Length);
}
}
}
</code></pre>
<p><strong>This method is to get <code>file</code> from database and put it as <code>MemoryStream</code></strong>:</p>
<pre><code>public static MemoryStream databaseFileRead(string varID) {
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("@varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
return memoryStream;
}
</code></pre>
<p><strong>This method is to put <code>MemoryStream</code> into database:</strong></p>
<pre><code>public static int databaseFilePut(MemoryStream fileToPut) {
int varID = 0;
byte[] file = fileToPut.ToArray();
const string preparedCommand = @"
INSERT INTO [dbo].[Raporty]
([RaportPlik])
VALUES
(@File)
SELECT [RaportID] FROM [dbo].[Raporty]
WHERE [RaportID] = SCOPE_IDENTITY()
";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
using (var sqlWriteQuery = sqlWrite.ExecuteReader())
while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
}
}
return varID;
}
</code></pre> |
2,952,298 | How can I truncate an NSString to a set length? | <p>I searched, but surprisingly couldn't find an answer.</p>
<p>I have a long <code>NSString</code> that I want to shorten. I want the maximum length to be around 20 characters. I read somewhere that the best solution is to use <code>substringWithRange</code>. Is this the best way to truncate a string? </p>
<pre><code>NSRange stringRange = {0,20};
NSString *myString = @"This is a string, it's a very long string, it's a very long string indeed";
NSString *shortString = [myString substringWithRange:stringRange];
</code></pre>
<p>It seems a little delicate (crashes if the string is shorter than the maximum length). I'm also not sure if it's Unicode-safe. Is there a better way to do it? Does anyone have a nice category for this?</p> | 2,953,277 | 11 | 2 | null | 2010-06-01 18:33:42.507 UTC | 21 | 2020-06-22 07:39:49.39 UTC | null | null | null | null | 74,118 | null | 1 | 70 | iphone|objective-c|cocoa|string | 37,351 | <p>Actually the part about being "Unicode safe" was dead on, as many characters combine in unicode which the suggested answers don't consider.</p>
<p>For example, if you want to type é. One way of doing it is by typing "e"(0x65)+combining accent" ́"(0x301). Now, if you type "café" like this and truncate 4 chars, you'll get "cafe". This might cause problems in some places.</p>
<p>If you don't care about this, other answers work fine. Otherwise, do this:</p>
<pre><code>// define the range you're interested in
NSRange stringRange = {0, MIN([myString length], 20)};
// adjust the range to include dependent chars
stringRange = [myString rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
NSString *shortString = [myString substringWithRange:stringRange];
</code></pre>
<p>Note that in this way your range might be longer than your initial range length. In the café example above, your range will expand to a length of 5, even though you still have 4 "glyphs". If you absolutely need to have a length less than what you indicated, you need to check for this.</p> |
3,036,749 | Is it the best practice to extract an interface for every class? | <p>I have seen code where every class has an interface that it implements.</p>
<p>Sometimes there is no common interface for them all.</p>
<p>They are just there and they are used instead of concrete objects.</p>
<p>They do not offer a generic interface for two classes and are specific to the domain of the problem that the class solves.</p>
<p>Is there any reason to do that?</p> | 3,036,925 | 13 | 2 | null | 2010-06-14 11:19:08.733 UTC | 18 | 2016-01-26 19:45:48.443 UTC | 2016-01-23 22:03:57.417 UTC | null | 3,666,197 | null | 85,140 | null | 1 | 65 | c#|interface|software-design | 24,997 | <p><sub>After revisiting this answer, I've decided to amend it slightly.</sub></p>
<p>No, it's not best practice to extract interfaces for <em>every</em> class. This can actually be counterproductive. However, interfaces are useful for a few reasons:</p>
<ul>
<li>Test support (mocks, stubs).</li>
<li>Implementation abstraction (furthering onto IoC/DI).</li>
<li>Ancillary things like co- and contra-variance support in C#.</li>
</ul>
<p>For achieving these goals, interfaces are <em>considered</em> good practice (and are actually required for the last point). Depending on the project size, you will find that you may never need talk to an interface or that you are constantly extracting interfaces for one of the above reasons. </p>
<p>We maintain a large application, some parts of it are great and some are suffering from lack of attention. We frequently find ourselves refactoring to pull an interface out of a type to make it testable or so we can change implementations whilst lessening the impact of that change. We also do this to reduce the "coupling" effect that concrete types can accidentally impose if you are not strict on your public API (interfaces can only represent a public API so for us inherently become quite strict).</p>
<p>That said, it is possible to abstract behaviour without interfaces and possible to test types without needing interfaces, so they are not a <em>requirement</em> to the above. It is just that most frameworks / libraries that you may use to support you in those tasks will operate effectively against interfaces.
<hr/>
<sub>I'll leave my old answer for context.</sub></p>
<p>Interfaces define a public contract. People implementing interfaces have to implement this contract. Consumers only see the public contract. This means the implementation details have been <em>abstracted away</em> from the consumer.</p>
<p>An immediate use for this these days is <strong><em>Unit Testing</em></strong>. Interfaces are easy to mock, stub, fake, you name it.</p>
<p>Another immediate use is <strong><em>Dependency Injection</em></strong>. A registered concrete type for a given interface is provided to a type consuming an interface. The type doesn't care specifically about the implementation, so it can abstractly ask for the interface. This allows you to change implementations without impacting lots of code (the impact area is very small so long as the contract stays the same).</p>
<p>For very small projects I tend not to bother, for medium projects I tend to bother on important core items, and for large projects there tends to be an interface for almost every class. This is almost always to support testing, but in some cases of injected behaviour, or abstraction of behaviour to reduce code duplication.</p> |
2,361,426 | Get the first item from an iterable that matches a condition | <p>I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following function is adequate:</p>
<pre><code>def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i
</code></pre>
<p>This function could be used something like this:</p>
<pre><code>>>> first(range(10))
0
>>> first(range(10), lambda i: i > 3)
4
</code></pre>
<p>However, I can't think of a good built-in / one-liner to let me do this. I don't particularly want to copy this function around if I don't have to. Is there a built-in way to get the first item matching a condition?</p> | 2,364,277 | 16 | 1 | null | 2010-03-02 07:11:29.527 UTC | 67 | 2022-09-22 10:20:19.633 UTC | 2017-11-08 17:50:16.347 UTC | null | 400,617 | null | 203,002 | null | 1 | 474 | python|iterator | 322,083 | <h2>Python 2.6+ and Python 3:</h2>
<p>If you want <code>StopIteration</code> to be raised if no matching element is found:</p>
<pre class="lang-py prettyprint-override"><code>next(x for x in the_iterable if x > 3)
</code></pre>
<p>If you want <code>default_value</code> (e.g. <code>None</code>) to be returned instead:</p>
<pre class="lang-py prettyprint-override"><code>next((x for x in the_iterable if x > 3), default_value)
</code></pre>
<p>Note that you need an extra pair of parentheses around the generator expression in this case − they are needed whenever the generator expression isn't the only argument.</p>
<p>I see most answers resolutely ignore the <a href="https://docs.python.org/2/library/functions.html#next" rel="noreferrer"><code>next</code></a> built-in and so I assume that for some mysterious reason they're 100% focused on versions 2.5 and older -- without mentioning the Python-version issue (but then I don't see that mention in the answers that <em>do</em> mention the <code>next</code> built-in, which is why I thought it necessary to provide an answer myself -- at least the "correct version" issue gets on record this way;-).</p>
<h2>Python <= 2.5</h2>
<p>The <a href="https://docs.python.org/2.5/ref/yieldexpr.html#l2h-407" rel="noreferrer"><code>.next()</code></a> method of iterators immediately raises <code>StopIteration</code> if the iterator immediately finishes -- i.e., for your use case, if no item in the iterable satisfies the condition. If you don't care (i.e., you know there <strong>must</strong> be at least one satisfactory item) then just use <code>.next()</code> (best on a genexp, line for the <code>next</code> built-in in Python 2.6 and better).</p>
<p>If you <em>do</em> care, wrapping things in a function as you had first indicated in your Q seems best, and while the function implementation you proposed is just fine, you could alternatively use <code>itertools</code>, a <code>for...: break</code> loop, or a genexp, or a <code>try/except StopIteration</code> as the function's body, as various answers suggested. There's not much added value in any of these alternatives so I'd go for the starkly-simple version you first proposed.</p> |
3,105,613 | Best Loop Idiom for special casing the last element | <p>I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (for example every normal element will be comma separated except for the last case).</p>
<p>Is there some best practice idiom or elegant form that doesn't require duplicating code or shoving in an if, else in the loop.</p>
<p>For example I have a list of strings that I want to print in a comma separated list. (the do while solution already assumes the list has 2 or more elements otherwise it'd be just as bad as the more correct for loop with conditional).</p>
<p>e.g. List = ("dog", "cat", "bat")</p>
<p>I want to print "[dog, cat, bat]"</p>
<p>I present 2 methods the</p>
<ol>
<li><p>For loop with conditional</p>
<pre><code>public static String forLoopConditional(String[] items) {
String itemOutput = "[";
for (int i = 0; i < items.length; i++) {
// Check if we're not at the last element
if (i < (items.length - 1)) {
itemOutput += items[i] + ", ";
} else {
// last element
itemOutput += items[i];
}
}
itemOutput += "]";
return itemOutput;
}
</code></pre></li>
<li><p>do while loop priming the loop</p>
<pre><code>public static String doWhileLoopPrime(String[] items) {
String itemOutput = "[";
int i = 0;
itemOutput += items[i++];
if (i < (items.length)) {
do {
itemOutput += ", " + items[i++];
} while (i < items.length);
}
itemOutput += "]";
return itemOutput;
}
</code></pre>
<p>Tester class:</p>
<pre><code>public static void main(String[] args) {
String[] items = { "dog", "cat", "bat" };
System.out.println(forLoopConditional(items));
System.out.println(doWhileLoopPrime(items));
}
</code></pre></li>
</ol>
<p>In the Java AbstractCollection class it has the following implementation (a little verbose because it contains all edge case error checking, but not bad).</p>
<pre><code>public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
</code></pre> | 3,121,784 | 18 | 4 | null | 2010-06-23 21:16:06.23 UTC | 17 | 2018-04-25 05:17:56.747 UTC | 2018-04-25 05:17:56.747 UTC | null | 7,076,153 | null | 98,050 | null | 1 | 52 | java|loops|while-loop|idioms | 18,126 | <p>There are a lot of for loops in these answers, but I find that an Iterator and while loop reads much more easily. E.g.:</p>
<pre><code>Iterator<String> itemIterator = Arrays.asList(items).iterator();
if (itemIterator.hasNext()) {
// special-case first item. in this case, no comma
while (itemIterator.hasNext()) {
// process the rest
}
}
</code></pre>
<p>This is the approach taken by <a href="http://code.google.com/p/google-collections/source/browse/trunk/src/com/google/common/base/Joiner.java#262" rel="noreferrer">Joiner</a> in Google collections and I find it very readable.</p> |
3,018,289 | xcopy file, rename, suppress "Does xxx specify a file name..." message | <p>This seems pretty simple and maybe I'm just overlooking the <a href="http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true" rel="noreferrer">proper flag</a>, but how would I, in one command, copy a file from one directory to another and rename it in the destination directory? Here's my command:</p>
<pre><code>if exist "bin\development\whee.config.example"
if not exist "TestConnectionExternal\bin\Debug\whee.config"
xcopy "bin\development\whee.config.example"
"TestConnectionExternal\bin\Debug\whee.config"
</code></pre>
<p>It prompts me with the following every time:</p>
<blockquote>
<p>Does TestConnectionExternal\bin\Debug\whee.config specify a file name
or directory name on the target (F = file, D = directory)?</p>
</blockquote>
<p>I want to suppress this prompt; the answer is always <code>F</code>.</p> | 3,018,369 | 23 | 3 | null | 2010-06-10 20:36:16.703 UTC | 62 | 2021-08-18 22:39:59.52 UTC | null | null | null | null | 38,743 | null | 1 | 448 | command-line|command-prompt|xcopy | 406,600 | <p>Don't use the <code>xcopy</code>, use <code>copy</code> instead, it doesn't have this issue.</p>
<p><code>xcopy</code> is generally used when performing recursive copies of multiple files/folders, or when you need the verification/prompting features it offers. For single file copies, the <code>copy</code> command works just fine.</p> |
50,815,189 | How to initialize an empty ArrayList in Kotlin? | <p>I have an empty arraylist:</p>
<pre><code>var mylist: ArrayList<Int> = ArrayList()
</code></pre>
<p>When I want to set value in it I got this error:</p>
<pre><code>java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
</code></pre>
<p>The question is: How can I initialize my list?</p> | 50,815,266 | 2 | 1 | null | 2018-06-12 10:40:21.923 UTC | 3 | 2022-07-01 05:48:42.087 UTC | 2022-07-01 05:48:42.087 UTC | null | 5,336,567 | null | 5,336,567 | null | 1 | 55 | arraylist|kotlin|indexoutofboundsexception | 73,827 | <p>According to the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/array-list-of.html" rel="noreferrer">api-doc</a>:</p>
<pre><code>val list = arrayListOf<Int>()
</code></pre>
<p>This is also mentioned here: <a href="https://stackoverflow.com/questions/36896801/how-to-initialize-listt-in-kotlin#36897638">How to initialize List in Kotlin?
</a>.</p> |
6,098,655 | When to use events over commands in WPF? | <p>Hi i have recently looked into WPF and started learning about Events and Commands. I typically use Commands on Button clicks which causes a method to Run in my "view model". </p>
<p>Is it possible to make the Button react to any other events like the MouseOver event through the use of commnds? Or would WPF Events be used in this case?</p>
<p>If WPF Events are to be used, then should the event handler implementation just call a method in the View Model to keep concerns sperate?</p> | 6,098,941 | 2 | 1 | null | 2011-05-23 14:32:40.79 UTC | 3 | 2011-05-23 15:07:37.79 UTC | 2011-05-23 14:57:18.98 UTC | null | 72,871 | null | 762,715 | null | 1 | 30 | wpf|mvvm|mvvm-light|routed-commands|eventtocommand | 6,557 | <p>This is a fair question, and one that is a common, yet "solved" (debatably) problem within the MVVM architecture realm. If you are using an MVVM framework, you are likely to find something similar to the EventToCommand Behavior, <a href="http://blog.galasoft.ch/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx" rel="noreferrer">here</a> is the sample from the MVVM Light Toolkit. </p>
<p>In short, this allows you to map an event to a command binding like so:</p>
<pre><code><Rectangle Fill="White"
Stroke="Black"
Width="200"
Height="100">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<cmd:EventToCommand Command="{Binding TestCommand,
Mode=OneWay}"
CommandParameter="{Binding Text,
ElementName=MyTextBox,
Mode=OneWay}"
MustToggleIsEnabledValue="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle>
</code></pre>
<p><strong>Update:</strong></p>
<p>There are two other "reasonable" solutions to this problem:</p>
<p>One uses the now considered legacy "AttachedCommandBehavior" extension found <a href="http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/" rel="noreferrer">here.</a></p>
<p>The other is a little bit irritating, but workable.</p>
<ol>
<li>Capture a command via en
event purely in the view. </li>
<li>Query the control's DataSource Step</li>
<li>Grab a string binding target
identifier that denotes your command
(perhaps using a const string on the
view)</li>
<li>Invoke your command on
the view model via reflection and
pass in the command arguments.</li>
</ol>
<p>This looks gross but I'm fairly certain is actually a bit faster than just using traditional command
bindings. In order to be sure I'd need to see the IL, and I don't think that it matters in this case.</p>
<p><strong>/Update</strong></p>
<p>I want to note however that this is not always an ideal situation. I've discovered that more often than not, I'm using EventToCommand to cover a design issue. Please consider the following:</p>
<ul>
<li>Use events and code behind to handle User-Interface related behaviors.</li>
<li>Consider creating custom controls that have command bindings if appropriate, especially if you find yourself using commands to encapsulate event driven bevahior to set bound data that is then reflected in the view. (i.e. setting a transparency value based on proximity to a control or something similar)</li>
<li>EventToCommand should most likely be used to handle "Command-like" events only (double clicking etc) not reactive events (mouse-over). However there is nothing preventing this. Implement as you see fit.</li>
</ul>
<p>Most importantly perhaps is that you remember that you are the developer. Guidelines in themselves do not solve problems, but consideration of guidelines may make the solution to a problem apparent.</p> |
58,400,001 | Should I call super.initState at the end or at the beginning? | <p>I am confused as to where to call the <code>super.initSate()</code> in Flutter? In some code examples, it's called at the beginning and in others at the end. Is there a difference?</p>
<p>I have tried to google this but haven't found any explanation on the position of this function call.</p>
<p>Which one is correct?</p>
<pre class="lang-dart prettyprint-override"><code>void initState() {
super.initState();
//DO OTHER STUFF
}
</code></pre>
<p>or</p>
<pre class="lang-dart prettyprint-override"><code>void initState() {
//DO OTHER STUFF
super.initState();
}
</code></pre> | 58,400,324 | 4 | 0 | null | 2019-10-15 17:40:20.62 UTC | 15 | 2021-07-16 23:35:03.203 UTC | 2021-07-16 23:35:03.203 UTC | null | 12,349,734 | null | 9,554,350 | null | 1 | 75 | flutter|dart | 15,825 | <h2>It does matter for <code>mixin</code>s (and because of that <em>for you</em> as well)</h2>
<p>It is a <strong>paradigm</strong> in the Flutter framework to call the super method when overriding lifecycle methods in a <code>State</code>. This is why even <a href="https://github.com/flutter/flutter/blob/6b93efdd857d2acb54b61dfbf63c24540d3ccb63/packages/flutter/lib/src/widgets/framework.dart#L872" rel="noreferrer"><code>deactivate</code></a> has a <a href="https://api.flutter.dev/flutter/meta/mustCallSuper-constant.html" rel="noreferrer"><code>mustCallSuper</code> annotation</a>.<br />
<em>Additionally</em>, some <code>mixin</code>s expect that you call the super methods of those lifecycle methods at a particular point in the function.</p>
<p>This means that you should follow the documentation and call <code>super.dispose</code> <strong>at the end</strong> of your <code>dispose</code> method because <code>mixin</code>s on <code>State</code> in the framework expect that this is the case.<br />
For example: <a href="https://api.flutter.dev/flutter/widgets/TickerProviderStateMixin-mixin.html" rel="noreferrer"><code>TickerProviderStateMixin</code></a> and <a href="https://api.flutter.dev/flutter/widgets/SingleTickerProviderStateMixin-mixin.html" rel="noreferrer"><code>SingleTickerProviderStateMixin</code></a> <a href="https://github.com/flutter/flutter/blob/fb33b7a1b86aacae45145e40f7946a4de62e3e9a/packages/flutter/lib/src/widgets/ticker_provider.dart#L183" rel="noreferrer">assert</a> <code>super.dispose</code> at the end:</p>
<blockquote>
<p>All Tickers must [..] be disposed before calling super.dispose().</p>
</blockquote>
<p>Another example: <a href="https://github.com/flutter/flutter/blob/fb33b7a1b86aacae45145e40f7946a4de62e3e9a/packages/flutter/lib/src/widgets/automatic_keep_alive.dart#L344" rel="noreferrer"><code>AutomaticKeepAliveMixin</code></a> executes logic in <code>initState</code> and <code>dispose</code>.</p>
<h2>Conclusion</h2>
<p><a href="https://api.flutter.dev/flutter/widgets/State/initState.html" rel="noreferrer">Start your <code>initState</code> with <code>super.initState</code></a> and <a href="https://api.flutter.dev/flutter/widgets/State/dispose.html" rel="noreferrer">end your <code>dispose</code> with <code>super.dispose</code></a> if you want to be on the easy and safe side adding <code>mixin</code>s to your <code>State</code>.<br />
Furthermore, follow the documentation for other lifecycle methods (any method you overwrite in <code>State</code>) because the framework will expect that you call the super methods as described in the documentation.</p>
<p>Thus, the following is what you should do:</p>
<pre class="lang-dart prettyprint-override"><code>@override
void initState() {
super.initState();
// DO YOUR STUFF
}
@override
void dispose() {
// DO YOUR STUFF
super.dispose();
}
</code></pre>
<p>However, it does not <em>really</em> matter for <code>State</code>, which I will explain in the following and even for mixins, it only matters for assertions judging from what I could find - so it would not affect your production app.</p>
<h2>It does not matter for <code>State</code></h2>
<p>I think that the previous two answers from <a href="https://stackoverflow.com/users/11938462/">Pablo Barrera</a> and <a href="https://stackoverflow.com/users/6618622">CopsOnRoad</a> are <em>misleading</em> because the truth of the matter is that it really does not matter and you do not need to look far.</p>
<p>The only actions that <a href="https://api.flutter.dev/flutter/widgets/State/initState.html" rel="noreferrer"><code>super.initState</code></a> and <a href="https://api.flutter.dev/flutter/widgets/State/dispose.html" rel="noreferrer"><code>super.dispose</code></a> take in the <code>State</code> class itself are <strong>assertions</strong> and since <code>assert</code>-statements are only evaluated in <em>debug mode</em>, it does not matter at all once build your app, i.e. in production mode.</p>
<hr />
<p>In the following, I will guide you through what <code>super.initState</code> and <code>super.dispose</code> do in <code>State</code>, which is all the code that will be executed when you have no additional mixins.</p>
<h3><code>initState</code></h3>
<p>Let us look exactly what code is executed in <code>super.initState</code> first (<a href="https://github.com/flutter/flutter/blob/fb33b7a1b86aacae45145e40f7946a4de62e3e9a/packages/flutter/lib/src/widgets/framework.dart#L1017" rel="noreferrer">source</a>):</p>
<pre class="lang-dart prettyprint-override"><code>@protected
@mustCallSuper
void initState() {
assert(_debugLifecycleState == _StateLifecycle.created);
}
</code></pre>
<p>As you can see, there is only a lifecycle assertion and the purpose of it is to ensure that your widget works correctly. So as long as you call <code>super.initState</code> <strong>somewhere</strong> in your own <code>initState</code>, you will see an <code>AssertionError</code> if your widget is not working as intended. It does not matter if you took some prior action because the <code>assert</code> is only meant to report that something in your code is wrong anyway and you will see that even if you call <code>super.initState</code> at the very end of your method.</p>
<h3><code>dispose</code></h3>
<p>The <code>dispose</code> method is analogous (<a href="https://github.com/flutter/flutter/blob/fb33b7a1b86aacae45145e40f7946a4de62e3e9a/packages/flutter/lib/src/widgets/framework.dart#L1209" rel="noreferrer">source</a>):</p>
<pre class="lang-dart prettyprint-override"><code>@protected
@mustCallSuper
void dispose() {
assert(_debugLifecycleState == _StateLifecycle.ready);
assert(() {
_debugLifecycleState = _StateLifecycle.defunct;
return true;
}());
}
</code></pre>
<p>As you can see, it also only contains assertions that handle <strong>debug</strong> lifecycle checking. The second <code>assert</code> here is a nice trick because it ensures that the <code>_debugLifecycleState</code> is only changed in debug mode (as <code>assert</code>-statements are only executed in debug mode).<br />
This means that as long as you call <code>super.dispose</code> <em>somewhere</em> in your own method, you will not lose any value without mixins adding additional functionality.</p> |
35,758,924 | How do we query on a secondary index of dynamodb using boto3? | <p>Is there a way at all to query on the <code>global secondary index</code> of dynamodb using <code>boto3</code>. I dont find any online tutorials or resources. </p> | 36,869,361 | 4 | 0 | null | 2016-03-02 21:56:38.467 UTC | 11 | 2020-02-01 05:33:29.82 UTC | null | null | null | null | 4,186,589 | null | 1 | 56 | amazon-web-services|amazon-dynamodb|boto3 | 55,010 | <p>You need to provide an <code>IndexName</code> parameter for the <code>query</code> function. </p>
<p>This is the <strong><em>name</em> of the index</strong>, which is usually different from the <strong>name of the index <em>attribute</em></strong> (the name of the index has an <code>-index</code> suffix by default, although you can change it during table creation). For example, if your index attribute is called <code>video_id</code>, your index name is probably <code>video_id-index</code>.</p>
<pre class="lang-py prettyprint-override"><code>import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('videos')
video_id = 25
response = table.query(
IndexName='video_id-index',
KeyConditionExpression=Key('video_id').eq(video_id)
)
</code></pre>
<p>To check the <strong>index name</strong>, go to the <code>Indexes</code> tab of the table on the web interface of AWS. You'll need a value from the <code>Name</code> column.</p> |
19,270,392 | What is `priority` of ng-repeat directive can you change it? | <p>Angular Documentation says: -</p>
<blockquote>
<p>The compilation of the DOM is performed by the call to the $compile()
method. The method traverses the DOM and matches the directives. If a
match is found it is added to the list of directives associated with
the given DOM element. Once all directives for a given DOM element
have been identified they are <strong><em>sorted by priority</em></strong> and their
compile() functions are executed.</p>
</blockquote>
<p>The ng-repeat directive I believe has a lower priority than custom directives, in certain use cases like <a href="https://stackoverflow.com/questions/19254705/index-of-ng-repeat-computed-after-linker-function-of-angular-directive-co">dynamic id and custom directive</a>. Does angular permit tinkering with priority of directives to choose execution of one before the other?</p> | 19,271,293 | 2 | 0 | null | 2013-10-09 11:08:58.397 UTC | 9 | 2015-07-29 19:34:34.82 UTC | 2017-05-23 12:19:19.78 UTC | null | -1 | null | 2,596,724 | null | 1 | 38 | angularjs|angularjs-directive|angularjs-ng-repeat|ng-repeat | 27,264 | <p>Yes, you can set the priority of a directive. <code>ng-repeat</code> has a priority of <a href="https://github.com/angular/angular.js/blob/v1.2.0-rc.2/src/ng/directive/ngRepeat.js#L215" rel="noreferrer">1000</a>, which is actually higher than custom directives (default priority is 0). You can use this number as a guide for how to set your own priority on your directives in relation to it. </p>
<pre><code>angular.module('x').directive('customPriority', function() {
return {
priority: 1001,
restrict: 'E',
compile: function () {
return function () {...}
}
}
})
</code></pre>
<blockquote>
<p><strong>priority</strong> - When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. The order of directives with the same priority is undefined. The default priority is 0.</p>
</blockquote> |
8,423,576 | Is it possible to test the order of elements via RSpec/Capybara? | <p>I'm using RSpec/Capybara as my test suite. I have some javascript that dynamically appends <code><li></code> to the end of a <code><ul></code>. I want to write a request spec to ensure that this is happening. </p>
<p>I tried using the <code>has_css</code> Capybara method and advanced CSS selectors to test for the ordering of the <code><li></code> elements, but Capybara doesn't support the <code>+</code> CSS selector.</p>
<p>Example:</p>
<pre><code>page.should have_css('li:contains("ITEM #1")')
pseuo_add_new_li
page.should have_css('li:contains("ITEM #1")+li:contains("ITEM #2")')
</code></pre>
<p>Does anyone know of another way to test for ordering?</p> | 8,454,355 | 12 | 0 | null | 2011-12-07 22:32:50.66 UTC | 10 | 2022-04-24 16:30:11.167 UTC | null | null | null | null | 171,662 | null | 1 | 47 | ruby-on-rails-3|rspec|ruby-on-rails-3.1|capybara | 17,989 | <p>I resolved this issue by testing for a regex match against the body content of the page. A bit kludgy, but it works.</p>
<pre><code>page.body.should =~ /ITEM1.*ITEM2.*ITEM3/
</code></pre> |
47,824,598 | Why does my training loss have regular spikes? | <p>I'm training the Keras object detection model linked at the bottom of this question, although I believe my problem has to do neither with Keras nor with the specific model I'm trying to train (SSD), but rather with the way the data is passed to the model during training.</p>
<p>Here is my problem (see image below):
My training loss is decreasing overall, but it shows sharp regular spikes: </p>
<p><a href="https://i.stack.imgur.com/7zmbx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7zmbx.png" alt="Training loss"></a></p>
<p>The unit on the x-axis is not training epochs, but tens of training steps. The spikes occur precisely once every 1390 training steps, which is exactly the number of training steps for one full pass over my training dataset.</p>
<p>The fact that the spikes always occur after each full pass over the training dataset makes me suspect that the problem is not with the model itself, but with the data it is being fed during the training.</p>
<p>I'm using the <a href="https://github.com/pierluigiferrari/ssd_keras/blob/master/ssd_batch_generator.py" rel="noreferrer">batch generator provided in the repository</a> to generate batches during training. I checked the source code of the generator and it does shuffle the training dataset before each pass using <code>sklearn.utils.shuffle</code>.</p>
<p>I'm confused for two reasons:</p>
<ol>
<li>The training dataset is being shuffled before each pass.</li>
<li>As you can see in <a href="https://github.com/pierluigiferrari/ssd_keras/blob/master/train_ssd7.ipynb" rel="noreferrer">this Jupyter notebook</a>, I'm using the generator's ad-hoc data augmentation features, so the dataset should theoretically never be same for any pass: All the augmentations are random.</li>
</ol>
<p>I made some test predictions to see if the model is actually learning anything, and it is! The predictions get better over time, but of course the model is learning very slowly since those spikes seem to mess up the gradient every 1390 steps.</p>
<p>Any hints as to what this might be are greatly appreciated! I'm using the exact same Jupyter notebook that is linked above for my training, the only variable I changed is the batch size from 32 to 16. Other than that, the linked notebook contains the exact training process I'm following.</p>
<p>Here is a link to the repository that contains the model:</p>
<p><a href="https://github.com/pierluigiferrari/ssd_keras" rel="noreferrer">https://github.com/pierluigiferrari/ssd_keras</a></p> | 47,839,270 | 3 | 2 | null | 2017-12-15 01:33:29.3 UTC | 10 | 2021-11-12 13:27:20.8 UTC | 2019-11-18 13:07:54.823 UTC | null | 7,517,192 | null | 7,517,192 | null | 1 | 22 | deep-learning|keras | 13,014 | <p>I've figured it out myself:</p>
<p><strong>TL;DR:</strong></p>
<p>Make sure your loss magnitude is independent of your mini-batch size.</p>
<p><strong>The long explanation:</strong></p>
<p>In my case the issue was Keras-specific after all.</p>
<p>Maybe the solution to this problem will be useful for someone at some point.</p>
<p>It turns out that Keras divides the loss by the mini-batch size. The important thing to understand here is that it's not the loss function itself that averages over the batch size, but rather the averaging happens somewhere else in the training process.</p>
<p>Why does this matter?</p>
<p>The model I am training, SSD, uses a rather complicated multi-task loss function that does its own averaging (not by the batch size, but by the number of ground truth bounding boxes in the batch). Now if the loss function already divides the loss by some number that is correlated with the batch size, and afterwards Keras divides by the batch size <strong>a second time</strong>, then all of a sudden the magnitude of the loss value starts to depend on the batch size (to be precise, it becomes inversely proportional to the batch size).</p>
<p>Now usually the number of samples in your dataset is not an integer multiple of the batch size you choose, so the very last mini-batch of an epoch (here I implicitly define an epoch as one full pass over the dataset) will end up containing fewer samples than the batch size. This is what messes up the magnitude of the loss if it depends on the batch size, and in turn messes up the magnitude of gradient. Since I'm using an optimizer with momentum, that messed up gradient continues influencing the gradients of a few subsequent training steps, too.</p>
<p>Once I adjusted the loss function by multiplying the loss by the batch size (thus reverting Keras' subsequent division by the batch size), everything was fine: No more spikes in the loss.</p> |
26,970,825 | Printing an external PDF document in VB.net | <p>I know this question has been asked before, but my situation is a bit wonky.</p>
<p>Basically, I'm trying to print a PDF file that I've generated using a previous Windows Form. I can find the file no problem, and I used the following code which I found off MSDN's help forums:</p>
<pre><code>Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "C:\534679.pdf" 'This is the file name
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
</code></pre>
<p>So far so good, but everytime I press the button to run this code, it keeps asking me to save it as a PDF file instead, as shown below:</p>
<p><img src="https://i.stack.imgur.com/rIG4O.png" alt="enter image description here"></p>
<p>I've also tried adding a PrintDialog to the Windows Form, getting it to pop up, and I can select the printer I want to use from there, but even after selecting the printer it still asks me to print to PDF Document instead.</p>
<p>What am I doing wrong?</p> | 26,972,265 | 4 | 1 | null | 2014-11-17 10:42:37.527 UTC | 1 | 2017-09-18 08:41:28.66 UTC | null | null | null | null | 1,254,149 | null | 1 | 2 | vb.net|printing | 52,036 | <p>First, to be able to select a Printer, you'll have to use a <strong>PrintDialog</strong> and <strong>PrintDocument</strong> to send graphics to print to the selected printer.</p>
<pre><code>Imports System.Drawing.Printing
Private WithEvents p_Document As PrintDocument = Nothing
Private Sub SelectPrinterThenPrint()
Dim PrintersDialog As New PrintDialog()
If PrintersDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
Try
p_Document = New PrintDocument()
PrintersDialog.Document = p_Document
AddHandler p_Document.PrintPage, AddressOf HandleOnPrintPage
Catch CurrentException As Exception
End Try
End If
End Sub
Private Sub HandleOnPrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles p_Document.PrintPage
Dim MorePagesPending As Boolean = False
'e.Graphics.Draw...(....)
'e.Graphics.DrawString(....)
' Draw everything...
If MorePagesPending Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
</code></pre>
<p>That's what I'm doing since I usually have custom objects to print.</p>
<hr>
<p>But to print PDF Files, you must understand that PDF means <strong>absolutely nothing</strong> to dotNet. Unlike common images like Bitmaps (.bmp) or Ping images (.png) the dotNet doesn't seem to have any inbuilt parser/decoder for reading, displaying and printing PDF files.</p>
<p>So you must use a third party <strong>application</strong>, thrid party <strong>library</strong> or your own <strong>custom PDF parser/layout generator</strong> in order to be able to send pages to print to your printer.</p>
<p>That's why you can't launch a hidden (not visible) process of Acrobat Reader with the command "print". You won't be able to select a printer but will direct to the default one instead !</p>
<p>You can however launch the Acrobat Reader process just to open the file, and do the printing manipulations (select a printer) <strong>inside Acrobat Reader</strong> (you're outside dotNet coding now)</p>
<hr>
<p>A workaround for your may aslo to select another default printer by opening Acrobat Reader, and print one blank page on an <code>actual working printer</code>. This should deselect your FoxIt thing in favour of an actual printer..</p> |
61,430,311 | Exposing multiple TCP/UDP services using a single LoadBalancer on K8s | <p>Trying to figure out how to expose multiple TCP/UDP services using a single LoadBalancer on Kubernetes. Let's say the services are ftpsrv1.com and ftpsrv2.com each serving at port 21. </p>
<p>Here are the options that I can think of and their limitations :</p>
<ul>
<li>One LB per svc: too expensive.</li>
<li>Nodeport : Want to use a port outside the 30000-32767 range.</li>
<li>K8s Ingress : does not support TCP or UDP services as of now.</li>
<li>Using Nginx Ingress controller : which again <a href="https://kubernetes.github.io/ingress-nginx/user-guide/exposing-tcp-udp-services/" rel="noreferrer">will be one on one mapping</a>: </li>
<li>Found <a href="https://github.com/DevFactory/smartnat" rel="noreferrer">this custom implementation</a> : But it doesn't seem to updated, last update was almost an year ago.</li>
</ul>
<p>Any inputs will be greatly appreciated.</p> | 61,461,960 | 4 | 0 | null | 2020-04-25 18:10:01.667 UTC | 12 | 2022-04-29 15:15:48.34 UTC | null | null | null | null | 8,925,518 | null | 1 | 21 | kubernetes|kubernetes-ingress | 16,854 | <p>It's actually <a href="https://kubernetes.github.io/ingress-nginx/user-guide/exposing-tcp-udp-services/" rel="noreferrer">possible</a> to do it using NGINX Ingress.</p>
<p>Ingress does not support TCP or UDP services. For this reason this Ingress controller uses the flags <code>--tcp-services-configmap</code> and <code>--udp-services-configmap</code> to point to an existing config map where the key is the external port to use and the value indicates the service to expose using the format: <code><namespace/service name>:<service port>:[PROXY]:[PROXY]</code>.</p>
<p><a href="https://minikube.sigs.k8s.io/docs/tutorials/nginx_tcp_udp_ingress/" rel="noreferrer">This guide</a> is describing how it can be achieved using minikube but doing this on a on-premises kubernetes is different and requires a few more steps.</p>
<p>There is lack of documentation describing how it can be done on a non-minikube system and that's why I decided to go through all the steps here. This guide assumes you have a fresh cluster with no NGINX Ingress installed.</p>
<p>I'm using a GKE cluster and all commands are running from my Linux Workstation. It can be done on a Bare Metal K8S Cluster also.</p>
<p><strong>Create sample application and service</strong></p>
<p>Here we are going to create and application and it's service to expose it later using our ingress.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
name: redis-deployment
namespace: default
labels:
app: redis
spec:
replicas: 1
selector:
matchLabels:
app: redis
template:
metadata:
labels:
app: redis
spec:
containers:
- image: redis
imagePullPolicy: Always
name: redis
ports:
- containerPort: 6379
protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
name: redis-service
namespace: default
spec:
selector:
app: redis
type: ClusterIP
ports:
- name: tcp-port
port: 6379
targetPort: 6379
protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
name: redis-service2
namespace: default
spec:
selector:
app: redis
type: ClusterIP
ports:
- name: tcp-port
port: 6380
targetPort: 6379
protocol: TCP
</code></pre>
<p>Notice that we are creating 2 different services for the same application. This is only to work as a proof of concept. I wan't to show latter that many ports can be mapped using only one Ingress.</p>
<p><strong>Installing NGINX Ingress using Helm:</strong></p>
<p>Install helm 3:</p>
<pre><code>$ curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash
</code></pre>
<p>Add NGINX Ingress repo:</p>
<pre><code>$ helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
</code></pre>
<p>Install NGINX Ingress on kube-system namespace:</p>
<pre><code>$ helm install -n kube-system ingress-nginx ingress-nginx/ingress-nginx
</code></pre>
<p><strong>Preparing our new NGINX Ingress Controller Deployment</strong></p>
<p>We have to add the following lines under spec.template.spec.containers.args:</p>
<pre><code> - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
- --udp-services-configmap=$(POD_NAMESPACE)/udp-services
</code></pre>
<p>So we have to edit using the following command:</p>
<pre><code>$ kubectl edit deployments -n kube-system ingress-nginx-controller
</code></pre>
<p>And make it look like this:</p>
<pre><code>...
spec:
containers:
- args:
- /nginx-ingress-controller
- --publish-service=kube-system/ingress-nginx-controller
- --election-id=ingress-controller-leader
- --ingress-class=nginx
- --configmap=kube-system/ingress-nginx-controller
- --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
- --udp-services-configmap=$(POD_NAMESPACE)/udp-services
- --validating-webhook=:8443
- --validating-webhook-certificate=/usr/local/certificates/cert
- --validating-webhook-key=/usr/local/certificates/key
...
</code></pre>
<p><strong>Create tcp/udp services Config Maps</strong></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ConfigMap
metadata:
name: tcp-services
namespace: kube-system
</code></pre>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ConfigMap
metadata:
name: udp-services
namespace: kube-system
</code></pre>
<p>Since these configmaps are centralized and may contain configurations, it is best if we only patch them rather than completely overwrite them every time you add a service:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl patch configmap tcp-services -n kube-system --patch '{"data":{"6379":"default/redis-service:6379"}}'
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ kubectl patch configmap tcp-services -n kube-system --patch '{"data":{"6380":"default/redis-service2:6380"}}'
</code></pre>
<p>Where:</p>
<ul>
<li><code>6379</code> : the port your service should listen to from outside the minikube virtual machine</li>
<li><code>default</code> : the namespace that your service is installed in</li>
<li><code>redis-service</code> : the name of the service</li>
</ul>
<p>We can verify that our resource was patched with the following command:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl get configmap tcp-services -n kube-system -o yaml
apiVersion: v1
data:
"6379": default/redis-service:6379
"6380": default/redis-service2:6380
kind: ConfigMap
metadata:
annotations:
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"v1","kind":"ConfigMap","metadata":{"annotations":{},"name":"tcp-services","namespace":"kube-system"}}
creationTimestamp: "2020-04-27T14:40:41Z"
name: tcp-services
namespace: kube-system
resourceVersion: "7437"
selfLink: /api/v1/namespaces/kube-system/configmaps/tcp-services
uid: 11b01605-8895-11ea-b40b-42010a9a0050
</code></pre>
<p>The only value you need to validate is that there is a value under the <code>data</code> property that looks like this:</p>
<pre class="lang-yaml prettyprint-override"><code> "6379": default/redis-service:6379
"6380": default/redis-service2:6380
</code></pre>
<p><strong>Add ports to NGINX Ingress Controller Deployment</strong></p>
<p>We need to patch our nginx ingress controller so that it is listening on ports 6379/6380 and can route traffic to your service.</p>
<pre><code>spec:
template:
spec:
containers:
- name: controller
ports:
- containerPort: 6379
hostPort: 6379
- containerPort: 6380
hostPort: 6380
</code></pre>
<p>Create a file called <code>nginx-ingress-controller-patch.yaml</code> and paste the contents above.</p>
<p>Next apply the changes with the following command:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl patch deployment ingress-nginx-controller -n kube-system --patch "$(cat nginx-ingress-controller-patch.yaml)"
</code></pre>
<p><strong>Add ports to NGINX Ingress Controller Service</strong></p>
<p>Differently from the solution presented for minikube, we have to patch our NGINX Ingress Controller Service as it is the responsible for exposing these ports.</p>
<pre><code>spec:
ports:
- nodePort: 31100
port: 6379
name: redis
- nodePort: 31101
port: 6380
name: redis2
</code></pre>
<p>Create a file called <code>nginx-ingress-svc-controller-patch.yaml</code> and paste the contents above.</p>
<p>Next apply the changes with the following command:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl patch service ingress-nginx-controller -n kube-system --patch "$(cat nginx-ingress-svc-controller-patch.yaml)"
</code></pre>
<p><strong>Check our service</strong></p>
<pre><code>$ kubectl get service -n kube-system ingress-nginx-controller
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
ingress-nginx-controller LoadBalancer 10.15.251.203 34.89.108.48 6379:31100/TCP,6380:31101/TCP,80:30752/TCP,443:30268/TCP 38m
</code></pre>
<p>Notice that our <code>ingress-nginx-controller</code> is listening to ports 6379/6380.</p>
<p>Test that you can reach your service with telnet via the following command:</p>
<pre><code>$ telnet 34.89.108.48 6379
</code></pre>
<p>You should see the following output:</p>
<pre><code>Trying 34.89.108.48...
Connected to 34.89.108.48.
Escape character is '^]'.
</code></pre>
<p>To exit telnet enter the <code>Ctrl</code> key and <code>]</code> at the same time. Then type <code>quit</code> and press enter.</p>
<p>We can also test port 6380:</p>
<pre><code>$ telnet 34.89.108.48 6380
Trying 34.89.108.48...
Connected to 34.89.108.48.
Escape character is '^]'.
</code></pre>
<p>If you were not able to connect please review your steps above.</p>
<p><strong>Related articles</strong></p>
<ul>
<li><a href="https://kubernetes.io/docs/Handbook/access-application-cluster/ingress-minikube/" rel="noreferrer">Routing traffic multiple services on ports 80 and 443 in minikube with the Kubernetes Ingress resource</a></li>
<li><a href="https://kubernetes.io/docs/Handbook/access-application-cluster/port-forward-access-application-cluster/" rel="noreferrer">Use port forwarding to access applications in a cluster</a></li>
</ul> |
30,488,223 | How to create a JavaFX Maven project in IntelliJ IDEA? | <p>How can I open a JavaFX Maven project from scratch in IntelliJ IDEA? As there is no difference between a Java project and a JavaFx project, I want to open a dedicated JavaFX project (Selection JavaFX from create project Wizard) with Maven module included. </p> | 38,639,576 | 6 | 0 | null | 2015-05-27 16:30:06.103 UTC | 7 | 2021-10-08 05:13:24.833 UTC | 2015-05-27 16:39:18.48 UTC | null | 3,880,800 | null | 3,880,800 | null | 1 | 24 | java|maven|intellij-idea|javafx | 44,217 | <p>Although dated I'm answering this because I had the same question recently and too many people told me to write my own pom file etc. While that is technically true, it can create more headaches if you aren't careful. </p>
<p>I recommend you:</p>
<ol>
<li>Create a JavaFX project as you normally would. </li>
<li>Make sure that project view (dropdown in project structure side tool window) is set to '<em>Project</em>' or '<em>Packages</em>' (otherwise option in 4th step will not be visible)</li>
<li>Then once it is opened and ready right click on the project folder</li>
<li>Go to "Add Framework Support...". </li>
<li>Check the box for Maven and click "OK". </li>
</ol>
<p>Let IntelliJ do the work for you at this point.</p>
<p>As for editing FXML files link the IDEA to SceneBuilder. <a href="https://www.jetbrains.com/help/idea/2016.2/preparing-for-javafx-application-development.html#d432543e165" rel="noreferrer">Here</a> is the official documentation. But basically:</p>
<ol>
<li>Install <a href="http://gluonhq.com/products/" rel="noreferrer">Scene Builder</a>.</li>
<li>File -> Settings -> Languages & Frameworks -> JavaFX</li>
<li>Point to the exe file.</li>
</ol>
<p>To Use: Right click on the FXML file and select "Open In SceneBuilder" (way down at the bottom)</p> |
30,615,400 | Android RecyclerView.Adapter onCreateViewHolder() working | <p>I am using RecyclerView.Adapter but I am little confused regarding working of its method <code>onCreateViewHolder</code>. </p>
<pre><code> @Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if(viewType==TYPE_ITEM) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.inflate_common_item, viewGroup, false);
ViewHolder vh = new ViewHolder(mView);
return vh;
} else {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.inflate_uncommon_item, viewGroup, false);
ViewHolderFooter vh = new ViewHolderFooter(mView);
return vh;
}
}
</code></pre>
<p>So incase I have 10 items in my list so for each item this method will be called and every time a new <code>ViewHolder</code> will be created of course it'll one time for each view but now my question is when we were using <code>ListView</code> and <code>BaseAdapter</code> with them we store <code>ViewHolder</code> in tag and use that. We don't create <code>ViewHolder</code> for each item. </p>
<pre><code> @Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.tvDesc, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.ivIcon, myList.get(position).getImgResId());
return convertView;
}
</code></pre>
<p>So are we not creating extra viewholders object. Please help me understand the pros and cons.</p>
<p>Thanks</p> | 30,615,637 | 2 | 0 | null | 2015-06-03 09:00:48.373 UTC | 3 | 2017-11-29 08:38:16.827 UTC | 2015-06-03 09:07:02.16 UTC | null | 717,778 | null | 2,885,340 | null | 1 | 15 | android|android-recyclerview | 41,663 | <p><code>onCreateViewHolder</code> only creates a new view holder when there are no existing view holders which the <code>RecyclerView</code> can reuse. So, for instance, if your <code>RecyclerView</code> can display 5 items at a time, it will create 5-6 <code>ViewHolders</code>, and then automatically reuse them, each time calling <code>onBindViewHolder</code>. </p>
<p>Its similar to what your code in the <code>ListView</code> does (checking if <code>convertView</code> is <code>null</code>, and if not, grabbing the existing <code>ViewHolder</code> from the tag), except, with <code>RecyclerView</code>, this is all done automatically.</p>
<p>I suppose this is one of the pros with using a <code>RecyclerView</code> - you don't need to worry so much about reusing <code>ViewHolders</code> as you do with <code>ListView</code>. The con is, <code>RecyclerView</code> is very customisable, but has very little built in functionality - unlike <code>ListView</code> which is not very customisable, but has a lot of built in functionality. </p> |
680,334 | Server Tag is not well formed | <p>This is so damn stupid but driving me absolutely fing crazy.</p>
<pre><code><input type="radio" name="OptGroup" id="<%#"rbEmail" + ((Action)Container.DataItem).ID %>" value="<%#((Action)Container.DataItem).ID %>" runat="server" /><label for="<%#"rbEmail" + ((Action)Container.DataItem).ID %>"><%#((Action)Container.DataItem).Action %></label>
</code></pre>
<p>What am I doing wrong here! I've also tried:</p>
<pre><code><input type="radio" name="OptGroup" id='<%#"rbEmail" + ((Action)Container.DataItem).ID %>' value='<%#((Action)Container.DataItem).ID %>' runat="server" /><label for='<%#"rbEmail" + ((Action)Container.DataItem).ID %>'><%#((Action)Container.DataItem).Action %></label>
</code></pre>
<p>and</p>
<pre><code><input type="radio" name="OptGroup" id="<%#'rbEmail' + ((Action)Container.DataItem).ID %>" value="<%#((Action)Container.DataItem).ID %>" runat="server" /><label for="<%#'rbEmail' + ((Action)Container.DataItem).ID %>"><%#((Action)Container.DataItem).Action %></label>
</code></pre>
<p>I specifically do not want to use an asp.net radiobutton due to the problems with GroupName it creates while inside a repeater. I want to use a bare radio button and bind its values to my datasource.</p> | 680,359 | 3 | 0 | null | 2009-03-25 05:33:14.907 UTC | null | 2017-11-16 09:00:56.33 UTC | 2017-11-16 09:00:56.33 UTC | null | 6,807,812 | null | 72,603 | null | 1 | 3 | asp.net | 38,020 | <p>Do you need to access the control server-side? If not, take off the runat="server", you cannot databind to the ID property for a server control. Not sure if thats the problem, since that should give you a different error</p>
<p>EDIT:</p>
<p>Something like this should suit your purposes..</p>
<pre><code><asp:Repeater runat="server">
<ItemTemplate>
<label><input type="radio" name="rbEmail" value='<%# ((Action)Container.DataItem).ID %>' /><%# ((Action)Container.DataItem).Action %></label>
</ItemTemplate>
</asp:Repeater>
</code></pre>
<p>Then in the postback, you can get the value from Request.Form["rbEmail"]</p>
<p>EDIT2:</p>
<p>Fully tested simple page example..</p>
<p>Default.aspx</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<label><input type="radio" name="rbEmail" value='<%# Container.DataItem %>' /><%# Container.DataItem %></label>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="submit" />
</form>
</body>
</html>
</code></pre>
<p>Default.aspx.cs</p>
<pre><code>using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = new string[] { "Hello", "World" };
Repeater1.DataBind();
}
protected void submit_Click(object sender, EventArgs e)
{
Response.Write(Request.Form["rbEmail"]);
}
}
</code></pre> |
1,282,251 | Saving data to session in JSF | <p>I am new to the world of J(2)EE and web app development but am quickly navigating my way around it and learning a lot. Every day is a fantastic voyage of new discovery for me.</p>
<p>I am currently working on a project in which I am using Visual JSF Woodstock on Glassfish v2. I am pretty new to JSF also. </p>
<p>There are times when I need to save some objects (say MyObject for instance) between requests. And from what I have read and understood so far, I need to be using sessions to save these objects between different requests. So far so good.</p>
<p>Exactly how to do this is where my concern lies. I know that in JSP you can use the <code>session.setAttribute("myObj", myObject)</code> which would save the object at client side using cookies or url rewrites or hidden form variables. </p>
<p>On the other hand, in JSF I use Session scoped beans, say SessionBean1 for e.g., and save objects as SessionBean1 properties (e.g. <code>SessionBean1.setSomeOjb(myObj)</code>). Is this the right way to go about with this? </p>
<p>I am guessing that doing it this way will result in increased memory utilization at the server end since each request will create a new instance of the session scoped bean, SessionBean1 plus the memory utilized by the saved myObject instances in SessionBean1.</p>
<p>I have read that you can use <code>FacesContext.getExternalContext().getSession/getSessionMap()</code> which would save session variables at client side.</p>
<p>So which method would you suggest that I use - the session scoped bean or the sessionmap to save objects for access between requests for a session?</p>
<p>Thanks.</p> | 1,282,301 | 3 | 1 | null | 2009-08-15 16:27:19.853 UTC | 15 | 2015-08-12 05:49:53.23 UTC | 2013-05-07 09:04:30.487 UTC | null | 1,703,313 | null | 97,233 | null | 1 | 23 | jsf|session-state|session-variables | 83,673 | <p>In general Java EE Web Apps tend not to expect to save session data client side. You're right to be concerned about session bloat on the server side, a common problem seen is to have huge session footprints which can cause significant resource and performance issues, and can be especially in clustered environments.</p>
<p>I'd like to know where you see</p>
<blockquote>
<p>I have read that you can use FacesContext.getExternalContext().getSession/getSessionMap() which would save session variables at client side.</p>
</blockquote>
<p>I believe (correct me on this point) that this simply gives access to the HttpSession object, on which you can then use the same</p>
<pre><code> session.setAttribute("myObj", myObject)
</code></pre>
<p>this does not in itself send the object back to the client, it's held in the server and keyed by some session identifier, usually passed in a cookie. </p>
<p>Now there are two other techniques: you could explicitly choose to put data into a cookie of your own manufacture - the servlet APIs that you can access from JSF or JSP would let you do that, or you can use hidden fields on your forms, and hence pass aorund session data.</p>
<p>But consider this. A rule of thumb on the App Server I use is that HttpSession of the order of 1k-4k tend not to be a problem. Larger than that (and I have seen sessions of measured in megabytes) do stress the infrastructure. If you were concerned about sessions of that size would you expect to send megabytes of data in a cookie or hidden field back to the browser on every request? Even 1k-2k is probably a bit big.</p>
<p>So recommendations:</p>
<ol>
<li><p>Keep it simple. Use the Session API, or its JSF manifestation.</p></li>
<li><p>Keep the amount of data in the session under control. </p></li>
</ol>
<p>Added in response to question about clustering:</p>
<p>Typically, in a clustered environment we have session affinity, so that requests are sent back to the same cluster member. However we still need to consider the case (perhaps if a cluster members fails) when the request goes to a different server. </p>
<p>Some App Server vendors offer session replication, either via direct inter-server communication or by persisting the session to a database - obviously there are overheads here, so sometimes, for low value sessions we just accept the loss of session in event of failure. </p>
<p>There is an argument that if the session data has high value then it should be persisted by the application, it's actually business data and should be treated as such. Increasingly, NOSQL databases such as Cloudant or MongoDb are used for this. In this case we may think of the HTTP session as a cache, in the knowledge that the session data can be retrieved in the event of error.</p>
<p>So I'd argue that a Shopping Cart may well have considerable value to the business; it represent the customers thoughtful accumulation of things they want to spend money on. So it should be persisted, rather then just kept in the session. Once we decide to persist it, then we find that it leads to other interesting scenarios such as a consolidated experience across many client devices. The customer starts shopping at home on a desktop PC, but completes the purchase online.</p>
<p>So a further principle:</p>
<p>3). Don't over-use the HTTP session just because it's there. Consider the business value of the data and whether it should be persisted.</p> |
633,384 | Storing Credit Card Information | <p>Can I store my users' credit card's expiration date & last 4 digits? The reasons for this is so we can notify the user that their card is about to expire and that they should change their account over to their new card. Storing the last four digits will allow the user to identify what card they have stored with our system.</p> | 633,391 | 3 | 0 | null | 2009-03-11 04:54:11.83 UTC | 9 | 2009-11-03 04:00:18.687 UTC | 2009-11-03 04:00:18.687 UTC | null | 21,398 | Radar | 15,245 | null | 1 | 27 | security|credit-card | 5,336 | <p>There's a whole set of rules about what you can and cannot store, Google for <a href="http://www.google.com/search?q=pci-compliance" rel="noreferrer">PCI-Compliance</a>. However, in short, yes, the expiration date and last-4 would be ok to store. The <em>huge</em> no-no is storing the CID number (number on the back of the card), but there are many other rules too. </p>
<p>Edit: This is based on the US rules.</p> |
1,268,834 | What is the symbol for a queue? | <p>In a flowchart or process diagram, what is the symbol for a FIFO queue?</p> | 1,268,870 | 3 | 1 | null | 2009-08-12 21:31:38.493 UTC | 8 | 2018-05-21 20:55:26.917 UTC | null | null | null | null | 116 | null | 1 | 60 | queue|diagram | 90,948 | <p>I don't have a source to cite, unfortunately, but I recall seeing it represented as an <a href="http://en.wikipedia.org/wiki/Isosceles_trapezoid" rel="noreferrer">isosceles trapezoid</a>.</p>
<p>Actually I found an example of it <a href="http://cf.inspiration.com/download/pdf/V7SymbolGuide.pdf" rel="noreferrer">here</a> (though maybe not the most authoritative of sources).</p>
<p><strong>Edit:</strong> From comments it looks like the example site I had linked is no longer available. This is a recreation of what was in the original document:</p>
<p><img src="https://i.stack.imgur.com/Upxsw.png" alt="trapezoid"></p> |
687,942 | Java Map equivalent in C# | <p>I'm trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows:</p>
<pre><code>class Test {
Map<Integer,String> entities;
public String getEntity(Integer code) {
return this.entities.get(code);
}
}
</code></pre>
<p>Is there an equivalent way of doing this in C#?
<code>System.Collections.Generic.Hashset</code> doesn't uses hash and I cannot define a custom type key
<code>System.Collections.Hashtable</code> isn't a generic class<br>
<code>System.Collections.Generic.Dictionary</code> doesn't have a <code>get(Key)</code> method</p> | 687,949 | 3 | 0 | null | 2009-03-26 23:30:14.923 UTC | 16 | 2019-03-08 19:18:27.223 UTC | 2013-01-08 06:33:49.583 UTC | null | 871,910 | anonymous-pek | null | null | 1 | 158 | c#|java|generics|collections | 175,656 | <p>You can index Dictionary, you didn't need 'get'.</p>
<pre><code>Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
</code></pre>
<p>An efficient way to test/get values is <code>TryGetValue</code> (thanx to Earwicker):</p>
<pre><code>if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}
</code></pre>
<p>With this method you can fast and exception-less get values (if present).</p>
<p>Resources:</p>
<p><a href="http://dotnetperls.com/Content/Dictionary-Keys.aspx" rel="noreferrer">Dictionary-Keys</a></p>
<p><a href="http://dotnetperls.com/Content/TryGetValue.aspx" rel="noreferrer">Try Get Value</a></p> |
28,822,034 | Simple node.js server that sends html+css as response | <p>I've created basic http server that sends html file as response. How can I send css file as well so client using browser will see a html using css ?</p>
<p>The code I have:</p>
<pre><code>var http = require('http');
var fs = require('fs');
var htmlFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end(htmlFile);
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
</code></pre>
<p>What I have tried(it seems it does not work - client sees only css file content here):</p>
<pre><code>var http = require('http');
var fs = require('fs');
var htmlFile;
var cssFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
fs.readFile('./AppClientStyle.css', function(err, data) {
if (err){
throw err;
}
cssFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
response.end();
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
response.end();
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
</code></pre>
<p>html file:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="AppClientStyle.css">
</head>
<body>
<div class=middleScreen>
<p id="p1">Random text</p>
</div>
</body>
</html>
</code></pre>
<p>css file :</p>
<pre><code>@CHARSET "UTF-8";
.middleScreen{
text-align:center;
margin-top:10%;
}
</code></pre>
<p>I don't want to use express here(it is just for learning purpose)</p> | 28,838,314 | 2 | 1 | null | 2015-03-03 00:36:34.43 UTC | 18 | 2019-11-25 06:39:46.577 UTC | 2015-03-03 01:14:02.223 UTC | null | 4,625,642 | null | 4,625,642 | null | 1 | 20 | javascript|html|css|node.js | 39,655 | <p>What you have written in your first snippet is a web server that responds with the body of your HTML file regardless of what URI the browser requests.</p>
<p>That's all nice and well, but then with the second snippet, you're trying to send a second document to a closed response handle. To understand why this doesn't work, you have to understand how HTTP works. HTTP is (for the most part) a request->response type protocol. That is, the browser asks for something and the server sends that thing, or an error message of some sort, back to the browser. (I'll skip over keep-alive and methods that allow the server to push content to the browser--those are all far beyond the simple learning purpose you seem to have in mind here.) Suffice it to say that it is inappropriate to send a second response to the browser when it hasn't asked for it. </p>
<p>So how do you get the browser to ask for a second document? Well, that's easy enough... in your HTML file you probably have a <code><link rel="stylesheet" href="AppClientStyle.css"></code> tag. This will cause the browser to make a request to your server asking it for AppClientStyle.css. You can handle this by adding a <code>switch</code> or <code>if</code> to your createServer code to perform a different action based on the URL the browser requests.</p>
<pre><code>var server = http.createServer(function (request, response) {
switch (request.url) {
case "/AppClientStyle.css" :
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
break;
default :
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
});
response.end();
}
</code></pre>
<p>So, first, when you access your server at <a href="http://localhost:8000" rel="noreferrer">http://localhost:8000</a> you will be sent your html file. Then the contents of that file will trigger the browser to ask for <a href="http://localhost:8000/AppClientStyle.css" rel="noreferrer">http://localhost:8000/AppClientStyle.css</a> </p>
<p>Note that you can make your server far more flexible by serving any file that exists in your project directory:</p>
<pre><code>var server = http.createServer(function (request, response) {
fs.readFile('./' + request.url, function(err, data) {
if (!err) {
var dotoffset = request.url.lastIndexOf('.');
var mimetype = dotoffset == -1
? 'text/plain'
: {
'.html' : 'text/html',
'.ico' : 'image/x-icon',
'.jpg' : 'image/jpeg',
'.png' : 'image/png',
'.gif' : 'image/gif',
'.css' : 'text/css',
'.js' : 'text/javascript'
}[ request.url.substr(dotoffset) ];
response.setHeader('Content-type' , mimetype);
response.end(data);
console.log( request.url, mimetype );
} else {
console.log ('file not found: ' + request.url);
response.writeHead(404, "Not Found");
response.end();
}
});
})
</code></pre>
<p>Start this in the same directory as your HTML and CSS files. The above is simplistic, error-prone and INSECURE. But it should be sufficient for your own learning or local development purposes.</p>
<p>Keep in mind that all the above is far less succinct than just using Express. In fact, I'm not sure why you wouldn't want to use Express, so I'm going to try to convince you to try it:</p>
<pre><code>$ npm install express
$ mkdir www
$ mv AppClientStyle.css www/
$ mv AppClient.html www/index.html
</code></pre>
<p>Your script will look like: (Borrowed from <a href="http://expressjs.com/starter/hello-world.html" rel="noreferrer">Express Hello World</a>)</p>
<pre><code>var express = require('express')
var app = express()
app.use(express.static('www'));
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log('Express app listening at http://%s:%s', host, port)
})
</code></pre>
<p>Then run your script and point your browser to <a href="http://localhost:8000" rel="noreferrer">http://localhost:8000</a>. It really is that painless.</p> |
40,867,727 | How to assign domain names to containers in Docker? | <p>I am reading a lot these days about how to setup and run a docker stack. But one of the things I am always missing out on is how to setup that particular containers respond to access through their domain name and not just their container name using docker dns.</p>
<p>What I mean is, that say I have a microservice which is accessible externally, for example: users.mycompany.com, it will go through to the microservice container which is handling the users api</p>
<p>Then when I try to access the customer-list.mycompany.com, it will go through to the microservice container which is handling the customer lists</p>
<p>Of course, using docker dns I can access them and link them into a docker network, but this only really works for wanting to access container to container, but not internet to container.</p>
<p>Does anybody know how I should do that? Or the best way to set that up.</p> | 40,869,934 | 3 | 0 | null | 2016-11-29 13:58:06.267 UTC | 32 | 2020-10-02 10:05:04.713 UTC | 2019-07-02 10:04:57.537 UTC | null | 4,217,744 | null | 279,147 | null | 1 | 49 | docker|dns|docker-compose | 68,477 | <p>So, you need to use the concept of port publishing, so that a port from your container is accessible via a port from your host. Using this, you can can setup a simple <em>proxy_pass</em> from an <em>Nginx</em> that will redirect <code>users.mycompany.com</code> to <code>myhost:1337</code> (<em>assuming that you published your port to <code>1337</code></em>)</p>
<p>So, if you want to do this, you'll need to setup your container to expose a certain port using: </p>
<pre><code>docker run -d -p 5000:5000 training/webapp # publish image port 5000 to host port 5000
</code></pre>
<p>You can then from your host <em>curl</em> your <code>localhost:5000</code> to access the container.</p>
<pre><code>curl -X GET localhost:5000
</code></pre>
<p>If you want to setup a domain name in front, you'll need to have a webserver instance that allows you to <em>proxy_pass</em> your hostname to your container.</p>
<p>i.e. in <em>Nginx</em>:</p>
<pre><code>server {
listen 80;
server_name users.mycompany.com;
location / {
proxy_pass http://localhost:5000;
}
}
</code></pre>
<p>I would advise you to follow <a href="https://docs.docker.com/engine/tutorials/usingdocker/#/running-a-web-application-in-docker" rel="noreferrer">this tutorial</a>, and maybe check the <a href="https://docs.docker.com/engine/reference/commandline/run/" rel="noreferrer">docker run reference</a>.</p> |
32,830,654 | Get failure exception in @HystrixCommand fallback method | <p>Is there a way to get the reason a <code>HystrixCommand</code> failed when using the <code>@HystrixCommand</code> annotation within a Spring Boot application? It looks like if you implement your own <code>HystrixCommand</code>, you have access to the <code>getFailedExecutionException</code> but how can you get access to this when using the annotation? I would like to be able to do different things in the fallback method based on the type of exception that occurred. Is this possible?</p>
<p>I saw a <a href="https://stackoverflow.com/questions/28323773/hystrix-getting-access-to-the-current-execution-state-within-fallback">note</a> about <code>HystrixRequestContext.initializeContext()</code> but the <code>HystrixRequestContext</code> doesn't give you access to anything, is there a different way to use that context to get access to the exceptions?</p> | 32,848,965 | 5 | 0 | null | 2015-09-28 19:49:07.047 UTC | 8 | 2018-06-20 03:15:14.897 UTC | 2017-05-23 12:09:39.44 UTC | null | -1 | null | 726,214 | null | 1 | 19 | spring|spring-cloud|hystrix | 29,032 | <p>I haven't found a way to get the exception with Annotations either, but creating my own Command worked for me like so:</p>
<pre><code>public static class DemoCommand extends HystrixCommand<String> {
protected DemoCommand() {
super(HystrixCommandGroupKey.Factory.asKey("Demo"));
}
@Override
protected String run() throws Exception {
throw new RuntimeException("failed!");
}
@Override
protected String getFallback() {
System.out.println("Events (so far) in Fallback: " + getExecutionEvents());
return getFailedExecutionException().getMessage();
}
}
</code></pre>
<p>Hopefully this helps someone else as well. </p> |
32,720,492 | Why is a class __dict__ a mappingproxy? | <p>I wonder why a class <code>__dict__</code> is a <code>mappingproxy</code>, but an instance <code>__dict__</code> is just a plain <code>dict</code></p>
<pre><code>>>> class A:
... pass
>>> a = A()
>>> type(a.__dict__)
<class 'dict'>
>>> type(A.__dict__)
<class 'mappingproxy'>
</code></pre> | 32,720,603 | 3 | 0 | null | 2015-09-22 15:08:59.223 UTC | 14 | 2021-03-24 08:20:39.487 UTC | 2020-10-28 03:01:26.053 UTC | null | 42,223 | null | 799,785 | null | 1 | 106 | python|python-3.x|class|dictionary|python-internals | 26,228 | <p>This helps the interpreter assure that the keys for class-level attributes and methods can only be strings.</p>
<p>Elsewhere, Python is a "consenting adults language", meaning that dicts for objects are exposed and mutable by the user. However, in the case of class-level attributes and methods for classes, if we can guarantee that the keys are strings, we can simplify and speed-up the common case code for attribute and method lookup at the class-level. In particular, the __mro__ search logic for new-style classes is simplified and sped-up by assuming the class dict keys are strings.</p> |
59,507,471 | Use Binding<Int> with a TextField SwiftUI | <p>I am currently building a page to add player information to a local database. I have a collection of TextFields for each input which is linked to elements in a player struct.</p>
<pre><code>var body: some View {
VStack {
TextField("First Name", text: $player.FirstName)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Last Name", text: $player.LastName)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Email", text: $player.eMail)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Shirt Number", text: $player.ShirtNumber)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("NickName", text: $player.NickName)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Height", text: $player.Height)
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Weight", text: $player.Weight)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
submitPlayer(player: self.player)T
}) {
Text("Submit")
}
Spacer()
}
}
</code></pre>
<p>My player struct is</p>
<pre><code>struct Player: Hashable, Codable, Identifiable {
var id: Int
var FirstName: String
var LastName: String
var NickName: String
var eMail: String
var ShirtNumber: Int
var Height: Int
var Weight: Int
}
</code></pre>
<p>The issue is that ShirtNumber, Height, and Weight are all Int values. When I bind them to the TextField I get an error saying <code>Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<String>'</code>. Everything I have looked into about SwiftUI says it's impossible to have a TextField with an Int value bound to it. </p>
<p>My question is, would it be possible to create a new class that extends TextField but allows for only Int inputs and that binds an Int variable, something like this?</p>
<pre><code>struct IntTextField: TextField {
init(_ text: String, binding: Binding<Int>) {
}
}
</code></pre>
<p>So far all I have been able to find is an answer to part of my question (accepting only Int input) from <a href="https://stackoverflow.com/questions/57822749/how-to-create-swiftui-textfield-that-accepts-only-numbers-and-a-single-dot">this</a> question. I am looking for a way to combine this with the <code>Binding<Int></code>.</p>
<p>Thanks for the help.</p> | 59,508,167 | 4 | 0 | null | 2019-12-28 01:33:54.923 UTC | 8 | 2022-08-23 13:32:39.607 UTC | null | null | null | null | 5,569,399 | null | 1 | 35 | swift|xcode|swiftui | 27,413 | <p>Actually , you can binding manyTypes with <code>TextField</code>:</p>
<pre><code> @State var weight: Int = 0
var body: some View {
Group{
Text("\(weight)")
TextField("Weight", value: $weight, formatter: NumberFormatter())
}}
</code></pre> |
30,841,981 | How to deserialize a blank JSON string value to null for java.lang.String? | <p>I am trying a simple JSON to de-serialize in to java object. I am however, getting empty <em>String</em> values for <code>java.lang.String</code> property values. In rest of the properties, blank values are converting to <em>null</em> values(which is what I want).</p>
<p>My JSON and related Java class are listed below.</p>
<p>JSON string:</p>
<pre class="lang-json prettyprint-override"><code>{
"eventId" : 1,
"title" : "sample event",
"location" : ""
}
</code></pre>
<p><em>EventBean</em> class POJO:</p>
<pre class="lang-java prettyprint-override"><code>public class EventBean {
public Long eventId;
public String title;
public String location;
}
</code></pre>
<p>My main class code:</p>
<pre class="lang-java prettyprint-override"><code>ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
try {
File file = new File(JsonTest.class.getClassLoader().getResource("event.txt").getFile());
JsonNode root = mapper.readTree(file);
// find out the applicationId
EventBean e = mapper.treeToValue(root, EventBean.class);
System.out.println("It is " + e.location);
}
</code></pre>
<p>I was expecting print "It is null". Instead, I am getting "It is ". Obviously, <em>Jackson</em> is not treating blank String values as NULL while converting to my <em>String</em> object type. </p>
<p>I read somewhere that it is expected. However, this is something I want to avoid for <em>java.lang.String</em> too. Is there a simple way? </p> | 30,842,427 | 5 | 0 | null | 2015-06-15 09:42:16.137 UTC | 7 | 2020-12-16 10:37:20.97 UTC | 2018-05-15 15:48:33.063 UTC | null | 814,702 | null | 2,784,336 | null | 1 | 31 | java|json|jackson | 40,207 | <p>Jackson will give you null for other objects, but for String it will give empty String.</p>
<p>But you can use a Custom <code>JsonDeserializer</code> to do this:</p>
<pre><code>class CustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
if (node.asText().isEmpty()) {
return null;
}
return node.toString();
}
}
</code></pre>
<p>In class you have to use it for location field:</p>
<pre><code>class EventBean {
public Long eventId;
public String title;
@JsonDeserialize(using = CustomDeserializer.class)
public String location;
}
</code></pre> |
49,834,961 | The module 'app' is an Android project without build variants | <p>I am getting below error while importing android project.</p>
<p>Error:The module 'app' is an Android project without build variants, and cannot be built.
Please fix the module's configuration in the build.gradle file and sync the project again.</p>
<p>Gradle file code.</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.djalel.android.bilal"
minSdkVersion 9
targetSdkVersion 25
versionCode 4
versionName "1.3"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt')
}
}
aaptOptions {
cruncherEnabled = false
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:25.3.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:25.3.1'
implementation 'com.android.support:support-v4:25.3.1'
implementation 'com.google.android.gms:play-services-location:12.0.1'
implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1'
implementation 'com.jakewharton.timber:timber:3.1.0'
}
repositories {
mavenCentral()
}
</code></pre>
<p>I checked with working gradle file as well but getting same error in this project.</p> | 53,533,401 | 7 | 3 | null | 2018-04-14 18:45:47.927 UTC | 3 | 2020-10-09 20:09:53.127 UTC | null | null | null | null | 2,598,244 | null | 1 | 38 | android|android-studio|android-gradle-plugin | 33,626 | <p>Above gradle file code seems to be perfect. Probably its nothing to do with app/build.gradle (Module:app). Just open other build.gradle (Project:Android) file in Project window and verify your Android Studio version it must be same as yours.</p>
<p>I replaced from:</p>
<pre><code>dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
</code></pre>
<p>to my Android Studio v3.0.1 in my case:</p>
<pre><code>dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
</code></pre>
<p>Press "Try Again" to Sync gradle file. This resolved my problem with a successful build.</p> |
19,102,950 | Default Values for Parameter not Working in SSRS 2008 R2 | <p>I have a report (BIDS SSRS 2008 R2) that has a parameter that allows the user to select multiple values from a list (Sales Regions, lets say). </p>
<p>I want, though, since the list is long (15 or so possible values) have selected by default the 2 values that are used the most. </p>
<p>I configure that in the Parameter Properties >> Default Value dialog and when I run the report in preview mode it works, meaning, the default values are checked.</p>
<p>However, when I deploy it and run it with IE9 (or Chrome) it doesn't work.</p>
<p>Any ideas?</p> | 19,103,518 | 6 | 0 | null | 2013-09-30 20:12:25.457 UTC | 6 | 2022-08-24 12:08:52.997 UTC | null | null | null | null | 1,239,352 | null | 1 | 20 | reporting-services|bids | 54,621 | <p>I would guess that your build is bad you are deploying and did not get updated from either a change you made or it is not overwriting a value. You can do a few things to ensure default parameter values are there.</p>
<ol>
<li><p>Go the published report on the server and click the drop down arrow on the right and choose 'manage'. Now choose 'Parameters' on the left pane. Under the 'Has Default' column (3rd from left on 2008R2 and higher) it should be checked. Then under 'Default Value' it is either a specific explicit input or it will say 'Query based' meaning it derives its value from a dataset or similar manner. If this is different than your value you would expect and is explicit you can just change it here.</p></li>
<li><p>If it is query based and you observe that your data cannot be altered here I would go to BIDS and open up the SSRS project under the solution and choose to 'Open Folder in Windows Explorer'. Find your report's DATA file and delete it. Note this is NOT the report itself but a file similar to it like 'report.rdl.data'. This is NOT a step that most likely affects the build but merely the preview, however we wish to see the preview after the rebuild exactly as it would be. Go to your report's project and choose 'Clean' then 'Rebuild' to ensure you are removing all the data files in the bin in addition to the one you did explicitly. Rebuild will now build all the files from the instructions. Now click preview on your report, verify it is as expected with defaults. Publish again and observe.</p></li>
<li><p>If this still did not change the report I would guess the updates are not taking. I would rename the report on the server like 'report_old' and try to publish again.</p></li>
<li><p>If this still did not take I would check that the publish location we want is valid and we are deploying correctly and that any parameters are not getting data from shared datasets that are not set to 'do not overwrite' or weird edge cases resulting from publishing being halted due to config settings.</p></li>
</ol>
<p>SSRS has had weird issues for me in the past with the issue of my files being under source control and then the system not wanting updates to parameters myself. Generally this is fixed with a rebuild but sometimes it does require a new binary file to be published.</p> |
26,735,629 | Angular.js 1.3 One-time binding in ng-bind | <p>In Angular.js 1.3 I can do a one time binding with:</p>
<pre><code>{{::name}}
</code></pre>
<p>But how may I use this in <code>ng-bind</code>?</p>
<p><code>ng-bind</code> had some performance improvements in comparison to the <code>{{</code> syntax.</p>
<p>Is it supported?</p> | 26,735,724 | 1 | 0 | null | 2014-11-04 12:52:26.78 UTC | 3 | 2015-09-19 03:25:46.37 UTC | 2015-09-19 03:25:46.37 UTC | null | 2,451,726 | null | 593,461 | null | 1 | 48 | angularjs|ng-bind | 10,573 | <p>Yes. This works: </p>
<pre><code><span ng-bind="::name"></span>
</code></pre> |
35,860,102 | Autoshrink setting for UIButton in Storyboard | <p>There is a setting for UILabel in storyboard that allows setting auto-shrink configurations, as shown below:</p>
<p><a href="https://i.stack.imgur.com/8fIgI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8fIgI.png" alt="enter image description here" /></a></p>
<p>But I am unable to find the same for UIButton's textlabel. <em><strong>I am aware that I can set this programmatically but curious to know if there's a way to enable this setting for UIButton in Storyboard.</strong></em></p> | 36,151,101 | 5 | 0 | null | 2016-03-08 06:01:25.907 UTC | 9 | 2022-05-04 17:40:00.46 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,756,279 | null | 1 | 43 | ios|xcode|xcode-storyboard | 12,682 | <p>You can use User Defined Runtime Attributes to set this flag using the storyboard.</p>
<p>Set the following key path:</p>
<pre><code>titleLabel.adjustsFontSizeToFitWidth to true
</code></pre>
<p><a href="https://i.stack.imgur.com/V3okJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V3okJ.png" alt="Adjust Font Size using Storyboard"></a></p> |
48,117,059 | Could not write JSON: failed to lazily initialize a collection of role | <p>I try to implement a server REST with java - hibernate - spring, which returns a json.</p>
<p>I have map a many to many relation. </p>
<p>I explain better, I have a supplier that have a list of ingredients, and each ingredient has a list of supplier.</p>
<p>I created the table:</p>
<pre><code>CREATE TABLE supplier_ingredient (
supplier_id BIGINT,
ingredient_id BIGINT
)
ALTER TABLE supplier_ingredient ADD CONSTRAINT supplier_ingredient_pkey
PRIMARY KEY(supplier_id, ingredient_id);
ALTER TABLE supplier_ingredient ADD CONSTRAINT
fk_supplier_ingredient_ingredient_id FOREIGN KEY (ingredient_id)
REFERENCES ingredient(id);
ALTER TABLE supplier_ingredient ADD CONSTRAINT
fk_supplier_ingredient_supplier_id FOREIGN KEY (supplier_id) REFERENCES
supplier(id);
</code></pre>
<p>Then I have <strong>Ingredient</strong> model:</p>
<pre><code>.....
.....
@ManyToMany(mappedBy = "ingredients")
@OrderBy("created DESC")
@BatchSize(size = 1000)
private List<Supplier> suppliers = new ArrayList<>();
....
....
</code></pre>
<p>Then I have <strong>Supplier</strong> model:</p>
<pre><code>....
@ManyToMany
@JoinTable( name = "supplier_ingredient ",
joinColumns = @JoinColumn(name = "supplier_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "ingredient_id", referencedColumnName = "id"),
foreignKey = @ForeignKey(name = "fk_supplier_ingredient_supplier_id"))
@OrderBy("created DESC")
@Cascade(CascadeType.SAVE_UPDATE)
@BatchSize(size = 1000)
private List<Ingredient> ingredients = new ArrayList<>();
....
</code></pre>
<p><strong>Endpoint</strong>:</p>
<pre><code>@RequestMapping(value = "/{supplierId:[0-9]+}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public SupplierObject get(@PathVariable Long supplierId) {
Supplier supplier = supplierService.get(supplierId);
SupplierObject supplierObject = new SupplierObject (supplier);
return SupplierObject;
}
</code></pre>
<p><strong>Service</strong></p>
<pre><code>....
public Supplier get(Long supplierId) {
Supplier supplier = supplierDao.getById(supplierId); (it does entityManager.find(entityClass, id))
if (supplier == null) throw new ResourceNotFound("supplier", supplierId);
return supplier;
}
....
</code></pre>
<p><strong>SupplierObject</strong></p>
<pre><code> @JsonIgnoreProperties(ignoreUnknown = true)
public class SupplierObject extends IdAbstractObject {
public String email;
public String phoneNumber;
public String address;
public String responsible;
public String companyName;
public String vat;
public List<Ingredient> ingredients = new ArrayList<>();
public SupplierObject () {
}
public SupplierObject (Supplier supplier) {
id = supplier.getId();
email = supplier.getEmail();
responsible = supplier.getResponsible();
companyName = supplier.getCompanyName();
phoneNumber = supplier.getPhone_number();
ingredients = supplier.getIngredients();
vat = supplier.getVat();
address = supplier.getAddress();
}
}
</code></pre>
<p>And <strong>IdAbstractObject</strong></p>
<pre><code>public abstract class IdAbstractObject{
public Long id;
}
</code></pre>
<p>My problem is, when I call the endpoint:</p>
<pre><code>http://localhost:8080/supplier/1
</code></pre>
<p>I got an error:</p>
<blockquote>
<p>"Could not write JSON: failed to lazily initialize a collection of
role: myPackage.ingredient.Ingredient.suppliers, could not initialize
proxy - no Session; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily
initialize a collection of role:
myPackage.ingredient.Ingredient.suppliers, could not initialize proxy
- no Session (through reference chain: myPackage.supplier.SupplierObject[\"ingredients\"]->org.hibernate.collection.internal.PersistentBag[0]->myPackage.ingredient.Ingredient[\"suppliers\"])"</p>
</blockquote>
<p>I followed this:</p>
<p><a href="https://stackoverflow.com/questions/21708339/avoid-jackson-serialization-on-non-fetched-lazy-objects/21760361#21760361">Avoid Jackson serialization on non fetched lazy objects</a></p>
<p>Now I haven't the error but in json returned, the ingredients field is null:</p>
<pre><code>{
"id": 1,
"email": "[email protected]",
"phoneNumber": null,
"address": null,
"responsible": null,
"companyName": "Company name",
"vat": "vat number",
"ingredients": null
}
</code></pre>
<p>but in debug I can see ingredients....</p>
<p><a href="https://i.stack.imgur.com/0vTaB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/0vTaB.jpg" alt="enter image description here"></a></p> | 48,152,153 | 8 | 0 | null | 2018-01-05 15:56:46.723 UTC | 3 | 2022-07-25 13:57:27.237 UTC | 2020-02-06 13:23:05.573 UTC | null | 8,718,377 | null | 3,336,884 | null | 1 | 14 | java|spring|hibernate|spring-boot|jackson | 46,631 | <p>This is the normal behaviour of Hibernate and Jackson Marshaller
Basically you want to have the following: a JSON with all Supplier object details... included the Ingredients. </p>
<p>Please note that in this case you must be very carefull because you can have a cyclic reference when you try to create the JSON itself so you should use also <a href="https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonIgnore.html" rel="noreferrer"><code>JsonIgnore</code></a> annotation</p>
<p>The first thing you must do is to load the Supplier and all its details (ingredients included). </p>
<p>How can you do it? By using several strategies... let's use the <a href="https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Hibernate.html#initialize-java.lang.Object-" rel="noreferrer"><code>Hibernate.initialize</code></a>. This <strong>must be used before the closing of hibernate session</strong> that is in the DAO (or repository) implementation (basically where you use the hibernate session). </p>
<p>So in this case (I assume to use Hibernate) in my repository class I should write something like this:</p>
<pre><code>public Supplier findByKey(Long id)
{
Supplier result = (Supplier) getSession().find(Supplier.class, id);
Hibernate.initialize(result.getIngredients());
return result;
}
</code></pre>
<p>Now you have the <code>Supplier</code> object with all its own details (<code>Ingredients</code> too)
Now in your service you can do what you did that is:</p>
<pre><code>@RequestMapping(value = "/{supplierId:[0-9]+}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public SupplierObject get(@PathVariable Long supplierId)
{
Supplier supplier = supplierService.get(supplierId);
SupplierObject supplierObject = new SupplierObject (supplier);
return SupplierObject;
}
</code></pre>
<p>In this way Jackson is able in writing the JSON <code>but</code> let's give a look to the <code>Ingredient</code> object.. it has the following property:</p>
<pre><code>@ManyToMany(mappedBy = "ingredients")
@OrderBy("created DESC")
@BatchSize(size = 1000)
private List<Supplier> suppliers = new ArrayList<>();
</code></pre>
<p>What will happen when Jackson tries to create the JSON? It will access to the each element inside the <code>List<Ingredient></code> and it will try to create a JSON for this one too.... also for the suppliers list and this is a cyclic reference... so you must avoid it and you can avoid it by using the JsonIgnore annotation. For example you may write your <code>Ingredient</code> entity class in this way:</p>
<pre><code>@JsonIgnoreProperties(value= {"suppliers"})
public class Ingredient implements Serializable
{
......
}
</code></pre>
<p>In this way you:</p>
<ul>
<li>load the supplier object with all the related ingredient</li>
<li>avoid a cyclic reference when you try to create the JSON itself</li>
</ul>
<p>In any case I would suggest to you to create specific DTO (or VO) object to use for marshalling and unmarshalling JSONs</p>
<p>I hope this is usefull</p>
<p>Angelo</p> |
34,498,184 | Difference between FileContentResult and FileStreamResult | <p>I'm editing some code and there is one method which return <code>FileContentResult</code> type. I get a stream from service, so for me it would be more convenient to change returning type to <code>FileStreamResult</code>. </p>
<p>Should I convert stream to an array to return <code>FileContentResult</code>? </p>
<p>Or can I just change returning type safely?</p> | 34,498,291 | 2 | 0 | null | 2015-12-28 17:45:07.667 UTC | 9 | 2021-11-19 23:02:52.477 UTC | 2015-12-28 17:55:12.13 UTC | null | 1,669,996 | null | 3,818,229 | null | 1 | 34 | c#|asp.net-mvc|file | 45,491 | <p><code>FileResult</code> is an abstract base class for all the others.</p>
<ul>
<li><code>FileContentResult</code> - use it when you have a byte array you would
like to return as a file</li>
<li><code>FileStreamResult</code> - you have a stream open, you want to return it's
content as a file</li>
</ul>
<p>Reference: <a href="https://stackoverflow.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc/1187270#1187270">What's the difference between the four File Results in ASP.NET MVC</a></p> |
25,941,559 | Is there a way to keep execCommand("insertHTML") from removing attributes in chrome? | <p>Context is Chrome 37.0.2062.120 m. </p>
<p>I'm using execCommand to insert html into an editable div. My execCommand call looks like this:</p>
<pre><code>function insertHTML(){
document.execCommand('insertHTML', false, '<span id="myId">hi</span>');
}
</code></pre>
<p>When the editable div looks like this:</p>
<pre><code><div contenteditable="true">
some [insertion point] content
</div>
</code></pre>
<p>and I use execCommand to insert html into a contenteditable div, all of the attributes of the HTML are inserted as expected and I end up with this:</p>
<pre><code><div contenteditable="true">
some <span id="myId">hi</span> content
</div>
</code></pre>
<p>When, however, I insert the exact same html into this structure:</p>
<pre><code><div contenteditable="true">
some content
<div>more [insertion point] content</div>
</div>
</code></pre>
<p>The attributes are removed from the span being inserted and it ends up looking like this:</p>
<pre><code><div contenteditable="true">
some content
<div>more <span style="font-size: 10pt;">hi</span> content</div>
</div>
</code></pre>
<p>Is there any way to keep this from happening?</p> | 25,943,182 | 2 | 0 | null | 2014-09-19 20:00:12.36 UTC | 9 | 2019-07-19 14:20:17.703 UTC | 2014-09-19 20:49:26.593 UTC | null | 166,060 | null | 166,060 | null | 1 | 23 | javascript|contenteditable|execcommand | 23,520 | <p>In this particular case I would suggest using <a href="https://developer.mozilla.org/en-US/docs/Web/API/range.insertNode"><code>Range.insertNode</code></a> instead, which will give you total control of what gets inserted:</p>
<pre><code>function insertHTML() {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
range.collapse(true);
var span = document.createElement("span");
span.id = "myId";
span.appendChild( document.createTextNode("hi") );
range.insertNode(span);
// Move the caret immediately after the inserted span
range.setStartAfter(span);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function isOrIsAncestorOf(ancestor, descendant) {
var n = descendant;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function nodeContainsSelection(node) {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
return isOrIsAncestorOf(node, range.commonAncestorContainer);
}
return false;
}
function insertHTML() {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
range.collapse(true);
var span = document.createElement("span");
span.id = "myId";
span.appendChild( document.createTextNode("hi") );
range.insertNode(span);
// Move the caret immediately after the inserted span
range.setStartAfter(span);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
window.onload = function() {
document.getElementById("inserter").onmousedown = function() {
var editor = document.getElementById("editor");
if (nodeContainsSelection(editor)) {
insertHTML();
return false;
}
};
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
font-weight: bold;
color: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="inserter" value="Insert span">
<div contenteditable="true" id="editor">
some content
</div></code></pre>
</div>
</div>
</p> |
45,001,503 | Vue-Router Passing Data with Props | <p>I am having a hard time passing props using Vue-Router. I seem to not be able to access the props when I bring them into the next view. This is my methods object: </p>
<pre><code>methods: {
submitForm() {
let self = this;
axios({
method: 'post',
url: url_here,
data:{
email: this.email,
password: this.password
},
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'
}
}).then(function(response) {
self.userInfo = response.data;
self.$router.push({name: 'reading-comprehension', props: {GUID:self.userInfo.uniqueID }});
})
}
}
</code></pre>
<p>The post request is working, but when I try to route to a new component and pass in a props to access in the next component, it says,</p>
<blockquote>
<p>Property or method "guid" is not defined on the instance but
referenced during render. Make sure to declare reactive data
properties in the data option.</p>
</blockquote>
<p>By the way, the component that I am routing to looks like this:</p>
<pre><code><template lang="html">
<div class="grid-container" id="read-comp">
<div class="row">
<h1>Make a sentence:</h1>
{{ GUID }}
</div>
</div>
</template>
<script>
export default {
data(){
return {
props: ['GUID'],
}
}
}
</code></pre> | 45,001,550 | 1 | 0 | null | 2017-07-09 22:08:20.31 UTC | 8 | 2017-07-10 00:53:55.96 UTC | 2017-07-10 00:53:55.96 UTC | null | 3,412,322 | null | 7,710,038 | null | 1 | 23 | vue.js|vuejs2|vue-component|axios|vue-router | 28,095 | <p>When you navigate to the new route programmatically, you should <a href="https://router.vuejs.org/en/essentials/navigation.html" rel="noreferrer">use <code>params</code>, not props</a>.</p>
<pre><code>self.$router.push({name: 'reading-comprehension', params: {guid:self.userInfo.uniqueID }});
</code></pre>
<p>Secondly, in your route definition, you should set <a href="https://router.vuejs.org/en/essentials/passing-props.html" rel="noreferrer">the <code>props</code> property</a> to true.</p>
<pre><code>{name: "reading-comprehension", component: SomeComponent, props: true }
</code></pre>
<p>Finally, in your component, you define <code>props</code> separately from <code>data</code> and it should be all lower case.</p>
<pre><code>export default {
props: ["guid"],
data(){
return {
}
}
}
</code></pre> |
7,057,934 | Property vs Instance Variable | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/843632/is-there-a-difference-between-an-instance-variable-and-a-property-in-objectiv">Is there a difference between an "instance variable" and a "property" in objective-c / cocoa / cocoa-touch?</a> </p>
</blockquote>
<p>What is a case in Objective C where you would want to use an instance variable vs property? Can someone provide a real-life example?</p> | 7,057,966 | 1 | 1 | null | 2011-08-14 16:00:07.867 UTC | 41 | 2018-05-12 08:02:09.23 UTC | 2017-05-23 11:33:13.66 UTC | null | -1 | null | 472,292 | null | 1 | 50 | objective-c | 45,004 | <p>An instance variable is unique to a class. By default, only the class and subclasses can access it. Therefore, as a fundamental principal of object-oriented programming, instance variables (ivars) are private—they are encapsulated by the class. </p>
<p>By contrast, a property is a public value that may or may not correspond to an instance variable. If you want to make an ivar public, you'd probably make a corresponding property. But at the same time, instance variables that you wish to keep private do not have corresponding properties, and so they cannot be accessed from outside of the class. You can also have a calculated property that does not correspond to an ivar.</p>
<p>Without a property, ivars can be kept hidden. In fact, unless an ivar is declared in a public header it is difficult to even determine that such an ivar exists. </p>
<p>A simple analogy would be a shrink-wrapped book. A property might be the <code>title</code>, <code>author</code> or hardcover vs. softcover. The "ivars" would be the actual contents of the book. You don't have access to the actual text until you own the book; you don't have access to the ivars unless you own the class.</p>
<p><hr />
More interestingly, properties are better integrated into the runtime. Modern 64-bit runtimes will generate an ivar for accessor properties, so you don't even need to create the ivar. Properties are in fact methods:</p>
<pre><code>// This is not syntactically correct but gets the meaning across
(self.variable) == ([self variable];)
(self.variable = 5;) == ([self setVariable:5];)
</code></pre>
<p>For every property, there are two methods (unless the property is declared <code>readonly</code>, in which case there is only one): there is the <em>getter</em>, which returns the same type as the ivar and is of the same name as the ivar, as well as the <em>setter</em> (which is not declared with a <code>readonly</code> ivar); it returns void and its name is simply <em>set</em> prepended to the variable name. </p>
<p>Because they are methods, you can make dynamic calls on them. Using <a href="http://www.cocoadev.com/index.pl?NSSelectorFromString" rel="noreferrer"><code>NSSelectorFromString()</code></a> and the various <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html" rel="noreferrer"><code>performSelector:</code></a> methods, you can make a very dynamic program with many possibilities. </p>
<p>Finally, properties are used extensively in Core Data and with <a href="http://cupsofcocoa.wordpress.com/2011/05/09/objective-c-lesson-13-key-value-coding/" rel="noreferrer">Key-Value Coding</a>. Core Data is an advanced framework for storing data in a SQLite database while providing a clear Obj-C front-end; KVC is used throughout Core Data and is a dynamic way to access properties. It is used when encoding/decoding objects, such as when reading from XIBs.</p> |
22,532,302 | Pandas: peculiar performance drop for inplace rename after dropna | <p>I have reported this as an issue on <a href="https://github.com/pydata/pandas/issues/6674" rel="noreferrer">pandas issues</a>.
In the meanwhile I post this here hoping to save others time, in case they encounter similar issues.</p>
<p>Upon profiling a process which needed to be optimized I found that renaming columns NOT inplace improves performance (execution time) by x120.
Profiling indicates this is related to garbage collection (see below).</p>
<p>Furthermore, the expected performance is recovered by avoiding the dropna method.</p>
<p>The following short example demonstrates a factor x12:</p>
<pre><code>import pandas as pd
import numpy as np
</code></pre>
<h3>inplace=True</h3>
<pre><code>%%timeit
np.random.seed(0)
r,c = (7,3)
t = np.random.rand(r)
df1 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
indx = np.random.choice(range(r),r/3, replace=False)
t[indx] = np.random.rand(len(indx))
df2 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
df = (df1-df2).dropna()
## inplace rename:
df.rename(columns={col:'d{}'.format(col) for col in df.columns}, inplace=True)
</code></pre>
<blockquote>
<p>100 loops, best of 3: 15.6 ms per loop</p>
</blockquote>
<p>first output line of <code>%%prun</code>:</p>
<blockquote>
<p>ncalls tottime percall cumtime percall filename:lineno(function)</p>
<pre><code>1 0.018 0.018 0.018 0.018 {gc.collect}
</code></pre>
</blockquote>
<h3>inplace=False</h3>
<pre><code>%%timeit
np.random.seed(0)
r,c = (7,3)
t = np.random.rand(r)
df1 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
indx = np.random.choice(range(r),r/3, replace=False)
t[indx] = np.random.rand(len(indx))
df2 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
df = (df1-df2).dropna()
## avoid inplace:
df = df.rename(columns={col:'d{}'.format(col) for col in df.columns})
</code></pre>
<blockquote>
<p>1000 loops, best of 3: 1.24 ms per loop</p>
</blockquote>
<h3>avoid dropna</h3>
<p>The expected performance is recovered by avoiding the <code>dropna</code> method:</p>
<pre><code>%%timeit
np.random.seed(0)
r,c = (7,3)
t = np.random.rand(r)
df1 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
indx = np.random.choice(range(r),r/3, replace=False)
t[indx] = np.random.rand(len(indx))
df2 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
#no dropna:
df = (df1-df2)#.dropna()
## inplace rename:
df.rename(columns={col:'d{}'.format(col) for col in df.columns}, inplace=True)
</code></pre>
<blockquote>
<p>1000 loops, best of 3: 865 µs per loop</p>
</blockquote>
<pre><code>%%timeit
np.random.seed(0)
r,c = (7,3)
t = np.random.rand(r)
df1 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
indx = np.random.choice(range(r),r/3, replace=False)
t[indx] = np.random.rand(len(indx))
df2 = pd.DataFrame(np.random.rand(r,c), columns=range(c), index=t)
## no dropna
df = (df1-df2)#.dropna()
## avoid inplace:
df = df.rename(columns={col:'d{}'.format(col) for col in df.columns})
</code></pre>
<blockquote>
<p>1000 loops, best of 3: 902 µs per loop</p>
</blockquote> | 22,533,110 | 1 | 0 | null | 2014-03-20 11:59:42.1 UTC | 18 | 2017-06-08 22:12:53.95 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,204,331 | null | 1 | 44 | python|performance|pandas|in-place | 22,205 | <p>This is a copy of the explanation on github.</p>
<p>There is <strong>no guarantee</strong> that an <code>inplace</code> operation is actually faster. Often they are actually the same operation that works on a copy, but the top-level reference is reassigned.</p>
<p>The reason for the difference in performance in this case is as follows.</p>
<p>The <code>(df1-df2).dropna()</code> call creates a slice of the dataframe. When you apply a new operation, this triggers a <code>SettingWithCopy</code> check because it <em>could</em> be a copy (but often is not).</p>
<p>This check must perform a garbage collection to wipe out some cache references to see if it's a copy. Unfortunately python syntax makes this unavoidable.</p>
<p>You can not have this happen, by simply making a copy first.</p>
<pre><code>df = (df1-df2).dropna().copy()
</code></pre>
<p>followed by an <code>inplace</code> operation will be as performant as before.</p>
<p>My personal opinion: I <strong>never</strong> use in-place operations. The syntax is harder to read and it does not offer any advantages.</p> |
22,255,476 | Rails formatting date | <p>I am posting a date to an API and the required format is as follows:</p>
<pre><code>2014-12-01T01:29:18
</code></pre>
<p>I can get the date from the model like so:</p>
<pre><code>Model.created_at.to_s
</code></pre>
<p>That returns:</p>
<pre><code>2014-12-01 01:29:18 -0500
</code></pre>
<p>How can I use Rails or Ruby to format it like the required format with the T and removing the -0500?</p> | 22,255,887 | 4 | 0 | null | 2014-03-07 16:28:35.08 UTC | 40 | 2021-09-19 20:46:50.523 UTC | 2019-12-07 23:39:42.213 UTC | null | 212,378 | null | 2,879,095 | null | 1 | 156 | ruby-on-rails|ruby|date|date-format | 213,255 | <p>Use</p>
<pre><code>Model.created_at.strftime("%FT%T")
</code></pre>
<p>where, </p>
<pre><code>%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)
</code></pre>
<p>Following are some of the frequently used useful list of <code>Date</code> and <code>Time</code> formats that you could specify in <code>strftime</code> method:</p>
<pre><code>Date (Year, Month, Day):
%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%C - year / 100 (round down. 20 in 2009)
%y - year % 100 (00..99)
%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%B - The full month name (``January'')
%^B uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
%^b uppercased (``JAN'')
%h - Equivalent to %b
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)
%j - Day of the year (001..366)
Time (Hour, Minute, Second, Subsecond):
%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)
%l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')
%M - Minute of the hour (00..59)
%S - Second of the minute (00..59)
%L - Millisecond of the second (000..999)
%N - Fractional seconds digits, default is 9 digits (nanosecond)
%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
%12N picosecond (12 digits)
</code></pre>
<p>For the <em>complete list</em> of formats for <code>strftime</code> method please visit <a href="http://apidock.com/ruby/DateTime/strftime">APIDock</a></p> |
31,820,336 | Why must/should UI frameworks be single threaded? | <p>Closely related questions have been asked before: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/5544447/why-are-most-ui-frameworks-single-threaded">Why are most UI frameworks single threaded?</a>.</li>
<li><a href="https://stackoverflow.com/questions/743008/should-all-event-driven-frameworks-be-single-threaded">Should all event-driven frameworks be single-threaded?</a></li>
</ul>
<p>But the answers to those questions still leave me unclear on some points.</p>
<ul>
<li><p>The asker of the first question asked if multi-threading would help performance, and the answerers mostly said that it would not, because it is very unlikely that the GUI would be the bottleneck in a 2D application on modern hardware. But this seems to me a sneaky debating tactic. Sure, if you have carefully structured your application to do nothing other than UI calls on the UI thread you won't have a bottleneck. But that might take a lot of work and make your code more complicated, and if you had a faster core or could make UI calls from multiple threads, maybe it wouldn't be worth doing.</p></li>
<li><p>A commonly advocated architectural design is to have view components that don't have callbacks and don't need to lock anything except maybe their descendants. Under such an architecture, can't you let any thread invoke methods on view objects, using per-object locks, without fear of deadlock?</p></li>
<li><p>I am less confident about the situation with UI controls, but as long their callbacks are only invoked by the system, why should they cause any <em>special</em> deadlock issues? After all, if the callbacks need to do anything time consuming, they will delegate to another thread, and then we're right back in the multiple threads case.</p></li>
<li><p>How much of the benefit of a multi-threaded UI would you get if you could just block on the UI thread? Because various emerging abstractions over async in effect let you do that.</p></li>
<li><p>Almost all of the discussion I have seen assumes that concurrency will be dealt with using manual locking, but there is a broad consensus that manual locking is a bad way to manage concurrency in most contexts. How does the discussion change when we take into consideration the concurrency primitives that the experts are advising us to use more, such as software transactional memory, or eschewing shared memory in favor of message passing (possibly with synchronization, as in go)?</p></li>
</ul> | 31,822,536 | 3 | 0 | null | 2015-08-04 22:17:27.03 UTC | 10 | 2022-06-19 06:29:04.383 UTC | 2017-05-23 11:46:40.517 UTC | null | -1 | null | 4,943,253 | null | 1 | 18 | multithreading|swing|concurrency|erlang|locking | 5,593 | <p><strong>TL;DR</strong></p>
<p>It is a simple way to force sequencing to occur in an activity that is going to ultimately be in sequence anyway (the screen draw X times per second, in order).</p>
<p><strong>Discussion</strong></p>
<p>Handling long-held resources which have a single identity within a system is typically done by representing them with a single thread, process, "object" or whatever else represents an atomic unit with regard to concurrency in a given language. Back in the non-emptive, negligent-kernel, non-timeshared, One True Thread days this was managed manually by polling/cycling or writing your own scheduling system. In such a system you still had a 1::1 mapping between function/object/thingy and singular resources (or you went mad before 8th grade).</p>
<p>This is the same approach used with handling network sockets, or any other long-lived resource. The GUI itself is but one of many such resources a typical program manages, and typically long-lived resources are places where the ordering of events matters.</p>
<p>For example, in a chat program you would usually not write a single thread. You would have a GUI thread, a network thread, and maybe some other thread that deals with logging resources or whatever. It is not uncommon for a typical system to be so fast that its easier to just put the logging and input into the same thread that makes GUI updates, but this is not always the case. In all cases, though, each category of resources is most easily reasoned about by granting them a single thread, and that means one thread for the network, one thread for the GUI, and however many other threads are necessary for long-lived operations or resources to be managed without blocking the others.</p>
<p>To make life easier its common to <em>not</em> share data directly among these threads as much as possible. Queues are much easier to reason about than resource locks and can guarantee sequencing. Most GUI libraries either queue events to be handled (so they can be evaluated in order) or commit data changes required by events immediately, but get a lock on the state of the GUI prior to each pass of the repaint loop. It doesn't matter what happened before, the only thing that matters when painting the screen is the state of the world <em>right then</em>. This is slightly different than the typical network case where all the data needs to be sent in order and forgetting about some of it is not an option.</p>
<p>So GUI frameworks are not multi-threaded, per se, it is the GUI loop that needs to be a single thread to sanely manage that single long-held resource. Programming examples, typically being trivial by nature, are often single-threaded with all the program logic running in the same process/thread as the GUI loop, but this is not typical in more complex programs.</p>
<p><strong>To sum up</strong></p>
<p>Because scheduling is hard, shared data management is even harder, and a single resource can only be accessed serially anyway, a single thread used to represent each long-held resource and each long-running procedure is a typical way to structure code. GUIs are only one resource among several that a typical program will manage. So "GUI programs" are by no means single-threaded, but GUI libraries typically are.</p>
<p>In trivial programs there is no realized penalty to putting other program logic in the GUI thread, but this approach falls apart when significant loads are experienced or resource management requires either a lot of blocking or polling, which is why you will often see event queue, signal-slot message abstractions or other approaches to multi-threading/processing mentioned in the dusty corners of nearly any GUI library (and here I'm including game libraries -- while game libs typically expect that you want to essentially build your own widgets around your own UI concept, the basic principles are very similar, just a bit lower-level).</p>
<p>[As an aside, I've been doing a lot of Qt/C++ and Wx/Erlang lately. <a href="http://doc.qt.io/qt-5/threads-technologies.html" rel="noreferrer">The Qt docs do a good job of explaining approaches to multi-threading</a>, the role of the GUI loop, and where Qt's signal/slot approach fits into the abstraction (so you don't have to think about concurrency/locking/sequencing/scheduling/etc very much). Erlang is inherently concurrent, but <a href="http://www.erlang.org/doc/man/wx.html" rel="noreferrer">wx itself is typically started as a single OS process that manages a GUI update loop</a> and Erlang posts update events to it as messages, and GUI events are sent to the Erlang side as messages -- thus permitting normal Erlang concurrent coding, but providing a single point of GUI event sequencing so that wx can do its GUI update looping thing.]</p> |
28,819,709 | How can you tell if a value is not numeric in Oracle? | <p>I have the following code that returns an error message if my value is invalid. I would like to give the same error message if the value given is not numeric.</p>
<pre><code>IF(option_id = 0021) THEN
IF((value<10000) or (value>7200000) or /* Numeric Check */)THEN
ip_msg(6214,option_name); -- Error Message
return;
END IF;
END IF;
</code></pre>
<p>In SQL Server, I simply used <code>ISNUMERIC()</code>. I would like to do something similar in Oracle. Such as, </p>
<pre><code>IF((!ISNUMERIC(value)) or (value<10000) or (value>7200000))
THEN ...
</code></pre> | 28,820,388 | 8 | 0 | null | 2015-03-02 21:24:39.973 UTC | 13 | 2021-04-11 18:11:51.99 UTC | 2020-07-11 20:42:31.333 UTC | null | 6,571,020 | null | 4,449,640 | null | 1 | 47 | sql|oracle|plsql|isnumeric | 204,430 | <pre><code>REGEXP_LIKE(column, '^[[:digit:]]+$')
</code></pre>
<p>returns TRUE if column holds only numeric characters</p> |
19,947,538 | Django form with unknown number of checkbox fields and multiple actions | <p>I need help with form which looks like a Gmail inbox and have multiple actions. There is a list of items and I want to wrap it with form, on the way that every item have checkbox in the front of the line. So when user select few items he is able to click on two buttons with different actions for example delete and mark read.</p>
<pre><code><form action="">
{% for item in object_list %}
<input type="checkbox" id="item.id">
{{ item.name }}
{% endfor %}
<button type="submit" name="delete">Delete</button>
<button type="submit" name="mark_read">Mark read</button>
</form>
</code></pre>
<p>I can find which submit button is user click on if use <code>if 'delete' in request.POST</code> but I cant refer to any form because Django form cant be defined with unknown number of fields as I think. So how can I process selected items in view?</p>
<pre><code>if request.method == 'POST':
form = UnknownForm(request.POST):
if 'delete' in request.POST:
'delete selected items'
if 'mark_read' in erquest.POST:
'mark selected items as read'
return HttpResponseRedirect('')
</code></pre> | 19,949,097 | 4 | 0 | null | 2013-11-13 07:10:23.39 UTC | 10 | 2021-03-12 18:38:23.333 UTC | null | null | null | null | 928,017 | null | 1 | 16 | django|django-models|django-forms|django-templates|django-views | 29,106 | <p>Multiple checkboxes with the same name are all the same field.</p>
<pre><code><input type="checkbox" value="{{item.id}}" name="choices">
<input type="checkbox" value="{{item.id}}" name="choices">
<input type="checkbox" value="{{item.id}}" name="choices">
</code></pre>
<p>you can collect and aggregate them with a single django form field.</p>
<pre class="lang-py prettyprint-override"><code>class UnknownForm(forms.Form):
choices = forms.MultipleChoiceField(
choices = LIST_OF_VALID_CHOICES, # this is optional
widget = forms.CheckboxSelectMultiple,
)
</code></pre>
<p>Specifically, you can use a ModelMultipleChoiceField.</p>
<pre class="lang-py prettyprint-override"><code>class UnknownForm(forms.Form):
choices = forms.ModelMultipleChoiceField(
queryset = queryset_of_valid_choices, # not optional, use .all() if unsure
widget = forms.CheckboxSelectMultiple,
)
if request.method == 'POST':
form = UnknownForm(request.POST):
if 'delete' in request.POST:
for item in form.cleaned_data['choices']:
item.delete()
if 'mark_read' in request.POST:
for item in form.cleaned_data['choices']:
item.read = True; item.save()
</code></pre> |
6,208,214 | Placing 3 div's Side by Side | <p>I want to place 3 divs side by side using CSS. I have gone through many posts on SO, but not getting the thing working for my project.</p>
<pre><code>#quotescointainer{
width: 100%;
font-size: 12px;
}
#quotesleft{
float:left;
width: 33%;
background-color: white;
}
#quotescenter{
background-color:white;
width: 33%;
}
#quotesright{
float:left;
width: 33%;
}
</code></pre>
<p>The above does not place the div's in the correct place. I cannot seem to figure out the mistake I am making.</p> | 6,208,292 | 3 | 0 | null | 2011-06-01 21:57:04.027 UTC | 4 | 2018-01-04 02:51:29.467 UTC | 2011-06-01 21:59:35.41 UTC | null | 74,022 | null | 737,124 | null | 1 | 10 | html|css | 39,322 | <p>You could <code>float: left</code> <em>all</em> the inner <code>div</code>s:</p>
<p><a href="http://jsfiddle.net/W8dyy/">http://jsfiddle.net/W8dyy/</a></p>
<p>You should fix the spelling of <code>quotescointainer</code> to <code>quotescontainer</code>.</p>
<pre><code>#quotescointainer{
width: 100%;
font-size: 12px;
overflow: hidden; /* contain floated elements */
background: #ccc
}
#quotesleft {
float: left;
width: 33%;
background-color: #bbb;
}
#quotescenter {
float: left;
background-color: #eee;
width: 33%;
}
#quotesright{
float: left;
width: 33%;
background-color: #bbb;
}
</code></pre> |
6,175,004 | What is the best way of converting List<Long> object to long[] array in java? | <p>Is there any utility method to convert a list of Numerical types to array of primitive type?
In other words I am looking for a better solution than this.</p>
<pre><code>private long[] toArray(List<Long> values) {
long[] result = new long[values.size()];
int i = 0;
for (Long l : values)
result[i++] = l;
return result;
}
</code></pre> | 30,907,598 | 4 | 3 | null | 2011-05-30 10:16:40.71 UTC | 5 | 2017-02-27 16:05:42.6 UTC | null | null | null | null | 497,544 | null | 1 | 39 | java|collections | 55,047 | <p>Since Java 8, you can do the following:</p>
<pre><code>long[] result = values.stream().mapToLong(l -> l).toArray();
</code></pre>
<p>What's happening here?</p>
<ol>
<li>We convert the <code>List<Long></code> into a <code>Stream<Long></code>.</li>
<li>We call <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#mapToLong-java.util.function.ToLongFunction-" rel="noreferrer"><code>mapToLong</code></a> on it to get a <code>LongStream</code>
<ul>
<li>The argument to <code>mapToLong</code> is a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/ToLongFunction.html" rel="noreferrer"><code>ToLongFunction</code></a>, which has a <code>long</code> as the result type.</li>
<li>Because Java automatically unboxes a <code>Long</code> to a <code>long</code>, writing <code>l -> l</code> as the lambda expression works. The <code>Long</code> is converted to a <code>long</code> there. We could also be more explicit and use <code>Long::longValue</code> instead.</li>
</ul></li>
<li>We call <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#toArray--" rel="noreferrer"><code>toArray</code></a>, which returns a <code>long[]</code></li>
</ol> |
45,756,791 | Install software using powershell script | <p>I am trying to install Notepad++ software using a PowerShell v2.0 script for one of my POC. I need to install the client's software in my current project. As I am running the below script I'm getting errors.</p>
<pre><code>Start-Process 'C:\Users\kirnen\Desktop\A\npp.7.5.Installer.exe'-InstallerParameters "/S" `
-RegistryKey HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Notepad++ `
-RegistryName DisplayVersion -RegistryValue 7.5
</code></pre>
<p>As I am very much new to powershell scripting, can you please help in this? Is the above code right, or do I need to change anything else to install the software?</p> | 45,764,665 | 5 | 2 | null | 2017-08-18 12:34:57.983 UTC | 3 | 2022-03-23 18:13:31.963 UTC | 2018-08-01 21:52:10.427 UTC | null | 7,690,687 | null | 6,155,119 | null | 1 | 4 | powershell|powershell-2.0 | 104,782 | <p>I use this snippet of PowerShell code for a lot of installs. As long as you can figure out the silent switch for ".exe's". For ".msi's" just change out where <code>Create()</code> with <code>Create("msiexec /I C:\temp\generic.msi /qn")</code></p>
<pre><code>$computers = c:\temp\computerName.csv
$Notepad = "Location of notepad install"
$computers | where{test-connection $_ -quiet -count 1} | ForEach-Object {
copy-item $Notepad -recurse "\\$_\c$\temp"
$newProc=([WMICLASS]"\\$_\root\cimv2:win32_Process").Create("C:\temp\npp.6.9.2.Installer.exe /S")
If ($newProc.ReturnValue -eq 0) {
Write-Host $_ $newProc.ProcessId
} else {
write-host $_ Process create failed with $newProc.ReturnValue
}
}
</code></pre> |
32,335,335 | How to remove elements from a list with lambda based on another list | <p>I have List of file Paths: . </p>
<pre><code>List<Path> filePaths; //e.g. [src\test\resources\file\15\54\54_exampleFile.pdf]
</code></pre>
<p><code>54</code> above refers to file ID</p>
<p>I then obtain a <code>Set</code> of <code>String</code> Ids which my application can handle as follows:</p>
<pre><code>Set<String> acceptedIds = connection.getAcceptedIDs(); //e.g. elements [64, 101, 33]
</code></pre>
<p>How can I use Java 8 lambdas to <code>filter</code> out all elements in <code>filePaths</code> that do not contain any of the acceptable Ids that are contained in <code>acceptedIds</code> collection Set.</p>
<p>In other words, I would like to retain in <code>filePaths</code> only the paths that have ids which are in <code>acceptedIds</code> set. For example, 54 is not in the above list so is removed.</p>
<pre><code>filePaths.stream().filter(...).collect(Collectors.toList());
</code></pre> | 32,335,740 | 4 | 2 | null | 2015-09-01 15:20:26.62 UTC | 1 | 2017-03-16 17:18:58.79 UTC | 2017-03-16 17:18:58.79 UTC | null | 1,982,385 | null | 2,781,389 | null | 1 | 20 | java|lambda|java-8|java-stream | 50,332 | <p>The most efficient way is to extract the ID from the path, then attempt to find it in the Set, making each filter execute in constant time, ie <code>O(1)</code> giving an overall <code>O(n)</code>, where <code>n</code> is the number of paths:</p>
<pre><code>filePaths.stream()
.filter(p -> acceptedIds.contains(p.getParent().getFileName().toString()))
.collect(Collectors.toList());
</code></pre>
<p>If the reverse approach is done, where each <code>acceptedIds</code> is searched for in the path (as in other answers), each filter is <code>O(m*k)</code>, where <code>m</code> is the number of <code>acceptedIds</code> and <code>k</code> is the average Path length, giving an overall <code>O(n * m * k)</code>, which will perform very poorly for even moderate sizes of collections.</p> |
6,059,722 | How to change the colors of a PNG image easily? | <p>I have PNG images that represent playing-cards.
They are the standard colours with Clubs and Spades being blank and Diamonds and Hearts being red.</p>
<p>I want to create a 4-colour deck by converting the the Clubs to green and the Diamonds to blue.</p>
<p>I don't want to re-draw them but just changing them by hand seems a lot of work since the colours are not all "pure" but graded near the edges.</p>
<p>How do I do it?</p> | 24,579,533 | 6 | 2 | null | 2011-05-19 13:49:35.357 UTC | 4 | 2017-03-01 16:11:32.763 UTC | null | null | null | null | 648,746 | null | 1 | 17 | colors|png | 106,430 | <p>Photoshop - right click layer -> blending options -> color overlay
change color and save</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.